【问题标题】:How to get percentage count based on multiple columns in pandas dataframe?如何根据熊猫数据框中的多列获取百分比计数?
【发布时间】:2017-12-18 11:11:07
【问题描述】:

我在一个数据框中有 20 列。 我在这里列出了其中的 4 个作为示例:

is_guarantee:0 或 1
酒店星级:0、1、2、3、4、5
订单状态:40、60、80
旅程(标签):0、1、2

    is_guarantee  hotel_star  order_status  journey
0              0           5            60        0
1              1           5            60        0
2              1           5            60        0
3              0           5            60        1
4              0           4            40        0
5              0           4            40        1
6              0           4            40        1
7              0           3            60        0
8              0           2            60        0
9              1           5            60        0
10             0           2            60        0
11             0           2            60        0

Click to View Image

但系统需要输入如下格式的出现矩阵才能起作用:

Click to View Image

任何身体都可以帮忙吗?

df1 = pd.DataFrame(index=range(0,20))
df1['is_guarantee'] = np.random.choice([0,1], df1.shape[0])
df1['hotel_star'] = np.random.choice([0,1,2,3,4,5], df1.shape[0])
df1['order_status'] = np.random.choice([40,60,80], df1.shape[0])
df1['journey '] = np.random.choice([0,1,2], df1.shape[0])

【问题讨论】:

  • 我希望看到您在问题中编辑的数据为 text。我无法将图片复制并粘贴到终端中,也不想从头开始输入。请让每个人的生活更轻松,将您的数据和预期输出作为文本发布在您的问题中。没有数据 = 没有帮助。
  • @jezrael... 没有人是来迫害你的,尤其是我。我告诉过你,我尊重你的知识。不幸的是,有时您会做一些可能被认为对网站不健康的事情。那不是我的意见。无论如何,我已经重新提出了这个问题,享受吧。
  • 我还应该提到,通过回答问题来鼓励低质量问题与我之前提到的不健康习惯相同。
  • @cᴏʟᴅsᴘᴇᴇᴅ - 我同意你的看法。如果只是有趣,我会回答这种问题,否则不会。
  • @jezrael,好的,只要你明白,我没有怨言。 :-)

标签: python pandas numpy matrix


【解决方案1】:

我认为你需要:

  • melt 重塑并通过groupbysize 获得计数,由unstack 重塑
  • 然后除以每行的总和并将MultiIndex 连接到index

df = (df.melt('journey')
       .astype(str)
       .groupby(['variable', 'journey','value'])
       .size()
       .unstack(1, fill_value=0))

df = (df.div(df.sum(1), axis=0)
        .mul(100)
        .add_prefix('journey_')
        .set_index(df.index.map(' = '.join))
        .rename_axis(None, 1))

print (df)

                    journey_0  journey_1
hotel_star = 2     100.000000   0.000000
hotel_star = 3     100.000000   0.000000
hotel_star = 4      33.333333  66.666667
hotel_star = 5      80.000000  20.000000
is_guarantee = 0    66.666667  33.333333
is_guarantee = 1   100.000000   0.000000
order_status = 40   33.333333  66.666667
order_status = 60   88.888889  11.111111

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 2020-04-17
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2018-12-23
    相关资源
    最近更新 更多