Bottom Page

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
Quote
#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
Quote
#3
Thanks Zivoni. I used the concat and fix my index .

It worked.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Pandas Import CSV count between numerical values within 1 Column ptaylor520 3 71 Jul-16-2019, 08:13 AM
Last Post: ptaylor520
  How to use the excel filename as a value to populate new column, using Pandas? Dequanharrison 5 206 Jun-26-2019, 11:11 PM
Last Post: Dequanharrison
  pandas change row value an existing column with conditionals Gigux 1 139 Jun-22-2019, 08:04 PM
Last Post: Gigux
  How to delete column if entire column values are "nan" Sri 4 364 Apr-13-2019, 12:16 PM
Last Post: Sri
  Insert images in a folder into dataframe tofi 0 377 Dec-14-2018, 08:05 PM
Last Post: tofi
  Bulk Insert into SQL Server without a file rsouza 0 461 Oct-04-2018, 02:02 PM
Last Post: rsouza
  Text to column pandas ms5573 0 456 Aug-25-2018, 08:18 PM
Last Post: ms5573
  Splitting values in column in a pandas dataframe based on a condition hey_arnold 1 1,128 Jul-24-2018, 02:18 PM
Last Post: hey_arnold
  Output column names Scott 2 615 Jun-25-2018, 12:47 PM
Last Post: volcano63
  Multiply entire column with a constant with pandas in python fyec 1 12,827 Jun-17-2018, 04:33 AM
Last Post: Mekire

Forum Jump:


Users browsing this thread: 2 Guest(s)