我正在尝试迭代创建数据帧的子集。一个玩具示例:
In:
A B participant
0 1 3 1
1 2 4 1
2 5 8 2
3 4 9 2
4 3 7 3
(条件语句感谢下面的评论者)
for p in df:
subset = df[df['participant'] == p].loc[: , 'A']
期望的结果是:
A participant
0 1 1
1 2 1
A participant
0 5 2
1 4 2
等等
但是 for 循环按行生成子集,而不是按参与者生成子集。如何获取每个参与者的子集?
最初的尝试:
for p in df:
p.pressure = df[(:, 'pressure') & (df['participant'] == p)]
最佳答案
这是一种方法。
首先获取参与者的唯一值:
participants = df['participant'].unique()
#array([1, 2, 3])
现在为每个参与者创建一个数据框。在此示例中,我将每个 DF 存储在一个字典中,并以参与者编号作为键控。
output_dfs = {p: df[df['participant'] == p] for p in participants}
for p in output_dfs:
print("Participant = %s"%p)
print(output_dfs[p])
print("")
打印内容:
Participant = 1
A B participant
0 1 3 1
1 2 4 1
Participant = 2
A B participant
2 5 8 2
3 4 9 2
Participant = 3
A B participant
4 3 7 3
关于python - For 循环子集化的 pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49242992/