计算 Pandas 列中字符串中的数值

Calculate Numeric Value inside a String within a Pandas Column

我有一个 pandas 数据框,我可以 select 我想查看的列:

column_x = str(data_frame[4])

如果我打印 column_x,我得到:

0     AF1000g=0.09
1     AF1000g=0.00
2     AF1000g=0.14
3     AF1000g=0.02
4     AF1000g=0.02
5     AF1000g=0.00
6     AF1000g=0.54
7     AF1000g=0.01
8     AF1000g=0.00
9     AF1000g=0.04
10    AF1000g=0.00
11    AF1000g=0.03
12    AF1000g=0.00
13    AF1000g=0.02
14    AF1000g=0.00
...

我想计算有多少行包含 AF1000g=0.05 或更小的值。以及包含值 AF1000g=0.06 或更大的行。

Less_than_0.05 = count number of rows with AF1000g=0.05 and less

Greater_than_0.05 = count number of rows with AF1000g=0.06 and greater    

当列中的值是包含字符串和数字内容的字符串时,如何从该列中计算这些值?

谢谢。

罗德里戈

您可以使用apply提取数值,并在那里进行计数:

vals = column_x.apply(lambda x: float(x.split('=')[1]))
print sum(vals <= 0.05) #number of rows with AF1000g=0.05 and less
print sum(vals >= 0.06) #number of rows with AF1000g=0.06 and greater

上面的评论说得很有道理。一般在分析之前先把重点放在解析上。

也就是说,这并不难。将 pd.Series.str.extract 与正则表达式一起使用,然后强制为浮点数,然后对其进行操作。

 floats = column_x.str.extract("^AF1000g=(.*)$").astype(float)
 num_less = (vals <= 0.05).sum()
 num_greater = (vals > 0.05).sum()

这利用了与 vals 比较返回的布尔数组可以强制为 0 和 1 的事实。