Johnny Winter
Johnny Winter

Reputation: 11

How to loops to column in dataframe in pandas python

i am the newone with pandas, can i loops 2 column by position 1 and 3 in pandas dataframe below

import pandas as pd
inp = [("tokyo",8,7),("new york",6,8),("sydney",4,7),("london",12,7)]

df = pd.DataFrame(data=inp,columns=["a","b","d"])
print(df)

the result will bee like this

tokyo
7
new york
8
london
7

Thanks you for your help!

Upvotes: 1

Views: 60

Answers (5)

Muhammad Hassan
Muhammad Hassan

Reputation: 4229

You can use:

result = pd.Series(df.iloc[:, [0,2]].to_numpy().flatten())

Upvotes: 0

Kapil Musale
Kapil Musale

Reputation: 223

you can also do this way:

s=''
for index, row in df.iterrows():
    for key,value in row[:].items():
        s+=str(value)+" "
        if key=='b':
            pass
        else:
            print(s)
        s=''

output

tokyo 
7 
new york 
8 
sydney 
7 
london 
7 

Upvotes: 0

Jonathan Leon
Jonathan Leon

Reputation: 5648

If you don't have to loop, which is slower, you can do this

df[['a','d']].stack().reset_index(drop=True)

0       tokyo
1           7
2    new york
3           8
4      sydney
5           7
6      london
7           7
dtype: object

Upvotes: 1

Yok Chirathivat
Yok Chirathivat

Reputation: 116

Based on the output, what you can do is to loop through row, then use only selected columns

Example:

for i, row in df.iterrows():
    print(row['a'])
    print(row['d'])

Upvotes: 0

user17242583
user17242583

Reputation:

Try this:

lst = [x for y in zip(df['a'], df['d']) for x in y]

for item in lst:
    print(item)

Output:

tokyo
7
new york
8
sydney
7
london
7

Upvotes: 1

Related Questions