Python Pandas 以公式作为值求值

Python Pandas eval with the formula as value

我想做一个奇怪的事情,我准备了一个例子:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [1,2,3], 'formula': ['A+B', 'A-B', 'A*B']})

df:

+---+---+---+---------+
|   | A | B | formula |
+---+---+---+---------+
| 0 | 1 | 1 | A+B     |
| 1 | 2 | 2 | A-B     |
| 2 | 3 | 3 | A*B     |
+---+---+---+---------+

我想做这样的事情:

df[C] = df.eval(df['formula])

获得:

+---+---+---+---------+---+
|   | A | B | formula | C |
+---+---+---+---------+---+
| 0 | 1 | 1 | A+B     | 2 |
| 1 | 2 | 2 | A-B     | 0 |
| 2 | 3 | 3 | A*B     | 9 |
+---+---+---+---------+---+

但是我遇到了一个策略错误:

ValueError:传递的项目数错误 3,放置意味着 1

试试 groupbyeval

df['New']=[x.eval(x['formula'].iloc[0]).iloc[0] for _,x in df.groupby(level=0)]
df
Out[270]: 
   A  B formula  New
0  1  1     A+B    2
1  2  2     A-B    0
2  3  3     A*B    9

试试这个,你会得到准确的输出:

import pandas as pd
dataFrame = pd.DataFrame({'A': [1,2,3], 'B': [1,2,3], 'formula': ['A+B', 'A-B', 'A*B']})
dataFrame['C']=[x.eval(x['formula'].iloc[0]).iloc[0] for _,x in dataFrame.groupby(level=0)]
print dataFrame

此处测试:http://tpcg.io/xSqKh7