1

I have a dataframe df like below :

data = {'A': [1, 2, 3, 4, 5, 6], 'B':[1, 0, 0, 0, 0, 0]}
df = pd.DataFrame(data)
df

     |  A  |  B |                                 
     +-----+----+
     |  1  |  1 |                  
     |  2  |  0 |         
     |  3  |  0 | 
     |  4  |  0 |  
     |  5  |  0 | 
     |  6  |  0 |
     +-----+----+

I have a list of values (list_values) that I want to insert as a new column D in my existing dataframe df. The end result should look like below

list_values = ['A', 'B', 'C']

Expected Output :

     |  A  |  B |  D   |                             
     +-----+----+------+
     |  1  |  1 |  A   |              
     |  2  |  0 |  B   |     
     |  3  |  0 |  C   |  
     |  4  |  0 |  NaN |
     |  5  |  0 |  NaN | 
     |  6  |  0 |  NaN |
     +-----+----+------+

I tried to insert the values from the list to a new column in dataframe, using the below code, however, I wasn't successful in my approach as it throws a value error.

start_index = df[df['B'] == 1].index

df.loc[start_index,'D'] = list_values

Is there a way wherein I can insert the values of a list as a separate column of a dataframe and get output like the above ? Thanks !

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
user3046211
  • 466
  • 2
  • 13

2 Answers2

1

This works for me:

list_values = pd.DataFrame(['A', 'B', 'C'])
new_df = pd.concat([df, list_values], axis=1)
new_df.columns = ['A', 'B', 'list_values'] # Naming the columns here 
new_df

The output:

    A   B   list_values
0   1   1   A
1   2   0   B
2   3   0   C
3   4   0   NaN
4   5   0   NaN
5   6   0   NaN
1

Another solution:

list_values = ['A', 'B', 'C']

df = df.assign(D=list_values + [np.nan] * (len(df) - len(list_values)))
print(df)

   A  B    D
0  1  1    A
1  2  0    B
2  3  0    C
3  4  0  NaN
4  5  0  NaN
5  6  0  NaN
Jason Baker
  • 3,170
  • 2
  • 12
  • 15