一个人如何拆分df.value
value
--------
Top/Animals/Cat
Top/Dog
Pig/Guineea/Piglet
分为多列
val1 | val2 | val3 |
Top Animals Cat
NaN Top Dog
Pig Guineea Piglet
这样我就有最长的字符串和NaN的列数,而其他字符串的长度不一样?
答案 0 :(得分:2)
让我们尝试一些新的东西
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
答案 1 :(得分:1)
.str.split()
的{{1}}是您的朋友!
expand=True
答案 2 :(得分:0)
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
输出
val1 val2 val3
0 Top Animals Cat
1 None Top Dog
2 Pig Guineea Piglet
3 None None Top
答案 3 :(得分:0)
您可以使用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
答案 4 :(得分:0)
此解决方案返回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)