【问题标题】:where statements with groupby in python dataframes在 python 数据框中使用 groupby 的 where 语句
【发布时间】:2017-06-14 10:33:04
【问题描述】:
train[['Pclass', 'Age']].groupby(['Pclass'], as_index=False).median().sort_values(by='Pclass', ascending=True)

这是我进行分组、查找汇总统计数据并根据列(在本例中为“Pclass”)对其进行排序的地方。

如何同时使用 where 子句?我想输入的 where 子句将执行类似于 train[train.Survived==1]

对如何实现这一点有任何想法吗?我正在使用经典的“泰坦尼克号”数据集。

【问题讨论】:

    标签: python python-3.x pandas group-by where


    【解决方案1】:

    train[['Pclass', 'Age']]改为

    train.loc[train['Survived'] == 1, ['Pclass', 'Age']]
    

    例如,

    import pandas as pd
    import seaborn as sns
    train = sns.load_dataset("titanic")
    
    print(train.loc[train['survived'] == 1, ['pclass', 'age']]
               .groupby(['pclass'], as_index=False)
               .median()
               .sort_values(by='pclass', ascending=True))
    

    打印

       pclass   age
    0       1  35.0
    1       2  28.0
    2       3  22.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      相关资源
      最近更新 更多