简体   繁体   中英

Iterating over Dataframe columns

I have a dataframe with a bunch of columns looks something like this

City1, City2, Cord_City1
LA     LA     10,12
LA     SF     10,12
LA     SD     10,12
SF     LA     11,13
SD     SF     12,14  

I have the values for all of the coordinates for city 1 and all of the cities in city 2 are contained inside city 1

Now I want to make a column of coordinates City 2 using the coordinates I already have

So the new table should look something like this (SF coord = 11,13 and SD Coord = 12,14)

City1, City2, Cord_City1, Cord_City2
LA     LA     10,12       10,12
LA     SF     10,12       11,13
LA     SD     10,12       12,14
SF     LA     11,13       10,12
SD     SF     12,14       11,13

How would I iterate over the city2 column then over the city 1 column and return the coordinates from cord_city1?

use City1 and Cord_City1 as dictionary such that:

key = Cord and Value = City

dict_cords = pd.Series(df.Cord_City1.values,index=df.City1).to_dict()

you get:

{'LA': '10,12', 'SF': '11,13', 'SD': '12,14'}

create Cord_City2:

df['Cord_City2'] = df['City2'].map(dict_cords)

and you get the desired result:

    City1   City2   Cord_City1  Cord_City2
0   LA       LA      10,12      10,12
1   LA       SF      10,12      11,13
2   LA       SD      10,12      12,14
3   SF       LA      11,13      10,12
4   SD       SF      12,14      11,13

We can do one-line

df['CordCity2'] = df.City2.map(dict(zip(df.City1,df.CordCity1)))
df
Out[223]: 
  City1 City2 CordCity1 CordCity2
0    LA    LA     10,12     10,12
1    LA    SF     10,12     11,13
2    LA    SD     10,12     12,14
3    SF    LA     11,13     10,12
4    SD    SF     12,14     11,13

This should do it:

df.merge(df[['City1','Cord_City1']].drop_duplicates().rename(columns = {'Cord_City1':'Cord_City2','City1':'City2'}),
                                  left_on = 'City2', right_on = 'City2', how = 'left')


City1   City2   Cord_City1  Cord_City2
0   LA  LA  10,12   10,12
1   LA  SF  10,12   11,13
2   LA  SD  10,12   12,14
3   SF  LA  11,13   10,12
4   SD  SF  12,14   11,13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM