python - 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)
我尝试附加客户的信息,但它只是输出没有值的数据框。请帮忙。
解决方案
以下是您可以构建所需功能的方法之一:
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仅指数值
推荐阅读
- php - 当我在浏览器中运行脚本时,它看起来像笔记本
- python - 正确序列化一个值,以便正确地将其传递给 CurrentUserField()
- r - ggplot和ggplotly之间图例位置的差异?
- sqlite - SQLite.Net-PCL CreateTableAsync 添加列
- python - 点文件的“锯齿状”输出
- java - 如何在令牌请求时向 Azure AD 访问令牌 (JWT) 添加自定义声明?
- asynchronous - 微服务客户端确认和事件溯源
- ansible - 如何使用 ansible 设置 logrotation?
- python - 使用 Pandas 标头问题解析脏文本文件
- c - C 程序帮助使用 getopt 和命令行参数在 Unix/Linux 中打开文件