如何根据条件对 Python 中的数据帧进行下采样
How to down sample a dataframe in Python based on condition
我是新来的所以不知道如何使用这个网站。
我有 37404 个 ICU 患者 的时间序列数据。每个病人有多行。我想 向下采样 我的数据框和 select 仅 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 列上使用一些条件,但我很困惑。
感谢您的帮助。
使用numpy.random.choice
for random P_ID
and filter in Series.isin
with boolean indexing
:
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')
我是新来的所以不知道如何使用这个网站。
我有 37404 个 ICU 患者 的时间序列数据。每个病人有多行。我想 向下采样 我的数据框和 select 仅 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 列上使用一些条件,但我很困惑。
感谢您的帮助。
使用numpy.random.choice
for random P_ID
and filter in Series.isin
with boolean indexing
:
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')