我有以下数据帧:
print(df)
id_code turnover costs
001 100 200
002 100 200
003 100 200
004 100 200
print(df_db)
Description Code1, Code2, ... CodeN
Retail 001 002 ... nan
Wholesale 003 nan ... nan
Supply 004 nan ... nan
我想创建以下final_df,并在df_db中添加一个表示描述的列;基本上,如果id_code存在于df_db的一行中,则合并值:
print(final_df)
id_code turnover costs Description
001 100 200 Retail
002 100 200 Retail
003 100 200 Wholesale
004 100 200 Supply
我尝试使用pdivot,但未报告所需结果。如何获取final_df?
答案 0 :(得分:0)
我们在Ad
Yes
8 nov. 2019 à 14:29
La
I don't think so
8 nov. 2019 à 13:39
Ad
Why ?
8 nov. 2019 à 13:19
La
Come on
8 nov. 2019 à 13:15
之前使用melt
merge
答案 1 :(得分:0)
使用DataFrame.melt
+ Series.map
如果df_db中没有重复的代码:
mapper=df_db.melt('Description').set_index('value')['Description']
df['Description']=df['id_code'].map(mapper)
print(df)
id_code turnover costs Description
0 1 100 200 Retail
1 2 100 200 Retail
2 3 100 200 Wholesale
3 4 100 200 Supply
详细信息:
print(mapper)
value
1 Retail
3 Wholesale
4 Supply
2 Retail
5 Wholesale
6 Supply
Name: Description, dtype: object