将列值用作大熊猫JSON中的键

发布于 2025-01-29 10:36:40 字数 324 浏览 2 评论 0原文

我有下面的熊猫数据框架。我只是想知道是否有任何方法可以将我的列值作为JSON的钥匙。

DF: |符号|价格| |:------- | ------- | | a。 | 120 | | b。 | 100 | | C | 200 |

我希望json看起来像{'a':120,'b':100,'c':200}

我尝试了下面的结果,并将结果作为{符号:'a',价格:120} { :'b',价格:100} {符号:'c',价格:200}

df.to_json('price.json', orient='records', lines=True) 

I have a pandas dataframe as below. I'm just wondering if there's any way to have my column values as my key to the json.

df:
|symbol | price|
|:------|------|
|a. |120|
|b. |100|
|c |200|

I expect the json to look like {'a': 120, 'b': 100, 'c': 200}

I've tried the below and got the result as {symbol: 'a', price: 120}{symbol: 'b', price: 100}{symbol: 'c', price: 200}

df.to_json('price.json', orient='records', lines=True) 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦途 2025-02-05 10:36:40

首先,让我们创建OP提及的数据

import pandas as pd

df = pd.DataFrame({'symbol': ['a', 'b', 'c'], 'price': [120, 100, 200]})

框 以下工作将完成工作,以下工作将完成工作

df.groupby('symbol').price.apply(lambda x: x.iloc[0]).to_dict()

[Out]: {'a': 120, 'b': 100, 'c': 200}

pandas-json/72259719#comment127663214_72259545“>在此处注释),如果一个人想要json值作为列表,

df.groupby('symbol').price.apply(list).to_json()

[Out]: {"a":[120],"b":[100],"c":[200]}

Let's start by creating the dataframe that OP mentions

import pandas as pd

df = pd.DataFrame({'symbol': ['a', 'b', 'c'], 'price': [120, 100, 200]})

Considering that OP doesn't want the JSON values as a list (as OP commented here), the following will do the work

df.groupby('symbol').price.apply(lambda x: x.iloc[0]).to_dict()

[Out]: {'a': 120, 'b': 100, 'c': 200}

If one wants the JSON values as a list, the following will do the work

df.groupby('symbol').price.apply(list).to_json()

[Out]: {"a":[120],"b":[100],"c":[200]}
蓝天 2025-02-05 10:36:40

尝试这样:

import pandas as pd

d = {'symbol': ['a', 'b', 'c'], 'price': [120, 100, 200]}
df = pd.DataFrame(data=d)

print(df)

print (df.set_index('symbol').rename(columns={'price':'json_data'}).to_json())

# EXPORT TO FILE
df.set_index('symbol').rename(columns={'price':'json_data'}).to_json('price.json')

输出:

  symbol  price
0      a    120
1      b    100
2      c    200
{"json_data":{"a":120,"b":100,"c":200}}

Try like this :

import pandas as pd

d = {'symbol': ['a', 'b', 'c'], 'price': [120, 100, 200]}
df = pd.DataFrame(data=d)

print(df)

print (df.set_index('symbol').rename(columns={'price':'json_data'}).to_json())

# EXPORT TO FILE
df.set_index('symbol').rename(columns={'price':'json_data'}).to_json('price.json')

Output :

  symbol  price
0      a    120
1      b    100
2      c    200
{"json_data":{"a":120,"b":100,"c":200}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文