gpt4 book ai didi

python - 编写一个函数,返回并打印列中所有值中的最大值

转载 作者:行者123 更新时间:2023-12-01 08:38:18 25 4
gpt4 key购买 nike

我有这张表:

A DataFrame table which is made by using Jupyter Notebook.

这实际上只是表格的一部分。

完整的表格实际上是一个 .csv 文件,通过使用 .head() 函数,仅显示前五行。

我需要编写一个函数,返回并打印第二列中所有值中的最大值,其标签为“Gold”。
该函数应返回单个字符串值。

在写问题之前,我查阅了多个资料来源,尝试了多种方法来解决我的问题。

这似乎是一个非常简单的解决方案,但不幸的是我没有成功找到它。
(这个查询可能有几种可选的解决方案......?)

请帮助我,我完全困惑。
谢谢!

以下是所有来源:

以下是我尝试解决该问题的所有方法,其中一些存在语法错误:

1.a:传统的求最大值算法,如C语言中的“for”循环。

def answer_one():

row=1

max_gold = df['Gold'].row # Setting the initial maximum.

for col in df.columns:

if col[:2]=='Gold': # finding the column.

# now iterating through all the rows, finding finally the absolute maximum:

for row in df.itertuples(): # I also tried: for row=2 in df.rows:

if(df['Gold'].row > max_gold) # I also tried: if(row.Gold > max_gold)

max_gold = df['Gold'].row # I also tried: max_gold = row.Gold

return df.max_gold

我在如何将打印功能合并到上面的代码中时遇到问题,所以我单独添加了它:

1.b:

for row in df.itertuples():
print(row.Gold) # or: print(max_gold)

1.c:

for col in df.columns: 

if col[:2]=='Gold':

df[df['Gold'].max()]

2.

def answer_one():

df = pd.DataFrame(columns=['Gold']) # syntax error.

for row in df.itertuples(): # The same as the separated code sction above.
print(row.Gold)

3.

def answer_one():

print(df[['Gold']][df.Value == df.Value.max()]) # I don't know if "Value" is a key word or not.
  • def answer_one():
    return df['Gold'].max() # right syntax, wrong result (not the max value).
  • 5.

    def answer_one():

    s=data.max()

    print '%s' % (s['Gold']) # syntax error.

    6.a:

    def answer_one():

    df.loc[df['Gold'].idxmax()] # right syntax, wrong output (all the column indexes of the table are shown in a column)

    6.b:

    def answer_one():

    df.loc[:,['Gold']] # or: df.loc['Gold']

    df['Gold'].max()

    最佳答案

    第一个问题很好,我假设您正在 coursera 上学习 Python 数据科学类(class)?

    正如已经指出的,df['Gold'].max() 是正确的,但是,如果数据类型错误,它将不会返回预期结果。所以首先要确保它是一个数字。如果此数据集的输出不是 int64,您可以通过运行 df['Gold'].dtype 进行检查,您可以通过运行 df 来更正它。 loc[:,'Gold'] = df.loc[:,'Gold'].str.replace(',','').astype(int) 之后 df['Gold' ].max() 将返回 1022。

    当涉及到 for 循环时,在这种情况下,您可以迭代 Gold 系列中的所有值,而不是同时迭代所有列和所有行。请注意,python 使用 0 索引!因此,如果您使用第 1 行作为起点,如果最大值位于第一行 (row0),并且您使用 [Index] 而不是 进行索引,则会得到错误的结果。索引。所以 for 循环可能看起来像这样。

    CurrentMax = df['Gold'][0]
    for value in df['Gold']:
    if value>CurrentMax:
    CurrentMax = value
    print(CurrentMax)

    包装为函数:

    def rowbyrow(df=df):
    CurrentMax = df['Gold'][0]
    for value in df['Gold']:
    if value>CurrentMax:
    CurrentMax = value
    #print(CurrentMax) if you want to print the result when running
    return CurrentMax

    关于第3点。我相信您所追求的是下面的内容,它会根据 Gold 值等于最大值的位置来过滤 Gold,因为您在 Gold 周围使用了两个括号,这将返回一个数据框而不仅仅是值:df[['Gold']][df.Gold == df.Gold.max()]如果有一个括号,它将返回一系列:df['Gold'][df.Gold == df.Gold.max()]

    关于第5点,如果使用python 3可能会导致语法错误?在 python 3 中,您需要在 print 语句之后使用 (),因此下面应该可以工作:

    s=df.max()
    print('%s' % (s['Gold']))

    关于第6点:a如果您只想输出特定列,则需要在过滤条件之后传递该列(用,分隔),如下所示:

    df.loc[df['Gold'].idxmax(),'Gold']

    如果你想返回几列,你可以传递一个列表,例如

    df.loc[df['Gold'].idxmax(),['Country','Gold']]

    对于点 1:c,[:2] 将返回前两个字母。与四个字母的单词 Gold 相比,So 始终为 false。

    一些性能比较:

    1.

    %%timeit
    df.loc[df['Gold'].idxmax(),'Gold']
    10000 loops, best of 3: 76.6 µs per loop

    2.

    %%timeit
    s=df.max()
    '%s' % (s['Gold'])
    1000 loops, best of 3: 733 µs per loop

    3.

    %%timeit
    rowbyrow()
    10000 loops, best of 3: 71 µs per loop

    4.

    %%timeit
    df['Gold'].max()
    10000 loops, best of 3: 106 µs per loop

    我惊讶地发现函数 rowbyrow() 的结果最快。

    创建具有 10k 随机值的系列后,rowbyrow() 仍然是最快的。

    看这里:

    df = pd.DataFrame((np.random.rand(10000, 1)), columns=['Gold']) 

    %%timeit # no. 1
    df['Gold'].max()

    The slowest run took 10.30 times longer than the fastest.
    10000 loops, best of 3: 127 µs per loop


    %%timeit # no. 2
    rowbyrow()

    The slowest run took 8.12 times longer than the fastest.
    10000 loops, best of 3: 72.7 µs per loop

    关于python - 编写一个函数,返回并打印列中所有值中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603068/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com