for loop on a dataframe variables in python

To loop through variables in a pandas dataframe, you can use the iteritems() function to iterate through the columns of the dataframe. Here is an example code snippet:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})

# loop through the variables in the dataframe
for col_name, col_data in df.iteritems():
    print(col_name)
    print(col_data)
246 chars
10 lines

In this example, the iteritems() function returns a tuple with the column name and the column data. Then, the loop prints the name of the column and the data contained in the column.

You can modify the loop to perform different operations on each variable or to filter the variables based on their names or data types.

gistlibby LogSnag