Python 在timestap表上进行数据透视会返回意外结果

Python 在timestap表上进行数据透视会返回意外结果,python,datetime,pandas,time-series,pivot-table,Python,Datetime,Pandas,Time Series,Pivot Table,我有一个包含两列的数据帧:ts(时间戳)和n(数字) 时间戳从2016-07-15开始: In [1]: d.head() Out[1]: ts n 0 2016-07-15 00:04:09.444 12 1 2016-07-15 00:05:01.633 12 2 2016-07-15 00:05:03.173 31 3 2016-07-15 00:05:03.970 12 4 2016-07-15 00:05:04.258 23

我有一个包含两列的数据帧:
ts
(时间戳)和
n
(数字)

时间戳从2016-07-15开始:

In [1]: d.head()
Out[1]:
                       ts   n
0 2016-07-15 00:04:09.444  12
1 2016-07-15 00:05:01.633  12
2 2016-07-15 00:05:03.173  31
3 2016-07-15 00:05:03.970  12
4 2016-07-15 00:05:04.258  23
现在,我要说:

pd.pivot_table(d, columns='n', values='ts', aggfunc=lambda x: (np.min(x) - pd.Timestamp('2016-07-15')).days)
我希望看到带有整数的列表示天数,但我看到的是:

n
12   1970-01-01
23   1970-01-01
31   1970-01-01
Name: ts, dtype: datetime64[ns]
我在这里错过了什么?是否有更好的方法实现同样的效果(尝试以天为单位获得表中第一次出现的
n
的偏移量)

IIUC您需要并使用
apply
添加自定义函数:

print (d.groupby('n')['ts'].apply(lambda x: (x.min() - pd.Timestamp('2016-07-15')).days))
n
12    0
23    0
31    0
Name: ts, dtype: int64
在您的代码中,您也会得到
0
,但值会转换为
datetime
1970-01-01
),因为
ts
dtype
以前是
datetime

我想接下来需要将
datetime
转换为
int
,但首先通过以下方式转换为
numpy数组


谢谢groupby似乎是pivot的更好选择!
s = pd.pivot_table(d, columns='n', 
                      values='ts', 
                      aggfunc=lambda x: (np.min(x) - pd.Timestamp('2016-07-15')).days)
s = s.values.astype(int)
print (s)
n
12    0
23    0
31    0
Name: ts, dtype: int64