pandas 添加列,注意 Series 的真值不明确 [英] pandas add columns ,note The truth value of a Series is ambiguous
本文介绍了pandas 添加列,注意 Series 的真值不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在数据框 a 中添加一列,
a = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])如果 a['B'] >一个['A']:a['C']='是'别的:a['C']='否'
<块引用>
ValueError:系列的真值不明确.使用 a.empty,a.bool()、a.item()、a.any() 或 a.all().
解决方案
使用 numpy.where
:
#swapped 2,1a = pd.DataFrame([[2,1],[3,4]],columns=['A','B'])a['C'] = np.where(a['B']>a['A'], '是','否')打印(一)乙丙0 2 1 否1 3 4 是
您的代码有问题:
print (a['B']>a['A'])0 错误1 真数据类型:布尔
它返回布尔掩码,if
无法决定做什么.
也检查 使用如果对熊猫的真实陈述.
I want do add a column to dataframe a,
a = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])
if a['B'] > a['A']:
a['C']='是'
else:
a['C']='否'
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
解决方案
Use numpy.where
:
#swapped 2,1
a = pd.DataFrame([[2,1],[3,4]],columns=['A','B'])
a['C'] = np.where(a['B']>a['A'], '是','否')
print (a)
A B C
0 2 1 否
1 3 4 是
Problem with your code is if use:
print (a['B']>a['A'])
0 False
1 True
dtype: bool
it return boolean mask and if
cannot decide what to do.
Check also using if truth statements with pandas.
这篇关于pandas 添加列,注意 Series 的真值不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文