从列中拾取值

2024-04-29 18:47:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas DataFrame,其中的值位于多个列中,为了简单起见,将其设为两列,还有一列是我想用来从其他列中选取值的列名:

import pandas as pd
import numpy as np

np.random.seed(1337)
df = pd.DataFrame(
    {"a": np.arange(10), "b": 10 - np.arange(10), "c": np.random.choice(["a", "b"], 10)}
)

> df['c']

0    b
1    b
2    a
3    a
4    b
5    b
6    b
7    a
8    a
9    a
Name: c, dtype: object

也就是说,我希望第一个和第二个元素从列b中选取,第三个元素从a中选取,依此类推

这项工作:

def pick_vals_from_cols(df, col_selector):
    condlist = np.row_stack(col_selector.map(lambda x: x == df.columns))
    values = np.select(condlist.transpose(), df.values.transpose())
    return values

> pick_vals_from_cols(df, df["c"])

array([10, 9, 2, 3, 6, 5, 4, 7, 8, 9], dtype=object)

但它感觉如此脆弱和笨重。有更好的方法吗


Tags: import元素dataframepandasdfobjectasnp
1条回答
网友
1楼 · 发布于 2024-04-29 18:47:10

^{}

df.lookup(df.index, df.c)

array([10,  9,  2,  3,  6,  5,  4,  7,  8,  9])

理解力

但是为什么你有lookup

[df.at[t] for t in df.c.items()]

[10, 9, 2, 3, 6, 5, 4, 7, 8, 9]

奖金黑客

不打算用于实际用途

[*map(df.at.__getitem__, zip(df.index, df.c))]

[10, 9, 2, 3, 6, 5, 4, 7, 8, 9]

因为df.get_value已被弃用

[*map(df.get_value, df.index, df.c)]

FutureWarning: get_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead

[10, 9, 2, 3, 6, 5, 4, 7, 8, 9]

相关问题 更多 >