首页 > 解决方案 > 根据时间列中两个值之间的差异,将数据框中的每一行重复 N 次

问题描述

这里的时间分辨率是 1 秒,我想将其转换为 10 毫秒 这里的时间分辨率是 1 秒,我想将其转换为 10 毫秒

我想将该表中的时间分辨率从 1 秒更改为 10 毫秒,方法是减去每行之间的时间差乘以 100 并用该数字复制每一行。

例如: Row[n] 将重复 Time((n+1)-n)*100

当时间 = 2 秒(第三行)时,我们有某些值组合将保持不变,直到下一行时间 = 22 秒(第四行),所以这里的时间差异是 = 20 秒,基于我想要的(第三行) 重复 (20*100)

Row[2] 将重复 (22-2)*100

import pandas
import pandas as pd
# Dataframe from Excel sheet
excel_data_Outputs_df = pandas.read_excel(".xlsx", sheet_name='Outputs')
excel_data_Inputs_df = pandas.read_excel("xlsx", sheet_name='Inputs')
# Exclude All zeros columns
excel_data_Outputs_df = excel_data_Outputs_df.loc[:, (excel_data_Outputs_df != 0).any(axis=0)]
excel_data_Inputs_df = excel_data_Inputs_df.loc[:, (excel_data_Inputs_df != 0).any(axis=0)]

# Get the time difference and convert it 10ms resolution 
shifted=excel_data_Inputs_df.Time.shift(-1)
excel_data_Inputs_df.Time=(shifted-excel_data_Inputs_df.Time)*100
excel_data_Inputs_df['Time'] = excel_data_Inputs_df['Time'].fillna(0)
excel_data_Inputs_df.Time=excel_data_Inputs_df.Time.astype(int)

# Repeat Rows
newexcel_data_Inputs_df = excel_data_Inputs_df.loc[excel_data_Inputs_df.index.repeat(excel_data_Inputs_df.Time)].reset_index(drop=True)
print(newexcel_data_Inputs_df)
print(excel_data_Outputs_df)

标签: pythonpandasdataframe

解决方案


创建另一列来保存列值的差异,以供重复参考,然后执行如下操作:

import pandas as pd

# Sample dataframe
df = pd.DataFrame({
    'id' : ['a', 'b', 'c', 'd'],
    'col1' : [4, 5, 6, 7],
    'col2' : [3, 2, 4, 3]
    })

# Create a new column to hold the difference in column values 
# i.e. the number of times the row repition is required.
df['times'] = df.col1 - df.col2

# create the finalDf with repeated rows
finalDf = df.loc[df.index.repeat(df.times)].reset_index(drop=True)
print(finalDf.head())

语句的输出print如下所示:

  id  col1  col2  times
0  a     4     3      1
1  b     5     2      3
2  b     5     2      3
3  b     5     2      3
4  c     6     4      2

推荐阅读