Skip to content Skip to sidebar Skip to footer

Merge And Then Sort Columns Of A Dataframe Based On The Columns Of The Merging Dataframe

I have two dataframes, both indexed with timestamps. I would like to preserve the order of the columns in the first dataframe that is merged. For example: #required packages impo

Solution 1:

Using an OrderedDict, as you suggested.

from collections importOrderedDictfrom itertools import chain

c = df3.columns.tolist()
o = OrderedDict()

for x inc:
    o.setdefault(x.split('_')[0], []).append(x)

c = list(chain.from_iterable(o.values()))
df3 = df3[c]

An alternative that involves extracting the prefixes and then calling sorted on the index.

# https://stackoverflow.com/a/46839182/4909087p = [s[0] for s in c]
c = sorted(c, key=lambda x: (p.index(x[0]), x))
df = df[c]

Post a Comment for "Merge And Then Sort Columns Of A Dataframe Based On The Columns Of The Merging Dataframe"