![](/img/trans.png)
[英]How to convert a string of text into new columns in a pandas DataFrame? Airbnb Dataset
[英]How to convert string representation of dictionary in Pandas DataFrame to a new columns?
我在 Pandas DataFrame Column 中有一個字典的字符串表示,如下所示:
>>> df['the_column']
0 "{'a': 1., 'b': 2., 'c':3.}"
1 "{'a': 4., 'b': 5., 'c':6.}"
2 "{'a': 7., 'b': 8., 'c': 9.}"
3 "{'a': 10., 'b': 11., 'c':12.}"
...
我想將每個鍵附加到現有 DataFrame 中的列,這怎么可能?
我試過這樣的事情:
list_of_new_col = [json.loads(c) for c in df['the_column']]
# resulting list of dictionary
# convert it to pandas DataFrame
# and then concat with the existing DataFrame
但我得到了TypeError: the JSON object must be str, bytes or bytearray, not 'float'
關於如何解決這個問題的任何想法?
謝謝你。
注意:我犯了一個錯誤,請檢查已接受的答案和評論以獲取詳細信息。
你可以試試ast
df['the_column']=df['the_column'].apply(ast.literal_eval)
除了接受的答案,我發現這也有效
pd.concat([df, df.the_column.apply(json.loads).apply(pd.Series)], axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.