【问题标题】:Lengths of series not matching for np.where与 np.where 不匹配的系列长度
【发布时间】: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

【问题讨论】:

  • VISTAMbrStartYrVISTAGrantYr 的长度不同。你想做什么?
  • 我编辑了上面的内容,并且确信我的方法是错误的。我想要一个新列来反映 VISTAGrantYrStarts 在 VISTAGrantYr 中的年份与 VISTAMbrStartYr 中的年份相匹配,否则什么都没有。
  • 你需要.isin()这个函数吗?

标签: python python-3.x pandas numpy dataframe


【解决方案1】:

如果我理解正确,您可以通过以下方式实现您的目标:

MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'], errors='coerce')
VISTAGrantYrStarts = pd.to_datetime(VISTAGrantYrStarts, errors='coerce')
VISTAGrantYr = VISTAGrantYrStarts.year
MSYs_init['VISTA Grand Year'] = np.where(MSYs_init['Start Date'].dt.year.isin(VISTAGrantYr),
                                         MSYs_init['Start Date'].dt.year,
                                         np.nan)

工作示例:

import pandas as pd
import numpy as np
df=pd.DataFrame({'index':[0,1,2,3],
                 'dates':['2019-02-20','2019-02-21','2020-02-21','2021-02-20']})
df['dates'] = pd.to_datetime(df['dates'],errors='coerce')
aux = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
df['dates_2'] = np.where(df['dates'].dt.year.isin(aux),df['dates'].dt.year,np.nan)

输出:

   index      dates  dates_2
0      0 2019-02-20   2019.0
1      1 2019-02-21   2019.0
2      2 2020-02-21      NaN
3      3 2021-02-20      NaN

@Celius,我需要它来返回 VISTAGrantYrStarts,而不是“开始日期”,所以当我尝试这样做时,它不起作用。

MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'],errors='coerce')
GrantStarts = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
MSYs_init['Mbr Grant Start'] = np.where(MSYs_init['Start Date'].dt.year.isin(GrantStarts),GrantStarts.dt.year,np.nan)
MSYs_init.head(50)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-71-52fd06b959bf> in <module>
      1 MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'],errors='coerce')
      2 GrantStarts = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
----> 3 MSYs_init['Mbr Grant Start'] = np.where(MSYs_init['Start Date'].dt.year.isin(GrantStarts),GrantStarts.dt.year,np.nan)
      4 MSYs_init.head(50)

AttributeError: 'Int64Index' object has no attribute 'dt'

【讨论】:

  • 抛出此错误:AttributeError: 'Series' object has no attribute 'year'
  • 不过,isin 可能会有所帮助。我想这样做:
  • MSYs_init['VISTA Grant Year'] = np.where(VISTAGrantYr.isin(VISTAGrantYr), VISTAGrantYrStarts, np.nan)
  • 是的,我忘了你已经用.year定义了一个变量
  • 但这给了我这个错误:“无效类型提升”
猜你喜欢
  • 1970-01-01
  • 2018-02-22
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 2018-09-23
  • 1970-01-01
  • 2016-05-09
相关资源
最近更新 更多