如何修复这个Python错误?Jupyter笔记本将R转换为Python

ljo96ir5  于 2022-12-15  发布在  Python
关注(0)|答案(2)|浏览(122)

我在Jupyter Notebooks中不断得到一个错误,并试图将R代码转换为Python。我对Python非常陌生,我的代码不断抛出一个错误,说hosp_names是未定义的。下面是我的代码。任何帮助。我也张贴了我试图转换的原始R代码。
R代码:

# Get the unique hospital names
hosp_names = hosp_info %>% 
  filter(`Hospital Type` == "Acute Care Hospitals") %>%
  filter(State == "CA") %>%
  pull(`Hospital Name`)

# Filter based on those hospital names
hosp_info_CA = 
hosp_info %>% 
  rename(Hospital = `Hospital Name`,
         Provider_ID = `Provider ID`,
         Safety = `Safety of care national comparison`,
         Effectiveness = `Effectiveness of care national comparison`
         ) %>%
  filter(Hospital %in% hosp_names, State == "CA") %>%
  mutate(Overall_Rating = as.numeric(`Hospital overall rating`)) %>%
  drop_na(Overall_Rating)

hosp_info_CA %>% 
  arrange(desc(Overall_Rating), Hospital) %>% 
  head(7)

hosp_info_CA %>% 
  group_by(Overall_Rating, Safety) %>% 
  count()

write_csv(hosp_info_CA, 'hosp_info_CA.csv')

Python代码:
输入Pandas为PD #输入Pandas
医院名称=医院信息医院信息= [(医院信息[”医院类型“] ==“急症护理医院“)&(医院信息[”州“] ==“CA“)].loc[:,”医院名称“].unique()
医院信息CA =医院信息重命名(列={”医院名称“:“医院“、“提供者ID“:“提供者ID“、“护理安全性国家比较“:“安全性“、“全国护理有效性比较“:“有效性“}).loc[医院信息[”医院“].isin(医院名称)&(医院信息[”州“] ==“CA“)].dropna(子集=[”医院总体评级“]).assign(总体评级= lambda x:pd.to_数字(x[”医院总体评分“])
hosp_info_CA.排序_值(按=”总体_评级“,升序=假).head(7)
hosp_info_CA.groupby([”总体评分“,“安全性“]).count()
主机信息CA.to_csv(“主机信息CA.csv“)
我一直收到错误:
错误:
名称错误追溯(最近调用最后)在3 4 #中获取唯一医院名称----〉5 hosp_names = hosp_info6 hosp_info = [(hosp_info[”医院类型“] ==“急症护理医院“)&(hosp_info[”州“] ==“CA“)].loc[:,”医院名称“].unique()7
名称错误:未定义名称'hosp_info'

xbp102n0

xbp102n01#

您是否已将包含医院信息的数据文件导入到Python中?如果尚未导入,假设它是csv文件,您可以通过以下方式进行导入:

import pandas as pd

host_info = pd.read_csv(r'Path where the CSV file is stored\File name.csv')
print(host_info )
yhxst69z

yhxst69z2#

查看错误:

Error:

NameError Traceback (most recent call last) in 3 4 
# Get the unique hospital names -
---> 5 hosp_names = hosp_info 6 hosp_info = [(hosp_info[" Hospital Type "] == " Acute Care Hospitals ") & (hosp_info[" State "] == " CA ")].loc[:," Hospital Name "].unique() 7

NameError: name 'hosp_info' is not defined

上面写着:
名称错误:未定义名称'hosp_info'
因为在代码的第5行你把hosp_names赋给了hosp_info,而hosp_info是没有定义的.所以当你试图在第6行调用hosp_info时,它是没有定义的.我假设你想用相反的方法来做:

将第5行更改为:

hosp_info = hosp_names

相关问题