wwl wwl - 23 days ago 4x
Python Question

Adding row to dataframe

Suppose I am trying add rows to a dataframe with 40 columns. Ordinarily it would be something like this:

df = pandas.DataFrame(columns = 'row1', 'row2', ... ,'row40'))

df.loc[0] = [value1, value2, ..., value40]

(don't take the dots literally)

However let's say value1 to value10 are in list1 (i.e. list1 = [value1, value2, ..., value10]), and all the remaining values are individual elements.

I tried:

df.loc[0] = [list1, value11, value12, ..., value40]

but it doesn't work, because Python interprets the entire list as one element. So it's the wrong dimension. How can I rewrite the code to make it work?


I think you need:

df.loc[0] = list1 + [value11, value12, ..., value40]


df = pd.DataFrame(columns = ['row1', 'row2','row3', 'row4','row5', 'row6','row40'])

list1 =  ['a','b','c']
df.loc[0] = list1 + ['d','e','f', 'g']
print (df)
  row1 row2 row3 row4 row5 row6 row40
0    a    b    c    d    e    f     g