簡體   English   中英

將 function 傳遞到數據框中的列 - Python

[英]Pass function to column in data frame - Python

我正在嘗試傳遞將時間戳截斷為單個列的 function。 它正在執行 function 但返回一個列表。 我希望保留數據結構。

df = pd.DataFrame({
    'Time' : ['8:03:001','8:17:004','8:20:003','8:28:002','8:35:004','8:40:006','8:42:002','8:45:004','8:50:009'],                 
    'Place' : ['House 1','House 1','House 1','House 2','House 2','House 2','House 3','House 3','House 3'],                 
     })

def truncate_time(col):
    col = [x[:-2] for x in col]
    return col

df1 = (truncate_time(df['Time']))

預期 Output:

       Time    Place
0  8:03:0    House 1
1  8:17:0    House 1
2  8:20:0    House 1
3  8:28:0    House 2
4  8:35:0    House 2
5  8:40:0    House 2
6  8:42:0    House 3
7  8:45:0    House 3
8  8:50:0    House 3

您可以分配回:

df['Time'] = truncate_time(df['Time'])
print (df)
     Time    Place
0  8:03:0  House 1
1  8:17:0  House 1
2  8:20:0  House 1
3  8:28:0  House 2
4  8:35:0  House 2
5  8:40:0  House 2
6  8:42:0  House 3
7  8:45:0  House 3
8  8:50:0  House 3

但這里也可以將str與索引一起使用:

df['Time'] = df['Time'].str[:-2]

或 lambda function:

df['Time'] = df['Time'].apply(lambda col: col[:-2])

或者對於 function 簡化解決方案,使用Series.apply刪除列表理解:

def truncate_time(col):
    return col[:-2]

df['Time'] = df['Time'].apply(truncate_time)

最后一個帶有列表理解的解決方案:

df['Time'] = [x[:-2] for x in df['Time']]

編輯:可能缺失值的性能 - 取決於值的數量以及缺失值的數量:

#added one row with missing value
df = pd.DataFrame({
    'Time' : ['8:03:001','8:17:004','8:20:003','8:28:002','8:35:004','8:40:006','8:42:002','8:45:004','8:50:009',np.nan],                 
    'Place' : ['House 1','House 1','House 1','House 2','House 2','House 2','House 3','House 3','House 3','House 3'],                 
     })

def truncate_time(col):
    return col[:-2] if col == col else col

#[1000000 rows x 2 columns]
df = pd.concat([df] * 100000, ignore_index=True)

In [104]: %timeit df['Time1'] = df['Time'].str[:-2]
460 ms ± 20.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [105]: %timeit df['Time2'] = [x[:-2] if x == x else x for x in df['Time']]
445 ms ± 9.72 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [106]: %timeit df['Time3'] = df['Time'].apply(lambda col: col[:-2] if col == col else col)
428 ms ± 18.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [107]: %timeit df['Time4'] = df['Time'].apply(truncate_time)
416 ms ± 8.28 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

暫無
暫無

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

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