python - Pandas 数据框的一个特定项目的计数

标签 python pandas

我已经使用下面的行来获取数量

从文件的特定列(包含 READ、WRITE、NOP)“读取”。这不是 csv 文件,而是一个以\t 作为分隔符的 .out 文件。

    data = pd.read_csv('xaa',usecols=[1], header=None,delimiter='\t')
    df2=df1.iloc[start:end,]

    count=df2.str.count("R").sum()

我遇到了错误

AttributeError:

'DataFrame' object has no attribute 'str'

但是当我使用

 if filename.endswith(".csv"): 
        data = pd.read_csv(filename)
df1=data.loc[:,"operation"]
df2=df1.iloc[start:end,] 
count=df2.str.count("R").sum()

没有错误。但在这里我必须输入每个 csv 文件。我必须打开文件并在我需要的列中插入“操作”。请给个灵魂

最佳答案

我认为需要为 Series 选择列 1,否则获取一列 DataFrame:

count=df2[1].str.count("R").sum()

或按eq比较和 Truesum:

count=df2[1].eq("R").sum()

编辑:

另一种解决方案是通过参数squeezeread_csv中返回Series:

s = pd.read_csv('xaa',usecols=[1], header=None,delimiter='\t', squeeze=True)

count=s.iloc[start:end].str.count("R").sum()

#for another solution
#count=s.iloc[start:end].eq("R").sum()

示例:

df2 = pd.DataFrame({1:['R','RR','Q']})
print (df2)
    1
0   R
1  RR
2   Q

#count all substrings
count=df2[1].str.count("R").sum()
print (count)
3

#count only strings
count=df2[1].eq("R").sum()
print (count)
1

关于python - Pandas 数据框的一个特定项目的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49976644/

相关文章:

python - 从 S3 将 CSV 数据加载到 Jupyter Notebook

python - 使用 Pandas 将 JSON 列添加到模式中

Python HTMLParser 在 & 处划分数据

python - 在 Python 3 中将字符串转换为字节的最佳方法?

python - 只需将文件保存到 Django 中的文件夹

python:从 Pandas 中的数据框生成的列表比数据框列长得多

python - 使用 Python3 在 Pyramid 中使用 Websocket

python - 如何通过组合 pandas 数据框中的两行来创建列

python - 在 Python 中获取从周日开始的周数的问题?

python - 在数据框中查找值介于 x 和 y 之间的单元格