简体   繁体   English

在熊猫数据框中按给定索引顺序连续求和的值

[英]Sum values in given Index order consecutively in pandas dataframe

I have a list of index values that represent the order of the coordinates I should be visiting on a map. 我有一个索引值列表,这些索引值表示我应该在地图上访问的坐标的顺序。 Each index represents (x,y). 每个索引代表(x,y)。

Out[4]: [0, 8, 11, 6 ,10, 3, 4, 2, 14, 1, 7, 12, 13, 15, 5, 9]

Using these coordinates I generated a distance matrix. 使用这些坐标,我生成了一个距离矩阵。 My aim is to find the total travel distance. 我的目的是找到总的行驶距离。

I manage to achieve it using iloc where I consecutively summed the index values. 我设法使用iloc来实现这iloc ,在iloc中我连续求和了索引值。 However need an automated way of doing this as I have a large amount of data to go through. 但是,由于我需要处理大量数据,因此需要一种自动化的方法。 Is there an easier way to do this? 有没有更简单的方法可以做到这一点?

In[6]: dmatrix.iloc[0][8]+dmatrix.iloc[8][11]+dmatrix.iloc[11][6]+dmatrix.iloc[6][10]+dmatrix.iloc[10][3]+dmatrix.iloc[3][4]+dmatrix.iloc[4][2]+dmatrix.iloc[2][14]+dmatrix.iloc[14][1]+dmatrix.iloc[1][7]+dmatrix.iloc[7][12]+dmatrix.iloc[12][13]+dmatrix.iloc[13][15]+dmatrix.iloc[15][5]+dmatrix.iloc[5][9]+dmatrix.iloc[9][0]

You can create a loop and iterate through your list of indexes: 您可以创建一个循环并遍历索引列表:

sum = 0
for i in range(0, len(yourList)-1):
    sum += dmatrix.iloc[yourList[i]][yourList[i+1]]

Best 最好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Pandas 数据框 - 将列相加到预先给定的值,返回索引 - Pandas dataframe - Sum columns up to a pre given value, return index pandas 数据帧中第二级多索引的总和值 - Sum values for second level of multi-index in pandas dataframe 从DataFrame到父索引 - Python / Pandas的值和 - Sum values from DataFrame into Parent Index - Python/Pandas Pandas-通过对列和索引的值求和来合并两个数据框 - Pandas- merging two dataframe by sum the values of columns and index 为 Pandas DataFrame 中的给定索引值组合连续行 - Combine Consecutive Rows for given index values in Pandas DataFrame 如何在pandas DataFrame中设置给定索引级别的值 - How to set values for a given index level in a pandas DataFrame 使用字典替换 Pandas 数据帧上给定索引号的列值 - Using a dictionary to replace column values on given index numbers on a pandas dataframe 给定MultiIndex对象如何更改熊猫DataFrame层次结构索引的值 - How to change values of a pandas DataFrame hierarchical index given a MultiIndex object 检索连续等于列表值的 Pandas dataframe 行 - Retrieve Pandas dataframe rows that are consecutively equal to the values of a list 在Pandas中,如何在给定类似索引的情况下使用来自另一个数据帧的值来修补具有缺失值的数据帧? - In Pandas, how can I patch a dataframe with missing values with values from another dataframe given a similar index?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM