gpt4 book ai didi

python - 根据字典键创建具有值的新列

转载 作者:行者123 更新时间:2023-12-01 00:16:14 24 4
gpt4 key购买 nike

我有一个数据框和一本字典:

news = {'Text':['dog ate the apple', 'cat ate the carrot', 'dog drank water'], 'Source':['NYT', 'WP', 'Guardian']}
news_df = pd.DataFrame(news)


w = {1:['horse', 'dog'], 2:['apple'], 10: ['water', 'melon', 'liquerice']}

我想创建一个新列 news_df['sum'] 来查看 news_df['Text'],检查是否有任何字典值可用,如果列中有 1 个或多个值,则分配按键。我的结果是:

results = {'Text':['dog ate the apple', 'cat ate the carrot', 'dog drank water'], 'Source':['NYT', 'WP', 'Guardian'], 'sum' : [3, 0, 11]}
results_df = pd.DataFrame(results)

知道怎么做吗?我不确定该采取什么方法?也许将字典变成数据框?

最佳答案

这是一个应用方法:

def counts(x): 
sumcount = 0
for k, v in w.items():
for word in v:
if word in x:
sumcount+=int(k)
return sumcount

news_df.Text.apply(counts)
                 Text    Source  sum
0 dog ate the apple NYT 3
1 cat ate the carrot WP 0
2 dog drank water Guardian 11

关于python - 根据字典键创建具有值的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59315792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com