python - DataFrame Python 中的数学求值字符串

标签 python numpy pandas dataframe eval

>>> df['X'].head()
0    25+4
1    25+5
2    15+3
3    20+2
4    20+3
Name: X, dtype: object

我如何评估这个,所以我的数据框是这样的:

>>> df['X'].head()
0    29
1    30
2    18
3    22
4    23

Name: X, dtype: int64

最佳答案

虽然存在安全问题,但您可以使用 eval 使用 lambda 表达式来计算每个元素。

df = pd.DataFrame({'X': ['25+4', '25+5', '15+3', '20+2', '20+3']})

>>> df
      X
0  25+4
1  25+5
2  15+3
3  20+2
4  20+3

>>> df.X.apply(lambda x: eval(x))
0    29
1    30
2    18
3    22
4    23
Name: X, dtype: int64

有关安全问题的说明,请参阅:

关于python - DataFrame Python 中的数学求值字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083872/

相关文章:

python - 如何防止 wx 面板与其他 sizer 重叠

python - 双循环的迭代计数器

Python:如何通过一列中的重复值对一组数据进行分箱

python - 如何在 df.iterrows() 期间删除 Pandas 数据框中的当前行

python - Pandas :对于 df 中的每一行,复制行 N 次,稍作更改

python - 使用 Pandas Align 时,时间序列数据帧返回错误 - valueError : cannot join with no overlapping index names

python - “str”对象没有属性 'message_from_bytes'

python - loadtxt 函数的隐藏错误

python - matplotlib热图反转数据?

python - Pandas :合并多个数据框并控制列名?