简体   繁体   中英

How to retrieve and store multiple values from a python Data Frame?

I have the following Dataframe that represents a From-To distance matrix between pairs of points. I have predetermined "trips" that visit specific pairs of points that I need to calculate the total distance for.

For example,

Trip 1 = [A:B] + [B:C] + [B:D] = 6 + 5 + 8 = 19

Trip 2 = [A:D] + [B:E] + [C:E] = 6 + 15 + 3 = 24

import pandas

graph = {'A': {'A': 0, 'B': 6, 'C': 10, 'D': 6, 'E': 7},
         'B': {'A': 10, 'B': 0, 'C': 5, 'D': 8, 'E': 15},
         'C': {'A': 40, 'B': 30, 'C': 0, 'D': 9, 'E': 3}}        
df = pd.DataFrame(graph).T  
df.to_excel('file.xls')

I have many "trips" that I need to repeat this process for and then need to store the values in a row in a new Dataframe that I can export to excel. I know I can use df.at[A,'B'] to retrieve specific values in the Dataframe but how can retrieve multiple values, sum them, store in new Dataframe, and then repeat for the enxt trip.

Thank you in advance for any help or guidance,

I think if you don't transpose then maybe an unstack will help?

import pandas as pd

graph = {'A': {'A': 0, 'B': 6, 'C': 10, 'D': 6, 'E': 7},
         'B': {'A': 10, 'B': 0, 'C': 5, 'D': 8, 'E': 15},
         'C': {'A': 40, 'B': 30, 'C': 0, 'D': 9, 'E': 3}}        
df = pd.DataFrame(graph)
df = df.unstack()
df.index.names = ['start','finish']


# a list of tuples to represent the trip(s)
trip1 = [('A','B'),('B','C'),('B','D')]
trip2 = [('A','D'),('B','E'),('C','E')]
trips = [trip1,trip2]

my_trips = {}
for trip in trips:
    my_trips[str(trip)] = df.loc[trip].sum()

distance_df =  pd.DataFrame(my_trips,index=['distance']).T

distance_df

                                        distance
[('A', 'B'), ('B', 'C'), ('B', 'D')]    19
[('A', 'D'), ('B', 'E'), ('C', 'E')]    24

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM