转换JSON到csv使用python熊猫

问题描述:

我已经提到这一点: Nested Json to pandas DataFrame with specific format转换JSON到csv使用python熊猫

这:json_normalize produces confusing KeyError

尝试和规范的json代码片段中使用熊猫json_normalize。 但是,输出未完全正常化。下面是我的代码片段

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']) 

的值列的输出是

values 
[{'value': {'share': 2, 'like': 10}}] 

我会一直喜欢有两个列输出,而不是像

value.share value.like 
2    10 

我应该如何做到这一点?

您可能适用json_normalize到值列一个更多的时间来压平:

pd.concat([ 
    df.drop('values', 1), 
    df['values'].apply(lambda x: pd.io.json.json_normalize(x).iloc[0]) 
], axis=1) 

enter image description here

为了您的数据帧,

您可以从内嵌套的字典创建一个新的数据帧值使用df.from_dcit()做:

df2 = pd.DataFrame.from_dict(df['values'].values[0][0], orient = 'index').reset_index().drop(['index'], axis=1) 

获得:

df2: 

    share like 
0  2 10 

然后添加到您现有的数据帧,以获得您需要使用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 

如果需要的话可以重新命名:

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') 
+0

这如果你解释为什么你的代码可以工作会更好。 –