Python Pandas - 日期列到列索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15752422/
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
Python Pandas - Date Column to Column index
提问by MrHopko
I have a table of data imported from a CSV file into a DataFrame.
我有一个从 CSV 文件导入到 DataFrame 的数据表。
The data contains around 10 categorical fields, 1 month column (in date time format) and the rest are data series.
数据包含大约 10 个分类字段、1 个月列(日期时间格式),其余为数据系列。
How do I convert the date column into an index across the the column axis?
如何将日期列转换为跨列轴的索引?
回答by Andy Hayden
You can use set_index:
您可以使用set_index:
df.set_index('month')
For example:
例如:
In [1]: df = pd.DataFrame([[1, datetime(2011,1,1)], [2, datetime(2011,1,2)]], columns=['a', 'b'])
In [2]: df
Out[2]:
a b
0 1 2011-01-01 00:00:00
1 2 2011-01-02 00:00:00
In [3]: df.set_index('b')
Out[3]:
a
b
2011-01-01 1
2011-01-02 2
回答by aysebilgegunduz
I had similar problem I've just solved by reset_index. But you can use either set_index or reset_index:
我刚刚通过 reset_index 解决了类似的问题。但是您可以使用 set_index 或 reset_index:
ind_df=df.set_index(['A', 'B'])
ind_df=df.set_index(['A', 'B'])
df.reset_index(level=0, inplace=True)
回答by Shankar ARUL - jupyterdata.com
If you don't know the name of the date column ahead of time and need to set the index automatically based on the time series column in the data
如果您提前不知道日期列的名称,需要根据数据中的时间序列列自动设置索引
df.set_index((df.select_dtypes(include=[np.datetime64]).columns).tolist())

