根据其他2个列表对齐2个python列表

2024-10-03 15:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数组,即nlxTTLttlState。两个阵列都包含0和1的重复模式,指示输入电压可以是高(1)或低(0),并从发送1秒脉冲宽度的TTL脉冲(高和低)的同一源记录

但是由于一些记录错误,在ttlState列表中发生了一些删除操作,即它不记录0和1的重复序列,最终删除值

好的一点是,我还为两个列表接收到的每个TTL输入记录时间戳。TTL事件时间戳之间的差异清楚地表明TTL事件错过了一个脉冲

以下是数据的示例:

nlxTTL, ttlState, nlxTime, ttlTime
0,0,1000,1000
1,1,2000,2000
0,1,3000,4000
1,1,4000,6000
0,0,5000,7000
1,1,6000,8000
0,0,7000,9000
1,1,8000,10000

正如您所看到的,nlxTimettlTime显然是不同的。然后如何使用这些时间戳来对齐所有4个列表


Tags: 列表宽度错误记录时间模式事件数组
1条回答
网友
1楼 · 发布于 2024-10-03 15:22:09

在处理表格数据(如CSV文件)时,最好使用库来简化处理过程。我喜欢pandas数据帧库

对于你的问题,思考这个问题的一个方法是你真的有两个数据集。。。一个nlx数据集和一个ttl数据集。您希望通过时间戳将这些数据集连接在一起。熊猫使这样的任务非常容易

import pandas as pd
from StringIO import StringIO

data = """\
nlxTTL, ttlState, nlxTime, ttlTime
0,0,1000,1000
1,1,2000,2000
0,1,3000,4000
1,1,4000,6000
0,0,5000,7000
1,1,6000,8000
0,0,7000,9000
1,1,8000,10000
"""

# Load data into dataframe.
df = pd.read_csv(StringIO(data))

# Remove spaces from column names.
df.columns = [x.strip() for x in df.columns]

# Split the data into an nlx dataframe and a ttl dataframe.
nlx = df[['nlxTTL', 'nlxTime']].reset_index()
ttl = df[['ttlState', 'ttlTime']].reset_index()

# Merge the dataframes back together based on their timestamps.
# Use an outer join so missing data gets filled with NaNs instead
# of just dropping the rows.
merged_df = nlx.merge(ttl, left_on='nlxTime', right_on='ttlTime', how='outer')

# Get back to the original set of columns
merged_df = merged_df[df.columns]

# Print out the results.
print(merged_df)

这将产生以下输出

   nlxTTL  ttlState  nlxTime  ttlTime
0     0.0       0.0   1000.0   1000.0
1     1.0       1.0   2000.0   2000.0
2     0.0       NaN   3000.0      NaN
3     1.0       1.0   4000.0   4000.0
4     0.0       NaN   5000.0      NaN
5     1.0       1.0   6000.0   6000.0
6     0.0       0.0   7000.0   7000.0
7     1.0       1.0   8000.0   8000.0
8     NaN       0.0      NaN   9000.0
9     NaN       1.0      NaN  10000.0

您会注意到,它用NaN值填充删除的值,因为我们正在进行外部连接。如果不需要这样做,请将how='outer'参数更改为how='inner'以执行内部联接。这将只保留在该时间戳上同时具有nlx和ttl响应的记录

相关问题 更多 >