How it works...

The .loc indexing operator is used to select and assign data based on the row and column labels. The first value passed to it represents the row label. In step 2, names.loc[4] refers to the row with a label equal to the integer 4. This label does not currently exist in the DataFrame. The assignment statement creates a new row with data provided by the list. As was mentioned in the recipe, this operation modifies the names DataFrame itself. If there was a previously existing row with a label equal to the integer 4, this command would have written over it. This modification in-place makes this indexing operator riskier to use than the append method, which never modifies the original calling DataFrame.

Any valid label may be used with the .loc indexing operator, as seen in step 3. Regardless of what the new label value actually is, the new row will always be appended at the end. Even though assigning with a list works, for clarity it's best to use a dictionary so that we know exactly which columns are associated with each value, as done in step 4.

Step 5 shows a little trick to dynamically set the new label to be the current number of rows in the DataFrame. Data stored in a Series will also get assigned correctly as long as the index labels match the column names.

The rest of the steps use the append method, which is a simple method that only appends new rows to DataFrames. Most DataFrame methods allow both row and column manipulation through an axis parameter. One exception is with append, which can only append rows to DataFrames.

Using a dictionary of column names mapped to values isn't enough information for append to work, as seen by the error message in step 6. To correctly append a dictionary without a row name, you will have to set the ignore_index parameter to True. Step 10 shows you how to keep the old index by simply converting your dictionary to a Series. Make sure to use the name parameter, which is then used as the new index label. Any number of rows may be added with append in this manner by passing a list of Series as the first argument.

When wanting to append rows in this manner with a much larger DataFrame, you can avoid lots of typing and mistakes by converting a single row to a dictionary with the to_dict method and then using a dictionary comprehension to clear out all the old values replacing them with some defaults.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.20