为附加列等于特定字符串的重复项添加后缀

2024-10-03 13:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图向所有重复的值添加一个后缀-US,并且additoanlcountry列等于US。下面是我的数据帧df的一个片段

 product_num      country
 101              US
 101              Ireland
 302              US
 303              Scotland
 304              France
 305              US
 305              Germany
 306              US
 307              US

我期望的输出如下所示

   product_num      country
     101-US           US
     101              Ireland
     302              US
     303              Scotland
     304              France
     305-US           US
     305              Germany
     306              US
     307              US

Tags: 数据dfproductcountry后缀numusfrance
1条回答
网友
1楼 · 发布于 2024-10-03 13:21:22

通过将所有重复项的^{}keep='False'链接来创建掩码,并将country列与^{}进行比较,并仅将筛选的行设置为添加后缀字符串的字符串:

m = df.duplicated('product_num', keep=False) & df['country'].eq('US')
df.loc[m, 'product_num'] = df.loc[m, 'product_num'].astype(str) + '-US'

使用^{}的替代解决方案:

df['product_num'] = np.where(m, df['product_num'].astype(str) + '-US', df['product_num'])

print (df)
  product_num   country
0      101-US        US
1         101   Ireland
2         302        US
3         303  Scotland
4         304    France
5      305-US        US
6         305   Germany
7         306        US
8         307        US

相关问题 更多 >