我正在尝试用熊猫编写代码。我有 5 列,df['all'] 包含值列表,df['ind'] 包含列表索引。我只想从 df['all'] 中获取那些索引在 df['ind'] 中可用的值。例如在第 0 行,df['ind'] 有 [1, 2],我想在新列 df['values'] 中得到 [2, 3]。我正在尝试,但我认为我在某个地方犯了错误并且无法纠正它。
import pandas as pd
df = pd.DataFrame([[0, 2, 3], [5, 6, 5], [10, 20, 30]],index=[0, 1, 2], columns=['A', 'B', 'C'])
df['all'] = df.apply(lambda x: [i for i in x], axis=1)
e = pd.Series([[1,2],[0], [1,3]], index=[0, 1, 2])
df = df.assign(ind=e.values)
print(df)
df['values'] = df['ind'].apply(lambda x: [df.at[i, 'all'] for i in x])
print(df)
A B C all ind
0 0 2 3 [0, 2, 3] [1, 2]
1 5 6 5 [5, 6, 5] [0]
2 10 20 30 [10, 20, 30] [1, 2]
我不确定我是否以这种方式调用应用函数中的另一列。
您可以定义一个函数并应用:
def func(row):
row['values'] = [row['all'][idx] for idx in row['ind']]
return row
df = df.apply(func, axis = 1)
给:
A B C all ind values
0 0 2 3 [0, 2, 3] [1, 2] [2, 3]
1 5 6 5 [5, 6, 5] [0] [5]
2 10 20 30 [10, 20, 30] [1, 2] [20, 30]