dataframe在特定列 插入_如何在pandas中的特定列索引处插入列?

bd96500e110b49cbb3cd949968f18be7.png

Can I insert a column at a specific column index in pandas?

import pandas as pd

df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})

df['n'] = 0

This will put column n as the last column of df, but isn't there a way to tell df to put n at the beginning?

解决方案

using idx = 0 will insert at the beginning

df.insert(idx, col_name, value)

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

df

Out:

B C

0 1 4

1 2 5

2 3 6

idx = 0

new_col = [7, 8, 9] # can be a list, a Series, an array or a scalar

df.insert(loc=idx, column='A', value=new_col)

df

Out:

A B C

0 7 1 4

1 8 2 5

2 9 3 6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值