gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:52:15 25 4
gpt4 key购买 nike

我正在开发数据库,​​并且我是 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 的列(正如我之前所说,我是一个新手,我的编程逻辑可能会偏离)

谢谢

最佳答案

这确实是一个卷积问题。或者检测匹配模式的问题。我创建了一个带有序列的单列 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

关于python - 如何用不同的序列替换特定的数字序列(连续行中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56242924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com