通过更正字符串中的错误Pandas.DataFram

2024-10-03 06:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个庞大的列表,这些数据存储在文本中,我需要做一些争论,但就是不能找出什么是最好和最有效的方法。另一个需要考虑的问题是这些数据非常庞大。样本量160万行,产量达到100万。在

In [200]:data=['Bernard 51','Ber%nard Bachelor','BER78NARD$ bsc','BERnard$d B.']

In [201]:test=pd.DataFrame(data,columns=['Names'])

In [2020:test
Out[202]: 


  Names
0 Bernard 51
1 Ber%nard Bachelor
2 BER78NARD$ bsc
3 BERnard$d B.

我的目标是输出

^{pr2}$

我的伪代码将类似于:

In[222]:test_processed=pd.DataFrame(test.Names.str.lower()) #covert all str to lower

In[223]:test_processed
Out[223]: 


  Names
0 bernard 51
1 ber%nard bachelor
2 ber78nard$ bsc
3 bernard$d b.

In[224]:test_processed2=pd.DataFrame(test_processed.Names.str.replace('[^\w\s]',''))
#removes punctuation/symbol typos
In[225]:test_processed2
Out[225]: 


  Names
0 bernard 51
1 bernard bachelor
2 ber78nard bsc
3 bernardd b

In[226]:BA=['bachelor','bsc','b.'] #define list to be replaced with ba

In[227]:test_processed.replace(BA,'ba') #replace list defined above with standard term
Out[227]: 

  Names
0 bernard 51
1 ber%nard bachelor
2 ber78nard$ bsc
3 bernard$d b.

#no change, didn't work

我的观察告诉我,如果replace应用于Pandas数据帧,则它不适用于列表。在

我不使用已处理测试2的原因。名称.str.replace是因为,DataFrame.str.replace不允许使用要替换的列表。在

我之所以使用列表,是因为我希望随着越来越多不同的变量的出现,可以轻松地维护列表。我很乐意听到您的意见,如果您有一个解决方案或更好的选择,而不是使用Python或Pandas。在


Tags: 数据intestdataframe列表namesoutreplace
1条回答
网友
1楼 · 发布于 2024-10-03 06:28:47

test_processed.replace(BA,'ba')只替换精确的匹配项,而不是部分条目。也就是说,如果你的条目中有一个是‘单身汉’,它将很好地取代它。对于部分字符串,可以按照docs使用regex选项。在

还有一个replace可以在字符串上工作。例如,如果你有一个列表data,并且你想用'ba'替换'bsc'的所有实例,你要做的是:

data = [d.replace('bsc', 'ba') for d in data]

对于整个替换列表,您可以执行以下操作:

^{pr2}$

现在,虽然我觉得这正是你要问的问题,但我应该指出,这并不是解决打字错误的正确方法。假设您有条目“B.Bernard,msc”—您将用“BA”替换“B.”,而这不应该发生。你的算法非常基础,因此有问题。在

相关问题 更多 >