PER*_*Zje 2 python string pandas
所以我有这个数据帧:
filename width height class xmin ymin xmax ymax
0 128782.JPG 640 512 Panel 36 385 119 510
1 128782.JPG 640 512 Panel 124 388 207 510
2 128782.JPG 640 512 Panel 210 390 294 511
3 128782.JPG 640 512 Panel 294 395 380 510
4 128782.JPG 640 512 Panel 379 398 466 511
5 128782.JPG 640 512 Panel 465 402 553 510
6 128782.JPG 640 512 P+SD 552 402 638 510
7 128782.JPG 640 512 P+SD 558 264 638 404
...
...
57170 128782.JPG 640 512 P+SD 36 242 121 383
57171 128782.JPG 640 512 HS+P+SD 36 97 122 242
57172 128782.JPG 640 512 P+SD 214 106 304 250
Run Code Online (Sandbox Code Playgroud)
其中包含的名为"class"的列具有唯一值"Panel","P + SD"和"HS + P + SD".我想要计算这些值有多少行,所以我尝试了这个:
print(len(split_df[split_df["class"].str.contains('Panel')]))
print(len(split_df[split_df["class"].str.contains('HS+P+SD')]))
print(len(split_df[split_df["class"].str.contains('P+SD')]))
Run Code Online (Sandbox Code Playgroud)
这给了我这个输出:
56988
0
0
Run Code Online (Sandbox Code Playgroud)
这是不正确的,因为您可以根据上面提供的数据框的片段清楚地看到,为什么所有内容都适用于Panel,但没有计算其他两个"类"名称?
这是split_df.info的输出:
RangeIndex: 57172 entries, 0 to 57171
Data columns (total 8 columns):
filename 57172 non-null object
width 57172 non-null int64
height 57172 non-null int64
class 57172 non-null object
xmin 57172 non-null int64
ymin 57172 non-null int64
xmax 57172 non-null int64
ymax 57172 non-null int64
dtypes: int64(6), object(2)
memory usage: 3.5+ MB
Run Code Online (Sandbox Code Playgroud)
我不能为我的生活弄清楚出了什么问题.任何帮助表示赞赏.
pd.Series.str.contains有regex=True默认.由于+是正则表达式,使用特殊字符regex=False,re.escape或\逃避:
import re
s = pd.Series(['HS+P+SD', 'AB+CD+EF'])
s.str.contains('HS+P+SD').sum() # 0
s.str.contains('HS+P+SD', regex=False).sum() # 1
s.str.contains(re.escape('HS+P+SD')).sum() # 1
s.str.contains('HS\+P\+SD').sum() # 1
Run Code Online (Sandbox Code Playgroud)
我想计算这些值有多少行
如果这是您的核心问题并且您不想'P+SD'计算包含'HS+P+SD',请不要使用str.contains.检查是否相等,并使用value_counts您想要计算的值:
L = ['Panel', 'HS+P+SD', 'P+SD']
counts = df.loc[df['class'].isin(L), 'class'].value_counts()
Run Code Online (Sandbox Code Playgroud)
或者对于所有计数只是使用df['class'].value_counts().
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |