【问题标题】:how to map dictionary to pandas series of series?如何将字典映射到熊猫系列系列?
【发布时间】:2019-09-28 01:21:44
【问题描述】:

我想将字典键值替换为列表值的数据框系列。

我的意见:

字典:

   doc_id  name
     1      tamil.sh
     2      english.sh
     3      maths.sh

数据框:

 doc_id     count 
  ["1","2"]     3
  ["2","3"]     4

我希望输出:

     doc_id               count
  ["tamil.sh","english.sh"]   3
  ["english.sh","maths.sh"]   4

【问题讨论】:

  • 为什么你的dict 看起来像DataFrame

标签: python-3.x pandas pandas-groupby


【解决方案1】:

通过第一个 DataFramezip 创建字典 - 这里是键整数,因此如果需要在列表理解和 get 中将字符串转换为 ints 以获得正确的匹配值:

d = dict(zip(df1['doc_id'], df1['name']))
print (d)
{1: 'tamil.sh', 2: 'english.sh', 3: 'maths.sh'}

#values are strings, so converting to integers is necessary
print (df2.loc[0, 'doc_id'])
['1', '2']

df2['doc_id'] = df2['doc_id'].apply(lambda x: [d.get(int(y),y) for y in x])
print (df2)
                   doc_id  count
0  [tamil.sh, english.sh]      3
1  [english.sh, maths.sh]      4

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2021-04-30
    • 2019-12-13
    • 2017-03-06
    • 2021-12-08
    • 2017-12-15
    • 2016-09-22
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多