Python透视表遍历每个值

2024-04-27 00:04:59 发布

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

下面是一个数据示例

Temperature Voltage Data
         25     3.3   2
         25     3.3 2.5
         25     3.3 3.7
         25     3.3 3.5
         25     3.3 2.7
         25    3.45 1.9
         25    3.45 1.7
         25    3.45 1.5
         25    3.45   2
         25    3.45 2.9
        105     3.3   3
        105     3.3 3.5
        105     3.3 4.7
        105     3.3 4.5
        105     3.3 3.7
        105    3.45 2.5
        105    3.45 2.3
        105    3.45 2.1
        105    3.45 3.3
        105    3.45   4

我想遍历每一行来计算两个连续数据点之间的差值,然后计算该差值等于或大于1的次数

然后,打印出每种温度每种电压发生的次数

谢谢你, 维克托


Tags: 数据示例data温度次数电压temperaturevoltage
1条回答
网友
1楼 · 发布于 2024-04-27 00:04:59

编辑:添加np.abs以确保取差值的绝对值

您可以使用pandasdiff,然后使用np.where作为条件:

import numpy as np
import pandas as pd
data = {
    'Temperature': [25,25,25,25,25,25,25,25,25,25,105,105,105,105,105,105,105,105,105,105],
    'Voltage': [3.3,3.3,3.3,3.3,3.3,3.45,3.45,3.45,3.45,3.45,3.3,3.3,3.3,3.3,3.3,3.45,3.45,3.45,3.45,3.45],
    'Data': [2,2.5,3.7,3.5,2.7,1.9,1.7,1.5,2,2.9,3,3.5,4.7,4.5,3.7,2.5,2.3,2.1,3.3,4]
}
df = pd.DataFrame(data)
df['difference'] = df['Data'].diff(1)
df['flag'] = np.where(np.abs(df['difference']) >= 1,'More than 1','Less than one')
print(df)

输出:

    Temperature  Voltage  Data  difference           flag
0            25     3.30   2.0         NaN  Less than one
1            25     3.30   2.5         0.5  Less than one
2            25     3.30   3.7         1.2    More than 1
3            25     3.30   3.5        -0.2  Less than one
4            25     3.30   2.7        -0.8  Less than one
5            25     3.45   1.9        -0.8  Less than one
6            25     3.45   1.7        -0.2  Less than one
7            25     3.45   1.5        -0.2  Less than one
8            25     3.45   2.0         0.5  Less than one
9            25     3.45   2.9         0.9  Less than one
10          105     3.30   3.0         0.1  Less than one
11          105     3.30   3.5         0.5  Less than one
12          105     3.30   4.7         1.2    More than 1
13          105     3.30   4.5        -0.2  Less than one
14          105     3.30   3.7        -0.8  Less than one
15          105     3.45   2.5        -1.2    More than 1
16          105     3.45   2.3        -0.2  Less than one
17          105     3.45   2.1        -0.2  Less than one
18          105     3.45   3.3         1.2    More than 1
19          105     3.45   4.0         0.7  Less than one

相关问题 更多 >