Python 如何使某些列值默认为同一行不同列中的另一个值?
我有一个示例数据框,如下所示:Python 如何使某些列值默认为同一行不同列中的另一个值?,python,pandas,dataframe,replace,Python,Pandas,Dataframe,Replace,我有一个示例数据框,如下所示: ID Product UPC Units Sold no link cereal 3463 12 2211 cereal 2211 13 2211 cereal 8900 11 2211 cereal 6754 14 no link cereal 9012 13 3340 cereal 3340 12
ID Product UPC Units Sold
no link cereal 3463 12
2211 cereal 2211 13
2211 cereal 8900 11
2211 cereal 6754 14
no link cereal 9012 13
3340 cereal 3340 12
3340 cereal 5436 15
“ID”列将类似产品标识为一个产品系列ID。该ID由该系列的第一个UPC编号创建。”“无链接”标识的产品是其系列中唯一的成员。我想要的是将“无链接”值设置为UPC编号的默认值。
我希望我的输出是这样的:
ID Product UPC Units Sold
3463 cereal 3463 12
2211 cereal 2211 13
2211 cereal 8900 11
2211 cereal 6754 14
9012 cereal 9012 13
3340 cereal 3340 12
3340 cereal 5436 15
这就是我到目前为止所做的:
for row in product_families:
if product_families.loc['Product Family Number'] == 'no link':
将
loc
与布尔索引一起使用,并使用内部数据对齐进行分配:
df.loc[df.ID.eq('no link'),'ID'] = df.UPC
输出:
ID Product UPC Units Sold
0 3463 cereal 3463 12
1 2211 cereal 2211 13
2 2211 cereal 8900 11
3 2211 cereal 6754 14
4 9012 cereal 9012 13
5 3340 cereal 3340 12
6 3340 cereal 5436 15
斯科特·波士顿的解决方案应该奏效 也许值得尝试使用apply row-wise的不同方法
df['ID']=df.apply(lambda x: x.UPC if x.ID=='no link' else x.ID, axis=1)
嘿,谢谢斯科特!然而,我得到了这个错误:“ValueError:无法从重复的轴重新编制索引。”我使用的是一个包含许多产品、ID和UPC的大型数据帧。您知道如何更改上面的代码来修复整个数据帧的错误吗?@Hana您能显示当前数据帧的df.head()吗?