python - 如何在熊猫中使用正则表达式在包含混合数据的df列中查找数字
问题描述
您知道如何转换此代码以获得更快的代码吗?在这段代码中,我只想取数字(十进制或整数)并拒绝列中存在的单词。事实上,在 a 列中,我可以找到数字和单词。谢谢!
a=['a', '9','4.5','nnn', '3.4543', '2'] c=[1,10,5,4,4,7]
df=pd.DataFrame(a,c)
b =pd.Series(np.zeros(len(df)), name='b', index=df.index)
i = 0
for row in df.a:
if re.findall(r'(\d+[.]\d+)', str(row)):
b.loc[i] = re.search(r'(\d+[.]\d+)', str(row)).group()
elif re.findall(r'(\b\d+\b)', str(row)):
b.loc[i] = re.search(r'(\b\d+\b)', str(row)).group()
else:
b.loc[i] = '9999'
i = i + 1
for i in range(len(b)):
b.loc[i]=float(b.loc[i])
df.a = b
我想获得 a=[9999, 9, 4.5,9999,3.4543, 2]
解决方案
使用 apply 和 assign 函数来创建一个新列:
重新进口
regnumber = re.compile(r'\d+(?:,\d*)?')
a=['a', '9','4.5','nnn', '3.4543', '2']
c=[1,10,5,4,4,7]
df=pd.DataFrame({'a':a,'c':c})
df = df.assign(
a = lambda x: x['a'].apply(lambda s: s if regnumber.match(s) else 9999)
)
print(df)
a c
9999 1
9 10
4.5 5
9999 4
3.4543 4
2 7
推荐阅读
- c++ - 使用 InfluxdbV2.h 将 ESP32 数据写入 Influxdb 会出现 NULL 错误
- mysql - 将可变长度整数加载到 MySQL 表中的问题
- post - Swift - 错误:套接字 SO_ERROR [61:连接被拒绝]
- discord.js - 获取用户在频道中提及的次数
- laravel - 标记每个资源的重叠事件(FullCalendar 5,Laravel 7)
- ios - 从 `URLSession.dataTaskPublisher` 接收任务进度
- android - 是否可以在 android 设备上构建推送通知的文本?
- c++ - 如果它只是“浅常量”而不是“深常量”,我应该声明方法“常量”吗?
- reactjs - 部署生产构建时 React App 空白页面
- image - XAML 将图像加载到网格中