我有一個包含多列的資料框,我想在一列中用空格將數字與字母分開。在此示例中,我想在第三列中添加空格。你知道怎么做嗎?

import pandas as pd
data = {'first_column': ['first_value', 'second_value', 'third_value'],
'second_column': ['first_value', 'second_value', 'third_value'],
'third_column':['AA6589', 'GG6589', 'BXV6589'],
'fourth_column':['first_value', 'second_value', 'third_value'],
}
df = pd.DataFrame(data)
print (df)
uj5u.com熱心網友回復:
str.replace與短正則運算式一起使用:
df['third_column'] = df['third_column'].str.replace(r'(\D )(\d )',
r'\1 \2', regex=True)
正則運算式:
(\D ) # capture one or more non-digits
(\d ) # capture one or more digits
替換為\1 \2(第一個捕獲的組,然后是空格,然后是第二個捕獲的組)。
環顧四周的替代方案:
df['third_column'] = df['third_column'].str.replace(r'(?<=\D)(?=\d)',
' ', regex=True)
含義:在非數字和數字之間的任何位置插入空格。
uj5u.com熱心網友回復:
同樣,您可以從“third_column”中提取數字和非數字字符,并將它們放在一起,中間有空格:
df.assign(
third_column=df["third_column"].str.extract(r'(\D )') " " df["third_column"].str.extract(r'(\d )')
)
first_column second_column third_column fourth_column
0 first_value first_value AA 6589 first_value
1 second_value second_value GG 6589 second_value
2 third_value third_value BXV 6589 third_value
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505727.html
