Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pd.DataFrame question
#1
I hope you are all having a good. Why does the following program cause Python to crash (I'm using the Jupyter notebook):

df2=pd.DataFrame(data=df,index=df['Day of Week'],columns=df['Hour'])

df is a DataFrame already and I want it to have an index of the day of the week variable and columns for the hour variable.
Reply
#2
You should check documentation forĀ pandas dataframe. columns parameter accepts list of column names, so you are trying to create dataframe with colums named as values in df.Hour column (with width given by lenght of your original dataframe).

If you just want to use existing column as an index, just use:
df2 = df.set_index('Day of Week', drop=True)[['Hour']]
that will set index values from Day of Week column and deletes Day of Week column. If your original dataframe contains only Hour and Day of Week columns, selecting with [['Hour']] is obsolete.
Reply
#3
(Mar-30-2017, 08:17 PM)zivoni Wrote: You should check documentation for pandas dataframe. columns parameter accepts list of column names, so you are trying to create dataframe with colums named as values in df.Hour column (with width given by lenght of your original dataframe). If you just want to use existing column as an index, just use:
 df2 = df.set_index('Day of Week', drop=True)[['Hour']] 
that will set index values from Day of Week column and deletes Day of Week column. If your original dataframe contains only Hour and Day of Week columns, selecting with [['Hour']] is obsolete.


Thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python & Dataframe basic question georgialtr 0 3,833 Apr-06-2020, 03:59 PM
Last Post: georgialtr
  Simple pandas dataframe question popohoma 1 3,493 Jan-03-2019, 05:00 PM
Last Post: ashlardev
  Newbie question to return only the index of a dataframe zydjohn 0 2,521 Jan-22-2018, 03:40 PM
Last Post: zydjohn
  Question for dataframe to replace INF value zydjohn 0 5,116 Jan-15-2018, 10:00 PM
Last Post: zydjohn
  very simple dataframe question really_this_dumb 0 2,156 Jan-02-2018, 11:30 AM
Last Post: really_this_dumb
  Newbie question: how to generate dataframe and use multiple regression zydjohn 0 2,252 Dec-10-2017, 09:49 AM
Last Post: zydjohn

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020