您如何根据索引选择将信息放入 pandas DataFrame 的位置?

How do you choose where to put information based on an index into a 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);

使用 table 值和 headers,我最终会得到如下内容:

InvoiceNo Customer
1000 Jimmy
1001 Bob
1002 Max
1003 April
1004 Tom
... ...
... ...
... ...
... ...

我想知道如何在 Python 中完成此操作。我的主要问题是如何创建条目?如何将 table 放入 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)

任何帮助都会很棒!

虽然我没有完全理解你的问题,但我会尝试给你一些可能有用的工具:

要获取输入值,您可以使用(并将其放入 '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

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