Pandas GroupBy聚合不保留数据类型



我通过对数值列使用summaxmin等函数来使用PandasGroupByGroupby.agg,但我注意到,在GroupBy聚合后,我之前强加给列的数据类型(如np.int8、np.int16、np.int32(没有保留,实际上每列都被过度缓存到int64。Pandas 1.1.5版

我目前的解决方案是在完成分组聚合后重新向下转换,这是一个已知的问题吗?和/或有更好的解决方案吗?

在Panda 1.1.5版本上测试

我没有得到同样的结果。类型是保守的。

import pandas as pd
import numpy as np
df = pd.DataFrame(dict(a=[1,2,3,4,5], b=[1,2,3,4,5], c=[1,2,3,4,5]))
df = df.astype({'a': np.int8, 'b': np.int16, 'c': np.int32})
new_df = df.groupby(by='c').max()
print(new_df.dtypes)
""" Output - dtypes are conserved.
a     int8
b    int16
dtype: object
"""

也许你使用了一个通过多个专栏的聚合器。如果要聚合a+b=>你会得到int16

new_df = df.groupby(by='c').apply(lambda x: x['a'] + x['b'])
print(new_df.dtypes)
# Output : int16

最新更新