我的非数字列在重新采样时被删除

时间:2019-08-20 16:19:06

标签: python pandas

我的2个非数字列标签和FID在重新采样时被删除,如何保留这些列?

T               CP      LC      DP     VB   WP      LABEL   FID
10/26/201711:00 251.05  40.9    3157.9  0   256.27  F30d    MN-0001-2017-1
10/26/201711:01 250.88  38.8    3159.3  0   257.32  F30d    MN-0001-2017-1
10/26/201711:02 250.85  38.2    3157.2  0   256.81  F30d    MN-0001-2017-1
10/26/201711:03 250.72  31.7    3159.7  0   255.74  F30d    MN-0001-2017-1

使用groupby似乎只保留1列:

newseries1 = newseries.groupby('LABEL').resample('10min', level=1).mean()
newseries1.head(10)

我想在数据框中保留2个列LABEL和FID

1 个答案:

答案 0 :(得分:1)

resample就像groupby一样,因此您可以指定字典以不同方式聚合数字和非数字列。

numeric = df.select_dtypes('number').columns
non_num = df.columns.difference(numeric)
d = {**{x: 'mean' for x in numeric}, **{x: 'first' for x in non_num}}

df.resample('10min').agg(d)

样本数据

import pandas as pd
import numpy as np

df = pd.DataFrame(index=pd.date_range('2010-01-01', freq='3min', periods=20),
                  data={'col1': np.random.randint(1, 100, 20),
                        'col2': np.random.choice(list('abcde'), 20)})

numeric = df.select_dtypes('number').columns
non_num = df.columns.difference(numeric)
d = {**{x: 'mean' for x in numeric}, **{x: 'first' for x in non_num}}

df.resample('10min').agg(d)

#                          col1 col2
#2010-01-01 00:00:00  45.750000    e
#2010-01-01 00:10:00  61.000000    d
#2010-01-01 00:20:00  81.000000    b
#2010-01-01 00:30:00  28.750000    e
#2010-01-01 00:40:00  37.333333    a
#2010-01-01 00:50:00  20.333333    a