0

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.

enter image description here

enter image description here

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)
Babeeshka
  • 105
  • 1
  • 4
  • 21
  • This doesn't feel right. Why aren't you using the Datetime as index? – Anton vBR Nov 16 '17 at 18:53
  • I tried, but kept receiving errors. I did manage to set up the DataFrame as needed and I will edit the original post. Ideally you're right, that would be best. – Babeeshka Nov 17 '17 at 00:32

1 Answers1

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
Andrew L
  • 6,618
  • 3
  • 26
  • 30
  • Am I able to index where the columns will be placed? For example, skipping the first two columns, which are coordinates? I am trying to accomplish this `.iloc[:,2:]`, but keep getting errors of length mismatch. – Babeeshka Nov 16 '17 at 18:41
  • It doesn't seem very clean but I used the following answer- https://stackoverflow.com/questions/40427943/how-do-i-change-a-single-index-value-in-pandas-dataframe ... See edits ... You'll want to be absolutely sure the length matches. – Andrew L Nov 16 '17 at 18:47