【问题标题】:Add key values pair inside list into pandas dataframe column将列表内的键值对添加到熊猫数据框列中
【发布时间】:2018-07-08 05:54:52
【问题描述】:

我有 listA

[{'index': 0,
  'keywords': ['nuclear','china','force','capabilities','pentagon','defence']},
 {'index': 1,
  'keywords': ['pakistan', 'membership', 'china', 'nsg', 'kirby', 'meets']},
 {'index': 2,
  'keywords': ['payment', 'rbi', 'applications', 'bill', 'bbpou', 'payments']}]

`

我想将它作为第一个单元格的第一个元素添加到 pandas 列中。我预期的输出为:-

Column_new
{'index': 0,'keywords': ['nuclear','china','force','capabilities','pentagon','defence']}
{'index': 1,'keywords': ['pakistan', 'membership', 'china', 'nsg', 'kirby', 'meets']}
{'index': 2,'keywords': ['payment', 'rbi', 'applications', 'bill', 'bbpou', 'payments']}

我所做的是:-

df = pd.DataFrame(listA,col=['Column_new'])

但它给出了一个带有 NaN 值的数据框,

   Column_new
0  NaN

1  NaN

2  NaN

【问题讨论】:

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


    【解决方案1】:

    问题是……你有一个系列。改为这样做:

    df = pd.Series(listA).to_frame('Column_new')
    

    完整示例:

    import pandas as pd
    
    listA = [{'index': 0,
      'keywords': ['nuclear','china','force','capabilities','pentagon','defence']},
     {'index': 1,
      'keywords': ['pakistan', 'membership', 'china', 'nsg', 'kirby', 'meets']},
     {'index': 2,
      'keywords': ['payment', 'rbi', 'applications', 'bill', 'bbpou', 'payments']}]
    
    
    df = pd.Series(listA).to_frame('Column_new')
    print(df)
    

    返回:

                                              Column_new
    0  {'index': 0, 'keywords': ['nuclear', 'china', ...
    1  {'index': 1, 'keywords': ['pakistan', 'members...
    2  {'index': 2, 'keywords': ['payment', 'rbi', 'a...
    

    【讨论】:

    • @James 在这种情况下,您可以使用df['newcolumn'] = pd.Series(listA) 或简单地说:df['newcolumn'] = listA。还是我错过了什么?
    • 你能看看这个https://stackoverflow.com/questions/51574485/match-keywords-in-pandas-column-with-another-list-of-elements。我没有得到解决方案
    猜你喜欢
    • 2016-09-08
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    相关资源
    最近更新 更多