输入 df
Index col1
0 Img
1 Fruit
2 Img
3 Ball
4 Ball
5 Fruit
6 shirt
7 Fruit
将列表映射到输入 dflist1 = ['Img_A_10', 'Fruit_A_100', 'Ball_B_120']
输出 df col1 col22
0 Img Img_A_10
1 Fruit Fruit_A_100
2 Img Img_A_10
3 Ball Ball_B_120
4 Ball Ball_B_120
5 Fruit Fruit_A_100
6 shirt shirt
7 Fruit Fruit_A_100
最佳答案
尝试这个,
df['col2'] = df.col1.map({k.split("_")[0]: k for k in list1}).fillna(df.col1)
或 df['col2'] = df.col1.replace({k.split("_")[0]: k for k in list1})
df
Out[93]:
col1 col2
0 Img Img_A_10
1 Fruit Fruit_A_100
2 Img Img_A_10
3 Ball Ball_B_120
4 Ball Ball_B_120
5 Fruit Fruit_A_100
6 shirt shirt
7 Fruit Fruit_A_100
关于python - 我想基于上一列添加一个新的 DataFrame 列,以便如果上一列元素与列表值匹配,则更改该值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63636992/