Reputation: 77
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
Upvotes: 1
Views: 937
Reputation: 164623
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
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})
Upvotes: 2
Reputation: 34046
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
Upvotes: 1