How to Insert a Column at a Specific Column Index in Pandas

how do I insert a column at a specific column index in pandas?

see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

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 (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171 1
174 2
173 3

Is this what you are looking for?

how do I insert a column at a specific column index in pandas data frame? (Change column order in pandas data frame)

You can try df.insert + df.pop after getting location of B by get_loc

df.insert(df.columns.get_loc("B")+1,"F",df.pop("F"))
print(df)

     A  B    F    C  D    E
0 7.0 1 6.0 NaN 8 1.0
1 8.0 2 8.0 5.0 8 5.0
2 9.0 3 5.0 6.0 8 NaN
3 1.0 8 NaN 1.0 3 4.0
4 6.0 8 9.0 2.0 5 0.0
5 NaN 2 8.0 NaN 1 3.0

Insert a column at the beginning (leftmost end) of a DataFrame

DataFrame.insert

df = pd.DataFrame({'A': ['x'] * 3, 'B': ['x'] * 3})
df

A B
0 x x
1 x x
2 x x

seq = ['a', 'b', 'c']

# This works in-place.
df.insert(0, 'C', seq)
df

C A B
0 a x x
1 b x x
2 c x x

pd.concat

df = pd.concat([pd.Series(seq, index=df.index, name='C'), df], axis=1)
df

C A B
0 a x x
1 b x x
2 c x x

DataFrame.reindex + assign
Reindex first, then assign will remember the position of the original column.

df.reindex(['C', *df.columns], axis=1).assign(C=seq)

C A B
0 a x x
1 b x x
2 c x x

Pandas - add value at specific iloc into new dataframe column

There are two steps to created & populate a new column using only a row number...
(in this approach iloc is not used)

First, get the row index value by using the row number

rowIndex = df.index[someRowNumber]

Then, use row index with the loc function to reference the specific row and add the new column / value

df.loc[rowIndex, 'New Column Title'] = "some value"

These two steps can be combine into one line as follows

df.loc[df.index[someRowNumber], 'New Column Title'] = "some value"

How to add an empty column to a dataframe?

If I understand correctly, assignment should fill:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
>>> df
A B
0 1 2
1 2 3
2 3 4
>>> df["C"] = ""
>>> df["D"] = np.nan
>>> df
A B C D
0 1 2 NaN
1 2 3 NaN
2 3 4 NaN


Related Topics



Leave a reply



Submit