[英]Value Count String Occurrences for Pandas Column of Lists type in Python
[英]count occurrences matching partial string by column in pandas python
new_data 是一個有 4 列的 Pandas 數據框,並且:
如果我想按列獲取精確匹配的出現次數,我會這樣做:
new_data[new_data == 'blank'].count()
輸出:
A 0
B 0
C 0
D 2654
如果我想要字符串 'bla' 的部分匹配,會是這樣的:
new_data[new_data in 'bla'].count()
但這當然行不通。 正確的做法是什么?
將DataFrame.apply
和Series.str.contains
與sum
用於 count True
s:
np.random.seed(1234)
new_data = pd.DataFrame(np.random.choice(['a blas', 's'], size=(2,4)), columns=list('ABCD'))
print (new_data)
A B C D
0 s s a blas s
1 a blas a blas a blas s
print (new_data.apply(lambda x: x.str.contains('bla')).sum())
A 1
B 1
C 2
D 0
dtype: int64
您的解決方案:
print (new_data[new_data.apply(lambda x: x.str.contains('bla'))].count())
A 1
B 1
C 2
D 0
dtype: int64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.