Pandas 数据帧插入计算行
示例中显示了问题的简化: 本质上,我希望在现有行之间插入新行,这是基于使用跨新行的两行中的值的计算 在我的示例中,您可以看到我们插入了一行,该行是该行前后的中点值 我的目标是实际使用一个函数来计算两个纬度之间的中点并插入该值。我认为这个简化的示例将演示所需的技术。我将包括完整的工作代码的lat,lon的例子,如果我得到一个答案Pandas 数据帧插入计算行,pandas,Pandas,示例中显示了问题的简化: 本质上,我希望在现有行之间插入新行,这是基于使用跨新行的两行中的值的计算 在我的示例中,您可以看到我们插入了一行,该行是该行前后的中点值 我的目标是实际使用一个函数来计算两个纬度之间的中点并插入该值。我认为这个简化的示例将演示所需的技术。我将包括完整的工作代码的lat,lon的例子,如果我得到一个答案 import pandas as pd import numpy as np def midpoint(x,y): return (x+y)/2 #we st
import pandas as pd
import numpy as np
def midpoint(x,y):
return (x+y)/2
#we start with this
pd.DataFrame(np.arange(2,10).reshape((4,2)),columns=['A','B'])
A B
0 2 3
1 4 5
2 6 7
3 8 9
#want to get to this.
pd.DataFrame(np.array([2,3,3,4,4,5,5,6,6,7,7,8,8,9]).reshape((7,2)),columns=['A','B'])
A B
0 2 3
1 3 4
2 4 5
3 5 6
4 6 7
5 7 8
6 8 9
Ok这里是拉特龙的例子
gp=pd.DataFrame(np.array([25.7,-87.7],[26.3,-88.6],[27.2,-89.2],[28.2,-89.6]),列=[“纬度”,“经度])
经纬度
0 25.7 -87.7
1 26.3 -88.6
2 27.2 -89.2
3 28.2 -89.6
x=gp[['纬度','经度']]
y=gp[['纬度','经度]].移位(周期=-1)
foo=pd.merge(x,y,后缀=['1','2'],left_index=“True”,right_index=“True”)
#修剪最后一行,因为它有南边
bar=foo['Latitude1','Longitude1','Latitude2','Longitude2'][:-1]
#计算中点并缝合回主数据
条形=条形。应用(中点,轴=1)
fogazzi=np.vstack((gp[['纬度','经度']]值,条['中点纬度','中点经度']]值))
gp=pd.DataFrame(fogazzi,columns=['Latitude','Longitude'])。排序(columns=['Latitude','Longitude']))
经纬度
0 25.700000 -87.700000
4 26.000696 -88.148851
1 26.300000 -88.600000
5 26.750316 -88.898812
2 27.200000 -89.200000
6 27.700144 -89.399084
3 28.200000 -89.600000
-------------------------------------
def中点(跳线):
lat1、lon1、lat2、lon2=跳线
assert-90您可以使用如下合并:
In [54]:
df = pd.DataFrame(np.arange(2,10).reshape((4,2)),columns=['A','B'])
df
Out[54]:
A B
0 2 3
1 4 5
2 6 7
3 8 9
[4 rows x 2 columns]
In [53]:
(df + df.shift(periods=-1))/2
Out[53]:
A B
0 3 4
1 5 6
2 7 8
3 NaN NaN
[4 rows x 2 columns]
In [59]:
combined = df.merge((df + df.shift(periods=-1))/2, how='outer')
combined.sort(columns=['A'],inplace=True)
In [60]:
combined
Out[60]:
A B
0 2 3
4 3 4
1 4 5
5 5 6
2 6 7
6 7 8
3 8 9
7 NaN NaN
[8 rows x 2 columns]
假设我们的索引设置略有不同:
df = pd.DataFrame(np.arange(2,10).reshape((4,2)), index=range(0, 8, 2), columns=['A','B'])
然后:
谢谢你的两个答案(1)和(2),是的,基于我的例子,这两个答案都很好。我将更新原始帖子,并输入lat-lon中点的真实计算值
df = pd.DataFrame(np.arange(2,10).reshape((4,2)), index=range(0, 8, 2), columns=['A','B'])
res = pd.DataFrame(index=range(len(df) * 2 - 1)).join(df)
res.interpolate()