w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python defaultdict that does not insert missing values
You can subclass dict and implement __missing__: class missingdict(dict): def __missing__(self, key): return 'default' # note, does *not* set self[key] Demo: >>> d = missingdict() >>> d['foo'] 'default' >>> d {} You could subclass defaultdict too, you'd get the factory handling plus copy and pickle support thrown in: from collections import defaultdict class missingdict(defaultdict): def __missing__(self, key): return self.default_factory() Demo: >>> from collections import defaultdict >>> class missingdict(defaultdict): ... def __missing__(self, key): ... return self.default_factory() ... >>> d = missingdict(list) >>> d['foo'] [] >>> d defaultdict(<type 'list'>,

Categories : Python

Insert Missing Month Values as 0 in Python List
I think a simpler solution is to just iterate through the months and years in the range, and add the ones that are missing. This would be easier if you used a dict instead of a list of two-element lists, so let's do that first. data = dict(t) for year in range(2012, 2014): for month in range(1, 13): mmyyyy = '{:02}-{:04}'.format(month, year) data.setdefault(mmyyyy, 0) Then, if you want to convert it back to your original format, that's easy too: t = [[k, v] for k, v in data.items()] And if you need them sorted by date… Well, your month-first format makes that ugly, but it's certainly doable: t = sorted(t, key=lambda kv: kv[0][3:] + kv[0][:2]) But, as that last line shows, it's often a whole lot easier to deal with dates as date objects rather than stri

Categories : Python

Building a table from Python nested dictionaries with missing values
You can use d[j].get(q, '0') instead of d[j][q] to fill in 0 for all missing entries: # print the table header labs = sorted(max(d.values(), key=len)) print "bin" + " " + " ".join(labs) # loop and print the values for j in d: print j + " " + " ".join(str(d[j].get(q, '0')) for q in labs) I also made some slight modifications to the other parts of the code so the columns are ordered.

Categories : Python

Clean solution for missing values in python list comprehensions
Try this: top_scores = [{"name":obj.name, "score":obj.score, "latitude": obj.loc.lat if hasattr(obj.loc, lat) else 0 "longitude":obj.loc.lon if hasattr(obj.loc, lon) else 0} for obj in db_objs] Or, in your query set a default value.

Categories : Python

Reading space delimited file in Python/Panda with missing values
I agree with Justin that cleaning it up first is the best way to be sure to get it right. If you can skim your results to verify quality control, than this hack might get the job done in this case. pd.read_csv(header=None, sep='s{1, 7}') I'll say again, this is not a great idea. If you just want to get a smallish data set loaded, it will do the job. But if you can't verify that it worked, better use read_fwf and carefully specify colspecs, or follow Justin's advice and clean up the file.

Categories : Python

Numeric values in r and dealing with missing values
You can use sapply to do them all at once, but you will end up with a matrix so you have to wrap in an as.data.frame to convert back. The warnings are just there to tell you that there were characters in your original data that could not be matched to a number, so were replaced by NA. In your case these characters were "-". To ensure the warnings do not print, use suppressWarnings: suppressWarnings(as.data.frame(sapply(df,as.numeric))) KY27PHY1 KY27PHY2 KY27PHY3 1 4 4 5 2 5 4 4 3 5 4 4 4 4 4 4 5 NA NA NA 6 4 5 5 7 2 2 1 8 3 3 4 9 5 5 5 10 NA NA NA 11 4 5 4

Categories : R

R replacing missing values with the mean of surroundings values
Using na.locf (Last Observation Carried Forward) from package zoo: R> library("zoo") R> x <- c(12.2, NA, NA, 16.8, 10.1, NA, 12.0) R> (na.locf(x) + rev(na.locf(rev(x))))/2 [1] 12.20 14.50 14.50 16.80 10.10 11.05 12.00 (does not work if first or last element of x is NA)

Categories : R

