第一种方法可能是最直接的方法,您只需迭代并从列表中获取每个值,然后将其添加到结果列表中。在import pprint # used here to output results nicely
data = {
'Period':['2016-02','2016-02','2016-02','2016-02','2016-03','2016-03','2016-04'],
'Name':['a','b','c','c','d','e','v'],
'amount':[2,3,41,1,8,43,20],
'Credit':[5,2,45,50,9,21,32]
}
res = []
count = len(data['Period'])
for i in range(count):
period = data['Period'][i]
name = data['Name'][i]
amount = data['amount'][i]
credit = data['Credit'][i]
if period == '2016-02':
rate = amount / credit * 1.2
elif period == '2016-03':
rate = amount / credit * 1.1
else:
rate = amount / credit * 1.0
res.append( ( period, name, amount, credit, rate ) )
pprint.pprint(res)
更紧凑的解决方案是
^{pr2}$
注意,如果你想要一个numpy的解决方案,请看piRSquared的answer或pandas的解决方案,请看s Ringne的answer。在