Python 计算列中字符串内的数值
我有一个pandas数据框,我可以选择我想查看的列:Python 计算列中字符串内的数值,python,string,pandas,count,Python,String,Pandas,Count,我有一个pandas数据框,我可以选择我想查看的列: column_x = str(data_frame[4]) 如果我打印列_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
column_x = str(data_frame[4])
如果我打印列_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
当列中的值是包含字符串和数字内容的字符串时,如何从该列中计算这些值
多谢各位
Rodrigo您可以使用来提取数值,并在那里进行计数:
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
上面的评论很有道理。通常,在分析之前,您应该关注解析 也就是说,这并不难。与正则表达式一起使用,然后强制为float,然后对其执行操作
floats = column_x.str.extract("^AF1000g=(.*)$").astype(float)
num_less = (vals <= 0.05).sum()
num_greater = (vals > 0.05).sum()
这利用了这样一个事实,即通过与VAL的比较返回的布尔数组可以强制为0和1。最好将列命名为AF1000g,并使值成为列中唯一的内容。这应该是你的问题,然后所有其他的东西会很容易来。