The DataFrame index can be expanded or enlarged by adding new rows to the DataFrame using the loc
or append
method.
Using loc
method to add new rows:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['row1', 'row2', 'row3'])
print(df)
# Output:
# A B
# row1 1 4
# row2 2 5
# row3 3 6
# Adding new rows to the DataFrame using loc method
df.loc['row4'] = [7, 8]
df.loc['row5'] = [9, 10]
print(df)
# Output:
# A B
# row1 1 4
# row2 2 5
# row3 3 6
# row4 7 8
# row5 9 10
Using append
method to add new rows:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['row1', 'row2', 'row3'])
print(df)
# Output:
# A B
# row1 1 4
# row2 2 5
# row3 3 6
# Adding new rows to the DataFrame using append method
new_data = {'A': [7, 8], 'B': [9, 10]}
new_df = pd.DataFrame(new_data, index=['row4', 'row5'])
df = df.append(new_df)
print(df)
# Output:
# A B
# row1 1 4
# row2 2 5
# row3 3 6
# row4 7 9
# row5 8 10
Both of these methods allow us to expand or enlarge the index of a DataFrame by adding new rows.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-04-26 11:00:00 +0000
Seen: 16 times
Last updated: Nov 08 '21
How can one generate a list by using a portion of another list?
What is the calculation for the combination index?
What is the way to incorporate BitSet in Go?
What is the process of organizing strings into an index called?
In c#, what is the method to obtain the index of an element in a List<T>?
How can we manipulate the range of a string slice in the Golang template?
What is the procedure for removing all vectors within a specific namespace index in Pinecone?