我有一個這樣的熊貓資料集:
import pandas as pd
data = {'id': ['001', '002', '003','004'],
'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA",
"1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA",
"William N. Barnard\\n145 S. Durbin\\nCasper, WY 82601\\nUSA",
"215 S 11th ST"],
'locality': [None, None, None,'Laramie'],
'region': [None, None, None, 'WY'],
'Zipcode': [None, None, None, '87656'],
'Country': [None, None, None, 'US']
}
df = pd.DataFrame(data)
我試圖用新行拆分地址列,但是因為它有兩個 \ 后跟 n。我做不到。請幫助我將 \n 從地址中拆分出來并將其決議為地區郵政編碼和國家/地區。
樣本輸出:
id address locality region Zipcode Country
1 290 Valley Dr. Casper WY 82604 USA
2 1180 Shelard Tower Minneapolis MN 55426 USA
3 145 S. Durbin Casper WY 82601 USA
4 215 S 11th ST Laramie WY 87656 US
我嘗試了使用 split 命令拆分 \n 的不同方法,但它給了我額外的 \。我正在嘗試將其保存在 pandas 資料框中,以便進行進一步分析。我是 python 的新手,任何幫助將不勝感激。
謝謝
uj5u.com熱心網友回復:
這是一種使用extract而不是拆分和update就地的方法:
df.update(df['address'].str.extract(r'([^,] )(?:,\s(\w )\s*(\d )\\n(\w ))?$')
.set_axis(["address", "region", "Zipcode", "Country"], axis=1)
)
df['name'] = pd.NA
df.update(df['address'].str.extract(r'(?:(.*?)\\n)?(.*)\\n(. )')
.set_axis(['name', 'address', 'locality'], axis=1)
)
輸出:
id address locality region Zipcode Country name
0 001 290 Valley Dr. Casper WY 82604 USA William J. Clare
1 002 1180 Shelard Tower Minneapolis MN 55426 USA <NA>
2 003 145 S. Durbin Casper WY 82601 USA William N. Barnard
3 004 215 S 11th ST Laramie WY 87656 US <NA>
正則運算式演示
uj5u.com熱心網友回復:
第二行沒有名稱,因此可能會引起一些麻煩。請檢查您的示例是否正確。
鑒于你的 df 是這樣的:
data = {'id': ['001', '002', '003','004'],
'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA",
"name\\n1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA",
"William N. Barnard\\n145 S. Durbin\\nCasper, WY 82601\\nUSA",
"215 S 11th ST"],
'locality': [None, None, None,'Laramie'],
'region': [None, None, None, 'WY'],
'Zipcode': [None, None, None, '87656'],
'Country': [None, None, None, 'US']
}
df = pd.DataFrame(data)
您可以創建過濾條件:
cond = df[["locality", "region", "Zipcode", "Country"]].isna()
然后split與expand=True
df.loc[cond.all(axis=1)].address.str.split(r"\\n", expand=True)
0 William J. Clare 290 Valley Dr. Casper, WY 82604 USA
1 name 1180 Shelard Tower Minneapolis, MN 55426 USA
2 William N. Barnard 145 S. Durbin Casper, WY 82601 USA
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/518019.html
上一篇:在多個檔案中搜索單詞的最有效方法
