我有一个数据框架MSYs_init,它包含一个现有的列“Start Date”,大约有250个值。我想从该列的日期中选取年份,并将其与一系列赠款开始日期中的年份相匹配。请看下面,因为我相信我已经把事情复杂化了,无法通过谷歌fu获得解决方案
MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'], errors='coerce')
VISTAMbrStartYr = pd.DatetimeIndex(MSYs_init['Start Date']).year
VISTAGrantYrStarts = pd.Series(['2020, 8, 17','2019, 8, 18', '2018, 8, 19', '2017, 9, 17'])
VISTAGrantYrStarts = pd.to_datetime(VISTAGrantYrStarts, errors='coerce')
VISTAGrantYr = pd.DatetimeIndex(VISTAGrantYrStarts).year
MSYs_init['VISTA Grant Year'] = np.where(VISTAMbrStartYr == VISTAGrantYr, VISTAGrantYrStarts, np.nan)
这是我的错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-129-27a1a1454145> in <module>
12 VISTAGrantYr = pd.DatetimeIndex(VISTAGrantYrStarts).year
13
---> 14 MSYs_init['Mbr Starting Grant Yr'] = np.where((VISTAMbrStartYr == VISTAGrantYr) &
15 (VISTAMbrStartMoDay >= VISTAGrantYrStartMoDay),
16 VISTAMbrStartYr,VISTAMbrStartYr-1)
~\anaconda3\envs\PythonData\lib\site-packages\pandas\core\indexes\base.py in cmp_method(self, other)
100 if isinstance(other, (np.ndarray, Index, ABCSeries)):
101 if other.ndim > 0 and len(self) != len(other):
--> 102 raise ValueError("Lengths must match to compare")
103
104 if is_object_dtype(self) and not isinstance(self, ABCMultiIndex):
ValueError: Lengths must match to compare
如果我理解正确,您试图实现的目标可以通过以下方式实现:
工作示例:
输出:
@Celius,我需要它来返回VISTAGrantYrStarts,而不是“开始日期”,所以当我尝试这样做时,它不起作用
相关问题 更多 >
编程相关推荐