我有一個 Dataframe,其中有兩列名為 volume qty 和 volume price。我想根據上述列創建第三列。
如果交易量和交易量價格列都有值或兩者都為空白或空,則第三列應具有值“是”。如果其中一列作為值而另一列為空或空白,那么我希望第三列應具有值“NO” 例如
volume qty volume price column x
20 100 YES
YES
30 NO
200 NO
有什么方法可以使用任何內置函式來實作這一點。
uj5u.com熱心網友回復:
您可以使用numpy.select:
情況 1:當列具有空 (NaN) 值時:
In [152]: df
Out[152]:
volume qty volume price
0 20.0 100.0
1 NaN NaN
2 30.0 NaN
3 NaN 200.0
In [152]: import numpy as np
In [153]: conds = [df['volume qty'].notna() & df['volume price'].notna(), df['volume qty'].isna() & df['volume price'].isna(), df['volume qty'].isna() | df['volume price'].isna()]
In [154]: choices = ['YES', 'YES', 'NO']
In [156]: df['column x'] = np.select(conds, choices)
In [157]: df
Out[157]:
volume qty volume price column x
0 20.0 100.0 YES
1 NaN NaN YES
2 30.0 NaN NO
3 NaN 200.0 NO
情況 2:當列有空值時:
In [167]: df
Out[167]:
volume qty volume price
0 20 100
1
2 30
3 200
In [164]: conds = [~df['volume qty'].eq('') & ~df['volume price'].eq(''), df['volume qty'].eq('') & df['volume price'].eq(''), df['volume qty'].eq('') | df['volume price'].eq('')]
In [165]: choices = ['YES', 'YES', 'NO']
In [168]: df['column x'] = np.select(conds, choices)
In [169]: df
Out[169]:
volume qty volume price column x
0 20 100 YES
1 YES
2 30 NO
3 200 NO
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355129.html
標籤:熊猫 数据框 麻木的 python-3.9
上一篇:如何遍歷和比較資料幀的值?
下一篇:為什么r_[r_]掛了?
