gpt4 book ai didi

python - 将值应用于列并按这些值对所有列进行分组

转载 作者:行者123 更新时间:2023-12-01 09:27:46 26 4
gpt4 key购买 nike

我有一个 pandas 数据框,如下所示。所有没有 ["sente"] 值的行都包含更多信息,但尚未链接到 ["sente"]

id    pos      value       sente
1 a I 21
2 b have 21
3 b a 21
4 a cat 21
5 d ! 21
6 cat N Nan
7 a My 22
8 a cat 22
9 b is 22
10 a cute 22
11 d . 22
12 cat N NaN
13 cute M NaN

现在我希望 ["sente"] 中没有值的每一行都从上面的行中获取其值。然后,我想按 ["sente"] 将它们全部分组,并使用 ["sente"] 中没有值的行中的内容创建一个新列。

  sente      pos          value            content
21 a,b,b,a,d I have a cat ! 'cat,N'
22 a,a,b,a,d My cat is cute . 'cat,N','cute,M'

这将是我的第一步:

df.loc[(df['sente'] != df["sente"].shift(-1) & df["sente"] == Nan) , "sente"] = df[ "sente"].shift(+1)

但它仅适用于额外一行,不适用于 2 行或更多行。

这按照我想要的方式将一列分组:

df.groupby(["sente"])['value'].apply(lambda x: "".join()

但是对于更多列,它不会像我想要的那样工作:

df.groupby(["sente"]).agr(lambda x: ",".join()

有没有办法在不使用堆栈函数的情况下做到这一点?

最佳答案

用途:

#check NaNs values to boolean mask
m = df['sente'].isnull()
#new column of joined columns only if mask
df['contant'] = np.where(m, df['pos'] + ',' + df['value'], np.nan)
#replace to NaNs by mask
df[['pos', 'value']] = df[['pos', 'value']].mask(m)
print (df)
id pos value sente contant
0 1 a I 21.0 NaN
1 2 b have 21.0 NaN
2 3 b a 21.0 NaN
3 4 a cat 21.0 NaN
4 5 d ! 21.0 NaN
5 6 NaN NaN NaN cat,N
6 7 a My 22.0 NaN
7 8 a cat 22.0 NaN
8 9 b is 22.0 NaN
9 10 a cute 22.0 NaN
10 11 d . 22.0 NaN
11 12 NaN NaN NaN cat,N
12 13 NaN NaN NaN cute,M

最后通过使用 ffill 前向填充替换 NaN 并使用 删除 NaNjoin删除:

df1 = df.groupby(df["sente"].ffill()).agg(lambda x: " ".join(x.dropna()))
print (df1)
pos value contant
sente
21.0 a b b a d I have a cat ! cat,N
22.0 a a b a d My cat is cute . cat,N cute,M

关于python - 将值应用于列并按这些值对所有列进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com