简体   繁体   English

从迭代字典追加到列表

[英]Appending to a list from an iterated dictionary

I've written a piece of script that at the moment I'm sure can be condensed. 我已经写了一段脚本,目前可以确定。 What I'm try to achieve is an automatic version of this: 我试图实现的是此的自动版本:

file1 = tkFileDialog.askopenfilename(title='Select the first data file')
file2 = tkFileDialog.askopenfilename(title='Select the first data file')
TurnDatabase = tkFileDialog.askopenfilename(title='Select the turn database file')

headers = pd.read_csv(file1, nrows=1).columns
data1 = pd.read_csv(file1)
data2 = pd.read_csv(file2)

This is how the data is collected. 这就是收集数据的方式。 There's many more lines of code which focus on picking out bits of the data. 还有更多的代码行专注于挑选数据位。 I'm not going to post it all. 我不会发布所有内容。

This is what I'm trying to condense: 这就是我要凝结的:

EntrySummary = []
for key in Entries1.viewkeys():
    MeanFRH = Entries1[key].hRideF.mean()
    MeanFRHC = Entries1[key].hRideFCalc.mean()
    MeanRRH = Entries1[key].hRideR.mean()
# There's 30 more lines of these...
# Then the list is updated  with this:
EntrySummary.append({'Turn Number': key, 'Avg FRH': MeanFRH, 'Avg FRHC': MeanFRHC, 'Avg RRH': MeanRRH,... # and so on})


EntrySummary = pd.DataFrame(EntrySummary)
EntrySummary.index = EntrySummary['Turn Number']
del EntrySummary['Turn Number']

This is the old code. 这是旧的代码。 What I've tried to do is this: 我试图做的是这样的:

EntrySummary = []

for i in headers():
    EntrySummary.append({'Turn Number': key, str('Avg '[i]): str('Mean'[i])})
    print EntrySummary
# The print is only there for me to see if it's worked. 

However I'm getting this error at the minute: 但是我在一分钟出现此错误:

for i in headers():
TypeError: 'Index' object is not callable

Any ideas as to where I've made a mistake? 关于我在哪里犯了错误的任何想法? I've probably made a few... 我可能已经做了一些...

Thank you in advance 先感谢您

Oli 奥利

If I'm understanding your situation correctly, you want to replace the long series of assignments in the "old code" you've shown with another loop that processes all of the different items automatically using the list of headers from your data files. 如果我正确地理解了您的情况,则希望将您显示的“旧代码”中的一长串分配替换为另一个循环,该循环使用数据文件中的标头列表自动处理所有不同的项目。

I think this is what you want: 我认为这是您想要的:

EntrySummary = []
for key, value in Entries1.viewitems():
    entry = {"Turn Number": key}
    for header in headers:
        entry["Avg {}".format(header)] = getattr(value, header).mean()
    EntrySummary.append(entry)

You might be able to come up with some better variables names, since you know what the keys and values in Entries1 are (I do not, so I used generic names). 您可能可以提出一些更好的变量名称,因为您知道Entries1中的键和值是Entries1 (我不知道,所以我使用了通用名称)。

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

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