作为一些数据清理的一部分,我需要针对“年”和“ ID”的每个组合“对齐”“列A”中的值,具体取决于“年份”和“ ID的组合
我已经尝试过np.where()
但只收到ValueError: Can only compare identically-labeled Series objects
这是一个简短的示例数据框:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[1, 2007, 0],
[2, 2008, 0],
[2, 2009, 1],
[3, 2007, 0],
[4, 2010, 0],
[4, 2011, 1],
[4, 2011, 0]]), #I want to change this 0 to 1
columns=['ID', 'Year', 'ColA'])
结果应如下所示:
result = pd.DataFrame(np.array([[1, 2007, 0],
[2, 2008, 0],
[2, 2009, 1],
[3, 2007, 0],
[4, 2010, 0],
[4, 2011, 1],
[4, 2011, 1]]),
columns=['ID', 'Year', 'ColA'])
我们可以使用groupby.transform
同any
。然后我们得到一个结果,boolean
因此,如果将其转换为int
with,astype
我们将获得所需的结果:
m = df.groupby(['ID', 'Year'])['ColA'].transform(any).astype(int)
df['ColA'] = m
ID Year ColA
0 1 2007 0
1 2 2008 0
2 2 2009 1
3 3 2007 0
4 4 2010 0
5 4 2011 1
6 4 2011 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句