Python : Best way to sort a python dictionary based on values ; values are lists
Do you mean length? >>> sorted(d, key=lambda k: -len(d[k])) ['Gross', 'Ugly', 'Random', 'Stupid'] >>> sorted(d, key=lambda k: len(d[k]), reverse=True) ['Gross', 'Ugly', 'Random', 'Stupid']

Categories : Python

How to impute missing values with row mean in R
Use this: filter <- is.na(myVec) myVec[filter] <- colMeans(myDF[,filter], na.rm=TRUE) Where myVec is your vector and myDF is your data.frame.

Categories : R

how many values are missing for each observation
You can determine the number of missing values in a row with the NMISS and CMISS functions (NMISS for numeric, CMISS for character). If you have a list of just some of your variables, you should use that list; if not, you need to deal with the fact that number_missing itself will be missing (the -1 there). data want; set have; number_missing=nmiss(of _numeric_) + cmiss(of _character_)-1; run; Then do whatever you want with that new variable.

Categories : Sas

Using rollmean when there are missing values (NA)
From ?rollmean The default method of ‘rollmean’ does not handle inputs that contain ‘NA’s. In such cases, use ‘rollapply’ instead.

Categories : R

SQL update missing values from same table
The best solution would be to properly normalize the tables such that a one to one join table was created between them which joins each name to a single city, if indeed there should be exactly one city per name. Given what you have though, you may supply a subquery in the FROM clause which returns the MAX(city) per name group. From there the SET clause updates the main table's city to the value returned by the subquery. UPDATE tbl t SET city = c.city FROM /* Subquery in FROM returns first (max()) non-null city per name */ (SELECT name, MAX(city) AS city FROM tbl WHERE city IS NOT NULL GROUP BY name) c WHERE /* Only update non-null cities */ t.city IS NULL /* Here's the joining relation to the subquery */ AND t.name = c.name; Here's a demo: http://sqlfiddle.com/#!1/6ad

Categories : SQL

feedparser, missing entry values
In the current feed XML, you will see that the custom tags are actually in entry 3, not entry 1. In addition, while feedparser can consume the custom tags, they are renamed. This is described in http://pythonhosted.org/feedparser/namespace-handling.html . Try this (I am using version 5.1.2 of feedparser): >>> f.entries[3].title u'Summary - Remnants of BARBARA (EP2/EP022013)' >>> f.entries[3].nhc_center u'18.5, -94.5' >>> f.entries[3].nhc_type u'REMNANTS OF' >>> f.entries[3].nhc_name u'BARBARA' ...and similarly for the other children of nhc:Cyclone.

Categories : Python

Find and replace missing values with row mean
My solution is rwmns = rowMeans(df,na.rm=TRUE) df$c1[is.na(df$c1)] = rwmns[is.na(df$c1)] df$c2[is.na(df$c2)] = rwmns[is.na(df$c2)] df$c3[is.na(df$c3)] = rwmns[is.na(df$c3)] > df c1 c2 c3 1 1 3 2 2 2 1 1 3 3 3 3 4 2 3 1 Is there a more elegant way, especially when someone has many columns?

Categories : R

check missing values across two tables
something like select i.* from items as i where not exists ( select * from categories as c where c.item_id = i.item_id and c.cat_id <> 0 )

Categories : Mysql

R: levelplot (some values are missing in the contour)
Yes the panel.2dsmoother smooths away the relatively small zero region. Try to remove the smoother, for example using this you can see the blue region. levelplot(z ~ x * y, d, col.regions=col.l, cuts=30)

Categories : R

Impute Missing Values with Caret
This first part is a bug; the NA values should not be 1's (obviously). In the meantime, you can use model.matrix to generate the dummy variables, but you might have to do this at once for all of the data. Also, if you are using train, you can use the formula method. Overall, that is a better approach. I'll fix this in the next few weeks. I'm about to release a version of caret and this, plus UseR, will delay me a bit. EDIT: a new version will be released in the next week that fixes the bug Max

Categories : R

Find missing values, constrained by another value
Let's start by creating a saved query named [AccountCombinations] that gives us all combinations of ParentAccount and AccountNum: SELECT t2.ParentAccount, t1.AccountNum, t1.AccountName FROM Table1 t1, ( SELECT DISTINCT ParentAccount FROM Table2 ) t2 That query returns ParentAccount AccountNum AccountName ------------- ---------- ----------- 100 1 a 200 1 a 100 2 b 200 2 b 100 3 c 200 3 c 100 4 d 200 4 d Now we can just extract the ones that don't exist in Table2 SELECT * FROM AccountCombinations WHERE NOT EXISTS ( SELECT *

Categories : Ms Access

D3 Area chart that tends to zero where values are missing
I think the answer from this other SO post gives a usable answer, reposting it here so that this is not a dead-end for visitors coming from Google and finding this post first (as I did). d3 linechart - Show 0 on the y-axis without passing in all points?

Categories : D3 Js

How to do boolean algebra on missing values?
You can define a custom class (singleton?) and define custom __and__ (and whatever other you neeed) function. See this: http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types

Categories : Python

How can i delete missing values in my csv_file
It isn't clear from your question if you want to delete just values from the columns (which sounds wrong to me) or from all the columns. Either way it is better to use the power of genfromtxt. I recommend you read this marvellous guide or just the docs. In there you will find an argument missing values with this you could specify how you want to handle such occurrences when it is imported. There are many different ways to do this but one example could be using the fact that genfromtxt replaces missing floats with nan. Checking for the occurrence of nan in a row and disregarding if true: import numpy as np from StringIO import StringIO data = """ 0,4,1 34758,1,100 52,, """ my_data = np.genfromtxt(StringIO(data), delimiter=",") index_to_use=[] for i, row in enumerate(my_data): if T

Categories : Python

R dataframe from XML when values are multiple or missing
You can use xmlToList and then plyr to get a dataframe you can use require(XML) require(plyr) xD <- xmlParse(xData) xL <- xmlToList(xD) ldply(xL, data.frame) > ldply(xL, data.frame) .id name buildings.building.type buildings.building.bname 1 city London landmark Tower Bridge 2 city New York station Grand Central 3 city Paris landmark Eiffel Tower buildings.building.type.1 buildings.building.bname.1 1 station Waterloo 2 <NA> <NA> 3 landmark Louvre You can pick what you need from this dataframe

Categories : Xml

How to add values from the GAE dashboard to a missing field
Go to the "Datastore viewer" then select the kind of entity you want to modify. Select the individual item by clicking on it's ID/Name, add the data then click save. Now, it's probably the case you've tried this and it won't work because those "old" models literally don't have the field present so you can update it. Changing a model does not update all the older saved instances of that model, as you've noticed. So you'll have to write a bit of code that loads them, presents them to you in some kind of interface then you can add the relevant value then re-save it, then in the datastore it'll have the field you want and it can be updated from the admin interface in the future. But until that field exists on that model you can't add content to the field. Or you could write a bit of co

Categories : Google App Engine

Fill the missing/incorrect values for the gender
You can start with this, but what are the conditions with which you determine if it should be M or F? UPDATE yourTable SET gender = CASE WHEN -- your condition where you determine if it should be M -- THEN 'M' ELSE 'F' END WHERE LOWER(gender) NOT IN ('m', 'f')

Categories : Sql Server

Get all missing values between two limits in sql table column
First build a table of all N IDs. declare @allPossibleIds table (id integer) declare @currentId integer select @currentId = 1 while @currentId < 1000000 begin insert into @allPossibleIds select @currentId select @currentId = @currentId+1 end Then, left join that table to your real table. You can select MIN if you want, or you could limit your allPossibleIDs to be less than the max table id select a.id from @allPossibleIds a left outer join YourTable t on a.id = t.Id where t.id is null

Categories : SQL

Fill zeros for missing values in range
You could use a query like this that uses a LEFT JOIN: SELECT series, COUNT(score.n) FROM generate_series(0, (SELECT max(n) FROM score)) series LEFT JOIN score ON series=score.n GROUP BY series Please see fiddle here.

Categories : SQL

Filling missing values using numpy.genfromtxt
The issue is that numpy doesn't like ragged arrays. Since there is no character in the third position of the last row of the file, so genfromtxt doesn't even know it's something to parse, let alone what to do with it. If the missing value had a filler (any filler) such as: 1 2 3 4 5 6 7 8 '' Then you'd be able to: sol = np.genfromtxt("a.txt", dtype=float, invalid_raise=False, missing_values='', usemask=False, filling_values=0.0) and: sol array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., nan]]) Unfortunately, if making the columns of the file uniform isn't an option, you might be stuck with line-by-line parsing. One other possibility would be IF all the "short" rows are a

