我正在處理一個巨大的檔案,該檔案的列中包含我想要洗掉的無關值(如“|”鍵),但由于某種原因,我的str.replace函式似乎只適用于列中的某些行。
我在資料框中的列summary看起來像這樣:
Labels
test|test 1
test 2
test 3
test|test 4
test|test 5
test 6
如您所見,有些列已經是我想要的樣子,只包含名稱“test #”,但有些列有“test|” 在前面,我想洗掉它。
我洗掉它們的功能是這樣的:
correction = summary["Labels"].str.replace('test\|', '')
這似乎是作業最值的,但是當我檢查管道(“|”)的資料幀(有一次,我合并correction使用summary),它說,它發現了它們的9330:
found = summary[summary['Labels'].str.contains('|',regex=False)]
print(len(found))
print(found['Labels'].value_counts())
Results
9330
test|test-667 59
test|test-765 40
test|test-1810 39
test|test-685 36
test|test-1077 33
..
有誰知道這是為什么,我該如何解決?
uj5u.com熱心網友回復:
你走在正確的軌道上。替換原始字串如下
summary['Labels'] = summary['Labels'].str.replace(r'test\|','', regex=True)
Labels
0 test 1
1 test 2
2 test 4
uj5u.com熱心網友回復:
嘗試str.extract:
df['Labels'] = df['Labels'].str.extract(r'\|(.*)', expand=False) \
.combine_first(df['Labels'])
print(df)
# Output
Labels
0 test 1
1 test 2
2 test 3
3 test 4
4 test 5
5 test 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409474.html
標籤:
