【问题标题】:Copy and rename files using a pandas dataframe使用 pandas 数据框复制和重命名文件
【发布时间】:2020-12-17 23:52:14
【问题描述】:

我是 python 的相对较新的用户,因此在以下方面苦苦挣扎。本质上,我试图将一堆文件从一个文件夹移动到另一个文件夹,并使用我构建的 pandas df 重命名它们 - states_mapping_df。我尝试使用 states_mapping_df = states_mapping_df.astype("string") 将 df 转换为字符串,但这没有帮助。

from shutil import copyfile
covid_src_dir = r"I:\COVID\COVID tracker\UserA\Hospitalizations"

covid_new_dir = r"I:\COVID\COVID tracker\Hospitalizations_images"

states_mapping_df = pd.DataFrame ({"Abbr" :['CA','FL','IL','NJ','NY','NC','OH','PA','TX','VA'],
                                   "State_Name" :['California','Florida','Illinois','New Jersey','New York','North Caroliina','Ohio','Pennsylvania','Texas','Virginia']})

for row in states_mapping_df['Abbr']:
    #oldname = states_mapping_df['Abbr']+'.png'
    #newname = states_mapping_df['State_Name']+'.png'
    oldpath_covid = covid_src_dir + "\\" + row +'.png'
    newpath_covid = covid_new_dir + "\\" + states_mapping_df['State_Name'].astype('string') +'.png'
    copyfile(oldpath_covid, newpath_covid)

运行时出现以下错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-260-40e52504bb33> in <module>
     19     oldpath_covid = covid_src_dir + "\\" + row +'.png'
     20     newpath_covid = covid_new_dir + "\\" + states_mapping_df['State_Name'].astype('string') +'.png'
---> 21     copyfile(oldpath_covid, newpath_covid)
     22     #shutil.copy(oldpath_covid, newpath_covid)

~\Anaconda3\lib\shutil.py in copyfile(src, dst, follow_symlinks)
    238     sys.audit("shutil.copyfile", src, dst)
    239 
--> 240     if _samefile(src, dst):
    241         raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
    242 

~\Anaconda3\lib\shutil.py in _samefile(src, dst)
    215     if hasattr(os.path, 'samefile'):
    216         try:
--> 217             return os.path.samefile(src, dst)
    218         except OSError:
    219             return False

~\Anaconda3\lib\genericpath.py in samefile(f1, f2)
     99     """
    100     s1 = os.stat(f1)
--> 101     s2 = os.stat(f2)
    102     return samestat(s1, s2)
    103 

TypeError: stat: path should be string, bytes, os.PathLike or integer, not Series

【问题讨论】:

    标签: python python-3.x pandas dataframe shutil


    【解决方案1】:

    我相信你的问题就在这里states_mapping_df['State_Name']

    错误是告诉您您正在使用系列。您正在尝试将文件重命名为 DataFrame 中的一整列值(系列)。

    你需要过滤你想要的实际值。

    试试这个。

    for row in states_mapping_df['Abbr']:
        #oldname = states_mapping_df['Abbr']+'.png'
        #newname = states_mapping_df['State_Name']+'.png'
        
        # filter row of df according to present row from abbr
        filt = (df['Abbr']==row)
        # use .loc to isolate the specific cell from the filter and the column name
        row_filtered = df.loc[filt, 'State_Name']
        # a list is returned where first value is the cell value
        state_name = row_filtered.values[0]
        oldpath_covid = covid_src_dir + "\\" + row +'.png'
        # renamed the initial series to the state name
        newpath_covid = covid_new_dir + "\\" + 
        state_name +'.png'
        copyfile(oldpath_covid, newpath_covid)
    

    编辑,更多信息:

    .loc 是一种过滤 Pandas DataFrame 的方法。您通过 df.loc[a,b] 传递两个参数 a,b 其中 a = 行和 b = 列。 通常,大多数人会以与我在上面相同的方式使用它,他们首先像我一样创建一个用于a 的过滤器。 (df['state'] == 'California') 将返回一个布尔值列表 (true/false),其中只有 California 的实例会返回 True。然后,当您通过 .loc[] 以及您的列名时,您返回特定的单元格(或单元格,如果通过 b 的多个列名)。然后调用.values 返回一个由所述值组成的数组。

    另一种方法是.iloc[],虽然i 表示integer,但它的工作方式相同。因此,如果您想返回第 10 行和第 5 到 8 列,您可以使用 df.iloc[10,5:8]

    或者如果你想返回所有你也可以做的df.iloc[:,:] 或者如果你想返回你的行值等于加利福尼亚的所有列,使用与上面相同的过滤器表达式,那么你可以使用df.loc[filt, ::]

    冒号表达式表示索引切片,就像您在列表中所做的那样。

    更多:

    loc https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html

    iloc https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html

    索引和切片 https://realpython.com/lessons/indexing-and-slicing/

    各种其他过滤方法,包括提到的那些 https://towardsdatascience.com/7-different-ways-to-filter-pandas-dataframes-9e139888382a

    【讨论】:

    • 谢谢!我明白你的意思。不得不进行一些其他更改,但设法使其发挥作用。
    • 不客气。请点击勾号将我的帖子标记为答案,以便其他人看到。干杯!
    猜你喜欢
    • 2018-09-23
    • 2018-04-02
    • 2019-03-03
    • 2022-01-09
    • 2021-07-21
    • 1970-01-01
    • 2016-03-25
    • 2019-04-29
    • 2013-06-13
    相关资源
    最近更新 更多