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]
![](https://i.stack.imgur.com/PsvQz.png)
这是我低效的解决方案。我正在寻找一种有效的方法来在数据框中计算它。
Use pandas.eval。它支持有限范围的操作,这使得它使用起来比python的安全得多eval
并且比ast.literal_eval
.
从文档中:
支持以下算术运算:+、-、*、/、**、%、
// (仅限 python 引擎)以及以下布尔运算: |
(或)、&(和)和 ~(非)。此外,“pandas”解析器允许
使用 and、or 和 not 具有与
相应的按位运算符。 Series 和 DataFrame 对象是
支持并表现得像普通的 Python 评估一样。
df['ldm2'] = pd.eval(df['ldm'])
output:
ldm ldm2
0 90-2 88
1 91-3 88
2 90+4 94
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)