简体   繁体   English

如果变量存在,则在 python 中执行此操作

[英]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基本上是试图让 if else 语句起作用,以便每次 for 循环运行时,我在 for 循环内的数据框都会更新(附加)一个新条目

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.如果名为df的变量字面上不存在,则此代码将不起作用。

Initialize df to some empty value at the beginning of your code, then check if it's empty:在代码的开头将df初始化为某个空值,然后检查它是否为空:

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 和 else 语句后添加一个冒号(:)

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.您必须将 df 设置为某物才能将其用作 if 语句中的名称。 Sensible empty values are None and a dataframe with no rows.合理的空值是None和没有行的数据框。 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.但是,您显然可以将 if 语句从 for 循环中提出来,这更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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