Python int比较在pandas中无法正常工作

2024-05-09 02:19:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个函数,用于根据数据集上的评估计算文档的数字。我选择熊猫是因为它似乎是使用大数据集最有效的方式。 我的列是:引用(标识符)、引用(标识符)、创建(字符串YYYY-MM或YYYY)。
我需要向集合中添加引用对象的所有标识符,这些对象符合在第1年或第2年创建的标准。 我发现了通过索引将数据框子集的一个很酷的技巧:我将索引的数据框保存到一个局部变量(“引用”),然后在创建列时使用.loc[identifier]['creation']获取该行的值。问题是,这可以返回一个序列(多个标识符)或一个字符串(只有一个值,因此直接返回创建日期)。
由于该值可以是str(YYYY-MM)或str(yyy)格式,因此我必须使用[:4]对其进行切片以进行实际比较,加上。 我试图基于数据类型执行条件块,但一定是出了问题,因为我用调试行打印的是:

DEBUG: 2014 is == to either 2015 or 2014
DEBUG: 2016 is == to either 2015 or 2014
DEBUG: 2018 is == to either 2015 or 2014
DEBUG: 2015 is == to either 2015 or 2014

我还尝试进行字符串比较,在str()中转换日期,然后比较字符串,不幸的是,我得到了相同的结果

for identifier in ls:
    citing = data.set_index('citing')  # save data indexed by 'citing' column to local variable
        try:                               # handle KeyError exception

            creation = citing.loc[identifier]['creation']  # this can either be a str or a pandas series

            if type(creation) == pandas.core.series.Series:
                if int(creation.iloc[0][:4]) == (int(year))-1 or int(creation.iloc[0][:4]) == (int(year))-2:
                    print('DEBUG: ', creation.iloc[0][:4], 'is == to either {} or {}'.format(str(int(year)-1), str(int(year)-2)))
                    pub.add(identifier)

            elif type(creation) == str:
                if int(creation[:4]) == (int(year))-1 or (int(year))-2:
                    print('DEBUG: ', creation[:4], 'is == to either {} or {}'.format(str(int(year)-1), str(int(year)-2)))
                    pub.add(identifier)

        except KeyError:
            pass

这确实是我在python中的第一个复杂函数,因此有些事情可能明显错误、缓慢或效率低下,请您为我详细说明,以便我可以改进我的函数! 谢谢大家!

编辑: 作为数据帧的示例输入:

 citing    cited    creation
0  1234  1235  2018-11 
1  1237  1234  2017     
2  1236  1237  2011-01
3  1234  1248  2018-11
4  1235  1236  2018-11 

如果输入是此数据帧和2018年,则结果集应仅包含{1237},因为它是在y-1或y-2中创建的唯一结果集


Tags: orto数据函数字符串debugis标识符
1条回答
网友
1楼 · 发布于 2024-05-09 02:19:07

您可以(几乎)在一次射击中找到与您的标准匹配的所有行。事实上,这更有效,因为您将在一次操作中针对所有行计算标准,而不是在每个值上循环

ix = df[
    df.creation.astype(str).str[:4].astype(int).isin({year-1, year-2})
  ].index
identifiers = set(df.loc[ix, 'citing'])
pub |= identifiers

更多解释:

.astype(str)->;确保每个值都是str类型,即使是几年(以防万一)

.str->;熊猫的字符串访问器,允许您使用字符串方法(更多信息here

[:4]->;字符串方法,将允许您捕获前4个字符

.astype(int)->;将整个结果强制转换为int(请注意,如果有缺少值的行,这可能会失败;请参阅下面的解决方法)

.isin(...)->;将允许查看(每行上的)值是否在(…)内

您将获得一个“索引”,它可用于在一次操作中过滤数据帧

如果缺少值,可以从使用df['creation'].fillna("1000", inplace=True)开始

相关问题 更多 >