好吧,这应该很简单,但我在尝试做我需要做的事情时遇到了最困难的时间。 (我对 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/