我想根据定界符 ":"
将一列拆分为 3,我能够做到
使用下面的代码。但是现在想改拆分名
列的默认值为 1、2、3、4。请建议我该怎么做。
from pandas import *
df = DataFrame(
{'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]});
df
df.join(df.Seatblocks.apply(lambda x: Series(x.split(':'))))
最佳答案
人们已经给出了 rename
方法,但我发现如果您避免将所有内容都塞进一行的诱惑,这些事情会更容易。一旦你有了一个框架,你可以简单地分配给 .columns
:
>>> sb = df.Seatblocks.str.split(":").apply(pd.Series)
>>> sb.columns = ["a", "Three Digit", "??", "coord"]
>>> pd.concat([df, sb], axis=1)
CustomerName Seatblocks a Three Digit ?? coord
0 Paul 2:218:10:4,6 2 218 10 4,6
1 John 2:218:10:4,6 2 218 10 4,6
第一行只是 (df.Seatblocks.apply(lambda x: Series(x.split(':'))))
的一个版本,它利用了向量化字符串操作访问器 .str
( docs )。
关于python - 拆分列并使用 pandas 命名它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28256025/