[英]How to append a specific string according to each value in a string pandas dataframe column?
[英]How to append counter number to each repeated string value in pandas column?
我正在嘗試轉換以下熊貓字符串列。 我只想在重復的案例名稱后面加上數字。 如下預期結果部分所示。
Index CaseName
0 CASE_A
1 CASE_A
2 CASE_A
3 CASE_A
4 CASE_A
5 CASE_B
6 CASE_B
7 CASE_B
8 CASE_B
9 CASE_B
10 CASE_B
我試圖創建一個列表,可以將其替換為當前列,但是生成的列表的長度比預期的大。 可能是由於下面編寫了嵌套循環。
updatedID=[]
for val in temp_val:
for cnt in temp_cnt:
for n in range(cnt):
updatedID.append(val+str(n))
但是產生的結果是錯誤的。
預期結果:
Index CaseName
0 CASE_A1
1 CASE_A2
2 CASE_A3
3 CASE_A4
4 CASE_A5
5 CASE_B1
6 CASE_B2
7 CASE_B3
8 CASE_B4
9 CASE_B5
10 CASE_B6
通過GroupBy.cumcount
添加計數器,將1
和最后一個GroupBy.cumcount
添加到string
:
df['CaseName'] += df.groupby('CaseName').cumcount().add(1).astype(str)
print (df)
CaseName
Index
0 CASE_A1
1 CASE_A2
2 CASE_A3
3 CASE_A4
4 CASE_A5
5 CASE_B1
6 CASE_B2
7 CASE_B3
8 CASE_B4
9 CASE_B5
10 CASE_B6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.