【问题标题】:Pandas Add column based on dict value of another columnPandas 根据另一列的 dict 值添加列
【发布时间】:2021-03-23 02:02:44
【问题描述】:

给定一个数据框 df,它包含以下列:col1, col2, col3

Col1 包含字符串值(可能重复的值),如图所示:

Val1
Val2
Val3
Val1
Val1
Val1

此外,我有一个存储 Col1 映射的字典 -> 我需要添加到数据框“df”的新值。 示例:

{
    "Val1" : "new_val1",
    "Val2" : "new_val2",
    "Val3" : "new_val3",
}

现在,根据字典映射,我想将“col_new”添加到“df”中。最终数据框示例(仅显示相关列):

col1  col_new
Val1  new_val1
Val2  new_val2
Val3  new_val3
Val1  new_val1
Val1  new_val1
Val1  new_val1

我尝试了 df.map(),但这似乎只在数据框中的键列唯一时才有效。

建议?

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    除了@sophods 的回答 你也可以

    df['col_new'] = df['col1'].apply(lambda x:your_dict[x])
    

    根据评论添加

    import pandas as pd
    
    df=pd.DataFrame({'col1':['Val1','Val2','Val3','Val1','Val1','Val1']})
    your_dict={
        "Val1" : "new_val1",
        "Val2" : "new_val2",
        "Val3" : "new_val3",
        }
    
    df['col_new'] = df['col1'].apply(lambda x:your_dict[x])
    print(df)
    

    输出

       col1   col_new
    0  Val1  new_val1
    1  Val2  new_val2
    2  Val3  new_val3
    3  Val1  new_val1
    4  Val1  new_val1
    5  Val1  new_val1
    

    【讨论】:

    • df['col_new'] = df['col1'].apply(lambda x:your_dict[x]) 返回错误:文件“/Library/Python/3.8/site-packages/pandas /core/series.py”,第 4213 行,在 apply mapped = lib.map_infer(values, f, convert=convert_dtype) 文件中“pandas/_libs/lib.pyx”,第 2403 行,在 pandas._libs.lib.map_infer 文件中“cn.py”,第 73 行,在 df['col_new'] = df['col1'].apply(lambda x:your_dict[x]) TypeError: 'set' object is not subscriptable
    • 我已经添加了完整的代码,我在其中得到了结果 - 欢迎。
    【解决方案2】:

    这应该可以解决问题,使用map:

    your_dict={
        "Val1" : "new_val1",
        "Val2" : "new_val2",
        "Val3" : "new_val3",
    }
    
    df['col_new'] = df['col1'].map(your_dict)
    

    prints 你想要的输出:

       col1   col_new
    0  Val1  new_val1
    1  Val2  new_val2
    2  Val3  new_val3
    3  Val1  new_val1
    4  Val1  new_val1
    5  Val1  new_val1
    

    【讨论】:

    • df['col_new'] = df['col1'].map(your_dict) 行返回错误:文件“/Library/Python/3.8/site-packages/pandas/core/series. py”,第 3983 行,地图 new_values = super()._map_values(arg, na_action=na_action) 文件“/Library/Python/3.8/site-packages/pandas/core/base.py”,第 1160 行,在 _map_values new_values = map_f(values, mapper) 文件“pandas/_libs/lib.pyx”,第 2403 行,在 pandas._libs.lib.map_infer TypeError: 'set' object is not callable
    • 奇怪的是它不起作用,我几乎每天都使用这个命令。它在我的身上完美运行。你有什么pandaspython 版本?
    • 这是我的问题,我没有正确定义我的字典;有什么方法可以将此问题标记为无效? (PS 感谢您的帮助)
    猜你喜欢
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 2022-12-15
    • 2018-04-15
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多