Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用复杂逻辑创建计数器_Python_Pandas - Fatal编程技术网

Python 使用复杂逻辑创建计数器

Python 使用复杂逻辑创建计数器,python,pandas,Python,Pandas,我有一段类似于此的代码,但运行起来花费了大量时间: 数据如下所示。实际数据不止这些,但这是前几行: names, date1, date2, date3 A 2004-11-23 2006-11-23 2012-11-23 A 2008-11-23 2011-11-23 2011-11-23 B 2015-11-23 2013-11-23 2010-11-23 B 2013-11-23 2014-11-23 2009-11-23 C 2012

我有一段类似于此的代码,但运行起来花费了大量时间:

数据如下所示。实际数据不止这些,但这是前几行:

names, date1,     date2,     date3
A    2004-11-23  2006-11-23 2012-11-23
A    2008-11-23  2011-11-23 2011-11-23
B    2015-11-23  2013-11-23 2010-11-23
B    2013-11-23  2014-11-23 2009-11-23
C    2012-11-23. 2015-11-23 2008-11-23
C    2021-11-23. 2017-11-23 2002-11-23
C    2009-11-23  2016-11-23 2011-11-23 
运行此代码后,我应该得到五列

for name in df['names'].unique():
    for dt in df[df['names'] == name]['date1'].unique():
        test = df[(df['names'] == name) & (df['date2'] <= dt)]
        test = test.drop(index = test[test['date1'] > dt].index)
        test = test.drop(index = test[test['date3'] > dt].index)
        
        test['count'] = test['names'].transform('nunique')

还有,还有什么方法可以加快速度吗?

sudo=pseudo?如果按名称分组,为什么A组中没有值为1的计数器?没有,计数器1在B组中
name 'test' is not defined