簡體   English   中英

如何將 function 作為單獨 function 的一部分應用於 DataFrame

[英]How to apply a function to a DataFrame as part of a separate function

我正在嘗試將正則表達式 function 應用於 DataFrame,它將日期格式的單元格替換為取自某些字符的字符串。

我在將 function 應用於 dataframe 本身時遇到問題。

到目前為止,這是我的代碼:

def preprocess_test_data(self, test_df):

        def to_month_day(s):
            m = re.match("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", s)
            if m:
                return m[0][8:10].lstrip('0') + '-' + m[0][5:7].lstrip('0')
            return s

        test_df = test_df.apply(to_month_day)
        a = test_df[:,0].astype(str)
        b = test_df[:,1].astype(str)
        c = test_df[:,2].astype(str)
        d = test_df[:,3].astype(str)
        e = test_df[:,4].astype(str)
        f = test_df[:,5].astype(str)
        g = test_df[:,6].astype(str)
        h = test_df[:,7].astype(str)
        i = test_df[:,8].astype(str) 

我不斷收到此錯誤:

AttributeError                            Traceback (most recent call last)

<ipython-input-10-a9f16326387d> in <module>
    183 
    184 # Dont change
--> 185 x_test_processed = my_model.preprocess_test_data(x_test)
    186 
    187 # Train your model

<ipython-input-10-a9f16326387d> in preprocess_test_data(self, test_df)
    119             return s
    120 
--> 121         test_df = test_df.apply(to_month_day)
    122         a = test_df[:,0].astype(str)
    123         b = test_df[:,1].astype(str)

AttributeError: 'numpy.ndarray' object has no attribute 'apply'

如何重新格式化 dataframe 以便它允許我運行 Re function。

該錯誤是由test_df是 numpy 數組而不是 Pandas DataFrame的。 但是,即使使用真正的 dataframe,在apply方法中傳遞的 function 也會收到完整的Series ,默認情況下是一列,如果使用axis=1則為一行。

這里你想要的(一旦test_df是一個 DataFrame)是:

test_df = test_df.apply(lambda x: x.apply(to_month_day))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM