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

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)


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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.