繁体   English   中英

我如何 append 到 Pandas DataFrame 的字符串?

[英]How do I append a string to a Pandas DataFrame?

我正在尝试将 append 字符串转换为 Pandas Dataframe,然后使用 df.at ZC1C425268E683895D14A 为它们分配值。 下面是我使用 Pandas 的 2 段代码,在第一个中,我使用字符串输入并将输入作为索引附加到数据帧。 在第二个中,我尝试使用字符串输入,但出现以下错误。

cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

片段 1

    allBooks = pd.DataFrame(columns=['Copies'])


    newBook = input("Enter the title of the book you wish to add ")
    newCopies = int(input("Enter the amount of copies of this book "))
    allBooks.append(newBook)
    allBooks.at[allBooks.item(newBook), 'Copies'] = newCopies
    allBooks.to_csv(r'totalInventory.csv')

片段 2

    userData = pd.DataFrame(columns=['fname','lname','dob','pwd'])


    fname = input("Please enter your first name. ")
    lname = input("Please enter your last name. ")
    dob = input("Please enter your DOB MM/DD/YYYY ")
    pwd = input("Type in the password you want to use. ")
    dobSeperate = dob.split("/")
    idChars = str(dobSeperate[1]) + str((dobSeperate[2])[2:4])
    userId = fname.lower() + idChars
    print("This is your user ID, please write it down:", userId)
    print("This is your password, please remember it:", pwd)
    users[userId] = pwd

    userData.append(userId)
    print(userId)

如何更改代码以便我可以 append 第二段代码中的字符串?

我看不出片段 1 与该问题有何关联。

对于片段 2,您可以从列表中将用户信息添加到 dataframe:

# include userId in columns
userData = pd.DataFrame(columns=['fname','lname','dob','pwd','userId'])
........

# append new user info
userData.loc(len(userData)+1) = [fname, lname, dob, pwd, userId]

将字符串直接附加到 dataframe 是行不通的。对于片段 1,您可以考虑对方法进行轻微更改。

import pandas as pd

allBooks = pd.DataFrame(columns=['Title', 'Copies'])
newBook = input("Enter the title of the book you wish to add ")
newCopies = int(input("Enter the amount of copies of this book "))
row = pd.DataFrame({'Title':[newBook], 'Copies':[newCopies]})
pd.concat([allBooks, row], axis=0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM