我有一个混合的pd.DataFrame
:
import pandas as pd
import numpy as np
df = pd.DataFrame({ 'A' : 1.,
'B' : pd.Timestamp('20130102'),
'C' : pd.Timestamp('20180101'),
'D' : np.random.rand(10),
'F' : 'foo' })
df
Out[12]:
A B C D F
0 1.0 2013-01-02 2018-01-01 0.592533 foo
1 1.0 2013-01-02 2018-01-01 0.819248 foo
2 1.0 2013-01-02 2018-01-01 0.298035 foo
3 1.0 2013-01-02 2018-01-01 0.330128 foo
4 1.0 2013-01-02 2018-01-01 0.371705 foo
5 1.0 2013-01-02 2018-01-01 0.541246 foo
6 1.0 2013-01-02 2018-01-01 0.976108 foo
7 1.0 2013-01-02 2018-01-01 0.423069 foo
8 1.0 2013-01-02 2018-01-01 0.863764 foo
9 1.0 2013-01-02 2018-01-01 0.037085 foo
我想聚合我的数字列,但也保留非数字列。
如果我做一个gropuby
其次是agg
.
I get:
df.groupby('B').agg(np.median)
Out[13]:
A D
B
2013-01-02 1.0 0.482157
这很好,我知道这是期望的行为,因为其他 dtypes 可能会在 np.median 期间引发异常,但我也想得到我的原始专栏F
有价值foo
, 也C
with 2018-01-01
到目前为止,我已经使用自定义包装器解决了我的数值聚合函数,例如如果我想对我的数据框进行 nanmean:
def my_nan_median(x):
if isinstance(x.values[0], np.datetime64):
return np.min(x) # let the first datetime pass!
elif isinstance(x.values[0], str):
return x.values[0] # let the strings pass!
else:
return np.nanmedian(x)
但看起来很糟糕。
这样做的正确方法是什么?
通过使用select_dtypes
:
df.groupby(list(df.select_dtypes(exclude=[np.number]))).agg(np.median).reset_index()
或者是这样的:
df1 = df.groupby('B',as_index=False).agg(np.median)
pd.concat([df1,df.drop_duplicates(['B']).drop(list(df1),1).reset_index(drop=True)],axis=1)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)