1 回答
![?](http://img1.sycdn.imooc.com/545865b000016a9202200220-100-100.jpg)
TA贡献1909条经验 获得超7个赞
如果您始终知道分割数,您可以执行以下操作:
import pandas as pd
df = pd.DataFrame({ "a": [ "test_a_b", "test2_c_d" ] })
# Split column by "_"
items = df["a"].str.split("_")
# Get last item from splitted column and place it on "b"
df["b"] = items.apply(list.pop)
# Get next last item from splitted column and place it on "c"
df["c"] = items.apply(list.pop)
# Get final item from splitted column and place it on "d"
df["d"] = items.apply(list.pop)
这样,数据框将变成
a b c d
0 test_a_b b a test
1 test2_c_d d c test2
由于您希望列按特定顺序排列,因此可以对数据框的列重新排序,如下所示:
>>> df = df[[ "d", "c", "b", "a" ]]
>>> df
d c b a
0 test a b test_a_b
1 test2 c d test2_c_d
添加回答
举报