'How do I get a variable inside of an "if" statement to be a global variable?
I'm new to Python, and I need to get the new DataFrame with the appended values (df_ap) after the condition is met, is this possible or should I try a completely new approach.
This is my current code:
df = pd.DataFrame(columns=["C1", "C2", "C3"])
Var1 = input("Input ")
if Var1 == 1:
df_ap = df.append({"C1": 100, "C2": 200, "C3":300}, ignore_index=True)
print(df)
print(df_ap)
Output:
Input 1
Empty DataFrame
Columns: [C1, C2, C3]
Index: []
NameError: name 'df_ap' is not defined
Solution 1:[1]
First, in order to make your condition working, you need to make sure your input has been converted into int before the if condition.
Since you using df_ap outside of the if condition, you have to define it outside the if as well, which is before the condition execution.
import pandas as pd
df = pd.DataFrame(columns=["C1", "C2", "C3"])
df_ap = pd.DataFrame()
Var1 = int(input("Input "))
if Var1 == 1:
df_ap = df.append({"C1": 100, "C2": 200, "C3":300}, ignore_index=True)
print(df)
print(df_ap)
Another way, you can simply reuse df, since it has been defined outside if condition:
import pandas as pd
df = pd.DataFrame(columns=["C1", "C2", "C3"])
Var1 = int(input("Input "))
if Var1 == 1:
df = df.append({"C1": 100, "C2": 200, "C3":300}, ignore_index=True)
print(df)
Solution 2:[2]
Var_1 is a string not an integer so you have to cast as int or compare it with a string:
Var1 = int(input("Input "))
if Var1 == 1:
Or:
Var1 = input("Input ")
if Var1 == "1":
Solution 3:[3]
Try creating the definition outside the if.
df = pd.DataFrame(columns=["C1", "C2", "C3"])
Var1 = input("Input ")
df_ap = None
if Var1 == 1:
df_ap = df.append({"C1": 100, "C2": 200, "C3":300}, ignore_index=True)
print(df)
print(df_ap)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DrakeLiam |
| Solution 2 | Corralien |
| Solution 3 | Eric Breyer |
