python - 使用 pandas 从 python 中的 csv 刷新数据

我是python 的新手,并试图在旅途中学习它,我正在尝试使用python 和pandas 制作数据输入电话簿。

有我写的代码:

import pandas as pd
Book = pd.read_csv(r'/Users/denisvirnik/VSCODE/Py/Projects/Book.csv')

start = True
while(start):
        print("1: Add a new contact: ")
        print("2. View contacts: ")
        print("3. Exit ")
        op = input("Which option you want to do?: ")
        if(op == "1"):
                name = input("Type the first name: ")
                lastName = input("Type the last Name: ")
                phoneNumber = input("Type the Phone Number: ")
                data = {
                'FristName,': [name],
                'LastName,': [lastName],
                'PhoneNumber,': [phoneNumber]
                }
                df = pd.DataFrame(data)#makes the data frame of the user input above
                df.to_csv(r'/Users/denisvirnik/VSCODE/Py/Projects/Book.csv', mode='a', index=False, header=False)# appends data frame to CSV file
                print("Contact successfully added.")
        if(op == "2"):
                print(Book.head())
        if(op == "3"):
                start = False

我设置的选项之一是查看电话簿(代码中的选项 2),但是如果我在电话簿中输入新数据然后尝试查看它而不终止程序并再次运行它就不会显示,希望也许有人知道一种方法来刷新电话簿中的数据,就像我在其中输入新数据一样。

回答1

您可能希望对 book 和 df 使用相同的变量,以便输入新数据并查看它。

当 op == 2 时,您还想阅读 book

除此之外,您没有正确地将数据写入 dataframe 。

我没有给你一个完整的答案。但是,您可以从这个代码片段开始。

import pandas as pd

start = True
while(start):
    print("1: Add a new contact: ")
    print("2. View contacts: ")
    print("3. Exit ")
    op = input("Which option you want to do?: ")
    if(op == "1"):
        book = pd.read_csv('book.csv')
        
        first_name = input("Type the first name: ")
        last_name = input("Type the last Name: ")
        phone_number = input("Type the Phone Number: ")
        
        '''
        Make sure you are writing information
        to the dataframe correctly
        '''
        # Write your code
        
        # appends data frame to CSV file
        book.to_csv('book.csv', mode='a', index=False, header=False)
        print("Contact successfully added.")
    if(op == "2"):
        book = pd.read_csv('book.csv')
        print(book.head())
    if(op == "3"):
        start = False

相似文章

r - 在 R 中加载 csv 数据框时添加列

我们正在Airbnb内部为我们的大学开展一个项目。我们加载了许多不同城市的列表,并希望将所有数据加载到一个相互绑定的数据框中。但是,我们解决了这个问题。现在我们需要为每个数据集添加一个列,说明它属于哪...

随机推荐

最新文章