【问题标题】:ValueError: Incompatible indexer with Series while adding date to Date to Data FrameValueError:将日期添加到数据框时与系列不兼容的索引器
【发布时间】:2022-05-10 17:16:04
【问题描述】:

我是 python 新手,不知道为什么会出现此错误:ValueError: Incompatible indexer with Series。

我正在尝试向我的数据框添加日期。

我要添加的日期:

date = (chec[(chec['Día_Sem']=='Thursday') & (chec['ID']==2011957)]['Entrada'])
date

日期输出:


56   1900-01-01 07:34:00
Name: Entrada, dtype: datetime64[ns]

然后我尝试使用 loc 将“日期”添加到我的数据框中:

rep.loc[2039838,'Thursday'] = date
rep

我得到这个错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-347-3e0678b0fdbf> in <module>
----> 1 rep.loc[2039838,'Thursday'] = date
      2 rep

~/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py in __setitem__(self, key, value)
    188             key = com.apply_if_callable(key, self.obj)
    189         indexer = self._get_setitem_indexer(key)
--> 190         self._setitem_with_indexer(indexer, value)
    191 
    192     def _validate_key(self, key, axis):

~/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py in _setitem_with_indexer(self, indexer, value)
    640                 # setting for extensionarrays that store dicts. Need to decide
    641                 # if it's worth supporting that.
--> 642                 value = self._align_series(indexer, Series(value))
    643 
    644             elif isinstance(value, ABCDataFrame):

~/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py in _align_series(self, indexer, ser, multiindex_indexer)
    781             return ser.reindex(ax)._values
    782 
--> 783         raise ValueError('Incompatible indexer with Series')
    784 
    785     def _align_frame(self, indexer, df):

ValueError: Incompatible indexer with Series

【问题讨论】:

    标签: python pandas date valueerror


    【解决方案1】:

    尝试date.iloc[0] 而不是date

    rep.loc[2039838,'Thursday'] = date.iloc[0]
    

    因为date 实际上是一个值的系列(基本上就像一个列表/数组),而.iloc[0] 实际上选择了值。

    【讨论】:

      【解决方案2】:

      你使用loc获取具体值,而你的日期类型是series或者dataframe,两者之间的类型不能匹配,你可以改代码把date的值给rep.loc[2039838,' Thursday'],例如,如果您的日期类型是系列且不为空,您可以这样做:

      rep.loc[2039838,'Thursday'] = date.values[0]
      
      

      【讨论】:

        【解决方案3】:

        我也面临类似的问题,但情况不同。我遇到了重复索引的线程,但我当然不是这种情况。对我有用的是使用.at 代替.loc。所以你可以试试看是否有效

        rep['Thursday'].at[2039838] = date.values[0]

        【讨论】:

          猜你喜欢
          • 2021-03-12
          • 1970-01-01
          • 1970-01-01
          • 2021-01-19
          • 1970-01-01
          • 2021-09-06
          • 2020-05-17
          • 2017-05-22
          • 2011-02-03
          相关资源
          最近更新 更多