Python - Pandas - DataFrame 减少行数
我有一个像这样的数据表:
ind col1 col2
1 12 string1 ...
2 23 string2 ...
3 34 string1 ...
4 13 string2 ...
5 17 string3 ...
... ... ... ...
我想把这个数据表压缩一下,让第二列(col2)里的值变得唯一。在第一列(col1)和其他所有数字列中,我想把那些第二列相同的值的中位数放进去。
我知道可以通过提取 df[df["col2"] == "stringN"] 来计算中位数,然后再建立一个新的数据表,但有没有更优雅、更符合 Python 风格的方法来做到这一点呢?
1 个回答
5
你可以使用 groupby 来根据 col2
的值把行分组,然后使用 .median()
来计算中位数:
>>> df
ind col1 col2
0 1 12 string1
1 2 23 string2
2 3 34 string1
3 4 13 string2
4 5 17 string3
>>> df.groupby("col2")
<pandas.core.groupby.DataFrameGroupBy object at 0x9f41b8c>
>>> df.groupby("col2").median()
ind col1
col2
string1 2 23
string2 3 18
string3 5 17
>>> df.groupby("col2").median().reset_index()
col2 ind col1
0 string1 2 23
1 string2 3 18
2 string3 5 17
注意,结果中也包含了 ind
值的中位数。你还可以看看 .mean()
(平均值)、.min()
(最小值)、.max()
(最大值),或者如果你想的话,也可以自己写一个函数来实现。