我正在尝试使用正则表达式从我的Pandas数据框[height]
中的列中提取数字。列中的数据使用ft并在以下位置以字符串形式列出:例如“ 5ft 6in
”。为了可视化此数据以供将来分析,我需要将此格式转换为完全以英寸为单位并为整数。到目前为止,我已经使用下面的第一行代码成功创建了列height_feet
。但是,我在提取英寸height_in
时遇到了麻烦。
modcloth_df = modcloth_df.assign(height_feet = modcloth_df['height'].str.extract('(\d+)'))
modcloth_df = modcloth_df.assign(height_in = modcloth_df['height'].str.extract('((\d+)in)'))
modcloth_df.head()
这将导致回溯:
ValueError: Wrong number of items passed 2, placement implies 1
这可追溯到第二行以提取英寸。然后,我想使用两个整数将一列分配为total_height。
re.findall
从给定格式中提取数字re.findall
,以英寸为单位计算并返回值int
import pandas as pd
import re
# create dataframe
df = pd.DataFrame({'height': ['5ft 6in', '6ft 0in']})
# function to extract numbers, convert and return inches
def convert_to_inches(x):
values = re.findall(r'\d+', x)
return int(values[0]) * 12 + int(values[1])
# apply the function
df['height_in'] = df.height.apply(convert_to_inches)
# output
height height_in
0 5ft 6in 66
1 6ft 0in 72
列不包含height
in
另一种尝试,未导入df = pd.DataFrame({'height': ['5ft 6in', '6ft 0in', '6ft']})
def convert_to_inches(x):
values = re.findall(r'\d+', x)
ft = int(values[0])
try:
inches = int(values[1])
except IndexError:
inches = 0
return ft * 12 + inches
df['height_in'] = df.height.apply(convert_to_inches)
# output
height height_in
0 5ft 6in 66
1 6ft 0in 72
2 6ft 72
模块(re
):
explanation of the regex
打印:
import pandas as pd
modcloth_df = pd.DataFrame({'height':
['5ft 6in',
'4ft 1in',
' 6in',
'3ft']})
modcloth_df[ ['height_feet', 'height_in'] ] = modcloth_df['height'].str.extract(r'(?:(\d+)ft)?\s*(?:(\d+)in)?').fillna(0).astype(int)
modcloth_df[ 'total_height' ] = modcloth_df[ 'height_feet' ] * 12 + modcloth_df['height_in']
print(modcloth_df)