0

I am trying to add a row(list of int) to pandas dataframe but i am somehow unable to append it. The thing is the dataframe has no header and everywhere the put data through specifying column names. I dont understand how to do it without header. Below is my dataframe named sheet

sheet = pd.read_csv("labels.csv",header = None) #sheet = [[1,1,1,2,2 ...]]

i want to append resulting list named simple_list = [1,2,3,4,2,1,1,1] to it.

Bilal Nadeem
  • 19
  • 1
  • 5
  • What's does the error say? How many columns are in your dataframe? Does this number agree with the number of datapoints in `simple_list`? For example, how does `sheet.head()` look? – nostradamus Jan 09 '20 at 15:59
  • so i have 60000 cells in .csv file in one row. – Bilal Nadeem Jan 09 '20 at 16:10
  • It numbers them with indeces 0,1,2,3,....59999 and place points under them – Bilal Nadeem Jan 09 '20 at 16:10
  • from what i understood u wanted to add a row to your dataframe? – Umar.H Jan 09 '20 at 16:14
  • @Datanovice the first line says so ... trying to add a row(list of int) – Bilal Nadeem Jan 09 '20 at 16:16
  • `pd.concat([sheet,pd.DataFrame({k:v for k,v in zip(sheet.columns.tolist(),simple_list)})])` I thought something like this.Since append will just create a new column? – Umar.H Jan 09 '20 at 16:44
  • Always add further explanation to your posts, not in the comments. – AMC Jan 09 '20 at 23:28
  • Possible duplicate of: https://stackoverflow.com/q/10715965/11301900, https://stackoverflow.com/q/26309962/11301900 – AMC Jan 09 '20 at 23:39
  • Does this answer your question? [Add one row to pandas DataFrame](https://stackoverflow.com/questions/10715965/add-one-row-to-pandas-dataframe) – nostradamus Jan 10 '20 at 07:56

3 Answers3

1

Does the following work?

sheet = sheet.append(pd.DataFrame([[1,2,3,4,2,1,1,1]]), ignore_index=True)
Sam Chats
  • 2,271
  • 1
  • 12
  • 34
0

You need to create a series out of simple_list.

simple_series = pd.Series(simple_list)

Then you can append a row to your dataframe with argument ignore_index=True:

sheet = sheet.append(simple_series, ignore_index=True)
xopclabs
  • 11
  • 1
  • 1
0

This work for me. sheet.appends returns a dataframe, you need to assign it to the same var or a new one to us it. If not "sheet" will have always the original CSV content

import pandas as pd

if __name__ == '__main__':
    sheet = pd.read_csv("labels.csv", header=None)
    sheet = sheet.append([[41, 42, 42, 44, 45]], ignore_index=True)