【发布时间】:2014-01-26 19:03:20
【问题描述】:
嗨,
我有一些来自行为实验的连续 x/y 坐标,我想使用 Pandas 在组内平均。
我在这里使用数据的一个子集。
data
Out[11]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2036 entries, 0 to 1623
Data columns (total 9 columns):
id 2036 non-null values
subject 2036 non-null values
code 2036 non-null values
acc 2036 non-null values
nx 2036 non-null values
ny 2036 non-null values
rx 2036 non-null values
ry 2036 non-null values
reaction_time 2036 non-null values
dtypes: bool(1), int64(3), object(5)
nx 和 ny 包含一系列 TimeSeries 对象,它们都具有相同的索引。
data.nx.iloc[0]
Out[16]:
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 0
...
86 1.019901
87 1.010000
88 1.010000
89 1.005921
90 1.000000
91 1.000000
92 1.000000
93 1.000000
94 1.000000
95 1.000000
96 1.000000
97 1.000000
98 1.000000
99 1.000000
100 1.000000
Length: 101, dtype: float64
这些 TimeSeries 列可以正常平均,使用 data.nx.mean(),并按预期运行,但是当我尝试对数据进行分组时遇到了麻烦。
grouped = data.groupby(['code', 'acc'])
means = grouped.mean()
print means
id subject reaction_time
code acc
group1 False 1570.866667 47474992.333333 1506.000000
True 1337.076152 46022403.623246 1322.116232
group2 False 1338.180180 48730402.045045 1289.112613
True 1382.631757 42713592.628378 1294.952703
group3 False 1488.587156 43202477.623853 1349.568807
True 1310.415233 47054310.498771 1341.837838
group4 False 1339.682540 52530349.936508 1540.714286
True 1343.261176 44606616.407059 1362.174118
奇怪的是,我可以强制他们平均 TimeSeries 数据,并且可能不得不依靠这种方式进行黑客攻击,如下所示:
for name, group in grouped:
print group.nx.mean()
0 0.000000
1 0.000000
2 0.000000
3 0.000000
4 0.000000
5 0.000667
6 0.000683
7 0.001952
8 0.002000
9 0.002000
{etc, 101 values for 6 groups}
最后,如果我尝试强制 GroupBy 对象对它们进行平均,我会得到以下结果:
grouped.nx.mean()
---------------------------------------------------------------------------
DataError Traceback (most recent call last)
<ipython-input-25-0b536a966e02> in <module>()
----> 1 grouped.nx.mean()
/usr/local/lib/python2.7/dist-packages/pandas-0.12.0-py2.7-linux-i686.egg/pandas/core/groupby.pyc in mean(self)
357 """
358 try:
--> 359 return self._cython_agg_general('mean')
360 except GroupByError:
361 raise
/usr/local/lib/python2.7/dist-packages/pandas-0.12.0-py2.7-linux-i686.egg/pandas/core/groupby.pyc in _cython_agg_general(self, how, numeric_only)
462
463 if len(output) == 0:
--> 464 raise DataError('No numeric types to aggregate')
465
466 return self._wrap_aggregated_output(output, names)
DataError: No numeric types to aggregate
有人有什么想法吗?
【问题讨论】:
-
你的浮动数据都是df的信息中的对象dtype(参见object(5))。您是如何生成/读取数据的? (对于数字类型操作,它应该是 float64 dtype)
标签: python pandas time-series mean