[英]Splitting Pandas column into multiple columns without using str.split()
[英]How to split a column into two or multiple columns columns in python using either str.split or regex?
如何將此列拆分為 2 列或更多列。 我使用str.split('/',2)
進行拆分,但它只是刪除了 '/' 並沒有拆分為 2 列。
X |
---|
東行:6900 / 西行:7700 |
東行:7800 / 西行:8700 |
北界:5000 / 南界:4900 |
北界:7000 / 南界:9000 |
東行:4900 / 西行:9700 |
我想要的是:
第一方向 | 第二方向 |
---|---|
東界:6900 | 西行:7700 |
東行:7800 | 西行:8700 |
北界:5000 | 南行:4900 |
北界:7000 | 南行:9000 |
東界:4900 | 西行:9700 |
更好的是,如果我可以為四個基本方向設置四個列標題並用第一個表中的值填充它,例如:
北 | 南 | 東方 | 西方 |
---|---|---|---|
0 | 0 | 6900 | 7700 |
0 | 0 | 7800 | 8700 |
5000 | 4900 | 0 | 0 |
7000 | 4900 | 0 | 0 |
0 | 0 | 4900 | 9700 |
如果我正確閱讀了文檔,我相信這可以通過正則表達式模式來完成,但是有沒有一種有效的方法來簡潔地做到這一點?
這是使用的原始df: df = ['East Bound: 6900 / West Bound: 7700', 'East Bound: 7800 / West Bound: 8700', 'North Bound: 5000 / South Bound: 4900', 'North Bound: 7000 / South Bound: 9000', 'East Bound: 4900 / West Bound: 9700']
對於 Q1,您可以嘗試.str.split
df[['First Direction', 'Second direction']] = df['X'].str.split(' / ', expand=True)
print(df)
X First Direction Second direction
0 East Bound: 6900 / West Bound: 7700 East Bound: 6900 West Bound: 7700
1 East Bound: 7800 / West Bound: 8700 East Bound: 7800 West Bound: 8700
2 North Bound: 5000 / South Bound: 4900 North Bound: 5000 South Bound: 4900
3 North Bound: 7000 / South Bound: 9000 North Bound: 7000 South Bound: 9000
4 East Bound: 4900 / West Bound: 9700 East Bound: 4900 West Bound: 9700
對於 Q2,您可以嘗試將X
列轉換為字典,然后將該列分解為單獨的列
out = df['X'].apply(lambda x: dict([direction.split(':') for direction in x.split(' / ')])).apply(pd.Series)
print(out)
East Bound West Bound North Bound South Bound
0 6900 7700 NaN NaN
1 7800 8700 NaN NaN
2 NaN NaN 5000 4900
3 NaN NaN 7000 9000
4 4900 9700 NaN NaN
我的方法是使用具有特定模式的Series.str.extractall
來獲取方向和數量,將數量轉換為合適的類型(我剛剛在這里使用整數),然后在適當的地方用零填充 pivot_table,例如:
out = (
df['X'].str.extractall(r'(?P<bound>North|South|West|East) (?:Bound): (?P<n>\d+)')
.astype({'n': int})
.pivot_table(index=pd.Grouper(level=0), columns='bound', values='n', fill_value=0)
)
這會給你:
bound East North South West
0 6900 0 0 7700
1 7800 0 0 8700
2 0 5000 4900 0
3 0 7000 9000 0
4 4900 0 0 9700
這會保留您的原始 DF ID...,因此您可以在某個時候合並/加入原始 DF。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.