Python Forum
pandas : insert new column
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pandas : insert new column
#1
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
Reply
#2
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
Reply
#3
Thanks Zivoni. I used the concat and fix my index .

It worked.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  HTML Decoder pandas dataframe column mbrown009 3 961 Sep-29-2023, 05:56 PM
Last Post: deanhystad
  pandas column percentile nuncio 7 2,383 Aug-10-2022, 04:41 AM
Last Post: nuncio
  pandas: Compute the % of the unique values in a column JaneTan 1 1,756 Oct-25-2021, 07:55 PM
Last Post: jefsummers
  Pandas Data frame column condition check based on length of the value aditi06 1 2,655 Jul-28-2021, 11:08 AM
Last Post: jefsummers
  How to move each team row to a new column. Pandas vladiwnl 0 1,694 Jun-13-2021, 08:10 AM
Last Post: vladiwnl
  iretate over columns in df and calculate euclidean distance with one column in pandas Pit292 0 3,266 May-09-2021, 06:46 PM
Last Post: Pit292
Question Pandas - Creating additional column in dataframe from another column Azureaus 2 2,913 Jan-11-2021, 09:53 PM
Last Post: Azureaus
  Pandas: summing columns conditional on the column labels ddd2332 0 2,075 Sep-10-2020, 05:58 PM
Last Post: ddd2332
  Pandas DataFrame and unmatched column sritsv19 0 2,989 Jul-07-2020, 12:52 PM
Last Post: sritsv19
  Pandas - Dynamic column aggregation based on another column theroadbacktonature 0 3,011 Apr-17-2020, 04:54 PM
Last Post: theroadbacktonature

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020