pandas 将 <m8[ns] 转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41125256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:37:03  来源:igfitidea点击:

Convert <m8[ns] to int

pythonpandasnumpy

提问by Cheng

I am using pandas and one of the column is of type <m8[ns]. I stored 'days' in it, like 5 days, 3 days, etc.

我正在使用Pandas,其中一列的类型是<m8[ns]。我在其中存储了“天”,例如 5 天、3 天等。

I want to convert this 'days' column from <m8[ns]to float64, how can I do that?

我想将此“天”列从 转换<m8[ns]float64,我该怎么做?

回答by EdChum

The dtypeyou're seeing is the numpy dtype for datetimes, if you just want the days then use dt.dayto return you the days:

dtype你看到的是日期时间的numpy的D型,如果你只是想在天,然后用 dt.day返回你的日子:

df['days'] = df['days'].dt.day

See this example:

看这个例子:

In [124]:
import datetime as dt
import pandas as pd
df = pd.DataFrame({'dates':pd.date_range(dt.datetime(2016,1,1), periods=10)})
df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 1 columns):
dates    10 non-null datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 160.0 bytes

In [125]:    
df['dates'].dtype

Out[125]:
dtype('<M8[ns]')

In [126]:
df['day'] = df['dates'].dt.day
df

Out[126]:
       dates  day
0 2016-01-01    1
1 2016-01-02    2
2 2016-01-03    3
3 2016-01-04    4
4 2016-01-05    5
5 2016-01-06    6
6 2016-01-07    7
7 2016-01-08    8
8 2016-01-09    9
9 2016-01-10   10

In [127]:    
df.dtypes

Out[127]:
dates    datetime64[ns]
day               int64
dtype: object