Pandas version checks
-
[X] I have checked that this issue has not already been reported.
-
[X] I have confirmed this bug exists on the latest version of pandas.
-
[ ] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import numpy as np
import pandas as pd
c_names = ["a.1", "b", "c", "d"]
df = pd.DataFrame(np.random.randn(100, 4), columns=c_names)
df.eval("f.1 = a.1 + 5")
Issue Description
Raises following exception:
f .1 =a .1 +5
SyntaxError: invalid syntax
this applies to all prohibited characters in variable names. I have some "bicycle" solution for this issue (for "." only) for now:
def apply_formulas(data, formulas):
literal = "arxhdkl_wqmasmdvcalsnd"
columns = [name.replace(".", literal) for name in data.columns]
data.columns = columns
for formula in formulas:
f = formula.replace(".", literal)
data.eval(f, inplace=True)
columns = [name.replace(literal, ".") for name in data.columns]
data.columns = columns
return data
I think that the problem lies in the fact that something like this happens inside the method:
df.f.1 = df.a.1 + 5
instead
df["f.1"] = df["a.1"] + 5
Expected Behavior
df.eval("f.1 = a.1 + 5")
I hope DataFrame.eval() will supports equation like below
Installed Versions
Comment From: ritikBhandari
Hi @RinnetenseiQ,
So the problem with the code is that the column name "a.1" contains a period (.) character, which is a special character in pandas when used in column names. The period is used to separate levels in a hierarchical index.
If you want to use such names in the column, you need to enclose the column name in backticks to indicate that it is a literal column name.
Like this
df.eval("`a.1`+5")
And also, eval() method does not create new columns in the original DF unless the expression is explicitly designed to do so. You can use this expression for much clarity though:
df["f.1"] = df["a.1"] + 5
Comment From: topper-123
Yes, like @ritikBhandari says, the dot is used to access attributes, so if it exists in a name, the fix is to surround the name by backticks.
I'm closing this issue as wontfix.