Ask Your Question
4

How can the DataFrame index be expanded or enlarged?

asked 2021-04-26 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-11-08 22:00:00 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-04-26 11:00:00 +0000

Seen: 16 times

Last updated: Nov 08 '21