我有以下df
:
df = pd.DataFrame({
"value": [10,20,30,40,50,60,70,80,90,100]
})
我需要计算每 n
行的中值。理想情况下,编写一个可以将 pd.Series
和 n
作为参数传递的函数。因此,如果n=2
,我的函数应该返回:
median
15
35
55
75
95
如果n=3
,那么它应该返回:
median
20
50
80
100
在此示例中,当 n=3
时,最后返回的值为 100
,但是在我的真实数据集中,我有一个 df
数千行,我想将 n
设置为 10
或 20
。因此,作为最后一个中值,它应该返回 n%10
的中值。
我在下面添加了一个类似的函数,仅供引用 link ,它以我解释的相同方式计算平均值,但我需要调整它来计算中位数。
def find_mean(col, rows):
"""
col: pd.Series
rows: number of rows
"""
if isinstance(col, pd.Series):
col = col.to_numpy()
mod = col.shape[0] % rows
if mod != 0:
exclude = col[-mod:]
keep = col[: len(col) - mod]
out = keep.reshape((int(keep.shape[0]/rows), int(rows))).mean(1)
out = np.hstack((out, exclude.mean()))
else:
out = col.reshape((int(col.shape[0]/rows), int(rows))).mean(1)
return out
最佳答案
您可以使用groupby
:
N = 3
df.groupby(np.arange(len(df))//N)['value'].median()
输出:
0 20
1 50
2 80
3 100
Name: value, dtype: int64
关于python - 计算 pandas df 中每一行的中值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75663401/