gpt4 book ai didi

python - pandas groupby 是否通过引用或值传递?

转载 作者:行者123 更新时间:2023-12-03 17:27:19 24 4
gpt4 key购买 nike

假设我有一个 Pandas DataFrame 数据我想按某一列拆分它, col , 根据

def split_by_column(data, column):

chunk_list = [(k,g) for k, g in data.groupby(column)]
return dict(chunk_list)


collection = split_by_column(data, 'col')

这样我以后就可以轻松地访问和应用函数到这个集合。

例如,如果我有一个对象同时具有 数据收藏作为实例变量,我是否在内存中有两个单独的数据副本,或者字典是否包含对数据中适当夹头的引用?

最佳答案

我试过这个:

data=pd.DataFrame({'a':[1,2,3,4], 'b':[6,9,8,9]})
print('data initial:',data)
def split_by_column(data, column):
chunk_list = [(k,g) for k, g in data.groupby(column)]
return dict(chunk_list)
collection = split_by_column(data, 'b')
print('collection initial:',collection)

输出是:
data initial:    a  b
0 1 6
1 2 9
2 3 8
3 4 9
collection initial: {6: a b
0 1 6, 8: a b
2 3 8, 9: a b
1 2 9
3 4 9}

如果我现在更改数据
data.at[3,'a']=5

并再次打印数据和收集,输出是这样的:
data new:    a  b
0 1 6
1 2 9
2 3 8
3 5 9
collection new: {6: a b
0 1 6, 8: a b
2 3 8, 9: a b
1 2 9
3 4 9}

由于我也刚刚开始探索 Pandas ,我无法告诉您底层机制是什么,但是由于值 5 仅出现在数据框中,而不出现在 dict 中,因此我得出结论,您有两个不同的副本你的数据。

我希望,这对你有帮助。
最好的,lepakk

关于python - pandas groupby 是否通过引用或值传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59388416/

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