繁体   English   中英

谁能帮我用 Python 处理数据?

[英]Can anyone help me processing data with Python?

所以我有一个DataFrame的列表:

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

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

这是我的to_numeric function:

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 都没有改变,所以我有点困惑这样做。 任何人都可以帮我解决这个问题吗?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM