问题描述
我知道一个非常基本的问题,但我是 python 的新手,所以这里是。我正在编写一个程序,可以同时“抛出”4 个骰子并将它们的可能结果相加。现在我的代码完全可以工作,但是我不想打印每个唯一值的计数,我只希望它打印“18.0”的计数。即 80 如下
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
four_dice = np.zeros([pow(6,4),5]) # 1296 rows x 5 columns
n = 0
outcomes = [1,2,3,4,5,6]
for i in outcomes:
for j in outcomes:
for k in outcomes:
for l in outcomes:
four_dice[n,:] = [i,j,k,l,i+j+k+l]
n +=1
four_dice_df = pd.DataFrame(four_dice,columns=('1','2','3','4','Total'))
print(four_dice_df) # print the table of all possible outcomes
print(four_dice_df.Total.value_counts().sort_index()) # print unique values and how many times they each occur
1 2 3 4 Total
0 1.0 1.0 1.0 1.0 4.0
1 1.0 1.0 1.0 2.0 5.0
2 1.0 1.0 1.0 3.0 6.0
3 1.0 1.0 1.0 4.0 7.0
4 1.0 1.0 1.0 5.0 8.0
... ... ... ... ... ...
1291 6.0 6.0 6.0 2.0 20.0
1292 6.0 6.0 6.0 3.0 21.0
1293 6.0 6.0 6.0 4.0 22.0
1294 6.0 6.0 6.0 5.0 23.0
1295 6.0 6.0 6.0 6.0 24.0
[1296 rows x 5 columns]
4.0 1
5.0 4
6.0 10
7.0 20
8.0 35
9.0 56
10.0 80
11.0 104
12.0 125
13.0 140
14.0 146
15.0 140
16.0 125
17.0 104
18.0 80 #only value I want printed
19.0 56
20.0 35
21.0 20
22.0 10
23.0 4
24.0 1
Name: Total,dtype: int64
因此,我尝试使用谷歌搜索并查看过去有关如何在打印时设置标准的问题,但我找不到任何有用的信息,但我很确定需要在此行的某处设置输出标准。
>print(four_dice_df.Total.value_counts().sort_index())
解决方法
您应该创建数据框的子集,只包含 Total 等于 18 的行。您可以使用以下代码执行此操作:
dfTotal18 = four_dice_df[four_dice_df['Total'] == 18]
它看起来像这样:
名称:总计,长度:80,数据类型:float64
然后可以使用您已经使用的函数计算行数,但您将不再需要 sort_index():
dfTotal18.Total.value_counts()
否则,您只需一步即可完成:
four_dice_df.Total[four_dice_df['Total'] == 18].value_counts()
你最终会得到这个结果:
18.0 80
Name: Total,dtype: int64