I wanted to get the unique values in a Data frame. I used drop.duplicates() but after that, i got the unique values but the indexing are not in natural order. Indexing was something like, 0,1,5,9,15, etc...I wanted a natural indexing like 0,1,2,3,4 etc after doing drop.duplicated(). How to do that?
Just reassign the index after drop duplcated, ie:
df.index = range(0,len(df))
df= df.reset_index()
should do the trick! For more information on what this does, and its arguments you can read the documentation below.
http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.reset_index.html
Related
I have a model that has one attribute with a list of floats:
values = ArrayField(models.FloatField(default=0), default=list, size=64, verbose_name=_('Values'))
Currently, I'm getting my entries and order them according to the sum of all diffs with another list:
def diff(l1, l2):
return sum([abs(v1-v2) for v1, v2 in zip(l1, l2)])
list2 = [0.3, 0, 1, 0.5]
entries = Model.objects.all()
entries.sort(key=lambda t: diff(t.values, list2))
This works fast if my numer of entries is very slow small. But I'm afraid with a large number of entries, the comparison and sorting of all the entries will get slow since they have to be loaded from the database. Is there a way to make this more efficient?
best way is to write it yourself, right now you are iterating over a list over 4 times!
although this approach looks pretty but it's not good.
one thing that you can do is:
have a variable called last_diff and set it to 0
iterate through all entries.
iterate though each entry.values
from i = 0 to the end of list, calculate abs(entry.values[i]-list2[i])
sum over these values in a variable called new_diff
if new_diff > last_diff break from inner loop and push the entry into its right place (it's called Insertion Sort, check it out!)
in this way, in average scenario, time complexity is much lower than what you are doing now!
and maybe you must be creative too. I'm gonna share some ideas, check them for yourself to make sure that they are fine.
assuming that:
values list elements are always positive floats.
list2 is always the same for all entries.
then you may be able to say, the bigger the sum over the elements in values, the bigger the diff value is gonna be, no matter what are the elements in list2.
then you might be able to just forget about whole diff function. (test this!)
The only way to makes this really go faster, is to move as much work as possible to the database, i.e. the calculations and the sorting. It wasn't easy, but with the help of this answer I managed to actually write a query for that in almost pure Django:
class Unnest(models.Func):
function = 'UNNEST'
class Abs(models.Func):
function = 'ABS'
class SubquerySum(models.Subquery):
template = '(SELECT sum(%(field)s) FROM (%(subquery)s) _sum)'
x = [0.3, 0, 1, 0.5]
pairdiffs = Model.objects.filter(pk=models.OuterRef('pk')).annotate(
pairdiff=Abs(Unnest('values')-Unnest(models.Value(x, ArrayField(models.FloatField())))),
).values('pairdiff')
entries = Model.objects.all().annotate(
diff=SubquerySum(pairdiffs, field='pairdiff')
).order_by('diff')
The unnest function turns each element of the values into a row. In this case it happens twice, but the two resulting columns are instantly subtracted and made positive. Still, there are as many rows per pk as there are values. These need to be summed, but that's not as easy as it sounds. The column can't be simply be aggregated. This was by far the most tricky part—even after fiddling with it for so long, I still don't quite understand why Postgres needs this indirection. Of the few options there are to make it work, I believe a subquery is the single one expressible in Django (and only as of 1.11).
Note that the above behaves exactly the same as with zip, i.e. the when one array is longer than the other, the remainder is ignored.
Further improvements
While it will be a lot faster already when you don't have to retrieve all rows anymore and loop over them in Python, it doesn't change yet that it results in a full table scan. All rows will have to be processed, every single time. You can do better, though. Have a look into the cube extension. Use it to calculate the L1 distance—at least, that seems what you're calculating—directly with the <#> operator. That will require the use of RawSQL or a custom Expression. Then add a GiST index on the SQL expression cube("values"), or directly on the field if you're able to change the type from float[] to cube. In case of the latter, you might have to implement your own CubeField too—I haven't found any package yet that provides it. In any case, with all that in place, top-N queries on the lowest distance will be fully indexed hence blazing fast.
I have an array and hash which I need to combine. Please let me know the simplest way to do this.
array1 = [:user_id, :project_id, :task_id]
entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87]}
When it is combined i want a hash like
output = {"user_id"=>1, "project_id"=>8, "task_id"=>87}
Thanks for the help!
It's a bit unclear to me what you want to achieve here. Looking at your example, the easiest solution would be to change the keys of entry_hash using .downcase and adding _id. For the value, you could check if it's an array and if so, use the first value.
output = {}
entry_hash.each do |key, value|
output[key.downcase + '_id'] = value.kind_of?(Array) ? value[0] : value
end
This assumes of course that the keys in the hash are the nouns for the column names in the array. The code above will not work if the names are more complex (e.g. CamelCaseName or snake_case_id). Rails comes with ActiveSupport that can help you there, but this is a totally different question: Converting camel case to underscore case in ruby
If array and hash don't share the same names there is no easy way to do this automatically. Hash doesn't guarantee the order of its elements, so iterating through both and mapping values like in the above snippet won't work reliably.
I have a dataset in which there's a numerical attribute for the 'number of days since last contact' but the value -1 is being used to indicate that there hasn't been a last contact. It is by far the largest value for this attribute.
My idea is to discretise this attribute but how can I ensure there is a 'no contact'/-1 bin?
Also, is this the correct approach to this problem?
The proper approach supposedly is to
Split the data into -1 and everything else
Apply binning to the values in the 'everything else' set only
Concatenate the data sets again (it may be good to shuffle, too)
If anyone else has this question and can't find an answer, here's how I did it based on Anony-Mousse's method. The filter documentation for MathExpression gives a good example of splitting into arbitrary bins.
Split using the MathExpression filter e.g. ifelse(A>0, 2, 1) to split into two bins: above and below 0. I used ifelse(A>0, ifelse(A>400, 21, ceil(A/20)+1), 1) to bin my -1 and >400 values, and for in between values to be in bins of width 20.
Convert using numericToNominal
I am using boost::accumulators::tag::extended_p_square_quantile for calculating percentile. In this, I also need to feed probabilities to the accumulator so I did this m_acc = AccumulatorType(boost::accumulators::extended_p_square_probabilities = probs); where probs is a vector containing the probabilities.
Values in the prob vector are {0.5,0.3,0.9,0.7}
I provided some sample values to accumulator.
But when I try to get the percentile using boost::accumulators::quantile(m_acc, boost::accumulators::quantile_probability = probs[0]); it returns incorrect values and even nan sometimes.
What is wrong here?
I ran into this problem and wasted lot of time to figured out the problem and therefore want to answer this.
Problem is with the vector. Vector should be shorted in increasing order of its values.
Change the vector values to this {0.3,0.5,0.7,0.9} and it will work as expected.
So if someone is using tag::extended_p_square_quantile for percentile(which supports multiple probabilities) then (s)he needs to give probabilities(vector/array/list) in sorted order.
This isn't the case with tag::p_square_quantile because we can give only one value(probability) in it.
I have used R quite a bit and I know I can use head(data[,"column"]) or head(data) to see the first few rows/cells of data.
How can I do that in Stata?
You can use the list command for this:
list column in 1/6
or
list in 1/6
If you have a look at help list, you will discover plenty of options to customize the display.