[英]converting json to csv using python pandas
I have referred this: Nested Json to pandas DataFrame with specific format 我已经提到了这一点:将Json嵌套到具有特定格式的pandas DataFrame
and this: json_normalize produces confusing KeyError 这: json_normalize产生令人困惑的KeyError
to try and normalize my json snippet using json_normalize in pandas. 尝试在熊猫中使用json_normalize对我的json代码段进行规范化。 However, the output isn't getting normalized fully.
但是,输出未完全标准化。 Here's a snippet of my code
这是我的代码片段
x =[{'fb_metrics': [{'period': 'lifetime', 'values': [{'value': {'share': 2, 'like': 10}}], 'title': 'Lifetime Post Stories by action type', 'name': 'post_stories_by_action_type', '_id': '222530618111374_403476513350116/insights/post_stories_by_action_type/lifetime', 'description': 'Lifetime: The number of stories created about your Page post, by action type. (Total Count)'}]}]
df = pd.io.json.json_normalize(x[0]['fb_metrics'])
The output for values column is 值列的输出是
values
[{'value': {'share': 2, 'like': 10}}]
I would've liked to have two column outputs instead like 我本来希望有两个列输出,而不是像
value.share value.like
2 10
How should I achieve this? 我应该如何实现?
For your dataframe, 对于您的数据框,
You can create a new DataFrame from the nested dictionary within values using df.from_dcit()
do: 您可以使用
df.from_dcit()
在值内的嵌套字典中创建新的DataFrame:
df2 = pd.DataFrame.from_dict(df['values'].values[0][0], orient = 'index').reset_index().drop(['index'], axis=1)
to get: 要得到:
df2:
share like
0 2 10
Then add this to your existing dataframe to get the format you need using pd.concat
: 然后将其添加到您现有的数据
pd.concat
以使用pd.concat
获得所需的格式:
result = pd.concat([df, df2], axis=1, join='inner')
result[['values', 'share', 'like']]
Out[74]:
values share like
0 [{u'value': {u'share': 2, u'like': 10}}] 2 10
If needed can rename: 如果需要可以重命名:
result.rename(columns={'share': 'values.share', 'like':'values.like'}, inplace=True)
result[['values', 'share', 'like']]
Out[74]:
values values.share values.like
0 [{u'value': {u'share': 2, u'like': 10}}] 2 10
import pandas as pd
df = pd.read_json('data.json')
df.to_csv('data.csv', index=False, columns=['title', 'subtitle', 'date',
'description'])
import pandas as pd
df = pd.read_csv("data.csv")
df = df[df.columns[:4]]
df.dropna(how='all')
df.to_json('data.json', orient='records')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.