Grouper and axis must be same length in Python

社会主义新天地 提交于 2019-12-11 05:09:16

问题


I am a beginner of Python, and I study a textbook to learn the Pandas module. I have a dataframe called Berri_bike, and it is from the following code:

  bike_df=pd.read_csv(os.path.join(path,'comptagevelo2012.csv'),parse_dates=['Date'],\
                          encoding='latin1',dayfirst=True,index_col='Date')



  Berri_bike=bike_df['Berri1'].copy() # get only the column='Berri1'

  Berri_bike['Weekday']=Berri_bike.index.weekday

  weekday_counts = Berri_bike.groupby('Weekday').aggregate(sum)
  weekday_counts

I have 3 columns in my Berri_bilk , a data index- from 1/1/2012 to 12/31/2012, and value column with numbers for each data, and a weekday column I assigned to it. But when I want to group by the values, I got the error: ValueError: Grouper and axis must be same length, I am not sure what this mean, what I want to do is very simple, like in SQL, sum(value) grouped weekday... can anyone please let me know what happended here?


回答1:


You copy your column into a pandas series instead of a new dataframe, hence the following operations behave differently. You can see this if you print out Berri_bike because it doesn't show the column name.
Instead, you should copy the column into a new dataframe:

import pandas as pd
df = pd.DataFrame(np.random.randint(0, 30, size = (70, 2)),
                  columns = ["A", "B"],
                  index = pd.date_range("20180101", periods = 70))

Berri_bike = df[["A"]]

Berri_bike['Weekday'] = Berri_bike.index.weekday

weekday_counts = Berri_bike.groupby("Weekday").sum()
print(weekday_counts)
#sample output
          A
Weekday    
0        148
1        101
2        127
3        139
4        163
5         74
6        135


来源:https://stackoverflow.com/questions/50884704/grouper-and-axis-must-be-same-length-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!