Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an extra row to a pandas dataframe [duplicate]

Tags:

python

pandas

If I have an empty dataframe as such:

columns = ['Date', 'Name', 'Action','ID'] df = pd.DataFrame(columns=columns)  

is there a way to append a new row to this newly created dataframe? Currently I have to create a dictionary, populate it, then append the dictionary to the dataframe at the end. Is there a more direct way?

like image 624
Ahdee Avatar asked Oct 14 '13 17:10

Ahdee


People also ask

How do I add more rows in pandas?

You can add rows to the pandas dataframe using df. iLOC[i] = ['col-1-value', 'col-2-value', ' col-3-value '] statement. Other options available to add rows to the dataframe are, append()

How do I add rows to an existing DataFrame?

append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value. ignore_index : If True, do not use the index labels.


1 Answers

Try this:

df.loc[len(df)]=['8/19/2014','Jun','Fly','98765']  

Warning: this method works only if there are no "holes" in the index. For example, suppose you have a dataframe with three rows, with indices 0, 1, and 3 (for example, because you deleted row number 2). Then, len(df) = 3, so by the above command does not add a new row - it overrides row number 3.

like image 88
Jun Avatar answered Oct 05 '22 00:10

Jun