Getting IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices - python-3.x

I'm getting this index error when I run this function. This function finds the average rent prices of a zipcode of a city. I have a dictionary of cities called city with zipcode as the key and city name as the value. There are multiple zipcodes for some cities and arrRent is a array with lists of rents of houses of the city and I want to find the average rent price.
def meanPrice(self, city):
total = 0
cityLoc = 0
for keys, cities in self.city.items():
if self.city[keys] == city:
for i in self.arrRent[cityLoc]:
total += int(self.arrRent[cityLoc][i])
mean = total / i
print(total / i)
else:
cityLoc += 1
Here's a snippet of the dictionary:
{'95129': 'San Jose'}
{'95128': 'San Jose'}
{'95054': 'Santa Clara'}
{'95051': 'Santa Clara'}
{'95050': 'Santa Clara'}
and here's a snippet of the array:
[['2659' '2623.5' '2749.5' '2826.5' '2775' '2795' '2810' '2845' '2827'
'2847' '2854' '2897.5' '2905' '2925' '2902.5' '2869.5']
['3342.5' '3386' '3385' '3353' '3300' '3190' '3087.5' '3092' '3170'
'3225' '3340' '3315' '3396' '3470' '3480' '3380']
['2996' '2989' '2953' '2950' '2884.5' '2829' '2785' '2908' '2850' '2761'
'2997.5' '3020' '2952' '2997.5' '2952' '2923.5']
['2804.5' '2850.5' '2850' '2850' '2867' '2940' '2905' '2945' '2938'
'2860' '2884' '2946' '2938' '2986.5' '2931.5' '3032.5']
['2800' '3074' '2950' '2850' '2850' '2875' '2757' '2716' '2738.5' '2696'
'2809' '2891' '3000' '2960' '2950' '2831']]

