Python 如何用不同的序列替换特定的数字序列(在连续行中)
我正在处理一个数据库,我是一个使用python的新手。我已经能够使用numpy和pandas函数来完成一些事情,但现在我想做一些可能很容易解决,也可能不容易解决的事情 我有一个输出1和0的数据源,我使用fillna成功地填补了列中的空白 但是现在我想创建一个新列,它复制第一个列,然后在特定序列发生时替换数据Python 如何用不同的序列替换特定的数字序列(在连续行中),python,pandas,Python,Pandas,我正在处理一个数据库,我是一个使用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
#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的列(正如我前面所说的,我是一个新手,我的编程逻辑可能有点不对劲)
谢谢这确实是一个卷积问题。或者说检测匹配模式的问题。 我创建了一个带有序列的单列
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
这实际上是一个卷积问题,或者说是检测匹配模式的问题。 我创建了一个带有序列的单列
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
你能给出一个df['filled_motor']列的示例吗?它只是一个0和1的列,所以:filled_motor 1 1 1 0 0 0 0 1 1 1 1它们与日期时间列相关联。通常会有大约40-100 1秒,然后可能是2000秒,那么你能给出一个df['filled_motor']的示例吗列看起来像?它只是一个0和1的列,所以:填充的1 1 0 0 0 0 1 1 1 1 1它们与日期时间列相关联。通常会有大约40-100 1,然后可能是2000 0,然后重复。谢谢,这是一个将数字序列转换为字符串的好主意。但是,当我试图使其与我的数据库一起工作时,我得到一个错误:ValueError:值的长度与索引的长度不匹配。我正在使用df.to\u csv写回csv。我的索引设置为我的日期\u时间列(我尝试更改该列,但没有更正错误)谢谢,这是一个将数字序列转换为字符串的好主意。但是,当我试图使其与我的数据库一起工作时,我得到了一个错误:ValueError:值的长度与索引的长度不匹配。我正在使用df.to_csv写回csv。我的索引设置为我的date_time列(我尝试更改它,但没有纠正错误)