首页 > 解决方案 > python pandas数据框不输出

问题描述

以下python代码dosent输出它应该输出的内容(新数据框)

import pandas as pd
import numpy as np

try:
    file = pd.read_csv("customers.csv")
except:
    pass


customers = {"name":[""],
             "last":[""],
             "age_range":[0],
             "emails":[""]}

df_customers = pd.DataFrame(customers)


def add_customer(df,name,last,age=np.nan,email=np.nan):
    df_customers = df.append({"name":name,
             "last":last,
             "age_range":age,
             "emails":email},ignore_index=True)




add_customer(df_customers,"mohamed","miboun",email="mohamedwapana@gmail.com")
print(df_customers)

我尝试附加客户的信息,但它只是输出没有值的数据框。请帮忙。

标签: pythonpandasdataframenumpy

解决方案


以下是您可以构建所需功能的方法之一:

def add_customer(df,name,last,age=np.nan,email=None):
    # First, taking care to manipulate the last index and add a new line
    index = " "
    if df.iloc[-1, 0] == "":
        index = 0
    else:
        index = df.index[-1] + 1
    
    # Now, we simply assign each respective column
    df.loc[index, 'name'] = name
    df.loc[index, 'last'] = last
    df.loc[index, 'age'] = age
    df.loc[index, 'email'] = email


add_customer(df_customers,"mohamed","miboun",email="mohamedwapana@gmail.com")
df_customers

此功能将添加一个新行并填写客户信息。

在“email”的命名参数中,默认值应该是 None 并注意 np.nan ,就像您在示例中插入的那样。请注意, np.nan仅指数值


推荐阅读