python - 有没有更好的方法来索引数据帧?

标签 python pandas dataframe

我是 Python 和数据帧的新手。我想知道是否有更好的方法来做这样的事情:

df['Datetime'] = df.index
df.reset_index(inplace=True, drop=True)
df['id'] = df.index
df.index = df['Datetime']
df.drop('Datetime', axis=1, inplace=True)

我需要一个 ID/索引列,以便我可以在数学公式中使用它( sin(2*pi*id)sin(2*pi*datetime) 效果更好)。

有没有一种更简单(Pythonic)的方法来生成它而无需移动列?

更新:

print(df.index)
print(df['id'])

输出:

DatetimeIndex(['2013-01-03', '2013-01-04', '2013-01-07', '2013-01-08',
               '2013-01-09', '2013-01-10', '2013-01-11', '2013-01-14',
               '2013-01-15', '2013-01-16', 
               ...
               '2014-01-20', '2014-01-21', '2014-01-22', '2014-01-23',
               '2014-01-24', '2014-01-27', '2014-01-28', '2014-01-29',
               '2014-01-30', '2014-01-31'],
              dtype='datetime64[ns]', length=282, freq=None, tz='UTC')
2013-01-03 00:00:00+00:00      0
2013-01-04 00:00:00+00:00      1
2013-01-07 00:00:00+00:00      2
2013-01-08 00:00:00+00:00      3
2013-01-09 00:00:00+00:00      4
2013-01-10 00:00:00+00:00      5
2013-01-11 00:00:00+00:00      6
2013-01-14 00:00:00+00:00      7

最佳答案

您可以使用pd.DataFrame来重新构建所需的DataFrame。

import numpy as np
import pandas as pd

df = pd.DataFrame(index=pd.date_range('2009-1-1', periods=4))
df['Datetime'] = df.index
df.reset_index(inplace=True, drop=True)
df['id'] = df.index
df.index = df['Datetime']
df.drop('Datetime', axis=1, inplace=True)

相当于

df = pd.DataFrame(index=pd.date_range('2009-1-1', periods=4))
df = pd.DataFrame({'id': np.arange(len(df))}, index=df.index)
#             id
# 2009-01-01   0
# 2009-01-02   1
# 2009-01-03   2
# 2009-01-04   3

或者,如 A L points out ,你可以简单地使用

df['id'] = np.arange(len(df))

关于python - 有没有更好的方法来索引数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37355592/

相关文章:

Python - Pandas,将长列拆分为多列

python - 如何从终端更新 Scrapy?

python - 在 python 中使用 Beautiful Soup 解析 html

javascript - 在 js 或 jquery 中轻松创建数组,就像在 python 中一样

python-3.x - 根据多个条件按列名过滤数据框

python - 重新排序 Pandas 数据框中的某些列

python - 从列中删除不在范围内的日期

python - 如何将对应于 'n' 的值列表排序到按 'n' 排序的大表中

按位置重命名数据框列

python - 如何保护自己免受 gzip 或 bzip2 炸弹的伤害?