【问题标题】:How to store a particular key value from a list of dictionaries in a data frame如何从数据框中的字典列表中存储特定的键值
【发布时间】:2021-05-12 02:32:04
【问题描述】:

我一直在尝试将特定键的值从另一个具有字典列表的数据框中存储到 pandas 数据框中。 谁能帮我怎么做??

source data frame

result data frame

【问题讨论】:

    标签: python python-3.x pandas list dictionary


    【解决方案1】:

    转置数据帧并使用 loc 通过索引查找将列值替换为字典值。

    dct2={0:[{'a':1,'b':2},{'a':3,'b':4}] ,
         1:[{'a':4,'b':5},{'a':4,'b':1}] ,
         2:[{'a':3,'b':6},{'a':5,'b':4}] 
        }
    df=pd.DataFrame(dct2)
    df=df.T
    df=df.rename(columns={0:'a^',1:'b^'})
    df=df.reset_index()
    print(df)
    
    for key,row in df.iterrows():
         df.loc[key,'a^']=str(row['a^']['a'])+","+str(row['b^']['a'])
        df.loc[key,'b^']=str(row['a^']['b'])+","+str(row['b^']['b'])
    print(df)
    

    【讨论】:

      【解决方案2】:

      试试下面的代码 -

      # assuming that source data frame is df and you have imported pandas as pd
      dataDict = {'a': [], 'b': []}
      for i, row in df.iterrows():
          dataDict['a'].append((row[0][0]['a'], row[0][1]['a']))
          dataDict['b'].append((row[0][0]['b'], row[0][1]['b']))
      newDataFrame = pd.DataFrame(dataDict)
      print(newDataFrame)
      

      【讨论】:

      • 抛出错误:AttributeError: 'Series' object has no attribute 'iterrows'
      • 解决方案是在列表中创建元组,然后构建数据框。
      • @ParashantMahajan 那么你实现或发布了错误的代码。此外,有人毫无道理地对我投了反对票!属性错误显示您在 df 中有一个系列对象,而我在最上面的评论中明确提到我假设它是根据您的问题的数据框!
      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 2019-06-21
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2018-08-30
      相关资源
      最近更新 更多