python - 将值与以前的值进行比较并打印它是否相同或不同
问题描述
我需要确定输出“开”或“关”是否与前一个单元格相同,如果相同则打印“相同周期”或不同打印“不同周期”。我在 jupyter python 中,我当前的代码是:
import pandas as pd
import numpy as np
header_list = ['Time']
df = pd.read_csv('S8-1.csv' , skiprows=6 , names = header_list)#splits the data into proper columns
df[['Date/Time','Pressure']] = df.Time.str.split(",,", expand=True)#deletes orginal messy column
df.pop('Time')
#convert Pressure from object to numeric
df['Pressure'] = pd.to_numeric(df['Pressure'], errors = 'coerce')#converts to a time
df['Date/Time'] = pd.to_datetime(df['Date/Time'], format = '%m/%d/%y %H:%M:%S.%f' , errors = 'coerce')
df['Moving Average'] = df['Pressure'].rolling(window=5).mean()
df['Rolling Average Center']= df['Pressure'].rolling(window=5, center=True).mean()
df['Machine On/Off'] = ['1' if x >= 115 else '0' for x in df['Rolling Average Center'] ]
df['Moving Avg of Binary'] = df['Machine On/Off'].rolling(window=3).mean()
df['On/Off'] = ['On' if x > 0 else 'Off' for x in df ['Moving Avg of Binary']]
df['Cycle change'] = ['Same Cycle' if x == last else 'New Cycle' for x != last in df['On/Off']]
最后一行给我带来了麻烦。我的数据看起来像这样:Excel 数据
解决方案
欢迎来到 Stackoverflow,让我们假设您的数据框如下:
import pandas as pd
your_dataframe = pd.DataFrame({'your_on/of_column':['ON', 'OFF', 'ON', 'ON', 'OFF', 'ON', 'ON', 'OFF', 'ON']})
your_dataframe['other_column1'] = ['foo' for item in range(len(your_dataframe))]
your_dataframe['other_column2'] = ['bar' for item in range(len(your_dataframe))]
######
your_on/of_column other_column1 other_column2
0 ON foo bar
1 OFF foo bar
2 ON foo bar
3 ON foo bar
4 OFF foo bar
5 ON foo bar
6 ON foo bar
7 OFF foo bar
8 ON foo bar
有一个著名的函数用于确定命名的连续值之间的差异diff
,您可以在此处阅读!唯一需要注意的是它只能对数字/逻辑值进行操作所以将列转换your_on/of_column
为布尔值并继续!
your_dataframe['Cycle'] = your_dataframe['your_on/of_column'].apply(lambda item:item=='ON').diff().apply(lambda item:"Different Cycle" if item else "Same Cycle")
输出:
your_on/of_column other_column1 other_column2 Cycle
0 ON foo bar Different Cycle
1 OFF foo bar Different Cycle
2 ON foo bar Different Cycle
3 ON foo bar Same Cycle
4 OFF foo bar Different Cycle
5 ON foo bar Different Cycle
6 ON foo bar Same Cycle
7 OFF foo bar Different Cycle
8 ON foo bar Different Cycle
推荐阅读
- javascript - 我需要按日期过滤任务以显示在某个区域 - React Native
- node.js - 用于生产的免费 SMTP
- r - 在函数中设置默认值时遇到问题[r]
- python - 如何使用python获取json响应?
- css - 在灰度背景图像上将文本颜色从黑色“反转”为白色
- python - Python networkx边缘和节点标记问题
- java - 无法使用 java 中的 openchannel 访问远程机器中的 cmd 提示符
- python - 使用 np.repeat 将一维数组扩展为多维数组
- javascript - 谁能教我下面给出的这个JS代码?
- javascript - 循环遍历数组以使用 vanilla javascript 创建图像滑块