[英]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:].位置没有从某行填写,所以这就是为什么有addr[2008:]。 The locations dont change so I can have them written like that.位置不会改变,所以我可以让它们这样写。 This code returns KeyError.此代码返回 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.据我了解,如果LOCATIONS栏有“”号,ADDRESS栏会填入国家信息。
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对于更多城市,您当然需要调整正则表达式字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.