python - pandas DataFrame 中列的更短符号

标签 python pandas dataframe calculated-columns

取一个随机的DataFrame:

df = pd.DataFrame(np.random.rand(3, 2), columns=['a', 'b'])

Pandas 允许以两种方式定义新列:

df['c'] = df.a + df.b
df['c'] = df['a'] + df['b']

随着 DataFrame 名称变长,这种表示法变得不那么可读了。

然后是查询函数:

df.query('a > b')

它返回符合条件的 df 切片。

有没有办法运行类似 DataFrame.query() 的东西?但对于框架上的操作?

最佳答案

函数DataFrame.eval()正是这样做的:

df.eval('c = a + b')

无警告赋值:

df.eval('c = a + b', inplace=True)

更一般地说,pandas.eval() :

The following arithmetic operations are supported: +, -, *, /, **, %, // (python engine only) along with the following boolean operations: | (or), & (and), and ~ (not). Additionally, the 'pandas' parser allows the use of and, or, and not with the same semantics as the corresponding bitwise operators.

Pandas 文档说 eval 只支持 Python expression statements (例如,a == b),但 pandas 默默地支持 abs(a - b) 和其他语句。其余的抛出错误。例如:

df.eval('del(a)')

返回 NotImplementedError:“删除”节点未实现

关于python - pandas DataFrame 中列的更短符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44311923/

相关文章:

python - 在python中查找以多个后缀结尾的公共(public)前缀

python - 根据具有不同索引的引用数据帧连接数据帧中的特定列对

python - 无法在cygwin中使用python的pexpect

python - 使用 py.test 列出可用的测试

python - 我希望绘制 df.mean() 的输出

python - 如何在 DataFrame 列中匹配 'key off' 对

R日期时间对齐并填充值

python - for 循环内的 dataframe.replace()

python - 尝试用特定值填充 NaN 值

javascript - 在 javascript 中从 prompt.get trim 换行符