PythonPandas-根据单元格值查找列值
我正在尝试使用一个单元格的值来查找另一列中一个单元格的值。第一个单元格值指示要查找的列。
import pandas as pd
df = pd.DataFrame({'A': ['John', 'Andrew', 'Bob', 'Fred'], 'B': [
'Fred', 'Simon', 'Andrew', 'Andrew'], 'source': ['A', 'B', 'A', 'B']}, )
print(df)
A B source
0 John Fred A
1 Andrew Simon B
2 Bob Andrew A
3 Fred Andrew B
我在“输出”列中所需的输出值是对“源”的查找
A B source output
0 John Fred A John
1 Andrew Simon B Simon
2 Bob Andrew A Bob
3 Fred Andrew B Andrew
失败的尝试
df['output'] = df[df['source']]
这会导致ValueError: Wrong number of items connected 4,placement 意味着 1,因为df['source']传递的是一个系列,而不是一个字符串。我尝试使用以下方法转换为字符串:
df['output'] = df[df['source'].convertDTypes(convert_string=True)]
这给出了错误AttributeError: 'Series' object has no attribute 'convertDTypes'。
工作解决方案
我发现一个解决方案可能是使用以下方法遍历行:
for index, row in df.iterrows():
column = df.loc[index, 'source']
df.at[index, 'output'] = df.loc[index, column]
然而,这篇文章表明迭代是一个坏主意。代码看起来也不是很优雅。
我觉得我在这里错过了一些基本的东西;这真的不应该那么难。
回答
让我们numpy做点事情,因为lookup在未来的版本中将不再起作用
df['new'] = df.values[df.index,df.columns.get_indexer(df.source)]
df
Out[339]:
A B source new
0 John Fred A John
1 Andrew Simon B Simon
2 Bob Andrew A Bob
3 Fred Andrew B Andrew