3
\$\begingroup\$

pandas.DataFrame.insert can only handle an int for it's loc kwarg this is inconvenient for the user with medium to big data. In an attempt to solve this problem temporarily for my development environment I have come up with the following methods. I'm testing out as hot patches but I plan on implementing them in my fork of pandas and submitting a PR to the pandas master;

import pandas as pd
import numpy as np

@property
def label_pos(self):
    "Return a dict with column labels as keys and their positions as values."
    return dict(i[::-1] for i in enumerate(self.columns))

setattr(pd.DataFrame, 'label_pos', label_pos)

def label_insert(self, label, *args, **kwargs):
    "Insert an array-like into a DataFrame before a column with the given label."
    self.insert(int(self.label_pos[label]), *args, **kwargs)

setattr(pd.DataFrame, 'label_insert', label_insert)

Testing

ex = pd.DataFrame(np.zeros((10,5)),columns=list('ABCEF'))
D = pd.Series(np.zeros(10))

ex.label_insert(label='C', column='D', value=D)

ex.label_insert('E', 'D', D, allow_duplicates=True)
\$\endgroup\$

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.