让我们以下面的例子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 生成字符列表,然后构造一个 Series 因此它返回一个 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
