【发布时间】:2020-05-30 12:59:39
【问题描述】:
我有一个数据框 MSYs_init,其中包含一个现有的“开始日期”列,其中包含大约 250 个值。我想从该列的日期中获取年份,并将其与一系列资助开始日期中的年份相匹配。请看下面,因为我认为我的事情过于复杂并且无法通过 Google-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
【问题讨论】:
-
VISTAMbrStartYr和VISTAGrantYr的长度不同。你想做什么? -
我编辑了上面的内容,并且确信我的方法是错误的。我想要一个新列来反映 VISTAGrantYrStarts 在 VISTAGrantYr 中的年份与 VISTAMbrStartYr 中的年份相匹配,否则什么都没有。
-
你需要
.isin()这个函数吗?
标签: python python-3.x pandas numpy dataframe