Что я делаю не так? Невозможно выполнить строку кода. Python | Наука о данных | Набор данных о продажах Big Mart - PullRequest
0 голосов
/ 12 июля 2020

Я пытался научиться анализировать набор данных о продажах в Big Mart. В столбце Item_Weight есть несколько значений NaN . Поэтому я хотел обновить эти значения, найдя значения из pivot_table , который содержит Item_Identifier как Index и Item_Weight . Это изображение

enter image description here

cdata['Item_Weight'] = cdata[['Item_Weight','Item_Identifier']].apply(lambda x: item_avg_weight.loc[x[1],'Item_Weight'] if pd.isnull(x[0]) else x[1]).astype(float)

But when I run the above line of code, I get an error

I am unable to get why I am getting this error.

Link to data set : https://www.kaggle.com/brijbhushannanda1979/bigmart-sales-data/data

РЕДАКТИРОВАТЬ 1

Журнал ошибок

ValueError                                Traceback (most recent call last)
<ipython-input-158-7ecf8cf7385f> in <module>
----> 1 cdata['Item_Weight'] = cdata[['Item_Weight','Item_Identifier']].apply(lambda x: item_avg_weight.loc[x[1],'Item_Weight'] if pd.isnull(x[0]) else x[1]).astype(float)

~\Anaconda3\lib\site-packages\pandas\core\generic.py in astype(self, dtype, copy, errors, **kwargs)
   5689             # else, only a single dtype is given
   5690             new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors,
-> 5691                                          **kwargs)
   5692             return self._constructor(new_data).__finalize__(self)
   5693 

~\Anaconda3\lib\site-packages\pandas\core\internals\managers.py in astype(self, dtype, **kwargs)
    529 
    530     def astype(self, dtype, **kwargs):
--> 531         return self.apply('astype', dtype=dtype, **kwargs)
    532 
    533     def convert(self, **kwargs):

~\Anaconda3\lib\site-packages\pandas\core\internals\managers.py in apply(self, f, axes, filter, do_integrity_check, consolidate, **kwargs)
    393                                             copy=align_copy)
    394 
--> 395             applied = getattr(b, f)(**kwargs)
    396             result_blocks = _extend_blocks(applied, result_blocks)
    397 

~\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in astype(self, dtype, copy, errors, values, **kwargs)
    532     def astype(self, dtype, copy=False, errors='raise', values=None, **kwargs):
    533         return self._astype(dtype, copy=copy, errors=errors, values=values,
--> 534                             **kwargs)
    535 
    536     def _astype(self, dtype, copy=False, errors='raise', values=None,

~\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in _astype(self, dtype, copy, errors, values, **kwargs)
    631 
    632                     # _astype_nansafe works fine with 1-d only
--> 633                     values = astype_nansafe(values.ravel(), dtype, copy=True)
    634 
    635                 # TODO(extension)

~\Anaconda3\lib\site-packages\pandas\core\dtypes\cast.py in astype_nansafe(arr, dtype, copy, skipna)
    700     if copy or is_object_dtype(arr) or is_object_dtype(dtype):
    701         # Explicit copy, or required since NumPy can't view from / to object.
--> 702         return arr.astype(dtype, copy=True)
    703 
    704     return arr.view(dtype)

ValueError: could not convert string to float: 'DRC01'

Что мне требуется?

Я хочу обновить cdata DataFrame , чтобы столбец Item_Weight не имел значений NaN. Я хочу сделать это с помощью сводной таблицы, а именно item_avg_weight , которая содержит вес элемента на Item_Identifier

EDIT 2

Информация о фрейме данных

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 14204 entries, 0 to 14203
Data columns (total 13 columns):
Item_Fat_Content             14204 non-null object
Item_Identifier              14204 non-null object
Item_MRP                     14204 non-null float64
Item_Outlet_Sales            8523 non-null float64
Item_Type                    14204 non-null object
Item_Visibility              14204 non-null float64
Item_Weight                  11765 non-null float64
Outlet_Establishment_Year    14204 non-null int64
Outlet_Identifier            14204 non-null object
Outlet_Location_Type         14204 non-null object
Outlet_Size                  10188 non-null object
Outlet_Type                  14204 non-null object
source                       14204 non-null object
dtypes: float64(4), int64(1), object(8)
memory usage: 1.4+ MB

1 Ответ

1 голос
/ 12 июля 2020
  • Насколько я понимаю, для Item_Weight вы хотите fillna на основе mean каждой группы в Item_Identifier
  • Это может быть выполняется с использованием groupby и groupby.apply следующим образом
  • Должно быть два файла, поэтому создайте фрейм данных для каждого файла
  • NaN значений можно заполнить или отбросить, например, df_test.dropna(inplace=True)
import pandas as pd

# create two dataframes
df_test = pd.read_csv('datasets_9961_14084_Test.csv')
df_train = pd.read_csv('datasets_9961_14084_Train.csv')

# fill the NaN values in Item_Weight with the mean of their repective Item_Identifier group
df_test.Item_Weight = df_test.groupby('Item_Identifier')['Item_Weight'].apply(lambda x: x.fillna(x.mean()))
df_train.Item_Weight = df_train.groupby('Item_Identifier')['Item_Weight'].apply(lambda x: x.fillna(x.mean()))
...