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

Failing to create list of pandas data frame

I have below code

import pandas as pd
[pd.concat([pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']}), pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']})], axis = 0) if (i == 2) \
    pd.concat([pd.DataFrame({'X' : [1,2], 'Y' : ['D', 'E']}), pd.DataFrame({'X' : [1,2], 'Y' : ['D', 'E']})], axis = 0) for i in range(1, 4)]

Unfortunately this code is giving error

>>> [pd.concat([pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']}), pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']})], axis = 0) if (i == 2) \
...     pd.concat([pd.DataFrame({'X' : [1,2], 'Y' : ['D', 'E']}), pd.DataFrame({'X' : [1,2], 'Y' : ['D', 'E']})], axis = 0)     for i in range(1, 4)]
  File "<stdin>", line 2
    [pd.concat([pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']}), pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']})], axis = 0) if (i == 2) \
    pd.concat([pd.DataFrame({'X' : [1,2], 'Y' : ['D', 'E']}), pd.DataFrame({'X' : [1,2], 'Y' : ['D', 'E']})], axis = 0) for i in range(1, 4)]
     ^
SyntaxError: invalid syntax

Could you please help me to indeify where my code went wrong and how can I correct that?

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

>Solution :

Not sure what you want to do, but you’re missing an else in the ternary:

[pd.concat([pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']}),
            pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']})], axis = 0)
 if (i == 2) else                                                         ## HERE
 pd.concat([pd.DataFrame({'X' : [1,2], 'Y' : ['D', 'E']}),
            pd.DataFrame({'X' : [1,2], 'Y' : ['D', 'E']})], axis = 0)
 for i in range(1, 4)]

output:

[   X  Y
 0  1  D
 1  2  E
 0  1  D
 1  2  E,
    X  Y
 0  1  A
 1  2  B
 0  1  A
 1  2  B,
    X  Y
 0  1  D
 1  2  E
 0  1  D
 1  2  E]
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