python - 我想基于上一列添加一个新的 DataFrame 列,以便如果上一列元素与列表值匹配,则更改该值

标签 python pandas numpy dataframe

输入 df

Index       col1
0     Img    
1     Fruit  
2     Img    
3     Ball    
4     Ball    
5     Fruit    
6     shirt    
7     Fruit 
将列表映射到输入 df
list1 = ['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/

相关文章:

python - 解析 gff 文件,获取脚手架名称并创建一个新的数据框

python - 在 Python 的正则表达式中与后向断言和负向后断言打结

Python Opencv output.avi screengrab 颜色为蓝色密集

python - numpy 3d 数组 - 选择沿给定轴的最大元素

python - 重新索引(重新映射)列的值

python - 软件包安装在 anaconda\lib\site-packages 中并在 spy 程序中找到,但不在 jupyter 笔记本中

python - 在 pandas boolean 比较中保留 NaN 值

python - 通过提取 DatetimeIndex 的时间而不使用 for 循环,在一个图上绘制每一天

python - 未实现错误 : numpy() is only available when eager execution is enabled

python - 协助 ruby​​ def