什么是 pandas 计算匹配条件的文本的方法?
What is a pandas approach to counting text that matches condition?
有哪些 pandas 方法可以对满足多个条件的行进行计数?
例如:
df = pd.DataFrame({ 'A' : ["1","2","3","4"],
'B' : pd.Timestamp('20130102'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo' })
df
我将在下面演示如何计算单个条件:
print ("Sum for 1 and 3:",(df['A']=="1").sum(),"records")
有哪些方法可以同时计算“1”和“3”?
在上面的示例中,我希望输出 Sum for 1 and 3: 2 records
您可以使用:
print ("Sum for 1 and 3:",((df['A']=="1") | (df['A']=="3")).sum(),"records")
('Sum for 1 and 3:', 2, 'records')
或使用 str.contains
和 |
(or
):
print ("Sum for 1 and 3:",(df['A'].str.contains("1|3")).sum(),"records")
('Sum for 1 and 3:', 2, 'records')
更快的方法使用 np.sum
:
print ("Sum for 1 and 3:",np.sum(df['A'].str.contains("1|3")),"records")
('Sum for 1 and 3:', 2, 'records')
在这种情况下,您可以使用 in1d
,检查设备:
np.in1d(df["A"],["1","3"]).sum()
这非常快。
有哪些 pandas 方法可以对满足多个条件的行进行计数?
例如:
df = pd.DataFrame({ 'A' : ["1","2","3","4"],
'B' : pd.Timestamp('20130102'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo' })
df
我将在下面演示如何计算单个条件:
print ("Sum for 1 and 3:",(df['A']=="1").sum(),"records")
有哪些方法可以同时计算“1”和“3”?
在上面的示例中,我希望输出 Sum for 1 and 3: 2 records
您可以使用:
print ("Sum for 1 and 3:",((df['A']=="1") | (df['A']=="3")).sum(),"records")
('Sum for 1 and 3:', 2, 'records')
或使用 str.contains
和 |
(or
):
print ("Sum for 1 and 3:",(df['A'].str.contains("1|3")).sum(),"records")
('Sum for 1 and 3:', 2, 'records')
更快的方法使用 np.sum
:
print ("Sum for 1 and 3:",np.sum(df['A'].str.contains("1|3")),"records")
('Sum for 1 and 3:', 2, 'records')
在这种情况下,您可以使用 in1d
,检查设备:
np.in1d(df["A"],["1","3"]).sum()
这非常快。