我有一个包含许多列的大型数据框(100000行)。以下是我的问题的相关专栏:
id herd birth H_BY HYcount death H_DY HYcount2
1 1345 2005-01-09 134505 1 2010-01-09 134510 1
2 1345 2010-03-05 134510 2 2015-01-09 134515 2
3 1345 2010-05-10 134510 2 2015-01-09 134515 2
4 1345 2011-06-01 134511 1 2016-01-09 134516 1
5 1345 2012-09-01 134512 1 2017-01-09 134517 2
6 1345 2015-09-13 134515 1 2017-01-09 134517 2
7 1346 2015-10-01 134615 3 2019-01-09 134619 1
8 1346 2015-10-27 134615 3 2020-01-09 134620 2
9 1346 2015-11-10 134615 3 2020-01-09 134620 2
10 1346 2016-12-10 134616 1 2021-01-09 134621 1
我正在创建牛群年固定效果。 我已经将从众和出生/死亡列组合成从众+出生年和从众+死亡年两个单独的列,并计算了每个固定效应在数据框中出现的时间。如上所述
但是,现在我想检查整个数据帧中小于3的HYcount和HYcount2。所以我不想在HY组中有任何1或2
我想运行数据帧,并将每个组1或2的HY组组合到其他组中。低于或高于
编辑
我也只想在每个畜群中组合HY组
所以我不想将一个牧群的牧群成员添加到另一个具有牧群年份变量的牧群中
这是我用出生年份固定效应试过的
#Sort the df by the relevant value
df= df.sort_values(by=['H_BY'])
df.loc[
(df['HYcount'] < 3),
'H_BY'] = df['H_BY'].shift(-1)
#Count the values again
df['HC1_c'] = df.groupby('H_BY')['H_BY'].transform('count')
但这是一个非常微弱的尝试。我必须多次执行此操作,以清除数据帧中所有小于3的值,并且它无法处理记录编号1。我想在至少4列上重复这个过程
编辑
当然,这段代码对在一个群体中组合没有任何作用
有什么建议和窍门或想法,我可以如何更有效地做到这一点
编辑
上述数据除外
id herd birth H_BY HYcount death H_DY HYcount2
1 1345 2005-01-09 134510 3 2010-01-09 134515 3
2 1345 2010-03-05 134510 3 2015-01-09 134515 3
3 1345 2010-05-10 134510 3 2015-01-09 134515 3
4 1345 2011-06-01 134515 3 2016-01-09 134517 3
5 1345 2012-09-01 134515 3 2017-01-09 134517 3
6 1345 2015-09-13 134515 3 2017-01-09 134517 3
7 1346 2015-10-01 134615 4 2019-01-09 134620 4
8 1346 2015-10-27 134615 4 2020-01-09 134620 4
9 1346 2015-11-10 134615 4 2020-01-09 134620 4
10 1346 2016-12-10 134615 4 2021-01-09 134620 4
为了解决这个问题,我删除了
H_BY
和H_DY
列,以便允许对组进行动态计数。在数据帧中包含计数的问题之一是,如前所述,您需要重新计算它 更改分组的时间,以及重复计数的时间然后,我将
birth
和death
更改为datetimes
,以便为出生年份和死亡年份by
和dy
创建新列对于实际处理,我们首先按
herd
分组,这样就不会在它们之间混淆。然后,如果可能,我们向前合并组,否则向后合并组,直到不再发生合并。最后,我们将这些组分配回原始数据最后,如果仍然需要用于分组的
H_BY
标识符,可以使用相关问题 更多 >
编程相关推荐