sinshi k s
sinshi k s

Reputation: 43

How to iterate over columns of dataframe using pandas

I have a data frame with eight columns, I wanted to iterate over each column and save each iteration data in the new variable. That is in the first iteration the first column values will remain the same and other columns value will change to None and save this data frame as a new one.In second iteration only the second column will hold the values other columns values changed to none and save as new data frame.So finally I will get an 8 data frame each will have only one column with values and other columns will hold the none value.

Upvotes: 1

Views: 979

Answers (1)

jezrael
jezrael

Reputation: 863116

Create dictionary of DataFrames by dict comprehension with reindex:

d = {x: df[[x]].reindex(columns=df.columns, fill_value=None) for x in df.columns}

Sample:

df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0]})

print (df)
   A  B  C  D
0  a  4  7  1
1  b  5  8  3
2  c  4  9  5
3  d  5  4  7
4  e  5  2  1
5  f  4  3  0

d = {x: df[[x]].reindex(columns=df.columns, fill_value=None) for x in df.columns}
#print (d)

print (d['A'])
   A   B   C   D
0  a NaN NaN NaN
1  b NaN NaN NaN
2  c NaN NaN NaN
3  d NaN NaN NaN
4  e NaN NaN NaN
5  f NaN NaN NaN

print (d['B'])
    A  B   C   D
0 NaN  4 NaN NaN
1 NaN  5 NaN NaN
2 NaN  4 NaN NaN
3 NaN  5 NaN NaN
4 NaN  5 NaN NaN
5 NaN  4 NaN NaN

Upvotes: 3

Related Questions