Python 如何将新行附加到 Pandas 中的数据帧?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49916371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:18:02  来源:igfitidea点击:

How to append new row to dataframe in pandas?

pythonpandascsvdataframe

提问by vipul-rao

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.

如何使用 Pandas 数据框将姓名、密码和电子邮件存储在 csv 文件中。

login.csv

登录.csv

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

回答by Mihai Alexandru-Ionut

Another simple approach is to use pd.Dataframe.locmethod.

另一种简单的方法是使用pd.Dataframe.loc方法。

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

回答by Vivek Kalyanarangan

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]

回答by jpp

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

您可以使用pd.DataFrame.loc向数据框中添加一行:

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)