由于我的问题得到了赞成,我想,有些人仍然对此感兴趣。到目前为止,我已经对 Python 有了相当多的了解,让我来回答一下,也许这会对其他用户有所帮助。
首先我们导入需要的包
import pandas as pd
from dfply import *
from os.path import basename, dirname, join
并制作所需的 pandas DataFrame
resultstatsDF = pd.DataFrame({'file': ['/home/user/this/file1.png', '/home/user/that/file2.png']})
which is
file
0 /home/user/this/file1.png
1 /home/user/that/file2.png
我们看到仍然出现错误(尽管由于 dfply 的不断开发而发生了变化):
resultstatsDF.reset_index() >> \
mutate(dirfile = join(basename(dirname(X.file)), basename(X.file)))
类型错误:index返回非 int (意图类型)
原因是,因为 mutate 适用于系列,但我们需要一个适用于元素的函数。这里我们可以使用这个函数pandas.Series.apply https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html的 pandas,适用于系列。
但是,我们还需要一个自定义函数,可以将其应用于该系列的每个元素file
。
所有的东西放在一起我们最终得到了代码
def extract_last_dir_plus_filename(series_element):
return join(basename(dirname(series_element)), basename(series_element))
resultstatsDF.reset_index() >> \
mutate(dirfile = X.file.apply(extract_last_dir_plus_filename))
哪个输出
index file dirfile
0 0 /home/user/this/file1.png this/file1.png
1 1 /home/user/that/file2.png that/file2.png
在没有 dfply 的情况下执行此操作mutate
,我们也可以写成
resultstatsDF['dirfile'] = resultstatsDF.file.apply(extract_last_dir_plus_filename)