Python 从dataframe中的列中提取字符串中的数字

Python 从dataframe中的列中提取字符串中的数字,python,pandas,dataframe,data-cleaning,feature-extraction,Python,Pandas,Dataframe,Data Cleaning,Feature Extraction,我需要使用dataframe house_price中的“便利设施”列进行特征提取 该列包含以下一组数据 house_data['Amenities'] 3 3 beds 1 bath 4 1 bed 1 bath 1 parking 5 3 beds 1 bath 6 2 beds 2 baths 2 parking 7 3 beds

我需要使用dataframe house_price中的“便利设施”列进行特征提取

该列包含以下一组数据

house_data['Amenities']

3                       3 beds 1 bath
4              1 bed 1 bath 1 parking
5                       3 beds 1 bath
6            2 beds 2 baths 2 parking
7             3 beds 1 bath 2 parking
                    ...              
2096    3 beds 2 baths 1 parking 419m
2097          4 beds 1 bath 2 parking
2098         3 beds 2 baths 2 parking
2099         2 beds 2 baths 1 parking
2100    3 beds 2 baths 1 parking 590m
Name: Amenities, Length: 1213, dtype: object
我需要提取床、浴室和停车场的数量,并将它们存储到3个独立的列中

house_data["bedrooms"] = ''
house_data["bedrooms"] = house_data["Amenities"].str.extract("(\d*\.?\d+)", expand=True)



3       3
4       1
5       3
6       2
7       3
       ..
2096    3
2097    4
2098    3
2099    2
2100    3
Name: bedrooms, Length: 1213, dtype: object
上面的代码只提取整个字符串的第一个数字。如何提取表示浴室/停车场数量的数字并将其存储在不同的列中?

您可以尝试以下方法:

df = df['Amenities'].str.split(r'[a-zA-Z ]+', expand=True).drop(columns=[3, 4])
print(df)

   0  1  2
0  3  1   
1  1  1  1
2  3  1   
3  2  2  2
4  3  1  2
5  3  2  1
6  4  1  2
7  3  2  2
8  2  2  1
9  3  2  1

我们可以将
命名组
Series.str.extract
一起使用:

regex = r'(?P<beds>\d)\sbeds?\s(?P<bath>\d+)\sbaths?\s?(?P<parking>\d)?'
df = pd.concat([df, df['Amenities'].str.extract(regex)], axis=1)

                       Amenities beds bath parking
0                  3 beds 1 bath    3    1     NaN
1         1 bed 1 bath 1 parking    1    1       1
2                  3 beds 1 bath    3    1     NaN
3       2 beds 2 baths 2 parking    2    2       2
4        3 beds 1 bath 2 parking    3    1       2
5  3 beds 2 baths 1 parking 419m    3    2       1
6        4 beds 1 bath 2 parking    4    1       2
7       3 beds 2 baths 2 parking    3    2       2
8       2 beds 2 baths 1 parking    2    2       1
9  3 beds 2 baths 1 parking 590m    3    2       1
regex=r'(?P\d)\sbeds?\s(?P\d+)\sbaths?\s?(?P\d)?'
df=pd.concat([df,df['commercies'].str.extract(regex)],轴=1)
设施、床、浴室、停车场
0 3张床1个浴室3 1个南
1床1浴1停车1 1
2张3张床1个浴室3个1男
3 2张床2个浴室2个停车场2 2
4张床1个浴室2个停车场3 1 2
5张床2个浴室1个停车场419m 3 2 1
6 4张床1个浴室2个停车场4 1 2
7 3张床2个浴室2个停车场3 2 2
8 2张床2个浴室1个停车场2 1
9 3张床2个浴室1个停车场590m 3 2 1