【问题标题】:How to down sample a dataframe in Python based on condition如何根据条件在 Python 中对数据帧进行下采样
【发布时间】:2021-12-26 12:07:00
【问题描述】:

我是新来的,所以不知道如何使用这个网站。

我有 37404 名 ICU 患者的时间序列数据。每个患者有多个行。我想向下采样我的数据框并选择2932 名患者(相应患者 ID 的所有行)。谁能帮我?我的数据如下所示:

HR SBP DBP Sepsis P_ID
92 120 80 0 0
98 115 85 0 0
93 125 75 0 1
95 130 90 0 1
102 120 80 0 1
109 115 75 0 2
94 135 100 0 2
97 100 70 0 3
85 120 80 0 4
88 115 75 0 4
93 125 85 0 4
78 130 90 0 5
115 140 110 0 5
102 120 80 0 5
98 140 110 0 5

我知道我应该在 P_ID 列上使用一些条件,但我很困惑。

感谢您的帮助。

【问题讨论】:

    标签: python pandas dataframe pandas-resample


    【解决方案1】:

    numpy.random.choice 用于随机P_ID 并使用boolean indexing 过滤Series.isin

    df2 = df[df['P_ID'].isin(np.random.choice(df['P_ID'].unique(), size=2932, replace=False))]
    

    替代方案:

    df2 = df[df['P_ID'].isin(df['P_ID'].drop_duplicates().sample(n=2932))]
    

    编辑:对于随机位置使用:

    df1 = df['P_ID'].drop_duplicates().sample(n=2932).to_frame('P_ID')
    
    df2 = df.merge(df1, how='right')
    

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2016-01-10
      • 2022-01-23
      • 2020-10-27
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      相关资源
      最近更新 更多