如何使用Python中的另一个数据框更改列值(列表)

问题描述 投票:0回答:1

我有两个数据框,我需要使用第二个数据框更改列表中第一个数据框的列值。

第一个数据框

df1 = pd.DataFrame({'title':['The Godfather','Fight Club','The Empire'], genre_ids':[[18, 80],[18],[12, 28, 878]]})

第二个数据框

df2 = pd.DataFrame({'id'[18,80,12,28,878,99],'name'['Action','Adventure','Adventure','Animation','Comedy','Documentary'\]})

如何在 python 中使用 df2 像这样分配genere_ids

       title       genre_ids  
0   The Godfather  [Action, Horror] 
1   Fight Club     [Action]
2   The Empire     [Adventure, Animation, Comedy]
python dataframe list
1个回答
1
投票

你可以这样做(注意:

id
80 在你的例子中是冒险,而不是恐怖):

m = dict(zip(df2["id"], df2["name"]))
df1["genre_ids"] = df1["genre_ids"].apply(lambda l: [m.get(v) for v in l])

print(df1)

打印:

           title                       genre_ids
0  The Godfather             [Action, Adventure]
1     Fight Club                        [Action]
2     The Empire  [Adventure, Animation, Comedy]
© www.soinside.com 2019 - 2024. All rights reserved.