【问题标题】:dfply: Mutating string column: TypeErrordfply:变异字符串列:TypeError
【发布时间】:2017-03-08 12:16:59
【问题描述】:

我的 pandas 数据框包含一列“文件”,它是带有文件路径的字符串。我正在尝试使用 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 pandas dfply


    【解决方案1】:

    由于我的问题被投了赞成票,我猜,这对某些人来说仍然很有趣。到目前为止已经在 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 返回非 int(意图类型)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 2021-04-21
      • 1970-01-01
      • 2015-06-11
      相关资源
      最近更新 更多