【问题标题】:Can anyone help me processing data with Python?谁能帮我用 Python 处理数据?
【发布时间】:2021-01-02 13:20:49
【问题描述】:

所以我有一个 DataFrame 列表:

list_table = [a, b, c, d, e, f, g]

我想从每个 DataFrame 中删除 "Unnamed: 36" 列并将数据类型更改为数字,并且我还想创建一个新列,该列从名为 'Total' 的每一行的总和中获得。

这是我的to_numeric 函数:

def to_numeric(df):
    col = df.columns

    for i in range(len(col)):
        df[col[i]] = pd.to_numeric(
            df[col[i]].fillna(0).apply(
                lambda x: str(x).replace(",", "")
            )
        )

    return df

我的 for 循环进行处理:

for newtable in list_table:
    newtable = newtable.drop("Unnamed: 36", axis=1)
    newtable = to_numeric(newtable)
    newtable['Total'] = newtable.sum(axis=1)
    newtable.index = pd.to_datetime(newtable.index)

但是在处理循环之后,每个 DataFrame 都没有改变,所以我有点困惑这样做。谁能帮我解决这个问题?

【问题讨论】:

标签: python dataframe jupyter-notebook


【解决方案1】:

您实际上并没有更新列表中的数据框。您必须在列表元素上应用所有这些更改,其中一种方法是使用函数。见下文:

def change(newtable):
    newtable = newtable.drop("Unnamed: 36", axis=1)
    newtable = to_numeric(newtable)
    newtable['Total'] = newtable.sum(axis=1)
    newtable.index = pd.to_datetime(newtable.index)
    return newtable

result=[change(i) for i in list_table]

或者,您可以遍历 list_table 的索引并更新如下项目:

for i in range(len(list_table)):
    newtable=list_table[i]
    newtable = newtable.drop("Unnamed: 36", axis=1)
    newtable = to_numeric(newtable)
    newtable['Total'] = newtable.sum(axis=1)
    newtable.index = pd.to_datetime(newtable.index)
    list_table[i]=newtable

【讨论】:

  • OP 会看到分配给名称 a 的 DataFrame 中的更改吗?
  • 我不认为 list_table 项目实际上是“a”、“b”等,很可能这些是纯数据帧。您不能将“数据框名称”附加到代表数据框的列表中,您只能附加数据框本身
  • 如果需要,您可以通过添加另一行来实现这一点:a,b,c,d,e,f,g = result
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2021-09-15
  • 2013-02-06
  • 2022-08-10
相关资源
最近更新 更多