【问题标题】:Is it possible to place a string inside df[ ] in python?是否可以在 python 中的 df[ ] 中放置一个字符串?
【发布时间】:2021-05-15 03:03:44
【问题描述】:

我知道这很糟糕。我真的很想知道这是否可以在 python 中完成,所以我有两个带有算术方程的字符串,现在我想将它们放在 df[] 中。 df是一个数据框这可以吗?

X = "'cars'+'bikes'*'planes'"

现在应该像下面这样放置

X = df['cars']+df['bikes']*df['planes']

如果可能怎么做?

【问题讨论】:

  • 什么是df?是熊猫数据框吗?
  • 是的 df 是数据框
  • 首先,您必须将字符串解析为操作符和运算符。考虑到引号可以包含的不仅仅是字符,这可能不是微不足道的。

标签: python string arithmetic-expressions


【解决方案1】:

我假设您知道使用 eval 的后果。

s =  "'cars'+'bikes'*'planes'"

df['out'] = eval(re.sub(r"([^+\-*\/]+)", r'df[\1]', s))

它所做的基本上是替代df。它将'cars'+'bikes'*'planes' 更改为df['cars']+df['bikes']*df['planes']。 如果不想使用eval,可以解析column namesoperands 之类的

columns = re.findall(r"'([^+\-*\/]+)'", s)
operands = re.findall(r'([+\-*\/]+)', s)

但在这种情况下,您需要定义操作优先级并创建一个树来计算结果。


更新

import re
import pandas as pd

s =  "'cars'+30*'bikes'-'planes'+20"
s2 = re.sub(r"('[^+\-*\/'\d]+')", r'df[\1]', s)

pd.eval(s2)

【讨论】:

  • 如果我有 s = "'cars'30+'bikes''planes'+20" 如何避免将 df 添加到 20 和 30?是否有可能得到 s = df['cars']*30+df['bikes']*df['planes']+20 this?
  • 'bikes''planes' 之间是否有* 或者它是空的?
  • 哎呀!它放错了地方。就是这个 s = "'cars'+30*'bikes'-'planes'+20" 并且例外的输出是 s = df['cars']+30*df['bikes']-df['planes'] +20。有可能吗?
  • 我正要发短信说“'”。它现在工作正常谢谢洛蒂特兄弟!你是最棒的:)
  • ^ 符号应该像r"('[^>=<=<>!=+\-*\/'\d]+')" 一样开头,这意味着匹配所有内容except >=!=+\-*\/'\d. If youy know that the column names is alphabetical like aa` bb aBa 并且从不喜欢aa_1 some_32,只需使用r"('[A-Za-z]+')",它只匹配abcd...zABCD..Z
猜你喜欢
  • 2021-08-18
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多