Home > Net >  How to make Date a column in dataframe
How to make Date a column in dataframe

Time:12-14

I have the below dataframe and i am trying to display how many rides per day.
But i can see only 1 column "near_penn" is considered as a column but "Date" is not.

c = df[['start day','near_penn','Date']]

c=c.loc[c['near_penn']==1]

pre_pandemic_df_new=pd.DataFrame()
pre_pandemic_df_new=c.groupby('Date').agg({'near_penn':'sum'})
print(pre_pandemic_df_new)
print(pre_pandemic_df_new.columns)

enter image description here

Why doesn't it consider "Date" as a column?
How can i make Date as a column of "pre_pandemic_df_new"?

CodePudding user response:

Feel you can use to to_datetime method.

import pandas as pd

pre_pandemic_df_new["Date"]= pd.to_datetime(pre_pandemic_df_new["Date"])

Hope this works

CodePudding user response:

Why doesn't it consider "Date" as a column?

Because the date is an index for your Dataframe.

How can I make Date as a column of "pre_pandemic_df_new"?

you can try this:

pre_pandemic_df_new.reset_index(level=['Date'])

CodePudding user response:

df[['Date','near_penn']] = df[['Date_new','near_penn_new']]

Once you created your dataframe you can try this to add new columns to the end of the dataframe to test if it works before you make adjustments

OR

You can check for a value for the first row corresponding to the first "date" row.

These are the first things that came to my mind hope it helps

  • Related