1
$\begingroup$

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)
$\endgroup$
1
$\begingroup$

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)
```
| improve this answer | |
$\endgroup$
  • $\begingroup$ I see, thanks. I get anyway a warning: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. And also ASX code column is added at the end of the list and values are all printed in a single cell. $\endgroup$ – Steven Jul 22 at 10:29
  • $\begingroup$ no, also with .copy() I get the same output as before. $\endgroup$ – Steven Jul 22 at 10:40
  • $\begingroup$ Yes, it worked, thanks! So basically without [[]] it create a list, meanwhile with double [[]] it creates a dataframe? $\endgroup$ – Steven Jul 22 at 10:52
  • 1
    $\begingroup$ Thank you! It's clear now. $\endgroup$ – Steven Jul 22 at 11:40

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.