使用np.where
:
In [36]:
df = pd.DataFrame({'A':np.random.randn(5), 'B':0, 'C':np.arange(5),'D':1, 'E':['asdsa','ABC','DEF','ABC','DAS']})
df
Out[36]:
A B C D E
0 0.831728 0 0 1 asdsa
1 0.734007 0 1 1 ABC
2 -1.032752 0 2 1 DEF
3 1.414198 0 3 1 ABC
4 1.042621 0 4 1 DAS
In [37]:
df['New Value'] = np.where(df['E'] == 'ABC', df['C'], df['E'])
df
Out[37]:
A B C D E New Value
0 0.831728 0 0 1 asdsa asdsa
1 0.734007 0 1 1 ABC 1
2 -1.032752 0 2 1 DEF DEF
3 1.414198 0 3 1 ABC 3
4 1.042621 0 4 1 DAS DAS
的语法np.where
是:
np.where(<condition>, True condition, False condition)
所以当条件True
它返回true;而当False
其他条件。
这真棒!感谢它的工作。 – Kvothe
对不起,只是添加到此。如何获得字符串中的函数或函数?例如。 'ABC'还是'CBA'? – Kvothe
如果你有一个新问题,提出新问题,除非它是非常轻微 – EdChum