1 回答

TA貢獻1909條經驗 獲得超7個贊
如果您始終知道分割數(shù),您可以執(zhí)行以下操作:
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)
這樣,數(shù)據框將變成
a b c d
0 test_a_b b a test
1 test2_c_d d c test2
由于您希望列按特定順序排列,因此可以對數(shù)據框的列重新排序,如下所示:
>>> 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
添加回答
舉報