python - 在 Pandas 中重新索引并转换为 json

标签 python json pandas

我有一个数据框:

     accountname ip
0    aa          10.1.1.1
1    bb          10.1.1.2
2    cc          10.1.1.3

我想要一个像这样的 json:

{ 'aa':{'ip':'10.1.1.1'}, 'bb':{'ip':'10.1.1.2'},'cc':{'ip':'10.1.1.3'}}

但是用

df.index.name = 'accountname'
df.reset_index(drop=True)
json = df.to_json(orient='index')

我在 json 中有旧索引。任何建议将不胜感激。

最佳答案

这是一个简单的解决方案:

import pandas as pd
from io import StringIO

# Sample data
string=u"""accountname,ip
aa,10.1.1.1
bb,10.1.1.2
cc,10.1.1.3"""

# Creates a DataFrame from sample data
df = pd.read_csv(StringIO(string))

# the key here is the T where rows become columns
df.set_index("accountname").T.to_json()
# or
#df.set_index('accountname').to_json(orient='index')

返回:

'{"aa":{"ip":"10.1.1.1"},"bb":{"ip":"10.1.1.2"},"cc":{"ip":"10.1.1.3"}}'

关于python - 在 Pandas 中重新索引并转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46594675/

相关文章:

python dataset - 读取一组列并将其放入单独的数据框中?

python - 将字符串解析为 boolean 值?

创建特定元素列表的 Pythonic 方法

Python Scrapy : response object different from source code in browser

javascript - JSON.stringify 设置根元素

javascript - Ajax 脚本无法在表单提交上运行?

python - 根据元素的位置 reshape 列表列表

c# - 附加信息 : Error converting value [string] to type [enum]

python - 如何获取数据框中列的位置编号

Python: Unstacked DataFrame 太大,导致 int32 溢出