繁体   English   中英

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

[英]More efficient way of converting json to panda dataframe

我有一个简单的 json 文件,我必须将其转换为熊猫数据帧,然后再转换为 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 数据帧而不将所有列合并为一?

我会感谢一些帮助。 谢谢

将您的 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()]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM