简体   繁体   English

找到差异。 groupby 在 pandas 中的最大值和最小值?

[英]find diff. of max and min in pandas by groupby?

If I have date frame as below of 3 year of rainfall from 2015-2017 for three stations, could you help me how find diff.如果我有以下三个站点从 2015 年到 2017 年 3 年降雨的日期框架,你能帮我找到差异吗? between maximum and minimum for every station?每个站的最大值和最小值之间? 在此处输入图像描述

Code below uses groupby() with axis=1 to get min() and max() for each row.下面的代码使用groupby()axis=1来获取每行的min()max() The restuls are then combined using .merge() :然后使用.merge()组合结果:

Option-1 :选项 1

Using the non-repeating names in the column 'Name'在“名称”列中使用不重复的名称

# Import libraries
import pandas as pd

# Create DataFrame
df = pd.DataFrame({
    'Name':['Baghdad', 'Basra', 'Mousl'],
    'R2015':[300,190,350],
    'R2016':[240,180,540],
    'R2017':[290,160,490]
})

# Convert column to index
df = df.set_index('Name')

# Get min and max
df_min = df.groupby(['min']*df.shape[1],axis=1).min()
df_max = df.groupby(['max']*df.shape[1],axis=1).max()

# Combine
df_min_max = df_min.merge(df_max, on='Name')

# Get difference
df_min_max['diff'] = abs(df_min_max['min'] - df_min_max['max'])

# Output
df_min_max

在此处输入图像描述

Option-2 :选项 2

If the DataFrame had names in column Name repeating, then below should work.如果 DataFrame 的名称在列Name重复,那么下面应该可以工作。 Here, added Baghdad as an additional repeating row.在这里,添加了Baghdad作为额外的重复行。 Here, groupby() of groupby() is used.这里使用groupby()groupby()

# Import libraries
import pandas as pd

# Create DataFrame
df = pd.DataFrame({
    'Name':['Baghdad', 'Basra', 'Mousl','Baghdad'],
    'R2015':[300,190,350,780],
    'R2016':[240,180,540,455],
    'R2017':[290,160,490,23]
})

# Convert column to index
df = df.set_index('Name')

# Get min and max
df_min = df.groupby(['min']*df.shape[1],axis=1).min().groupby(['Name']).min()
df_max = df.groupby(['max']*df.shape[1],axis=1).max().groupby(['Name']).max()

# Combine
df_min_max = df_min.merge(df_max, on='Name')

# Get difference
df_min_max['diff'] = abs(df_min_max['min'] - df_min_max['max'])

# Output
df_min_max

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM