Ling
Ling

Reputation: 911

How to append a new row on pandas dataframe with single column?

This question might seems easy but I could not find any solution for it.

Say I have a CSV file like this without headers.

121
334
313
930

I want to add/append new row with number 0 at the bottom like this

121
334
313
930
0

I tried with the following method but did not succeed.

import pandas as pd
import os

folder_path = "/home/Ling/test/"
df = pd.read_fwf(folder_path + "test1.csv", usecols=[0], delimiter=",")
df2 = pd.DataFrame([[0]], dtype=int)
print df.append(df2, ignore_index=True)

The result

NaN 121
NaN 334
NaN 313
NaN 930
0.0 NaN

I am following this example

I even try to change from [[0]] to [[0,]] and [[,0]] but did not work. Is there anything that I miss here in the code?

Thank you for your help and suggestion.

Upvotes: 5

Views: 6618

Answers (2)

zipa
zipa

Reputation: 27869

You can add new row using loc and shape as well:

df.loc[df.shape[0]] = 0

Or if you want to use append:

df2 = pd.DataFrame([0])
df.append(df2, ignore_index=True)

Finally, when reading csv add header=None to imply that no column names are included.

Upvotes: 1

Ioannis Nasios
Ioannis Nasios

Reputation: 8527

import pandas as pd
import numpy as np

#read data frame with header None
df=pd.read_csv("datapath/df.csv",header=None)
df=df.append(pd.Series(np.array([0])),ignore_index=True)

Upvotes: 2

Related Questions