2

I have a simple question. I have a small dataframe:

      Column1  Column2  Column3
Row1        0        4        6
Row2        1        3        5
Row3        0        4        2

I need to only print out only Column1 and Column2 only if Column1 equals 1:

      Column1  Column2
Row2        1        3

I have this piece of code that I am stuck at:

col=[col for col in df.columns if col=="Column1" or col=="Column2"]
print(loc[:,col])

This is printing out the result such that we are having Column1 and Column2 with all the values.

      Column1  Column2
Row1        0        4
Row2        1        3
Row3        0        4

How can I incorporate the condition such that Column1==1?

Thanks!

0

3 Answers 3

3

Two of the easiest ways to do this are to use .loc with boolean indexing and query with column filtering:

Method 1:

df.loc[df.Column1 == 1,['Column1','Column2']]

Output:

      Column1  Column2
Row2        1        3

Method 2:

df.query('Column1 == 1')[['Column1','Column2']]

Output:

      Column1  Column2
Row2        1        3
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the namedtuple of python to do this. Namedtuple creates individual single classes to represent the values. It is worth remembering that classes have only values and no method.

would be like this:

from collections import namedtuple

Value = namedtuple('Value', ['column', 'line', 'value'])

examples = [Value(column, line, value) for column in range(3)
                                       for line in range(2)
                                       for value in range(2)]

>>> examples
[Value(column=0, line=0, value=0), Value(column=0, line=0, value=1), Value(column=0, line=1, value=0), Value(column=0, line=1, value=1), Value(column=1, line=0, value=0), Value(column=1, line=0, value=1), Value(column=1, line=1, value=0), Value(column=1, line=1, value=1), Value(column=2, line=0, value=0), Value(column=2, line=0, value=1), Value(column=2, line=1, value=0), Value(column=2, line=1, value=1)]

for _ in examples:
  if _.column == 1:
    print('Line: %s' % _.line, 'Value: %s' % _.value)

Line: 0 Value: 0
Line: 0 Value: 1
Line: 1 Value: 0
Line: 1 Value: 1

Comments

2

You can use a conditional index:

>>> df[df['Column1'] == 1]
      Column1  Column2  Column3
Row2        1        3        5

Then just select the columns you want:

>>> df[df['Column1'] == 1][['Column1', 'Column2']]
      Column1  Column2
Row2        1        3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.