我正在试着把3csv文件读成3个pandas DataFrame。但在执行该函数后,该变量似乎不可用。尝试在函数外部创建一个空白数据框,并在函数中读取和设置该框。但是框架是空白的。
# Load data from the csv file
def LoadFiles():
x = pd.read_csv('columns_description.csv', index_col=None)
print("Columns Description")
print(f"Number of rows/records: {x.shape[0]}")
print(f"Number of columns/variables: {x.shape[1]}")
LoadFiles()
x.head()Python Notebook for above code with Error
在第二种方法中,我尝试创建一个新的数据框架,其中包含来自数据集的一些合并信息。当变量似乎不再可用时,问题再次出现。
# Understand the variables
y = pd.read_csv('columns_description.csv', index_col=None)
def refresh_y():
var_y = pd.DataFrame(columns=['Variable','Number of unique values'])
for i, var in enumerate(y.columns):
var_y.loc[i] = [y, y[var].nunique()]
refresh_y()Screenshot with error code and solution restructuring in the function
我是Python的新手,代码是一个示例,并不代表实际的数据,在函数中,一个示例是单列。在这个派生的数据集中,我有多个列要根据更改进行刷新,因此采用了函数方法。
发布于 2021-11-20 08:01:51
定义函数时,如果要使用函数中定义的变量,则应以return var结尾。查看这个:Function returns None without return statement和一些关于定义函数的教程(https://learnpython.com/blog/define-function-python/)。
下面是一个帮助您开始定义函数的基本示例:
def sum_product(arg1,arg2): #your function takes 2 arguments
var1 = arg1 + arg2
var2 = arg1*arg2
return var1,var2 #returns two values
new_var1, new_var2 = sum_product(3,4) 对于第一个示例,尝试修改它,如下所示:
def LoadFiles():
var = pd.read_csv('columns_description.csv', index_col=None)
print("Columns Description")
print(f"Number of rows/records: {var.shape[0]}")
print(f"Number of columns/variables: {var.shape[1]}")
return var
x = LoadFiles()
x.head()发布于 2021-11-24 02:21:45
尝试以下代码
# Load data from the csv file
def LoadFiles():
x = pd.read_csv('columns_description.csv', index_col=None)
print("Columns Description")
print(f"Number of rows/records: {x.shape[0]}")
print(f"Number of columns/variables: {x.shape[1]}")
return x
x2 = LoadFiles()
x2.head()函数中的变量仅在函数内部可用。你可能需要研究一下作用域。我推荐下面这个简单的关于Python范围的站点。
https://stackoverflow.com/questions/70043838
复制相似问题