基于字典值创建新的Pandas列

时间:2016-11-25 15:53:40

标签: python pandas dictionary

我的字典看起来像这样:

ID      Hobby
1       Travel
2       Photography
3       Football
..........

我还有一个看起来像这样的数据库:

ID     Hobby        Name
1      Travel       Peter
2      Photography  Andrew
3      Football     NaN

我想在Dataframe中添加一个thirth列来实现:

opcache.max_accelerated_files

我确实找到了这个Adding a new pandas column with mapped value from a dictionary,但是我不需要列来包含字典中的值,而是密钥。 感谢

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情:

import pandas as pd
equiv = {'Andrew':['Photography'],'Peter':['Travel'], 'Jack': ['Football']}

df = pd.DataFrame( {'Hobby':[equiv[x][0] for x in equiv], 'Name': [key for key in equiv.keys()]})
print(df)