![](/img/trans.png)
[英]Create a new column in Pandas dataframe based on different conditions
[英]created a new column in a pandas dataframe based on multiple different conditions
我在這里發現了一個類似的問題,但它對我沒有幫助,因為我的情況不同。
我有一個巨大的數據框,看起來或多或少類似於下面的示例:
x y st mt ast sr c7 z w
0 mt 2 1 4 2 2 a yes
1 b 3 3 3 3 3 yes
2 1 1 2 4 3 yes
3 d 3 3 1 2 4 d
4 e 2 3 2 1 4
5 nlp 5 5 5 5 5 f yes
我的目標是根據以下條件創建另一個名為“other_flagged”的列:
'如果列 x、y 和 z 沒有用字符串填充,但 w 有“yes”,則用字符串 'flagged' 填充列“other_flagged”。 所以,我想要的輸出是:
x y st mt ast sr c7 z w other flagged
0 mt 2 1 4 2 2 a yes
1 b 3 3 3 3 3 yes
2 1 1 2 4 3 yes flagged
3 d 3 3 1 2 4 d
4 e 2 3 2 1 4
5 nlp 5 5 5 5 5 f yes
在這種情況下,只有第 2 行接收到字符串“已標記”,因為 x、y 和 z 為空,但列 w 具有字符串“yes”。 我嘗試了下面的代碼,但創建的新列完全用字符串“標記”填充,但不是基於條件:
survey.loc[(survey['x'] != '') & (survey['y'] !='') & (survey['z'] != '') &
(survey['w'] == 'yes'), 'other_flagged'] ='flagged'
也試過:
survey.loc[(survey['x'] != '[a-zA-Z0-9-]+') & (survey['y'] != '[a-zA-Z0-9-]+') &
(survey['z'] != '[a-zA-Z0-9-]+') & (survey['w'] == 'yes'), 'other_flagged']='flagged'
我怎樣才能實現這個目標?
使用如果不存在值是空字符串是可能的測試所有列一起使用DataFrame.all
:
m = (survey[['x', 'y', 'z']] == '').all(axis=1) & (survey['w'] == 'yes')
survey.loc[m, 'other_flagged'] ='flagged'
print (survey)
x y st mt ast sr c7 z w other_flagged
0 m t 2 1 4 2 2 a yes NaN
1 b 3 3 3 3 3 yes NaN
2 1 1 2 4 3 yes flagged
3 d 3 3 1 2 4 d NaN
4 e 2 3 2 1 4 NaN
5 nlp 5 5 5 5 5 f yes NaN
您的解決方案 - 將!=
更改為==
:
m = (survey['x'] == '') & (survey['y'] =='') & (survey['z'] == '') & (survey['w'] == 'yes')
survey.loc[m, 'other_flagged'] ='flagged'
如果值是缺失值:
m = survey[['x', 'y', 'z']].isna().all(1) & (survey['w'] == 'yes')
survey.loc[m, 'other_flagged'] ='flagged'
print (survey)
x y st mt ast sr c7 z w other_flagged
0 m t 2 1 4 2 2 a yes NaN
1 NaN b 3 3 3 3 3 NaN yes NaN
2 NaN NaN 1 1 2 4 3 NaN yes flagged
3 NaN d 3 3 1 2 4 d NaN NaN
4 NaN e 2 3 2 1 4 NaN NaN NaN
5 nlp NaN 5 5 5 5 5 f yes NaN
使用numpy.where
:
import numpy as np
survey['other flagged'] = np.where((survey['x'].eq('') & survey['y'].eq('') & survey['z'].eq('') & survey['w'].eq('yes')) , 'flagged', 'not flagged')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.