小编ITS*_*-79的帖子

Python Pandas - 根据单元格值查找列值

我正在尝试使用一个单元格的值来查找另一列中一个单元格的值。第一个单元格值指示要查找的列。

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
Run Code Online (Sandbox Code Playgroud)

我在“输出”列中所需的输出值是对“源”的查找

        A       B source  output
0    John    Fred      A    John
1  Andrew   Simon      B   Simon
2     Bob  Andrew      A     Bob
3    Fred  Andrew      B  Andrew
Run Code Online (Sandbox Code Playgroud)

失败的尝试

df['output'] = df[df['source']]
Run Code Online (Sandbox Code Playgroud)

这会导致ValueError: Wrong number of items connected …

dataframe python-3.x pandas

3
推荐指数
1
解决办法
260
查看次数

标签 统计

dataframe ×1

pandas ×1

python-3.x ×1