我有一个单列的pandas数据框,看起来每个字典当前都是一个字符串。我想将熊猫中的每个项目转换为字典,然后将其拆分为单独的列。
当前外观
0 {'Owl': '8109284', 'county': '27'}
1 {'Kid': '298049', 'county': '28'}
2 {'Tree': '190849', 'county': '29'}
3 {'Garden': '9801294', 'county': '30'}
4 {'House': '108094', 'county': '31'}
End Look
Item Count County County Number
0 'Owl' '8109284' 'county' '27'
1 'Kid' '298049' 'county' '28'
2 'Tree' '190849' 'county' '29'
3 'Garden' '9801294 'county' '30'
4 'House' '108094' 'county' '31'
Can anyone help resolve this. I've tried a bunch of different things.
您可以使用literal_eval()
将dict
对象移出string
。之后,使用items()
上的方法获取项目dictionary
。最后,构造数据框。
import ast
import pandas as pd
d = [[0, "{'Owl': '8109284', 'county': '27'}"],
[1, "{'Kid': '298049', 'county': '28'}"],
[2, "{'Tree': '190849', 'county': '29'}"],
[3, "{'Garden': '9801294', 'county': '30'}"],
[4, "{'House': '108094', 'county': '31'}"]]
df = pd.DataFrame(d, columns=['a', 'b'])
pd.DataFrame(df['b'].apply(lambda x: [j for i in ast.literal_eval(x).items() for j in i]).to_list(),
columns=['Item', 'Count', 'County', 'County Number'])
Item Count County County Number
0 Owl 8109284 county 27
1 Kid 298049 county 28
2 Tree 190849 county 29
3 Garden 9801294 county 30
4 House 108094 county 31
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句