peu*_*ing 4 python dataframe pandas
我有一个像这样的数据帧:
ind col1 col2
1 12 string1 ...
2 23 string2 ...
3 34 string1 ...
4 13 string2 ...
5 17 string3 ...
... ... ... ...
Run Code Online (Sandbox Code Playgroud)
我想折叠 DataFrame 以便 col2 是唯一的。在 col1(以及所有其他数字列)中,我想放置 col2 相等的所有值的中位数。
我知道我可以提取 df[df["col2"] == "stringN"],计算中位数并构建一个新的 DataFrame,但是有没有更优雅/pythonic 的方法来做到这一点?
您可以使用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
Run Code Online (Sandbox Code Playgroud)
请注意,结果也具有值的中位数ind。另请参阅.mean()、.min()、.max(),或者如果您愿意,也可以推出自己的产品。
| 归档时间: |
|
| 查看次数: |
7276 次 |
| 最近记录: |