使用正则表达式在数据框中提取数字以获取高度(ft,in)

问题描述 投票:2回答:2

我正在尝试使用正则表达式从我的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。

python regex pandas dataframe extract
2个回答
1
投票
  • 使用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

0
投票

另一种尝试,未导入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)
© www.soinside.com 2019 - 2024. All rights reserved.