我可以检查 Pandas 数据框索引是否已结束? - python

我使用while循环在数据框中显示数据

while True:
    last_id = get_last_id()
    res = df.iloc[last_id + 1]

当last_id数据结束并仍使用last_id + 1时,显示错误

IndexError: single positional indexer is out-of-bounds

我可以检查一下dataframe索引中是否没有last_id +1,然后什么也不显示?

参考方案

if-elseDataFrame的长度进行测试,因为按位置进行选择:

while True:
    last_id = get_last_id()
    if len(df) != last_id + 1:
        res = df.iloc[last_id + 1]
     else:
        print ('cannot select next value after last index')

另一个想法是使用try-except语句:

while True:
    try:
        last_id = get_last_id()
        res = df.iloc[last_id + 1]
    except IndexError:
        print ('cannot select next value after last index')

Python Pandas:按分组分组,平均? - python

我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…

重命名默认ID python - python

我想连接两个dataFrames,但是两个数据具有不同的ID,所以结果是错误的这是我的代码data=pd.DataFrame(df.columns) data1=data.drop(axis=1,index=[0,1,2,3]).transpose() data1 这是dataframe1另一个数据框:y=sma_algo(df.loc['H+L&…

Python Pandas:在多列上建立布尔索引 - python

尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…

pandas DataFrame:根据另一列中的布尔值计算总和 - python

我对Python相当陌生,我尝试在pandas中模拟以下逻辑我目前正在循环抛出行,并希望对前几行的AMOUNT列中的值求和,但只求和最后一次看到的“ TRUE”值。实际数据似乎效率低下(我的数据框大约有500万行)?想知道用Python处理这种逻辑的有效方法是什么?逻辑:逻辑是,如果FLAG为TRUE,我想对前几行的AMOUNT列中的值求和,但只求和最后一次…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…