Categories : Python

finding the missing value for ValueError: need more than X values to unpack
values = tuple(generatevalues(q)) try: a, b, c, x, y, z = values except ValueError as e: print(len(values)) # for example print(values) To debug this function - it's a good time to learn about the debugger values = tuple(generatevalues(q)) try: a, b, c, x, y, z = values except ValueError as e: import pdb; pdb.set_trace()

Categories : Python

SQL Search for records with missing values in the same table
Don;t know if this will work on SQLAnywhere. SELECT DISTINCT r.ReferenceID FROM (SELECT ReferenceID FROM TableName WHERE StatusID = 1 GROUP BY ReferenceID) r CROSS JOIN (SELECT StatusID FROM TableName GROUP BY StatusID) d LEFT JOIN TableName a ON d.StatusID = a.StatusID AND r.ReferenceID = a.ReferenceID WHERE a.StatusID IS NULL ORDER BY r.ReferenceID SQLFiddle Demo (running in MySQL)

Categories : SQL

pandas: Filling missing values within a group
You can do this: df.groupby('trial').fillna(method='ffill').fillna(method='bfill') cs_name trial 0 A1 1 1 A1 1 2 A1 1 3 A1 1 4 B2 2 5 B2 2 6 B2 2 7 B2 2 8 A1 3 9 A1 3 10 A1 3 11 A1 3

Categories : Python

Datagrid column header values are missing
Currently you're binding DataGridColumn.Header which means that your GridDataSource should expose 3 properties (Selection, XmlFile and Result) to be displayed in column headers, not values. If I understand your problem and data model, I think what what you want to bind is Binding, not Header: <DataGrid.Columns> <DataGridCheckBoxColumn Header="Selection" Binding="{Binding Selection}"/> <DataGridTextColumn Header="XmlFile" Binding="{Binding XmlFile}"/> <DataGridTextColumn Header="Result" Binding="{Binding Result}"/> </DataGrid.Columns> also DataGrid has AutoGenerateColumns option , which might be of a use here, that will create columns automatically for you based on the attached data source so you don't have to specify DataGrid.Columns manually <

Categories : Dotnet

Reshape acast() remove missing values
In this case, you might do better sticking to base R's table feature. I'm not sure that you can have an irregular array like you are looking for. For example: > lapply(df[-1], function(x) table(df[[1]], x)) $score1 x 1 2 3 one 9 6 5 two 11 4 5 $score2 x 1 2 3 4 5 6 one 2 5 4 3 3 3 two 4 2 2 3 4 5 $score3 x 1 2 3 one 9 5 6 two 4 11 5 $score4 x 1 2 3 4 one 4 4 8 4 two 2 6 5 7 Or, using your "long" data: with(dfMelt, by(dfMelt, variable, FUN = function(x) table(x[["subject"]], x[["value"]])))

Categories : Arrays

Checkbox Values Missing after upgrading to Sitefinity 6.1
The upgrade process from Sitefinity 5.1 to 6.1 added controlRenderingCompatibilityVersion="3.5" to the pages section in web.config. That was causing checkboxes to not include the value attribute. <configuration> <system.web> <pages controlRenderingCompatibilityVersion="3.5"> </pages> </system.web> </configuration>

Categories : Asp Net

