gpt4 book ai didi

python - 将分组数据框分解为单独的数据框

转载 作者:太空狗 更新时间:2023-10-30 02:52:20 25 4
gpt4 key购买 nike

我想获取一个已分组的数据框,并为每个相应的组创建单独的数据框。

我正在使用列表理解来使用列表 names_list 中的值对 pandas 数据帧进行切片,然后将结果分配给同名的变量。但是,names_list 中的值并不总是出现在我的数据框中,哪个不会出现在数据框中是完全随机的。我怎样才能让它工作并只返回实际出现的变量?

我尝试过的:

idx = pd.IndexSlice

names_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a, b, c, d, e, f, g, h = [df.loc[idx[x,:],:] for x in names_list]

只要数据框中不存在值,上面的代码就会返回一个 KeyError。

还试过:

def split_df(data):
try:
a = [df.loc[idx[x,:],:] for x in data]
except KeyError:
a = None
return a


names_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a, b, c, d, e, f, g, h = [x for x in names_list]
name_vars = [a, b, c, d, e, f, g, h]

name_vars_2 = []
for var, val in zip(name_vars,names_list):
var = split_df(val)
if var is None:
continue
else:
name_vars_2.append(var)

这种方法只为每个值返回一个 None 列表。

我想要的结果是一个变量列表,其中数据帧的相应切片分配给每个变量。

最佳答案

设置

df = pd.DataFrame(dict(A=range(10), B=[*'aabbccddee']))

字典

将它们存储在字典中而不是命名变量

d = dict((*df.groupby('B'),))

d['a']

A B
0 0 a
1 1 a

d['d']

A B
6 6 d
7 7 d

不推荐!

但是为了你的教育。您可以更新 locals() 字典。
这很糟糕,因为动态污染 namespace 会导致许多难以跟踪的错误。
事实上,它不能保证做任何事情。

Per Docs :

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

免责声明,这是你可以做到的:

locals().update(dict((*df.groupby('B'),)))

然后访问命名变量

a

A B
0 0 a
1 1 a

d

A B
6 6 d
7 7 d

关于python - 将分组数据框分解为单独的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53545348/

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