2017-04-16 121 views
1

我已經提到這一點: 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 

我應該如何做到這一點?

回答

1

您可能適用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

1

爲了您的數據幀,

您可以從內嵌套的字典創建一個新的數據幀值使用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 
0
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

這如果你解釋爲什麼你的代碼可以工作會更好。 –