I want to return the index of my DataFrame as a string. I am using this commandp_h = peak_hour_df.index.astype(str).str.zfill(4)
It is not working, I am getting this result: Index(['1645'], dtype='object', name
I need it to return the string '1645'
How do I accomplish this?
In short:
do p_h = list(peak_hour_df.index.astype(str).str.zfill(4))
. This will return a list and then you can index it.
In more detail:
When you do peak_hour_df.index.astype(str)
, as you see, the dtype
is already an object
(string), so that job is done. Note this is the type of the contents; not of the object itself. Also I am removing .str.zfill(4)
as this is additional and does not change the nature of the problem or the retuning type.
Then the type of the whole objet you are returning is pandas.core.indexes.base.Index
. You can check this like so: type(peak_hour_df.index.astype(str))
. If you want to return a single value from it in type str
(e.g. the first value), then you can either index the pandas object directly like so:
peak_hour_df.index.astype(str)[0]
or (as I show above) you can covert to list and then index that list (for some reason, most people find it more intuitive):
peak_hour_df.index.astype(str).to_list()[0]
list(peak_hour_df.index.astype(str))[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With