Skip to main content
 首页 » 编程设计

python之根据 CSV Python 检查列表中的数据

2025年02月15日7lvdongjie

大家好,我是 Python 的新手,我正在尝试通过制作一个可用的函数来增加我的知识。我正在尝试构建一个函数,该函数创建从 1 到 59 范围内的一组数字中提取的 6 个随机数的列表。现在我已经破解了那部分,接下来是棘手的部分。我现在想检查一个 csv 文件中的随机集合中的数字,然后如果从该集合中找到两个或更多数字,则打印出通知。现在我尝试了 print (df[df[0:].isin(luckyDip)]) 并取得了一点成功,因为它检查了集合中数字的数据框,然后显示了在数据框中匹配的数字,但它也将数据框的其余部分显示为 NaN,这在技术上不是很令人满意,也不是我真正想要的。

我只是在寻找一些关于下一步该做什么的指示,或者只是在谷歌上搜索什么,下面是我一直在搞乱的代码。

import random 
import pandas as pd 
 
url ='https://www.national-lottery.co.uk/results/euromillions/draw-history/csv' 
df = pd.read_csv(url,   sep=',', na_values=".") 
 
lottoNumbers = [1,2,3,4,5,6,7,8,9,10, 
           11,12,13,14,15,16,17,18,19,20, 
           21,22,23,24,25,26,27,28,29,30, 
           31,32,33,34,35,36,37,38,39,40, 
           41,42,43,44,45,46,47,48,49,50, 
           51,52,53,54,55,56,57,58,59] 
luckyDip = random.sample(lottoNumbers, k=6) #Picks 6 numbers at random 
print (sorted(luckyDip))     
print  (df[df[0:].isin(luckyDip)]) 

请您参考如下方法:

不像@ayhan 解决方案那么优雅,但它有效:

import random 
import pandas as pd 
 
url ='https://www.national-lottery.co.uk/results/euromillions/draw-history/csv' 
df = pd.read_csv(url, index_col=0,  sep=',') 
 
lottoNumbers = range(1, 60) 
 
tries = 0 
while True: 
    tries+=1 
    luckyDip = random.sample(lottoNumbers, k=6) #Picks 6 numbers at random 
 
    # subset of balls 
    draws = df.iloc[:,0:7] 
 
    # True where there is match 
    matches = draws.isin(luckyDip) 
 
    # Gives the sum of Trues 
    sum_of_trues = matches.sum(1) 
 
    # you are looking for matches where sum_of_trues is 6 
    final = sum_of_trues[sum_of_trues == 6] 
    if len(final) > 0: 
        print("Took", tries) 
        print(final) 
        break 

结果是这样的:

Took 15545 
DrawDate 
16-May-2017    6 
dtype: int64