我認爲你可以使用ix
,但是你確定你總是需要字符串cond2
轉到列c3
?
df['c3']='Nan'
df.ix[(df['c1'] == 'cond1')&(df['c2']=='cond2'), 'df3'] = 'cond2'
df.ix[(df['c1'] == 'cond3')&(df['c2']=='cond2'), 'df3'] = 'cond2'
df.ix[(df['c1'] == 'cond4')&(df['c2']=='cond2'), 'df3'] = 'cond2'
樣品:
import pandas as pd
import numpy as np
df = pd.DataFrame({'c1':['cond1','cond2','cond3','cond4'],
'c2':['cond2','cond2','cond2','cond2']})
print (df)
c1 c2
0 cond1 cond2
1 cond2 cond2
2 cond3 cond2
3 cond4 cond2
#set to NaN value
df['c3']= np.nan
#set to string 'Nan'
#df['c3']= 'Nan'
df.ix[(df['c1'] == 'cond1')&(df['c2']=='cond2'), 'c3'] = 'a'
df.ix[(df['c1'] == 'cond3')&(df['c2']=='cond2'), 'c3'] = 'b'
df.ix[(df['c1'] == 'cond4')&(df['c2']=='cond2'), 'c3'] = 'c'
print (df)
c1 c2 c3
0 cond1 cond2 a
1 cond2 cond2 NaN
2 cond3 cond2 b
3 cond4 cond2 c
循環的解決方案是非常緩慢的,但如果需要的話,你需要在循環使用row
代替df
:
import pandas as pd
import numpy as np
df = pd.DataFrame({'c1':['cond1','cond2','cond3','cond4'],
'c2':['cond2','cond2','cond2','cond2']})
print (df)
df['c3'] = ''
for index, row in df.iterrows():
if ((row['c1'] == 'cond1')&(row['c2']=='cond2')):
row['c3']='a'
elif ((row['c1'] == 'cond3')&(row['c2']=='cond2')):
row['c3']='b'
elif ((row['c1'] == 'cond4')&(row['c2']=='cond2')):
row['c3']='c'
else:
row['c3']=np.nan
print (df)
c1 c2 c3
0 cond1 cond2 a
1 cond2 cond2 NaN
2 cond3 cond2 b
3 cond4 cond2 c
你都清楚地失蹤縮進。請閱讀關於如何在Python中編寫循環和條件的教程。 – sisanared
你也應該粘貼錯誤的回溯。你可以在這裏閱讀縮進: https://docs.python.org/release/2.5.1/ref/indentation.html – noonewin