如何在 Pandas 的特定列索引处插入一列? [英] how do I insert a column at a specific column index in pandas?

查看:36
本文介绍了如何在 Pandas 的特定列索引处插入一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 Pandas 的特定列索引处插入一列吗?

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

这会将 n 列作为 df 的最后一列,但是没有办法告诉 df>n 开头?

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?

推荐答案

参见文档:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

使用 loc = 0 会在开头插入

using loc = 0 will insert at the beginning

df.insert(loc, column, 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

这篇关于如何在 Pandas 的特定列索引处插入一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