python - 使用 pandas 将多个 xlsm 文件自动转换为多个 csv 文件

标签 python pandas

我有 300 个原始数据(.xlsm),想要提取有用的数据并将它们转换为 csv 文件作为后续神经网络的输入,现在我尝试用 10 个数据来实现它们作为示例,我已经成功提取了信息我需要,但我不知道如何将它们转换为同名的 csv 文件,对于单个数据我们可以使用 df.to_csv,但是对于所有数据怎么样?与 for 函数?

    import glob
    import pandas as pd
    import numpy as np
    import csv
    import os

    excel_files = glob.glob('../../Versuch/Versuche/RohBeispiel/*.xlsm') 
    directory = '/Beispiel'
    for files in excel_files:
        data = pd.read_excel(files)
        # getting the list of rows and columns you need
        list_of_dfs = pd.DataFrame(data.values[0:600:,12:26], 
                                   columns=data.columns[12:26]).drop(['Sauberkeit', 'Temparatur'], axis=1)
        # converting pandas dataframe columns to numeric: string into float
        cols = ['KonzA', 'KonzB', 'KonzC', 'TempA', 
                'TempB', 'TempC', 'Modul1', 'Modul2', 
                'Modul3', 'Modul4', 'Modul5', 'Modul6']
        list_of_dfs[cols] = list_of_dfs[cols].apply(pd.to_numeric, errors='coerce', axis=1)
        # Filling down from a column through missing data
        for fec in list_of_dfs[cols]:
            list_of_dfs[fec].fillna(method='ffill', inplace=True)       

        csvfilename = files.split('/')[-1].split('.')[0] + '.csv'
        newtempfile = os.path.join(directory,csvfilename)
        print(newtempfile)
        print(list_of_dfs.head(2))

问题已解决。

folder_name = 'Beispiel'
csvfilename = files.split('/')[-1].split('.')[0] + '.csv'  # change into csv files
newtempfile = os.path.join(folder_name, csvfilename)

# Verify if directory exists
if not os.path.exists(folder_name):
    os.makedirs(folder_name)  # If not, create it

print(newtempfile)
list_of_dfs.to_csv(newtempfile, index=False)

最佳答案

最简单的方法是从 Excel 中获取文件名,然后使用 os.path.join() 方法将其保存到您想要的目录。

directory = "C:/Test"
for files in excel_files:
    csvfilename = (os.path.basename(file)[-1]).replace('.xlsm','.csv') 
    newtempfile=os.path.join(directory,csvfilename)

由于您已经有了要插入 csv 文件的 excel df,只需将上述代码添加到循环中并将输出 csv 文件更改为“newtempfile”即可。

df.to_csv(newtempfile, 'Beispel/data{0}.csv'.format(idx))

希望这有帮助。 :)

更新的代码:

    cols = ['KonzA', 'KonzB', 'KonzC', 'TempA', 
                    'TempB', 'TempC', 'Modul1', 'Modul2', 
                        'Modul3', 'Modul4', 'Modul5', 'Modul6']
    excel_files = glob.glob('../../Versuch/Versuche/RohBeispiel/*.xlsm')
        for file in excel_files:
            data = pd.read_excel(file, columns = cols) # import only the columns you need to the dataframe
            csvfilename = (os.path.basename(files)[-1]).replace('.xlsm','.csv') 
            newtempfile=os.path.join(directory,csvfilename)
            
            # converting pandas dataframe columns to numeric: string into float
            data[cols] = data[cols].apply(pd.to_numeric, errors='coerce', axis=1)
            data[cols].fillna(method='ffill', inplace=True)
            data.to_csv(newtempfile).format(idx)

关于python - 使用 pandas 将多个 xlsm 文件自动转换为多个 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53590379/

相关文章:

python - 如何在scrapy中获取队列中的请求数?

python - Pandas - 根据百分比获取前 n 行

python-3.x - 使用 Python 解压从 JSON 获得的字典

python - Pandas DataFrames 中的平等 - 列顺序很重要?

python - 如何显示 1 列的值相对于 Python 中 Excel 工作表中某些其他列中存在的特定值?

python - Try/Except,不返回 except

python - 在 Python 的类中创建 JSON

python - NLTK FCFG 语法标准/规范是什么?

python - Pyocrypt DES3文件加密,解密缺失部分文本

python - Pandas 子集根据另一个数据中的值从数据框中随机选择行数