> mutate(d-6ren">
gpt4 book ai didi

python - dfply:变异字符串列:TypeError

转载 作者:太空狗 更新时间:2023-10-30 02:55:22 29 4
gpt4 key购买 nike

我的 Pandas 数据框包含一个"file"列,它是带有文件路径的字符串。我正在尝试使用 dfply 来改变此列,例如

resultstatsDF.reset_index() >> mutate(dirfile = os.path.join(os.path.basename(os.path.dirname(X.file)),os.path.basename(X.file)))

但是我得到了错误

TypeError: __index__ returned non-int (type Call)

我做错了什么?我该怎么做才正确?

最佳答案

由于我的问题获得了赞成票,我想,它对某些人来说仍然很有趣。到目前为止,我已经在 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']})

这是

                        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)))

TypeError: index returned non-int (type Intention)

原因是,因为 mutate 适用于系列,但我们需要一个适用于元素的函数。这里我们可以使用函数pandas.Series.apply 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)

关于python - dfply:变异字符串列:TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42671168/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com