Python 需要帮助格式化json文件中的数据帧吗
您好,我需要帮助格式化一个json文件,我转换成熊猫数据帧 Json看起来像Python 需要帮助格式化json文件中的数据帧吗,python,pandas,dataframe,Python,Pandas,Dataframe,您好,我需要帮助格式化一个json文件,我转换成熊猫数据帧 Json看起来像 { "test": { "1":["test1_a", "test1_b", "test1_c"] "2":["test2_a", "test2_b", "test2_c"] "
{
"test":
{
"1":["test1_a", "test1_b", "test1_c"]
"2":["test2_a", "test2_b", "test2_c"]
"3":["test3_a", "test3_b", "test3_c"]
}
}
我需要把这个json转换成熊猫数据帧,然后像这样打印出来:
col1 col2 col3
test1_a test1_b test1_c
test2_a test2_b test2_c
test3_a test3_b test3_c
0 2
1 test1_a test1_b test1_c
2 test2_a test2_b test2_c
3 test3_a test3_b test3_c
我该怎么做?我需要它是一个数据帧,需要定义列行
到目前为止,我已经尝试:
json_file = open(json_file_path, 'r')
data = json.load(json_file)
pandasDataframe = pd.Dataframe.from_dict(data)
print(pandasDataframe)
它打印了这个,我不想要:(
更新:当我
pd.DataFrame(data['test'])
它看起来[不完全是我想要的,但它正在到达那里]
1 2 3
0 test1_a test2_a test3_a
1 test1_b test2_b test3_b
2 test1_c test2_c test3_c
更新#2:当我转置时,它看起来像这样:
col1 col2 col3
test1_a test1_b test1_c
test2_a test2_b test2_c
test3_a test3_b test3_c
0 2
1 test1_a test1_b test1_c
2 test2_a test2_b test2_c
3 test3_a test3_b test3_c
我如何摆脱顶部的0和2?这意味着什么?
还有,我如何去掉1,2,3(也就是第一列)
期望输出:
需要添加列名称(col1、col2、col3),但不知道如何添加)
您可以尝试:
pd.DataFrame(data['test']).T.rename(columns={0:'col1',1:'col2',2:'col3'})
输出:
col1 col2 col3
1 test1_a test1_b test1_c
2 test2_a test2_b test2_c
3 test3_a test3_b test3_c
IIUC,你需要
不幸的是,这根本不起任何作用。当您打印(数据)时,您可以添加什么输出吗@SOScodehelpSorry再次尝试,它基本上打印了我想要的内容,但是行就是列,列就是行如果这有意义的话,它基本上是翻转的!你知道我怎么才能把它翻过来吗@mrnobody33您的意思是像带有
df.T
的数据帧@索斯克德赫普
import pandas as pd
pd.DataFrame(data['test']).add_prefix('col')
col1 col2 col3
0 test1_a test2_a test3_a
1 test1_b test2_b test3_b
2 test1_c test2_c test3_c