简体   繁体   中英

Python: Printing out result from conditional for loop

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM