繁体   English   中英

Pandas 在遍历目录时不会将列添加到 dataframe

[英]Pandas wont add column to dataframe while iterating through a directory

当我运行时,我尝试通过遍历这样的目录在 pandas dataframe 中添加一列

import pandas as pd
import os
import sys

########generate file path
'getcwd:      ', os.getcwd()
osfile, maindir =('__file__:    ', __file__)
filename = os.path.basename(sys.argv[0])
inpath = maindir.replace(filename,"Excels")
outpath = maindir.replace(filename,"BulkFile.xlsx")


#########pandas script
def add_column():
    for root, dirs, files in os.walk(inpath):
        print(files)
        for f in files:
            path = os.path.join(root, f)
            excelframe = pd.read_excel(path)
            excelframe['full_name'] = excelframe['first_name'] + " " + excelframe['last_name']
            dataframe = [excelframe]
            compactframe = pd.concat(dataframe)
            compactframe.to_excel(outpath)

它什么也不做,没有错误代码或任何东西,它什么也不做。 但是如果我不遍历一个目录并用这个替换那个脚本

import pandas as pd
import sys
import os



#####generate file path
osfile, maindir =('__file__:    ', __file__)
filename = os.path.basename(sys.argv[0])
inpath = maindir.replace(filename,"BulkFile.xlsx")
outpath = maindir.replace(filename,"newfile.xlsx")




########pandas script
excelframe = pd.read_excel(inpath)
excelframe['full_name'] = excelframe['first_name'] + " " + excelframe['last_name']
dataframe = [excelframe]
compactframe = pd.concat(dataframe)
compactframe.to_excel(outpath)

它工作得很好。 有谁知道这是为什么或如何遍历目录并将列添加到 dataframe?

您已经定义了 function add_column但您还没有运行它。 将行add_column()添加到要执行的第一个脚本的末尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM