python - 选择一列中的特定值并从 pandas 的另一列中获取之前/之后的 n 行

标签 python pandas dataframe

我有一个包含两列的数据框:试验类型和直径。我需要找到 TrialType == 'start' 的所有位置,然后获取这些位置之前和之后的所有 2500 行的直径(包括这些位置)。我尝试了以下方法:

idx = df.loc(df[df['trialType']=='start'])
df.iloc[idx - 2500 : idx + 2500]

我的目标是拥有一个仅包含那些相关行的数据框(每个“开始”试验之间有 2500 行)。下面是一个行数少得多的示例:

trialType diameter
start     3.15
          3.17
          3.18
start     3.14
          3.13
          3.13

最佳答案

有趣。

关于:

idx = df.loc[lambda x: x['trialType']=='start'].index

rows = df.loc[idx]

a = df.shift( 2500).loc[idx]
b = df.shift(-2500).loc[idx]

然后您可以按照您认为最好的方式组合它们。

pd.concat([a,rows,b])

你还可以这样做:


idx = df.loc[lambda x: x['trialType']=='start'].index
df.loc[lambda x: (x.index-2500).isin(idx) 
               ¦  x.index.isin(idx) 
               ¦ (x.index+2500).isin(idx)]

但是如果你的索引不是连续的(0,1,2,3等),你必须修改上面的代码

关于python - 选择一列中的特定值并从 pandas 的另一列中获取之前/之后的 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69922459/

相关文章:

Python 多处理脚本看似无误地卡住

python - 根据另一个数据框的列值过滤数据框

python - 使 python lambda func 在 Pandas Dataframe 中的 apply 方法内工作

python - 如何在 python 中使用分组进行聚合

r - 快速滚动平均值 + 汇总

Python 有没有办法使用装饰器包装类的函数?

Python:字典和字数统计

python - 如何使用 Python 将多个 Excel 工作表从网站下载到 Pandas DataFrame 中

python - matplotlib 图例 : How to specify font weight?

python - 将列表附加到单个 pandas 数据框单元格中