2016-12-27 21 views
6

Tôi có một dataframe như thế này:cách Pythonic để tính chiều dài của danh sách trong cột dataframe gấu trúc

            CreationDate 
2013-12-22 15:25:02     [ubuntu, mac-osx, syslinux] 
2009-12-14 14:29:32 [ubuntu, mod-rewrite, laconica, apache-2.2] 
2013-12-22 15:42:00    [ubuntu, nat, squid, mikrotik] 

Tôi chiều dài tính toán của danh sách trong cột CreationDate và thực hiện một Length cột mới như thế này:

df['Length'] = df.CreationDate.apply(lambda x: len(x)) 

nào mang lại cho tôi điều này:

            CreationDate Length 
2013-12-22 15:25:02     [ubuntu, mac-osx, syslinux]  3 
2009-12-14 14:29:32 [ubuntu, mod-rewrite, laconica, apache-2.2]  4 
2013-12-22 15:42:00    [ubuntu, nat, squid, mikrotik]  4 

có p hơn ythonic cách để làm điều này?

Trả lời

10

Bạn cũng có thể sử dụng trình truy cập str cho một số thao tác danh sách. Trong ví dụ này,

df['CreationDate'].str.len() 

trả về độ dài của mỗi danh sách. Xem tài liệu cho str.len.

df['Length'] = df['CreationDate'].str.len() 
df 
Out: 
                CreationDate Length 
2013-12-22 15:25:02     [ubuntu, mac-osx, syslinux]  3 
2009-12-14 14:29:32 [ubuntu, mod-rewrite, laconica, apache-2.2]  4 
2013-12-22 15:42:00    [ubuntu, nat, squid, mikrotik]  4 

Đối với các hoạt động này, vanilla Python thường nhanh hơn. gấu trúc xử lý NaNs mặc dù. Dưới đây là thời gian:

ser = pd.Series([random.sample(string.ascii_letters, 
           random.randint(1, 20)) for _ in range(10**6)]) 

%timeit ser.apply(lambda x: len(x)) 
1 loop, best of 3: 425 ms per loop 

%timeit ser.str.len() 
1 loop, best of 3: 248 ms per loop 

%timeit [len(x) for x in ser] 
10 loops, best of 3: 84 ms per loop 

%timeit pd.Series([len(x) for x in ser], index=ser.index) 
1 loop, best of 3: 236 ms per loop 
+0

Tốc độ tương tự cho một khung dữ liệu nhỏ nhưng ít ký tự hơn. Bạn có nghĩ rằng nó sẽ tạo sự khác biệt cho dataframe lớn? – MYGz

Các vấn đề liên quan