简体   繁体   中英

If a variable exists, then do this in python

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

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()

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM