python中有没有一种快速的方法可以将字符串'1/100'转换为float 0.01?

时间:2020-10-23 16:35:10

标签: python pandas dataframe

我有这个df:

class MyTask(BaseTaskSet):

    def action_one(self):
        self.client.get('dummy_path')

我想将其转换为十进制赔率。

我知道我可以使用 Home Away 5+ corners 6+ corners 7+ corners 8+ corners 9+ corners 10+ corners 11+ corners 12+ corners 13+ corners 14+ corners 0 Aston Villa Leeds 1/100 1/50 1/20 1/8 1/4 4/9 4/6 11/10 13/8 5/2 1 West Ham Manchester City 1/100 1/33 1/12 1/6 1/3 4/7 10/11 11/8 2/1 3/1 2 Fulham Crystal Palace 1/66 1/33 1/10 1/5 2/5 4/6 11/10 7/4 5/2 4/1 3 Manchester Utd Chelsea 1/66 1/33 1/8 1/5 2/5 8/11 11/10 15/8 11/4 4/1 4 Liverpool Sheffield Utd 1/100 1/50 1/20 1/8 2/7 4/9 8/11 11/10 7/4 5/2 5 Southampton Everton 1/66 1/33 1/12 1/5 4/11 8/13 1/1 13/8 5/2 7/2 6 Wolves Newcastle 1/50 1/20 1/8 2/7 1/2 4/5 5/4 2/1 3/1 5/1 7 Arsenal Leicester 1/100 1/33 1/12 1/6 1/3 1/2 10/11 11/8 2/1 3/1 8 Brighton West Brom 1/66 1/33 1/8 1/4 2/5 4/6 11/10 7/4 11/4 4/1 9 Burnley Tottenham 1/100 1/33 1/12 1/6 1/3 4/7 10/11 11/8 9/4 3/1 来实现这一目标,但我想知道是否有更快的方法来实现这一目标。

3 个答案:

答案 0 :(得分:1)

按照@ ch3steR的建议,使用pd.eval并尝试

df['col_name'] = pd.eval(target=df, expr=df['col_name'])

答案 1 :(得分:0)

eval函数呢?

result = eval('1/2')

编辑:正如评论者所指出的那样,eval具有安全隐患,因为它有可能执行任意代码。

答案 2 :(得分:0)

您可以同时使用熊猫applyeval

df.loc[:,'5+ corners':] = df.loc[:,'5+ corners':].apply(pd.eval)

>>> print(df)
>>>
        Home            Away     5+ corners  ... 12+ corners 13+ corners 14+ corners
0     AstonVilla           Leeds       0.01  ...         1.1       1.625         2.5
1        WestHam  ManchesterCity       0.01  ...       1.375           2           3
2         Fulham   CrystalPalace  0.0151515  ...        1.75         2.5           4
3  ManchesterUtd         Chelsea  0.0151515  ...       1.875        2.75           4
4      Liverpool    SheffieldUtd       0.01  ...         1.1        1.75         2.5

这仅适用于最多100行的数据框,请参见here