【问题标题】:How to retrieve and store multiple values from a python Data Frame?如何从 python 数据框中检索和存储多个值?
【发布时间】:2016-03-19 10:22:21
【问题描述】:

我有以下数据框,它表示点对之间的从到距离矩阵。我已经预先确定了访问特定点对的“旅行”,我需要计算它们的总距离。

例如,

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

行程 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')

我有很多“旅行”,我需要重复这个过程,然后需要将值连续存储在一个新的数据框中,我可以导出到 excel。我知道我可以使用 df.at[A,'B'] 来检索 Dataframe 中的特定值,但是如何检索多个值,对它们求和,存储在新的 Dataframe 中,然后重复下一次旅行。

提前感谢您的任何帮助或指导,

【问题讨论】:

  • 什么是 Excel 连接?
  • 您的预期输出是什么,您尝试过什么? How to Ask
  • @Alexander 我试过 Trip1 = df.at['A','B']+df.at['B',C'] + df.at['B',D' ] 和 Trip2 等相同。然后,我遇到问题的部分是将每次旅行的结果写入新的 1 Row x X 列数据框。 excel连接是因为我需要在自己开发的一个excel应用中使用这些结果。
  • 您如何定义您的行程(例如 A->B、B->C、B->D)?

标签: python excel dictionary pandas dataframe


【解决方案1】:

我认为如果你不转置,那么 unstack 可能会有所帮助?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多