gpt4 book ai didi

python - Pandas - 从现有列创建多个默认列

转载 作者:行者123 更新时间:2023-11-30 22:24:11 33 4
gpt4 key购买 nike

以下内容来自: Pandas - creating 2 new columns based on 2 columns and a separate test column

但这本身就是一个不同的问题。应该更简单!

在引用的问题中,讨论了以下单行代码,用于从其他 2 列中填充 2 个新列,并依赖于第三列的值:

df['Buyer ID'], df['Seller ID'] = zip(
*np.where(df.buy_sell == 'Buy',
(df.buyer_name,df.seller_name),
(df.seller_name,df.buyer_name)).T)

这工作得很好 - 但是当我尝试简化它以使用固定标量值而不是其他列中的相应值时,它不起作用。

例如,如果我只有一位可能的买家 John 和一位可能的卖家 Maggie,那么以下更简单的构造就足够了:

df['Buyer ID'], df['Seller ID'] = zip(
*np.where(df.buy_sell == 'Buy',
("John","Maggie"),
("Maggie","John")).T)

内部 np.where() 调用失败:

operands could not be broadcast together with shapes

我尝试了一些变体,例如将元组包装在 zip() 中,这会改变形状,但我仍然收到错误。我认为问题在于 ("John","Maggie") 没有作为单个列的内容返回。元组扩展为 >1 列?

此链接也显示出一些希望: Changing certain values in multiple columns of a pandas DataFrame at once

但我认为该解决方案假设您要编辑的列已经存在,并且您只想在每个列中放置相同的单个值。

我可以通过多次传递来解决这个问题,但这并不理想:

np.where(df.buy_sell == 'Buy', 'John', 'Maggie') 

理想情况下,对于每一行,我想要一个可扩展到 N 个新列的单遍解决方案,这些新列填充有不同的固定默认值,但全部取决于另一列中的单个( bool )值。

有什么关于我遗漏的内容吗?

最佳答案

我认为您需要将掩码扩展为 2d 数组,因为需要 2 个新列 numpy.column_stack :

df = pd.DataFrame({'buy_sell': ['Buy','Buy','Buy','Sell','Sell']})

m = df.buy_sell == 'Buy'
mask = np.column_stack([m] * 2)
df1 = pd.DataFrame(np.where(mask, ("John","Maggie"), ("Maggie","John")))
df[['Buyer ID', 'Seller ID']] = df1
print (df)
buy_sell Buyer ID Seller ID
0 Buy John Maggie
1 Buy John Maggie
2 Buy John Maggie
3 Sell Maggie John
4 Sell Maggie John

编辑:

在调查原始解决方案是可能的广播 bool 掩码后,仅需要 [:, None] 对于 N x 1 数组:

m = df.buy_sell == 'Buy'
df1 = pd.DataFrame(np.where(np.array(m)[:, None], ("John","Maggie"), ("Maggie","John")))
df[['Buyer ID', 'Seller ID']] = df1
print (df)
buy_sell Buyer ID Seller ID
0 Buy John Maggie
1 Buy John Maggie
2 Buy John Maggie
3 Sell Maggie John
4 Sell Maggie John

详细信息:

print (np.array(m)[:, None])

[[ True]
[ True]
[ True]
[False]
[False]]

关于python - Pandas - 从现有列创建多个默认列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47887365/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com