Home > Software design >  (Python)Dataframe copy with selected columns and index
(Python)Dataframe copy with selected columns and index

Time:12-06

Whole dataframe can be copied to df2 as below. How to copy only 'B' column and index in df to df2?

import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30],'B': [100, 200, 300]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])
df2 = df.copy()

CodePudding user response:

You can simply select and then copy as follows:

df2 = df[['B']].copy()

I am using a list as the selection in order to have a DataFrame instead of a pd.Series.

  • Related