如何将此Pandas DataFrame转换为特定的JSON格式?

时间:2019-12-16 16:54:47

标签: python json dataframe

我试图弄清楚如何从此Pandas DataFrame中获得帮助

Pandas DataFrame

此JSON:

JSON

我已经尝试过dataframe.to_json方法(及其各种返回方向),但这没有给我确切的所需输出。我已经在网上阅读了很多,但是一切都很简单。任何帮助将不胜感激:)

原始dataFrame是这里的情况:

NETWORK_USERID  TALK_STATUS TALK_STATUS_EXPIRY  CATEGORY    CATEGORY_EXPIRY
0   f40daf16-f069-4c1d-ac2a-d1504f0fc147    Talker  15/12/2020  MN_FFBQ 23/12/2019
1   4d3e9e50-f88b-4c0b-a700-881474f992ab    Lurker  15/12/2020  MN_FFBQ 23/12/2019
2   c2e2fa63-efad-4b7d-b11e-77d9c8692677    Lurker  15/12/2020  MN_FFBQ 23/12/2019
3   c46a2af4-0c20-486e-9ae0-6323269f252d    Lurker  15/12/2020  MN_FFBQ 23/12/2019
4   f6f88be2-dca6-4129-93ed-2b32a633e1ec    Talker  15/12/2020  MN_FFBQ 23/12/2019

2 个答案:

答案 0 :(得分:0)

pandas库提供了一个适当的功能:to_json函数。

文档⬇️

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html

答案 1 :(得分:0)

也许这可以帮助您:

import pandas as pd
from io import StringIO

data = """
NETWORK_USERID,TALK_STATUS,TALK_STATUS_EXPIRY,CATEGORY,CATEGORY_EXPIRY
f40daf16-f069-4c1d-ac2a-d1504f0fc147,Talker,15/12/2020,MN_FFBQ,23/12/2019
4d3e9e50-f88b-4c0b-a700-881474f992ab,Lurker,15/12/2020,MN_FFBQ,23/12/2019
c2e2fa63-efad-4b7d-b11e-77d9c8692677,Lurker,15/12/2020,MN_FFBQ,23/12/2019
c46a2af4-0c20-486e-9ae0-6323269f252d,Lurker,15/12/2020,MN_FFBQ,23/12/2019
f6f88be2-dca6-4129-93ed-2b32a633e1ec,Talker,15/12/2020,MN_FFBQ,23/12/2019
"""
df = pd.read_csv(StringIO(data),sep=',')

v = df.values.tolist()
lst = []
col1=['value','expiry']

for row in v:
    lst.append([row[0],'['+str(dict(zip(col1, [row[3],row[4]])))+']'])

df1 = pd.DataFrame(lst,columns=['NETWORK_USERID','CATEGORY'])
print(df1)