【问题标题】:create new column using a dictionary key使用字典键创建新列
【发布时间】:2021-02-14 13:49:39
【问题描述】:

获取这个数据框df:

df = pd.DataFrame({'col_1':['some text green', 'some text blue', 'some text dog', 'some text']})

             col_1
0  some text green
1   some text blue
2    some text dog
3        some text

拿这本词典:

my_dict = {'color':['green', 'blue'],'animal':['dog']}

我需要创建一个新列new_col 搜索字符串是否包含在col_1 中。字符串在字典值中给出。如果是这样,我需要获取字典键并将其放在新列中。如果没有,只需放置 NaN。

结果应该是:

             col_1 new_col
0  some text green   color
1   some text blue   color
2    some text dog  animal
3        some text     NaN

【问题讨论】:

  • 必须是字典吗,可以用列表吗?
  • 我想要最简单的解决方案。可以是一个列表,是的。

标签: python pandas dataframe


【解决方案1】:

试试这个:

def f(s):
    for k in my_dict:
        for v in my_dict[k]:
            if v in s:
                return k

df["new_col"] = df["col_1"].apply(f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2022-06-22
    • 2019-12-27
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    相关资源
    最近更新 更多