【问题标题】:Getting TypeError when trying to retrieve values from keys in a list of dictionaries尝试从字典列表中的键中检索值时出现 TypeError
【发布时间】:2019-01-28 06:29:46
【问题描述】:

我在 pandas DataFrame 中有一个字典数组:

 0      [{'id': 16, 'name': 'Animation'}, {'id': 35, 'name': 'Comedy'}, {'id': 10751, 'name': 'Family'}]                                                                                                     
 1      [{'id': 12, 'name': 'Adventure'}, {'id': 88, 'name': 'Fantasy'}, {'id': 10751, 'name': 'Family'}]                                                                                                    
 2      [{'id': 10749, 'name': 'Romance'}, {'id': 77, 'name': 'Horror'}]     

我正在尝试将单行中的所有名称放入一个简单的字符串列表中,例如:数据集中每一行的“恐怖、家庭、戏剧”等。

我尝试了这段代码,但出现错误:字符串索引必须是整数

for y in df:
    names = [x['name'] for x in y]

任何帮助都是appriciated

【问题讨论】:

  • 遍历数据框会遍历其列的名称...
  • 在这种情况下,我的 df 仅包含一列。即使我跳过第一个循环,我也会得到同样的错误

标签: python string list pandas dictionary


【解决方案1】:

IIUC,这是字典而不是列表。你应该使用.get

[[y.get('name') for y in x ]for x in df['your columns']]
Out[578]: 
[['Animation', 'Comedy', 'Family'],
 ['Adventure', 'Fantasy', 'Family'],
 ['Romance', 'Horror']]

转换字符串

import ast
df.a=df.a.apply(ast.literal_eval)

【讨论】:

  • 谢谢,但现在我收到此错误:AttributeError: 'str' object has no attribute 'get' 不知道为什么它对你有用?
  • @JokkeMedKniven import ast;df.a=df.a.apply(ast.literal_eval)
  • 遍历数据框会遍历其列的名称
  • @juanpa.arrivillaga 我不确定它是数据框还是系列......因为数据显示就像系列
  • 我只从 DataFrame 中提取了我需要的列,所以我认为这使它成为一个系列?
【解决方案2】:

遍历数据框会遍历列的名称,`:

In [15]: df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

In [16]: df
Out[16]:
   a  b
0  1  4
1  2  5
2  3  6

In [17]: for x in df:
    ...:     print(x)
    ...:
a
b

就像dict 会迭代它的键。

你需要这样的东西:

df['your_column'].apply(lambda x: [d['name'] for d in x])

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2019-03-12
    • 2011-07-11
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多