2

我想创建一个旭日形图。因此,我需要一个在每一列(对于每个图表级别)中都有唯一字符串的数据框。我的目标是为 col2 中出现在 col1 中任何位置的所有字符串添加一个附加字符串。我的原始数据框如下所示:

   col1     col2    value
0   pig      dog        3
1   cat  chicken        2    
2  fish      pig        4
3   dog     mule        7

我想要实现的是这样的:

   col1     col2    value
0   pig   dog_ag        3
1   cat  chicken        2
2  fish   pig_ag        4
3   dog     mule        7

非常感谢任何帮助。

4

2 回答 2

3

Series.mask与 一起使用Series.isin

df['col2'] = df['col2'].mask(df['col2'].isin(df['col1']), df['col2'] + '_ag')
print (df)
   col1     col2  value
0   pig   dog_ag      3
1   cat  chicken      2
2  fish   pig_ag      4
3   dog     mule      7
于 2020-03-13T10:28:22.053 回答
0

使用list comprehension

df["col2"] = [i+"_ag" if i in df["col1"].values else i for i in df["col2"]]

或者你可以使用np.where

df["col2"] = np.where(df["col2"].isin(df["col1"]), df["col2"]+"_ag", df["col2"])
于 2020-03-13T10:31:17.167 回答