If the data type of the age variable is the object, I want to convert it to numeric. But I get an error like this in my model - data-analysis

these are the categorized form of age variable:
enter image description here
the code i wrote:
age_dict = { "[0-10)" : 1,
"[10-20)" : 2,
"[20-30)" : 3,
"[30-40)" : 4,
"[40-50)" : 5,
"[50-60)" : 6,
"[60-70)" : 7,
"[70-80)" : 8,
"[80-90)" : 9,
"[90-100)" : 10
}
["age_Ordinal"] = df_age.age.map(age_dict)
df_age
I get an error like this in my model:
ValueError: could not convert string to float: '[50-75)'
but there is no age range (50-75) in the variable.

Related

Serializing Multiple API Fields into one. Django

I have a pre-defined API, like:
{
time : some_time,
height : {1: 154, 2: 300, 3: 24},
color : {1: 'red', 2: 'blue', 3: 'green'},
age : {1: 27, 2: 324, 3: 1},
... many, many more keys.
}
I have no control of this API, so cannot change its structure.
Each integer key inside the sub dictionaries are linked and part of one record. For example the object that is 154 in height, is also colour: red and age: 27.
I am aware one strategy to work with this is to have separate serialisers for each field.
class MySerializer(serializers.ModelSerializer):
# Nested serializers
height = HeightSerializer()
colour = ColourSerializer()
age = AgeSerializer()
etc, etc, etc
But that still gives me messy data to work with, that requires lots of update() logic in the serializer.
What I instead want to do is have one nested serializer that has access to the full request data, and can work with height, colour and age simultaneously and return me something like from the to_internal_value() method:
{
['record' : 1, 'height': 154, 'colour' : 'red', 'age' : 27],
['record' : 2, 'height': 300, 'colour' : 'blue', 'age' : 324],
['record' : 3, 'height': 24, 'colour' : 'green', 'age' : 2],
}
But unfortunately the height serializer only seems to have access to information on fields called height. I am aware I can user source="foo" in the init call, but then it only has access to a field called "foo". I want it to have access to all fields.
I noticed there is a source='*' option, but it doesn't work. My init method of the serializer never gets called unless there is a key "height" in the api call.
Any ideas how I can have a nested serialiser that has access to all the data in the request?
Thanks
Joey

How to define a function that adds the values in HashMaps in Python?

The question is : create a function which will calculate the total stock worth in the cafe. You will need to remember to loop through the appropriate maps and lists to do this.
What I have so far :
menu = ("Coffee", "Tea", "Cake", "Cookies")
stock = {
"Coffee" : 10,
"Tea" : 17,
"Cake" : 15,
"Cookies" : 5,
}
price = {
"Coffee" : 'R 12',
"Tea" : 'R 11',
"Cake" : 'R 20',
"Cookies" : 'R 8',
}
def totalstock(stock):
Now I'm stuck, I know there should be a loop and a sum function, but I don't know how to convert the strings to ints so I can add them?
In this case your price dictionary doesn't just have numbers so you'll have to separate the R from the number. Example:
coffee_price = int(price['Coffee'].split(' ')[1])
To explain, take the string at price['Coffee'] and split it, giving a list with 2 values. Return the second value to the int() function to be converted to an integer and stored in coffee_price.

Convert long to ISODate using pymongo

I have a collection with date field as long. A sample json format of the collection is as follows:
{
"processID" : "1410449146441-3-8863e29e0055",
"department" : "ABC",
"price" : 9.99,
"unitSold" : 19,
"date" : 1410449146442
},
{
"processID" : "14104491tf-alhb-8863e29e0055",
"department" : "XYZ",
"price" : 19.99,
"unitSold" : 21,
"date" : 1410985985985
}
I need to convert this date field as ISOdate format so that I can extract year, month and day from it. I need to do it in pymongo.
I tried doing it as datetime.datetime.fromtimestamp({"$divide": ["$date", 1e3]}), but got error "TypeError: a float is required"
Can you please let me know a good way of doing it in pymongo
You got the error because fromtimestamp is a Python function not Mongo DB function. .fromtimestamp expects float instead you provided a dict.
Use datetime module to convert while iterating through your cursor:
import datetime
for x in cursor:
timestamp = datetime.datetime.fromtimestamp(x.get("date")/1000)
# timestamp = object of type datetime.
Note: If you don't divide the long value by 1000, you'll get the error of "year not in range".

