Home > database >  How do you choose where to put information based on an index into a pandas DataFrame?
How do you choose where to put information based on an index into a pandas DataFrame?

Time:11-17

In MATLAB, the loop I create looks like:

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);

With the table values and headers, I will end up getting something that looks like:

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

I would like to know how to accomplish this in Python. My main question is how do I create the entry? How do I put a table in a for loop and ask it to print information on the next row for each iteration?

In Python, I currently have the following:

        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)

Any help would be awesome!

CodePudding user response:

Although I do not get your question completely, I will try to give you some tools that might be useful:

To get input value you can use (and put this inside of a 'for' loop depending on the number of rows you want to create)

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

then you can either append these values as list into the main 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)

or , you can use '.loc' method:

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

Try to implement this in your code and report it back here.

  • Related