Pandas 计算数据框中列本身内的数据

发布于 2025-01-17 07:00:36 字数 770 浏览 0 评论 0原文

I have come up with a problem where my data in the column has been recorded as 90-2,91-3,90+4 etc.My motive here is to add and subtract the data directly into the column itself. Datatype of the column is an object.

df = df1["ldm"].str.split('+',expand =True)

if df.shape[1]>1:
  df_2 = df[0].str.split('-',expand = True)
  df_2 = df_2.fillna(value=0)
  df = df.fillna(value=0)
  df_2[0] = df_2[0].astype(int)
  df[1] = df[1].astype(int)
  df_2[1] = df_2[1].astype(int)
  df_2['3'] = df[1]
  df_2[0]=df_2[0]-df_2[1]
  df_2[0] = df_2[0]+df_2['3']

df1['ldm'] = df_2[0]

这是我效率低下的解决方案。我正在寻找一种有效的方法来在数据框中计算它。

I have come up with a problem where my data in the column has been recorded as 90-2,91-3,90+4 etc.My motive here is to add and subtract the data directly into the column itself. Datatype of the column is an object.

df = df1["ldm"].str.split('+',expand =True)

if df.shape[1]>1:
  df_2 = df[0].str.split('-',expand = True)
  df_2 = df_2.fillna(value=0)
  df = df.fillna(value=0)
  df_2[0] = df_2[0].astype(int)
  df[1] = df[1].astype(int)
  df_2[1] = df_2[1].astype(int)
  df_2['3'] = df[1]
  df_2[0]=df_2[0]-df_2[1]
  df_2[0] = df_2[0]+df_2['3']

df1['ldm'] = df_2[0]

This is my inefficient solution..I am looking for an efficient way to compute this in the dataframe.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅浅淡淡 2025-01-24 07:00:36

使用 pandas.eval。它支持有限范围的操作,这使得它使用起来比 python 的 eval 更安全,也比 ast.literal_eval 更方便。

从文档中:

支持以下算术运算:+、-、*、/、**、%、
// (仅限 python 引擎)以及以下布尔运算: |
(或),& (和),和〜(不)。此外,“pandas”解析器允许
使用 and、or 和 not 具有与
相应的按位运算符。 Series 和 DataFrame 对象是
支持并表现得像普通的 Python 评估一样。

df['ldm2'] = pd.eval(df['ldm'])

输出:

    ldm  ldm2
0  90-2    88
1  91-3    88
2  90+4    94

Use pandas.eval. It supports a limited range of operations, which makes it much safer to use than python's eval and more convenient than ast.literal_eval.

From the documentation:

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. Series and DataFrame objects are
supported and behave as they would with plain ol’ Python evaluation.

df['ldm2'] = pd.eval(df['ldm'])

output:

    ldm  ldm2
0  90-2    88
1  91-3    88
2  90+4    94
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文