如何解决从pandas数据框中的列中提取字符串中的数字
我需要使用数据框house_price中的“便利设施”列进行特征提取。
“便利设施”列具有以下数据集
s = paramiko.SSHClient()
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname,port,username,password)
command = 'xe vm-list'
(stdin,stdout,stderr) = s.exec_command(command)
output = stdout.read()
x = output.replace("\n",",").strip()
print(x)
s.close()
我需要提取床,浴室和停车场的数量,并将它们存储在3个单独的列中。
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
上面的代码仅提取整个字符串的第一位。如何提取代表浴场/停车场数量的数字并将其存储在不同的列下?
解决方法
我们可以在named groups
中使用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
,
您可以尝试以下方法:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。