disney82231
disney82231

Reputation: 199

select columns with condition on dataframe

I have a dataframe:

    GPA1PP GPB1PP C D E  GPAB12PP
0
1
2
3

Now I want to select some columns

a_test=df.loc[:,df.columns.str.contains("A")]
b_test=df.loc[:,df.columns.str.contains("B")]

1. Both a_test and b_test have "GPAB12PP" columns but I want to it only appears in the a_test dataframe. How can I do?

2.

C D E columns not be selected. Can I use "minus" to select them?

For example in R

c_test=df[:,-c(1,2,6)]
print(c_test)
  C D E
0
1
2
3

Does python be the same?

Thanks

Upvotes: 0

Views: 80

Answers (1)

Moez Ben Jannet
Moez Ben Jannet

Reputation: 35

  1. for the first question you can use this:

    a_test=df.loc[:,df.columns.str.startswith("A")]
    b_test=df.loc[:,df.columns.str.startswith("B")]
    
  2. for the second question you can use this:

    c_test=df.loc[:,~(df.columns.str.contains('A') | df.columns.str.contains('B'))]
    

Upvotes: 2

Related Questions