logo_learn_stats

Tips on how to Iterate Over Columns in Pandas DataFrame

Posted on
banner 336x280

You’ll worth refer to plain syntax to iterate over columns in a pandas DataFrame:

for identify, values in df.iteritems():
  print(values)

Refer to examples display how one can worth this syntax in apply with refer to pandas DataFrame:

banner 468x60
import pandas as pd

#build DataFrame
df = pd.DataFrame({'issues': [25, 12, 15, 14, 19],
                   'assists': [5, 7, 7, 9, 12],
                   'rebounds': [11, 8, 10, 6, 6]})

#view DataFrame
df

	issues	assists	rebounds
0	25	5	11
1	12	7	8
2	15	7	10
3	14	9	6
4	19	12	6

Instance 1: Iterate Over All Columns in DataFrame

Refer to code presentations how one can iterate over each column in a pandas DataFrame:

for identify, values in df.iteritems():
  print(values)

0    25
1    12
2    15
3    14
4    19
Title: issues, dtype: int64
0     5
1     7
2     7
3     9
4    12
Title: assists, dtype: int64
0    11
1     8
2    10
3     6
4     6
Title: rebounds, dtype: int64

We will be able to additionally worth refer to syntax to iterate over each column and print simply the column names:

for identify, values in df.iteritems():
  print(identify)

issues
assists
rebounds

Instance 2: Iterate Over Particular Columns

Refer to syntax presentations how one can iterate over particular columns in a pandas DataFrame:

for identify, values in df[['points', 'rebounds']].iteritems():
  print(values)

0    25
1    12
2    15
3    14
4    19
Title: issues, dtype: int64
0    11
1     8
2    10
3     6
4     6
Title: rebounds, dtype: int64

We will be able to additionally worth refer to syntax to iterate over a territory of particular columns:

for identify, values in df.iloc[:, 0:2].iteritems():
  print(values)

0    25
1    12
2    15
3    14
4    19
Title: issues, dtype: int64
0     5
1     7
2     7
3     9
4    12
Title: assists, dtype: int64

You’ll in finding your complete documentation for the iteritems() serve as right here.

Backup Assets

Tips on how to Follow a Serve as to Decided on Columns in Pandas
Tips on how to Trade the Sequence of Columns in Pandas
Tips on how to Shed Columns through Index in Pandas

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *