如何在Pandas中的特定列索引处插入列?

发布于 2021-01-29 14:58:04

我可以在熊猫的特定列索引处插入列吗?

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

这会将列n作为的最后一列df,但是没有办法告诉df它放在n开始处吗?

关注者
0
被浏览
102
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    使用loc = 0将在开头插入

    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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看