如何用不同的序列替换特定的数字序列(连续的行)

时间:2019-05-21 16:44:29

标签: python pandas

我正在研究数据库,但是我是使用python的新手。我已经能够使用numpy和pandas函数完成某些事情,但是现在我想做一些可能容易解决的事情

我有一个输出1s和0s的数据源,我使用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 

我想知道如何用另一个特定序列替换col中的特定行序列。

但是,当我对这个特定问题进行更多的思考时,我想知道在我的思想中是否由于某种类型的逻辑错误而使它变得更加困难,其中每当将1、0、0的序列替换为1、1、1时,会在它之后立即创建一个新的1、0、0序列,因此最终总是会产生全为1的col(正如我之前所说的,我是一名新手,我的编程逻辑可能还很遥远)

谢谢

1 个答案:

答案 0 :(得分:0)

这确实是一个卷积问题。或检测匹配模式的问题。 我创建了一个带有序列的单列col1,最初这是一个数字数组系列。

但是我将其转换为字符串,然后简单地替换了模式,然后返回到列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