数据帧:从列中的字符串提取浮点值

2024-10-03 15:23:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从字符串中提取一个特定列的浮点值。你知道吗

原始输出

DATE        strCondition
4/3/2018    2.9
4/3/2018    3.1, text
4/3/2018    2.6 text
4/3/2018    text, 2.7 

以及其他变化。 我也尝试过regex,但我的知识有限,我想到了:

clean = df['strCondition'].str.contains('\d+km')
df['strCondition'] = df['strCondition'].str.extract('(\d+)', expand = False).astype(float)

输出结果如下所示,其中显示的是主整数。。。你知道吗

DATE        strCondition
4/3/2018    2.0
4/3/2018    3.0
4/3/2018    2.0
4/3/2018    2.0 

我期望的结果是:

DATE        strCondition
4/3/2018    2.9
4/3/2018    3.1
4/3/2018    2.6
4/3/2018    2.7 

我感谢你的时间和投入!你知道吗

编辑: 我忘了提到在我的原始数据帧中有类似于的strCondition条目

2.9(1.0) #where I would like both numbers to get returned
11/11/2018 #where this date as a string object can be discarded 

很抱歉给您带来不便!你知道吗


Tags: 字符串textcleanfalsedfdateextractwhere
2条回答

一个简单的替代品就是

查找(?m)^([\d/]+[ \t]+).*?(\d+\.\d+).*

替换\1\2

https://regex101.com/r/pVC4jc/1

尝试:

df['float'] = df['strCondition'].str.extract(r'(\d+.\d+)').astype('float')

输出:

       DATE strCondition  float
0  4/3/2018          2.9    2.9
1  4/3/2018    3.1, text    3.1
2  4/3/2018     2.6 text    2.6
3  4/3/2018    text, 2.7    2.7

相关问题 更多 >