Home > Back-end >  Failing to create list of pandas data frame
Failing to create list of pandas data frame

Time:07-18

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?

CodePudding user response:

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]
  • Related