【发布时间】:2018-12-03 22:42:58
【问题描述】:
我有这张桌子:
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()
【问题讨论】:
-
df['Gold'].max()有什么问题?为什么要写这么长的问题? -
@timgeb 值错误。应该是 1022。不是 976。我想从错误中吸取教训。
-
咦,为什么不是 18 岁?
-
这不是我写的完整列表。
-
我建议把它们扔掉。 :)
标签: python pandas jupyter-notebook