How to get sum of nested JSON elements in Long format using scala and play?

I have nested JSON like -
"disks" : [ {
"name" : "v2.16",
"diskAggregate" : "aggr0",
"diskRPM" : 15000,
"totalSizeBytes" : 1077477376,
"vendorId" : "NETAPP ",
"usedBytes" : 1070071808,
"diskType" : "FCAL",
"uuid" : "4E455441:50502020:56442D31:3030304D:422D465A:2D353230:32353836:30303030:00000000:00000000",
"portName" : "FC:A ",
"raidGroup" : "rg0"
},
{
"name" : "v4.16",
"diskAggregate" : "aggr0",
"diskRPM" : 15000,
"totalSizeBytes" : 1077477376,
"vendorId" : "NETAPP ",
"usedBytes" : 1070071808,
"diskType" : "FCAL",
"uuid" : "4E455441:50502020:56442D31:3030304D:422D465A:2D353230:32353633:34333030:00000000:00000000",
"portName" : "FC:B ",
"raidGroup" : "rg0"
}]
I want to get addition 'totalSizeBytes' from above list of objects.
I used following code to get it -
val storageDevices = "above given json".toList
val totalCapacity = storageDevices.foldLeft(0) {
case (sumOfAllDevices, storageDevice) =>
val sumOfTotalBytesOnStorageDevice = storageDevice.disks.foldLeft(0) {
case (totalBytesOnDevice, disk) =>
totalBytesOnDevice + disk.usedBytes.getOrElse(0).toString.toInt
}
sumOfAllDevices + sumOfTotalBytesOnStorageDevice
// Logger.info("dss"+sumOfTotalBytesOnStorageDevice.toString.toInt)
}
This code gives me total capacity in Integer format. But as there are too many objects in disks array, the totalCapacity will get exceed int. So I wanted to convert it to Long while doing addition.
I want following output-
"totalCapacity": [
{
"name": "192.168.20.22",
"y": 123456789
}
]
How do I convert it to Long to get exact sum of all 'totalBytesAvailable' from array/list???
Cast zero values as 0L (by default assumed Int), both in foldLeft(0L) and in getOrElse(0L), so the compiler will enforce arithmetic additions on Long.

Having trouble to decode json string

I have an json string i want to parse to small array of objects, i am using decoder for that but it wont help, why is this happining?
I have defined the variable as $cleanforcharacters
$cleanforcharacters = preg_replace('/["{mtwrdayfsasusseto}"]_/', '', $found['newdiscounthours']);
this is my output
discount_org: "{"day":"8:00","time":"12:00","discount":"10","day":"8:00","time":"12:00","discount":"10"}"
this is desired output (array of objects)
discount_org: [
{
day: 0,
time: 8,
discount: 10
},
{
day: 0,
time: 14,
discount: 10
},
this is how i tried
$arrayOfEmails = json_decode($cleanforcharacters);
and this is what i am getting now
discount_org: {
day: "20",
time: "12:00",
discount: "20"
}
the rest is not coming out either
This is because you have declared that as an object and the keys are overriding the values rather than being set as new values:-
You have given:-
discount_org: "{"day":"8:00","time":"12:00","discount":"10","day":"8:00","time":"12:00","discount":"10"}"
It should be:-
discount_org: "[{"day":"8:00","time":"12:00","discount":"10"},{"day":"8:00","time":"12:00","discount":"10"}]"
Then use:-
$arrayOfEmails = json_decode($cleanforcharacters,true);
This would give you correct result.