How to append new row to dataframe in pandas?

前端 未结 4 825
臣服心动
臣服心动 2021-02-13 19:29

This is the code i have used

    iname = \"name1\"    
    ipassword = \"password1\"
    iemail = \"email@domain.com\"
    res1 = []
            


        
相关标签:
4条回答
  • 2021-02-13 19:57

    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)
    
    0 讨论(0)
  • 2021-02-13 20:09

    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

    0 讨论(0)
  • 2021-02-13 20:12

    Use -

    iname = "name1"    
    ipassword = "password1"
    iemail = "email@domain.com"
    
    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@domain.com
    
    0 讨论(0)
  • 2021-02-13 20:13

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

    iname = "name1"    
    ipassword = "password1"
    iemail = "email@domain.com"
    
    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)
    
    0 讨论(0)
提交回复
热议问题