Skip to content Skip to sidebar Skip to footer

Adding List With Different Length As A New Column To A Dataframe

I am willing to add or insert the list values in the dataframe. The dataframe len is 49, whereas the length of list id 47. I am getting the following error while implementing the c

Solution 1:

If you convert the list to a Series then it will just work:

datasetTest.loc[:,'predict_close'] = pd.Series(test_pred_list)

example:

In[121]:
df = pd.DataFrame({'a':np.arange(3)})
df

Out[121]: 
   a
0  0
1  1
2  2

In[122]:
df.loc[:,'b'] = pd.Series(['a','b'])
df

Out[122]: 
   a    b
0  0    a
1  1    b
2  2  NaN

The docs refer to this as setting with enlargement which talks about adding or expanding but it also works where the length is less than the pre-existing index.

To handle where the index doesn't start at 0 or in fact is not an int:

In[126]:
df = pd.DataFrame({'a':np.arange(3)}, index=np.arange(3,6))
df

Out[126]: 
   a
3  0
4  1
5  2

In[127]:
s = pd.Series(['a','b'])
s.index = df.index[:len(s)]
s

Out[127]: 
3    a
4    b
dtype: object

In[128]:
df.loc[:,'b'] = s
df

Out[128]: 
   a    b
3  0    a
4  1    b
5  2  NaN

You can optionally replace the NaN if you wish calling fillna


Solution 2:

You can add items to your list with an arbitrary filler scalar.

Data from @EdChum.

filler = 0
lst = ['a', 'b']

df.loc[:, 'b'] = lst + [filler]*(len(df.index) - len(lst))

print(df)

   a  b
0  0  a
1  1  b
2  2  0

Solution 3:

You still can assign it by using loc data from Ed

l = ['a','b']
df.loc[range(len(l)),'b'] = l
df
Out[546]: 
   a    b
0  0    a
1  1    b
2  2  NaN

Post a Comment for "Adding List With Different Length As A New Column To A Dataframe"