【问题标题】:Using a list of columns with boolean indexing使用带有布尔索引的列列表
【发布时间】:2022-06-10 20:12:19
【问题描述】:

在上一个问题中,我能够使用布尔索引完成求和值。

由于我有数十列,我将这些列存储在一个列表中以在 for 循环中使用,这样我就可以索引排名 0-5 的相关列值。

根据我的分析,我发现Disloyal30-40 岁的客户在 X 公司是 neutral or dissatisfied。“中性或不满意”意味着他们将服务和产品评为 0-2 分(满分为 5 分)。

我应该从 for 循环中插入 column 在最后一个块的哪个位置,有没有更好的方法来编写它?

示例数据:

Customer Type    Age    Satisfaction    Design   Food    Wi-Fi    Service    Distance
     Disloyal     28   Not Satisfied         0      1        2          2        13.5
        Loyal     30       Satisfied         5      3        5          4        34.2
     Disloyal     36   Not Satisfied         2      0        2          4        55.8

代码

ranked_cols = ['Customer Type', 'Age', 'Satisfaction', 'Design', 'Food', 'Wi-Fi', 'Service', 'Distance']

for column in df[ranked_cols]:
    columnSeriesObj = df[column]

sub = df[
(df["Customer Type"] == "Disloyal")
& (df["Satisfaction"] == "Not Satisfied")
& df["Age"].between(30, 40)
]

sub[(sub[ranked_cols] <= 2)].shape[0]

(sub.melt(value_vars=[c for c in sub.columns if c.startswith(column)])
.groupby("variable")
.value_counts()
.to_frame()
.reset_index()
.rename(columns={0: "count"}))

【问题讨论】:

    标签: python


    【解决方案1】:

    试试这个:

    # Choose the cols you want to see the ratings for
    ranked_cols = [
        "Design",
        "Food",
        "Wi-Fi",
        "Service",
    ]
    
    # Select the relevant customers
    sub = df[
        (df["Customer Type"] == "Disloyal")
        & (df["Satisfaction"] == "Not Satisfied")
        & df["Age"].between(30, 40)
    ]
    
    (
        sub.melt(value_vars=ranked_cols)
        .groupby("variable")
        .value_counts()
        .to_frame()
        .reset_index()
        .rename(columns={"value": "rating", 0: "count"})
    )
    

    这将输出一个 DataFrame,其中包含所有 ranked_cols 类别及其各自的 rating 以及该评分的次数 (count):

        variable  rating  count
    0   Design    2       1
    1   Food      0       1 
    2   Service   4       1
    3   Wi-Fi     2       1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 2014-02-03
      • 2019-02-09
      相关资源
      最近更新 更多