#python #pandas #dataframe
#питон #панды #фрейм данных
Вопрос:
Извините за беспорядочный код, но я работаю с этой функцией:
def zip_zap(diction): zipzap = {} #key = nwe pair = list of dfs for key, pair in diction.items(): elist= [] aftere = [] z3 = [] team = zipper[key] #for game in list of team games for i in pair[0:12]: elist.append(i) for e in elist: if e.columns.nlevels gt; 1: e.columns = e.columns.droplevel() e.apply(pd.to_numeric, errors = 'ignore') aftere.append(e.iloc[:,1:]) for i in aftere: print(i.dtypes)
Когда я запускаю это, я получаю этот вывод для каждого кадра данных. Указывает, что все столбцы имеют тип float64:
Итого float64 Тот float64 Пропуск float64 Пик float64 Товар float64 Тот float64 Пропуск float64 Пик float64 Товар float64 Тот float64 КО float64 КР float64 P float64 PR float64 FG/XP float64 dtype: объект
Но когда я пытаюсь найти разницу между строками, я получаю сообщение об ошибке, в котором говорится, что я не могу вычесть строку из строки
def zip_zap(diction): zipzap = {} #key = nwe pair = list of dfs for key, pair in diction.items(): elist= [] aftere = [] z3 = [] team = zipper[key] #for game in list of team games for i in pair[0:12]: elist.append(i) for e in elist: if e.columns.nlevels gt; 1: e.columns = e.columns.droplevel() e.apply(pd.to_numeric, errors = 'ignore') aftere.append(e.iloc[:,1:]) for i in aftere: differ = i.diff() z3.append(differ)
Это мой вывод ошибок:
TypeError Traceback (most recent call last) lt;ipython-input-140-a97f786b4bbbgt; in lt;modulegt; ----gt; 1 zip_zap(zipper) lt;ipython-input-139-bcb723143a3fgt; in zip_zap(diction) 25 for i in aftere: 26 ---gt; 27 differ = i.diff() 28 z3.append(differ) 29 # #Create Tm column and insert at first position so that we can concat the dfs ~anaconda3libsite-packagespandascoreframe.py in diff(self, periods, axis) 7254 return self.T.diff(periods, axis=0).T 7255 -gt; 7256 new_data = self._mgr.diff(n=periods, axis=bm_axis) 7257 return self._constructor(new_data) 7258 ~anaconda3libsite-packagespandascoreinternalsmanagers.py in diff(self, n, axis) 556 557 def diff(self, n: int, axis: int) -gt; "BlockManager": --gt; 558 return self.apply("diff", n=n, axis=axis) 559 560 def interpolate(self, **kwargs) -gt; "BlockManager": ~anaconda3libsite-packagespandascoreinternalsmanagers.py in apply(self, f, align_keys, **kwargs) 404 applied = b.apply(f, **kwargs) 405 else: --gt; 406 applied = getattr(b, f)(**kwargs) 407 result_blocks = _extend_blocks(applied, result_blocks) 408 ~anaconda3libsite-packagespandascoreinternalsblocks.py in diff(self, n, axis) 1270 def diff(self, n: int, axis: int = 1) -gt; List["Block"]: 1271 """ return block for the diff of the values """ -gt; 1272 new_values = algos.diff(self.values, n, axis=axis, stacklevel=7) 1273 return [self.make_block(values=new_values)] 1274 ~anaconda3libsite-packagespandascorealgorithms.py in diff(arr, n, axis, stacklevel) 1975 out_arr[res_indexer] = arr[res_indexer] ^ arr[lag_indexer] 1976 else: -gt; 1977 out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer] 1978 1979 if is_timedelta: TypeError: unsupported operand type(s) for -: 'str' and 'str'
Комментарии:
1.
apply
у панд не работает на месте. Вместо этого он возвращает новый фрейм данных. Таким образом, приложение на самом деле нигде не хранится.2. Поэтому вам нужно назначить результат обратно:
e = e.apply(...)
Ответ №1:
Измените эту строку:
e.apply(pd.to_numeric, errors = 'ignore')
к этому:
e = e.apply(pd.to_numeric, errors = 'ignore')
Потому apply()
что возвращает новый ряд/фрейм данных с изменениями; он не изменяет существующий.