我有一个长度间隔数据(来自钻孔)的数据框,看起来像这样:
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”列作为列标题,值是“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
所以基本上“从”和“到”描述了钻孔下方的非重叠区间,其中区间已按最小公分母拆分 - 正如您可以看到原始表中的“py”区间已拆分,第一个(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 值(即后续的“from”值不能小于之前的“to”值)。
有没有一种使用 Pandas 来完成此操作的优雅方法?感谢您的帮助!
最佳答案
我不知道 Pandas 中的自然区间算法,所以你需要去做。 这是一种方法,如果我正确理解约束条件。 这可能是一个 O(n^3) 问题,它将为大条目创建巨大的表。
# 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
关于python - 用 Pandas 按间隔拆分长度(米)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44878438/