Python Pandas DataFrame减少行数

2024-04-19 03:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据框:

ind  col1 col2
1    12   string1  ...
2    23   string2 ...
3    34   string1 ...
4    13   string2 ...
5    17   string3 ...
...  ...  ...     ...

我想折叠数据帧,以便col2是唯一的。在col1(和所有其他的数值列)中,我想把col2相等的所有值的中值放进去。

我知道我可以提取df[df[“col2”]=“stringN”]、计算媒体并构建一个新的数据帧,但有没有更优雅/pythonic的方法来做到这一点?


Tags: 数据方法dfpythonic媒体col2col1数值
1条回答
网友
1楼 · 发布于 2024-04-19 03:34:07

可以使用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(),如果您愿意,也可以自己滚动。

相关问题 更多 >