Name a dataframe based on csv file name?

前提是你 提交于 2021-01-27 17:28:33

问题


Trying to batch analyze a folder full of .csv files, then save them out again based on the .csv name. However, I'm having trouble extracting just the file name and assigning it to the dataframe (df).

import glob
import pandas as pd

path = r'csv_in'
allFiles = glob.glob(path + '/*.csv')

for file_ in allFiles:   
    df = pd.read_csv(file_, header=0)
    df.name = file_
    print(df.name)

The print result I get is "csv_in/*.csv".

The result I'm looking for is just the csv name, "*.csv"


回答1:


Create new column with [] and os.path.basename with os.path.normpath:

import os

for file_ in allFiles:   
    df = pd.read_csv(file_, header=0)
    df['name'] = os.path.basename(os.path.normpath(file_))
    #if need remove extension (csv)
    #df['name'] = os.path.splitext(os.path.basename("hemanth.txt"))[0]
    print(df.name)


来源:https://stackoverflow.com/questions/57751788/name-a-dataframe-based-on-csv-file-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!