将元素插入Pandas数据框列表

mgdq6dx1  于 2023-05-27  发布在  其他
关注(0)|答案(1)|浏览(125)

具有以下DataFrame:

df = pd.DataFrame({"booking": ['A', 'B', 'C'],
                   "route": [['1','2','3'],['5','4','1'],['3','6','8']]})

1.需要在每个“route”单元格中插入list开头的'0'来得到:

df1 = pd.DataFrame({"booking": ['A', 'B', 'C'],
                    "route": [['0','1','2','3'],['0','5','4','1'],['0','3','6','8']]})

1.下一步是split路由,得到以下结果:

df1 = pd.DataFrame({"booking": ['A', 'B', 'C'],
                    "legs": [['0>1','1>2','2>3'],['0>5', '5>4','4>1'],['0>3','3>6','6>8']]})
edqdpe6u

edqdpe6u1#

您可以使用列表解析:

df1 = df.assign(route=[[0]+l for l in df['route']])

输出:

booking         route
0       A  [0, 1, 2, 3]
1       B  [0, 5, 4, 1]
2       C  [0, 3, 6, 8]

然后:

df1 = df.assign(route=[[f'{a}>{b}' for a,b in zip(l, l[1:])]
                       for l in df1['route']])

输出:

booking            route
0       A  [0>1, 1>2, 2>3]
1       B  [0>5, 5>4, 4>1]
2       C  [0>3, 3>6, 6>8]

当然,正如@Nick评论的那样,如果不需要中间体,您可以使用单个步骤:

df1 = df.assign(route=[[f'{a}>{b}' for a,b in zip([0] + l, l)]
                       for l in df['route']])

输出:

booking            route
0       A  [0>1, 1>2, 2>3]
1       B  [0>5, 5>4, 4>1]
2       C  [0>3, 3>6, 6>8]

相关问题