为什么 str.replace 不替换所选 pandas 数据框列中的所有值?
Why doesn't str.replace replace ALL values in selected pandas dataframe column?
我正在处理一个巨大的文件,该文件的名称列中包含我想删除的无关值(如“|”键),但出于某种原因,我的 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
..
有谁知道这是为什么,我该如何解决?
尝试 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
你走在正确的轨道上。按如下方式替换原始字符串
summary['Labels'] = summary['Labels'].str.replace(r'test\|','', regex=True)
Labels
0 test 1
1 test 2
2 test 4
我正在处理一个巨大的文件,该文件的名称列中包含我想删除的无关值(如“|”键),但出于某种原因,我的 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
..
有谁知道这是为什么,我该如何解决?
尝试 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
你走在正确的轨道上。按如下方式替换原始字符串
summary['Labels'] = summary['Labels'].str.replace(r'test\|','', regex=True)
Labels
0 test 1
1 test 2
2 test 4