Python 在JSON文件中映射数据帧值

Python 在JSON文件中映射数据帧值,python,json,pandas,mapping,Python,Json,Pandas,Mapping,我想将下面的df映射到一个JSON文件中 #df fruit dessert ------------------- apple sauce blueberry muffin cherry pie import json df = df.to_json() #desired output {"apple": "sauce", "blueberry": "muffin", &q

我想将下面的
df
映射到一个JSON文件中

#df
fruit       dessert
-------------------
apple       sauce
blueberry   muffin
cherry      pie

import json
df = df.to_json()

#desired output
{"apple": "sauce", "blueberry": "muffin", "cherry": "pie"}
我已经导入了我需要的内容,并将
df
转换为JSON。我接下来应该做什么来获得所需的输出


任何帮助都将不胜感激

通过
zip
dict
创建字典,然后转换为
json

import json

j = json.dumps(dict(zip(df['fruit'], df['dessert'])))
print (j)
{"apple": "sauce", "blueberry": "muffin", "cherry": "pie"}
或创建
系列
并调用:


通过
zip
dict
创建字典,然后转换为
json

import json

j = json.dumps(dict(zip(df['fruit'], df['dessert'])))
print (j)
{"apple": "sauce", "blueberry": "muffin", "cherry": "pie"}
或创建
系列
并调用:


您可以重新编制索引并使用.to_dict

df.set_index('fruit').to_dict()['dessert'] 

您可以重新编制索引并使用.to_dict

df.set_index('fruit').to_dict()['dessert'] 

OP需要将值转换为json,而不是dict。json是一个字典子集。OP需要将值转换为json,而不是dict。json是一个字典子集。不确定发生了什么,但在运行代码几次之后,我现在收到了这个错误:
TypeError:字符串索引必须是整数
这可能是什么?@mattebeat-什么代码返回错误?因为python中的映射需要
dict
,而不是json,所以使用
d=dict(zip(df['fruit'],df['sarth'])
d=df.set_index('fruit')['sarth'])来设置json()
第一个给我这个
类型错误:字符串索引必须是整数
第二个给我这个
属性错误:“str”对象没有属性“set\u index”
@mattebeat-什么是
打印(df)
?它是
DataFrame
,如果test
print(type(df))
?@mattebeat-我这样问是因为error
AttributeError:“str”对象没有属性“set\u index”
意味着
df
不是DataFrame,而是字符串。因此,在
df之前是否可以测试
print(type(df))
。将_index('fruit')['sarth']设置为_json()
?因为它似乎使用了类似于
df=df.set_index('fruit')['sarth'].to_json()
-所以变量
df
被转换成字符串json,所以如果再次使用
df.set_index('fruit')['sarth'],to_json()
df不是数据帧,而是字符串。,因此引发的错误不确定发生了什么,但在运行代码几次之后,我现在得到了这个错误:
TypeError:string索引必须是整数
可能是什么?@mattebeat-什么代码返回错误?因为python中的映射需要
dict
,而不是json,所以使用
d=dict(zip(df['fruit'],df['sarth'])
d=df.set_index('fruit')['sarth'])来设置json()
第一个给我这个
类型错误:字符串索引必须是整数
第二个给我这个
属性错误:“str”对象没有属性“set\u index”
@mattebeat-什么是
打印(df)
?它是
DataFrame
,如果test
print(type(df))
?@mattebeat-我这样问是因为error
AttributeError:“str”对象没有属性“set\u index”
意味着
df
不是DataFrame,而是字符串。因此,在
df之前是否可以测试
print(type(df))
。将_index('fruit')['sarth']设置为_json()
?因为它似乎使用类似于
df=df.set_index('fruit')['sarth'].to_json()
-所以变量
df
被转换成字符串json,所以如果再次使用
df.set_index('fruit')['sarth'])。to_json()
df不是数据帧,而是字符串,因此引发了错误