从python为excel工作表中的每一行的最小值添加额外的列

2024-10-04 07:30:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序,它可以获取数据并写入excel文件,但是我想在每行的末尾添加一个公式,该公式可以获取从C列到CM列的所有数字的最小值,因此最小值将写入CO列。这里我有一个我想要的图像

The Min function is in the CO column click here for image (this was done by manually using the MIN function)

我目前的代码如下

import requests
import csv
from bs4 import BeautifulSoup

players = []

def get_name(td):
    return td.find('b').text

def get_id(td):
    links = td.find_all('a')
    link = links[0]['href']
    link = link.split('/')
    return link[5]

def get_ovr(ovr):
    return ovr.text

def read_page(pageId):
    link = 'https://www.futwiz.com/en/fifa21/players?page=' + str(pageId) + '&release=icons'
    r = requests.get(link)
    soup = BeautifulSoup(r.text, 'html.parser')
    ovrList = soup.find_all('div', {'class', 'otherversion21-txt'})
    td = soup.find_all('td', {'class', 'player'})
    for i in range(0, len(ovrList)):
        player = {
            'name': get_name(td[i + 1]),
            'id': get_id(td[i + 1]),
            'ovr': get_ovr(ovrList[i])
        }
        players.append(player)

def get_prices(playerId):
    link = 'https://www.futwiz.com/en/app/price_history_player21?p=' + str(playerId) + '&c=xb'
    r = requests.get(link)
    pricePageText = r.text
    pricePageText = pricePageText.replace('[', '')
    pricePageText = pricePageText.replace(']', '')
    pricePageText = pricePageText.split(',')
    prices = []
    for i in range(len(pricePageText)):
        if i % 2 == 1:
            prices.append(pricePageText[i])
    return prices


for pageId in range(0, 13):
    print('Reading page: ' + str(pageId+1))
    read_page(pageId)

f = open('newData.csv', 'w', newline='')
with f:
    writer = csv.writer(f)

    for player in players:
        print('Read player: ' + player['name'])
        prices = get_prices(player['id'])
        profile = [player['name'], player['ovr']]

        #To download all numbers, uncomment following line and comment (1) line
        profile.extend(prices)

        #To download only last number
       # profile.append(prices[len(prices) - 1]) #(1) Line

        writer.writerow(profile)

如有任何帮助,我们将不胜感激。提前谢谢。希望不要太混乱


Tags: nameinforgetreturndeflinkfind
1条回答
网友
1楼 · 发布于 2024-10-04 07:30:59

我不知道是否需要在Python脚本中获取最小值,或者只在Excel工作簿中使用它也是可以接受的。如果不要求python脚本计算最小值:可以使用以下解决方案:

创建一个新的.xlsx文件>;单击功能区中的“数据”选项卡,然后选择“从csv文件获取数据”。见下图: get data from file

选择python脚本创建的.csv文件。然后单击转换数据。电源查询编辑器将弹出,在这里您可以自动添加具有minum值的列。为此,请选择参与最小值的列(列C到CM),按住ctrl键选择多个列,然后单击列名

如果选择了所有列:单击“添加列选项卡”,单击统计信息并选择“最小值”。如果需要,还可以更改列的名称。现在创建了列,您可以单击“主页”选项卡,关闭并加载数据

结果是:运行python脚本,打开excel文件,单击“数据”选项卡中的“刷新数据”,您的数据集将具有最少的列

如果你被困在什么地方,请告诉我

,吉米

相关问题 更多 >