'How to append new row to dataframe in pandas?

This is the code I have used:

iname = "name1"    
ipassword = "password1"
iemail = "[email protected]"
res1 = []
df = pd.read_csv("login.csv", sep=',', encoding="utf-8")
res1.append(iname,ipassword,iemail)
print(res1,res2,res3)
df.to_csv("login.csv", index=False)

How to store the name, password and email in the csv file by using pandas dataframe?

login.csv:

name     password     email
admin    admin        asdfs
zds      sd           dsssfsfd
vipul    rao          dsfdsfs


Solution 1:[1]

Another simple approach is to use pd.Dataframe.loc method.

row = [iname, ipassword, iemail]
df.loc[len(df)] = row
df.to_csv("login.csv", index=False)

Solution 2:[2]

Use -

iname = "name1"    
ipassword = "password1"
iemail = "[email protected]"

df2 = df.append(pd.DataFrame([[iname,ipassword,iemail]], columns
=df.columns))
df2.to_csv("login.csv", index=False)

Output

    name   password             email
0  admin      admin             asdfs
1    zds         sd          dsssfsfd
2  vipul        rao           dsfdsfs
0  name1  password1  [email protected]

Solution 3:[3]

You can use pd.DataFrame.loc to add a row to your dataframe:

iname = "name1"    
ipassword = "password1"
iemail = "[email protected]"

df = pd.read_csv("login.csv", sep=',', encoding="utf-8")

df.loc[df.index.max()+1] = [iname, ipassword, iemail]

df.to_csv("login.csv", index=False)

Solution 4:[4]

A good way is to create an empty list first, populate it and then add to the empty data frame like this

data=[]

for i, row in new_df.head(4).iterrows():
    sequence=str(row['body'])
    author=row['author']
    data.append([author,sequence]) 
d=pd.DataFrame(data,columns = ['author', 'results'])

it will give the results like this enter image description here

Solution 5:[5]

The accepted answer is good if all you are doing is appending rows. However, if you do other operations such as:

df.drop_duplicates(subset=['name'],inplace=True)

then some of the index values will be greater than the size of the dataframe, and the accepted answer may overwrite an existing row.

In that case, I recommend:

row = [iname, ipassword, iemail]
df.loc[max(df.index)+1] = row
df.to_csv("login.csv", index=False)

which, if the dataframe could be empty, may have to become:

row = [iname, ipassword, iemail]
if len(df.index)>0:
    df.loc[max(df.index)+1] = row
else:
    df.loc[len(df)] = row
df.to_csv("login.csv", index=False)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mihai Alexandru-Ionut
Solution 2
Solution 3 jpp
Solution 4 Shaina Raza
Solution 5 Bob Philhower