Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract an item from a list and add it as a column in dataframe?

I have 3 lists like as shown below

numeric_cols = df.select_dtypes(include=np.number).columns # 3 items `qty`, `age`, `sqft`
date_cols = df.select_dtypes(include=['datetime64']).columns # 2 items
string_cols = df.select_dtypes(include=['object']).columns # 3 items `bucket`, `category`, `level`

Now, I would like to

a) select only one item from numeric cols – qty and all the items from string_cols (so dataframe has to have only 4 columns)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried the below

df[[*string_cols]] = df[[*string_cols]]
df.insert(2, "Qty",df['Qty'],True)

Please note that what I have shown is just a sample. In real data, I have millions of rows and 100’s of columns. Hence, I would like to follow the above approach.

Can guide me on how can I do this efficiently?

>Solution :

You can select subset of columns using a list of column names:

new_df = df[[*string_cols] + ['Qty']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading