相关疑难解决方法(0)

将区间的字符串表示形式转换为 pandas 中的实际区间

我的问题很简单,但我不确定是否有办法完成我正在寻找的事情:

我必须在 SQL 数据库中存储一些数据,其中包括一些稍后将使用的间隔。因此,我必须将其存储为字符串,如下所示:

 variable     interval
    A          (-0.001, 2.0]
    A          (2.0, 6.0]
Run Code Online (Sandbox Code Playgroud)

那么,我想使用所说的间隔来削减另一个变量,如下所示:

df1 =  pd.DataFrame({'interval': {4: '(-0.001, 2.0]',
  5: '(2.0, 6.0]'},
 'variable': {4: 'A',
  5: 'A',
}})
df2 =  pd.DataFrame({'A': [1,1,3]})
bins = df1[df1.variable.eq('A')].interval
new_series = pd.cut(df2['A'], bins=bins)
Run Code Online (Sandbox Code Playgroud)

但这带来了:

 ValueError: could not convert string to float: '(-0.001, 2.0]'
 
Run Code Online (Sandbox Code Playgroud)

尝试过:

bins = bins.astype('interval')
Run Code Online (Sandbox Code Playgroud)

但这带来了:

TypeError: type <class 'str'> with value (-0.001, 2.0] is not an interval
Run Code Online (Sandbox Code Playgroud)

有什么我可以做的吗?谢谢

python intervals pandas

5
推荐指数
1
解决办法
3241
查看次数

标签 统计

intervals ×1

pandas ×1

python ×1