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 !