-2

Basically trying to get an if else statement to work so that my data frame which is inside of a for loop gets updated (appended) with a new entry each time the for loop runs

psuedo code:

if df does not exist
   df = some matrix
else
   df1 = some new matrix
   df1 = df1.append(df)

it just doesnt work; i think i have the wrong syntax

Ben S.
  • 53
  • 1
  • 4
  • Can you share the rest of your code so that we can see a clearer picture of what is happening? Also please share the output you're getting as your pseudo code doesn't help much – Hari Jul 18 '19 at 01:18
  • Possible duplicate of [Viewing all defined variables](https://stackoverflow.com/questions/633127/viewing-all-defined-variables) – Nathan Jul 18 '19 at 01:23
  • Are you checking if the variable named `df` literally exists at all, or are you checking if it has a non-empty value? i.e. in real life it would be the difference between an empty box, and no box at all. – John Gordon Jul 18 '19 at 01:24
  • Inside a function, if `df` is an optional arg, declare it in the function header as `def myfunc(required_args_go_here, ..., df=None)` – smci Jul 18 '19 at 01:54

3 Answers3

1

If the variable named df literally does not exist, then this code will not work.

Initialize df to some empty value at the beginning of your code, then check if it's empty:

df = None

... lots of code here, that possibly assigns df a value

if df:
    do_something(df)

else:
    df = something_else()
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

You need to add a colon(:) after if and else statement

if not df:
   df = some matrix
else:
   df1 = some new matrix
   df1 = df1.append(df)
pranjal0819
  • 270
  • 2
  • 17
0

You have to set df to something to use it as a name in your if statement. Sensible empty values are None and a dataframe with no rows. Let's assume the first.

import pandas

df = None

for i in range(100):
    if df is None:
        # Your default dataframe here.
        # You probably want to set column names and types.
        df = pandas.DataFrame()

    # Instead of appending i, append your row.
    df = df.append([i])

But then, you could obviously raise the if statement out of the for loop, which makes more sense.

cmc
  • 973
  • 8
  • 17