TransWikia.com

Pandas copy() different columns from different dataframes to a new dataframe

Data Science Asked on November 22, 2021

I have 2 dataframes that are coming from 2 different Excel files. I want to extract some columns from one file and other columns from the second file to print a new dataframe with the copied columns.

I copied 2 columns from different dataframes (df1 and df2) but I get print only one of them (the last one) in df3. How can get all of them in the df3?

    import pandas as pd

    df1 = pd.read_csv('ASX_public_DB.csv', sep=';', skiprows=5)
    df2 = pd.read_excel('ASX_delisted_6months.xlsx')

    df3 = df1[['ticker_symbol']].copy()
    df3 = df2[['ASX code']].copy()

    print(df3)

One Answer

You are overwriting df3.

Method-1:

   import pandas as pd

    df1 = pd.read_csv('ASX_public_DB.csv', sep=';', skiprows=5)
    df2 = pd.read_excel('ASX_delisted_6months.xlsx')

    df3 = df1[['ticker_symbol']].copy()
    df3['ASX code'] = df2[['ASX code']].copy()

    print(df3)

Method-2:

    import pandas as pd

    df1 = pd.read_csv('ASX_public_DB.csv', sep=';', skiprows=5)
    df2 = pd.read_excel('ASX_delisted_6months.xlsx')

    df3 = pd.DataFrame()
    df3['ticker_symbol'] = df1['ticker_symbol'].copy()
    df3['ASX code'] = df2['ASX code'].copy()

    print(df3)
```

Answered by Sai Sreenivas on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP