我需要將郵政編碼(僅郵政編碼)提取到一個新列中以進行進一步分析。我主要在資料清理階段使用熊貓。我之前嘗試使用此代碼:
import pandas as pd
df_participant = pd.read_csv('https://storage.googleapis.com/dqlab-dataset/dqthon-participants.csv')
df_participant['postal_code'] = df_participant['address'].str.extract(r'([0-9]\d )')
print (df_participant[['address','postal_code']].head())
但它沒有用
這是輸出:

任何幫助將不勝感激!謝謝
uj5u.com熱心網友回復:
您可以使用.str.findall方法查找地址欄位中的所有數字,然后將最后一個值作為郵政編碼。
這是一個例子:
資料:
customer address
0 shovon 1234 56th St, Bham, AL 35222
1 arsho 4th Ave, Dever, NY 25699
2 arshovon 1245 apt 9 69th St, Rio, FL 54444
3 rahman this address has no number
代碼:
import pandas as pd
data = {
"customer": [
"shovon", "arsho", "arshovon", "rahman"
],
"address": [
"1234 56th St, Bham, AL 35222",
"4th Ave, Dever, NY 25699",
"1245 apt 9 69th St, Rio, FL 54444",
"this address has no number"
]
}
df = pd.DataFrame(data)
df['postal_code'] = df['address'].str.findall(r'([0-9]\d )').apply(
lambda x: x[-1] if len(x) >= 1 else '')
print(df)
輸出:
customer address postal_code
0 shovon 1234 56th St, Bham, AL 35222 35222
1 arsho 4th Ave, Dever, NY 25699 25699
2 arshovon 1245 apt 9 69th St, Rio, FL 54444 54444
3 rahman this address has no number
解釋:
這將搜索地址欄位中的每個號碼組并將最后一個號碼設定為郵政編碼。如果地址欄位中沒有數字,它將設定一個空字串作為郵政編碼。
參考:
- 關于 findall 方法的 Pandas 檔案
uj5u.com熱心網友回復:
和str.extract
df_participant['postal_code'] = df_participant['address'].str.extract(r'(\d{5})')
#OR if the length of the postal code changes, just make it \d combined with "$"
df_participant['postal_code'] = df_participant['address'].str.extract(r'(\d )$')
但你在這里不需要它。只需取字串的最后 5 位數字,因為郵政編碼總是在末尾。
df_participant['postal_code'] = df_participant['address'].str[-5:]
uj5u.com熱心網友回復:
如果所有郵政編碼都是 5 個字符長,那么以下可能會有所幫助。
改變
df_participant['postal_code'] = df_participant['address'].str.extract(r'([0-9]\d )')
到
df_participant['postal_code'] = df_participant['address'].str[-5::]
我最后收到的輸出
address postal_code
0 Gg. Monginsidi No. 08\nMedan, Aceh 80734 80734
1 Gg. Rajawali Timur No. 7\nPrabumulih, MA 09434 09434
2 Jalan Kebonjati No. 0\nAmbon, SS 57739 57739
3 Jl. Yos Sudarso No. 109\nLubuklinggau, SR 76156 76156
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/479729.html
上一篇:添加串列列
下一篇:熊貓每周計算重復值
