繁体   English   中英

如何在新列中添加具有特定条件的列的字符串值

[英]How to add string values of columns with a specific condition in a new column

所以我有一个 dataframe ,其中有几列和很多行。

现在我想创建一个新列 (C),如果第三列 (B) 相同,它将另一列 (A) 的值作为字符串添加在一起。

因此,每个“组”(在 B 中相同)最后应该具有与该列中的其他组不同的字符串。

一个 新立柱 C
第一的 1 第一_第三
第二 22 Second_Fourth
第三 1 第一_第三
第四 22 Second_Fourth

像这样的伪代码:

for x in df[B]:
if (x "is identical to" x "of another row"):
df[C] = df[C].cat(df[A])

我如何编写可以做到这一点的算法?

尝试这个:

df['C'] = df.groupby('B')['A'].transform(lambda x: '_'.join(x))

您可以使用:

df['C'] = df.groupby('B')['A'].transform('_'.join)

或者,如果您只想保留唯一值:

df['C'] = df.groupby('B')['A'].transform(lambda x: '_'.join(x.unique()))

output:

        A   B              C
0   First   1    First_Third
1  Second  22  Second_Fourth
2   Third   1    First_Third
3  Fourth  22  Second_Fourth

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM