首页 > 解决方案 > 如何在数据框中找到具有相同值(字符串)的列的两个连续行并在它们之间添加更多行?

问题描述

如何在数据框中找到具有相同值(字符串)的列的两个连续行并在它们之间添加更多行?数据框具有时间序列索引。

例如:如果 A 列具有相同值的 2 个连续行的索引是下午 5:30 和下午 6:00,我想在 2 行之间添加更多行,即增量为 1 分钟。下午 5 点 01 分,下午 5 点 02 分.....下午 5 点 59 分。

标签: pythonpandasdataframetime-series

解决方案


这是一种方法:

import pandas as pd
import numpy as np

# say this is your df:
df = pd.DataFrame(index=pd.date_range(periods=6, 
                                      start='12:00', end='12:30'))
df['A'] = [1,1,2,3,3,4]
print(df)

#                         A
#2019-05-09 12:00:00      1
#2019-05-09 12:06:00      1
#2019-05-09 12:12:00      2
#2019-05-09 12:18:00      3
#2019-05-09 12:24:00      3
#2019-05-09 12:30:00      4

# find positions with same value
ends_idx = np.arange(df.shape[0])[
    (df['A'].diff() == 0).values]

print(ends_idx)
# [1 4]

# create index with additional time stamps
old_index = df.index
new_index = sorted(np.unique(np.concatenate([
    pd.date_range(start=old_index[i-1], 
                  end=old_index[i], freq='min').values
    for i in ends_idx
] + [old_index.values])))

# create a new dataframe
new_df = pd.DataFrame(index=new_index)

# assign a default value
new_df['A'] = np.nan

# assign values from old dataframe
new_df.loc[old_index, 'A'] = df['A']
print(new_df)

#                       A
#2019-05-09 12:00:00  1.0
#2019-05-09 12:01:00  NaN
#2019-05-09 12:02:00  NaN
#2019-05-09 12:03:00  NaN
#2019-05-09 12:04:00  NaN
#2019-05-09 12:05:00  NaN
#2019-05-09 12:06:00  1.0
#2019-05-09 12:12:00  2.0
#2019-05-09 12:18:00  3.0
#2019-05-09 12:19:00  NaN
#2019-05-09 12:20:00  NaN
#2019-05-09 12:21:00  NaN
#2019-05-09 12:22:00  NaN
#2019-05-09 12:23:00  NaN
#2019-05-09 12:24:00  3.0
#2019-05-09 12:30:00  4.0

编辑:对于A中的字符串值,您可以将我们找到位置的部分替换为:

# find positions with same value
n = df.shape[0]
# place holders:
ends_idx = np.arange(n) 
same = np.array([False] * n)
# compare values explicitly
same[1:] = df['A'][1:].values == df['A'][:-1].values 
ends_idx = ends_idx[same]

推荐阅读