为什么 Pandas 这样做?

Why is Pandas doing this?

我在 'Outcome Date' 列上应用一个函数,它将更改它的日期格式。

def change_date_format(row):

    old_date = row['Outcome Date']
    old_date_reformatted  = datetime.datetime.strptime(old_date, '%m/%d/%Y %H:%M').strftime('%Y-%m-%d %H:%M')
    row['Outcome Date'] = old_date_reformatted

    return row


ffn = os.path.join(new_ciq_root, filename)

in_df = pd.read_csv(ffn, encoding="ISO-8859-1")
in_df[col_name] = in_df.apply(lambda row: change_date_format(row), axis=1)

我在应用函数中放置了一个断点,它到达最后一行,该行的 'Outcome Date' 似乎被正确地重新格式化(下面的屏幕截图)

但最终结果不是具有正确重新格式化的 'Outcome Date' 列的 DF,而是其中 'Outcome Date' 被 'Outcome Type' 列的值替换的位置。我做错了什么??

提示? 我的调试器在每次迭代 C:\Users\aidenm\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\pandas\core\apply.py 中遇到以下异常

    def apply_standard(self):

        # try to reduce first (by default)
        # this only matters if the reduction in values is of different dtype
        # e.g. if we want to apply to a SparseFrame, then can't directly reduce

        # we cannot reduce using non-numpy dtypes,
        # as demonstrated in gh-12244
        if (self.result_type in ['reduce', None] and
                not self.dtypes.apply(is_extension_type).any()):

            # Create a dummy Series from an empty array
            from pandas import Series
            values = self.values
            index = self.obj._get_axis(self.axis)
            labels = self.agg_axis
            empty_arr = np.empty(len(index), dtype=values.dtype)
            dummy = Series(empty_arr, index=index, dtype=values.dtype)

            try:
                result = reduction.reduce(values, self.f,
                                          axis=self.axis,
                                          dummy=dummy,
                                          labels=labels)
                return self.obj._constructor_sliced(result, index=labels)
            except Exception:
                pass
  1. apply 之后你得到一个新的 df 但你将它分配给旧的 in_df[col_name]

你应该df = df.apply(...)

  1. lambda row: change_date_format(row) 等同于传递 change_date_format lambda 是多余的。

  2. 在您的情况下,apply 单个 Series 上的函数比 Series 上的函数更好更优雅行:

in_df[col_name] = in_df[col_name].apply(change_date_format1(col), axis=0)

你的函数 change_date_format1 在这种情况下应该是:

lambda x: datetime.datetime.strptime(x, '%m/%d/%Y %H:%M').strftime('%Y-%m-%d %H:%M')