Skip to main content
 首页 » 编程设计

python之在时间戳表上旋转的 Pandas 返回意外结果

2025年04月02日9lyj

我有一个包含两列的 DataFrame: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] 

O 在这里缺少什么?并且是否有更好的方法来实现相同的目标(尝试在表中首次出现 n 时以天为单位获取偏移量)

请您参考如下方法:

IIUC 你需要groupby并使用 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,但首先通过values 转换为numpy array :

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