Home > Mobile >  How to loops to column in dataframe in pandas python
How to loops to column in dataframe in pandas python

Time:12-24

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!

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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'])

CodePudding user response:

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 

CodePudding user response:

You can use:

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