簡體   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