這是如下所示的資料集,我想將其轉換為每個資料列,其值為
我想在列中附加值,我嘗試了這段代碼
y = data['actions'].apply(lambda x: str(x).replace("'",'"'))
json.loads(y[0])
json.loads(y[1])
它給出如下所示的輸出
[{'action_type': 'post_reaction', 'value': '2'},
{'action_type': 'link_click', 'value': '42'},
{'action_type': 'comment', 'value': '1'},
{'action_type': 'post_engagement', 'value': '45'},
{'action_type': 'page_engagement', 'value': '45'},
{'action_type': 'onsite_conversion.lead_grouped', 'value': '6'},
{'action_type': 'leadgen_grouped', 'value': '6'},
{'action_type': 'lead', 'value': '6'}]
[{'action_type': 'onsite_conversion.post_save', 'value': '1'},
{'action_type': 'post_reaction', 'value': '4'},
{'action_type': 'link_click', 'value': '62'},
{'action_type': 'post_engagement', 'value': '67'},
{'action_type': 'page_engagement', 'value': '67'},
{'action_type': 'onsite_conversion.lead_grouped', 'value': '6'},
{'action_type': 'leadgen_grouped', 'value': '6'},
{'action_type': 'lead', 'value': '6'}]
我想創建將每個動作型別作為列的資料框,并將它們的值附加到相應的列中,如果沒有值,它會附加零,例如
| post_reaction| link click | comment |---------------------
| -------- | -----------|---------|
| 2 | 42 |1 |
| 4 | 62 |67 |
uj5u.com熱心網友回復:
如果資料中沒有串列ast.literal_eval用于首先轉換,然后使用串列理解創建DataFrame:
import ast
y = data['actions'].apply(ast.literal_eval)
df = pd.DataFrame([{z['action_type']:z['value'] for z in x} for x in y]).fillna(0)
如果資料中的串列僅使用串列理解:
df = (pd.DataFrame([{z['action_type']:z['value'] for z in x} for x in data['actions']])
.fillna(0))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410035.html
標籤:
上一篇:Python-使用PyGitHubget_contents從github下載yaml檔案并嘗試將其轉換為dict
