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 |
|---|---|---|---|---|---|---|
19,300 | 20,631,110 | Working with dates in pandas | <p>I have been collecting Twitter data for a couple of days now and, among other things, I need to analyze how content propagates. I created a list of timestamps when users were interested in content and imported twitter timestamps in pandas df with the column name 'timestamps'. It looks like this:</p>
<pre><code>0 ... | <p>That's ISO date format, it can be easily converted to datetime with <code>pd.to_datetime</code>:</p>
<pre><code>>>> df[:2]
timestamp
0 Sat Dec 14 05:13:28 +0000 2013
1 Sat Dec 14 05:21:12 +0000 2013
>>> df['timestamp'] = pd.to_datetime(df['timestamp'])
>>> df[:2... | python|pandas | 0 |
19,301 | 20,712,801 | Python where's the data | <p>Trying to find the data.</p>
<pre><code>import pandas as pd
import numpy as np
import urllib
url = 'http://cawcr.gov.au/staff/mwheeler/maproom/RMM/RMM1RMM2.74toRealtime.txt'
urllib.urlretrieve(url,'datafile.txt')
df = pd.read_table('datafile.txt', sep='\s+', header=None)
df.columns = ['year', 'month', 'day', 'n1'... | <p>You should skip the first two rows explicitly (it's confusing this isn't required on python 3):</p>
<pre><code>df = pd.read_csv('datafile.txt', sep='\s+', header=None, skiprows=2)
</code></pre> | python|pandas | 0 |
19,302 | 66,469,278 | Broadcasting error in constructing numpy array using a loop | <p>I'm trying to construct a matrix using the following loop:</p>
<pre><code>import numpy as np
def F_data(x, order):
X_F = np.zeros((len(x),order))
for i in range(order):
if i == 0:
X_F[:,i] = 1
if i % 2 != 0:
X_F[:,i] = np.sin(np.pi*x*i)
else:
X_F[:,i] = np.cos(np.pi*x*i)
return X_F
</... | <p>I also tried your code. It worked fine for me. you just need to upgrade numpy package.</p>
<ul>
<li>pip install numpy --upgrade use this command to upgrade numpy.</li>
</ul> | python|numpy | 0 |
19,303 | 66,372,010 | Is there a pandas method to find the 4th 5-quantile of a dataset? | <p>I was recently trying to solve a data science test. Part of the test was to get the number of observations in a dataset for which the variable X is less than the 4th 5-quantile of this variable X.
I don't realy understand what they meant by the 4th 5-quantile! I tried using pandas df.quantile function but I wasn't a... | <p>4th 5-quantile translates <code>value = data.quantile(4/5)</code></p> | python|pandas|dataframe|statistics|data-science | 0 |
19,304 | 66,713,761 | How to join two tensors | <p>I have two tensors of dimension [3,1]. I need to join them as a [3,2] tensor.</p>
<pre><code>t = torch.tensor([[3.],[1],[2]], requires_grad=True)
x = torch.tensor([[1.],[4],[5]], requires_grad=True)
</code></pre>
<p>I tried <code>torch.cat</code> and <code>torch.stack</code> but neither work for me.</p> | <p>With <code>cat</code> you need to specify the dimension the tensors are concatenated along. By default this is <code>0</code>, but you wish to use <code>1</code>:</p>
<pre><code>import torch
res = torch.cat([t,x], axis=1)
</code></pre> | python|pytorch|concatenation | 1 |
19,305 | 16,399,418 | Python, numpy, string decomposition (string from Abaqus AFXComTableKeyword.getValues()) | <p>From the <code>getValues()</code>method the <code>AFXComTableKeyword</code> class returns a string like:</p>
<pre><code>test = "('mat_huehne_2008', '0.125', '24.0'),('', '', '-24.0'),('', '', '41.0')"+\
",('', '', '-41.0'),('', '', ''),('', '', ''),('', '', ''),('','', ''),"+\
"('', '', ''),('', '', '... | <p>I'd use <code>ast</code> to eval the string into tuples. then it's easy:</p>
<pre><code>>>> import ast
>>> import numpy as np
>>> np.array(ast.literal_eval(test))
array([['mat_huehne_2008', '0.125', '24.0'],
['', '', '-24.0'],
['', '', '41.0'],
['', '', '-41.0'],
... | python|string|numpy | 3 |
19,306 | 16,181,307 | how to easily work out the 'valid' region for np.convolve | <p>Silly question - but is there a numpy function that returns the 'shape' of the convolve function when it is working in 'valid' mode.</p>
<p>Basically I have an issue working out which 'x' values match which y ones - and comparing it with the original data?</p>
<p>ie</p>
<pre><code>import numpy as np
x= np.arange... | <p>It should be <code>y.shape - window.shape + 1</code></p> | python|numpy | 1 |
19,307 | 16,296,028 | tensor dot operation in python | <p>I have two arrays <code>A=[1,2,3]</code> and <code>B=[[1],[0],[1],[0]]</code>. The question how to perform their tensor dot product in python. I am expecting to get:</p>
<pre><code>C=[[1,2,3],
[0,0,0],
[1,2,3],
[0,0,0]]
</code></pre>
<p>The function np.tensordot() returns an error concerning shapes of arr... | <p>Try using correct <code>numpy</code> arrays:</p>
<pre><code>>>> array([[1],[2],[3]]).dot(array([[1,0,1,0]]))
array([[1, 0, 1, 0],
[2, 0, 2, 0],
[3, 0, 3, 0]])
</code></pre>
<p>If your alignment is different, using <code>a.transpose()</code> can flip it:</p>
<pre><code>>>> array([[1... | python|matrix|numpy | 6 |
19,308 | 57,306,049 | Pandas read_csv usecols and names not working properly | <p>I am reading a csv file in pandas without headers. My problem is that when i hard code values in usecols and names it works fine. But when i take input from cols and names list which are taken as input from json files, the column names and rows are mismatched. I'm really struck at this issue from a long time.</p>
<p... | <pre><code>import pandas as pd
fields = ['a', 'b','c']
#always use `skipinitialspace` which remove the spaces in the header for reading specific columns
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
</code></pre>
<p>EDIT:</p>
<p>You are doing it in a wrong way usecols as <code>[2,3,1]</code> and... | python|pandas | 4 |
19,309 | 57,564,140 | How to get the 'create' script from a pandas dataframe? | <p>I have a pandas dataframe df. And lets say I wanted to share df with you guys here to allow you to easily recreate df in your own notebook.</p>
<p>Is there a command or function that will generate the pandas dataframe create statement? I realize that for a lot of data the statement would be quite large seeing that... | <p>We usually using <code>read_clipboard</code></p>
<pre><code>pd.read_clipboard()
Out[328]:
col1 col2
0 1 3
1 2 4
</code></pre>
<p>Or If you have the df save it into dict so that we can easily convert it back to the sample we need</p>
<pre><code>df.head(5).to_dict()
</code></pre> | python|pandas|dataframe | 3 |
19,310 | 57,312,134 | How to write in merged cell in Excel using `openpyxl` library? | <p>I am using <code>openpyxl</code> library to write in existing Excel file in separate cells. </p>
<p><strong>How do I write some text in Excel merged cell?</strong> </p>
<p><strong>ERROR</strong> <code>AttributeError: 'MergedCell' object attribute 'value' is read-only</code> </p>
<p>when cells are merged:</p>
<p>... | <p>Use the following code where ws is the sheet object.</p>
<pre><code> ws.cell(cells).value = 'Whatever you want it to be'
</code></pre>
<p>replace cells with the top-left cell of the merged block. I usually keep this as rows and columns. So B1 would be represented as row = 1, column = 2.</p>
<p>After the value ... | python|excel|pandas|for-loop|openpyxl | 1 |
19,311 | 24,080,651 | Convert Numpy array into Orange table of discrete values | <p>My problem is exactly what the title says: I have a numpy array of integers and wish to convert it into an Orange table with discrete values. If I follow these steps, it fails:</p>
<pre><code>import numpy as np
import Orange
a = np.arange(100).reshape((10,10)).astype(np.int8)
fields = ('one', 'two', 'three', 'four'... | <p>You can mmap your array to a file and then have orange read your mmap'ed file. Alternatively you may have some luck converting your np array to a python array and then reading that from orange.</p> | python|arrays|numpy|orange | 0 |
19,312 | 43,851,735 | Understanding input/output dimensions of neural networks | <p>Let's take a fully-connected neural network with one hidden layer as an example. The input layer consists of <strong>5 units</strong> that are each connected to all hidden neurons. In total there are <strong>10 hidden neurons</strong>.</p>
<p>Libraries such as Theano and Tensorflow allow <em>multidimensional input/... | <p>Yes, we just have a bunch of neurons throuhg which single numbers flow.</p>
<p>But: if you must give your network 5 numbers as input, it's then convenient to give these numbers in an array with length 5.</p>
<p>And if you're giving 30 thousand examples for your network to train, then it's convenient to create an arr... | tensorflow|neural-network|keras | 13 |
19,313 | 43,611,446 | Remove index from dataframe before converting to json with split orientation | <p>I am outputting a pandas dataframe to a json object using the following:</p>
<pre><code>df_as_json = df.to_json(orient='split')
</code></pre>
<p>In the json object superfluous indexes are stored. I do no want to include these.</p>
<p>To remove them I tried</p>
<pre><code>df_no_index = df.to_json(orient='records'... | <ul>
<li>import json module</li>
<li>Convert to <code>json</code> with <code>to_json(orient='split')</code></li>
<li>Use the <code>json</code> module to load that string to a dictionary</li>
<li>Delete the <code>index</code> key with <code>del json_dict['index']</code></li>
<li>Convert the dictionary back to <code>json... | python|json|pandas|dataframe | 8 |
19,314 | 1,636,929 | pythoncomplete in vim - hardcode factory function returns? | <p>I'm using pythoncomplete omnicompletion in vim.
It works great when I instantiate classes directly, eg</p>
<pre><code>import numpy as np
x = np.ndarray(l)
</code></pre>
<p>then x attributes complete correctly.</p>
<p>But I work with numpy and matplotlib so usually use factory functions ie </p>
<pre><code>x = np... | <p>Try <a href="https://github.com/davidhalter/jedi-vim" rel="nofollow">jedi-vim</a>.</p>
<p>There's an open issue for the problem you're facing. I think there's a good chance that it will be fixed in 3-4 months time: <a href="https://github.com/davidhalter/jedi/issues/372" rel="nofollow">https://github.com/davidhalte... | python|vim|numpy|omnicomplete | 2 |
19,315 | 1,949,225 | "painting" one array onto another using python / numpy | <p>I'm writing a library to process gaze tracking in Python, and I'm rather new to the whole numpy / scipy world. Essentially, I'm looking to take an array of (x,y) values in time and "paint" some shape onto a canvas at those coordinates. For example, the shape might be a blurred circle. </p>
<p>The operation I have i... | <p>In your question you describe a Gaussian filter, for which scipy has support via a <a href="http://www.scipy.org/SciPyPackages/Ndimage" rel="nofollow noreferrer">package</a>.
For example:</p>
<pre><code>from scipy import * # rand
from pylab import * # figure, imshow
from scipy.ndimage import gaussian_filter
# rand... | python|image-processing|numpy|scipy | 7 |
19,316 | 72,922,803 | GroupBy transform median with date filter pandas | <p>I have 2 dataframes:</p>
<p>df1:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>artist_id</th>
<th>concert_date</th>
<th>region_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>12345</td>
<td>2019-10</td>
<td>22</td>
</tr>
<tr>
<td>33322</td>
<td>2018-11</td>
<td>44</td>
</tr>
</tbody>
</table>
... | <p>Here's a way to do this without a python loop:</p>
<pre class="lang-py prettyprint-override"><code>df3 = df1.merge(df2, on=['artist_id', 'region_id'])
df3 = df3[df3.date >= df3.concert_date - pd.DateOffset(months=3)]
df3 = df3.groupby(['artist_id', 'region_id', 'concert_date']).median().rename(
columns={'popu... | python|pandas|loops|group-by | 3 |
19,317 | 72,920,875 | Substract values from two columns where same time (pandas, python) | <p>I have a pandas dataFrame with 3 columns of weather data - temperature, time and the name of the weather station.</p>
<p>It looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Time</th>
<th style="text-align: center;">Station_name</th>
<th style="te... | <p>You can use a <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html?highlight=pa" rel="nofollow noreferrer"><code>merge_asof</code></a> on the two sub-dataframes:</p>
<pre><code>df['Time'] = pd.to_datetime(df['Time'])
out = (pd
.merge_asof(df[df['Station_name'].eq('station_a')],
... | python|pandas|datetime|difference | 3 |
19,318 | 72,928,902 | Issue between number of classes and shape of inputs in metric collection torch | <p>I have a problem because I want to calculate some metrics in torchmetrics. but there is a problem:</p>
<pre><code>ValueError: The implied number of classes (from shape of inputs) does not match num_classes.
</code></pre>
<p>The output is from UNet and the loss function is BCEWithLogitsLoss (binary segmentation)</p>
... | <p>It seems that <code>torchmetrics</code> expects different shape. Try to flatten both output and labels:</p>
<pre><code>prec = torchmetrics.Precision(num_classes=1)(outputs.view(-1), labels.type(torch.int32).view(-1))
</code></pre> | python|deep-learning|pytorch | 1 |
19,319 | 73,094,282 | In numpy, most computationally efficient way to find the array with shortest non-zero sequence in array of arrays | <p>Say that I have an array of arrays</p>
<pre><code>import numpy as np
z = np.array(
[
[1, 1, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 1],
]
)
</code></pre>
<p>Where 1s start on the left side of each array, and 0s on the right side if any. For many applications... | <p>Benchmark with a 5000×5000 array:</p>
<pre><code> 74.3 ms Dani
33.8 ms user19077881
2.6 ms Kelly1
1.4 ms Kelly2
</code></pre>
<p>My <code>Kelly1</code> is an O(m+n) saddleback search from top-right to bottom-left:</p>
<pre><code>def Kelly1(z):
m, n = z.shape
j = n - 1
for i in range(m):
... | python|arrays|numpy | 4 |
19,320 | 72,838,845 | PIL won't load RGB Image | <p>I am trying to load this image into python (I provided a link because its 75mb): <a href="https://drive.google.com/file/d/1usiKRN1JQaIxTTo_HTXPwUj8LeyR8CDc/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1usiKRN1JQaIxTTo_HTXPwUj8LeyR8CDc/view?usp=sharing</a></p>
<p>My current code is belo... | <p>Try this instead:</p>
<pre><code>import numpy as np
from PIL import Image
Image.MAX_IMAGE_PIXELS = 233280000
png = Image.open('world.png').convert('RGB')
png.show()
png = np.array(png)
print(png.shape)
</code></pre> | python|numpy|python-imaging-library | 1 |
19,321 | 10,284,656 | NumPy and Python 3 - Error message on import | <p>Importing NumPy in Python 3, I get the following error message:</p>
<pre><code>>>> import numpy
/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/numpy/random/__init__.py:91: RuntimeWarning: numpy.ndarray size changed, may indicate binary incompatibility
from .mtrand import *
... | <p>According to this bug report, it's a non-issue: <a href="http://projects.scipy.org/numpy/ticket/2103" rel="nofollow">http://projects.scipy.org/numpy/ticket/2103</a></p>
<p>And the warning has been fixed in git.</p> | python|numpy | 1 |
19,322 | 70,543,503 | Generate array / matrix of kernel density over all extension | <p>I'd like extracting all values of a kernel density function to a matrix (a numpy array with shape ymax,xmax). It is very easy to plot the kernel density with seaborn:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import stats, random
x = random.sample(range(2000, 4500), 1... | <p>This is slow because <code>itertools.product</code> is a <em>iterable that produces millions of pure-Python objects</em> (integers and tuple) that needs to be decoded and translated to native integers by Numpy. You can use Numpy directly to efficiently generate such array:</p>
<pre class="lang-py prettyprint-overrid... | python|numpy|matrix|kernel-density | 2 |
19,323 | 70,527,202 | Slow Pandas Series initialization from list of DataFrames | <p>I found it to be extremely slow if we initialize a pandas Series object from a list of DataFrames. E.g. the following code:</p>
<pre><code>import pandas as pd
import numpy as np
# creating a large (~8GB) list of DataFrames.
l = [pd.DataFrame(np.zeros((1000, 1000))) for i in range(1000)]
# This line executes extrem... | <p>This is not a direct answer to the OP's question (what's causing the slow-down when constructing a series from a list of dataframes):</p>
<p>I might be missing an important advantage of using <code>pd.Series</code> to store a list of dataframes, however if that's not critical for downstream processes, then a better ... | python|pandas|dataframe | 0 |
19,324 | 70,399,839 | How to iterate through each column and convert to dictionary, where one of the columns is a list? | <p>Dataframe:</p>
<p><img src="https://i.stack.imgur.com/sw4iV.png" alt="dataframe example" /></p>
<p>I want to convert this into a nested dictionary that groups by the unique id (00#) or name like:</p>
<pre><code>{001:{Bob:{[a,b]:text},{Sky:{[a,d]:text}}, 002:{Ed:{[c,a]:text},{Jed:{[c,a]:text}}}
</code></pre>
<p>note:... | <p>Taking the comments of @user17242583 and @Andrea into account, you can create a nested dictionary with tuples as the keys. You can groupby <code>col1</code> and then iterate through each of the rows in the groupby DataFrame.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col1':['001','002','001','001','002'... | python|pandas|dataframe|dictionary|tuples | 0 |
19,325 | 70,444,512 | Removing rows and columns if all zeros in non-diagonal entries | <p>I am generating a <code>confusion matrix</code> to get an idea on my <code>text-classifier</code>'s <code>prediction</code> vs <code>ground-truth</code>. The purpose is to understand which <code>intent</code>s are being predicted as some another <code>intent</code>s. But the problem is I have too many classes (more ... | <p>You can use <code>any</code> on the comparison, but first you need to fill the diagonal with <code>0</code>:</p>
<pre><code># also consider using
# a = np.isclose(confusion_matrix.to_numpy(), 0)
a = confusion_matrix.to_numpy() != 0
# fill diagonal
np.fill_diagonal(a, False)
# columns with at least one non-zero
col... | python|pandas|matplotlib|crosstab|confusion-matrix | 2 |
19,326 | 42,873,136 | Calculate the delta between entries in Pandas using partitions | <p>I'm using <code>Dataframe</code> in <code>Pandas</code>, and I would like to calculate the delta between each adjacent rows, using a partition.</p>
<p>For example, this is my initial set after sorting it by A and B:</p>
<pre><code> A B
1 12 40
2 12 50
3 12 65
4 23 30
5 23 45
6 23 60
</co... | <p>You can group by column A and take the difference:</p>
<pre><code>df['C'] = df.groupby('A')['B'].diff()
df
Out:
A B C
1 12 40 NaN
2 12 50 10.0
3 12 65 15.0
4 23 30 NaN
5 23 45 15.0
6 23 60 15.0
</code></pre> | python|pandas|dataframe|data-analysis | 3 |
19,327 | 27,159,189 | Find empty or NaN entry in Pandas Dataframe | <p>I am trying to search through a Pandas Dataframe to find where it has a missing entry or a NaN entry.</p>
<p>Here is a dataframe that I am working with:</p>
<pre><code>cl_id a c d e A1 A2 A3
0 1 -0.419279 0.843832 -0.530827 text76 ... | <p><code>np.where(pd.isnull(df))</code> returns the row and column indices where the value is NaN:</p>
<pre><code>In [152]: import numpy as np
In [153]: import pandas as pd
In [154]: np.where(pd.isnull(df))
Out[154]: (array([2, 5, 6, 6, 7, 7]), array([7, 7, 6, 7, 6, 7]))
In [155]: df.iloc[2,7]
Out[155]: nan
In [160]... | list|python-2.7|pandas|indexing|dataframe | 73 |
19,328 | 26,918,462 | pandas ImportError: cannot import name hashtable on Mac OS X | <p>I recently noticed I had an old version of pandas installed on my machine (0.10). </p>
<p>I tried pip install -U first and got the error. I pip uninstalled, wiped any old directories, pip installed again and still the same error. I even tried building from the git, but whatever I seem to do, I get the same error:</... | <p>OK, the problem was that your pandas installation was screwed up.</p>
<p>The most likely reason for this is that you were inside a directory named <code>pandas</code> when you did the <code>pip install pandas</code>, which caused some of the build steps to pick up relative paths to the local directory instead of pa... | python|pandas | 3 |
19,329 | 13,221,368 | Converting a list of (x,y,z) tuples spaced on a square lattice to an array | <p>I have a list of tuples e.g. like this:</p>
<pre><code>l=[ (2,2,1), (2,4,0), (2,8,0),
(4,2,0), (4,4,1), (4,8,0),
(8,2,0), (8,4,0), (8,8,1) ]
</code></pre>
<p>and want to transform it to an numpy array like this (only z values in the matrix, corresponding to the sequence of x, y coordinates, the coordinates... | <p>It looks like <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html#numpy-unique" rel="nofollow noreferrer">np.unique</a> with the <code>return_inverse</code> option fits the bill. For example,</p>
<pre><code>In [203]: l[:,0]
Out[203]: array([2, 2, 2, 4, 4, 4, 8, 8, 8])
In [204]: np.unique... | python|numpy|matplotlib | 2 |
19,330 | 13,055,090 | FFTW3 on complex numpy array directly in scipy.weave.inline | <p>I am trying to implement an FFT based subpixel shifting (translation) algorithm in <code>Python</code>. The Fourier shift theorem allows an array to be translated by a subpixel amount by:
1. Forward FFT array
2. Multiply array by linear phase ramp in Fourier space
3. Inverse FFT array</p>
<p>This algorithm is... | <p>According to the <a href="http://www.fftw.org/doc/Complex-numbers.html" rel="nofollow">fftw manual</a>, you can import <code>complex.h</code> before <code>fftw.h</code>, which will guarantee that <code>fftw_complex</code> will correspond to the native C data type. I'm pretty sure that numpy data types are also guara... | python|c|numpy|scipy|fftw | 0 |
19,331 | 28,964,495 | how to slice a pandas data frame according to column values? | <p>I have a pandas data frame with following format:</p>
<pre><code>year col1
y1 val_1
y1 val_2
y1 val_3
y2 val_4
y2 val_5
y2 val_6
y3 val_7
y3 val_8
y3 val_9
</code></pre>
<p>How do I select only the values till year 2 and omit year 3?</p>
<p>I need a new_data frame... | <p>On your sample dataset the following works:</p>
<pre><code>In [35]:
df.iloc[0:df[df.year == 'y3'].index[0]]
Out[35]:
year col1
0 y1 val_1
1 y1 val_2
2 y1 val_3
3 y2 val_4
4 y2 val_5
5 y2 val_6
</code></pre>
<p>So breaking this down, we perform a boolean index to find the rows that equal the ... | python|python-2.7|pandas | 12 |
19,332 | 33,558,706 | Slice by date in pandas without re-indexing | <p>I have a pandas dataframe where one of the columns is made up of strings representing dates, which I then convert to python timestamps by using <code>pd.to_datetime()</code>.</p>
<p>How can I select the rows in my dataframe that meet conditions on date.</p>
<p>I know you can use the index (<a href="https://stackov... | <p>You can use a mask on the date, e.g.</p>
<pre><code>df[df['date'] > '2015-03-01']
</code></pre>
<p>Here is a full example:</p>
<pre><code>>>> df = pd.DataFrame({'date': pd.date_range('2015-02-15', periods=5, freq='W'),
'val': np.random.random(5)})
>>> df
date ... | python|date|pandas | 2 |
19,333 | 33,738,958 | add legend for some of the lines | <p><strong>I want to add legend to illustrate different value of a, there are 6 lines in the picture, however the two have the same color have the same value of a.I want to add a legend has only three lines in it, indicating $a=1$, $a=2$, $a=3$ for different color.</strong> </p>
<p>Note this code has a loop, so I don'... | <p>Labels are only included when <a href="https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html" rel="nofollow noreferrer"><code>matplotlib.axes.Axes.plot()</code></a> is called and a string is provided as an argument for the label variable (e.g. label='???'). </p>
<p>For example this adds (only) three li... | python|numpy|matplotlib | 1 |
19,334 | 23,748,842 | understanding math errors in pandas dataframes | <p>I'm trying to generate a new column in a pandas dataframe from other columns and am getting some math errors that I don't understand. Here is a snapshot of the problem and some simplifying diagnostics...</p>
<p>I can generate a data frame that looks pretty good:</p>
<pre><code>import pandas
import math as m
data... | <p>math functions such as <a href="https://docs.python.org/2/library/math.html#math.radians" rel="noreferrer">math.radians</a> expect a numeric value such as a float, not a sequence such as a <code>pandas.Series</code>. </p>
<p>Instead, you could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.r... | python|pandas|ipython | 9 |
19,335 | 29,521,027 | In python, what is a good way to match expected values to real values? | <p>Given a Dictionary with ideal x,y locations, I have a list of unordered real x,y locations that are close to the ideal locations and I need to classify them to the corresponding ideal location dictionary key. Sometimes, I get no data at all (0,0) for a given location.
An example dataset is:</p>
<pre><code>idealLoc... | <p><a href="http://en.wikipedia.org/wiki/K-d_tree" rel="nofollow">K-d trees</a> are an efficient way to partition data in order to perform fast nearest-neighbour searches. You can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html" rel="nofollow"><code>scipy.spatial.cKDTree</cod... | python|numpy|classification | 1 |
19,336 | 62,436,378 | PyTorch extracting tensor elements with boolean mask (retaining dimensions) | <p>Say, I have a PyTorch 2x2 tensor, and I also generated a boolean tensor of the same dimension (2x2). I want to use this as a mask.</p>
<p>For example, if I have a tensor:</p>
<pre><code>tensor([[1, 3],
[4, 7]])
</code></pre>
<p>And if my mask is:</p>
<pre><code>tensor([[ True, False],
[False, Tr... | <p>Assume you have :</p>
<pre><code>t = torch.Tensor([[1,2], [3,4]])
mask = torch.Tensor([[True,False], [False,True]])
</code></pre>
<p>You can use the mask by:</p>
<pre><code>masked_t = t * mask
</code></pre>
<p>and the output will be:</p>
<pre><code>tensor([[1., 0.],
[0., 4.]])
</code></pre> | boolean|pytorch|mask | 2 |
19,337 | 62,071,488 | Numpy: concat/expand 2D arrays based on matches in a column. How to eliminate for loop? | <p>I'm looking for a more "Numpy" way to perform an operation to expand and concatenate data from one array to another with repeating terms. </p>
<p><strong>Example Data</strong></p>
<p>I want <code>a</code> and <code>b</code> to look like <code>c</code> in the end:</p>
<pre><code>a = np.array(((0, 13), (0, 14), (1,... | <p>you could try to use the column 0 of <code>a</code> to index <code>b</code> values (sorry not sure of the term here) and then use <code>hstack</code> like:</p>
<pre><code>c = np.hstack([a, b[a[:, 0], 1:]])
print (c)
[[ 0 13 415 666]
[ 0 14 415 666]
[ 1 15 286 583]
[ 1 16 286 583]
[ 2 17 777 32]]
</co... | python|arrays|numpy | 3 |
19,338 | 62,175,862 | Calculating concurrent sessions given a start and end time | <p>i need to be able to work out how many sessions are running at any given time, per minute based on millions of rows of data like the ones below.</p>
<p>I have tried melting the dataframe and have created a new column which is equal to 1 or -1 depending on whether its the start or the end. Summing that and grouping ... | <p>My original approach was to create a <code>DatetimeIndex</code> that represents the time period which contains all of the events in the data and then for each event create an array, with the same dimension as the index, whose values are <code>1</code> or <code>True</code> when the event was taking place and <code>0<... | python-3.x|pandas | 1 |
19,339 | 62,062,400 | Transferring a double from C++ to python without loss of precision | <p>I have some C++ code which outputs an array of double values. I want to use these double values in python. The obvious and easiest way to transfer the values would of course be dumping them into a file and then rereading the file in python. However, this would lead to loss of precision, because not all decimal place... | <p>You could write out the double value(s) in binary form and then read and convert them in python with <code>struct.unpack("d", file.read(8))</code>, thereby assuming that IEEE 754 is used.</p>
<p>There are a couple of issues, however:</p>
<ul>
<li>C++ does not specify the bit representation of doubles. While it is ... | python|c++|numpy|floating-point | 2 |
19,340 | 48,632,524 | Python: Convert entire column to dictionary | <p>I am just getting started with pandas recently.</p>
<p>I have a dataframe that looks like this</p>
<pre><code>import pandas as pd
locations=pd.read_csv('locations.csv')
lat lon
0 30.29 -87.44
1 30.21 -87.44
2 31.25 -87.41
</code></pre>
<p>I want to convert it to something like this </p>
<p><code>{'lat... | <p>Check <code>to_dict</code></p>
<pre><code>df.to_dict('l')
Out[951]: {'Lon': [-87.44, -87.44, -87.41], 'lat': [30.29, 30.21, 31.25]}
</code></pre> | pandas|dictionary|dataframe | 5 |
19,341 | 48,840,499 | Tensorflow - classify based on multiple image as input, not signle one | <p>I'm building CNN that will tell me if a person has brain damage. I'm planning to use <a href="https://github.com/tensorflow/models/tree/f87a58cd96d45de73c9a8330a06b2ab56749a7fa/research/inception" rel="nofollow noreferrer">tf inception v3</a> model, and <a href="https://github.com/tensorflow/models/blob/f87a58cd96d4... | <p>It looks like multiple instance learning might be your approach. Check out these two papers:</p>
<p><a href="https://arxiv.org/pdf/1610.03155.pdf" rel="nofollow noreferrer">Multiple Instance Learning Convolutional Neural
Networks for Object Recognition</a></p>
<p><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/... | python|tensorflow|deep-learning|conv-neural-network | 2 |
19,342 | 48,461,151 | ConcatOp : Dimensions of inputs should match: shape[0] = [1363,300] vs. shape[1] = [128,128] | <p>So it seems I'm doing something wrong here and I would appreciate some help. When I input my validation set into the network, the dimensions are not the same as the ones used for training. I would've expected "shape[0] = [1363,300] vs. shape[1] = [128,300]" since my dimension for the word embedding is 300.</p>
<pre... | <p>From a quick look: You define </p>
<pre><code>rnn_input = tf.Variable(tf.zeros([batchSize, maxSeqLength, numDimensions]), dtype=tf.float32)
</code></pre>
<p>which is dependend on batch size (128) but then feed validation data which has len(1363)</p>
<p>I guess </p>
<pre><code>rnn_input = tf.Variable(tf.zeros([tf... | python|tensorflow | 0 |
19,343 | 48,708,509 | What does batch normalization do if the batch size is one? | <p>I'am currently reading the paper from Ioffe and Szegedy about Batch Normalization and im wondering what happens if the Batch size is set to one. The computation of the mini-Batch mean(which is basically the value of theactivation itself) and variance(should be Zero plus constant epsilon) would lead to a normalized D... | <p>Because of beta, the learnable parameter for translation which is enabled by default, the normalized output will not necessarily be zero.</p>
<p>Moving averages for input mean and variance will be computed during training and can be used at testing (if you set <code>is_training</code> accordingly).</p> | tensorflow|batch-normalization | 0 |
19,344 | 70,804,707 | Converting groupby pandas df of absolute numbers to percentage of row totals | <p>I have some data in my df <code>df</code> that shows the 2 categories a user belongs to. For which I want to see the number of users for each category pair expressed as a %total of the row.</p>
<p>Original dataframe <code>df</code>:</p>
<pre><code>
+------+------+--------+
| cat1 | cat2 | user |
+------+------+---... | <p>You can simplify your expression:</p>
<pre><code>piv = df.pivot_table('user', 'cat1', 'cat2', aggfunc='nunique')
pct = piv.div(piv.sum(axis=1), axis=0)
</code></pre>
<p>Output:</p>
<pre><code>>>> piv
cat2 X Y
cat1
A 3 2
B 2 1
>>> pct
cat2 X Y
cat1 ... | python|pandas|dataframe | 0 |
19,345 | 71,043,939 | creating new column based on condition (Python) | <p>I have a dataframe where one of the columns, "deals" is a TRUE/FALSE boolean. I want to create a new column that populates 1 when the "deals" column is True, and 0 when the "deals" columns is False.</p>
<p>I tried the following code but it's giving me all zeros.</p>
<pre><code>df['maded... | <p>You can simply use <code>astype(int)</code> which converts True to 1 and False to 0 (no need for <code>np.where</code> here):</p>
<pre><code>df['madedeal'] = df['deal'].astype(int)
</code></pre> | python|pandas|if-statement|boolean|conditional-statements | 0 |
19,346 | 70,885,562 | Combine multiple CSVs, skip first 9 rows for each file | <p>In my jupyter notebook I am usually able to combine multiple .csv format files in a shared folder into one .csv with the following code that I did not originally write.</p>
<p>I now have files that have 9 rows of header/material that I want to omit, but don't know how to make it work with this format. The files are... | <p><code>pandas.read_csv</code> takes an argument <code>skiprows</code>.</p>
<blockquote>
<p>Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file.</p>
</blockquote>
<p>E.g.,</p>
<pre><code>combined_csv = pd.concat([pd.read_csv(f, skiprows=9) for f in all_filenames ])
</code></pre> | python|pandas|export-to-csv|rows | 0 |
19,347 | 51,803,908 | Get the row with highest value of a column when they all share same dates? | <p>I'm working on an inventory search system, and one of the features is returning all rows that fall within a date range.</p>
<p>The thing is, there are multiple rows that share the same date, but each ID is unique and different. The higher the ID, the later the entry.</p>
<p>The dataframe looks like this:</p>
<pre... | <p>Using <code>drop_duplicates</code></p>
<pre><code>df.sort_values('id').drop_duplicates('date',keep='last')
</code></pre> | python|pandas | 4 |
19,348 | 51,805,340 | Replace entire row containing NaN in Pandas | <p>I have a pandas dataframe in python that has NaN values. If a row has an NaN value then I want to replace the entire row with the preceding row. </p>
<p>So this</p>
<pre><code> stock label open high low close
0 CAT 09:31 AM 137.090 137.175 137.090 137.175
1 CAT 09:32 AM ... | <p>Using <code>mask</code> and <code>isnull</code> to mask all row as NaN then we using <code>ffill</code></p>
<pre><code>df=df.set_index(['stock','label'])
df=df.mask(df.isnull().any(1)).ffill().reset_index()
df
Out[889]:
stock label open high low close
0 CAT 09:31AM 137.09 137.175 137.09 ... | python|pandas|nan | 4 |
19,349 | 51,875,463 | Can I read the CSV file from which use first column and that column as input to spinner with no repetition? | <p>I have designed a Spinner GUI where I had given some set of options and that's been working but I need to know how to display the set of options by scanning values from CSV file and displaying as an options set, here I am able to display the set of values too, but not as an input for spinner. In my CSV file there ar... | <p>I figured it out we just need to make some changes like:</p>
<p>instead of this line</p>
<pre><code>self.optionf = ['Select','a','b','c']
</code></pre>
<p>make some change as </p>
<pre><code>self.optionf = [str(row) for row in (a)]
</code></pre>
<p>where a is the value in which values are stored of column fi... | python|pandas|csv|kivy|spinner | 1 |
19,350 | 47,629,563 | Pandas : Replace values multiple times until the end | <p>I have a pandas df like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8666]})
</code></pre>
<p><a href="https://i.stack.imgur.com/LfdeV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LfdeV.png" alt="enter image description here"></a></p>
<p>It ... | <p>You can replace values to <code>NaN</code>s by condition and then use <code>ffill</code> - <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> with <code>method='ffill'</code>:</p>
<pre><code>df.loc[df.above < df.sales, 'sale... | python|pandas|replace|series|shift | 3 |
19,351 | 47,681,739 | Is it OK to pass pandas GroupBy functions as argument in python function? and how should I pass their arguments? | <p>I would like a function that takes a GroupBy operations such as mean(), max() as argument. I'm not sure as to how to include arguments for these functions. For example, in the case of quantile, there is the argument for telling which quantile, so in such case I should be able to provide this extra argument.</p>
<pr... | <p>It is ok to pass anything you want, if it works and serves you well.
You can pass function's agrs either as an additional dict/tuple argument, or just use *args and **kwargs.</p>
<p>still, it is unclear what you want to achieve here.
First, It looks like you're messing with <code>data</code> and <code>df</code> in... | python|pandas|pandas-groupby | 1 |
19,352 | 49,214,474 | Overlapping bars in pandas plot are not perfectly centered over each other when they have different width | <p>I am wondering if there is a way to center bars that overlap in a bar plot when using the plotting provided by pandas.</p>
<p>When using twiny, we get bars corresponding to the different plots to overlap, which is really practical. When they have the same width they will be centered perfectly over each other.</p>
... | <p>First you need to have the bar positions and widths on the same scale. So you would probably want to create a <code>twinx</code> axes instead of <code>twiny</code>. (You can still use <code>ax.set_ylim(ax2.get_ylim())</code> to get the y scale equal as well.)</p>
<p>Then, in case there are as many bars in the prima... | python|pandas|matplotlib | 2 |
19,353 | 48,955,971 | Getting ValueError: setting an array element with a sequence from tf.contrib.keras.preprocessing.image.ImageDatagenerator.flow | <p>I am trying to do Data Augmentation in Tensorflow. I have written this code.</p>
<pre><code>import numpy as np
import tensorflow as tf
import tensorflow.contrib.keras as keras
import time, random
def get_image_data_generator():
return keras.preprocessing.image.ImageDataGenerator(
rotation_range=get_random_... | <blockquote>
<p>Edit :: I am getting this error even if I pass a single image as argument.`</p>
</blockquote>
<p>Can you pass the single element as an array and see:</p>
<p>example:</p>
<pre><code>image_array, label_array = augment_data([image], [label])
</code></pre> | python|tensorflow | 0 |
19,354 | 70,316,758 | Unable to modify or reproduce a ragged numpy array | <p>** For convenience, I prepared a <a href="https://colab.research.google.com/drive/1oX0cOIgsGNjnW8u3lqkrkQqvcanMMMgn?usp=sharing" rel="nofollow noreferrer">notebook</a> which downloads <a href="https://drive.google.com/file/d/1Oq7AWzOb_pVJkJv69FewXynZaIBymt52/view?usp=sharing" rel="nofollow noreferrer">gt.mat</a> and... | <p>Skipping over most of your description, the last error is produced by an action like</p>
<pre><code>In [407]: np.array([np.ones([2,4,3]),np.zeros([2,4,2])],'O')
Traceback (most recent call last):
File "<ipython-input-407-6868cb2349dc>", line 1, in <module>
np.array([np.ones([2,4,3]),np.ze... | python|numpy|scipy | 2 |
19,355 | 70,210,702 | Pandas can't find a value in dataframe using values in another dataframe | <p>I have two dataframes:</p>
<p>df1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Index</th>
<th>geoid10</th>
<th>precinct_2020</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>360050020002003</td>
<td>43</td>
</tr>
<tr>
<td>2</td>
<td>360610005001008</td>
<td>1</td>
</tr>
<tr>
<td>3</td>... | <p>You can use pandas built-in function <code>isin</code>:</p>
<pre><code>print(df1['geoid10'].isin(df2["geoid10"]))
</code></pre>
<p>Output:</p>
<pre><code>0 False
1 True
2 True
3 False
4 True
5 True
6 True
</code></pre> | python|pandas | 1 |
19,356 | 70,081,669 | Python comparing two matrices produces error | <p>Hello I have the following code which transposes one matrix and compares it to the original matrix in order to check if the matrix is symetrical.</p>
<pre><code>def sym(x):
mat = x
transpose = 0;
(m,n) = x.shape
if(m != n):
print("Matrix must be square")
return
... | <p>What you are doing is trying to compare two ndarrays, which results in something like this:</p>
<pre><code>transpose == mat
array([[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, T... | python|numpy | 0 |
19,357 | 56,277,155 | Dropping different elements from different columns at once using Pandas | <p>I am trying to remove different elements from different columns from the data frame.</p>
<p>Here is what I have tried so far</p>
<pre><code>xdf
Out[46]:
Name Score1 Score2 Score3 Score4
0 Jack 10 Perfect 10 Perfect
1 Jill 10 10 10 Not Finished
2 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html" rel="nofollow noreferrer"><code>DataFrame.any</code></a> for test at lest one <code>True</code> per rows:</p>
<pre><code>drop_list = ["Perfect","Not Finished"]
df = xdf[~xdf[["Score1","Score2","Score3","Score4"]].isin(... | python-3.x|pandas|numpy|dataframe | 1 |
19,358 | 56,169,852 | Tensorflow 2-coordinates classifier | <p>Im a novice experimenting with machine learning. I saw this repo <a href="https://github.com/jbp261/Optimal-Classification-Model-of-BLE-RSSI-Dataset" rel="nofollow noreferrer">https://github.com/jbp261/Optimal-Classification-Model-of-BLE-RSSI-Dataset</a> and wanted to replicate a similar experiment.</p>
<p>So I hav... | <p>in <code>model.fit()</code> add some validation (simple way is <code>validation_split=0.5</code> or whatever percent you want to split.) This takes some of your data, separates it from training data, and only uses it after epoch ends to see how the network is performing on data <em>it has never seen before.</em> Thi... | python|tensorflow|machine-learning|keras|classification | 2 |
19,359 | 56,360,776 | is there a nice output of Keras model.summary( )? | <p>is it possible to have a nice output of keras model.summary(), that can be included in paper, or can be ploted in a nice table like this. </p>
<p><a href="https://i.stack.imgur.com/eFQ9P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eFQ9P.png" alt="enter image description here"></a></p> | <p>You need to install graphvis and pydot, but you might like the results from this. It doesn't make a table but the graph is much better in my opinion. </p>
<pre class="lang-py prettyprint-override"><code> from keras.utils import plot_model
plot_model(model, to_file='model.png', show_shapes=True,show_layer_nam... | python|tensorflow|keras|deep-learning | 3 |
19,360 | 55,762,706 | How to load pretrained googlenet model in pytorch | <p>I'm trying to finetune a GoogleNet network over a specific dataset but I'm having trouble loading it. What I try now is:</p>
<pre><code>model = torchvision.models.googlenet(pretrained=True)
</code></pre>
<p>However I get an error: </p>
<pre><code>AttributeError: module 'torchvision.models' has no attribute 'googl... | <p>You can instead use the GoogLeNet <code>inception_v3</code> model (<a href="https://arxiv.org/abs/1512.00567" rel="nofollow noreferrer">"Rethinking the Inception Architecture for Computer Vision"</a>):</p>
<pre><code>import torchvision
google_net = torchvision.models.inception_v3(pretrained=True)
</code></pre> | python|conv-neural-network|pytorch|pre-trained-model|torchvision | 1 |
19,361 | 55,600,435 | How to create a dataframe that includes all of the null values from an original dataframe? | <p>I am hoping to create a pandas dataframe from an original dataframe that contains just rows with NA values in them</p>
<p>Here is an example dataframe and what I want my output to look like:</p>
<pre><code> A B C A B C
2 1 Green 1 2 nan
1 2 nan 2 1 nan
1 1 Red ... | <p>If its just one column use:</p>
<pre><code>df = df[df.C.isnull()]
</code></pre>
<p>If its the whole dataframe (you want to filter where any column in the dataframe is null for a given row)</p>
<pre><code>df = df[df.isnull().sum(1) > 0]
</code></pre> | python|pandas|dataframe|na | 2 |
19,362 | 55,692,459 | Tensorflow-Numpy OSError: [WinError 193] %1 is not a valid Win32 application | <p>I am trying to import Keras (using tensorflow), and I am getting this error. I have tried everything I found in the Internet, but still does not work. Please I will appreciate a lot if you help me.</p>
<p>I have read is something with the 32bits and 64bits versions. I have tried everything (downloaded and uninstall... | <p>I solved the problem!</p>
<p>I just download a 64 NUMPY wheel and installed it.</p> | python|numpy | 1 |
19,363 | 65,042,956 | pandas: how to group rows into a new column | <p>I have a simple dataset in the form of:</p>
<pre><code>author_id,Publisher,Title
1,Archie Publications,Archie
1,Marvel,A-Team
1,NOW,The Green Hornet
2,Archie Publications,Betty & Veronica
2,Marvel,Absolute Carnage
2,NOW,Little Monsters
2,NOW,The Green Hornet
2,NOW,Kata
3,Archie Publications,Archie & Jughead
... | <p>I think this is what you want</p>
<p><code>df.groupby(['author_id', 'Publisher']).agg({'Title': list})</code></p>
<pre><code> Title
author_id Publisher
1 Archie Publications ... | python|pandas|data-wrangling | 1 |
19,364 | 64,739,009 | Python DataFrame Filtering and Sorting at the Same Time | <p>Hi I have a data frame with column as following: 'founded' and 'company name'</p>
<p>What I'm trying to do is filtering the year founded > 0 and then sorting by company name, ascending.</p>
<p>I'm looking for a code similar to this</p>
<pre><code>df_job_da_details_filter_sort = df_job_da_details[df_job_da_details... | <p>The error in the code is syntactical rather than a logical one.</p>
<p>The way you are currently doing is correct and will produce the intended result</p>
<p>Indentation Errors in Python are, primarily caused because there are space or tab errors in your code. Since Python uses procedural language, you may experienc... | python|pandas|dataframe | 1 |
19,365 | 64,939,701 | Error loading excel file when trying to run row by row | <p>I have a code for validating data from an excel-file and I'm trying to get the code to validate row by row from the file. I use this method with importing pandas since it works fine for loading lists for email sendings successfully, so naturally I run the following similar code:</p>
<pre><code>import pandas as pd
fr... | <pre><code>import pandas as pd
from validate_email import validate_email
email_list = pd.read_excel('/home/simon/Documents/Emaillist/test/test.xlsx')
emails = email_list['EMAIL'].tolist()
for i in range(len(emails)):
email = emails[i]
is_valid = validate_email(email_address=email, check_regex=True, check_mx=... | pandas|python-3.8|import-from-excel | 0 |
19,366 | 64,960,285 | Pandas pct_change with data containing NaN results in nonsensical values | <p>I'm very confused by the output of the pct_change function when data with NaN values are involved. The first several rows of output in the right column are correct - it gives the percentage change in decimal form of the cell to the left in Column A relative to the cell in Column A two rows prior. But as soon as it r... | <p><strong>The behaviour is as expected</strong>. You need to carefully read the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pct_change.html" rel="nofollow noreferrer"><code>df.pct_change docs</code></a>.</p>
<p>As per docs:</p>
<pre><code>fill_method: str, default ‘pad’
How to ... | python|pandas|dataframe|nan | 2 |
19,367 | 44,301,148 | Converting one to many mapping dictionary to Dataframe | <p>I have a dictionary as follows:</p>
<pre><code>d={1:(array[2,3]), 2:(array[8,4,5]), 3:(array[6,7,8,9])}
</code></pre>
<p>As depicted, here the values for each key are variable length arrays. </p>
<p>Now I want to convert it to DataFrame. So the output looks like:</p>
<pre><code>A B
1 2
1 3
2 8
2 4
2 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow noreferrer"><code>Series</code></a> constructor with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>str.len</code></a> for lenghts of <code>... | python|pandas|dictionary | 4 |
19,368 | 44,021,724 | Pandas Dataframe Mutli index sorting by level and column value | <p>I have a pandas dataframe which looks like this:</p>
<pre><code> value
Id
2014-03-13 1 -3
2 -6
3 -3.2
4 -3.1
5 -5
2014-03-14 1 -3.4
2 -6.2
... | <p>For me works <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code><... | python|sorting|pandas|dataframe|multi-index | 7 |
19,369 | 69,301,376 | python split the column values of a dataframe | <p>I am working on python and new to it.I have a dataframe as</p>
<pre><code>Date Emailable Lost_Fans New_Fans Country
12-10-2020 121134 JP
06-11-2020 120859 350 75 JP
18-12-2020 101857 19128 126 JP
29-01-202... | <ol>
<li><p>To find the missing months, use the following code:</p>
<pre><code>
months = []
miss_months = []
for i in range(len(df.Date)):
if df.Date[i].split('-')[1][0] != '0':
months.append(df.Date[i].split('-')[1])
else:
months.append(df.Date[i].split('-')[... | python|pandas | 2 |
19,370 | 41,133,227 | How can i install OpenBLAS and numpy on windows10 and anaconda? | <p>There are so many guide of install openBLAS for linux, So I want to know how can i install openBLAS on windows10 with anaconda3.</p> | <p>There is a conda 'openblas' version available. To get it use <code>conda install -c menpo openblas</code>
referenced from <a href="https://anaconda.org/menpo/openblas" rel="nofollow noreferrer">https://anaconda.org/menpo/openblas</a></p> | python|numpy|theano|openblas | 0 |
19,371 | 41,007,474 | Dimension Reduction in CLDNN (tensorflow) | <p>I'm trying to write an implementation of CLDNN with tensorflow, like the one in <a href="https://www.researchgate.net/profile/Wei_Ning_Hsu2/publication/307889054/viewer/AS:415845072293888@1476156599818/background/3.png" rel="nofollow noreferrer">this scheme</a>. I am having a problem with the dimension reduction lay... | <p>Paper says</p>
<blockquote>
<p>The Computational Network Toolkit (CNTK) [24] is used for neural network training. As [14] suggests, we apply uniform random weight initialization for all layers without either generative or discriminative pretraining [1].</p>
</blockquote>
<p>Dimension reduction in diagram is simp... | tensorflow|speech-recognition|autoencoder|rbm | 0 |
19,372 | 40,903,867 | What causes the unpickling error in numpy? | <p>I'm currently getting an unpickling error for loading a gz file using the numpy load function. I'm not sure what's causing this. Could offer some suggestions. I'm not sure if the data inside the file might be the problem.</p>
<pre><code> import numpy as np
import gzip
import io
import pickle
n = np.load("prot... | <p>I believe that <code>numpy.load</code> expects to read an uncompressed <code>*.npy</code> file, not a gzipped <code>*.npy.gz</code> file. Try uncompressing the file first before loading it.</p> | python|numpy | 1 |
19,373 | 54,244,868 | Reshape DataFrame by pivoting multiple columns | <p>Hi how can I pivot a table like this</p>
<pre><code>import pandas as pd
d = {'name' : ['A','A','B','B'],'year': ['2018','2019','2018','2019'],'col1':[1,4,7,10],'col2':[2,5,8,11],'col3':[3,6,9,12]}
pd.DataFrame(data=d)
name year col1 col2 col3
A 2018 1 2 3
A 2019 4 ... | <p>You can use <code>melt</code> and <code>pivot_table</code>:</p>
<pre><code>(df.melt(['name','year'], var_name='cols')
.pivot_table(index=['name', 'cols'],
columns='year',
values='value',
aggfunc='sum')
.reset_index()
.rename_axis(None, 1))
name cols 2... | python|pandas|pivot-table|multi-index | 6 |
19,374 | 53,841,246 | "Expecting miMATRIX type" error when reading MATLAB MAT-file with SciPy | <p>This is a MATLAB question: the problem is caused by interactions with MATLAB files and Python/numpy. I am tying to write a 3-D array of type uint8 in MATLAB, and then read it in Python using numpy. This is the MATLAB code that creates the file:</p>
<pre><code>voxels = zeros(30, 30, 30);
....
fileID1 = fopen(fullF... | <p>To create a MAT-file, use the MATLAB <a href="https://www.mathworks.com/help/matlab/ref/save.html" rel="nofollow noreferrer"><code>save</code></a> command:</p>
<pre><code>voxels = zeros(30, 30, 30, 'uint8');
save(fullFileNameOut, 'voxels', '-v7')
</code></pre>
<p>You need to add <code>'-v7'</code> (or <code>'-v6'<... | arrays|matlab|numpy|scipy|mat-file | 2 |
19,375 | 66,137,513 | How should I combine the rows of similar time in a Dataframe? | <p>I'm processing a MIMIC dataset. Now I want to combine the data in the rows whose time difference (delta time) is below 10min. How can I do that?</p>
<p>The original data:</p>
<pre><code>charttime hadm_id age is_male HR RR SPO2 Systolic_BP Diastolic_BP MAP PEEP PO2
0 2119-07-20 17:54:00 26270240 NaN... | <p>First, I would round the timestamp column to 10 minutes:</p>
<pre class="lang-py prettyprint-override"><code>df['charttime'] = pd.to_datetime(df['charttime']).dt.floor('10T').dt.time
</code></pre>
<p>Then, I would drop the duplicates, based on the columns you want to compare (for example, <code>hadm_id</code> and <c... | python|pandas|dataframe|machine-learning|deep-learning | 0 |
19,376 | 52,554,457 | What are the outputs of the Object Detection API of Tensorflow? | <p>I used Tensorflow's Object Detection API found in <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/research/object_detection</a>. I used <code>summarize_graph</code> and verified that the outputs are <code>... | <p>They represent exactly what the names suggest:</p>
<p>detection_boxes: coordinates of the predicted objects. Usually they represent: xmin,xmax,ymin,ymax.</p>
<p>detection_scores: exactly the score of each prediction, i.e., the model is 69% sure that certain image represent a A card.</p>
<p>detection_classes: a la... | python|tensorflow|image-processing|video-processing | 1 |
19,377 | 52,617,771 | Attribute Error: Converting hh:mm:ss to decimal in Python | <p><strong>Solution Update:</strong> From the link provided above, Here's what I've come up with: </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.read_csv('Book1.csv')
df = df.set_index(pd.DatetimeIndex(df['Duration']))
idx = pd.DatetimeIndex(df['Duration'])
df['Duration_Decimal'] = idx.hour + idx.minu... | <p>Your data already seem to be in datetime format. Your <code>conversion_function</code> expects to work with strings, though, which is why you get an error (<code>split()</code> works on strings). </p>
<p>Since you're working with Pandas, I'd recommend using the built-in Pandas date manipulation methods:</p>
<pre... | python|pandas|time | 0 |
19,378 | 52,811,458 | Pandas aggregation with dictionary `count_if=1` ignored. | <p>I would like to aggregate a Pandas DataFrame using <code>sum</code> and get <code>NaN</code> if all values of a group are <code>NaN</code>. This works in the case of <code>.agg('sum', min_count=1)</code> but the <code>min_count</code> is ignored when using a aggregation dictionary.</p>
<p>What am I missing here and... | <p>You can use lambda function:</p>
<pre><code>df1 = df.groupby('l').agg({'v': lambda x: x.sum(min_count=1), 'w': 'mean'})
print (df1)
v w
l
a -1.0 -1.0
b 2.0 1.0
c NaN NaN
</code></pre> | python|pandas | 6 |
19,379 | 46,238,677 | Create dummy values for a list of dates in pandas | <p>I have a dataframe with a double index (day, time) and would like to create a new column 'Holiday' equal to one if the index day belongs to a list of holidays.</p>
<p>My list of holidays of type DatetimeIndex:</p>
<pre><code>holidays = ['2017-09-11', '2017-12-24']
</code></pre>
<p>My original dataframe:</p>
<pre... | <p>Use <code>isin</code> by taking the date level from <code>get_level_values</code> and use <code>astype(int)</code> to convert boolean to integer.</p>
<pre><code>In [192]: df['Holiday'] = df.index.get_level_values(0).isin(holidays).astype(int)
In [193]: df
Out[193]:
Visitor Holiday
Date Time... | python|pandas|dataframe|dummy-variable | 2 |
19,380 | 46,341,454 | How to concatenate values of two variables in Pandas | <p>I have 2 variable data frame. I want to concatenates values of these to variables into a new variable using python.
How can I do this?</p>
<p>E.g.:</p>
<p><img src="https://i.stack.imgur.com/YQEDw.png" alt="enter image description here"></p> | <p>Concatenate columns together with separator:</p>
<pre><code>df = pd.DataFrame({'F_name':['AA','BB','CC'],
'M_name':['dd','ee','ff']})
df['L_name'] = df['F_name'] + '_' + df['M_name']
</code></pre>
<p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.ht... | python|pandas|dataframe | 3 |
19,381 | 58,196,657 | Compare Misaligned Series columns Pandas | <p>Comparing 2 series objects of different sizes:</p>
<pre><code>IN[248]:df['Series value 1']
Out[249]:
0 70
1 66.5
2 68
3 60
4 100
5 12
Name: Stu_perc, dtype: int64
IN[250]:benchmark_value
#benchamrk is a subset of data from df2 only based on certain filters
Out[251]:
0 70
Name: Stu_per... | <p>Because benchmark_value is <code>Series</code>, for scalar need select first value of <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iat.html" rel="nofollow noreferrer"><code>Series.iat</code></a> and set <code>NaN</code>s by <a href="http://pandas.pydata.org/... | python|pandas|series|valueerror | 1 |
19,382 | 58,337,849 | Select ONLY true values from conditional statement | <p>A really quick one hopefully</p>
<p>I have the statement below. How would I make it only return TRUE values and drop the FALSE values from the resulting dataframe?</p>
<p>Thanks</p>
<p><a href="https://i.stack.imgur.com/10TcZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/10TcZ.png" alt="enter... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for new <code>Series</code> with same size like <code>df</code> filled by number of unique values for possible filter original rows:</p>
<pr... | python-3.x|pandas | 1 |
19,383 | 68,895,886 | Replacing NaN Values | <p>I have 2 dataframes. I want to replace the missing values of a column in the first dataframe with a value that is in a column of the second dataframe. The 2 dataframes are like this:</p>
<p>First DataFrame:</p>
<pre><code>Item_Identifier Item_Weight Item_Fat_Content Item_Visibility Item_Type
FDA15 ... | <p>Use -</p>
<pre><code>df1['Item_Weight'] = df1['Item_Weight'].fillna(df1['Item_Type'].map(df2.set_index('Item_Type')['mean']))
</code></pre>
<p><strong>Output</strong></p>
<pre><code> Item_Identifier Item_Weight Item_Fat_Content Item_Visibility Item_Type
0 FDA15 9.0 Low_Fat ... | python|pandas | 2 |
19,384 | 69,064,337 | Duplicating rows in pandas Python | <p>i hope you are doing good . I have the following output :</p>
<pre><code>ClassName Bugs HighBugs LowBugs NormalBugs WMC LOC
Class1 4 0 1 3 34 77
Class2 0 0 0 0 9 45
Class3 3 0 1 2 10 18
C... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>dfs, col_names, other_cols = (
[],
["NormalBugs", "LowBugs", "HighBugs"],
["ClassName", "WMC", "LOC"],
)
for _, row in df.iterrows():
if row["Bugs"] == 0:
dfs.append(... | python|pandas|dataframe|datatable|multiple-columns | 1 |
19,385 | 69,109,433 | Poetry failing to install pandas mac os | <p>folks. When I attempt to run</p>
<p><code>poetry install --no-root</code></p>
<p>I receive an error when poetry attempts to resolve the pandas dependency:</p>
<pre><code>n file included from pandas/_libs/lib.c:666:
pandas/_libs/src/parse_helper.h:141:26: error: implicit declaration of function 'tolower_ascii' is... | <p>I ran into the same problem yesterday, but when building an older version of pandas from source (v0.24.2). I think this error is a mismatch between a newer compiler or Python and older pandas code. From searching around it looks like this error isn't entirely new, it was previously a warning so compilation still com... | python|pandas|macos|python-poetry | 0 |
19,386 | 69,183,241 | How to create a bar plot with a logarithmic x-axis and gaps between the bars? | <p>I want to plot a beautiful bar plot using the data mentioned in the script. Additionally, the x-axis should be logarithmic and there must be gaps between the bars.</p>
<p>I tried the script as below:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig = plt.figure()
x = [0.000... | <p>With a log scale x-axis, you can't set constant widths for the bars. E.g. the first bar would go between <code>0</code> and <code>0.000002</code>, (0 is at minus infinity on a log scale).</p>
<p>You could use the x-positions for the left edge of the bars, and the next x-position for the right edge:</p>
<pre class="l... | python|pandas|numpy|matplotlib | 3 |
19,387 | 69,238,696 | How to build a binary classifier with 3D training data | <p>I have data that I have to classify as either 0 or 1. The data is loaded from an <code>.npz</code> file. It gives me training, validation, and test data. This is what they look like:</p>
<pre><code>x_train = [[[ 0 0 0 ... 0 1 4]
[ 0 0 0 ... 4 25 2]
[ 6 33 15 ... 33 0 0]
...
[ 0 ... | <p>There are multiple issues with your code. I have tried adding separate sections to explain them. Please go through all of them and do try out the code examples I have shown below.</p>
<h3>1. Passing the samples/batch channel as the input dimension</h3>
<p>You are passing the batch channel as the input shape for the ... | python|tensorflow|machine-learning|deep-learning|classification | 4 |
19,388 | 69,089,545 | Read SQL query into pandas dataframe and replace string in query | <p>I'm querying my SSMS database from pandas and the query I have is pretty huge, I've saved it locally and want to read that query as a pandas dataframe and also there is a date string that I have in the query, I want to replace that datestring with a date that I've already assigned in pandas. For reference sake I'll ... | <h2>Reading a file in Python</h2>
<p>Here's how to read in a text file in Python.</p>
<pre class="lang-py prettyprint-override"><code>query_filename = 'C:\Users\Admin\Desktop\Python\Open Source\query.sql'
# 'rt' means open for reading, in text mode
with open(query_filename, 'rt') as f:
# read the query_filename fil... | python|mysql|python-3.x|pandas | 1 |
19,389 | 68,925,778 | Numpy array display different results than the file that was used to create it | <p>I have a file which I had converted into an array.
File looks like this:</p>
<p><a href="https://i.stack.imgur.com/kz1mh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kz1mh.png" alt="enter image description here" /></a></p>
<p>When I print results I get these values:</p>
<pre><code># Example A
... | <p>You are indexing array <code>a</code> (it's also <code>gift_costs</code>) with itself, <em>i.e.</em> the resulting array <code>b</code> would be characterized by this loop:</p>
<pre><code>for i in range(len(a)):
b[i] = a[a[i]]
</code></pre> | python-3.x|numpy|numpy-ndarray | 2 |
19,390 | 68,884,301 | TypeError: data type 'category' not understood pandas dataframe | <p>I have a dataframe <code>df</code>, with <code>dtypes: category(16), float32(65), int32(41)</code>. I want to perform some analysis on the categorical column. but when I iterate through the columns I get the above error. I can't seem to figure out what might be the issue.</p>
<pre><code>for col in app_train:
if... | <p>You can use <code>pandas.api.types</code> module to check any data types, it's the most recommended way to go about it. It contains a function <a href="https://pandas.pydata.org/docs/reference/api/pandas.api.types.is_categorical.html" rel="nofollow noreferrer"><code>pd.api.types.is_categorical_dtype</code></a> that ... | python|pandas | 1 |
19,391 | 44,392,978 | Compute a confidence interval from sample data assuming unknown distribution | <p>I have sample data for which I would like to compute a confidence interval, assuming a distribution that is not normal and is unknown. Basically, it looks like the distribution is Pareto. <a href="https://i.stack.imgur.com/1ZYr8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ZYr8.png" alt="Distr... | <p>If you don't know the underlying distribution, then my first thought would be to use bootstrapping: <a href="https://en.wikipedia.org/wiki/Bootstrapping_(statistics)" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Bootstrapping_(statistics)</a></p>
<p>In pseudo-code, assuming <code>x</code> is a numpy arra... | python|numpy|scipy|statistics|confidence-interval | 5 |
19,392 | 44,563,648 | How to effectively use tf.bucket_by_sequence_length in Tensorflow? | <p>So I'm trying to use tf.bucket_by_sequence_length() from Tensorflow, but can not quite figure out how to make it work.</p>
<p>Basically, it should take sequences (of different lengths) as input and have buckets of sequences as output, but it does not seem to work this way.</p>
<p>From this discussion:
<a href="ht... | <p>Indeed you need input tensor to be a queue, which can be e.g. a <code>tf.FIFOQueue().deque()</code>, or a <code>tf.TensorArray().read(tf.train.range_input_producer())</code>.</p>
<p>This notebook that explains it quite well:</p>
<p><a href="https://github.com/wcarvalho/jupyter_notebooks/blob/ebe762436e2eea1dff34b... | python|tensorflow|deep-learning|bucket | 2 |
19,393 | 60,787,065 | OneVsRestClassifier and multi_class="ovr" score when using LogisticRegression | <p>Why <code>OneVsRestClassifier()</code> returns much lower score for the same dataset than just using <code>multi_class="ovr"</code> parameter?</p>
<p>Using simple way to fit and get score with logisitc regression:</p>
<pre><code>#Load Data, assign variables
training_data = pd.read_csv("iris.data")
training_data.... | <p>Yes, the score should be the same.
The problem is that for the second method, you binarize the output. This transforms <code>y</code> in a way that it changes the prediction. Try <code>clf.predict(X_test)</code> to see that the prediction has an incorrect format.</p>
<p>To correct your problem, remove the line:</p>... | python|pandas|machine-learning|scikit-learn | 1 |
19,394 | 61,026,476 | Loading a model Raise ValueError Unknown loss function | <p>this is the code after i try to save and load my model: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>model.save('path_to_my_model.h5')
del model
model = tf.keras.mo... | <p>TL/DR: When you have custom_objects in the saved model, then you need to provide <code>compile = False</code> as an argument to the <code>load_model</code>. After loading the model, you need to compile with the custom_objects. Please check the <a href="https://github.com/jvishnuvardhan/Stackoverflow_Questions/blob/m... | tensorflow|keras|keras-layer|tf.keras|keras-lambda | 4 |
19,395 | 71,507,516 | How merge two rows in one row in pandas? | <p>I have this DataFrame:</p>
<pre><code> id type value
0 104 0 7999
1 105 1 196193579
2 108 0 245744
3 108 1 93310128
</code></pre>
<p>I need to merge rows that have the same <code>id</code> and keep the two values in the same row, the following example is what I require:</p>
<... | <p>It seems you want to keep "type" column values as well. So you could use <code>groupby</code> + <code>first</code> to get the "type" column; then use <code>pivot</code> to get the remaining columns and <code>merge</code> it to the "type" and "id" columns:</p>
<pre><code>out = ... | python|pandas|dataframe|pivot | 2 |
19,396 | 71,469,279 | grab values and column names based on row values (multiple values in cell) | <p>I have this df</p>
<pre><code>df = pd.DataFrame( {'R': {0: '1', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7'},\
'a': {0: 1.0, 1: 1.0, 2: 2.0, 3: 3.0, 4: 3.0, 5: 2.0, 6: 3.0},\
'b': {0: 1.0, 1: 1.0, 2: 1.0, 3: 2.0, 4: 2.0, 5: 0.0, 6: 3.0},\
'c': {0: 1.0, 1... | <p>You can use comparison and boolean indexing per row, save the intermediate variable using assignment expression, and create a Series:</p>
<pre><code>df.join(df.drop(columns='R')
.apply(lambda s: pd.Series({'an': ','.join((S:=s[s.lt(0)]).index),
'nv': list(S)}), axis=1)... | pandas|row|multiple-columns|cell | 1 |
19,397 | 71,444,008 | Extract seasons and years from a string column in pandas | <p>I just wondering if there is any other way I can extract the year from a column and assign two new columns to it where one column is for season and one for year?</p>
<p>I tried this method and it seems to work, but only work for year and selected rows:</p>
<pre><code>year = df['premiered'].str.findall('(\d{4})').str... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> with the <code>expand</code> option:</p>
<blockquote>
<p><code>expand</code>: Expand the split strings into separate columns.</p>
</blockquote>
<pre><code>df[['season', ... | python|pandas|dataframe | 1 |
19,398 | 71,668,426 | Select columns and create new dataframe | <p>I have a dataframe with more than 5000 columns but here is an example what it looks like:</p>
<pre><code>data = {'AST_0-1': [1, 2, 3],
'AST_0-45': [4, 5, 6],
'AST_0-135': [7, 8, 20],
'AST_10-1': [10, 20, 32],
'AST_10-45': [47, 56, 67],
'AST_10-135': [48, 57, 64],
'AS... | <p>You can use <code>str.extract</code> on the v column names to get the wanted I'd, then <code>groupby</code> on <code>axis=1</code>.</p>
<p>Here creating a dictionary of dataframes.</p>
<pre><code>group = df.columns.str.extract(r'(\d+)$', expand=False)
out = dict(list(df.groupby(group, axis=1)))
</code></pre>
<p>Out... | python|pandas|dataframe | 3 |
19,399 | 71,489,011 | AttributeError: 'DataFrame' object has no attribute 'to_sparse' | <p><a href="https://pandas.pydata.org/pandas-docs/version/0.25.0/reference/api/pandas.DataFrame.to_sparse.html" rel="nofollow noreferrer"><code>sdf = df.to_sparse()</code></a> has been deprecated. What's the updated way to convert to a sparse DataFrame?</p> | <p>These are the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/sparse.html#sparse-migration" rel="nofollow noreferrer">updated sparse conversions</a> in pandas 1.0.0+.</p>
<hr />
<h2>How to convert dense to sparse</h2>
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.... | python|pandas|dataframe|sparse-matrix | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.