ENH: extend DataFrame.insert to also insert rows
See original GitHub issueIs your feature request related to a problem?
I wish I could use pandas to directly insert a row at a specific position in a data frame, just like I can insert a column via the DataFrame.insert
method. This would be similar to the add_row function that exist for R data frames.
Describe the solution you’d like
expand the functionality of DataFrame.insert
to take an axis argument and allow for the insertion of rows when axis
is set to 0
.
API breaking implications
as insert
currently inserts a column by default, the default argument to axis
should be set to 1
. When this is done, I don’t foresee any breaks.
Describe alternatives you’ve considered
An alternative is to use concatenate. This is tedious though, because it requires several concat operations (upper block + row to insert + lower block) and error prone. Another alternative (not in-place) is to use np.insert
like
import seaborn as sns
import pandas as pd
import numpy as np
def insert_row(df, row, position):
out = pd.DataFrame(np.insert(arr=df.values,
obj=position,
values=row,
axis=0),
columns=df.columns)
return out
iris = sns.load_dataset("iris")
row_to_insert = iris.iloc[1, :]
insert_row(iris, row_to_insert, 1)
Additional context
Code example to insert column:
import seaborn as sns
iris = sns.load_dataset("iris")
col_to_insert = iris.iloc[:, 1]
position_to_insert = 1
iris.insert(position_to_insert, "new_column", col)
Desired behaviour:
row_to_insert = iris.iloc[1, :]
iris.insert(position_to_insert, "new_row", row, axis=0)
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (8 by maintainers)
Agreeing with @TomAugspurger, while the
concat
option might be a bit, it truly reflects what’s going on. If users really need this, it is easy to write a function that (I think) would be just as performant as what we could do internally.closing as there doesn’t seem to be much support for this