我有一个带有文本,字符长度和'x'值的输入数据框。
x text len flag
0 1 hi 2 1
1 1 hello 5 0
2 1 how 3 1
3 2 are 3 1
4 2 you? 4 1
5 2 kiddo 5 1
我想对x进行分组,并得到flag为1的最小字符长度的文本。
x text len select
0 1 hi 2 hi
1 1 hello 5 nan
2 1 how 3 nan
3 2 are 3 are
4 2 you? 4 nan
5 2 kiddo 5 nan
我试图分组并获得最小值,但是如何获得存在最小值的文本?我不想使用申请。
df[df.flag == 1].groupby('x')['len'].transform('min')
我将获得最小字符长度值,而不是字符长度最小的文本值
答案 0 :(得分:2)
您需要groupby
和transform
和idxmin
:
# Handle the `flag` requirement.
v = df.assign(len=df['len'].where(df.flag.astype(bool)))
condition = v.groupby('x')['len'].transform('idxmin')
df.loc[condition, 'select'] = df.loc[condition, 'text'].values
df
x text len flag select
0 1 hi 2 1 hi
1 1 hello 5 0 NaN
2 1 how 3 1 NaN
3 2 are 3 1 are
4 2 you? 4 1 NaN
5 2 kiddo 5 1 NaN