【问题标题】:How to strip variable out of knot parameter dataframe如何从节点参数数据框中去除变量
【发布时间】:2019-09-13 14:13:30
【问题描述】:

我有一个 statsmodels 系数的数据框。我需要去掉变量名以加入另一个表。

下面是我目前拥有的和想要的代码。

一般说法同bs(np.clip(#variable name#, 0, np.inf), degree = 1, knots = [insert knots][number]

变量可以改变,所以我希望有足够强大的东西来从一般性声明中提取任何变量。

import pandas as pd
#current

dict = {'index': ['bs(np.clip(vehicle_age_model, 0, np.inf), degree=1, knots=[10, 25])[0]'
        , 'bs(np.clip(vehicle_age_model, 0, np.inf), degree=1, knots=[10, 25])[1]'
        , 'bs(np.clip(vehicle_age_model, 0, np.inf), degree=1, knots=[10, 25])[2]'
        ,'bs(np.clip(driver_age_model, 0, np.inf), degree=1, knots=[10, 25])[0]'
        , 'bs(np.clip(driver_age_model, 0, np.inf), degree=1, knots=[10, 25])[1]'
        ,'bs(np.clip(length_ft_model, 0, np.inf), degree=1, knots=[32])[0]'
        ,'bs(np.clip(length_ft_model, 0, np.inf), degree=1, knots=[32])[0]']}

df1 = pd.DataFrame.from_dict(dict)

df1

# Solution

dict2 = {'index': ['bs(np.clip(vehicle_age_model, 0, np.inf), degree=1, knots=[10, 25])[0]'
        , 'bs(np.clip(vehicle_age_model, 0, np.inf), degree=1, knots=[10, 25])[1]'
        , 'bs(np.clip(vehicle_age_model, 0, np.inf), degree=1, knots=[10, 25])[2]'
        ,'bs(np.clip(driver_age_model, 0, np.inf), degree=1, knots=[10, 25])[0]'
        , 'bs(np.clip(driver_age_model, 0, np.inf), degree=1, knots=[10, 25])[1]'
        ,'bs(np.clip(length_ft_model, 0, np.inf), degree=1, knots=[32])[0]'
        ,'bs(np.clip(length_ft_model, 0, np.inf), degree=1, knots=[32])[0]'],
       'desired': ['vehicle_age_model','vehicle_age_model','vehicle_age_model'
                   , 'driver_age_model', 'driver_age_model', 'length_ft_model','length_ft_model' ]}

df2 = pd.DataFrame.from_dict(dict2)

df2

【问题讨论】:

    标签: regex python-3.x string


    【解决方案1】:

    更优雅的解决方案是:

     import re
     def convert(x):
         pattern= re.compile(r"(bs\(np.clip\()(\w*)\,")
         match = pattern.search(x)
         if match:
            return match.group(2)
         return x
     df1['index'].apply(convert)
    

    【讨论】:

    • 是的,这样更好!不知道这一切意味着什么,但谢谢!是否可以将 [] 内的结后的数字拉到自己的列中?
    【解决方案2】:

    无视。反复试验产生了这个丑陋的结果。

    df['index'].str.replace('bs\(np.clip\(', '').str.replace(', 0, np.inf\), degree=1, knots\=\[', '').str.replace('[,\.\)\[\]!?0-9]', '').str.strip()

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多