Home > Enterprise >  Obtain column based on row value
Obtain column based on row value

Time:09-11

I have the following table:

       A  B  C  D  E  F  G  H
A
B
C
D
E
F
G
H
Value  1  3  4  1  4  3  3  4 

How could I filter columns where Value is greater than 3?

CodePudding user response:

The structure of your table is not clear.
Anyway, you can use pandas.DataFrame.loc to filter a column/dataframe.

Use the code below if df matches your table :

from io import StringIO
import pandas as pd

s = StringIO("""Letter  Value
A   1
B   3
C   4
D   1
E   4
F   3
G   3
H   4
""")

df = pd.read_csv(s, delimiter='\t')

print(df.loc[df['Value']>3])
  Letter  Value
2      C      4
4      E      4
7      H      4

CodePudding user response:

You can use boolean indexing:

df.loc[:, df.loc['Value'].astype(int).gt(3)]

NB. Converting to integer/numeric as a safety. If non numeric values are present in the columns, this would indeed force an object type.

output:

       C  E  H
A      x  x  x
B      x  x  x
C      x  x  x
D      x  x  x
E      x  x  x
F      x  x  x
G      x  x  x
H      x  x  x
Value  4  4  4
  • Related