python - 如何用不同的序列替换特定的数字序列(连续行)
问题描述
我正在研究数据库,我是使用 python 的新手。我已经能够使用 numpy 和 pandas 函数来完成一些事情,但现在我想做一些可能容易解决也可能不容易解决的事情
我有一个输出 1 和 0 的数据源,我使用 fillna 成功填充了列中的空白。
但是现在我想创建一个新列来复制第一个列,然后在发生特定序列时替换数据。
#When col1 = [1, 0, 0]
#replace with [1, 1, 1]
import pandas as pd
import numpy as np
df = pd.read_csv('HoboProbe_and_MotorState.txt')
df['Date_Time'] = pd.to_datetime(df['Date_Time'])
df.set_index('Date_Time',drop=True,inplace=True)
df.sort_index(inplace=True)
df['filled_motor'] = df['motor_state']
df['filled_motor'].fillna(method='ffill',inplace=True)
df['filled_motor'].fillna(method='bfill',inplace=True)
# all this above works fine, below is what I have attempted to solve the problem
df['col_Test1'] = df['filled_motor']
df['col_Test1'] = df['col_Test1'].replace([1, 0],[1, 1])
#this just replaced all the 1 and 0 with 1, as apposed to replacing it only when the 1, 0 sequence occures
df['col_Test2'] = np.where((df['filled_motor']==1) & ((df['filled_motor']+1)==0), 1, df.filled_motor)
#here I tried to say where col==1 and where col(row+1)==0 input a 1 everywhere else input col. But this did not work either
我想知道如何用另一个特定序列替换列中的特定行序列。
但是,当我更多地考虑这个特定问题时,我想知道我的想法中的某种逻辑错误是否会使它变得更加困难,每当将 1、0、0 的序列替换为 1、1、1 时,它只会创建紧随其后的 1, 0, 0 的新序列,因此最终总是会产生一个全为 1 的 col(正如我之前所说,我是一个新手,我的编程逻辑可能有问题)
谢谢
解决方案
这确实是一个卷积问题。或检测匹配模式的问题。col1
我创建了一个带有序列的单列,最初这是一个数字数组系列。
但是我将其转换为字符串,然后简单地替换了模式,然后返回到 column c
。
您可以使用字符串函数
s = df.col1.astype(str).sum()
s =s.replace('100', '111')
print(s)
df['c']=list(s)
print(df)
这是输出:
col1
0 0
1 1
2 0
3 0
4 1
5 1
6 0
0111110
col1 c
0 0 0
1 1 1
2 0 1
3 0 1
4 1 1
5 1 1
6 0 0
推荐阅读
- javascript - 换行符 \n 在 Javascript Blotter 中不起作用
- java - 为什么我的 HashSet 中有重复数据?
- postgresql - 使用 pg-promise 转换值时出现奇怪的错误
- python - 无法让我的 python 应用程序在 docker 容器中启动
- apache-kafka - Kafka 数据中心故障转移
- python - 反向查询集/列表,然后切片
- javascript - 为什么这个带有微不足道的异步回调的测试用例(Jest)会失败?
- c# - dotnet core 2.2 EntityFramework 与 postgres
- react-redux - 他们是一种重置 Twilio 设备处理程序函数的方法吗?
- terraform - Terraform 没有为所有实例分配公共 IP