Reputation: 5115
The docs of pandas.Index.get_loc
states it is used to "Get integer location".
Index.get_loc(self, key, method=None, tolerance=None)[source]
Get integer location, slice or boolean mask for requested label.
I could apply it to a normal column in a dataframe but am not sure how to do it on an index column of dataframe df
. Would it be correct to change it to time_index=df2.columns.get_loc(T_index.index)
? Thanks
Edit:
Let's say perviously for dataframe df
, Timestamp
is a normal column, and I used time_index=df2.columns.get_loc("Timestamp")
to get the integer location. If Timestamp
is converted into index format, how should the code change accordingly?
Timestamp Temperature
2020-02-06 08:23:04 18.5 0.0
2020-02-06 08:23:05 18.5 0.0
2020-02-06 08:23:06 18.5 0.0
2020-02-06 08:23:07 18.5 0.0
2020-02-06 08:23:08 18.5 0.0
...
Thanks
Upvotes: 1
Views: 1608
Reputation: 153460
Use df.columns.get_loc()
:
Given df,
df = pd.DataFrame(np.random.randint(0,100,(5,5)), index=[*'abcde'], columns=[*'VWXYZ'])
| | V | W | X | Y | Z |
|:---|----:|----:|----:|----:|----:|
| a | 27 | 50 | 12 | 96 | 47 |
| b | 63 | 93 | 27 | 37 | 7 |
| c | 77 | 29 | 57 | 85 | 65 |
| d | 84 | 6 | 98 | 32 | 85 |
| e | 38 | 8 | 69 | 66 | 15 |
df.columns.get_loc('X')
Output:
2
The integer location of the 'X' column is 2.
Note:
type(df.index)
pandas.core.indexes.base.Index
and
type(df.columns)
pandas.core.indexes.base.Index
Both the index and column headers of a dataframe are pd.Index.
Upvotes: 3