将json转换为熊猫数据框的更有效方法

时间:2020-10-29 18:40:24

标签: python json pandas dataframe nested

我有一个简单的json文件,我必须将其转换为panda datarame,然后转换为csv。该文件中的一些示例记录是:

    {
      '11': ['A', 'fried', 'is', 'a', 'nice', 'companion', '.'],  
      '2':  ['Let', 'the', 'things', 'happen', '.'], 
      '33': ['There', 'is', 'always', 'a', 'way', 'out', '.'],
      '4':  ['The', 'birds', 'are', 'flying', '.'],
       ... more than 500,000 records
    }

结果数据框:

    11,    A friend is a nice companion.
     2,    Let the things happen.            
    33,    There is always a way out.
     4,    The birds are flying.    
    ..... upto 500,000 records 

下面给出了将其转换的代码,并且可以正常工作:

import pandas as pd
import json

df = pd.read_json('my_file.json', orient = 'index')

df = df[df.columns[1:]].apply(lambda x:' '.join(x.dropna().astype(str)),axis=1)

#df = df.apply(lambda x: x.replace(',',' '))
print(df)

df.to_csv('outPutFile1.csv', encoding='utf-8')

我想知道是否有更有效的解决方案?因为我不得不将所有列合并为一列,因为“,”被大熊猫视为分隔符。可能直接将json转换为pandas数据框,而无需将所有列合并为一个?

我将不胜感激。 谢谢

1 个答案:

答案 0 :(得分:0)

将json文件转换为所需的csv文件格式的最快方法如下

# load json file to a dictionary
with open('my_file.json') as f:
    my_file_dictionary = json.load(f)    

# save dictionary keys and value(text separated by space) to a csv
with open('outPutFile1.csv', mode='w', encoding='utf-8') as fp:
    [fp.write('{0},{1}\n'.format(key, ' '.join(value))) for key, value in my_file_dictionary.items()]
相关问题