说我有一个带有两列(名称和值)的简单数据框(df)。我想根据名称添加第三列(新值)。
我尝试过:
df['New Value'] = df[['Name ']].apply((lambda x: df['Value'] * 2 if x == 'John' else df['Value']) , axis=0)
这样做,我得到以下错误:
ValueError :(“系列的真值不明确。请使用a.empty,a.bool(),a.item(),a.any()或a.all()。”,“发生于索引名称')
我了解到x是一个序列,我无法与字符串进行比较,这是正确的吗?如果不是,那是什么意思?
无论如何,我该如何解决这个问题?
答案 0 :(得分:1)
您可以使用where进行此操作:
df['New Value'] = (df['Value'] * 2).where(df['Name'] == 'John', df['Value'])
答案 1 :(得分:1)
您将操作仅应用于列'Name'
的数据帧,并且在进行逐行操作时,请设置axis=1
为您的用例尝试一下。
df['New Value'] = df.apply(lambda x: x['Value'] * 2 if x['Name'] == 'John' else x['Value'], axis=1)
解决方案
In [49]: df
Out[49]:
Name Value
0 John 5
1 Kevin 5
In [50]: df['New Value'] = df.apply(lambda x: x['Value'] * 2 if x['Name'] == 'John' else x['Value'], axis=1)
In [51]: df
Out[51]:
Name Value New Value
0 John 5 10
1 Kevin 5 5