I see 2 issues:
Issue in your list 'arrRent': It is supposed to be a list of lists, containing rents. But the different rents are not separated by comma in your list:
[['2659' '2623.5' '2749.5' '2826.5' '2775' '2795' '2810' '2845' '2827'
'2847' '2854' '2897.5' '2905' '2925' '2902.5' '2869.5']
['3342.5' '3386' '3385' '3353' '3300' .......
Your issue in code seems to be in this block of code. i is the actual rent here, not the index:
for i in self.arrRent[cityLoc]:
total += int(self.arrRent[cityLoc][i])
Change it to this:
for i in self.arrRent[cityLoc]:
total += int(i)

Related

Numerical integration of a numpy array in incremental time steps

I have two arrays. The first one is time in terms of Age (yrs) and the second one is a parameter that needs to be integrated with respect to time.
age = [5.00000e+08, 5.60322e+08, 6.27922e+08, 7.03678e+08, 7.88572e+08,
8.83709e+08, 9.90324e+08, 1.10980e+09, 1.24369e+09, 1.39374e+09,
1.56188e+09, 1.75032e+09, 1.96148e+09, 2.19813e+09, 2.46332e+09,
2.76050e+09, 3.09354e+09, 3.46676e+09, 3.88501e+09, 4.35371e+09,
4.87897e+09, 5.46759e+09, 6.12722e+09, 6.86644e+09, 7.69484e+09,
8.62318e+09, 9.66352e+09, 1.08294e+10, 1.21359e+10, 1.36000e+10]
sfr = [1.86120543e-02, 1.46680445e-02, 1.07275184e-02, 8.56960274e-03,
6.44041855e-03, 4.93194263e-03, 3.69203448e-05, 2.69813985e-04,
6.17644783e-04, 1.00780427e-02, 1.20645391e-02, 3.05009362e-02,
3.91535011e-02, 5.35479858e-02, 7.36489068e-02, 9.63931263e-02,
1.11108326e-01, 1.47781221e-01, 1.63057763e-01, 2.27429626e-01,
2.20941333e-01, 2.74413180e-01, 2.72010867e-01, 4.32215233e-01,
5.79654549e-01, 7.39362218e-01, 9.41168727e-01, 1.18868347e+00,
1.42839043e+00, 1.91326333e+00]
I want to perform integration of sfr array with respect to age array, but in steps.
For example, the first integration should contain only the first elements of both arrays, the second integration should contain the first 2 elements of both arrays, the third should have first 3 elements of both arrays and so on and so forth. And save the integration result for each step in a single output array.
The exact form of your desired result is not so clear. So, here are 2 posibilities:
age = [5.00000e+08, 5.60322e+08, 6.27922e+08, 7.03678e+08, 7.88572e+08,
8.83709e+08, 9.90324e+08, 1.10980e+09, 1.24369e+09, 1.39374e+09,
1.56188e+09, 1.75032e+09, 1.96148e+09, 2.19813e+09, 2.46332e+09,
2.76050e+09, 3.09354e+09, 3.46676e+09, 3.88501e+09, 4.35371e+09,
4.87897e+09, 5.46759e+09, 6.12722e+09, 6.86644e+09, 7.69484e+09,
8.62318e+09, 9.66352e+09, 1.08294e+10, 1.21359e+10, 1.36000e+10]
sfr = [1.86120543e-02, 1.46680445e-02, 1.07275184e-02, 8.56960274e-03,
6.44041855e-03, 4.93194263e-03, 3.69203448e-05, 2.69813985e-04,
6.17644783e-04, 1.00780427e-02, 1.20645391e-02, 3.05009362e-02,
3.91535011e-02, 5.35479858e-02, 7.36489068e-02, 9.63931263e-02,
1.11108326e-01, 1.47781221e-01, 1.63057763e-01, 2.27429626e-01,
2.20941333e-01, 2.74413180e-01, 2.72010867e-01, 4.32215233e-01,
5.79654549e-01, 7.39362218e-01, 9.41168727e-01, 1.18868347e+00,
1.42839043e+00, 1.91326333e+00]
integr_pairs = [[(a, s) for a, s in zip(age[:i], sfr[:i])] for i in range(1, len(age))]
print(integr_pairs)
# [[(500000000.0, 0.0186120543)], [(500000000.0, 0.0186120543), (560322000.0, 0.0146680445)], ....
integr_list = [[item for t in [(a, s) for a, s in zip(age[:i], sfr[:i])] for item in t ]for i in range(1, len(age))]
print(integr_list)
# [[500000000.0, 0.0186120543], [500000000.0, 0.0186120543, 560322000.0, 0.0146680445],

how could I make list of lists from neo4j record

I am facing list manipulation from loop iteration. I am trying to populate a list from Neo4j record
myquery="""MATCH (c :Customer {walletId:$item})-[:MR|:SENDS_MONEY]-(d)-[:PAYS]->(m)
WHERE NOT (c)-[]-(m)
RETURN c.walletId, m.walletId, m.name, COUNT(m.name) ORDER BY COUNT(m.name) DESC LIMIT 30"""
result=graphdbsessionwallet.run(myquery,item=item)
#print(result)
for record in result:
print(list(record))
and my current result is
['01302268120', '01685676658', 'Shojon Medical Hall', 6]
['01302268216', '01733243988', 'APEXFOOTWEAR LIMITED', 1]
and so on
desired
[['01302268120', '01685676658', 'Shojon Medical Hall', 6],['01302268216', '01733243988', 'APEXFOOTWEAR LIMITED', 1]]
I want to put this lists into one list , kindly help me to solve this
You can modify your query to return the list with the help of COLLECT clause:
MATCH (c :Customer {walletId:$item})-[:MR|:SENDS_MONEY]-(d)-[:PAYS]->(m)
WHERE NOT (c)-[]-(m)
WITH c, m, COUNT(m.name) as cnt
ORDER BY cnt DESC
RETURN COLLECT([c.walletId, m.walletId, m.name, cnt])
LIMIT 30

Create a dictionary from two lists having duplicate elements

Create a dictionary from two lists having duplicate elements where list 1 is the key of the new dictionary and for all strings in list 2 that exactly match list 1, append it to its values field for the keys in list 1. So, for example:
{'assembla':['assemblabase', 'assemblauploading']}
Like this, I want for each element in list 1
Stuck in this logic:
new_d = {}
for j in list2:
if j == list1 :
new_d['j'].get('j')
print(new_d)
List 1:
list1 = ['assembla', 'bitbucket', 'cloudapp', 'cloudforge', 'cloudinary', 'concur', 'confluence', 'convo', 'dochub', 'docstoc', 'docusign', 'draw.io', 'dropbox', 'egnyte', 'evernote', 'facebook', 'flickr', 'github', 'gitlab', 'glassdoor', 'globalmeet', 'gotowebinar', 'hightail', 'hootsuite', 'huddle', 'icloud', 'imgur', 'instagram', 'issuu', 'jumpshare', 'linkedin', 'lucidpress', 'mail.ru', 'maytech', 'meetup', 'mega', 'mendeley', 'mixi', 'myspace', 'ning', 'onehub', 'owncloud', 'pastebin', 'pinterest', 'prezi', 'proofhub', 'quip', 'quora', 'readytalk', 'reddit', 'renren', 'screencast', 'scribd', 'sendthisfile', 'sharevault', 'slack', 'slideshare', 'smartsheet', 'soundcloud', 'sourceforge', 'stocktwits', 'storify', 'surveymonkey', 'syncplicity', 'tableau', 'teamdrive', 'teamviewer', 'trello', 'tumblr', 'twitter', 'viber', 'vimeo', 'vine', 'virustotal', 'workday', 'yammer', 'youtube', 'zendesk', 'zenefits']
List 2:
list2 = ['2ch', '2chbase', '2chposting', '51.com', '51.commail', '51.combase', '51.combbs', '51.composting', '51.comwebdisk', '51.commusic', '51.comgames', 'adobeconnect', 'adobemeeting', 'adobemeetingdesktopsharing', 'adobemeetinguploading', 'adobemeetingfiletransfer', 'adobemeetingremotecontrol', 'adobeconnectnow', 'adobeconnectnowbase', 'adobeconnectnowfiletransfer', 'adobeconnectnowremotecontrol', 'adobecreativecloud', 'adobecreativecloudbase', 'adobecreativeclouduploading', 'aim', 'aimbase', 'aimvideo', 'aimaudio', 'aimfiletransfer', 'aimexpress', 'aimexpressbase', 'aimexpressfiletransfer', 'aliwangwang', 'aliwangwangbase', 'aliwangwangaudiovideo', 'aliwangwangfiletransfer', 'aliwangwangremotecontrol', 'amazonclouddrive', 'amazonclouddrivebase', 'amazonclouddriveuploading', 'amazonmusic', 'amazonmusicbase', 'amazonmusicstreaming', 'amebanow', 'amebanowbase', 'amebanowposting', 'assembla', 'assemblabase', 'assemblauploading', 'autodesk360', 'autodesk360base', 'autodesk360uploading', 'avayawebalive', 'avayawebalivebase', 'avayawebalivedesktopsharing', 'avayawebalivevoice', 'avayawebalivefiletransfer', 'bacnet', 'bacnetbase', 'bacnetackalarm', 'bacnetconfirmedcovnotify', 'bacnetconfirmedeventnotify', 'bacnetgetalarmsummary', 'bacnetgetenrollmentsummary', 'bacnetsubscribecov', 'bacnetatomicreadfile', 'bacnetatomicwritefile', 'bacnetaddlistelement', 'bacnetremovelistelement', 'bacnetcreateobject', 'bacnetdeleteobject', 'bacnetreadproperty', 'bacnetreadpropconditional', 'bacnetreadpropmultiple', 'bacnetwriteproperty', 'bacnetwritepropmultiple', 'bacnetdevicecommcontrol', 'bacnetconfirmedprivatexfer', 'bacnetconfirmedtextmessage', 'bacnetreinitializedevice', 'bacnetvtopen', 'bacnetvtclose', 'bacnetvtdata', 'bacnetauthenticate', 'bacnetrequestkey', 'bacnetreadrange', 'bacnetlifesafetyoperation', 'bacnetsubscribecovproperty', 'bacnetgeteventinformation', 'baiduhi', 'baiduhibase', 'baiduhiaudiovideo', 'baiduhifiletransfer', 'baiduhigames', 'bebo', 'bebomail', 'bebobase', 'beboposting', 'bitbucket', 'bitbucketbase', 'bitbucketuploading']
I believe this solves your problem:
new_dict = {}
for i in list1:
new_dict[i] = []
for j in list2:
if i in j:
new_dict[i].append(j)
Use a combined dict/list comprehension (it is shorter, but has worse readability):
new_dict = {key:[val for val in list2 if key in val and not key == val] for key in list1 if key in list2}
On my machine I get the following output:
{'assembla': ['assemblabase', 'assemblauploading'], 'bitbucket': ['bitbucketbase', 'bitbucketuploading']}
Updated with your more precise problem description. Just added a second condition within the list comprehension.
Use zip to create dict out to two list
a=[1,2]
b=["a","b"]
c=zip(a,b)
c=dict(c)

How to sum map values based on two keys?

I have a map with two keys (customer and price) like the one shown below:
[
customer: ['Clinton', 'Clinton', 'Mark', 'Antony', 'Clinton', 'Mark'],
price: [15000.0, 27000.0, 28000.0, 56000.0, 21000.0, 61000.0]
]
customer and price values are mapped by their index positione i.e first name from customer list maps with the first price and so on.
Example
Cliton price is 15000.0
Cliton price 27000.0
Mark price 28000.0
Antony price 56000.0
Clinton price 21000.0
Mark price 61000.0
I would like to sum up price grouped by names. Expected output:
Clinton price 63000
Mark price 89000
Antony price 56000
Are there any built-in functions to achieve this in Groovy, or do I need to iterate over the map and sum values by writing my own functions?
You can start with a transpose on both lists to get tuples of customer and price. From there its basically like the other answers (group by customer, build map with customer and summed up prices). E.g.:
def data = [
customer:['Clinton', 'Clinton', 'Mark', 'Antony', 'Clinton', 'Mark'],
price:[15000.0, 27000.0, 28000.0, 56000.0, 21000.0, 61000.0]
]
println(
[data.customer, data.price].transpose().groupBy{ c, p -> c }.collectEntries{ c, ps -> [c, ps*.last().sum() ] }
)
// => [Clinton:63000.0, Mark:89000.0, Antony:56000.0]
In the problems like this, we should always plan having every entry as separate object inside a list to make it intuitive and future easy manipulation in the list.
In that case the same result can be obtained in naturally
def list = [
[customer: 'Clinton', price: 15000.0],
[customer: 'Clinton', price: 27000.0],
[customer: 'Mark', price: 28000.0],
[customer: 'Antony', price: 56000.0],
[customer: 'Clinton', price: 21000.0],
[customer: 'Mark', price: 61000.0]
]
def map = list.groupBy({it.customer}).collectEntries {k, v -> [k, v.price.sum()]}
map.each {println it}
The followint creates a map of price aggregated by customer:
def vals = (0..(-1+map.customer.size()))
.collect{['name':map.customer[it], 'price': map.price[it]]}
.groupBy{it['name']}
.collectEntries{[(it.key): it.value.collect{it['price']}.sum()]}
That results in:
[Clinton:63000.0, Mark:89000.0, Antony:56000.0]
It's essentially an iteration using a range of numbers from 0 to map.customer.size() - 1, followed by a group-by with sum of values.
This version is derived from #cfrick's answer, with an alternative to the summation. Using a map with default values isn't as "functional"/declarative, but IMHO the code is arguably easier to grok later (i.e. maintenance):
Given:
def map = [
customer: ['Clinton', 'Clinton', 'Mark', 'Antony', 'Clinton', 'Mark'],
price: [15000.0, 27000.0, 28000.0, 56000.0, 21000.0, 61000.0]
]
Approach:
def getSumMap = { data ->
def result = [:].withDefault { c -> 0.0 }
[data.customer, data.price].transpose().each { c, p -> result[c] += p }
result
}
assert 63000.0 == getSumMap(map)['Clinton']
assert 89000.0 == getSumMap(map)['Mark']
assert 56000.0 == getSumMap(map)['Antony']

Python 3: Accesing values in key in dictionary

automobiles = {
'germany': ['bmw', 'audi', 'mercedes benz'],
'japan': ['honda', 'toyota', 'subaru'],
'united states': ['ford', 'gm', 'buick'],
'italy': ['alfa romeo', 'ferrari', 'maserati'],
'great britain': ['jaguar', 'mini', 'aston martin'],
}
How can I access individual values in the different keys? (example: Who do I access the 'audi' in the germany key or 'buick' in the united states key?
So you have a dictionary who's keys are strings and who's values are lists.
To access 'audi' you can do this:
print(automobiles['germany'][1])
# which prints audi
Syntax: command(dict['key'][index])
In your case this would translate to:
print(automobiles['germany'][1])
'audi'
print(automobiles['united states'][2])
'buick'
The values stored in your dictionary are stored as lists. You can access elements in a list like list[n] where n is the index of the value you wish to access. Indexes start at 0 for python.

Resources