【问题标题】:How to get the sum of values from one column with the conditional of another column如何在另一列的条件下从一列中获取值的总和
【发布时间】:2022-01-19 21:23:48
【问题描述】:

对于下图所示的示例数据:

如果条件 customer_id 相同,我如何获得一列中出现的相似项目的数量?

ls=[]
for i in data['customer_id']:
    sum=0
    for j in data['category']:    
        if i == j[0]:
            sum+=j[1]
    ls.append(sum)

简而言之:

[food and fruit, vegetable, bakery and bread, cookies snacks or candies, seafoods and meat] 
customer_id[0] = [4,9,5,1,0]

【问题讨论】:

  • 欢迎来到 SO!请不要将数据或代码添加为图像。而是使用纯文本或更好的方法,提供一段构建数据框的代码。这将更有可能有人能够快速帮助您。

标签: python pandas list dataframe for-loop


【解决方案1】:

假设您的数据已加载到 pandas 数据框中,您可以使用:

# Sample data
labels = ["a", "b", "c", "a, b, c", "b, c"]
df = pd.DataFrame({
    "customer_id": [0, 1]*10,
    "category": [labels[np.random.randint(0,len(labels ))] for i in range(20)]
})

# Count per group and pivot the rows to columns
df.groupby(['customer_id', 'category']).size().reset_index().pivot_table(
    0, ['customer_id'], 'category').fillna(0).rename_axis(
        None, axis=1).reset_index()

输出:

    customer_id   a      a, b, c      b      b, c      c
0   0           2.0          1.0    1.0       5.0    1.0
1   1           2.0          0.0    4.0       1.0    3.0

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多