我有一个简单的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转换为数据帧,而不将所有列合并为一列
我会感谢你的帮助。 谢谢
将json文件转换为csv文件格式的最快方法如下
相关问题 更多 >
编程相关推荐