hupili / python-for-data-and-media-communication-gitbook

An open source book on Python tailed for communication students with zero background
115 stars 62 forks source link

How to merge grouped data #149

Open iiiJenny opened 5 years ago

iiiJenny commented 5 years ago

Troubleshooting

合并grouped data后,无法用pandas引用某一列数据

Describe your question

初始数据如下图: image 目标:我想根据pic(10个)和pos_x,pos_y(方位:左中右)进行分类,算出每个组合x与y的最大最小值。

  1. groupby数据:根据上述三个变量合并形成10pic大分组,1033小分类,每类均有x,y的min和max。
  2. 但是,columns的是错位的(pic和pos_x,pos_y偏下); image
  3. 无法引用pic等;引用lable等出现的是组合形式(series.Series) image image image

如何像平时引用pandas每一列一样引用数据呢?如:df['x']-->出来一列数据

@hupili could you please help me? thax~

iiiJenny commented 5 years ago

以下两列代码不知道哪个更合适,目的是求出x和y在聚合分类下(pic,pos_x,pos_y)对应的的最大、最小4个值【即每个小分组下,显示x_min, x_max, y_min, y_max四列,以及每个小分组的其他信息:lable等】:

grouped1 = df_data.groupby(['pic','pos_x','pos_y']).min()
grouped2 = df_data.groupby(['pic','pos_x','pos_y']).max()

data = pd.merge(grouped1,grouped2, on=('pic','pos_x','pos_y','lable','type','xpos','ypos','pic_width','pic_height'))
type(data) # pandas.core.frame.DataFrame
data
grouped = df_data.groupby(['pic','pos_x','pos_y','lable','type','xpos','ypos','pic_width','pic_height'])[['x','y']]

df1 = grouped.min()
df2 = grouped.max()

df_cleaning = pd.merge(df1,df2,on=('pic','pos_x', 'pos_y','lable','type','xpos','ypos','pic_width','pic_height'))
df_cleaning

数据: https://github.com/iiiJenny/data/blob/master/data.csv

ConnorLi96 commented 5 years ago

根据你的

目标:我想根据pic(10个)和pos_x,pos_y(方位:左中右)进行分类,算出每个组合x与y的最大最小值。

解决方案:

Step1. 定义一个函数来查询 Series 中是否含有“左中右”等字符串

def has_zuo(t):
return '左' in str(t).lower()

Step2. apply 函数并组成新的 series

df_data['pos_x'] = ['pos_statistic'].apply(has_zuo)
df_data.head()
iiiJenny commented 5 years ago

找到方法了:

data.add_suffix('_Count').reset_index()

image

问题解决,感谢大家~