简体   繁体   中英

How to Iterate on dataframe columns

I have a little problem with my code. I would like to create a "for" cycle all over dataframe columns. My solution has a static list, i tried to create a dynamic one putting "df_list_cols= df.shape[1]" but obviusly it cannot iterate on an Int object. Any ideas to create a dynamic solution?

My solution above, Thank you in advance!

df_list = [0,1,2,3,4]
for i in df_list_cols:
    do stuff

Iterating columns

You are close. The way the in operator is defined for Pandas dataframes, iterating a pd.DataFrame object is equivalent to iterating over its columns:

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]})

for col in df:
    print(col)
# A
# B
# C

Applying functions to each column

In many cases, you may wish to use pd.DataFrame.apply to apply the same function to each column:

df = df.apply(lambda x: x*2)

print(df)
#    A  B   C
# 0  2  6  10
# 1  4  8  12

The equivalent if you have a different function for each column is pd.DataFrame.transform :

df = df.transform({'A': lambda x: x*2, 'B': lambda x: x*3, 'C': lambda x: x*4})

You can iterate over df.columns :

df.columns gives you a list of the columns of the dataframe.

In [222]: df.columns.tolist()
Out[222]: ['A', 'B', 'C']

In [218]: for i in df.columns:
     ...:     print(i)
     ...:     ## do your stuff
A
B
C

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