![](/img/trans.png)
[英]Fill values in a column of a particular row with the value of same column from another row based on a condition on second column in Pandas
[英]Creating new column in Pandas with a condition based on existing row values and returning another row's values
希望對以下問題有所幫助。 我目前有一個包含3列的熊貓數據框 - test1,test2,test3
我希望實現的是result_column,其邏輯將是:
1)如果test1 AND test2> 0中的值,則返回test3的值
2)否則如果值test1 AND test2 <0,則返回test3的NEGATIVE值
3)否則返回0
test1 test2 test3 result_column
0 0.5 0.1 1.25 1.25
1 0.2 -0.2 0.22 0
2 -0.3 -0.2 1.12 -1.12
3 0.4 -0.3 0.34 0
4 0.5 0 0.45 0
這是我第一次在python和pandas上發布一個問題。 如果此處的格式不是最佳,請提前道歉。 感謝我能得到的任何幫助!
我認為需要使用&
( AND
)鏈接的條件的numpy.select
或子集[[]]
選擇所有測試的列,比較DataFrame.all
ant test:
m1 = (df.test1 > 0) & (df.test2 > 0)
#alternative
#m1 = (df[['test1', 'test2']] > 0).all(axis=1)
m2 = (df.test1 < 0) & (df.test2 < 0)
#alternative
#m2 = (df[['test1', 'test2']] < 0).all(axis=1)
df['result_column'] = np.select([m1,m2], [df.test3, -df.test3], default=0)
print (df)
test1 test2 test3 result_column
0 0.5 0.1 1.25 1.25
1 0.2 -0.2 0.22 0.00
2 -0.3 -0.2 1.12 -1.12
3 0.4 -0.3 0.34 0.00
4 0.5 0.0 0.45 0.00
巧妙地使用np.sign
和邏輯
如果> 0
或兩者< 0
則產品為1
,否則產品為-1
或0
。 如果兩者都> 0
則總和的符號為1
。 如果兩者都< 0
則則sum的符號為-1
,否則為0
。 這些東西的產物正是我們想要的。
v = np.sign(df[['test1', 'test2']].values)
df.assign(result_column=v.prod(1) * np.sign(v.sum(1)) * df.test3 + 0)
test1 test2 test3 result_column
0 0.5 0.1 1.25 1.25
1 0.2 -0.2 0.22 0.00
2 -0.3 -0.2 1.12 -1.12
3 0.4 -0.3 0.34 0.00
4 0.5 0.0 0.45 0.00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.