Home > Software design >  How to get the content of every cell in a row from a dataframe using itertuples() on Python? Pandas
How to get the content of every cell in a row from a dataframe using itertuples() on Python? Pandas

Time:01-28

Let's suppose I have the following df:

       0      0      1               1    2       2     3        3      4    4    5     5         
0  Fondo Oceano Cuerpo Cuerpo cangrejo Ojos Antenas Color Amarillo Pinzas None Puas None            
1  Fondo Oceano Cuerpo Cuerpo cangrejo Ojos Antenas Color Amarillo Pinzas None Puas Arena     
2  Fondo Oceano Cuerpo Cuerpo cangrejo Ojos Antenas Color Amarillo Pinzas None Puas Marron    
3  Fondo Oceano Cuerpo Cuerpo cangrejo Ojos Antenas Color Amarillo Pinzas None Puas Purpura    
4  Fondo Oceano Cuerpo Cuerpo cangrejo Ojos Antenas Color Amarillo Pinzas None Puas Verde    

I know I can merge .itertuples(index=False) and .iloc[[0]] this way to print the contents of each cell from that row:

for i in df.iloc[[0]].itertuples(index=False):
    print(i)

Output:

Pandas(_0='Fondo', _1='Oceano', _2='Cuerpo', _3='Cuerpo cangrejo', _4='Ojos', _5='Antenas', _6='Color', _7='Amarillo', _8='Pinzas', _9='None', _10='Puas', _11='None')

But I don't know how could I improve the sentence above to get the following output for that particular row (i.e. 0):

Desired output:

Fondo

Oceano

Cuerpo

Cuerpo cangrejo

Ojos

Antenas

Color

Amarillo

Pinzas

None

Puas

None

Any ideas?

CodePudding user response:

By slicing with double square brackets you get a (2D) DataFrame.

It looks like you're trying to loop in 1D. You should use Series.iteritems:

for _, e in df.iloc[0].iteritems():
    print(e)

output:

Fondo
Oceano
Cuerpo
Cuerpo
cangrejo
...
  •  Tags:  
  • Related