【问题标题】:Unable to update nan values in column using loc?无法使用 loc 更新列中的 nan 值?
【发布时间】:2020-10-23 11:10:32
【问题描述】:

我已经存储了该列在索引中缺少值的所有记录的索引值,并且我正在尝试根据两个数据帧中常见的“StockCode”列从另一个数据帧中估算 nan 值。

这就是 df_mod 的样子。 df 也相同,但描述为 nan。索引是数组,如 [1,2,3,4] snapshot of df_mod

for i in index:
    if df.loc[i,'StockCode'] in df_mod['StockCode'].values:
        df.loc[i,'Description']=df_mod.loc[(df_mod.StockCode==df.loc[i,'StockCode']),'Description']
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-201-ada042d0d5a1> in <module>
      1 for i in index:
      2     if df.loc[i,'StockCode'] in df_mod['StockCode'].values:
----> 3         df.loc[i,'Description']=df_mod.loc[(df_mod.StockCode==df.loc[i,'StockCode']),'Description']

D:\Anaconda\lib\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):

D:\Anaconda\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value)
    467 
    468             if isinstance(value, ABCSeries):
--> 469                 value = self._align_series(indexer, value)
    470 
    471             info_idx = indexer[info_axis]

D:\Anaconda\lib\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 nan pandas-loc


    【解决方案1】:

    没有(样本)您的数据,很难说。但这可能是replace 的情况:

    df['Description'] = df['StockCode'].replace(df_mod.set_index('StockCode')['Description'])
    

    【讨论】:

    • 嗨@Quang 我添加了一个快照以使其更清晰。你现在能帮我吗
    猜你喜欢
    • 1970-01-01
    • 2022-06-20
    • 2017-07-15
    • 2023-02-08
    • 2019-12-16
    • 1970-01-01
    • 2022-08-18
    • 2012-09-04
    • 1970-01-01
    相关资源
    最近更新 更多