python - 在数据框中更改某些条件时获取行
问题描述
我正在寻找一种解决方案来在某些条件发生变化时获得行。
这是我的数据框的示例。
ts fdw time_stamp
0 n [0, 0] 1635211605896
1 n [0, 0] 1635211606896
2 l [0, 0] 1635211607896
3 l [0, 0] 1635211608896
4 l [0, 0] 1635211609896
5 l [0, 0] 1635211609896
6 n [0, 0] 1635211609896
在上面的数据框中,我想在列名ts
更改时提取行,例如n
tol
或l
to n
。
这是我的预期输出。
ts fdw time_stamp
1 n [0, 0] 1635211606896
2 l [0, 0] 1635211607896
5 l [0, 0] 1635211609896
6 n [0, 0] 1635211609896
解决方案
import pandas
import pdrle
# Data
df = pandas.DataFrame({"ts": ["n", "n", "l", "l", "l", "l", "n"]})
df["val"] = [1, 2, 3, 4, 5, 6, 7]
# Get runs of consecutive lengths in ts
rle = pdrle.encode(df.ts)
grp = rle.index.repeat(rle.runs)
# Get first and last row of each runs
ans = (
df.groupby(grp)
.apply(lambda x: x.iloc[[-1], :] if len(x) == 1 else x.iloc[[0, -1], :])
.droplevel(0)
)
# If the first and last group have more than two rows, remove duplicates
if rle.runs.iloc[0] > 1:
ans.drop(ans.head(1).index, inplace=True)
if rle.runs.iloc[-1] > 1:
ans.drop(ans.tail(1).index, inplace=True)
ans
# ts val
# 1 n 2
# 2 l 3
# 5 l 6
# 6 n 7
推荐阅读
- git - 如何使用 git 进行 grep 但限制某些提交?
- c# - 将工具提示添加到 DataGridTextColumn WPF
- javascript - 使用 Node.js 进行名称实体识别或文本提取
- android - 如何使用 android.biometric 包中的本地化字符串?
- java - Java 8 - 如何在列表中找到最接近的名称
- javascript - Crypto JS相当于Java加密方法?
- python - 如何删除 TypeError: unhashable type: 'list' using pymongo
- javascript - 如何在 Lit 中正确实现 Bootstrap?
- apache-flink - Apache Flink - 匹配连续模式中具有不同值的字段
- javascript - npm 安装/discordjs 错误