Multi series chart (D3) with missing values
I could solve it, but I'm not sure if I can handle data updates this way with transitions. I changed the data format a bit and am drawing each line separately now: http://jsfiddle.net/G5z4N/3/ var data = [ { name: "x1", color: "green", data: [ [1, 0.8], [2, 0.9], [3, 0.9], [5, 0.8], [6, 0.9] ] }, { name: "x2", color: "red", data: [ [3, 1.2], [4, 1.1], [5, 1.1], [6, 1.2], [7, 1.3] ] }, { name: "x3", color: "blue", data: [ [1, 0.7], [2, 0.7], [3, 0.7], [4, 0.7], [5, 2.7], [6, 2.6], [

Categories : Javascript

DataFrame Column with missing values won't accept input
You might be getting a TypeError when you're trying to change the column value. Add this to your code: if not Cell_GMDesig.is_empty(): self.PD_CL['Cdesig_gm'] = self.PD_CL['Cdesig_gm'].astype(str) # cast to string first self.PD_CL['Cdesig_gm'][self.UID] = str(Cell_GMDesig.value) (Some more details: When Pandas reads in a CSV, it selects a datatype for each column. A blank column is read in as a column of floats, and writing a string to one of the entries will fail. Putting in junk data lets pandas know that the column shouldn't be numerical, so the write succeeds.)

Categories : Python

How to handle missing values when using a reverse geocode function?
Better use this instead: coords2country_NAsafe <- function(points) { bad <- with(points, is.na(lon) | is.na(lat)) result <- character(length(bad)) result[!bad] <- coords2country(points[!bad,]) result }

Categories : R

idw() or krige() Error: dimensions do not match when missing values
The na.action argument deals with missing values within newdata (not locations or data). This is clearly stated in ?idw / ?krige / ?predict.gstat function determining what should be done with missing values in 'newdata'. The default is to predict 'NA'. Missing values in coordinates and predictors are both dealt with. There is no method to deal with NA values within the locations or data (and hence the error which is basically saying that there are two more values in the locations as the data (ie. the x and y coordinate of the missing data point) You can get it to work by removing location with the missing value int <- idw(zinc ~ 1, meuse2[!is.na(meuse2$zinc),],newdata= meuse.grid)

Categories : R

Jsoup will clean up your HTML content while parsing and also It can handle your HTML though its not well-formed. Try to dump the html after parsing i.e, Document.html() and check the dump if your discarded elements are eligible for your select clause. UPDATE Here you go, try this out, I'll explain you things if this works!! public static void main(String[] args) throws IOException { try { Map<String, String> cookieMap = new HashMap<String, String>(); cookieMap.put("day1host", "h"); cookieMap.put("d1.loginity.mark", "1"); cookieMap.put("hostid", "-1314014314"); cookieMap.put("__qca", "P0-2042580316-1371938383086"); cookieMap.put("cd1v", "OOhB"); cookieMap.put("c29", "1"); cookieMap.put("__utma", "210074

Categories : Java

R-Find missing values from the dataframe and insert value in that position
For each date make rows 0:23, convert to dataframe, then merge with your data. Your data: values <- read.table(text="ID Date Hour Value 1 2013-06-01 8 9 2 2013-06-01 9 17 3 2013-06-01 10 16 4 2013-06-01 11 21 5 2013-06-01 12 19 6 2013-06-01 13 15 7 2013-06-01 14 14 8 2013-06-01 15 14 9 2013-06-01 16 21 10 2013-06-01 17 22 11 2013-06-01 18 13 12 2013-06-01 19 2 13 2013-06-01 20 2 14 2013-06-01 21 1 15 2013-06-01 22 1 16 2013-06-01 23 1 17 2013

Categories : R

HighCharts datetime xAxis without missing values (weekends)
Highcharts doesn't support ordinal axis. This feature is part of Highstock and require Highstock lbrary to be used. When using Highstock, you are able to create stock charts by calling new Highstock.StockChart() and basic charts by callling new Highstock.Chart().

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.