python - 使用 Pandas 保存列中条目的总数

标签 python python-3.x pandas

好吧,这应该很简单,但我在尝试做我需要做的事情时遇到了最困难的时间。 (我对 python 还很陌生)。

我想做的事情:我想通过 Pandas 运行一个 Python 脚本,通过列搜索高于 0.02 的值。如果脚本找到高于 0.02 的条目,则会将其保存为 1,并将其后的每个条目添加为 1,而不是其报告值。这个想法是将有多少条目高于 0.02 与该列的总数进行比较并获得百分比值。

import pandas

# Need to establish what file to run, then create headers for the 
columns to pull for later computing
df = pandas.read_csv('random.csv', 
names=['Name', 'some', 'thing', 'Value', 'Dots', 'Average', 'Average2', 
'Accuracy', 'run'])

# Begin with the count of how many lines there are to start
print('Checking the my wizardry...\n')

count_row = df.shape[0]

print('Total count for this file is: ' + str(count_row))


bad = 0
# Loop through Accuracy Column to compute percentage of bad entries
for i in df['Accuracy']: 
  if i > 0.02:
    print(i)

示例输出:

Checking the my wizardry...
Total count for this file is: 279
0.357
0.353
0.341
0.337
0.332
0.325
0.325
0.32
0.31
0.306
0.306
0.297
...

这个脚本是我用来自动化一个我以前手动执行的过程的脚本,我认为这对于一个有趣的项目来说非常有用。

最佳答案

如果我没记错的话,您只想将大于 0.02 的值的数量除以列中值的总数。

df

   Accuracy
0     0.005
1     0.020
2     0.034
3     0.560

float(df.query('Accuracy > 0.02').count() / df.Accuracy.count())

0.5

或者

(df['Accuracy'] > 0.02).sum() / df['Accuracy'].count()

0.5

关于python - 使用 Pandas 保存列中条目的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54067937/

相关文章:

c++ - Boost python,将原始指针与托管指针进行比较?

Python:如何找到连续系列中第一个和最后一个字符的索引

python - Pandas Excel合并单元格解析重命名未命名列

python - 如何在 Python 3.6 中读取/转换包含用 Python 2.7 编写的 pandas 数据帧的 HDF 文件?

python - 如何在Python中动态地将元组值保存到变量中?

python - pandas 列值到行值

python - PyPI 模块不工作

python - 如何使用openpyxl更改图片大小

python - 循环指示器的进度

python - 异步和异步错误——TypeError : 'coroutine' object is not callable