-1

Leaving out the lead-up and data to the following because it looks like an error in how the list comprehension is written. It is meant to cycle through a list l of pandas DataFrames and Series, and label them based on whether they are two dimensional (both index and columns) or one dimensional (index only). Why the error (even if a close the line-break)?

[pd.DataFrame(A, index=labels, columns=labels) for A in l 
            if type(A) is pd.DataFrame else pd.Series(A, index=labels)]

results in

    if type(A) is pd.DataFrame else pd.Series(A, index=tickers)]
                                  ^
SyntaxError: invalid syntax
develarist
  • 1,224
  • 1
  • 13
  • 34
  • the filter clause is only `if` in a list comprehension. What you are actually trying to do is use a conditional expression in the main clause. – juanpa.arrivillaga Jan 16 '21 at 21:15

2 Answers2

2

You need to move the for A in l to the end of your statement.

[pd.DataFrame(A, index=labels, columns=labels) if type(A) is pd.DataFrame else pd.Series(A, index=labels) for A in l]

See: Is it possible to use 'else' in a list comprehension?

effprime
  • 578
  • 3
  • 10
0

Is you issue is not due to the is. Maybe try with isinstance(type(A) , pd.DataFrame) Another point is the order of your list compréhension if think it should be

[f(x) if condition else g(x) for x in sequence]

So you can try

[pd.DataFrame(A, index=labels, columns=labels) if isinstance(type(A) , pd.DataFrame) else pd.Series(A, index=labels) for A in l ]
Renaud
  • 2,709
  • 2
  • 9
  • 24