[英]Pandas split column in multiple columns
我有一個 dataframe 在“標題”列中包含以下信息:
Title
2.1 text1 and bla bla 1
2.2 text2 bla 2
2.3 text3 other text 7
我嘗試按以下方式拆分列:
col1 Title col3
2.1 text1 and bla bla 1
2.2 text2 bla 2
2.3 text3 other text 7
我試圖遵循多種方式,但沒有成功。
您可以在空白處拆分以獲得x
。 然后取出列表的第一項並將它們分配給'col1'
和最后一項分配給'col3'
。 最后拿走剩下的,加入他們並將他們分配給'Title'
:
x = df['Title'].str.split()
df['col1'] = x.str[0]
df['col3'] = x.str[-1]
df['Title'] = x.apply(lambda y: ' '.join(y[1:-1]))
df = df[['col1','Title','col3']]
Output:
col1 Title col3
0 2.1 text1 and bla bla 1
1 2.2 text2 bla 2
2 2.3 text3 other text 7
@Neither 在評論中給出了更好的解決方案。
df.Title.str.split(r"^(\d\.\d)\s(.+)\s(\d)$", expand=True).iloc[:, 1:-1].add_prefix("col_")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.