从一个大数据帧创建较小的数据帧,然后将它们传递给不同的函数

问题描述 投票:0回答:1

我是Python的新手,不知道从哪里开始。我之前发布了类似的问题,但被要求提供更多细节。

假设我有一个数据框,其中包含客户对调查的答复。不同问题有多个问题ID,并且可以基于同一客户对多个问题的回答来复制记录ID。

QuestionID 1 =您的性别是?

QuestionID 2 =您对这项服务的满意度如何? (0-5分制题)

import pandas as pd 

data = {'RecordID':['01', '01', '02', '02', '03', '03', '04', '04'],
        'QuestionID':['1','2','1','2','1','2','1','2'],
        'Response': ['male', '5', 'male', '4', 'female', '1', 'female', '1']}

df = pd.DataFrame(data)

我希望能够创建段,这些段本质上是主数据帧的过滤版本。我的细分为:

# This gives a dataframe with only female responses
female_response = df[(df['Response'] == 'female')]

# This gives a dataframe with only male responses
male_response = df[(df['Response'] == 'male')]

[接下来,我想创建一个函数,该函数将根据每个段的响应进行某种计算。可以说,我要计算的是“前2个盒子的百分比”,这些客户回答了“您对这项服务的满意度如何”问​​题通过选择4或5。公式为:[回答4或5的人数] / [回答的所有人的人数]

def top2(segment):
    calc = df[(df['QuestionID'] == '2')] 
       t2 = ((calc['4'] + calc['5']) / (calc.sum())) * 100
       return top2percent

上面的函数不正确,因为我在运行它时总是出错。

我想要的最后一步是能够将我创建的两个细分分组,一个是男性受访者,另一个是女性受访者,然后将所有这些细分传递给该函数。

我的最终结果应该是一个新的数据框,其中包含类似于以下内容的订单项:

男性= 100%(在2个男性回答中,一个得分为4,其他得分为5)

女性= 0%(在2个女性回答中,没有一个得分为4或5)

我的用例是,我有一个较大的数据框,我想从中创建较小的段(较小的数据框)。然后,我想创建不同的函数来传递所有段,以使每个段完成计算。

有人可以提供详细的解决方案吗?抱歉,这是一个简单的问题。

python pandas
1个回答
0
投票

对于熊猫数据框,您需要对如何使用数据进行不同的思考。

import pandas as pd 

data = {'RecordID':['01', '01', '02', '02', '03', '03', '04', '04'],
        'QuestionID':['1','2','1','2','1','2','1','2'],
        'Response': ['male', '5', 'male', '4', 'female', '1', 'female', '1']}

df = pd.DataFrame(data)

# convert strings to numbers
df['QuestionID'] = pd.to_numeric(df['QuestionID'])

# reshape the dataframe to records flat with questions wided
df_reshaped = df.set_index(['RecordID', 'QuestionID'])['Response'].unstack()

# convert string to number for scores
df_reshaped[2] = pd.to_numeric(df_reshaped[2])

# Use groupby with aggregration to calculate percent per group.
df_result = df_reshaped.groupby(1)[2].agg(lambda x: (x.isin([4,5]).sum()/x.count()) * 100)

# show output
df_result

输出:

1
female      0
male      100
Name: 2, dtype: int64

def get_top_2_percent(df):
    df['QuestionID'] = pd.to_numeric(df['QuestionID'])

    # reshape the dataframe to records flat with questions wided
    df_reshaped = df.set_index(['RecordID', 'QuestionID'])['Response'].unstack()

    # convert string to number for scores
    df_reshaped[2] = pd.to_numeric(df_reshaped[2])

    # Use groupby with aggregration to calculate percent per group. 

    df_result = df_reshaped.groupby(1)[2].agg(lambda x: (x.isin([4, 5]).sum()/x.count()) * 100)
    return df_result
© www.soinside.com 2019 - 2024. All rights reserved.