python - 如何在数据框中找到具有相同值(字符串)的列的两个连续行并在它们之间添加更多行?
问题描述
如何在数据框中找到具有相同值(字符串)的列的两个连续行并在它们之间添加更多行?数据框具有时间序列索引。
例如:如果 A 列具有相同值的 2 个连续行的索引是下午 5:30 和下午 6:00,我想在 2 行之间添加更多行,即增量为 1 分钟。下午 5 点 01 分,下午 5 点 02 分.....下午 5 点 59 分。
解决方案
这是一种方法:
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]
推荐阅读
- sql - 如果表格从“G”开始,则删除表中整个列值的第一个“G”字符
- java - 一次只解析 JSON 中的特定字段
- python - TypeError:解码为str:需要一个类似字节的对象,发现元组SQLite,Python
- nginx - 位置为 /kibana 的 nginx kibana 反向代理问题
- r - 如何将字符串的函数参数插入到 dplyr::filter() 中的 abs() 中?
- sql - 在postgresql中将值插入到大整数范围内的列中
- java - 当我使用 StAX 获得“非法字符((CTRL-CHAR,代码 26))”时,我可以获得字符串标签值吗?
- kubernetes-helm - 是否可以在 Helm 聊天之外定义模板?
- ldap - LDAP 用户密码一直过期
- google-sheets - 将列设置为等于 Google 表格中某行的负数