python - 使用 pandas python 获取整行作为输出,其中某些列具有最大值

标签 python pandas

enter image description here

我是 python-pandas 新手。我需要一些帮助来获取整行作为输出,而不是一列。例子: df1.max() 给了我这个输出。

每行费用 263566.10

但我需要输出为:

claim_number charge_per_line

3 263566.10

谢谢!!

最佳答案

对于一列DataFrame需要sort_values并按 iloc 选择最后一行:

df = pd.DataFrame({'claim_number':[1,1,2,2,3,3], 
                   'Charge_Per_Line':[10,5,4,20,10,3]})
print (df)
   Charge_Per_Line  claim_number
0               10             1
1                5             1
2                4             2
3               20             2
4               10             3
5                3             3

df1 = df.groupby('claim_number').sum()
print (df1)
              Charge_Per_Line
claim_number                 
1                          15
2                          24
3                          13

res = df1.sort_values('Charge_Per_Line').iloc[[-1]]
#alternative solution
#res = df1.loc[[df1['Charge_Per_Line'].idxmax()], ['Charge_Per_Line']]
print (res)
              Charge_Per_Line
claim_number                 
2                          24

如果想要来自索引的列:

df1 = df.groupby('claim_number', as_index=False).sum()
print (df1)
   claim_number  Charge_Per_Line
0             1               15
1             2               24
2             3               13

res = df1.sort_values('Charge_Per_Line').iloc[[-1]]
#alternative
#res = df1.loc[[df1['Charge_Per_Line'].idxmax()]]
print (res)
   claim_number  Charge_Per_Line
1             2               24

关于python - 使用 pandas python 获取整行作为输出,其中某些列具有最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49272557/

相关文章:

python - Pandas :更改具有多级列的数据框中的特定列名

python - 天气 "events"根据 Pandas 的时差进行分组

python - 如何创建重复字符串的动态大小列并将其同时添加到数据框中

java - 0xaa 和 0x55 在做什么?

python - 为我的自定义迭代器实现 iteritems 函数?

python - 导入错误: No module named couchbase. _libcouchbase

python - 使用 Python 表示合并排序,如何避免 IndexError

python - 如何找到内置 Python 方法的源代码位置?

python - 将 Excel 文件的第 n 行到 n+x 行加载到 python 中的数据框中,其中 n 和 x 是预定义的

python - 如何从每列中包含字典或列表的数据框中获取信息?