减少python中数据框的尺寸

时间:2018-10-23 20:53:01

标签: python pandas numpy group-by

我有数据框,包含三列。我想缩小数据框的尺寸。

  data = [[1, 876, 0.98],[1, 888, 0.58],[1, 976, 0.48],[1, 648, 0.98],[2, 765, 0.28], [2, 986, 0.28], [2, 765, 1.0], [2, 876, 0.45]]
    sample = pd.DataFrame(data, columns=['col1','col2', 'col3'])
   col1  col2  col3
0     1   876  0.98
1     1   888  0.58
2     1   976  0.48
3     1   648  0.98
4     2   765  0.28
5     2   986  0.28
6     2   765  1.00
7     2   876  0.45

我希望根据条件将以下内容作为所需的输出: 1.对于col1中的每个值,应该有一行,而col 4应该是元组列表(col2,col3) 2. col4应该仅基于col3中的值具有前两个元组。例如在示例数据帧中,col2 765中发生了两次,最终数据帧应采用col3中具有最高值而第二高的数据帧

data = [[1, [(876, 0.98),(648, 0.98)]],[2, [(876, 0.45), (765, 1.0)]]]
desired_output = pd.DataFrame(data, columns=['col1', 'col2'])

   col1                        col4
0     1  [(876, 0.98), (648, 0.98)]
1     2   [(876, 0.45), (765, 1.0)]

我想存储在元组列表中,以便将其用于其他目的。这只是解决更大问题的一部分。

1 个答案:

答案 0 :(得分:4)

FWIW

sample = sample.sort_values(['col1', 'col3'], ascending=[True, False])
sample.groupby('col1')[['col2', 'col3']].apply(
    lambda d: [*d.head(2).itertuples(index=False)]
).reset_index(name='col4')

   col1                        col4
0     1  [(876, 0.98), (648, 0.98)]
1     2   [(765, 1.0), (876, 0.45)]

那些将被命名为元组。您可以使用name=None

避免这种情况
sample = sample.sort_values(['col1', 'col3'], ascending=[True, False])
sample.groupby('col1')[['col2', 'col3']].apply(
    lambda d: [*d.head(2).itertuples(index=False, name=None)]
).reset_index(name='col4')