获取相应列内容满足条件的索引范围的最有效方法是什么..例如以标记开头并以“正文”标记结尾的行。
例如数据框看起来像这样
我想获得行索引 1-3
谁能建议最pythonic的方式来实现这一目标?
import pandas as pd
df=pd.DataFrame([['This is also a interesting topic',2],['<body> the valley of flowers ...',1],['found in the hilly terrain',5],
['we must preserve it </body>',6]],columns=['description','count'])
print(df.head())
你想满足什么条件?
import pandas as pd
df=pd.DataFrame([['This is also a interesting topic',2],['<body> the valley of flowers ...',1],['found in the hilly terrain',5],
['we must preserve it </body>',6]],columns=['description','count'])
print(df)
print(len(df[df['count'] != 2].index))
在这里,df['count'] != 2
对 df 进行子集化,并len(df.index)
返回索引的长度。
更新; 请注意,我使用str.contains()
, 而不是显式查找开始或结束字符串。
df2 = df[(df.description.str.contains('<body>') | (df.description.str.contains('</body>')))]
print(df2)
print(len(df2.index))
帮助来自:检查字符串是否在熊猫数据框中
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句