Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
371,200
39,648,991
Pandas dataframe pivot not fitting in memory
<p>I have a dataframe <code>df</code> with the following structure:</p> <pre><code> val newidx Code Idx 0 1.0 1220121127 706 1 1.0 1220121030 706 2 1.0 1620120122 565 </code></pre> <p>It has 1000000 lines. In total we have 600 ...
<p>Try to see if this fits in your memory:</p> <pre><code>df.groupby(['newidx', 'Code'])['val'].max().unstack() </code></pre> <p><code>pivot_table</code> is unfortunately very memory intensive as it may make multiple copies of data.</p> <hr> <p>If the <code>groupby</code> does not work, you will have to split your ...
python|pandas|dataframe|out-of-memory
12
371,201
43,988,128
Python - Differences between numpy asarray assignment
<p>What is the difference between</p> <pre><code>train_x = np.asarray([[0.0], [1.0], [2.0], [3.0], [4.0]]) train_y = np.asarray([1.0, 1.1, 3.0, 2.0, 5.0]) </code></pre> <p>in Python numpy.asarray assignment? What is the meaning of [] brakets in the first line?</p> <p>Thank you.</p>
<p>The difference is creating a numpy array from a list of floats (1D) vs creating an array from a list of list of floats (2D)</p>
python|numpy
0
371,202
44,298,723
Why this isn't printing out the X,Y np arrays
<p>So I have a dataframe <code>activities_and_attractions</code> with X,Y attributes numbers. I want to create a numpy array </p> <p>[[x1,y1]</p> <p>[x2,y2]</p> <p>[x3,y3]]</p> <p>but it turns out it only prints the last row</p> <pre><code>data = np.array([activities_and_attractions.X[0], activities_and_attraction...
<p>You need to assign the output of <code>vstack</code> to <code>data</code> in the loop:</p> <pre><code>for i in range(len(activities_and_attractions.index)): data = np.vstack((data, np.array([activities_and_attractions.X[i], activities_and_attractions.Y[i]]))) # assign to data </code></pre> <p>Consider using <...
python|numpy
1
371,203
44,218,195
Identifying difference of rows with a similar column using pandas
<p>I have written a script to parse a csv file. The csv file contains an ID and timestamp.</p> <pre><code>df = pd.read_csv(dataset_path, names = ['ID','TSTAMP','DIFF'], delimiter=';') d = {'min':'TSTAMP-INIT','max':'TSTAMP-FIN'} df = df.groupby(['UID'])['TSTAMP'].agg([min, max]).reset_index().rename(columns=d) df['DIF...
<p>on the UID column you are aggregating timestamp and then picking up min and max for that uid and then taking the difference. but for your requirement select the two columns and then rank them and do a self join on it with uid and rank = rank-1. or you can apply Rolling() pandas method.</p>
python|csv|pandas
0
371,204
44,038,685
Improve a sliced function (numpy)
<blockquote> <p>Slice is a powerful access index for elements of an array available in numpy. This solution is one of the most efficient. The image is initially create with zeros and then filled with those on even lines and then on odd lines, always scan the image every two pixels.</p> <p>Implement an iscc...
<p>It is possible to generate the whole <code>G</code> matrix at once, not building it by parts. That should speed up your operation a bit at least. Further, the calculation of Gaux is not used for anything and could therefore be removed, leading to:</p> <pre><code>def isccsym(F): G = F.conj().T return (abs(F-...
python|arrays|numpy
0
371,205
44,126,920
How to filter values out of a pivot table according to user input
<p>I am currently trying to change my pandas pivot table builder code to include a filter.</p> <p>Users will be asked the following questions which will be used to filter values out:</p> <pre><code>filterindex = raw_input('Column to filter: ') confilter = raw_input('Filter by &lt;, &gt; or != ?: ') value = raw_input(...
<p>Here attribute access does not work, need general <code>[]</code>:</p> <pre><code>table = table[table[filterindex] &lt; value] </code></pre>
python|pandas|pivot-table
1
371,206
44,083,168
Why is int type error? TypeError
<p>I got an error, TypeError: slice indices must be integers or None or have an <strong>index</strong> method . Traceback is like</p> <pre><code>Traceback (most recent call last): File "test.py", line 24, in &lt;module&gt; wavdata = wav[z:q] TypeError: slice indices must be integers or None or have an __index__ ...
<p>The variable <code>z</code> and <code>q</code> are still <code>float</code></p> <pre><code>center = len(wav) // 2 cuttime = 0.04 z = center - cuttime // 2 * fs q = center + cuttime // 2 * fs </code></pre> <p>Because both <code>cuttime</code> and <code>fs</code> are <code>float</code>, so the whole expre...
python|numpy|scipy
2
371,207
44,074,909
Numpy array multiple mask
<p>Trying to slice and average a numpy array multiple times, based on an integer mask array:</p> <p>i.e.</p> <pre><code>import numpy as np data = np.arange(11) mask = np.array([0, 1, 1, 1, 0, 2, 2, 3, 3, 3, 3]) results = list() for maskid in range(1,4): result = np.average(data[mask==maskid]) results.append...
<p>One approach using <a href="https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.bincount.html" rel="nofollow noreferrer"><code>np.bincount</code></a> -</p> <pre><code>np.bincount(mask, data)/np.bincount(mask) </code></pre> <p>Another one with <a href="https://docs.scipy.org/doc/numpy-1.12.0/reference...
python|arrays|numpy
1
371,208
44,264,018
backward, grad function in pytorch
<p>I'm trying to implement backward, grad function in pytorch.</p> <p>But, I don't know why this value is returned.</p> <p>Here is my code.</p> <pre><code>x = Variable(torch.FloatTensor([[1,2],[3,4]]), requires_grad=True) y = x + 2 z = y * y gradient = torch.ones(2, 2) z.backward(gradient) print(x.grad) </code></pr...
<p>The below piece of code on pytorch v0.12.1</p> <pre><code>import torch from torch.autograd import Variable x = Variable(torch.FloatTensor([[1,2],[3,4]]), requires_grad=True) y = x + 2 z = y * y gradient = torch.ones(2, 2) z.backward(gradient) print(x.grad) </code></pre> <p>returns </p> <pre><code>Variable contain...
variables|pytorch
2
371,209
44,189,278
poly1d gives erroneous coefficients when they are very large integers
<p>I am working with python 3.5.2 in ubuntu 16.04.2 LTS, and NumPy 1.12.1. When I use poly1d function to get the coeffs, there is a mistake with the computation: </p> <pre><code>&gt;&gt;&gt; from numpy import poly1d &gt;&gt;&gt; from math import fabs &gt;&gt;&gt; pol = poly1d([2357888,459987,78123455],True) &gt;&gt;&...
<p>As Warren Weckesser said, this is a precision issue. But it can be worked around by declaring the array of roots to be of type object. In this way you can take advantage of Python's big integers, or of higher precision provided by <code>mpmath</code> objects. NumPy is considerate enough <a href="https://github.com/n...
python|numpy|polynomials
4
371,210
44,367,478
numpy.hstack with strings and numbers removes decimals
<p>I am trying to create a table to export in CSV. I have to attach different numerical values (with decimals), and I would like also to attach an indicator column. This is formed by empty spaces '_' and 'X', in order to help me with the post-process of the data. As you can see in the code below, while I append only nu...
<p>Numpy convert all elements to a common datatype, which is, in your case <code>S1</code>, strings of length 1.</p> <p>Despite this, my test shows, that the common datatype os <code>S1</code> and <code>float</code> is <code>S32</code>:</p> <pre><code>&gt;&gt;&gt; z = array([['X'],[' ']], dtype='S1') &gt;&gt;&gt; d =...
python|string|numpy|append|decimal
0
371,211
44,344,876
Tiling in groupby on dataframe
<p>I have a data frame that contains returns, size and sedols for a couple of dates.</p> <p>My goal is to identify the top and bottom values for a certain condition per date, i.e I want the top decile largest size entries and the bottom decile smallest size entries for each date and flag them in a new column by 'xx' a...
<p>Consider using <code>transform</code> on the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html" rel="nofollow noreferrer">pandas.qcut</a> method with labels 1 through ntile+1 for a <em>decile</em> column, then conditionally set <em>flag</em> with <code>np.where</code> using decile valu...
python|dataframe|tiling|pandas-groupby
1
371,212
43,958,447
applying a function groupwise in python
<p>How would you apply a function groupwise to a pandas data frame; where the function is applied to the Child Group but the child groups are repeated across different parent groups?</p> <p>Example:</p> <pre><code>| Parent Group | Child Group | Value | -------------------------------------- | A | I1 ...
<p>You can just do something like this:</p> <pre><code>df.groupby(['Parent Group', 'Child Group'])['Value'].apply(lambda x: ', '.join(x)) </code></pre> <p>Output:</p> <pre><code> Parent Group Child Group A I1 V1, V2 I2 V3, V4 B I1 ...
python|pandas|numpy
0
371,213
44,270,455
Sorting dataframe by two columns in Python
<p>I'm getting the following error from the code below: </p> <pre><code>***File "&lt;ipython-input-61-517e344a129d&gt;", line 1 df.sort_values(by "Script Count", "Drug Name"), axis=0, ascending=True, inplace=False, kind='quicksort', ^ SyntaxError: invalid syntax*** (the carrot i...
<p>Refering to the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html#pandas-dataframe-sort-values" rel="nofollow noreferrer">docs</a>, the right syntax is:</p> <pre><code> DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='las...
python|csv|pandas
2
371,214
44,285,869
How to convert Pandas dataframe to np.array while preserving the index?
<p>For example, I have a small set of data (from movielens)</p> <p>check.csv</p> <pre><code>userId,movieId,rating,timestamp 1,31,2.5,1260759144 1,1029,3.0,1260759179 1,1061,3.0,1260759182 2,17,5.0,835355681 3,267,3.0,1298861761 3,296,4.5,1298862418 3,318,5.0,1298862121 </code></pre> <p>If I do </p> <pre><code>ratin...
<pre><code>df = pd.read_csv('check.csv') Y = pd.pivot_table(df, values=['rating'], index=['movieId'], columns=['userId']) rating userId 1 2 3 movieId 31 2.5 0 0 1029 3.0 0 0 1061 3.0 0 0 17 0 5.0 0 296 0 0 ...
python|pandas
0
371,215
44,293,327
Split string with names and middle initial? (python3)
<p>I have a dataset, however it includes Position #, "Lastname, Firstname M ",,</p> <p>I am able to split it, however i want the middle initial gone, and the white space gone too, this is what i have:</p> <pre><code>df = pd.read_excel('C:\\HR employees\\EE Listing as of 5-30-17.xlsx') df['Last Name'], df['First Nam...
<pre><code>df = pd.read_excel('C:\\HR employees\\EE Listing as of 5-30-17.xlsx') df['Last Name'], df['First Name'] = df['NAME'].str.split(',').str df['First Name'] = df['First Name'].apply(lambda s: s[:-2] if s[-2] == ' ' else s) del df['NAME'] df.to_excel('output.xlsx') </code></pre> <p>The lambda function che...
python|python-3.x|pandas
2
371,216
44,297,368
Remove columns from pandas DataFrame that are not integers and outside specified numerical range
<p>I have a DataFrame that has imported data. However, the imported data can be incorrect and so I am trying to get rid of it. An example DataFrame:</p> <pre><code> user test1 test2 other 0 foo 1 7 bar 1 foo 2 9 bar 2 foo 3;as 5 bar 3 foo ...
<p>You could do something like this; use <code>np.logical_and</code> to construct the <code>and</code> condition from multiple columns and use it to subset the data frame:</p> <pre><code>headers = ['test1', 'test2'] df[pd.np.logical_and(*(pd.to_numeric(df[col], errors='coerce').isin(values_dict[col]) for col in header...
python|pandas|dataframe
2
371,217
44,357,145
Python: Alternative way to avoid memoryerror when using numpy array?
<p>I am new to python and started using numpy. I am following an algorithm from paper and with my dataset it requires an array of dimension 1million * 1million.</p> <p>The exact code is <code>larray(np.random.normal(0, sigma**2, size=(794832, 794832))</code></p> <p>Although I have a 16GB ram, numpy tries to load the ...
<p>The size of the data you are creating will depend on the matrix size and the precision-type of the data.</p> <p>You are trying to use <code>np.random.normal</code> that creates a matrix with float64 precision type values. The 64 number means that your are using 64 bits for each number, so each number will require a...
python|numpy|memory|memory-management|out-of-memory
3
371,218
44,155,560
Why does int(maxint) give a long, but int(int(maxint)) give an int? Is this a NumPy bug?
<p>Pretty self-explanatory (I'm on Windows):</p> <pre><code>&gt;&gt;&gt; import sys, numpy &gt;&gt;&gt; a = numpy.int_(sys.maxint) &gt;&gt;&gt; int(a).__class__ &lt;type 'long'&gt; &gt;&gt;&gt; int(int(a)).__class__ &lt;type 'int'&gt; </code></pre> <p>Why does calling <code>int</code> once give me a <code>long</code>...
<p>As proposed in the (now-deleted) other answer, this does seem to be a bug due to an incorrect use of <code>&lt;</code> instead of <code>&lt;=</code>, but it's not coming from the code cited in the other answer. That code is part of the printing logic, which isn't involved here.</p> <p>I believe the code that handle...
python|python-2.7|numpy|int|long-integer
4
371,219
44,109,048
create pandas dataframe from python dictionary
<p>I am trying to create pandas dataframe from dictionary which should look like. the keys are the index and values are assign as first column.</p> <pre><code>Expected Output 2016-06-01 02:00:00 grey 2016-06-02 02:00:00 green 2016-06-03 02:00:00 green . . . . 2016-07-26 02:00:00 green 2016-07-27 02:00...
<p>Hopefully, I understand the logic in your script correctly.</p> <p>Here is the full code:</p> <pre><code>import pandas as pd import sqlite3 as sql from datetime import datetime def add_column_date_value(row): usec = row['usec'] current_start = row['current_start'] current_end = row['current_end'] ...
python|mysql|pandas|numpy
1
371,220
69,374,962
Merging DataFrames with Different Columns
<p>Suppose I have two dataframes <code>df1</code> and <code>df2</code> as shown by the first two dataframes in the image below. I want to combine them to get <code>df_desired</code> as shown by the final dataframe in the image. My current attempts result in the third dataframe in the image; as you can see it is ignorin...
<p>You can merge on <code>name</code> with outer join using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>.merge()</code></a></p> <pre><code>df_desired = df1.merge(df2, on='name', how='outer') </code></pre> <p><strong>Result:</strong></p...
python|pandas
0
371,221
69,432,662
pandas split column based on groupby
<p>I want to split a column into multiple column based on a grouped value. For example</p> <pre class="lang-py prettyprint-override"><code># input df = pd.DataFrame([[1,2,1], [1,4,4], [1,5,7], [2,1,1], [2,3,5], [2,3,1]], columns=['cat', 'v1', 'v2']) #output df_out = pd.DataFrame([[1,2,0,1,0], [...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>DataFrame.unsta...
python|pandas|numpy
1
371,222
69,307,263
How find duplicates in Python Pandas DataFrame across parent groups for all children?
<p>Given the below DataFrame, how do I find the duplicates across parent groupings for all parents?</p> <pre><code>data = {'buildings': {0: 'mansion', 1: 'mansion', 2: 'house', 3: 'house', 4: 'house', 5: 'apartment', 6: 'apartment', 7: 'apartment', 8: 'apartment', 9: 'apartment', 10: 'apartment', 11: 'apartment', 12: '...
<p>In your case try with <code>duplicated</code></p> <pre><code>out = g[g.index.get_level_values(2).duplicated(keep=False)] Out[294]: Value buildings vehicles animals apartment big truck jaguar 11 lemur 8 lion 10 ...
python|pandas|dataframe|duplicates|pandas-groupby
1
371,223
69,633,879
Read in existing CSV with columns in scientific notation, create new CSV with float
<p>I've read about how you can write a df to CSV in pandas, and suppress scientific notation using:</p> <pre><code>float_format='{:f}' </code></pre> <p>But what about an existing csv with several columns that look like this:</p> <pre><code>FIPS_BLOCK FIPS_BLKGR FIPS_TRACT 5.51E+14 5.51E+11 5.51E+10 5.51E+14 ...
<p>The solution to <a href="https://stackoverflow.com/questions/34013790/pandas-read-scientific-notation-and-change">this</a> question uses pandas' built in <code>to_numeric</code> function to cast entries with scientific notation:</p> <pre class="lang-py prettyprint-override"><code>df1 = df.apply(pd.to_numeric, args=(...
python|pandas|string|csv
0
371,224
69,481,508
Pivot/crosstab without agg function duplicates issue?
<p>I have the following dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame.from_dict({'data_point_key': {28: 'a', 30: 'b', 31: 'c', 32: 'd', 33: 'e', 34: 'f', 55: 'a', 56: 'b', 57: 'c', 58: 'd', 59: 'e', 60: 'f', 61: 'a', 63: 'b'...
<p>You can remove duplicates before pivoting seems cleanest way in my opinion:</p> <pre><code>df = df.drop_duplicates(['request_id','data_point_key','val']) df1 = pd.crosstab(index=df['request_id'], columns=df['data_point_key'], values=df['val'], aggfunc=','.join) print (df1) data_po...
python-3.x|pandas|dataframe
2
371,225
69,658,275
Read CSV file in Pandas Python
<p>I'm trying to read CSV file.</p> <pre><code>import pandas as pd df = pd.read_csv(r'C:\Users\San\TEMP OLSTP MECH AMT.csv') df.head() </code></pre> <p>But when I show the dataset, it looks messed up. <a href="https://i.stack.imgur.com/QQ3Ig.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QQ3Ig.png" ...
<p>Your data is <code>;</code>-sheared, you need to inform <code>pandas</code> about that, try</p> <pre><code>import pandas as pd df = pd.read_csv(r'C:\Users\San\TEMP OLSTP MECH AMT.csv',sep=&quot;;&quot;) df.head() </code></pre> <p>Read <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_cs...
python|pandas|csv|export-to-csv
4
371,226
69,549,888
Passing a function through list of columns with numpy.vectorize or DataFrame.apply?
<p>I've got the following data frame</p> <pre><code>df = pd.DataFrame(data= {'Product_JP': ['トマトコ- サルサ C225G','マトケチヤツプ','トマトケチヤツプバリユ-','ケチヤツプハ-フ','トマトケチヤツププレミアム'], 'Value1': [1,12313,1.123,0.112,0], 'Metric1_JP': ['マ-ケットサイズ(販売金額(x1000))','加重販売率(販売金額)','アイテム販売店当り(販売個数)','加重販売率(...
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a> applies the function to each cell (row) in the Series since there is a single dimension. However, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" ...
python|pandas|vectorization|apply
1
371,227
69,515,775
Why is the mean squared error increasing over epochs?
<p>I am training a neuron network, and I encounter this phenomenon which is the loss is decreasing while the mse metric is increasing. I still cannot figure it out the problem. <a href="https://i.stack.imgur.com/OyX3Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OyX3Y.png" alt="enter image descrip...
<p>The problem is in the line of code <code>self.true_positives.assign_add(tf.reduce_mean(loss))</code> It should be <code>self.true_positives.assign(tf.reduce_mean(loss))</code></p>
machine-learning|keras|tensorflow2.0
0
371,228
69,315,586
When are Model call() and train_step() called?
<p>I am going through this tutorial on how to customize the training loop</p> <p><a href="https://colab.research.google.com/github/tensorflow/docs/blob/snapshot-keras/site/en/guide/keras/customizing_what_happens_in_fit.ipynb#scrollTo=46832f2077ac" rel="noreferrer">https://colab.research.google.com/github/tensorflow/doc...
<p>These are different concepts and are used like this:</p> <ul> <li><code>train_step</code> is called by <code>fit</code>. Basically, <code>fit</code> loops over the dataset and provide each batch to <code>train_step</code> (and then handles metrics, bookkeeping, etc., of course).</li> <li><code>call</code> is used wh...
python|tensorflow|machine-learning
11
371,229
69,329,784
How to use Adam().minimize in tensorflow 2x?
<p>First I disable eager execution Then, I compute my loss function as follows:</p> <pre><code>def loss_fn(x, y): y_ = model(x, training=True) loss = tf.reduce_mean(tf.square(y_ - y)) return loss </code></pre> <p>My optimizer is:</p> <pre><code>opt = Adam(1e-3) </code></pre> <p>Now, I want to minimize the a...
<p><code>minimize</code> function expects a loss function as a parameter in order to compute gradients using a gradient tape within it. So you may write <code>train</code> function this way,</p> <pre class="lang-py prettyprint-override"><code>def train(x, y): opt.minimize(lambda : loss_fn(x, y), var_list=model.trai...
python|keras|tensorflow2.0|minimize
2
371,230
69,408,994
Matplotlib plot becomes blank after tf.image.resize
<p>I have some code that I am using with tensorflow datasets. It's worked fine previously and it may still work. But I don't think so</p> <pre><code>img = parse_image(img_paths[0]) img = tf.image.resize(img, [224, 224]) plt.imshow(img) </code></pre> <p>Just outputs a blank <code>224x224</code> canvas.</p> <pre><code>im...
<p>The &quot;problem&quot; is with Matplotlib. When you resize with Tensorflow, it turns your input to float. Matplotlib accepts two image formats, integers between 0-255 and floats between 0 and 1. If you call <code>plt.imshow()</code> on floats of more than 1, it will clip all values and you'll see a white image. It'...
python|tensorflow|matplotlib|image-processing|tensorflow-datasets
2
371,231
69,608,765
Find the max value across all features in tensorflow
<p>Consider the following code below:</p> <pre><code>import tensorflow as tf input_slice=3 labels_slice=2 def split_window(x): inputs = tf.slice(x,[0], [input_slice]) labels = tf.slice(x,[input_slice], [labels_slice]) return inputs, labels dataset = tf.data.Dataset.range(1, 25 + 1).batch(5).map(split_...
<p>One solution to your problem would be to use <code>tf.TensorArray</code> and <code>tf.reduce_max</code>:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf input_slice=3 labels_slice=2 def split_window(x): inputs = tf.slice(x,[0], [input_slice]) labels = tf.slice(x,[input_slice],...
python|tensorflow|tensorflow-datasets
1
371,232
69,544,056
Python: Trim strings in a column
<p>I have a column dataframe that I would like to trim the leading and trailing parts to it. The column has contents such as: <code>['Tim [Boy]', 'Gina [Girl]'...]</code> and I would like it to make a new column that just has <code>['Boy','Girl'... etc.]</code>. I tried using <code>rstrip</code> and <code>lstrip</code>...
<p>I assume that the cells of the column are <code>'Tim [Boy]'</code>, etc.</p> <p>Such as in:</p> <pre><code> name_gender 0 AAa [Boy] 1 BBc [Girl] </code></pre> <p>You want to use a replace method call passing a regular expression to pandas.</p> <p>Assuming that your dataframe is called <code>df</code>, the origin...
python|pandas
1
371,233
69,429,077
Aggregate count based on column identifier
<p>Given a dataframe with this structure and with a variable with identifiers such as &quot;q1_att_brand&quot;:</p> <pre><code>id q1_1_1 q1_1_2 q1_2_1 q1_2_2 1 1 1 1 1 2 1 1 1 3 1 1 4 1 1 1 5 1 1 1 </code></pre...
<p>You can turn your columns into a multi-index, then use sum and unstack:</p> <pre><code># Do this step if &quot;id&quot; is not already the index # df = df.set_index('id') df.columns = pd.MultiIndex.from_tuples( (f'att{a}', f'brand{b}') for _, a, b in df.columns.str.split('_')) df.sum().unstack() brand1 ...
python|pandas
3
371,234
69,605,457
Pandas drop rows appearing above/below string match
<p>I have a dataframe from a .txt file, and I am only interested in the data that appears between the <code>&lt;Header&gt;</code> tags.</p> <pre><code> 0 1 0 webmaster @.com 1 &lt;Header&gt; 121112 2 ReportID 5353 3 Date 20210630 4 Type DMV13 5 &lt;/Header&gt; ...
<p>You could extract the <code>index</code> of the rows where the sign <code>&lt;</code> or <code>&gt;</code> is contained using <code>str.contains(r'..|..')</code>, and then filter your dataframe with <code>iloc</code>:</p> <pre><code># Extract the min and max index of rows that contain '&lt;' or '&gt;' min_i = df[df[...
python|python-3.x|pandas
0
371,235
69,337,156
Finding the delta of two unmatched dataframes in pandas
<p>Having 2 Data Frames with readings at 2 different times as:</p> <p>DF1</p> <pre><code> Sensor ID Reference Pressure Sensor Pressure 0 013677 100.15 93.18 1 013688 101.10 95.23 2 013699 100.87 ...
<p>Pandas has this beautiful feature where it automatically aligns on indices. So we can use that to solve your problem:</p> <pre><code>df1.set_index(&quot;Sensor ID&quot;).sub(df2.set_index(&quot;Sensor ID&quot;)) </code></pre> <pre><code> Reference Pressure Sensor Pressure Sensor ID ...
python|pandas
7
371,236
69,596,978
make command in windows 10 generating the error:
<p>Here's the code, I am trying to compile using make command in command prompt.</p> <pre><code>nvcc := &quot;C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.0/bin/nvcc&quot; cudalib := &quot;C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.0/extras/CUPTI/lib64&quot; cudainclude := &quot;C:/Program Files/N...
<p><strong>The immediate problem</strong></p> <p>You need to set your <em>VStudio</em> (<em>2019</em> that you already have installed) paths. <br>A common way of doing that is invoking <em>vcvarsall.bat</em>: <code>&quot;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat&quot...
python|c++|tensorflow|cuda|cudnn
1
371,237
69,626,528
Element-wise operation with lambda (pd.DataFrame)
<p>Trying to subtract a constant array from a DatraFrame using lambda.</p> <p>This is my DataFrame <code>d</code>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd d = pd.DataFrame() d['x'] = pd.Series([1, 2, 3, 4, 5, 6]) d['y'] = pd.Series([11, 22, 33, 44, 55, 66]) </code></pre> <p>A working as...
<p>If number of columns is same like length of list simpliest is:</p> <pre><code>print(d + [5, 10]) x y 0 6 21 1 7 32 2 8 43 3 9 54 4 10 65 5 11 76 </code></pre> <p>If there is multiple columns select by list, lengths of lists has to be same:</p> <pre><code>print(d[['x','y']] + [5, 10]) </code></p...
python|pandas|dataframe|lambda|elementwise-operations
3
371,238
69,302,763
Difference between WGAN and WGAN-GP (Gradient Penalty)
<p>I just find that in the code here:</p> <p><a href="https://github.com/NUS-Tim/Pytorch-WGAN/tree/master/models" rel="nofollow noreferrer">https://github.com/NUS-Tim/Pytorch-WGAN/tree/master/models</a></p> <p>The &quot;generator&quot; loss, <code>G</code>, between WGAN and WGAN-GP is different, for WGAN:</p> <pre><cod...
<p>In order to Update D network: lossD = Expectation of D(fake data) - Expectation of D(real data) + gradient penalty lossD ↓,D(real data) ↑</p> <p>so you need to add minus one to the gradient process</p>
deep-learning|neural-network|pytorch|backpropagation|generative-adversarial-network
0
371,239
69,593,105
tf_agents doesn't properly learn a simple environment
<p>I successfully followed <a href="https://www.tensorflow.org/agents/tutorials/1_dqn_tutorial" rel="nofollow noreferrer">this official tensorflow tutorial</a> for training an agent to solve the 'CartPole-v0' gym environment. I only diverged from the tutorial in that I did not use <a href="https://pypi.org/project/reve...
<p>The cause of the issue was that the agent had no incentive to <em>quickly</em> solve the problem, because going to the right after 10 steps and after 3 steps both result in equal reward. Because the step counter was not observed, the agent could not possibly correlate taking too long with losing; so it would occasio...
python|tensorflow|reinforcement-learning|tensorflow-agents
0
371,240
69,579,293
What is an efficient way to replace all values of a matrix except for those in rows or columns which contain a specific value?
<p>I'm trying to replace all values of the input matrix <code>X</code> with <code>np.nan</code> except for the rows and columns which contain a value <code>v</code>:</p> <p><a href="https://i.stack.imgur.com/W66EJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W66EJ.png" alt="enter image description...
<p>Check row and column condition first and then combine them into a boolean condition taking advantage of <a href="https://numpy.org/doc/stable/user/basics.broadcasting.html" rel="nofollow noreferrer">numpy broadcasting</a>:</p> <pre><code>v = 2 eq_v = X == v has_v = eq_v.any(0) | eq_v.any(1, keepdims=True) # check ...
python|numpy
3
371,241
69,447,101
Create a new column with unique values from another in python Pandas - without grouping
<p>I already posted a question, but I presented it badly. Here my problem:</p> <p>I have a dataframe like that:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Col1</th> <th>Col2</th> <th>Col3</th> <th>Col4</th> <th>DESIRED COLUMN</th> </tr> </thead> <tbody> <tr> <td>SF</td> <td>123</td> <t...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code>...
python|pandas|dataframe|aggregate|transform
2
371,242
69,504,996
Strange result when subtracting two tensors
<p>I try to subtract two tensors and then convert every negative value to zero using relu function, but i cannot do that because when i subtract two tensors, tensorflow for some reason add 256 to every negative value !!</p> <pre><code>img = mpimg.imread('/home/moumenshobaky/tensorflow_files/virtualenv/archive/training/...
<p>I could make it work using <code>tf.keras.utils.img_to_array</code> to convert the image into a numpy array to avoid any unknown behaviour.</p> <p>I used <a href="https://storage.googleapis.com/kagglesdsdata/datasets/432700/821742/evaluation/Dessert/15.jpg?X-Goog-Algorithm=GOOG4-RSA-SHA256&amp;X-Goog-Credential=gcp-...
tensorflow|tensor
-1
371,243
69,615,486
Change the dimension of an array
<p>I have a number of images that have shapes (10,1134,1135). I am trying to change the shape to (10,1134,1134). I converted the image into NumPy and use the array. reshape but I get an error saying cannot reshape the array of size 12870900 into shape (10,1134,1134). Is there an alternate way to do this?</p>
<p>Since you need to shrink the size of your array you need a to drop a vector on some axis of data. There are a few ways to do this through slicing.</p> <p><strong>Example Array:</strong></p> <pre><code>arr = np.zeros((10,1134,1135)) np.shape(arr) #output (10, 1134, 1135) </code></pre> <hr /> <p><strong>Drop First:</...
python|numpy
0
371,244
69,414,590
Pandas: Mapping values between 2 dataframes by matching 2 columns values (composite key) to 1 column and the column labels/index of another dataframe
<p>Question sounds to have been asked before, but couldn't apply or understand solutions for my case, hence asking...<br /> I have a dataframe <code>Main</code> that looks like this with two columns <code>topic, cat</code> with new needed column <code>Value</code> that I want:</p> <pre><code>topic | cat | Value(...
<p>You can make a mapping from <code>Values_df</code> by melting <code>Values_df</code> by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>.melt()</code></a> and then set index on columns <code>topic</code> and <code>cat</code> by <a href="...
python|python-3.x|pandas|dataframe|dictionary
1
371,245
69,544,408
Numpy array: get the raw bytes without copying
<p>I am trying to concatenate the bytes of multiple Numpy arrays into a single <code>bytearray</code> to send it in an HTTP post request.</p> <p>The most efficient way of doing this, that I can think of, is to create a sufficiently large <code>bytearray</code> object and then write into it the bytes from all the numpy ...
<p>You can make a numpy-compatible buffer out of your message <a href="https://docs.python.org/3/library/functions.html#func-bytearray" rel="nofollow noreferrer"><code>bytearray</code></a> and write to that efficiently using <a href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html" rel="nofollow...
python|arrays|numpy|zero-copy|python-bytearray
2
371,246
69,378,519
Class that returns a transformed dataframe
<p>I'm trying to create a class that takes the path and name of the CSV file, converts it to a dataframe, deletes some columns, converts another one to datetime, as in the code</p> <pre><code>import os from pathlib import Path import pandas as pd import datetime class Plans: def __init__(self, file , path): ...
<p>Probably one of the columns you are trying to delete is not actually in your file. You can handle the exception or remove this column label from your array.</p>
python|pandas|function|class
1
371,247
69,585,416
TypeError: unhashable type: 'numpy.ndarray' when applying datetime
<p>I get unhashable TypeError: unhashable type: 'numpy.ndarray' when trying to apply to datetime. The problem is that when applying iloc x is no longer from type pd. so what should I do is this case?</p> <p>the column of X which is dates like 21/10/2020</p> <pre><code>from pandas import read_csv from matplotlib import ...
<p>according to documentation <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html</a></p> <p>Parameters</p> <pre><code>arg: int, float, str, datetime, list, tuple, 1-d a...
pandas|dataframe|numpy|datetime|hash
0
371,248
69,456,839
Python .loc returning a TypeError
<p>I'm new to using .loc , but every time I try to use it, it returns 'TypeError: 'DataFrame' object is not callable'.</p> <p>For example, I can't get this simple code (used on the pokemon API) to work:</p> <pre><code>print(df.loc(df('Attack') &gt; 175)) TypeError: 'DataFrame' object is not callable </code></pre> <p>...
<p>Indexing (both <code>iloc</code> and accessing column <code>Attack</code>) should be done with square bracket, not round bracket (as they are not functions)</p> <p>For instance</p> <pre><code> df.loc[df['Attack'] &gt; 175] </code></pre> <p>With <code>df('Attack')</code>, you are trying to call <code>df</code> object...
python|pandas|typeerror|.loc
2
371,249
69,457,906
Pandas: New column value based on the matching multi-level column's conditions
<p>I have the following dataframe with multi-level columns</p> <pre class="lang-py prettyprint-override"><code>In [1]: data = {('A', '10'):[1,3,0,1], ('A', '20'):[3,2,0,0], ('A', '30'):[0,0,3,0], ('B', '10'):[3,0,0,0], ('B', '20'):[0,5,0,0], ...
<p>Idea is replace <code>0</code> by <code>NaN</code>, so if use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> all rows with <code>NaN</code>s are removed. Then get indices by <a href="http://pandas.pydata.org/p...
python|pandas|pivot-table
1
371,250
69,522,044
How to speed up pandas dataframe iteration involving 2 different dataframes with a complex condition?
<p>I have a pandas dataframe A of approximately 300000 rows. Each row has a latitude and longitude value.</p> <p>I also have a second pandas dataframe B of about 10000 rows, which has an ID number, a maximum and minimum latitude, and a maximum and minimum longitude.</p> <p>For each row in A, I need the ID of the corres...
<p>I would use geopandas to do this, which makes use of rtree indexing.</p> <pre><code>import geopandas as gpd from shapely.geometry import box a_gdf = gpd.GeoDataFrame(a[['location']], geometry=gpd.points_from_xy(a.longitude, a.latitude)) b_gdf = g...
python|pandas
3
371,251
69,641,397
finding duplicates and adding ID as attribute pandas
<p>I'm working in geopandas with a large number (around 4.5 million) objects, where each has a unique ID number ('PARCEL_SPI') and also another code ('PC_PLANNO').</p> <p>What I would like to do is write some code that, for each object, finds all other objects with the same PLANNO and adds their ID number as a list in ...
<p>Here converting to list is not necessary - filter duplciated rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a> and for it use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas...
python|pandas|dataframe|geopandas
2
371,252
40,853,786
Sorting a table values based on index and non-indexed columns using python
<p>How can I sort values in a dataframe based on an index and non-indexed columns?</p> <p>Dataframe:</p> <pre><code>ID Colour A B C 45356 Green 1 34 4 34455 Yellow 23 0 1 53443 Brown 3 4 3 45555 Green 5 5 2 </code></pre> <p>Table has two index columns (ID and Colour). I will like t...
<p>you want</p> <pre><code>df.reset_index().sort_values( ['ID', 'A', 'C'], ascending=['True','False','True'] ).set_index(['ID', 'Colour']) </code></pre> <p><a href="https://i.stack.imgur.com/vkbfm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vkbfm.png" alt="enter image description here"></a></p>
python|pandas
5
371,253
40,974,743
Replace column values according to values of consecutive rows in pandas
<p>I have a dataframe <code>df_in</code> defined as so:</p> <pre><code>import pandas as pd dic_in = {'A':['aa','bb','cc','dd','ee','ff','gg','uu','xx','yy','zz'], 'B':['200','200','200','400','400','500','700','700','900','900','200'], 'C':['da','cs','fr','fs','se','at','yu','j5','31','ds','sz']} df_in =...
<p>You can compare by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ne.html" rel="nofollow noreferrer"><code>ne</code></a> shifted column and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a...
python|pandas|dataframe|replace|sequence
3
371,254
40,919,751
Python Pandas from dictionary
<p>I have a dictionary </p> <pre><code>x={'XYZ': [4, 5, 6], 'ABC': [1, 2, 3]} </code></pre> <p>I want a <code>pd.DataFrame</code> like this:</p> <pre><code> 'SomeColumnName' 'XYZ' [4,5,6] 'ABC' [1,2,3] </code></pre> <p>Whatever I do, it splits the list of x.values() in 3 separate columns. I could do a '~'.j...
<p>Why don't you just input the data as:</p> <pre><code>x={'XYZ': [[4, 5, 6]], 'ABC': [[1, 2, 3]]} </code></pre> <p>Then you get:</p> <pre><code>In [7]: pd.DataFrame(x).transpose() Out[7]: 0 ABC [1, 2, 3] XYZ [4, 5, 6] </code></pre> <p>You can recode your dictionary using:</p> <pre><code>for key in ...
python|pandas
1
371,255
40,973,037
Create and rename dataframes dynamically
<p>I'd like to run a list of dataframes through the renaming (and code) of df1 and df2. Can this be done by def ....etc., or any other method?</p> <pre><code>df = pd.DataFrame( { 'A': ['d','d','d','d','d','d','g','g','g','g','g','g','k','k','k','k','k','k'], 'B': [5,5,6,4,5,6,-6,7,7,6,-7,7,-8,7,-6,6,-7,50], '...
<p>I think you can use custom function:</p> <pre><code>def func(df): df = (df.B + df.C).groupby([df.A, df.S]).agg(['sum','size']).unstack(fill_value=0) df1 = df.groupby(level=0, axis=1).sum() new_cols= list(zip(df1.columns.get_level_values(0),['total'] * len(df.columns))) df1.columns = pd.MultiIndex.fr...
python|pandas
1
371,256
40,898,968
Tensorflow installation on windows 8 not working
<p>I was very happy to see tensorflow's windows support. I am following the instructions on <a href="https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html#pip-installation-on-windows" rel="nofollow noreferrer">this</a> link. The installation is successful, but while importing, it generates an error.<br/> ...
<p>This error message means that one or more of the DLLs that TensorFlow depends on is not available on your computer. Installing the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=53587" rel="nofollow noreferrer">Microsoft Visual C++ 2015 Redistributable Update 3 (x64 version)</a> should fix this pr...
python|tensorflow
2
371,257
41,128,397
Run SVM on IRIS DataSet and get ValueError: Unknown label type: 'unknown'
<p>Who can explain this in a simple way to me? I include the full code for your convenience.</p> <p>I have this code which loads IRIS dataset and runs SVM:</p> <pre><code>from sklearn import svm import pandas as pd def prepare_iris_DS(): print("Loading iris DS...") url = 'http://archive.ics.uci.edu/ml/machi...
<p>When: <code>Y = Y.as_matrix()</code>, observe the data type of the target array:</p> <pre><code>&gt;&gt;&gt; Y.dtype object </code></pre> <p>The <code>fit</code> method of <code>SVC</code> expects an array iterable of numerical values as it's training vector, <em>X</em>. But currently, you've passed an array of nu...
python|pandas|scikit-learn|dataset
2
371,258
41,143,698
How to apply value_counts to a grouped object
<p>I have table that looks like this:</p> <pre><code>userid purchase_date 1 2016-08-01 1 2016-08-02 2 2016-08-01 2 2016-08-01 3 2016-08-01 3 2016-08-02 3 2016-08-03 </code></pre> <p>I am keeping track of each user's purchase history (a user can purchase multiple times a day). Now, I...
<p>I think you need <code>groupby</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.idxmin.html" rel="nofollow noreferrer"><code>idxmin</code></a> for get <code>indices</code> of minimal values per group with selecting by <code>loc</code>:</p> <pre><code>pr...
python|pandas
0
371,259
41,082,455
Runge–Kutta of 4th order
<p>Lets consider I have a system of 4 ODE: dX/dt = F(X), where X is a vector(4-demension) and F: R^4 -> R^4. F is called vectorDE_total_function, and I'm trying to calculate the solution using RK-4.</p> <pre><code>def solvingDES(): previous_vector = np.array ([theta_1, omega_1, theta_2, omega_2]); for current_...
<p>It is a strange, seldom seen way to implement it and it only works for classical RK4, other Runge-Kutta methods would not work like that. But the general idea seems correct.</p> <p>You have a common error in an usually unexpected place. Setting</p> <pre><code>temp_vector = previous_vector; </code></pre> <p>and la...
python|numpy|numerical-methods|runge-kutta
1
371,260
40,917,742
Tensorflow: tf.get_collection Not Returning Variables in Scope
<p>I'm trying to get all the variables in a variable scope, as is explained <a href="https://stackoverflow.com/questions/36533723/tensorflow-get-all-variables-in-scope">here</a>. However, the line <code>tf.get_collection(tf.GraphKeys.VARIABLES, scope='my_scope')</code> is returning an empty list even though there are v...
<p>The <code>tf.GraphKeys.VARIABLES</code> collection name has been deprecated since TensorFlow 0.12. Using <code>tf.GraphKeys.GLOBAL_VARIABLES</code> will give the expected result:</p> <pre><code>with tf.variable_scope('my_scope'): a = tf.Variable(0) print tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='m...
python|tensorflow
11
371,261
41,045,871
How to fill numpy array with another numpy array
<p>I have an empty numpy array, and another one populated with values. I want to fill the empty numpy array with the populated one, x times. So, when x = 3, the (originally empty array) would look like <code>[[populated_array],[populated_array], [populated_array]]</code></p> <p>Where populated_array is the same value/...
<p><code>tile</code> and <code>repeat</code> are handy functions when you want to repeat an array in various ways:</p> <pre><code>In [233]: np.tile(np.array([4,6,6,1]),(3,1)) Out[233]: array([[4, 6, 6, 1], [4, 6, 6, 1], [4, 6, 6, 1]]) </code></pre> <p>On the failure, note the docs for <code>fill</code>...
python|arrays|numpy
10
371,262
40,985,420
Working with keys in Pandas Data Frame
<p>In R, Setkey can be used to work with keys and i.e. my data table gets sorted automatically when using aggregation functions. The R-Command I use is: setkey(myData, “Customer”)</p> <p>Does Python/Pandas also work with keys and Is there an equivalent for the R-Command? Thanks a lot.</p>
<p>R's data.table setkey() function, as far as I know, doesn't have a direct equivalent in Python. However, there are a few functions that replace this functionality. Note the <code>inplace</code> parameter for these functions. If you don't specify <code>inplace=True</code>, the underlying data is not changed unless yo...
r|pandas|key
1
371,263
40,813,813
How to annotate boxplot median, quartiles, and whiskers
<p>I have a pandas dataframe containing data on Facebook Posts broken down by "type of post." The dataframe is called "Posts_by_type" It contains the # of likes, # of shares, and the type of post. There are 3 types of post: Racing, Entertainment, and Promo.</p> <p>I want to create a boxplot in matplotlib showing th...
<p>A solution that also adds the values for the boxes.</p> <pre><code>import random import string import matplotlib.pyplot as plt import pandas as pd import numpy as np def get_x_tick_labels(df, grouped_by): tmp = df.groupby([grouped_by]).size() return ["{0}: {1}".format(k,v) for k, v in tmp.to_dict().items()...
python|pandas|matplotlib|seaborn|boxplot
11
371,264
41,108,834
How can I use sklearn CountVectorizer with mutliple strings?
<p>I have a list of strings (10,000s). Some of the strings constitute multiple words. I have another list which contains some sentences. I am trying to do a count of the number of times each string in my list appears in each sentence. </p> <p>At present I am using sklearn's feature extraction tool, because it works ve...
<p>I managed to solve this by playing with the n-grams parameter in the CountVectorizer. </p> <p>If I am able to find the largest number of words a single string in my wordlist I can set this as the upper limit to my n-gram. In the example above it is "brown cow" with two.</p> <pre><code>cv = feature_extraction.text....
python|numpy|scikit-learn|nltk
3
371,265
41,096,585
Construct matrix object from list of data (separated by empty line)
<p>I have a file which has scientific data expressed in scientific notation. The format is following where always bunch of 6 rows of numbers appear together,</p> <pre><code> 4.748257444721457E-004 -4.058788876602824E-006 -1.494658656964534E-004 4.686186383664201E-006 3.840708360798801E-006 ...
<p>It may help you.</p> <pre><code>import numpy as np matrix = [] row = [] with open("input.txt") as f: for line in f: line = line.rstrip('\n') if not line: if len(row) != 0: matrix.append(row) row = [] continue row.append(float(line)) i...
python|python-3.x|numpy
1
371,266
40,879,564
Dask dataframe has no attribute '_meta_nonempty' while merging large CSVs in Python
<p>I tried Pandas with:</p> <pre><code>import pandas as pd df1 = pd.read_csv("csv1.csv") df2 = pd.read_csv("csv2.csv") my_keys = ["my_id", "my_subid"] joined_df = pd.merge(df1, df1, on=my_keys) joined_df.to_csv('out_df.csv', index=False) </code></pre> <p>And got a memory error after some grinding. </p> <p>Next I tri...
<p>Followup: dumping to Postgres was pretty painless though dataframes still seem cleaner to me. </p> <pre><code>import pandas as pd from sqlalchemy import create_engine df1 = pd.read_csv("csv1.csv") df2 = pd.read_csv("csv2.csv") engine = create_engine('postgresql://user:passwd@localhost:5432/mydb') df1.to_sql('tabl...
python|pandas|dask
1
371,267
41,039,609
Convert matlab method to python
<p>There is very helpful method in matlab called "getwb()". For developers that coding neural network, this method returns the weights and biases at the final iteration. I have neural network (using tensorflow tools). There is possible to convert this method in some way? </p> <p>I tried alot with tensorFlow.saver() a...
<p>In your code you create a bunch of variables for weights and biases of hidden and output layers. You should be able to retrieve them at any moment (when a session is active) by using tf.Session.run() like follows:</p> <pre><code>import tensorflow as tf tf.reset_default_graph() v = tf.Variable(tf.random_normal((5,...
python|matlab|machine-learning|tensorflow
0
371,268
40,789,383
Python: Split CSV file according to first character of the first column
<p>I have a series of large CSV files "basename.csv" like:</p> <p>B1,3,5,6</p> <p>B2,2,1,5</p> <p>B3,1,9,0</p> <p>C1,4,7,9</p> <p>C2,1,9,3</p> <p>C3,8,5,2</p> <p>I would like to split them into different files like:</p> <p>basename_B.csv</p> <p>B1,3,5,6</p> <p>B2,2,1,5</p> <p>B3,1,9,0</p> <p>basename_C.csv<...
<p>Here's a simple application of <code>groupby</code>:</p> <pre><code>df = pandas.read_csv('basename.csv', header=None) def firstletter(index): firstentry = df.ix[index, 0] return firstentry[0] for letter, group in df.groupby(firstletter): group.to_csv('basename_{}.csv'.format(letter)) </code></pre> <p...
python|csv|pandas|split|multiple-columns
3
371,269
41,198,150
pass multiple dataframes through a function simultaneously
<p>How to pass df10 and df20 (and even more dataframes) through func simultaneously and keep their names for further use?</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame( { 'A': ['d','d','d','d','d','d','g','g','g','g','g','g','k','k','k','k','k','k'], 'B': [5,5,6,4,5,6,-6,7,7,6,-7,7,-8,...
<p>Edit: There is probably a much better way to do this; I just thought I would offer this suggestion. If it is not as required, please let me know, and I will delete.</p> <blockquote> <p>How to pass df10 and df20 (and even more dataframes) through func simultaneously and keep their names for further use?</p> </bloc...
python|pandas
7
371,270
41,024,404
Python Pandas - largest change in population within the five year period
<p>I have this table: <a href="https://i.stack.imgur.com/RZ0uG.jpg" rel="nofollow noreferrer">table_sensus</a></p> <p>And I would like to retrieve which county has had the largest change in population within the five year period, how?</p> <p>Thank you</p>
<p>Use <code>.argmax()</code> to get the biggest census and <code>.ix[]</code> to get the element by the index. After that you just have to select the column</p> <pre><code>&gt;&gt;&gt; d = {'census' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),'county' : pd.Series(['z','x','w','y'], index=['a', 'b', 'c', 'd'])} &...
python|pandas
0
371,271
40,932,215
Error while using a newer version of glibc
<p>I am trying to install tensorflow on a linux server where I am just a user without the root permission. And I cannot transfer files to/from it as I ssh to it through a jump server. The system is as following :</p> <p><code>Linux THENAME_OF_SURVER 2.6.32-573.18.1.el6.x86_64 #1 SMP Tue Feb 9 22:46:17 UTC 2016 x86_64 ...
<blockquote> <p><code>export LD_LIBRARY_PATH=/home/MYNAME/dependency/glibc-2.16/lib</code></p> </blockquote> <p><a href="https://stackoverflow.com/a/8658468/50617">This answer</a> explains why <code>LD_LIBRARY_PATH</code> doesn't work, and what you should do instead.</p> <blockquote> <p>I read your post and tried...
linux|linker|tensorflow|glibc
11
371,272
41,210,198
Replacing specific characters in string in python
<p>I have a file which contains a list of string. Here is the file:</p> <pre><code>['Alabama', 'Auburn (Auburn University)[1]', 'Florence (University of North Alabama)', 'Jacksonville (Jacksonville State University)[2]', 'Livingston (University of West Alabama)[2]', 'Montevallo (University of Montevallo)[2]', 'Troy (T...
<p>Try this (replace <code>data.txt</code> with your file path):</p> <pre><code>with open('data.txt', 'r') as data_file: data = data_file.read() raw_elements = data.replace('\n', '').strip('[]').split(',') elements = map((lambda item: item.strip("'").split(' ')[0]), raw_elements) print elements </code>...
python|string|pandas
1
371,273
40,818,987
Numpy: Code independent of dimensionality of array
<p>I have a function that takes a numpy array. I know it to be either of shape (1,C), or (R,C)</p> <p>What I need is to divide every entry by the sum of its according column. I read <a href="https://stackoverflow.com/questions/19602187/numpy-divide-each-row-by-a-vector-element#_=_">this question</a>, and the accepted a...
<p>Are you looking for <code>x / np.sum(x, axis=0)</code>? <code>[None,:]</code> has no useful effect here, and only serves to throw an error in the 1D case.</p>
python|arrays|numpy|dimensions
0
371,274
40,924,592
Python dictionary comprehension with Pandas
<p>I am trying to create a dictionary from two columns of a DataFrame (df)</p> <pre><code>mydict={x :y for x in df['Names'] for y in df['Births']} </code></pre> <p>But all of the values are the same(the last value in the column)!</p> <pre><code>{'Bob': 973, 'Jessica': 973, 'John': 973, 'Mary': 973, 'Mel': 973} </cod...
<p>I think Abdou hit the nail on the head with <code>dict(zip(dff['Names'], dff['Births']))</code>, but if you want to do it with a dict comprehension you can do this:</p> <pre><code> In [1]: import pandas as pd In [2]: df = pd.DataFrame( ...: [{'Births': 971, 'Names': 'Bob'}, ...: {'Births': 97...
python|pandas|dictionary|dict-comprehension
2
371,275
41,223,186
NumPy vectorization with integration
<p>I have a vector <img src="https://i.stack.imgur.com/50nLA.gif" alt="enter image description here"> and wish to make another vector of the same length whose k-th component is</p> <p><a href="https://i.stack.imgur.com/CV6iG.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CV6iG.gif" alt="enter image...
<p>The function <code>quad</code> executes an <em>adaptive</em> algorithm, which means the computations it performs depend on the specific thing being integrated. This cannot be vectorized in principle. </p> <p>In your case, a <code>for</code> loop of length 10 is a non-issue. If the program takes long, it's because ...
numpy|vectorization|quad
11
371,276
41,228,697
pandas to_csv: ascii can't encode character
<p>I'm trying to read and write a dataframe to a pipe-delimited file. Some of the characters are non-Roman letters (`, ç, ñ, etc.). But it breaks when I try to write out the accents as ASCII.</p> <pre><code>df = pd.read_csv('filename.txt',sep='|', encoding='utf-8') &lt;do stuff&gt; newdf.to_csv('output.txt', sep='|', ...
<p>Check the answer <a href="https://stackoverflow.com/questions/33058835/encoding-error-using-df-to-csv">here</a></p> <p>It's a much simpler solution:</p> <pre><code>newdf.to_csv('filename.csv', encoding='utf-8') </code></pre>
python|pandas|unicode|utf-8
71
371,277
41,220,617
Python 3D interpolation speedup
<p>I have following code used to interpolate 3D volume data.</p> <pre><code>Y, X, Z = np.shape(volume) xs = np.arange(0, X) ys = np.arange(0, Y) zs = np.arange(0, Z) points = list(zip(np.ravel(result[:, :, :, 1]), np.ravel(result[:, :, :, 0]), np.ravel(result[:, :, :, 2]))) interp = interpolate.RegularGridInterpolato...
<p>Here is slightly modified version of your <code>cython</code> solution:</p> <pre><code>import numpy as np cimport numpy as np from libc.math cimport floor from cython cimport boundscheck, wraparound, nonecheck, cdivision DTYPE = np.float ctypedef np.float_t DTYPE_t @boundscheck(False) @wraparound(False) @nonechec...
python|performance|numpy|interpolation|cython
4
371,278
40,839,101
Adding comma separators to a string in a Dataframe Column with pandas
<p><a href="https://i.stack.imgur.com/EEM4l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EEM4l.png" alt="Top15.head()"></a></p> <p>I am trying to add comma separators to indicate thousands to my string to a column in a dataframe. Can someone help with format? I do not understand how to do this to...
<p>I think what you are looking for is this:</p> <pre><code>Top15["PopEst"] = Top15["PopEst"].map(lambda x: "{:,}".format(x)) </code></pre> <p>The <code>"{:,}".format()</code> would work as a thousand separator for a single <code>string</code>/<code>float</code>/<code>int</code>, so you can use <code>map()</code> to ...
regex|pandas
4
371,279
40,913,944
Using python to add random Matrices with Numpy
<p>So I need to add random matrices in python. I have this code to generate a random matrix:</p> <pre><code>import numpy as np import random def generate_matrix(m, n): A = np.random.randint(100, size=(m, n)) B = np.random.randint(100, size=(m, n)) return A </code></pre> <p>However, I need to create a function...
<p><code>def generate_matrix(m, n):<br> A = np.random.randint(100, size=(m, n))<br> B = np.random.randint(100, size=(m, n))<br> return A + B</code><br> This is what I have but my formatting is wrong, and it only adds identical length matrices. </p>
python|arrays|numpy|matrix|random
0
371,280
41,157,645
Tensorflow Tensorboard on Windows shows a blank page
<p>I'm using Tensorflow on Windows but when I try to launch Tensorboard opening <code>http://localhost:6006</code> the browser shows a blank page</p> <p>I have added the codeline <code>writer = tf.train.SummaryWriter('mypath/my_graph', sess.graph)</code></p> <p>to my Tensorflow model and launched tensorboard with <co...
<p>The <code>0.12.0rc0</code> (Release Candidate 0) release of TensorFlow on Windows contains a broken version of TensorBoard. We recently made a new release (<code>0.12.0rc1</code>, Release Candidate 1) that contains a fix for TensorBoard on Windows. You can upgrade by following the <a href="https://www.tensorflow.org...
tensorflow|spyder|tensorboard
2
371,281
41,102,645
For every point in an array, find the closest point to it in a second array and output that index
<p>If I have two arrays:</p> <pre><code>X = np.random.rand(10000,2) Y = np.random.rand(10000,2) </code></pre> <p>How can I, for each point in X, find out which point in Y is closest to it? So that in the end I have an array showing:</p> <pre><code>x1_index y_index_of_closest 1 7 2 ...
<p>This question is pretty popular. Since similar questions keep getting closed and linked here, I think it's worth pointing out that even though the existing answers are quite fast for thousands of data points, they start to break down after that. My potato segfaults at 10k items in each array.</p> <p>The potential p...
python|arrays|numpy|enumerate
4
371,282
41,225,286
sort_by broken in pandas >= 0.18.0?
<p>I start with a data frame like</p> <pre><code>print(df) int float _i 1 2 2.000000e+00 1 3 3 3.000000e+00 3 2 3 4.000000e+00 2 4 -9223372036854775808 -1.797693e+308 4 0 -9223372036854775808 1.000000e+00 0 </code><...
<p>Recent pandas versions don't show this bug anymore, was fixed a while ago: <a href="https://github.com/pandas-dev/pandas/commit/6bea8275e504a594ac4fee71b5c941fb520c8b1a" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/commit/6bea8275e504a594ac4fee71b5c941fb520c8b1a</a></p>
python|pandas
0
371,283
54,169,217
Cut-off half a torus in a surface plot
<p>I am trying to plot only half of a torus using <code>matplotlib</code>.</p> <p>This is my approach so far:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D n = 100 # theta: poloidal angle; phi: toroidal angle theta = np.linspace(0, 2.*np.pi, n) phi = np....
<p>Cutting off surfaces with <code>nan</code>s will usually do that. This is due to the fact that patches of the surface are drawn using linear interpolation over a subset of the input data, and having <code>nan</code>s on the boundary will lead to <code>nan</code> results for values for some edge patches.</p> <p>In y...
python|numpy|matplotlib|3d
2
371,284
54,081,222
Change the time column precision
<p>Here we have a dataframe with <code>Pandas</code>. I am struggling to round the time precision.</p> <pre><code> Title 1 Title 2 Title 3 Title 4 ... midprice t0 t1 tEvent 2015-07-15 09:30:00+00:00 2673...
<p>You can round and then trim and convert back to datetime</p> <pre><code>df.index = df.index.round('ms').strftime('%Y-%m-%d %H:%M:%S.%f').str[:22] df.index = pd.to_datetime(df.index) Title 1 Title 2 Title 3 Title 4 2015-07-15 09:30:00.00 26730 26844 26851 26870 2015-07-15 09:30:00.50...
python|pandas|time
1
371,285
54,053,344
How do I convert points column values in rank order in Python Pandas
<p>I have a Pandas dataframe like this:</p> <pre><code>id1 id2 Points 1 1a 0.34 1 1a 0.34 1 2a 0.23 1 3a 0.71 2 73a 0.52 2 43a 0.2 2 43a 0.2 2 34a 0.83 3 23a ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.rank.html" rel="nofollow noreferrer"><code>GroupBy.rank</code></a> with parameters <code>dense</code> and <code>ascending=False</code>:</p> <pre><code>df['new'] = df.groupby('id1')['Points'].rank('dense', ascending=False)...
python|pandas
2
371,286
54,145,650
Pandas: add a column to a categorical dataframe
<p>My raw data looks like: </p> <pre><code>Bin A B C CPB% 0.00000 0 57 1728 0.00100 0 1579 1240 0.00200 1360 488 869 0.00300 184 499 597 0.00400 265 283 461 </code></pre> <p>I obtained it thanks to that code:</p> <pre><code>import operator bins = np...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.CategoricalIndex.add_categories.html" rel="nofollow noreferrer"><code>CategoricalIndex.add_categories</code></a> for add new category by new column name(s):</p> <pre><code>df_b.columns = df_b.columns.add_categories('Proba-b') df_b['Proba...
python|pandas
2
371,287
54,053,857
tensorflow.python.framework.errors_impl.OutOfRangeError: RandomShuffleQueue
<p>I'm reading batch of images from tfrecords. When I use this, my code is right.</p> <pre><code>image_ori, image_human, image_human_size, center, fname, pose, shape, gt2d, gt3d, seg = data_utils.parse_example_proto(example_serialized) image = tf.image.resize_images(seg, (224, 224), method=0) </code></pre> <p>Bu...
<p>I have soved this question. The value 'gt2d' need to be dealed, because some value is negative which lead to a mismatching crop image size.</p>
python|tensorflow
0
371,288
53,856,124
keras custom loss number of classification errors
<p>I'm using keras with the tensorflow backend and trying to write a custom loss function which simply counts the number of incorrect classification predictions. Here is my attempt:</p> <pre><code>def error_count_loss(yTrue, yPred): """Sum and return the number of incorrect predictions. Parameters ------...
<p>You can try to write something close to that using other functions, which have gradients, for example:</p> <pre><code>def error_count_loss(yTrue, yPred): return K.sum(K.abs(K.sign(yTrue) - K.sign(yFalse))) </code></pre> <p>But it's not the best loss function for training. Try looking at <a href="https://www.te...
python|tensorflow|keras
1
371,289
54,004,330
False positives in faster-rcnn object detection
<p>I'm training an object detector using tensorflow and the <code>faster_rcnn_inception_v2_coco</code> model and am experiencing a lot of false positives when classifying on a video.</p> <p>After some research I've figured out that I need to add negative images to the training process.</p> <p>How do I add these to <c...
<p>I was facing the same issue with faster RCNN, although you <strong>cannot</strong> actually <strong>use hard_example_miner</strong> with the <strong>faster RCNN</strong> model, you can add some <strong>background images</strong>, ie. images with no objects (Everything remains the same, except there is not object tag...
tensorflow|deep-learning|object-detection
5
371,290
53,814,261
Tensorflow C++ set GPU memory fraction and allow growth
<p>I want to set the <code>GPU memory fraction</code> and <code>allow growth</code> options as described <a href="https://www.tensorflow.org/guide/using_gpu#allowing_gpu_memory_growth" rel="nofollow noreferrer">here</a> for python, but in C++. Is this the correct way of doing this? I am especially not sure about the <c...
<p>I had to do exactly the same and this is how I do it in my project:</p> <pre><code>auto options = tensorflow::SessionOptions(); options.config.mutable_gpu_options()-&gt;set_per_process_gpu_memory_fraction(0.2); options.config.mutable_gpu_options()-&gt;set_allow_growth(true); tensorflow::Status status = tensorflow::...
c++|tensorflow|gpu
7
371,291
54,171,216
How to set and group pandas multi-level columns?
<p>I have a dataframe that has the shape like this:</p> <pre><code> PX_LAST PX_OPEN PX_CLOSE ticker source timestamp 0 1 2 3 A LSE 20180101 1 4 5 6 A LSE 20180102 1 7 8 9 B LSE 20180101 1 10 11 12 B LSE 2...
<p>One option is <code>melt</code>, <code>set_index</code> and <code>unstack</code>:</p> <pre><code>u = df.melt(['ticker', 'source', 'timestamp']) (u.set_index(u.columns.difference({'value'}).tolist())['value'] .unstack([1, 0, -1]) .sort_index(axis=1)) ticker A B s...
python|pandas|dataframe|pivot|pivot-table
3
371,292
54,117,962
UnpicklingError: invalid load key, '\x0a'
<pre><code>model_save_name = 'classifier.pt' path = F"/content/gdrive/My Drive/Others/{model_save_name}" model.load_state_dict(torch.load(path), strict = False) </code></pre> <p><em>trying to load into model state_dict from path. Later the same model state_dict will be used for saving the checkpoint like <code>torch....
<p>Is the model saved using the same python version as the one trying to load. If not there have been some changes in pickle across versions. Also if this is not the case can you also post the torch.save() call you are making.</p>
python-3.x|neural-network|pytorch
-1
371,293
54,105,398
Insert Blank Row In Python Data frame when value in column changes?
<p>I have a dataframe and I'd like to insert a blank row as a separator whenever the value in the first column changes.</p> <p>For example:</p> <pre><code>Column 1 Col2 Col3 Col4 A s b d A s j k A b d q B b a d C ...
<p>Create helper <code>DataFrame</code> with index values of last changes, add <code>.5</code>, join together with original by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>concat</code></a>, sorting indices by <a href="http://pandas.pydata.org/pandas-docs/sta...
python|pandas
10
371,294
54,129,098
Getting wrong prediction after loading a saved model
<p>I am trying to save an <code>Estimator</code> and then load it to predict as required. Part where I train the model:</p> <pre><code>classifier = tf.estimator.Estimator(model_fn=bag_of_words_model) # Train train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"words": x_train}, # x_train is 2D numpy array of...
<p>Finally, I got the answer. The model was saved and loaded correctly. The problem was that the <code>x_test</code> which I was passing to the prediction with saving/loading and without saving/loading was different (I know, I am really sorry for this mistake). The <code>x_test</code> w/o saving/loading the model had v...
python|tensorflow
3
371,295
54,032,486
Error when checking target: expected to have shape (256, 256, 1) but got array with shape (256, 256, 3)
<p>I'm trying to make <code>image2image</code> translation and my dataset is composed of Mnist(256<em>256) and transformed Mnist(256</em>256)</p> <p>I am literally suffering from this error:</p> <pre><code>ValueError: Error when checking target: expected conv2d_transpose_57 to have shape (256, 256, 1) but got array wit...
<p>MNIST data is grayscale, which means it has a shape of <code>(h,w,1)</code> you have set <code>PIL</code> to convert the data to <code>RGB</code> which has three colour dimensions <code>(h,w,3)</code>, the problem is with this line : </p> <pre class="lang-py prettyprint-override"><code>input_image = input_image.con...
python|tensorflow|keras
1
371,296
53,981,485
Pytorch: How does SGD with momentum works when optimizer has to call zero_grad() to help accumulation of gradients?
<p>In pytorch, the backward() function accumulates gradients and we have to reset it every mini-batch by calling optimizer.zero_grad(). In this case, how does the SGD with momentum works when actually momentum SGD updates the weights using exponential average of some past mini-batches. </p> <p>For a beginner in Pytorc...
<p>When using momentum you need to store a one-element history for each parameter, other solvers (e.g. ADAM) requires even more. The optimizer knows how to store this history data and accumuate new gradients in an orderly fashion. You do not have to worry about it.</p> <p>So why <code>zero_grad()</code>, you probably ...
machine-learning|deep-learning|pytorch|gradient-descent
2
371,297
53,884,698
Logging long tensor values in tensorflow estimator
<p>I have built a classification model using tensorflow estimator API. I am trying to get tensor outputs from hidden layes printed in logs while prediction using below code.</p> <pre><code>model = tf.estimator.DNNLinearCombinedClassifier( model_dir=model_dir, linear_feature_columns=wide_columns, ...
<p>So interesting, I found that the solution was to set <code>np.set_printoptions</code>.</p> <pre><code>import numpy as np np.set_printoptions(threshold=np.nan) </code></pre> <p>It seems that <code>tensorflow</code> and <code>numpy</code> are closely integrated.</p>
python|tensorflow|logging|tensorflow-estimator
1
371,298
53,965,588
Including TensorBoard as a callback in Keras model fitting causes a FailedPreconditionError
<p>Including tensorboard as callbacks in this code outputs an error:-</p> <pre><code>window_sizes=[3,5] conv_layers=[1,2] dense_layers=[1] for ws in window_sizes: for cl in conv_layers: for dl in dense_layers: name="{}-conv_layers-{}-window_size-{}-dense_layers-{}".format(cl,ws,dl,int(time.time...
<p>Using this</p> <pre><code>from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten,Conv2D, MaxPooling2D,Activation </code></pre> <p>instead of </p> <pre><code>from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten,Conv2D, MaxPooling2D...
python|python-3.x|tensorflow|keras|tensorboard
0
371,299
54,110,395
MetPy Matching GOES16 Reflectance Brightness
<p>I am having an issue with matching up the color table/brightness on CMI01 through CMI06 when creating GOES16 imagery with MetPy. I've tried using stock color tables and using random vmin/vmax to try and get a match. I've also tried using custom made color tables and even tried integrating things like min_reflectance...
<p>So your problem is, I believe, because there's a non-linear transformation being applied to the data on College of DuPage, in this case a square root (<code>sqrt</code>). This has been applied to GOES imagery in the past, as mentioned in the <a href="https://www.star.nesdis.noaa.gov/goesr/docs/ATBD/Imagery.pdf" rel=...
python|numpy|matplotlib|metpy
1