我需要取 n 行中的最小值并将其添加到数据帧新列中的这 n 行中。
例如:n = 3
Column 1 Column 2
-------------------
5 3
3 3
4 3
7 2
8 2
2 2
5 4
4 4
9 4
8 2
2 2
3 2
5 2
请注意,如果行数不能被 n 整除,则最后的值将合并到最后一组中。因此,在此示例中,数据帧的末尾 n=4。
提前谢谢您!
我不知道有什么直接的方法可以做到这一点,但这是一个工作示例(不优雅,但有效......)。
如果您不担心行数可被 n整除,则可以使用
.groupby()
:
import pandas as pd
d = {'col1': [1, 2,1,5,3,2,5,6,4,1,2] }
df = pd.DataFrame(data=d)
n=3
df['new_col']=df.groupby(df.index // n).transform('min')
产生:
col1 new_col
0 1 1
1 2 1
2 1 1
3 5 2
4 3 2
5 2 2
6 5 4
7 6 4
8 4 4
9 1 1
10 2 1
但是,我们可以看到最后 2 行被分组在一起,而不是在本例中与前 3 个值分组。
一种解决方法是查看由
.count()
生成的每个组中元素的 grouby
,并检查最后一个:
import pandas as pd
d = {'col1': [1, 2,1,5,3,2,5,6,4,1,2] }
df = pd.DataFrame(data=d)
n=3
# Temporary dataframe
A = df.groupby(df.index // n).transform('min')
# The min value of each group in a second dataframe
min_df = df.groupby(df.index // n).min()
# The size of the last group
last_batch = df.groupby(df.index // n).count()[-1:]
# if the last size is not equal to n
if last_batch.values[0][0] !=n:
last_group = last_batch+n
A[-last_group.values[0][0]:]=min_df[-2:].min()
# Assign the temporary modified dataframe to df
df['new_col'] = A
产生预期结果:
col1 new_col
0 1 1
1 2 1
2 1 1
3 5 2
4 3 2
5 2 2
6 5 1
7 6 1
8 4 1
9 1 1
10 2 1