簡體   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