Python Forum
pandas : insert new column - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: pandas : insert new column (/thread-2462.html)



pandas : insert new column - vvv - Mar-18-2017

Hi All,
I am trying to create an empty dataframe 'a' and insert slices of raw data from 'df' in to columns in 'a'. I can insert a one new columns and other columns get NULL value

l=[0,1,2,3,4,5,6,7,8,9,10]
df = pd.DataFrame(l)
df.columns = ['c']
a=pd.DataFrame()
a.insert(0,0,df.c.loc[0:2])
a.insert(1,1,df.c.loc[3:6])  ## inserts only NaN

Out[134]: 
   0   1
0  0 NaN
1  1 NaN
2  2 NaN

Thanks
vvv


RE: pandas : insert new column - zivoni - Mar-18-2017

It is not entirely clear what you want to do, as you are trying to insert a column with length 4 into a dataframe with length 3. Pandas respects indices when you try to insert second column and tries to insert values for index values 0, 1, 2 - there are none so NaN is used.
Output:
In [10]: import pandas as pd In [11]: df = pd.DataFrame({'c': range(11)}) In [12]: a = pd.DataFrame() In [13]: a.insert(0, 0, df.c.loc[0:2])
You  can use pd.concat to concatenate your dataframe and serie - either with respect of index:
Output:
In [14]: pd.concat([a, df.c.loc[3:6]], axis=1) Out[14]:      0    c 0  0.0  NaN 1  1.0  NaN 2  2.0  NaN 3  NaN  3.0 4  NaN  4.0 5  NaN  5.0 6  NaN  6.0
or without:
Output:
In [15]: pd.concat([a, df.c.loc[3:6].reset_index(drop=True)], axis=1) Out[15]:      0  c 0  0.0  3 1  1.0  4 2  2.0  5 3  NaN  6



RE: pandas : insert new column - vvv - Mar-19-2017

Thanks Zivoni. I used the concat and fix my index .

It worked.