我有一个熊猫数据帧:
id photos
001 [{'medium':'https:blablabla1',
'xl':'something1',
's':'anotherthing1'},
{'medium':'https:blablabla2',
'xl':'something2',
's':'anotherthing2'},
{'medium':'https:blablabla3',
'xl':'something3',
's':'anotherthing3'}]
002 [{'medium':'https:blablabla4',
'xl':'something4',
's':'anotherthing4'},
{'medium':'https:blablabla5',
'xl':'something5',
's':'anotherthing5'},
{'medium':'https:blablabla6',
'xl':'something6',
's':'anotherthing6'}]
003 [{'medium':'https:blablabla7',
'xl':'something7',
's':'anotherthing7'},
{'medium':'https:blablabla8',
'xl':'something8',
's':'anotherthing8'},
{'medium':'https:blablabla9',
'xl':'something9',
's':'anotherthing9'}]
第二个照片列包含字典列表。 我想要的是第一个的价值键:值对在列表中。在
所需输出应如下所示:
^{pr2}$我已经想好了,如果这是一个单列的dicts怎么做。像这样:
dicts_list = [{'medium':'https:blablabla1',
'xl':'something1',
's':'anotherthing1'},
{'medium':'https:blablabla2',
'xl':'something2',
's':'anotherthing2'},
{'medium':'https:blablabla3',
'xl':'something3',
's':'anotherthing3'}]
# Access the first value of the first dict in a list
list(dicts_list[0].values())[0]
#output
'https:blablabla1'
到目前为止,我已经做到了(这显然是错误的):
v = list()
for index, rows in df.iterrows():
photo = rows['photos']
v.append(photo[0])
# output
['[', '[']
其思想是将第一个值放入一个列表中,然后将其添加回原始数据帧中。 我不知道如何将它扩展到pandas数据帧中。在
注意 根据@daren thomas answer,我发现我在数据中引用的字典是dictionary的字符串表示。因此,要将此列转换为字典,请参考以下代码:
import ast
df.photos = df.photos.apply(lambda x: ast.literal_eval(x))
可以对每行使用
apply
函数,如下所示:输出:
^{pr2}$现在,如果您不喜欢
photos
列,可以直接删除它。。。在这是一种方法。如果您的列或
Series
是如下所示的dict列表:不确定是否有更优雅的解决方案。但希望这有帮助!在
编辑
作为补充说明,我知道在}是不受欢迎的。尤其是如果你有非常大的
pandas
社区中大量使用{DataFrame
s。。。您将看到一些性能问题。在我真的想不出一个
vectorized
的解决方案。但如果你的数据集不是太大,我想这应该能解决问题。在相关问题 更多 >
编程相关推荐