Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何解决;索引器:单位置索引器超出范围“;具有不同形状的数据帧_Python 3.x_Pandas_Dataframe_Index Error - Fatal编程技术网

Python 3.x 如何解决;索引器:单位置索引器超出范围“;具有不同形状的数据帧

Python 3.x 如何解决;索引器:单位置索引器超出范围“;具有不同形状的数据帧,python-3.x,pandas,dataframe,index-error,Python 3.x,Pandas,Dataframe,Index Error,我已经检查了关于indexer的其他帖子:单位置indexer是不允许的,但无法找到解释我的问题的解决方案 我有一个数据框,看起来像: Date Balance 0 2020-01-07 168.51 1 2020-02-07 179.46 2 2020-03-07 212.15 3 2020-04-07 221.68 4 2020-05-07 292.23 5 2020-06-07 321.61 6 2020-07-07 332.27 7

我已经检查了关于indexer的其他帖子:单位置indexer是不允许的,但无法找到解释我的问题的解决方案

我有一个数据框,看起来像:

    Date    Balance
0   2020-01-07  168.51
1   2020-02-07  179.46
2   2020-03-07  212.15
3   2020-04-07  221.68
4   2020-05-07  292.23
5   2020-06-07  321.61
6   2020-07-07  332.27
7   2020-08-07  351.63
8   2020-09-07  372.26
我的问题是,我想运行一个脚本,它接收像上面那个样的数据帧,并使用类似于
df.iloc[2][1]
的内容返回每行的余额。但是,数据帧的长度可以是1到12行。因此,如果我调用
df.iloc[8][1]
并且数据帧的长度小于9行,那么我将得到索引器

如果我想使用
df.iloc[]
返回每行的余额。。。如何在不使用12个不同的try和except语句的情况下处理索引错误

此外,这里的问题被简化了,数据帧可能变得相当大,因此我希望尽可能避免循环


谢谢

我的解决方案是在列表长度上使用循环,并将余额附加到列表中。然后,我用“NaN”值填充列表,使其长度为12

num_months = len(df)
N=12

list_balance_months = []
for month in range(num_months):
    list_balance_months .append(df_cd.iloc[month][0])
list_balance_months += [np.nan] * (N - len(list_balance_months ))

balance_month_1, balance_month_2, balance_month_3, balance_month_4, balance_month_5, balance_month_6, balance_month_7, balance_month_8, balance_month_9, balance_month_10, balance_month_11, balance_month_12 = list_credit_months

使用此解决方案,如果调用了
balance\u month\u 11
,并且数据帧只有4个月的数据,它将给出np.nan(
nan


如果你能想出一个更简单的解决方案,请告诉我

为什么要插入错误的行索引?您知道您的行在0和df之间。shape[0]-1这不是一个技术问题,而是一个内容方面的问题。如果数据帧长度小于4行,会发生什么情况?如果您真的需要访问第四行,为什么还要使用更小的数据帧呢?您只需一次尝试即可解决此问题,除了只检查数据帧长度是否大于或等于4。
pandas
基于列名+索引来本地化数据。这是一个裸表
numpy
的演变。因此,在使用
pandas
时,您应该尝试使用列名和索引。我猜您可能正在尝试合并两个数据帧。看看
合并
功能?