python-pandas-将不带分隔符的文本列拆分为多个列

python-pandas-将不带分隔符的文本列拆分为多个列,python,pandas,Python,Pandas,让我们以下面的示例DataFrame import pandas as pd df = pd.DataFrame([['foo', 2348], ['bar', 6132], ['baz',5843]], columns = list('ab')) a b 0 foo 2348 1 bar 6132 2 baz 5843 我希望得到以下结果,其中b列中的所有数字被分开 a b c d e 0 foo 2 3 4 8 1 bar 6

让我们以下面的示例
DataFrame

import pandas as pd
df = pd.DataFrame([['foo', 2348], ['bar', 6132], ['baz',5843]], columns = list('ab'))

     a     b
0  foo  2348
1  bar  6132
2  baz  5843
我希望得到以下结果,其中
b列中的所有数字被分开

     a  b  c  d  e
0  foo  2  3  4  8
1  bar  6  1  3  2
2  baz  5  8  4  3

您可以将类型强制转换为
str
,然后
apply
list
创建字符列表,然后构造一个
系列
,这样它会返回一个df,您可以将其添加回新列:

In [13]:
df[['b','c','d','e']] = df['b'].astype(str).apply(lambda x: pd.Series(list(x))).astype(int)
df

Out[13]:
     a  b  c  d  e
0  foo  2  3  4  8
1  bar  6  1  3  2
2  baz  5  8  4  3
您可以使用:

#convert column b to string
df['b'] = df.b.astype(str)

#indexing with str
df['c'] = df.b.str[1]
df['d'] = df.b.str[2]
df['e'] = df.b.str[3]
df['b'] = df.b.str[0]

#if need convert columns to int
df[['b','c','d','e']] = df[['b','c','d','e']].astype(int)
print df
     a  b  c  d  e
0  foo  2  3  4  8
1  bar  6  1  3  2
2  baz  5  8  4  3