按间隔拆分长度(米)数据 Pandas
splitting length (metre) data by interval with Pandas
我有一个 length-interval 数据(来自钻孔)的数据框,看起来像这样:
df
Out[46]:
from to min intensity
0 0 10 py 2
1 5 15 cpy 3.5
2 14 27 spy 0.7
我需要对这些数据进行透视,但也要在最不常见的长度区间上分解它;导致 'min' 列成为 headers 列,并且值为 'rank'。输出将如下所示:
df.somefunc(index=['from','to'], columns='min', values='intensity', fill_value=0)
Out[47]:
from to py cpy spy
0 0 5 2 0 0
1 5 10 2 3.5 0
2 10 14 0 3.5 0
3 14 15 0 3.5 0.7
4 15 27 0 0 0.7
所以基本上 "From" 和 "To" 描述了钻孔下方的 non-overlapping 间隔,其中间隔已被最小公分母分割 - 如您所见 "py"区间从原来的table被拆分,第一个(0-5m)拆分为py:2,cpy:0,第二个(5-10m)拆分为py:2,cpy:3.5.
基本 pivot_table 函数的结果是这样的:
pd.pivot_table(df, values='intensity', index=['from', 'to'], columns="min", aggfunc="first", fill_value=0)
Out[48]:
min cpy py spy
from to
0 10 0 2 0
5 15 3.5 0 0
14 27 0 0 0.75
它只是将 from 和 to 列组合为一个索引。重要的一点是我的输出不能有重叠的起始值和终止值(即后续的 'from' 值不能小于先前的 'to' 值)。
是否有使用 Pandas 实现此目的的优雅方法?感谢您的帮助!
我不懂Pandas中的自然区间运算,所以你需要去做。
这是一种方法,如果我正确理解约束条件。
这可能是一个 O(n^3) 问题,它会为大条目创建巨大的 table。
# make the new bounds
bounds=np.unique(np.hstack((df["from"],df["to"])))
df2=pd.DataFrame({"from":bounds[:-1],"to":bounds[1:]})
#find inclusions
isin=df.apply(lambda x :
df2['from'].between(x[0],x[1]-1)
| df2['to'].between(x[0]+1,x[1])
,axis=1).T
#data
data=np.where(isin,df.intensity,0)
#result
df3=pd.DataFrame(data,
pd.MultiIndex.from_arrays(df2.values.T),df["min"])
对于:
In [26]: df3
Out[26]:
min py cpy spy
0 5 2.0 0.0 0.0
5 10 2.0 3.5 0.0
10 14 0.0 3.5 0.0
14 15 0.0 3.5 0.7
15 27 0.0 0.0 0.7
我有一个 length-interval 数据(来自钻孔)的数据框,看起来像这样:
df
Out[46]:
from to min intensity
0 0 10 py 2
1 5 15 cpy 3.5
2 14 27 spy 0.7
我需要对这些数据进行透视,但也要在最不常见的长度区间上分解它;导致 'min' 列成为 headers 列,并且值为 'rank'。输出将如下所示:
df.somefunc(index=['from','to'], columns='min', values='intensity', fill_value=0)
Out[47]:
from to py cpy spy
0 0 5 2 0 0
1 5 10 2 3.5 0
2 10 14 0 3.5 0
3 14 15 0 3.5 0.7
4 15 27 0 0 0.7
所以基本上 "From" 和 "To" 描述了钻孔下方的 non-overlapping 间隔,其中间隔已被最小公分母分割 - 如您所见 "py"区间从原来的table被拆分,第一个(0-5m)拆分为py:2,cpy:0,第二个(5-10m)拆分为py:2,cpy:3.5.
基本 pivot_table 函数的结果是这样的:
pd.pivot_table(df, values='intensity', index=['from', 'to'], columns="min", aggfunc="first", fill_value=0)
Out[48]:
min cpy py spy
from to
0 10 0 2 0
5 15 3.5 0 0
14 27 0 0 0.75
它只是将 from 和 to 列组合为一个索引。重要的一点是我的输出不能有重叠的起始值和终止值(即后续的 'from' 值不能小于先前的 'to' 值)。
是否有使用 Pandas 实现此目的的优雅方法?感谢您的帮助!
我不懂Pandas中的自然区间运算,所以你需要去做。 这是一种方法,如果我正确理解约束条件。 这可能是一个 O(n^3) 问题,它会为大条目创建巨大的 table。
# make the new bounds
bounds=np.unique(np.hstack((df["from"],df["to"])))
df2=pd.DataFrame({"from":bounds[:-1],"to":bounds[1:]})
#find inclusions
isin=df.apply(lambda x :
df2['from'].between(x[0],x[1]-1)
| df2['to'].between(x[0]+1,x[1])
,axis=1).T
#data
data=np.where(isin,df.intensity,0)
#result
df3=pd.DataFrame(data,
pd.MultiIndex.from_arrays(df2.values.T),df["min"])
对于:
In [26]: df3
Out[26]:
min py cpy spy
0 5 2.0 0.0 0.0
5 10 2.0 3.5 0.0
10 14 0.0 3.5 0.0
14 15 0.0 3.5 0.7
15 27 0.0 0.0 0.7