首页 > 解决方案 > 您如何选择将基于索引的信息放入 pandas DataFrame 的位置?

问题描述

在 MATLAB 中,我创建的循环如下所示:

header_names = {'InvoiceNo','Customer',...}

for i = 1:length(x)
    entry(index+i,:) = [InvoiceNo, Customer,...]
end
% Create a table from the data.
fin_table = cell2table(entry,'VariableNames',header_names);

% Write to the finish file.
writetable(fin_table,finish);

使用表值和标题,我最终会得到如下所示的内容:

发票号码 顾客
1000 吉米
1001 鲍勃
1002 最大限度
1003 四月
1004 汤姆
... ...
... ...
... ...
... ...

我想知道如何在 Python 中实现这一点。我的主要问题是如何创建条目?如何将表放在 for 循环中并要求它在每次迭代的下一行打印信息?

在 Python 中,我目前有以下内容:

        for i in range(len(item)):
            entry = pd.DataFrame(
                [InvoiceNo, Customer, invoice, due, terms, Location, memo, item[i], item[i], quan[i], rate[i], taxable,
                 tax_rate, invoice, email, Class],
                columns=['InvoiceNo', 'Customer', 'InvoiceDate', 'DueDate', 'Terms', 'Location', 'Memo', 'Item',
                         'ItemDescription', 'ItemQuantity', 'ItemRate', 'ItemAmount', 'Taxable', 'TaxRate',
                         'ServiceDate', 'Email', 'Class'])
        # Increment the index for entry values to be correct.
        index += len(item)

任何帮助都是极好的!

标签: pythonpandasfor-loopindexing

解决方案


尽管我没有完全理解您的问题,但我会尝试为您提供一些可能有用的工具:

要获取您可以使用的输入值(并根据您要创建的行数将其放入“for”循环中)

new_InvoiceNo= input("Enter InvoiceNo:\n")
new_Customer= input("Enter Customer:\n")
new_invoice = input("Enter invoice:\n")
...

那么您可以将这些值作为列表附加到主 DF 中:

to_append = [new_InvoiceNo, new_Customer, new_invoice, ...]
new_values = pd.Series(to_append, index = df.columns)
df = df.append(new_values , ignore_index=True)

或者,您可以使用 '.loc' 方法:

to_append = [new_InvoiceNo, new_Customer, new_invoice, ...]
df_length = len(df)
df.loc[df_length] = to_append

尝试在您的代码中实现这一点并在此处报告。


推荐阅读