gpt4 book ai didi

python - Pandas 数据帧到 JSON 格式的操作

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:40 24 4
gpt4 key购买 nike

我有像这样的 pandas DataFrame

User  Category    Rating
1 [1,2,3] [5,1,3]
2 [3,2,1] [3,1,1]
3 [1,3,1] [2,1,4]

我想编写一个端点,它接受用户并返回特定用户的类别和评级列表。

www.endpoint.com/user/1

应该返回

[{类别:1,评级:5},{类别:2,评级:1},{类别:3,评级:3}]

在 Pandas 中是否有一种简单的方法可以做到这一点?

最佳答案

我会使用the following generic function which explodes lists in columns into rows :

def explode(df, lst_cols, fill_value=''):
# make sure `lst_cols` is a list
if lst_cols and not isinstance(lst_cols, list):
lst_cols = [lst_cols]
# all columns except `lst_cols`
idx_cols = df.columns.difference(lst_cols)

# calculate lengths of lists
lens = df[lst_cols[0]].str.len()

if (lens > 0).all():
# ALL lists in cells aren't empty
return pd.DataFrame({
col:np.repeat(df[col].values, df[lst_cols[0]].str.len())
for col in idx_cols
}).assign(**{col:np.concatenate(df[col].values) for col in lst_cols}) \
.loc[:, df.columns]
else:
# at least one list in cells is empty
return pd.DataFrame({
col:np.repeat(df[col].values, df[lst_cols[0]].str.len())
for col in idx_cols
}).assign(**{col:np.concatenate(df[col].values) for col in lst_cols}) \
.append(df.loc[lens==0, idx_cols]).fillna(fill_value) \
.loc[:, df.columns]

演示:

In [88]: df
Out[88]:
User Category Rating
0 1 [1, 2, 3] [5, 1, 3]
1 2 [3, 2, 1] [3, 1, 1]
2 3 [1, 3, 1] [2, 1, 4]

In [89]: cols = ['Category','Rating']

In [90]: x = explode(df, cols)

In [91]: x
Out[91]:
User Category Rating
0 1 1 5
1 1 2 1
2 1 3 3
3 2 3 3
4 2 2 1
5 2 1 1
6 3 1 2
7 3 3 1
8 3 1 4

现在我们可以轻松满足您的需求:

In [92]: x.loc[x.User == 1, cols].to_dict('r')
Out[92]:
[{'Category': '1', 'Rating': '5'},
{'Category': '2', 'Rating': '1'},
{'Category': '3', 'Rating': '3'}]

关于python - Pandas 数据帧到 JSON 格式的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45679050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com