简体   繁体   中英

Fill one column with value of another column in pandas DataFrame

my dataframe looks like this:

ID    ADDRESS                   PRICE    LOCATION
1     NEW YORK, BROOKLYN, 1      500     NEW YORK
2     LONDON, LONDON, 2          400     " "
3     City of MANCHESTER, 3      200     " "
.
.

I would like to fill the " " with the value from address. I tried something like this:

i = 2008
for addrs, loc in zip(addr[2008:].ADDRSS, addr[2008:].LOCATION):
     if addrs.find('NEW YORK') != -1:
          addr[i].LOCATION = 'NEW YORK'
     if addrs.find('LONDON') != -1:
          addr[i].LOCATION = 'LONDON'
     if addrs.find('PRAGUE') != -1:
          addr[i].LOCATION = 'PRAGUE'
     i = i + 1
.
.
.

The location didnt fill in from certain row, so thats why there is the addr[2008:]. The locations dont change so I can have them written like that. This code returns KeyError. I dont really know, what is wrong with this, can anybody help?

EDIT:

Expected output should be this:

ID    ADDRESS                   PRICE    LOCATION
1     NEW YORK, BROOKLYN, 1      500     NEW YORK
2     LONDON, LONDON, 2          400     LONDON
3     City of MANCHESTER, 3      200     MANCHESTER
.
.

The catch is that in the address column, there is a variety of options how the city is mentioned, so just an easy split with , wont work.

你可以这样做:

df.loc[df['LOCATION'].eq(' '), 'LOCATION'] = df['ADDRESS']

As I understand it, if there is a " "sign in the LOCATIONS column, it will be filled with the country information in the ADDRESS column.

The following code will be useful for this.

addr['LOCATION'].apply(lambda x: x if x != " " else addr['ADDRESS'].split(sep=',')[0])

I hope it works for you.

extending the other answer above

df.loc[df['LOCATION'].eq(' '), 'LOCATION'] = df.loc[df['LOCATION'].eq(' '), 'ADDRESS'].str.extract('(NEW YORK|LONDON|MANCHESTER)').values

for more Citys, you need to adapt the regex string of course

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