简体   繁体   English

熊猫-基于2列和一个单独的测试列创建2个新列

[英]Pandas - creating 2 new columns based on 2 columns and a separate test column

I'm trying to datafill 2 new columns from 2 existing columns, based on the value of another column. 我正在尝试根据另一列的值填充2个现有列中的2个新列。

The logic is that given a positive amount the buyer and seller should be filled out from the party and cparty fields respectively. 逻辑是,给定正数,应分别从“方”和“方”字段填写买方和卖方。 If the amount is negative then the situation is reversed and the buyer is the cparty rather than the party, and the seller is the party. 如果金额为负,则情况会相反,并且买方是当事人而不是当事人,卖方是当事人。

I'm trying to avoid doing something iterative - I can get each component using the expressions below but, but having tried to concatenate these results with concat, +, +=, combine_first, fillna and update, I've drawn a blank over how to merge the results. 我试图避免做一些迭代-我可以使用下面的表达式获取每个组件,但是,尝试将这些结果与concat,+,+ =,combin_first,fillna和update串联在一起之后,我在如何进行绘制上做了一个空白合并结果。

Each time they're either been overwritten (I suspect because Pandas matches on the column name, and not position) or I get 2 empty columns. 每次它们要么被覆盖(我怀疑是因为Pandas匹配列名而不是位置),或者我得到2个空列。

There must be a nice clean pythonic way to combine the below, or similar? 必须有一个很好的干净的pythonic方式来组合以下内容或类似内容?

df[['Buyer', 'Seller']] = df[df.amount > 0][['party', 'cparty']]
df[['Buyer', 'Seller']] = df[df.amount < 0][['cparty', 'party']]

Maybe you are looking for np.where as a one liner ie 也许您正在寻找np.where作为一个班轮,即

For example : 例如 :

df = pd.DataFrame({'key': ['a','b','b','c','c'],'key2': ['a','d','d','e','e'],'key3': ['j','k','l','m','n'], 'x': [1,2,3,4,5]})

df[['new1','new2']] = pd.DataFrame(np.where(df['x']>2,(df['key3'],df['key2']),(df['key2'],df['key3'])).T)

   key key2 key3  x new1 new2
0   a    a    j  1    a    j
1   b    d    k  2    d    k
2   b    d    l  3    l    d
3   c    e    m  4    m    e
4   c    e    n  5    n    e

In your case you can do 在你的情况下你可以做

df[['Buyer', 'Seller']] = pd.DataFrame(np.where(df.amount < 0,(df['cparty'],df['party']),(df['party'],df['cparty'])).T)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM