Python 如何替换数据帧中1列中的数字?
df大约有200000行。一列是电话号码。我需要将8替换为+7。我不想再创建一个df。我想就地做Python 如何替换数据帧中1列中的数字?,python,pandas,Python,Pandas,df大约有200000行。一列是电话号码。我需要将8替换为+7。我不想再创建一个df。我想就地做 df.head() client_id contact_number 0 +77760013505 1 +77779261433 2 +77071061047 3 +77714032401 4 87787763621 5 877
df.head()
client_id contact_number
0 +77760013505
1 +77779261433
2 +77071061047
3 +77714032401
4 87787763621
5 87787763621
我想用8到+7替换这些
starts_8_length_11 = df[(df['contact_number'].str.startswith('8')) & (df['contact_number'].str.len()==11)]
但是我不想从主df创建starts8_length11,更改它然后将其放回df。如何就地执行?解决方案应该是将字符串开头的
8
替换为regex^
,但仅用于长度11
的行:
m = (df['contact_number'].str.len()==11)
df.loc[m, 'contact_number'] = df.loc[m, 'contact_number'].str.replace('^8', '+7')
print (df)
client_id contact_number
0 0 +77760013505
1 1 +77779261433
2 2 +77071061047
3 3 +77714032401
4 4 +77787763621
5 5 +77787763621
我认为
inplace
不是一个好的做法,检查并执行。解决方案应该是将8
替换为regex^
作为字符串的开头,但仅用于长度11
的行:
m = (df['contact_number'].str.len()==11)
df.loc[m, 'contact_number'] = df.loc[m, 'contact_number'].str.replace('^8', '+7')
print (df)
client_id contact_number
0 0 +77760013505
1 1 +77779261433
2 2 +77071061047
3 3 +77714032401
4 4 +77787763621
5 5 +77787763621
我认为
inplace
不是一个好的做法,请检查并确认。为什么^8?什么是^8?正则表达式^如果我没有记错,8是字符串开头的数字8。为什么^8?什么是^8?正则表达式^如果我没有记错的话,8是字符串开头的数字8。