1 | initial version |
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.