Pandas - DatetimeIndex as column headings

十年热恋 提交于 2019-12-13 03:37:01

问题


I have a dataframe that is 438x14401. I have a DateTimeIndex that is the same length (width?) as the columns in the dataframe, which are now just labeled 1 - ... I am trying to replace those values with the dates in my DateTimeIndex.

I am trying to substitude column headings 0 - end with the datetimeindex values, which should match in length. I have tried just renaming the columns with the dates and merging them, with no success. Is this at all possible?

stations = stations.iloc[:,2:].rename(columns=v, inplace=True)

回答1:


You can assign your DatetimeIndex directly to stations.columns:

Sample df:

df = pd.DataFrame({'a': [1,2,3], 'b': [9,8,7], 'c': [7,5,1], 'd':[1,3,5]})
df
   a  b  c  d
0  1  9  7  1
1  2  8  5  3
2  3  7  1  5

some_date_range = pd.date_range('2017-01-01', periods=len(df.columns))

df.columns = some_date_range

df
   2017-01-01  2017-01-02  2017-01-03  2017-01-04
0           1           9           7           1
1           2           8           5           3
2           3           7           1           5

Keeping first two column values (referencing How do i change a single index value in pandas dataframe? since Index doesn't support mutable operations):

aslist = df.columns.tolist()
aslist[2:] = pd.date_range('2017-01-01', periods=2)
df.columns = aslist
df
   a  b  2017-01-01 00:00:00  2017-01-02 00:00:00
0  1  9                    7                    1
1  2  8                    5                    3
2  3  7                    1                    5


来源:https://stackoverflow.com/questions/47336863/pandas-datetimeindex-as-column-headings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!