【问题标题】:Find minimum respondent's age of each question查找每个问题的最小受访者年龄
【发布时间】:2023-01-09 14:46:49
【问题描述】:

给 df 一个包含问卷答案的数据框

import pandas as pd
import numpy as np
df = pd.DataFrame(data=[[10,np.nan,'Answer 1','Answer 2'],
                        [40,"Answer 4","Answer 3",'Answer 2'],
                        [20,"Answer 2", np.nan,'Answer 1']], 
                        columns = ['Age','Question 1','Question 2', 'Question 3'])


df

    Age Question 1  Question 2  Question 3
0   10  NaN         Answer 1    Answer 2
1   40  Answer 4    Answer 3    Answer 2
2   20  Answer 2    NaN         Answer 1

我想为每个问题创建第二个数据框,其中包含受访者的最低年龄

免责声明:前面的代码非常丑陋!

df2 = pd.DataFrame(data=df.columns.tolist(),columns=["Questions"])
for col in df2["Questions"]:
    if col != "Age":
        df2.loc[df2["Questions"]==col,"min_age"] = df.loc[:,["Age",col]].dropna()["Age"].min()

df2

    Question    min_age
0   Age         NaN
1   Question 1  20.0
2   Question 2  10.0
3   Question 3  10.0

【问题讨论】:

  • 那么,问题是什么?你已经得到了答案。
  • df.sort_values('Age').set_index('Age').isna().idxmin()

标签: python pandas


【解决方案1】:

您可以使用 Age 作为有序索引找到第一个非 NAN 值的索引:

df2 = df.set_index('Age').sort_index().notna()
out = df2.idxmax().where(df2.any())

输出:

Question 1    20
Question 2    10
Question 3    10
dtype: int64

【讨论】:

    【解决方案2】:

    另一种可能的解决方案,基于pandas.meltpandas.pivot_table

    (df.melt(id_vars='Age').dropna()
     .pivot_table(index='variable', values='Age', aggfunc='min')
     .reset_index(names='Question'))
    

    输出:

         Question  Age
    0  Question 1   20
    1  Question 2   10
    2  Question 3   10
    

    【讨论】:

      【解决方案3】:

      这可能是另一种解决方案:

      (pd.melt(df, id_vars='Age', value_vars=df.columns[1:])
       .dropna()
       .groupby('variable')
       .agg({'Age' : np.min}))
      
                  Age
      variable       
      Question 1   20
      Question 2   10
      Question 3   10
      

      【讨论】:

        【解决方案4】:
            df.set_index('Age').stack().reset_index().groupby('level_1').Age.min()
            
        level_1
        Question 1    20
        Question 2    10
        Question 3    10
        Name: Age, dtype: int64
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-29
          • 1970-01-01
          • 2021-12-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-02
          相关资源
          最近更新 更多