Python 3.x 生成数据帧的函数返回None
首先, 我创建了一个函数,在这个函数中,我将一些标题值转换为一列,然后保留每个标题的值。更具体地说,我的文件之前和之后如下所示: 代码是:Python 3.x 生成数据帧的函数返回None,python-3.x,dictionary,transpose,Python 3.x,Dictionary,Transpose,首先, 我创建了一个函数,在这个函数中,我将一些标题值转换为一列,然后保留每个标题的值。更具体地说,我的文件之前和之后如下所示: 代码是: #Transpose function def transpose(df): #Create a list of all the columns columns = list(df) #Create lists to hold headers and sites headers = [] sites
#Transpose function
def transpose(df):
#Create a list of all the columns
columns = list(df)
#Create lists to hold headers and sites
headers = []
sites = []
#Split columns list into headers and sites
for col in columns:
if col.startswith('Date') or col.startswith('Metric'):
headers.append(col)
else:
sites.append(col)
#Finalise the transpose of the headers into a new column using a new dataframe
df = pd.melt(df,
id_vars=headers,
value_vars=sites,
var_name='Site',
value_name='Value')
我现在尝试对多个文件使用此函数。我在一个路径中有文件夹,每个文件夹都有第一张图片所示格式的文件。为了使这个过程自动化,我的想法是创建一个包含数据帧的字典,然后将这些帧合并成一个。如果我在for循环中添加函数代码,效果很好:
#Dictionary of parent folders
dictionary = {}
#Dictionary of dataframes/ files per folder
dataframe_dictionary = {}
#list of all data frames. This is going to be used to create a final output (concat dataframes)
all_dataframes = []
#Find all subfolders in path
folderpath = r'C:\Documents\\'
onlyfolders = [f for f in listdir(folderpath) if not isfile(join(folderpath, f))]
#Find all the files for each folder and create a dictionary (Parent folder and its files)
for i in onlyfolders:
path = folderpath+i
pathfiles = [f for f in listdir(path) if isfile(join(path, f))]
dictionary[i] = pathfiles
numberOfFiles = len(dictionary[i])
#For each folder (folder) and then for each file create dataframe based on each CSV
for folder, file in dictionary.items():
for x in file:
#Create a unique dataframe per folder and file
filename = r'C:\Documents\\'+folder+'\\'+x
dataframe_dictionary[folder+'_'+x.replace(".csv", "")] = pd.read_csv(filename,skiprows=6,sep=',')
clean_name = dataframe_dictionary[folder+'_'+x.replace(".csv", "")]
clean_name['Folder'] = folder
####COPY PASTE THE CODE OF THE FUNCTION WITHOUT CALLING IT
all_dataframes.append(clean_name)
#Export final output
final_output = pd.concat(all_dataframes)
final_output.to_csv(r'DF1.csv', index = False)
但如果我尝试使用此选项,它将返回一个错误:
final_dataframe = transpose(clean_name)
错误是:
传递的所有对象均为“无”
问题是函数返回None。除此之外,对于如何使代码更高效、更好(不同的方法)还有什么建议吗?我看不出您在代码中在哪里使用了
转置功能!,你把它叫做哪里。。而且转置
功能运行良好,我刚刚测试过。如果不是empy,请检查clean_name
。