python - 如何选择值以 pandas 中的特定值开头和结尾的行?

标签 python pandas dataframe indexing series

我有一个 pandas DataFrame,我想选择值以特定值开头和结尾的行。例如,在 dataFrame df 中,我想选择列 state1 开头和结尾的行。即 2 5 8 10 行。并输出两个数据帧。

import pandas as pd

data = [['a1',0,'low'],
        ['a1',0,'low'],
        ['a1',1,'high'],
        ['a1',1,'low'],
        ['a1',1,'low'],
        ['a1',1,'high'],
        ['a1',0,'low'],
        ['a1',0,'low'],
        ['a2',1,'high'],
        ['a2',1,'low'],
        ['a2',1,'low'],
        ['a2',0,'low'],
        ['a2',0,'low']]

df = pd.DataFrame(data,columns=['id','state','type'])
df

输出:

    id  state   type
0   a1     0    low
1   a1     0    low
2   a1     1    high
3   a1     1    low
4   a1     1    low
5   a1     1    high
6   a1     0    low
7   a1     0    low
8   a2     1    high
9   a2     1    low
10  a2     1    low
11  a2     0    low
12  a2     0    low

最后,我想要两个数据框,如下所示:

df1

    id  state   type  code
2   a1     1    high  start
8   a2     1    high  start

df2

    id  state   type  code
5   a1     1    high  end
10  a2     1    low   end

最佳答案

您可以使用 bool 掩码来选择所需的行:

m1 = df['state'].diff() == 1
m2 = df['state'].shift(-1).diff() == -1

res  = df[m1 | m2]

print(res)

    id  state  type
2   a1      1  high
5   a1      1  high
8   a2      1  high
10  a2      1   low

您可以使用列表理解将其拆分为 2 个数据帧:

df1, df2 = [res.iloc[i::2] for i in range(int(len(res.index)/2))]

print(df1, df2, sep='\n\n')

   id  state  type
2  a1      1  high
8  a2      1  high

    id  state  type
5   a1      1  high
10  a2      1   low

关于python - 如何选择值以 pandas 中的特定值开头和结尾的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51571121/

相关文章:

python - 如何将字典作为一行添加到 DataFrame 中?

python - 根据列值等于 None 的条件删除 DataFrame 中的行

python - 从 Pandas Dataframe 获取一个或多个列值作为列表

python - Spyne:输入参数具有不同命名空间的请求

python - 与sympy逐步分化

python - Pathos 多处理池 CPickle 错误

python - Pandas ,将多索引之一移动到多列索引之上

python - 将 Pandas 数据帧转换为 csv 字符串

Python int 太大而无法转换为 C long - 绘制 Pandas 日期

r - 如何将最佳拟合线、方程、R^2 和 p 值添加到 R 中的绘图中?