将DateTime索引值转换为索引号

时间:2018-09-27 17:38:29

标签: python pandas numpy datetime dataframe

如果我有一个具有日期时间索引的数据框,并且我使用series.first_valid_index获得了第一个有效索引-它返回第一个非nan的日期时间,但这是我要查找的日期:

有没有一种方法可以获取datetime值所对应的索引号。例如,它返回2018-07-16,但我想知道那是数据帧的第18行吗?

如果没有,是否有一种方法可以计算从数据帧开头到该索引值的行?

4 个答案:

答案 0 :(得分:2)

TLDR :如果您需要一种将给定索引值(在这​​种情况下为DatetimeIndex)映射为其等效整数的方法,则您要求get_loc,如果您只想从Series中查找整数索引,请对基础argmax数组使用numpy

设置

np.random.seed(3483203)

df = pd.DataFrame(
    np.random.choice([0, np.nan], 5),
    index=pd.date_range(start='2018-01-01', freq='1D', periods=5)
)

              0
2018-01-01  NaN
2018-01-02  NaN
2018-01-03  0.0
2018-01-04  NaN
2018-01-05  NaN

在此处使用pandas.Index.get_loc,这是为给定标签返回整数索引的常规功能:

>>> idx = df[0].first_valid_index()
>>> idx
Timestamp('2018-01-03 00:00:00', freq='D')
>>> df.index.get_loc(idx)
2

如果您想完全避免找到datetime索引,则可以在基础argmax数组上使用numpy

>>> np.argmax(~np.isnan(df[0].values))
2

答案 1 :(得分:1)

我会尝试(未试用):

x = len(df)
num_index = range(0,x,1)
df =  df.reset_index()
df = df.set_index(num_index)

答案 2 :(得分:0)

您可以将np.arwherenp.isnanpd.notnull一起使用:

np.argwhere(~np.isnan(s)).flat[0]
# or:
# np.argwhere(pd.notnull(s)).flat[0]

给出系列:

>>> s
2018-09-27    NaN
2018-09-28    NaN
2018-09-29    5.0
2018-09-30    5.0
2018-10-01    NaN
Freq: D, dtype: float64

您得到:

>>> np.argwhere(~np.isnan(s)).flat[0]
2

或者,只需重置索引并获取first_valid_index

>>> s.reset_index()[0].first_valid_index()
2

答案 3 :(得分:0)

创建一个字典,键为datetime对象,其值为您的索引。 示例代码供您参考:

timestamp=df.iloc[0:,0].tolist()
timestamp_dict={}
number=0
for time in timestamp:
    timestamp_dict[time]=number
    number+=1

希望有帮助。

相关问题