2016-05-19 25 views
4

擁有大熊貓數據幀:如何獲取熊貓數據框中的單元格值的長度?

idx Event 
0 abc/def 
1 abc 
2 abc/def/hij 

運行:df['EventItem'] = df['Event'].str.split("/")

了:

idx EventItem 
0 ['abc','def'] 
1 ['abc'] 
2 ['abc','def','hij'] 

想要得到的各cell的長度,運行df['EventCount'] = len(df['EventItem'])

了:

idx EventCount 
0 6 
1 6 
2 6 

如何獲得正確的計數如下?

idx EventCount 
0 2 
1 1 
2 3 

回答

7

您可以使用.str.len得到一個列表的長度,即使名單是不是字符串:

df['EventCount'] = df['Event'].str.split("/").str.len() 

或者,你要找的計數僅僅是1比更個性化的字符串中"/"的,因此你可以添加1至.str.count結果:

df['EventCount'] = df['Event'].str.count("/") + 1 

爲任一方法所得到的輸出:

在一個稍大的數據幀個
  Event EventCount 
0  abc/def   2 
1   abc   1 
2 abc/def/hij   3 

時序:

%timeit df['Event'].str.count("/") + 1 
100 loops, best of 3: 3.18 ms per loop 

%timeit df['Event'].str.split("/").str.len() 
100 loops, best of 3: 4.28 ms per loop 

%timeit df['Event'].str.split("/").apply(len) 
100 loops, best of 3: 4.08 ms per loop 
+0

哇,'在名單.str.len'工作! – IanS

3

您可以使用applylen功能適用於每列:

df['EventItem'].apply(len) 

0 2 
1 1 
2 3 
Name: EventItem, dtype: int64 
相關問題