[英]Iterate through multiple columns in a Panda dataframe and find count unique values
[英]Grouping based on unique values of multiple panda columns
我有以下数据框(有数千行,这只是一个示例):
cluster_id bin_time trial_time spikes
1 0 0.5 1
2 5 0.7 0
6 0 0.5 5
3 5 0.7 0
2 5 0.5 1
8. 0. 0.7. 0
前三列有一些重复的值。 我想对峰值进行分组(最后一列),以便对于每个唯一的 trial_time 和 bin_time 的唯一值,我得到峰值的总和。 具有不同 cluster_id 的尖峰应该只是根据它们所属的试验和 bin_time 组合在一起(合计起来,这个维度可以消失)。
最后,我试图获得一个矩阵,该矩阵在 Y 轴上具有唯一的 trial_time 坐标,在 X 轴上具有唯一的 bin_time 坐标,并且每个条目都是尖峰的总和(所以我不关心基于 'cluster_id ')。
这是我尝试过的:
new_df = groupby('trial_time')['spikes']apply(lambda x: list(x))
但这仍然给我每个 trial_time 太多基于 cluster_id 的重复值......
非常感谢任何帮助! 我很困。
对于我给出的小示例数据,我想要一个 2D np 数组的输出:
trial 0.5, bin time 0 --> count of total 1+5=6 spikes
trial 0.5, bin time 5 --> count of total 1 spike
trial 0.7, bin time 0 --> count of 0 spikes
trial 0.7, bin time 5 --> count of 0+0 = 0
所以理想情况下,一个只有尖峰数的二维数组。
按两列分组并通过求和聚合。 分组时不要使用第一列,因为您不关心它。
qf = df.iloc[:,1:].groupby(['bin_time','trial_time']).agg(sum)
#qf = df.loc[:,['bin_time','trial_time','spikes']].groupby(['trial_time','bin_time']).agg(sum)
trial_time bin_time
0.5 0.0 6
5.0 1
0.7 5.0 0
0.7. 0.0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.