![](/img/trans.png)
[英]Pandas - How to split a string column into several columns, by the index of specific characters?
[英]How to split a column into multiple columns with the index of the string with pandas?
我有數據框,它看起來像:
df = pd.DataFrame({"a":["sea001", "seac002"]})
print(df)
a
0 sea001
1 seac002
我想將一列分為兩列,列“ b”中的前三個字符,列“ c”中的其余字符
a b c
0 sea001 sea 001
1 seac002 sea c002
我想使用df.a.str.split(),但是我沒有選擇在索引后面分隔單詞。 我該如何巧妙地做到這一點?
您可以將str
與切片語義一起使用來執行此操作:
In [102]:
df['b'], df['c'] = df['a'].str[:3], df['a'].str[3:]
df
Out[102]:
a b c
0 sea001 sea 001
1 seac002 sea c002
嘗試.str.extract()方法:
In [104]: df[['b','c']] = df.a.str.extract(r'(.{3})(.*)', expand=True)
In [105]: df
Out[105]:
a b c
0 sea001 sea 001
1 seac002 sea c002
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.