如何选择与某一行匹配的行

时间:2017-01-31 09:59:05

标签: python pandas dataframe

我有一个数据框

A B
a0 1
b0 1
c0 2
a1 3 
b1 4
b2 3

首先,如果df.A以"a"开头,我想剪切df

df[df.A.str.startswith("a")]

A B
a0 1
a1 3 

因此我想像下面那样削减df。

sub1

A B
a0 1
b0 1
c0 2

sub2

A B
a1 3 
b1 4
b2 3

然后我想提取列B号与列A以"a"开头的行匹配的行

sub1

A B
a0 1
b0 1

sub2

A B
a1 3  
b2 3

然后追加。

result

A B
a0 1
b0 1
a1 3
b2 3

如何像这样剪切和追加df

我尝试了cut方法,但效果不佳。

1 个答案:

答案 0 :(得分:1)

我认为您可以使用wheremask一起创建NaN,其中B值由ffill向前填充:

注意必须以a开头的必要值必须在每个组中首先使用ffill

print (df.B.where(df.A.str.startswith("a")))
0    1.0
1    NaN
2    NaN
3    3.0
4    NaN
5    NaN
Name: B, dtype: float64


print (df.B.where(df.A.str.startswith("a")).ffill())
0    1.0
1    1.0
2    1.0
3    3.0
4    3.0
5    3.0
Name: B, dtype: float64

df = df[df.B == df.B.where(df.A.str.startswith("a")).ffill()]
print (df)
    A  B
0  a0  1
1  b0  1
3  a1  3
5  b2  3