【问题标题】:how do I insert a column at a specific column index in pandas?如何在熊猫的特定列索引处插入一列?
【发布时间】:2013-09-11 12:22:14
【问题描述】:

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

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

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

【问题讨论】:

标签: python indexing pandas


【解决方案1】:

参见文档:http://pandas.pydata.org/pandas-docs/stable/generated/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

【讨论】:

  • 对于未来的用户,新的参数是“loc”、“column”、“value”Source
  • 打印后我数了数又重述了值的长度和索引的长度,但不断收到ValueError: Length of values does not match length of index
  • 对于未来的用户,如果您想借助特定列名而不是索引进行插入,请使用:df.insert(df.columns.get_loc('col_name'), 'new_col_name', ser_to_insert)insert 不直接支持列名用例,但您可以从列名中获取列索引并传递它。
【解决方案2】:

如果您想要所有行的单个值:

df.insert(0,'name_of_column','')
df['name_of_column'] = value

编辑:

您还可以:

df.insert(0,'name_of_column',value)

【讨论】:

  • 这个df.insert(0,'name_of_column',value) 正是我所需要的......谢谢:)
【解决方案3】:

您可以尝试将列提取为列表,根据需要对其进行按摩,然后重新索引您的数据框:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

编辑:这可以在一行中完成;但是,这看起来有点难看。也许一些更干净的建议可能会来......

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

【讨论】:

    【解决方案4】:
    df.insert(loc, column_name, value)
    

    如果没有其他同名的列,这将起作用。如果数据框中已存在具有您提供的名称的列,则会引发 ValueError。

    您可以传递带有True 值的可选参数allow_duplicates 以创建具有现有列名的新列。

    这是一个例子:

    >>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]}) >>> df b c 0 1 3 1 2 4 >>> df.insert(0, 'a', -1) >>> df a b c 0 -1 1 3 1 -1 2 4 >>> df.insert(0, 'a', -2) Traceback (most recent call last): File "", line 1, in File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates) File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert raise ValueError(f"cannot insert {item}, already exists") ValueError: cannot insert a, already exists >>> df.insert(0, 'a', -2, allow_duplicates = True) >>> df a a b c 0 -2 -1 1 3 1 -2 -1 2 4

    【讨论】:

    • 这对我有用,谢谢
    【解决方案5】:

    这是一个非常简单的答案(只有一行)。

    您可以在将“n”列添加到您的 df 之后执行此操作,如下所示。

    import pandas as pd
    df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
    df['n'] = 0
    
    df
        l   v   n
    0   a   1   0
    1   b   2   0
    2   c   1   0
    3   d   2   0
    
    # here you can add the below code and it should work.
    df = df[list('nlv')]
    df
    
        n   l   v
    0   0   a   1
    1   0   b   2
    2   0   c   1
    3   0   d   2
    
    
    
    However, if you have words in your columns names instead of letters. It should include two brackets around your column names. 
    
    import pandas as pd
    df = pd.DataFrame({'Upper':['a','b','c','d'], 'Lower':[1,2,1,2]})
    df['Net'] = 0
    df['Mid'] = 2
    df['Zsore'] = 2
    
    df
    
        Upper   Lower   Net Mid Zsore
    0   a       1       0   2   2
    1   b       2       0   2   2
    2   c       1       0   2   2
    3   d       2       0   2   2
    
    # here you can add below line and it should work 
    df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
    df
    
       Mid  Upper   Lower   Net Zsore
    0   2   a       1       0   2
    1   2   b       2       0   2
    2   2   c       1       0   2
    3   2   d       2       0   2
    

    【讨论】:

    • 如果我们想将另一个df_other的几列添加到loc 0,并将df_other的几列添加到我们的df末尾怎么办?
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 2022-09-23
    • 1970-01-01
    • 2021-10-03
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多