Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 443
Ling Avatar asked Oct 17 '22 05:10

Ling


1 Answers

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)
like image 50
Ioannis Nasios Avatar answered Oct 20 '22 10:10

Ioannis Nasios