[英]Split pandas column by separator for different string sizes
如何拆分像df.value
這樣的列
value
--------
Top/Animals/Cat
Top/Dog
Pig/Guineea/Piglet
分成多列
val1 | val2 | val3 |
Top Animals Cat
NaN Top Dog
Pig Guineea Piglet
這樣我就有最長字符串的列數和其他字符串長度不同的 NaN?
讓我們嘗試一些新的東西
sep='/'
s=df.value.str.count(sep)
s=((s.max()-s).map(lambda x : x*sep)+df.value).str.split(sep,expand=True)
0 1 2
0 Top Animals Cat
1 Top Dog
2 Pig Guineea Piglet
.str.split()
的expand=True
是你的朋友!
df['value'].str.split('/', expand=True)
str.split
與expand
參數一起使用df = pd.DataFrame({'value' : ['Top/Animals/Cat', 'Top/Dog', 'Pig/Guineea/Piglet', 'Top']})
# reverse string first. Top/Animals/Cat will become Cat/Animals/
df = df['value'].apply(lambda x : '/'.join(x.split('/')[::-1])).str.split('/', expand=True)
# column renaming and order
df.columns = ['val' + str(i) for i in range(len(df.columns), 0,-1)]
df = df[df.columns[::-1]]
df
output
val1 val2 val3
0 Top Animals Cat
1 None Top Dog
2 Pig Guineea Piglet
3 None None Top
您可以使用 DataFrame 構造函數以相反的順序構建列,然后重新索引它們:
resul = pd.DataFrame([reversed(i) for i in df['value'].str.split('/')])
resul = resul.reindex(reversed(resul.columns), axis=1)
resul.columns = ['val' + str(i+1) for i in range(len(resul.columns))]
它按預期給出:
val1 val2 val3
0 Top Animals Cat
1 None Top Dog
2 Pig Guineea Piglet
此解決方案返回 NaN 而不是 None (根據 OP 的要求)
import pandas as pd
import numpy as np
df = pd.DataFrame({"c1": ["Top/Animals/Cat",
"Top/Dog",
"Pig/Guineea/Piglet"]})
df["c1"] = df["c1"].str.split("/")
c1_max_len = df["c1"].map(len).max()
df["c1"] = df["c1"].map(lambda x: (c1_max_len - len(x)) * [np.nan] + x)
df_exploded = pd.DataFrame(df.c1.values.tolist(), index= df.index)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.