Skip to main content
 首页 » 编程设计

python之pandas DataFrame 中列的更短符号

2025年05月04日24over140

取一个随机的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:“删除”节点未实现。