[英]pandas split columns using length
如何使用長度拆分 pandas 中的列。 str.split
需要使用分隔符。 我可以在每列上使用兩次切片,如下所示
for i, col in enumerate(cols):
df[f'mn{i}'] = df[col].str.split[1:]
df[col] = df[col].str.split[:1]
因此,在 pandas 中尋找更高效的內置 function 可以根據長度拆分許多列。
Dataframe
Col1 Col2 Col3
012021 012021 032021
012021 012021 032021
預期 output
Col1 Col2 Col3 Col4 Col5 Col6
01 01 03 2021 2021 2021
01 01 03 2021 2021 2021
嘗試使用str.extract
和concat
:
pd.concat([df[x].str.extract('(\d{2})(\d{4})').add_prefix(f'{x}_')
for x in df],
axis=1)
Output:
Col1_0 Col1_1 Col2_0 Col2_1 Col3_0 Col3_1
0 01 2021 01 2021 03 2021
1 01 2021 01 2021 03 2021
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.