簡體   English   中英

如何根據其他列值填充列?

[英]How to fill columns based on other column values?

我有一個 df,我想在其中查詢郵政編碼以匹配地址和城市。

Postalcodestring
1181
1055
8547

我為此使用了 nomi.query_postal_code('n') 。 因此,當輸入以下表格時,將顯示:

postal_code                1181
country_code                 NL
place_name           Amstelveen
state_name        Noord-Holland
state_code                    7
county_name          Amstelveen
county_code                 362
community_name              NaN
community_code              NaN
latitude                  52.31
longitude                4.8631
accuracy                      6
Name: 0, dtype: object

我想為“City1”和“Country1”列填寫城市和國家,以填寫郵政編碼的每一行。 當郵政編碼為 n/a 時,我希望行 City1 和 Country1 也為 N/A!

我嘗試了以下代碼:

#NL
for i, row in df.iterrows():
    df.loc[i, 'City1'] = nomi.query_postal_code(df['Postalcodestring'][i])[2]    
#DE
for i, row in df.iterrows():
    df.loc[i,'City2'] = nomi2.query_postal_code(df['Postalcodestring'][i])[2]

#NLCountry
for i, row in df.iterrows():
    df.loc[i,['Country1']] = nomi.query_postal_code(df['Postalcodestring'][i])[1]    
#DECountry
for i, row in df.iterrows():
    df.loc[i,'Country2'] = nomi2.query_postal_code(df['Postalcodestring'][i])[1]

但是,收到以下錯誤:

ValueError                                Traceback (most recent call last)
<ipython-input-80-d0d96a6ea61b> in <module>
     67 #NL
     68 for i, row in df.iterrows():
---> 69     df.loc[i, 'City1'] = nomi.query_postal_code(df['Postalcodestring'][i])[2]
     70 #DE
     71 for i, row in df.iterrows():
ValueError: DataFrame constructor not properly called!

所需的 output:

Postalcodestring   City1 
1181               Amstelveen
1055               Amsterdam
8547               NaN

請幫忙 !

您應該使用df.apply方法:

import pandas as pd
import pgeocode

df = pd.DataFrame({'Postalcodestring': ['1181', '1055', '8547']})
nomi = pgeocode.Nominatim('nl')

df['City1'] = df['Postalcodestring'].apply(lambda code: nomi.query_postal_code(code)['place_name'])

當您可以使用df[COL].apply代替時,實際上不需要單獨遍歷行,將 function 應用於列的每一行。 正如您在我的代碼中看到的,您將 function 作為參數傳遞給 apply 方法。 In my case, I use a lambda function to define the function in the same expression, but you could just aswell define the function explicitly outside:

def get_city(code):
    return nomi.query_postal_code(code)['place_name']

df['City1'] = df['Postalcodestring'].apply(get_city)

只是旁注:不要因為我的代碼不使用循環而感到困惑。 當然需要循環來對多行執行這樣的操作。 只是df.apply在內部進行循環,所以你不需要自己做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM