计算在列或行之间条件内值的出现次数

2024-10-01 07:14:00 发布

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

我有一个数据集本文件:你知道吗

2017-03-01  31.8  28.0     32.6
2017-04-01  31.6  28.0     32.6
2017-05-01  31.0  27.0     32.6
2017-06-01  31.0  27.0     32.4
2017-07-01  31.0  27.0     31.4
2017-08-01  30.0  27.0     32.6

除第一列外,其余列均为温度。我想做的是比较第4列的值(从右起的最后一列)和其他列的值,以确定温度值是否不大于或小于2度(第4列)。例如,我想计算三列(按行)的值在30.6到34.6之间的次数。你知道吗

熊猫有这样的功能吗?你知道吗


Tags: 文件数据功能温度次数集本
3条回答

根据您的样本数据,您可以尝试:

df2[['t1','t2','t3']].apply(lambda x : abs(x-df2['t3'])<2).sum(axis=1)==3

Out[425]: 
0    False
1    False
2    False
3    False
4    False
5    False
dtype: bool

数据输入

    df2
    Out[426]: 
             Time    t1  t2    t3
    0  2017-03-01  31.8  28  32.6
    1  2017-04-01  31.6  28  32.6
    2  2017-05-01  31.0  27  32.6
    3  2017-06-01  31.0  27  32.4
    4  2017-07-01  31.0  27  31.4
    5  2017-08-01  30.0  27  32.6

如果我正确理解您的问题,您想知道所有值在第四列±2范围内的次数(列编号为0,1,2,3):

(((df[3] - df[1]).abs() < 2) & ((df[3] - df[2]).abs() < 2)).sum()
#0

ab的值小于c的2

In [726]: (df[['a', 'b']].sub(df['c'], axis=0).abs() < 2).all(1).sum()
Out[726]: 0

In [727]: (df[['a', 'b']].sub(df['c'], axis=0).abs() < 2)
Out[727]:
       a      b
0   True  False
1   True  False
2   True  False
3   True  False
4   True  False
5  False  False

值介于30.6到34.6之间

In [671]: (df[['a', 'b', 'c']] > 30.6) & (df[['a', 'b', 'c']] < 34.6)
Out[671]:
       a      b     c
0   True  False  True
1   True  False  True
2   True  False  True
3   True  False  True
4   True  False  True
5  False  False  True

值介于30.6到34.6之间,一行中的所有列都为真

In [672]: ((df[['a', 'b', 'c']] > 30.6) & (df[['a', 'b', 'c']] < 34.6)).all(1)
Out[672]:
0    False
1    False
2    False
3    False
4    False
5    False
dtype: bool

所有列的值在30.6到34.6之间的行计数

In [673]: ((df[['a', 'b', 'c']] > 30.6) & (df[['a', 'b', 'c']] < 34.6)).all(1).sum()
Out[673]: 0

相关问题 更多 >