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 |
|---|---|---|---|---|---|---|
355,800 | 41,768,504 | Optimal parameters not found for my curve fitting | <p>Hello I have a problem to fit some data with Python. I just begin to fit my data with Python so I have some problems... This is my code :</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import *
from numpy import linalg as LA
def f(x,a,b,c):
return a*np.power(x,b)+c
x = np... | <p>Three caveats :</p>
<ul>
<li>your model is not very good.</li>
<li>it diverge in x=0 : don't take first points.</li>
<li>you must give initial parameter estimations.</li>
</ul>
<p>An exemple:</p>
<pre><code>p0=[50000,-1,0]
x=x[10:]
y=y[10:]
params, cov = curve_fit(f, x, y,p0) #params=[3.16e+04 -5.83e-01 -1.00e+... | python|python-2.7|numpy|scipy|curve-fitting | 1 |
355,801 | 42,027,862 | Prevent pandas from reading None as Nan | <p>I have cleaned a dataset and had to replace a lot of <code>NaN</code> values with <code>None</code>. After that I saved it to a new csv file, when I read the cleaned dataset back using <code>pandas.read_csv</code>, all the <code>None</code> values are represented as <code>NaN</code>, how can I avoid this?</p> | <p>You can use parameter <code>keep_default_na</code> and <code>na_values</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer"><code>read_csv</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="... | python|csv|pandas|numpy|nan | 6 |
355,802 | 41,885,913 | How to use TensorFlow LSTM tutorial for character-level language modeling? | <p>I am trying to implement RNN character-level language model from Andrej Karpathy's blog <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/" rel="nofollow noreferrer">http://karpathy.github.io/2015/05/21/rnn-effectiveness/</a>
using TensorFlow RNN. For starters, I took ptb_word_lm.py from the LSTM tutor... | <p>Did you check your initialization? Learning can get stuck if the gradient is at zero. This would happen if you initialize weights (or bias) to either zeroes or ones. There are different initialization alternatives, depending on your activation (non-linearity). A well rounded initialization would be normal or truncat... | python|tensorflow|lstm | 0 |
355,803 | 42,049,681 | Pandas error when appending dataframes: invalid dtype determination in get_concat_dtype | <p>I have two <code>dataframes</code> with the same <code>dtypes</code>:</p>
<pre><code>>>> df1.dtypes
Out[3]:
GUID object
RID int64
SID int64
Threshold float64
Average float64
dtype: object
>>> df2.dtypes
Out[4]:
GUID object
RID ... | <p>Problem was MultiIndex</p>
<p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.droplevel.html" rel="nofollow noreferrer">droplevel</a> fixed the issue.</p>
<p>Very confusing error message.</p>
<pre><code>df1.columns.droplevel(1)
df1.append(df2)
</code></pre> | pandas|dataframe|append|python-3.6 | 3 |
355,804 | 41,869,206 | Generate Seaborn Countplot using column value as count | <p>For the following table</p>
<pre><code> count_value
CPUCore Offline_RetentionAge
i7 183 4184
7 1981
30 471
i5 183 2327
7 831
30 ... | <p>I think you need <a href="http://seaborn.pydata.org/generated/seaborn.barplot.html" rel="nofollow noreferrer">seaborn.barplot</a>:</p>
<pre><code>sns.barplot(x="count_value", y="index", hue='Offline_RetentionAge', data=df.reset_index())
</code></pre>
<p><a href="https://i.stack.imgur.com/n1UIz.png" rel="nofollow n... | pandas|seaborn | 1 |
355,805 | 42,092,657 | Changing multiple Numpy array elements using slicing in Python | <p>Say I have the <code>numpy</code> array <code>arr_1 = np.arange(10)</code> returning:</p>
<pre><code>array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>How do I change <em>multiple</em> elements to a certain value using slicing?</p>
<p>For example: changing the zeroth, first and second element that occur ever... | <p>Here is another solution based on what you did :</p>
<pre><code>arr_1 = np.arange(10)
arr_1[1::5] = 100
arr_1[2::5] = 100
arr_1[3::5] = 100
</code></pre>
<p>and it returns :</p>
<pre><code>array([ 0, 100, 100, 100, 4, 5, 100, 100, 100, 9])
</code></pre> | python|arrays|numpy|slice | 1 |
355,806 | 42,021,972 | Truncating decimal digits numpy array of floats | <p>I want to truncate the float values within the numpy array, for .e.g.</p>
<pre><code>2.34341232 --> 2.34
</code></pre>
<p>I read the post <a href="https://stackoverflow.com/questions/783897/truncating-floats-in-python">truncate floating point</a> but its for one float. I don't want to run a loop on the numpy a... | <p>Try out this modified version of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.trunc.html" rel="noreferrer">numpy.trunc()</a>.</p>
<pre><code>import numpy as np
def trunc(values, decs=0):
return np.trunc(values*10**decs)/(10**decs)
</code></pre>
<p>Sadly, <code>numpy.trunc</code> function... | python|numpy|vectorization | 35 |
355,807 | 41,922,767 | Convert a pandas dataframe function into a more efficient function | <p>Given the following two pandas dataframes</p>
<p>Dataframe 1</p>
<pre><code> open high low close
0 340.649 340.829 340.374 340.511
1 340.454 340.843 340.442 340.843
2 340.521 340.751 340.241 340.474
3 340.197 340.698 340.145 340.420
4 340.332 340.609 340.123 340.128
5 340.092... | <p>Here's a fairly quick conversion from a mostly-pandas function to a mostly-numpy function (<code>rolling</code> is still in pandas, but the rest is numpy). For 10,000 rows, this is about 10x faster.</p>
<pre><code>def norm_comp(df1, df2):
open = df1['open'].values
high = df1['high'].values
low = d... | python|pandas|numpy|vectorization | 2 |
355,808 | 41,858,836 | Why does .loc behave differently depending on whether values are printed or assigned? | <p>I got confused about the following behavior. When I have a dataframe like this:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6, 4), columns=list('ABCD'), index=list('bcdefg'))
</code></pre>
<p>which looks as follows:</p>
<pre><code> A B C ... | <p>I don't think this is a bug rather undocumented semantics, for instance setting with enlargement is allowed for the simple case where the row label doesn't exist:</p>
<pre><code>In [22]:
df.loc[3] = 10
df
Out[22]:
A B C D
b -0.907325 0.211740 0.150066 -0.240011
c -0.307... | python|pandas|slice | 3 |
355,809 | 7,813,305 | Array Assignment in numpy / : colon equivalent | <p>I am trying to relate the python/numpy indices of two arrays with different sizes, but I cannot pass index one from the small array to the large array through a subroutine. </p>
<p>For example, I have two numpy arrays: <code>a1</code> and <code>a2</code>. <code>a1.shape = (240,33,258)</code> and <code>a2.shape = (2... | <p>You should be able to use <code>slice(None)</code> to represent <code>:</code>. As in</p>
<pre><code>[index[0], slice(None), index[1], index[2]]
</code></pre> | python|indexing|numpy | 7 |
355,810 | 7,787,732 | How do I do matrix computations in python without rounding? | <p>I have some integer matrices of moderate size (a few hundred rows). I need to solve equations of the form <code>Ax = b</code> where <code>b</code> is a standard basis vector and <code>A</code> is one of my matrices. I have been using <code>numpy.linalg.lstsq</code> for this purpose, but the rounding errors end up be... | <p>If your only option is to use free tools written in python, <a href="http://code.google.com/p/sympy/" rel="nofollow">sympy</a> might work, but it could well be simpler to use mathematica.</p> | python|numpy | 2 |
355,811 | 37,872,565 | Reversed cumulative sum of a column in pandas.DataFrame | <p>I've got a pandas DataFrame with a boolean column sorted by another column and need to calculate reverse cumulative sum of the boolean column, that is, amount of true values from current row to bottom.</p>
<p>Example</p>
<pre><code>In [13]: df = pd.DataFrame({'A': [True] * 3 + [False] * 5, 'B': np.random.rand(8) }... | <p>Reverse column A, take the cumsum, then reverse again:</p>
<pre><code>df['C'] = df.loc[::-1, 'A'].cumsum()[::-1]
</code></pre>
<hr>
<pre><code>import pandas as pd
df = pd.DataFrame(
{'A': [False, True, False, False, False, True, False, True],
'B': [0.03771, 0.315414, 0.33248, 0.445505, 0.580156, 0.741551... | python|pandas|dataframe|reverse | 41 |
355,812 | 38,002,663 | viewing nested JSON data into a pandas dataframe | <p>I have now added the current problem onto GitHib. Please find the URL for the repo. I have included a Jupyter notebook that also explains the problem. Thanks guys.</p>
<p><a href="https://github.com/simongraham/dataExplore.git" rel="nofollow">https://github.com/simongraham/dataExplore.git</a></p>
<hr>
<p>I am cur... | <p><strong>UPDATE:</strong> this should work for your <code>kaidoData.json</code> file: </p>
<pre><code>df = (pd.io
.json
.json_normalize(data[0]['ionPortions'], 'nutritionNutrients',
['vcNutritionId','vcUserId','vcPortionId','vcPortionName','vcPortionSize',
'dtCreatedDate','dt... | python|json|pandas|dataframe | 4 |
355,813 | 37,997,300 | Python: Accessing a particular cell in a data frame, change it, then save into a new version of the data frame | <p>Using Pandas, I have a data frame with a column containing a string that I am splitting when a ; or , is seen:</p>
<pre><code>import re
re.split(';|,',x)
</code></pre>
<p>I want to iterate through the column in the whole data frame and create a copy of the current data frame with the new splits.</p>
<p>This is wh... | <p>Let me first describe how indexing works for pandas dataframe. Assuming you have the following daframe:</p>
<pre><code>df = DataFrame(randn(5,2),index=range(0,10,2),columns=list('AB'))
In [12]: df
Out[12]:
A B
0 0.767612 0.322622
2 0.875476 2.819955
4 1.876320 -1.591170
6 0.645850 ... | python|for-loop|pandas | 0 |
355,814 | 37,851,798 | python3.5/pandas - rolling mean by week and hour | <p>Trying to figure out how to use the rolling mean that takes into consideration the day and hour before computing the statistic.</p>
<p>File looks something like this:</p>
<pre><code> date hour price
1/1/2016 1 a
1/1/2016 2 b
. . .
. . .
1/8/2016 ... | <p>It's not 100% clear what you want but here are the assumption I made...</p>
<p>You want the mean by hour of all days before a certain date. This code does that...</p>
<pre><code>import pandas as pd
import numpy as np
import datetime
# build a sample table
np.random.seed(1)
values = np.random.choice(range(1, 11), ... | python|pandas | 1 |
355,815 | 37,629,976 | Pandas read_fwf ignores columns | <p>I have a .asc file where each line has 655 entries and looks somewhat like the following (note the leading whitespace)</p>
<pre><code> -999 -999 -999 -999 -999 -999 -999 -999 -999 ... -999 -999
</code></pre>
<p>When I read the file using pandas read_fwf </p>
<pre><code>data = pd.read_fwf('Users/.../file.asc', ind... | <p><strong>UPDATE2:</strong> using <code>colspecs</code> parameter when calling <code>read_fwf()</code></p>
<pre><code>In [83]: df = pd.read_fwf(fn, skiprows=6, header=None, na_values=[-999],
....: colspecs=[(5,6)] * 654)
In [84]: df.head()
Out[84]:
0 1 2 3 4 5 6 7 8 ... | python|pandas | 3 |
355,816 | 37,801,272 | Reducing the rows of a dataframe by adding observed values | <p>I have experimental data for a number of microscope slides. For each slide I have taken a number of photographic images, and on each image I have a number of specimens. I would like to know show many specimens I have for each slide:</p>
<p>eg: <strong>On slide 0, I have four specimens in total</strong> (three in im... | <p>The groupby feature allows you to essentially "pivot" the results like you would in excel:</p>
<pre><code>df = df.groupby(['Slide','Image']).Specimen.nunique()
</code></pre>
<p>The .nunique() function will give you the number of unique values per image per slide. You can then use .reset_index() on this series to c... | python|pandas|group-by | 2 |
355,817 | 37,762,275 | Ignore nested structures in numpy's array creation | <p>I want to write to a vlen hdf5 dataset, for that I am using <code>h5py.Dataset.write_direct</code> to speed up the process. Suppose I have a list of numpy arrays (e.g. given by <code>cv2.findContours</code>), and by dataset:</p>
<pre><code>dataset = h5file.create_dataset('dataset', \
... | <p>In this version</p>
<pre><code>contours_np = np.empty((len(contours),), dtype=object)
for i, contour in enumerate(contours):
contours_np[i] = contour
</code></pre>
<p>you can replace the loop with the single statement</p>
<pre><code>contours_np[...] = contours
</code></pre> | python|arrays|list|numpy | 1 |
355,818 | 37,702,825 | Select values from a set of arrays according to an array of permutations | <p>I have 3 numpy arrays of shape 2xN (with N large, a few millions), call them a1, a2, a3. Then I have another array of shape Nx3 whose row values refer to one of the arrays a1, a2, a3, call it permutations. This permutations array looks like:
[[0, 1, 2],
[1,2,0],
[1,0,2],
... up to N rows ]</p>
<p>I want to create ... | <p>With <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing" rel="nofollow"><code>fancy-indexing</code></a>, you could do -</p>
<pre><code>bb = aa[:,np.arange(N),permutations.T]
</code></pre>
<p>Please note that this would be of shape <code>(2,3,N)</code>. So,... | python|numpy|vectorization | 1 |
355,819 | 37,997,127 | Pandas Dataframe, looking for way to speed up df.apply that uses math | <p>I am using a Pandas Dataframe that has 29M rows. I am doing a computation based on four columns which are all floats.</p>
<p>This call is taking over 1100 seconds:</p>
<pre><code>df['d_from_avg'] = df.apply(lambda row: \
math.sqrt((row.x - row.avg_x)**2 + (row.y - row.avg_y)**2),axis=1)
</code></pre>
<p>Woul... | <p>You can make use of the vectorized operations instead of calculating row by row. </p>
<p>Try this:</p>
<pre><code>import numpy as np
np.sqrt((df['x'] - df['avg_x'])**2 + (df['y'] - df['avg_y'])**2)
</code></pre>
<p>It will be much faster than apply (tried it on a dataframe with 1000 rows):</p>
<pre><code>%timei... | python|performance|python-2.7|pandas|dataframe | 3 |
355,820 | 37,719,833 | how to read files from multiple folders in python | <p>my folder organization looks like below. Type 1 and Type 2 folders contains same files but I want to only read the files from 'type 2' folder. Is there any simple way to do that?</p>
<p>I have used this code but not able to read: </p>
<pre><code>for file in os.listdir('Type 2'):
print file
</code></pre>
<p><a... | <p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer"><code>read_csv</code></a> in folders <code>Type 2</code>, use <a href="https://docs.python.org/3/library/glob.html#glob.glob" rel="noreferrer"><code>glob</code></a>:</p>
<pre><code>files = glob.glob('... | python|file|pandas|dataframe|directory | 12 |
355,821 | 37,608,237 | skflow with Docker images gets learn.datasets not imported error | <p>I set the docker image with Dockerfile below.</p>
<pre><code>FROM gcr.io/tensorflow/tensorflow:latest-devel
RUN pip install --upgrade pip
RUN pip install scikit-learn
RUN pip install scipy
RUN pip install pandas
</code></pre>
<p>I am using Pycharm and set the remote Docker tf library.</p>
<p>The below file runs ... | <p>Please update your TensorFlow to latest version. That docker image is probably outdated. </p> | tensorflow|skflow | 0 |
355,822 | 37,780,057 | Explanation on Numpy Broadcasting Answer | <p>I recently posted a question <a href="https://stackoverflow.com/questions/37737368/python-list-of-lists-vs-numpy/">here</a> which was answered exactly as I asked. However, I think I overestimated my ability to manipulate the answer further. I read the broadcasting doc, and followed a few links that led me way back t... | <p>You can adjust your current code just a little bit to make it work.</p>
<pre><code>>>> out = np.zeros((4*5*10,4))
>>> out[:,:3] = (np.arange(4*5*10)[:,None]//(5*10, 10, 1)*(0.5, 0.2, 1)%(2, 1, 10))
>>> out
array([[ 0. , 0. , 0. , 0. ],
[ 0. , 0. , 1. , 0. ],
[ 0. , 0.... | python|arrays|numpy|array-broadcasting | 4 |
355,823 | 37,887,180 | pandas series add fill_value from left side only | <p>When applying an arithmetic operator via methods on a a pandas series or dataframe, you can pass an argument <code>fill_value</code> to specify how to handle missing values. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.add.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/sta... | <p>To do this from the left side's perspective:</p>
<pre><code>s1.fillna(0).add(s2)
0 2.0
1 2.0
2 NaN
dtype: float64
</code></pre>
<p>From the right:</p>
<pre><code>s1.add(s2.fillna(0))
s1.fillna(0).add(s2)
0 2.0
1 NaN
2 2.0
dtype: float64
</code></pre>
<p>From both:</p>
<pre><code>s1.fillna(0... | python|pandas | 1 |
355,824 | 37,885,882 | How do I optimize a pandas apply lambda that looks at all records? | <p>I have a dataframe that looks like this:</p>
<pre><code>ID YEAR AMOUNT
1 | 2001 | 4340
1 | 2002 | 5460
1 | 2004 | 1245
1 | 2006 | 6000
2 | 2003 | 5000
2 | 2006 | 3059
....
</code></pre>
<p>I would like to add a column that computes the highest amount thus far, as in:</p>
<pre><code>ID YEAR AMOUNT A... | <p>Use <code>cummax</code></p>
<pre><code>df['AMT_MAX'] = df.groupby('ID').AMOUNT.cummax()
</code></pre> | python|pandas|optimization|dataframe | 4 |
355,825 | 37,632,102 | Tensorflow: Trouble re-opening queues after restoring a session | <p>I have a trained model I'm trying to evaluate on a separate dataset, and I'm having trouble with my input pipeline. After restoring the session, and attempting to load the first batch of validation data, the following error is thrown:</p>
<pre><code>tensorflow.python.framework.errors.OutOfRangeError: FIFOQueue '_2_... | <p>Try replacing </p>
<pre><code>saver = tf.train.Saver()
</code></pre>
<p>with </p>
<pre><code>saver = tf.train.Saver( tf.trainable_variables() )
</code></pre>
<p>That did it for me. I stand by my explanation in the comment. You need to avoid restoring the queue(input_producer) states. I also had to append non-tra... | machine-learning|tensorflow | 1 |
355,826 | 37,734,413 | Pandas series - only keep value if index month is in [1,2,3] | <p>I have a pandas.Series() object and I am trying to filter the data based on the month in the index. Here is an example Series object (index is ["2010-01-01", "2010-02-01", ..., "2016-06-01"]):</p>
<pre><code>d = pd.Series(1, pd.date_range("20100101", periods=100, freq="MS"))
</code></pre>
<p>I would like to keep o... | <p>try:</p>
<pre><code>d.loc[pd.Series(d.index.month, d.index).isin([1, 2, 3])]
</code></pre> | python|numpy|pandas|scipy | 2 |
355,827 | 38,000,180 | Save tensorflow model to file | <p>I create a tensorflow model which I would like to save to file so that I can predict against it later. In particular, I need to save the: </p>
<ul>
<li>input_placeholder<br>
(<code>= tf.placeholder(tf.float32, [None, iVariableLen])</code>)</li>
<li>solution_space<br>
(<code>= tf.nn.sigmoid(tf.matmul(input_placeho... | <p>The way I solved this was by <a href="https://wiki.python.org/moin/UsingPickle" rel="noreferrer">pickleing</a> Sklearn objects like binarizers, and using <a href="https://www.tensorflow.org/versions/r0.9/how_tos/variables/index.html#saving-and-restoring" rel="noreferrer">tensorflow's inbuilt save functions</a> for t... | python-2.7|tensorflow|pickle | 12 |
355,828 | 38,053,687 | Access last elements of inner multiindex level in pandas dataframe | <p>In a <code>multi index</code> pandas dataframe I want to access the <strong>last</strong> element of the second index for all values of the first index. The number of levels in the second index vary depending on the value of the first index. I went through the <a href="http://pandas.pydata.org/pandas-docs/stable/adv... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.tail.html" rel="noreferrer"><code>tail</code></a>:</p>
<pre><code>print (df.grou... | python|pandas|indexing|dataframe|multi-index | 13 |
355,829 | 37,866,998 | Pattern search in pandas.dataframe.query() | <p>I have the following dataframe:</p>
<pre><code>----------------------------
Index| col1 | col2 |
----------------------------
0 | 1 | a-b-c
1 | 2 | d-e-f
2 | 3 | g
----------------------------
</code></pre>
<p>I want to be able to make queries like:</p>
<pre><code>myvar= 'a'
df.query('@myvar ... | <p>A bit overkill for what the OP needs but this post shows up first in search results for regex matching in <code>df.query()</code> which can be done with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.match.html" rel="nofollow noreferrer"><code>Series.str.match</code></a>:</p>
<pre class="lan... | python|pandas|pattern-matching | 3 |
355,830 | 37,715,316 | gdal_calc amin fails when passing more than 23 input files | <p>I've written an R function that calls <code>gdal_calc.py</code> to calculate the pixel-wise minimum value across a <code>RasterStack</code> (series of input raster files). I've done this because it's much faster than <code>raster::min</code> for large rasters. The function works well for up to 23 files, but throws a... | <p>The issue you were running into was that the <code>X</code> variable from the <code>calc</code> input was colliding with the variable created by a loop in the <code>doit</code> function:</p>
<pre><code>for X in range(0,nXBlocks):
</code></pre>
<p>It appears this has already been fixed by the gdal developers (in no... | python|r|numpy|raster|gdal | 2 |
355,831 | 37,709,960 | Python: Using Pandas, how do I choose the columns in my output? | <p>I am running my whole Active directory against user accounts trying to find what doesn't belong.
Using my code my output gives me the words that only occur once in the Username column. Even though I am analyzing one column of data, I want to keep all of the columns that are with the data. </p>
<pre><code>from ... | <p>Based on your description, I guess you want to use the counts of unique elements as index to select rows in your dataframe. Maybe you can try this:</p>
<pre><code>df2 = pd.DataFrame()
counts = f['User Name'].value_counts()
counts = counts[counts == 1].index
for index in counts:
df2 = df2.append(f[f['User Na... | python|python-3.x|pandas|ipython|jupyter-notebook | 1 |
355,832 | 37,710,387 | universal inner product of pandas.Series AND columns in a pandas.DataFrame | <p>I'm trying to build a function that computes the conditional Shannon entropy in a dataframe. I give it the following parameters:</p>
<pre><code>import random
rows = 1000
columns = 3
data=pd.DataFrame([[random.randrange(0, 4, 1) for x in range(columns)] for y in range(rows)], columns=['a', 'b', 'c'])
target = ['a',... | <p>Ok, I figured it out. Following @BrenBarn's advice I tracked the use of DataFrames and Series. </p>
<p>The problem I was having with the case <code>type(entropy)==Series</code>, (when there is just one column, <code>target=['a']</code>), is due to unexpected behavior of the <code>apply</code> function in line <code... | python|pandas | 1 |
355,833 | 37,623,419 | Extract specific bytes from a binary file in Python | <p>I have very large binary files with x number of int16 data points for y sensors, along with headers with some basic info. The binary file is written as y values for each sample time up to x samples, then another set of readings and so on. If I want all of the data, I am using <code>numpy.fromfile()</code> which work... | <p>I would definitely try <code>mmap()</code>:</p>
<p><a href="https://docs.python.org/2/library/mmap.html" rel="nofollow noreferrer">https://docs.python.org/2/library/mmap.html</a></p>
<p>You're reading a lot of small bits which has a lot of <a href="https://stackoverflow.com/questions/23599074/system-calls-overhead... | python|numpy|mmap|seek|fromfile | 6 |
355,834 | 37,684,059 | Python-performance-print large numpy array as strings to tab file | <p>I recently had <a href="https://stackoverflow.com/questions/37618611/compare-two-different-size-matrices-to-make-one-large-matrix-speed-improvement/37621374#37621374">this</a> post, where I was assisted in making a big matrix from two smaller matrices. The resulting matrix is correct and creating the multplied nump... | <p>For text output there's also the Numpy array <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html" rel="nofollow"><code>tofile</code></a> method. Here's a quick benchmark:</p>
<pre><code>import numpy as np
data = np.random.randint(49, size=(55000))
f = open('test.txt', 'w')
print... | python|arrays|numpy|matrix | 1 |
355,835 | 37,707,045 | Segmentation Fault: 11 on OSX python | <p>I'm getting an intermittant segfault in python, which really shouldn't happen. It's a heisenbug, so I haven't figured out exactly what's causing it.</p>
<p>I've done the search and found that there was a known problem with an older version of python, but I'm using 2.7.10 (in a virtualenv, in case that matters)</p>
... | <p>It looks like: <a href="https://stackoverflow.com/questions/9412156/how-to-generate-core-dumps-in-mac-os-x">How to generate core dumps in Mac OS X?</a></p>
<p>might be the best way to get stack trace...it appears in ~/Library/Logs/DiagnosticReports I'm not sure if it's USEFUL, and it's not a core per se, to be put ... | python|macos|numpy|pandas|scipy | 0 |
355,836 | 31,463,739 | Python: create category based on values in two arrays | <p>Say I have two lists:</p>
<pre><code>arrayA = np.array([3,4,1,2,5,6,8,6,3])
arrayB = np.array([4,2,5,6,1,3,6,5,3])
</code></pre>
<p>which basically represents a point in 2D.</p>
<p>I want to get a label list that looks like:</p>
<pre><code>listLael = [type1,type2,type1,type2,...]
</code></pre>
<p>that have the ... | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>>>> np.where((arrayA >= 5) & (arrayB >= 5), 'type1', 'type2')
array(['type2', 'type2', 'type2', 'type2', 'type2', 'type2', 'type1',
'type1', 'type2... | python|arrays|numpy|label | 2 |
355,837 | 31,458,794 | python: using .iterrows() to create columns | <p>I am trying to use a loop function to create a matrix of whether a product was seen in a particular week.</p>
<p>Each row in the df (representing a product) has a close_date (the date the product closed) and a week_diff (the number of weeks the product was listed).</p>
<pre><code>import pandas
mydata = [{'subid' :... | <p>You can't mutate the df using <code>row</code> here to add a new column, you'd either refer to the original df or use <code>.loc</code>, <code>.iloc</code>, or <code>.ix</code>, example:</p>
<pre><code>In [29]:
df = pd.DataFrame(columns=list('abc'), data = np.random.randn(5,3))
df
Out[29]:
a b ... | python|pandas | 59 |
355,838 | 31,409,620 | how to add specific row and columns from pandas | <p>I have a data set like below but when i tried to sum column it will sum from the year. what i want is sum from Jan to Dec.</p>
<p>the code which i tried is<code>data.sum(axis=0)</code></p>
<pre><code>Out[64]:
year Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
0 1981 32 26 62 22 23 ... | <p>Filter the columns first and then <code>sum</code>:</p>
<pre><code>In [274]:
df[df.columns[1:]].sum(axis=0)
Out[274]:
Jan 594
Feb 372
Mar 578
Apr 415
May 622
Jun 738
Jul 895
Aug 1129
Sep 874
Oct 721
Nov 687
Dec 670
dtype: int64
</code></pre>
<p>If you want to sum row... | pandas|dataframe | 0 |
355,839 | 31,359,810 | Rearrange dataframe using python | <p>I have a dataset that looks like this:</p>
<pre><code> Category Date_x Value_x Date_y Value_y
A 01/01/2015 3 02/01/2015 5
B 01/01/2015 6 02/01/2015 10
C 01/01/2015 7 02/01/2015 5
</code></pre>
<p>Using Pytho... | <p>It seems as though you merged or concatenated two dataframes with date, value and category columns on the horizoontal axis. In that case you should go back a step and concatenate them on the vertical axis. If not, assuming the index is <code>'Category'</code>, you can do</p>
<pre><code>df_1 = df[['Date_x', 'Value_... | python|pandas | 1 |
355,840 | 31,595,704 | How to store a large, sparse, multidimensional table with where cells contain a varying number of elements? | <p>I have a large, sparse, multidimensional lookup table, where cells contain arrays varying in size from 34 kB to circa 10 MB (essentially one or more elements stored in this bin/bucket/cell). My prototype has dimensions of 30**5=24,300,000, of which only 4,568 cells are non-empty (so it's sparse). Prototype non-emp... | <p>From what I understand, you might want to look at the amazing <a href="http://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a> package, as it has a specific facility for the <a href="http://pandas.pydata.org/pandas-docs/stable/sparse.html" rel="nofollow noreferrer">sparse data structure</a> you've described.... | python|database|numpy|multidimensional-array|data-structures | 0 |
355,841 | 31,260,151 | Python Pandas Dataframe to XML | <p>would appreciate some assistance or push in the right direction. I have a pandas dataframe, from a txt file, and would like to insert it in an xml doc I'm making. I can set up the xml doc, and convert my dataframe to xml using: <a href="https://stackoverflow.com/questions/18574108/how-do-convert-a-pandas-dataframe-t... | <p>First of all get rid of the <code>Series</code> tags in your <code>to_xml</code> method:</p>
<pre><code>def to_xml(df, filename=None, mode='w'):
def row_to_xml(row):
date = row.TIMESTAMP.split()[0]
time = row.TIMESTAMP.split()[1]
value = row.A
xml = '<event date="{0}" time="{1... | python|xml|pandas | 1 |
355,842 | 31,245,043 | Using matplotlib/pandas/python, I cannot visualize data as values per 30mins and per days | <p>I am analysing a CSV file with Matplotlib/Python.</p>
<p>This is the CSV file.
<a href="https://github.com/camenergydatalab/EnergyDataSimulationChallenge/blob/master/challenge2/data/total_watt.csv" rel="nofollow noreferrer">https://github.com/camenergydatalab/EnergyDataSimulationChallenge/blob/master/challenge2/dat... | <p>Using <code>pandas</code> and the <code>resample</code> function could make your life easier.</p>
<h3>Data</h3>
<pre><code>import io
import pandas as pd
content = '''timestamp value
2011-04-18 16:52:00 152.684299188514
2011-04-18 17:22:00 327.579073188405
2011-04-18 17:52:00 156.826945856169
2011-04-1... | python|csv|pandas|matplotlib | 3 |
355,843 | 31,655,634 | Pandas Groupy take only the first N Groups | <p>I have some DataFrame which I want to group by the ID, e. g.:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'item_id': ['a', 'a', 'b', 'b', 'b', 'c', 'd'], 'user_id': [1,2,1,1,3,1,5]})
print df
</code></pre>
<p>Which generates:</p>
<pre><code> item_id user_id
0 a 1
1 a 2
2 ... | <p>Here is one way using <code>list(grouped)</code>.</p>
<pre><code>result = [g[1] for g in list(grouped)[:3]]
# 1st
result[0]
item_id user_id
0 a 1
1 a 2
# 2nd
result[1]
item_id user_id
2 b 1
3 b 1
4 b 3
</code></pre> | python|pandas|pandas-groupby | 22 |
355,844 | 31,463,617 | Appending rows onto a numpy matrix | <p>I'm trying to append a 4x1 row of data onto a matrix in python. The matrix is initialized as empty, and then grows by one row during each iteration of a loop until the process ends. I won't know how many times the matrix will be appended, so initializing the array to a predetermined final size is not an option unfor... | <p>As @hpaulj suggested you should use a list of lists and then convert to a NumPy matrix at the end. This will be <strong><a href="https://stackoverflow.com/questions/29839350/numpy-append-vs-python-append">at least 2x faster</a></strong> than building up the matrix using np.r_ or other NumPy methods </p>
<pre><code... | python|numpy|matrix|append|row | 0 |
355,845 | 64,591,676 | plt.bar is returning error " 'value' must be an instance of str or bytes, not a float " eventhoguh I am giving str | <p>Similar questions have been asked before but I couldn't find my answer. I am trying to print a plt.bar with car accident data from every state.
My code:</p>
<pre><code>severity_1 = []
severity_2 = []
severity_3 = []
severity_4 = []
for i in df.State.unique():
severity_1.append(df[(df['Severity']==1)&(df['Sta... | <p>It's easier for people to answer if you share a minimal working example. In this case I downloaded the data set and read it using pandas (which I believe is the same as you did).</p>
<p>I did not receive the same error (see below).</p>
<p>Try splitting up your code for making the different severity lists. Put every ... | python|pandas|matplotlib | 1 |
355,846 | 64,580,583 | Python copy data from 1 df to first matching row in other df | <p>Basically I got a df1 that looks like this:</p>
<pre><code> Ticker Date
0 AAPL 20200501
1 AAPL 20200501
2 AAPL 20200502
3 AAPL 20200502
4 TSLA 20200501
5 TSLA 20200501
6 TSLA 20200502
7 TSLA 20200502
</code></pre>
<p>and a df2 that looks like this:</p>
<pre><code> Ticker Date Com... | <p>You can use <code>merge</code> to map the <code>Comm.</code> column, then <code>mask</code> to place <code>0</code> where the values are duplicated:</p>
<pre><code>df1['Comm.'] = (df1.merge(df2, on=['Ticker','Date'], how='left')
['Comm.']
.mask(df1.duplicated(['Ticker','Date']),... | python|python-3.x|pandas | 2 |
355,847 | 64,267,308 | How to add value in a column in pandas? | <p>I've one Dataframe</p>
<pre><code>import pandas as pd
data = {'a': [1,2,3,None,4,None,2,4,5,None]}
df = pd.DataFrame(data)
print(df)
a
0 1.0
1 2.0
2 3.0
3 NaN
4 4.0
5 NaN
6 2.0
7 4.0
8 5.0
9 NaN
</code></pre>
<p>i want to add the value till NaN comes, Once it will get the NaN then it will s... | <p>Using <code>cumsum</code> create the <code>groupby</code> key then <code>transform</code> with <code>mask</code></p>
<pre><code>df.a.groupby(df.a.isnull().cumsum()).transform('sum').mask(df.a.isnull())
0 6.0
1 6.0
2 6.0
3 NaN
4 4.0
5 NaN
6 11.0
7 11.0
8 11.0
9 NaN
Name: a, dtype:... | pandas|dataframe|python-3.7 | 3 |
355,848 | 64,516,488 | dataframe: do comparison of values within groups | <p>INPUT DATA:</p>
<pre><code>data = {'G1': ['a', 'a', 'a', 'a', 'a', 'b', 'b'], 'G2': ['b', 'b', 'c', 'c', 'd', 'c', 'c'], 'V1': [5, 15, 10, 20, 5, 10, 10], 'V2': [15, 5, 300, 10, 5, 10, 10]}
| G1 G2 V1 V2
-- + -- -- -- ---
0 | a b 5 15
1 | a b 15 5
2 | a c 10 300
3 | a c 20 10
... | <p>Probably not the best performance wise, but here is one way using a custom function using <code>np.diag</code>:</p>
<pre><code>def func(arr):
arr = arr.to_numpy()
if len(arr)<2: return pd.DataFrame([[np.NaN, np.NaN]])
x, y = np.diag(arr), np.diag(np.fliplr(arr))
return pd.DataFrame([[np.all(x==x[0... | python|pandas|group-by|datatable|comparison | 1 |
355,849 | 64,268,386 | Extract Multiple Columns from Dataframe and Return NaN for Columns that do not Exist | <p>I am trying to extract multiple columns from a data frame such as below. I want to identify the columns needed by calling their names and return NaN for columns that do not exist in the data frame.</p>
<pre class="lang-py prettyprint-override"><code>data_1 = {'host_identity_verified':['t','t','t','t','t','t','t','t'... | <p>Using the <code>reindex</code> function will create <code>naan</code> columns and extract the columns you need:</p>
<pre class="lang-py prettyprint-override"><code>df_1.reindex(['host_identity_verified', 'neighbourhood', 'latitude', 'longitude', 'price'], axis=1)
</code></pre> | python|pandas|extract | 1 |
355,850 | 64,268,579 | Group by Consecutive Dates and Rank | <p>I have a dataframe like this, and I want to create a new column called 'Rank' group by barcode and date with date condition must be either same days or have consecutive dates and it must go to Step C for each barcode. For example, Barcode B have the same date, but because it goes to step C again so its rank should b... | <p>You can do this by grouping and using <code>cumcount()</code></p>
<pre><code>df = df.sort_values(['Barcode', 'Date'])
df['Rank'] = df.groupby(['Barcode', 'Step']).cumcount() + 1
df
</code></pre>
<p>Gives you:</p>
<pre><code>Date Barcode Step Value Rank
2014-03-04 A C 2 1
2014-03-04 A D 4 1
... | python|pandas|date | 0 |
355,851 | 64,554,782 | Calculating daily difference for 15 minutes data in pandas | <p>I have a huge dataframe of open and close prices recorded every 15 minutes of the day. The day starts at 9:45 and ends at 16:15. My current df looks like this:</p>
<pre><code> open_p close_p
date
2013-12-20 09:45:00 -1.14 -1.12
2013-12-20 10:00:00 -1.12 ... | <p>You can <code>groupby</code> on date, <code>agg</code> on first and last, then find the difference:</p>
<pre><code>print (df.groupby(pd.Grouper(freq="D"))
.agg({"open_p":"first", "close_p":"last"})
.diff(axis=1)["close_p"])
date
2013-12-2... | python|python-3.x|pandas | 1 |
355,852 | 64,358,928 | python, sum of value from several rows | <p>I have hundreds of csv files like the follows:</p>
<p><a href="https://i.stack.imgur.com/aJUMk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aJUMk.png" alt="enter image description here" /></a></p>
<p>What I want to do it to calculate the sum of each row for columns <code>A_*</code>and <code>B_*... | <p>You can use <code>filter</code>:</p>
<pre><code>ret_df = pd.DataFrame()
ret_df['A_sum'] = df.filter(like='A_').sum(1)
ret_df['B_sum'] = df.filter(like='B_').sum(1)
</code></pre>
<p>Or use regex, and also a loop:</p>
<pre><code>for type in ['A','B']:
df[f'{type}_sum'] = df.filter(regex=f'^{type}_').sum(1)
</code... | python|pandas|dataframe|csv | 2 |
355,853 | 64,478,279 | numpy: How can I use matrix elements as index? | <p>I have a numpy matrix of integers whose elements represent indices. I would like to create a matrix of the same size whose elements are taken from a list at the respective index.</p>
<pre><code>import numpy as np
matrix = np.array([[0, 1, 1], [2, 0, 1]], dtype=int)
matrix
# array([[0, 1, 1],
# [2, 0, 1]])
... | <p>Ok, I just found out I works as expected when <code>values</code> is also an <code>np.ndarray</code> instead of a list.
So this works:</p>
<pre><code>import numpy as np
matrix = np.array([[0, 1, 1], [2, 0, 1]], dtype=int)
matrix
# array([[0, 1, 1],
# [2, 0, 1]])
values = np.array([7, 8, 9])
values[matrix]... | python|numpy|indexing | 2 |
355,854 | 64,558,862 | Optimisation of a numerical model with several data sets (scipy.minimize / scipy.optimise, pymoo or ??) | <p>So I have a problem and I'm a little bit lost at this point. So any input would be greatly appreciated, as I'm really struggling right now!</p>
<p>I have a model I want to check/optimise using some experimental data I got.</p>
<p>Generally speaking, my model takes two inputs (let's call say: time and temperature) an... | <p>The basic idea of a shared object function is fine. I don't really go into details of the OP attempts, as this might be misleading. The process would be to define a proper residual function that can be used in a least square fit. There are several possibilities in Python to do that. I'll show <code>scipy.optimize.le... | python|numpy|optimization|scipy|data-fitting | 2 |
355,855 | 64,396,430 | How to fetch failing rows in dataframe.to_sql? | <p>I am executing below code -</p>
<pre><code>try:
dataset.to_sql(name=schema.lower(), con=conn, if_exists='append', index=False)
except Exception as ex:
print("Data cannot be processed - ", ex)
exit(1)
</code></pre>
<p>This works really well if dataframe has valid rows.
But, if the... | <p>Without any feasible solution, I used Pandas schema to validate data before pitching into database</p>
<p><a href="https://tmiguelt.github.io/PandasSchema/" rel="nofollow noreferrer">Here</a> is the doc for Pandas schema. This solved my problem upto an extent.</p> | pandas|dataframe | 1 |
355,856 | 64,612,081 | How to work with `numpy.timedelta64` outside of pandas/numpy? | <p>From a pandas DataFrame, when I extract the value of a specific <code>timedelta</code> field, I receive an object of type <code>numpy.timedelta64</code>:</p>
<pre><code>>>> numpy_delta
numpy.timedelta64(-2700000000000,'ns')
</code></pre>
<p>I understand that this is numpy's representation for "-2700000... | <p>When working with <code>datetime64</code> dtype arrays, <code>tolist()</code> or <code>item()</code> do a good job of converting the array to base Python objects. Let's try that with your timedelta:</p>
<pre><code>In [174]: x=np.timedelta64(-2700000000000,'ns')
In [175]: x.item()
Out[175]: -2700000000000
</code></p... | python|numpy | 0 |
355,857 | 64,286,204 | How do I fix this ImportError in Jupyter Notebook? | <p>I need to use pandas for my project and whenever I write:</p>
<pre><code>import pandas as pd
</code></pre>
<p>this error comes up:</p>
<pre><code>ImportError: cannot import name 'infer_dtype_from_scalar' from partially initialized module 'pandas.core.dtypes.cast' (most likely due to a circular import) (C:\Users\Soor... | <p>Try <code>pip uninstall pandas</code> and <code>pip install pandas</code> then try to import it again.</p> | python|pandas|windows|jupyter-notebook|importerror | 0 |
355,858 | 64,386,238 | How to change bitrate of a video using opencv python library | <p>I have to create a application in which I need to read a video and lower its bitrate to decrease the size of video.</p> | <p>Yes. You have to build OpenCV with the GStream Libraries, then you can do this for example:</p>
<pre><code>cv2.VideoWriter("appsrc ! videoconvert ! avenc_mpeg4 bitrate=100000 ! mp4mux ! filesink location=video.mp4", cv2.CAP_GSTREAMER, 0, 20.0, (1280,720))
</code></pre> | python|tensorflow|opencv|video-encoding|bitrate | 0 |
355,859 | 64,190,759 | Implementing numpy.roll on a flattened array | <p>I am trying to generalize my 2d Ising Model (with periodic boundary conditions) simulator to be Nd as a personal project.</p>
<p>As a quick recap to what that is, please refer to this wiki-page (since Latex rendering is not supported on Stack Overflow) <a href="https://en.wikipedia.org/wiki/Ising_model" rel="nofollo... | <p>I think I have a decent answer. For starters, a flattened nd array has indices associated with the following index formula:</p>
<pre><code># index = (Ny*Nx)*nz + (Nx)*ny + nx
# spin_config.strides / spin_config.itemsize = (Ny*Nx, Nx, 1)
</code></pre>
<p>Issues near the boundary occur whenever <code>nj = Nj-1</code> ... | python|numpy-ndarray|numba|numpy-slicing | 0 |
355,860 | 64,470,539 | Custom loss issues in tensorflow | <p>I try to implement a custom loss function. The goal of the loss function is to minimize:
loss = max(y_actual,y_predicted)/min(y_actual, y_predicted)</p>
<p>The whole script looks like:</p>
<pre><code>def get_model():
model = Sequential()
model.add(Dense(512, activation = 'relu', input_dim = len(X[0])))
m... | <p>The reason of the error is that you are passing a list to tf.keras.backend.Mean, yet the function requires a tensor.</p>
<p>Firstly I believe you need to transform that list to a tensor, with a certain dtype.</p> | tensorflow|keras|loss-function | 1 |
355,861 | 64,379,339 | CIFAR10 dataloader sampler split | <p>i am trying to split the training data of CIFAR10 so the last 5000 of the training set is used for validation. my code</p>
<pre><code>size = len(CIFAR10_training)
dataset_indices = list(range(size))
val_index = int(np.floor(0.9 * size))
train_idx, val_idx = dataset_indices[:val_index], dataset_indices[val_index:]
tr... | <p>I cannot replicate your results, when I execute your code, the print statements outputs twice the same number : the number of elements in <code>train_CIFAR10</code>. So I guess you made a mistake when copying your code, and <code>valid_dataloader</code> is actually given <code>CIFAR10_test</code> (or something like ... | python|numpy|machine-learning|pytorch | 0 |
355,862 | 64,523,957 | Filter Pandas Groupby monotonically | <p>Let's say I have a Dataframe of values like this:</p>
<pre><code>df = pd.DataFrame([ [ 23, .30], [ 23, .29], [ 23, .33], [ 23, .29], [ 23, .31], [ 25, .31], [ 25, .32], [ 25, .22], [30, 0.9], [30, 0.91], [30, 0.92] ], columns=['Day', 'Rate'] )
</code></pre>
<p>I want to group by Day but only filter out the values th... | <p>THe new "Rate" can be obtained by <code>groupby-cummax</code>. Just replace Rate with the new values and drop duplicates. <code>.reset_index()</code> is optional.</p>
<pre><code>df["Rate"] = df.groupby("Day").cummax()
df = df.drop_duplicates().reset_index(drop=True)
</code></pre>
<p>Out... | python|pandas | 1 |
355,863 | 64,234,348 | Label sequences by group in Pandas | <p>I have the following dataframe :</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'ID_1' : ['i1','i1','i1','i1','i1','i1','i1','i1'],
'ID_2' : ['a1','a1','a1','a1','a2','a2','a2','a2'],
'label':['a','b','b','a','a','a','a','b']})
</code></pre>
<p>I would like to get an... | <p>Try this. I think you were close; use <code>groupby</code> and <code>transform</code> with your logic:</p>
<pre><code>df['seq_id'] = df.groupby(['ID_1', 'ID_2'])['label']\
.transform(lambda x: (x != x.shift()).cumsum())
</code></pre>
<p>Output:</p>
<pre><code> ID_1 ID_2 label seq_id
0 i1 a1 ... | python|pandas|dataframe|pandas-groupby | 1 |
355,864 | 64,528,645 | How to use @app.callback input value for creating dataframe and displaying it as table | <p>I am trying to create an app to calculate a refrigeration cycle. I managed to just display my results, but I am having trouble integrating user inputs.</p>
<p>At this point all I want to achieve is the following:</p>
<ul>
<li>User Input: Number</li>
<li>Number from input is used in cycle calculation</li>
<li>A dataf... | <p>You should change your output from the callback to <code>df.to_dict(orient='records')</code>. You cannot pass the <code>df</code> directly into the Dash datatable, which is what the error is telling you. It will work as a <code>dict</code> object, though. You may also want to set a default value for the <code>data</... | python|pandas|plotly-dash | 1 |
355,865 | 64,327,731 | Model plotted not clear with plot_model | <p>When <code>tensorflow</code> version <code>2.3.0</code> is used it gives unclear output model, how to resolve it?</p>
<pre><code>import tensorflow as tf
base_model = tf.keras.applications.EfficientNetB7(weights='imagenet', include_top=False) # or weig
tf.keras.utils.plot_model(base_model, to_file="image1.png&... | <p>So the issue is, that the model you try to output as image is a <strong>HUGE</strong> one. So <code>dpi=120</code> is barely enough in PNG format. In order to get a clearer image save it as a PDF. Then you can easily transform to image if you wish.</p>
<p>Using the follows:</p>
<pre><code>import tensorflow as tf
ba... | python|python-3.x|tensorflow|tensorflow2.0 | 1 |
355,866 | 64,359,327 | Compare new values to previous values and flag if not the same within Excel (Using Python) | <p>I have a dataframe, df, within Excel that contains values that I wish to compare to previous values. If the current value does not compare to the previous value, I wish to highlight the cell within excel.</p>
<p>This is my data:</p>
<pre><code>COL1 match
9 1 False
8 3 False
2 2 True
3 1 False
4... | <p>This is the code to set background to a cell</p>
<pre><code>cell_format = workbook.add_format()
cell_format.set_pattern(1) # This is optional when using a solid fill.
cell_format.set_bg_color('green')
for index, row in df.iterrows():
if row.COL1 == row.match:
worksheet.write("B"+str(index+1),... | python|excel|pandas|numpy | 1 |
355,867 | 64,498,273 | If loop for a dictionary of pandas dataframes | <p>I have a dictionary of dataframes. I defined the dict as range_, such that when I need a certain dataframe, I can call it range_[i].</p>
<p><a href="https://i.stack.imgur.com/OQDqE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OQDqE.png" alt="enter image description here" /></a></p>
<p>For every... | <p>That happens when you try to access an index that does not exist in the DF.</p>
<p>If you are sure that all the data frames have at least 10 rows, then this should work. If you still get this error, it means that one of the DataFrames has less than 10 rows. Thus your rule for determining the faultiness is invalid.</... | python|pandas|dictionary | 1 |
355,868 | 64,426,428 | Unable to run TensorFlow | Load images example (process_path error) | <p>I am trying to run the following tutorial from TF: <a href="https://www.tensorflow.org/tutorials/load_data/images" rel="nofollow noreferrer">Load images</a>.</p>
<p>I am running the <em>second method</em> (<strong>Using tf.data for finer control</strong>).</p>
<p>The provided tutorial runs fine up to using <code>Dat... | <p>Seems like you can't use argmax on boolean tensors. You can instead do the one hot encoding manually. Just make sure to define <code>n_classes</code>.</p>
<pre><code>def get_label(file_path):
parts = tf.strings.split(file_path, os.path.sep)
bool_values = tf.equal(parts[-2], class_names)
indices = tf.wher... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
355,869 | 64,426,074 | Extending dimensions | <p>Loading data from tensorflow returns ndarry <code>(x_train, y_train), (x_test, y_test)</code> where the data is of shape <code>(num_samples, 3, 32, 32)</code> I want to extend this shape to include another dimension to have something of <code> [num_classes, num_samples, im_height, im_width, im_channels].</code></p... | <p>You can't reshape because the total number of elements is different.</p>
<p>You need to create a new array and copy the data in whatever pattern you need. For example:</p>
<pre><code>new_x_train = np.empty((100, 50000, 32, 32, 3), x_train.dtype)
new_x_train[:] = x_train # 100 copies of x_train using broadcasting
</... | numpy|tensorflow|keras|multidimensional-array|tensor | 0 |
355,870 | 64,409,191 | Angle between two vectors in the interval [0,360] | <p>I'm trying to find the angle between two vectors.<br />
Following is the code that I use to evaluate the angle between vectors <code>ba</code> and <code>bc</code></p>
<pre><code>import numpy as np
import scipy.linalg as la
a = np.array([6,0])
b = np.array([0,0])
c = np.array([1,1])
ba = a - b
bc = c - b
cosine_an... | <p>Conceptually, obtaining the angle between two vectors using the dot product is perfectly alright. However, since the angle between two vectors is invariant upon translation/rotation of the coordinate system, we can find the angle subtended by each vector to the positive direction of the x-axis and subtract one value... | python|numpy | 4 |
355,871 | 64,249,597 | How to convert Pandas Data frame to python dictionary? | <p>I have a Pandas data frame & I need to convert it to list of dictionaries but when I use <code>df.to_dict()</code>, i'm not getting what I expected.</p>
<pre><code>Data Frame:
Name Class School
0 Alex 4 SVN
1 Julie 4 MSM
</code></pre>
<p>After using <code>df.to_dict()</code>,</p>
<pre><c... | <p>Try this: <code>df.T.to_dict().values()</code> instead of <code>df.to_dict()</code>:</p> | python|pandas|dataframe|dictionary | 2 |
355,872 | 64,231,735 | How to put a numpy array in a specific position of another numpy array | <p>I am doing linear interpolation and the formula is y = y0 + (x - x0) * ((y1 - y0)/(x1 - x0)). My points are</p>
<pre><code>
a = np.array([[9, 0],
[11, 7],
[18, 14],
[38, 31],
[43, 36],
[67, 59]])
</code></pre>
<p>For example: let's take x0 = 18, y0 = 14, x1 = 38, y1 = 31. So for every v... | <p>Inserting an item in an array its a little time consuming task. Every time you insert an item in a certain position all the items after has to be moved by one step. So potentially this operation could be <code>O(n^2)</code>.</p>
<p>You could insert the items at the end (so no previous item in the array has to be mov... | python|arrays|numpy | 0 |
355,873 | 64,363,609 | For Looping through Numpy array gives error | <p>I'm new to python and not understanding why this for loop won't work.</p>
<pre><code>i = np.random.uniform(0,1,100)
# this does not give error
print(i[0])
print(i[1])
print(i[2])
# this gives error
for x in i:
print( i[x] )
</code></pre>
<p>I figure it's something to do with the line <code>for x in i:</code>.... | <p>In <code>for x in i:</code>, <code>x</code> will be every elements in <code>i</code>. So your loop statement should be</p>
<pre><code>for x in i:
print( x )
</code></pre>
<p>If you want <code>x</code> to be the index, you should use the following code so that <code>x</code> would be from 0 to the len(i)-1 (all ... | python|numpy|for-loop | 1 |
355,874 | 64,489,722 | Increasing range in np.arange by 1 increases range by 2 instead | <p>I'm not sure if this is a bug or if I'm doing something wrong. I've got the following code:</p>
<pre><code>r_div = 200
r_max = 1.4
numMax=.84
lowerBin = int((numMax - .2)/(r_max/r_div))
upperBin = int((numMax + .2)/(r_max/r_div))
k =np.arange((r_max/r_div)*lowerBin,(r_max/r_div)*(upperBin+1),r_max/r_div)
</code></... | <p>From <code>arange</code> docs:</p>
<pre><code>arange([start,] stop[, step,], dtype=None)
....
When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `numpy.linspace` for these cases.
</code></pre> | python|numpy | 1 |
355,875 | 64,343,663 | Fast way to calculate min distance between two numpy arrays of 3D points | <p>I would like to know if there is a fast way to calculate Euclidian distance between all points of a 3D numpy array (<code>A [N,3]</code>) to all points of a second 3D numpy array (<code>B [M,3]</code>).</p>
<p>I should then get an array <code>C</code> which would be <code>[N, M]</code> with all distances from points... | <p>If the scipy method doesn't work or if you do have other reasons, here is a numpy way-</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
x = np.random.random((200, 3))
y = np.random.random((100,3))
x = x.reshape((-1, 1, 3)) # [200x1x3]
y = np.expand_dims(y, axis=0) ... | python|arrays|numpy|distance | 0 |
355,876 | 64,519,757 | RuntimeWarning: invalid value encountered in multiply, RuntimeWarning: divide by zero encountered in log | <p>While training for word vectors I'm facing the following runtime problems in between my epoch.</p>
<pre><code>/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:12: RuntimeWarning: divide by zero encountered in log
if sys.path[0] == '':
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:12: Run... | <p>I'm guessing this is occurring because you have a class in your word vector model that has a frequency of 0. And, as @CJR said, if you take the log of zero, you will get NaN.</p>
<p>I would recommend debugging this by first checking your class frequencies across your dataset, and seeing if anything looks out of the... | python|numpy|nlp|nan | 0 |
355,877 | 64,390,923 | Extract Location Coordinates from JSON results | <p>I am using geocodio to derive coordinates from a list of 2272 addresses from my dataframe. When I try to flatten the results using json_normalize, I get coordinates but my dataframe is 4800+ rows instead of the correct 2272 for each address.</p>
<pre><code>import json
from pandas.io.json import json_normalize
a... | <p>The idea is to go down your dictionary. Like this:</p>
<pre><code>import json
data = json.loads('{"a":{"b":{"location": {"lat": 35.507996, "lng": -97.52952}}}}')
data = data["a"]["b"]["location"]
print(data)
</code></pre> | python|json|pandas|geocoding | 0 |
355,878 | 64,292,414 | How to most efficiently retrieve data from NarrowPeak (BED6+4) format files? | <p>I am working on a bioinformatics project that involves very big <a href="https://genome.ucsc.edu/FAQ/FAQformat.html#format12" rel="nofollow noreferrer">NarrowPeak</a> formated files that look like this:</p>
<p>(the columns are 'chrom ,chromStart, chromEnd, name, score ,strand, signalValue ,pValue, qValue ,peak')</p>... | <p>Pandas is serious overkill. If you are using <code>tabix</code> for your querying too, with a command sequence like:</p>
<pre><code>$ tabix input.bed.gz # index the input
$ tabix input.bed.gz chr1:713835-714424 # query the input
chr1 713835 714424 chr1.1 1000 . 0.1621 10.6 -1 253
</code></pre>
<p>You... | pandas|bioinformatics|samtools | 0 |
355,879 | 64,209,377 | DataFrame creating weird data structure | <p>My code is:</p>
<pre><code>for i, out in zip(foo, output):
# doing stuff and conditions
# output = each value in col1
listA.append([i, out])
listA = pd.DataFrame(listA)
</code></pre>
<pre><code> 0 1
0 [15921, 10, 82, 22, 202973, 368, 1055, 3... | <p>input:</p>
<pre><code> data=[
[[15921, 10, 82, 22, 202973, 368, 1055, 3135]],[[15921, 10, 82, 22, 202973, 368, 1055, 3135]]
]
df=pd.DataFrame(data=data)
print(df)
0
0 [15921, 10, 82, 22, 202973, 368, 1055, 3135]
1 [15921, 10, 82, 22, 202973, 368, 1055, 3135]
</... | python|pandas|dataframe | 1 |
355,880 | 64,434,960 | rotate/pivot a table from long to wide in pandas and create column of difference between previous columns | <p>I have a table that looks like this:</p>
<p><code>> data = {'index':[0,1,2,3],'column_names':['foo_1','foo_2','bar_1','bar_2'], 'Totals':[1050,400,450,300]} </code></p>
<p>and I want to do three things:</p>
<ol>
<li>Pivot each row in the 'column name' column to an actual column name.</li>
<li>Create an additional... | <ol>
<li>You need to <code>.groupby</code> to get the difference with <code>diff().abs()</code> in <code>s1</code></li>
<li>Then, you need to <code>.groupby</code> to get the name of the total columns in <code>s2</code> and <code>concat</code> s1 and s2 together.</li>
<li>From there, <code>append</code> the results of ... | python-3.x|pandas|pivot-table | 0 |
355,881 | 64,237,996 | How to determine two vectors are linearly dependent or independent in python? | <p>Take in two 3 dimensional vectors, each represented as an array, and tell whether they are linearly independent. I tried to use np.linalg.solve() to get the solution of x, and tried to find whether x is trivial or nontrivial. But it shows 'LinAlgError: Last 2 dimensions of the array must be square'. Can anyone help ... | <p>As your final matrix will be in a rectangular form, a simple approach of EigenValues will not work. You need to use the library of sympy</p>
<pre><code>import sympy
import numpy as np
matrix = np.array([
[0, 5, 0],
[0, -10, 0]
])
_, indexes = sympy.Matrix(matrix).T.rref() # T is for transpose
print(indexes)
<... | python|numpy|scipy | 2 |
355,882 | 64,462,296 | How to configure tensorflow with CPU support? | <p>I am trying to run tensorflow with CPU support.</p>
<p>tensorflow:<br />
Version: 1.14.0</p>
<p>Keras:<br />
Version: 2.3.1</p>
<p>When I try to run the following piece of code :</p>
<pre class="lang-py prettyprint-override"><code>def run_test_harness(trainX,trainY,testX,testY):
datagen=ImageDataGenerator(rescal... | <p>You should try running your code on google colab. I think there aren't enough resources available on your PC for the task you are trying to run even though you are using a batch_size of 1.</p> | tensorflow|keras|cpu | 0 |
355,883 | 64,554,835 | Writing read_jpeg and decode_jpeg functions for TensorFlow Lite C++ | <p>TensorFlow Lite has a good C++ image classification example in their repo, <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/examples/label_image" rel="nofollow noreferrer">here</a>.
However, I'm working with .jpeg and this example is restricted to decoding .bmp images with <a href="https... | <p>Library you are using is already handling decoding for you, decoder.getImage() contains raw rgb data. You do not need to calculate any sizes whatsoever.</p>
<p>Stuff like row_size is something specific to BMP file format. BMP files may contain some padding bytes in addition to pixel color data, the code was handling... | c++|tensorflow|machine-learning|tensorflow-lite|image-classification | 1 |
355,884 | 64,326,053 | Dataframe increase speed of for loop for set value of column | <p>I have dataframe from pandas (import pandas as pd)</p>
<pre><code>print(df)
C1 C2
0 0 0
1 0 0
2 1 0
3 1 1
4 1 1
5 0 1
6 0 0
7 0 0
8 0 0
9 1 0
10 1 1
11 1 1
12 0 1
13 0 0
</code></pre>
<p... | <p>You can:</p>
<ul>
<li>create a Series <code>counts</code> that is a boolean mask for the condition you want (<code>counts</code>);</li>
<li>add <code>C3</code> to the original df with value <code>1 + counts.cumsum()</code></li>
</ul>
<p>Note: pandas joins the series to the dataframe based on index values, <em>not or... | python|pandas|dataframe | 2 |
355,885 | 64,524,610 | How to add all columns in dataframe below first column | <p>I have excel data in following format:</p>
<pre><code>Index 1 1 1 1
A x x x x
B x x x x
C x x x x
</code></pre>
<p>Where x is some time stamp, but since I know meaningful data to my program would be something like:</p>
<pre><code>Index 1
A x
B ... | <p>You may concatenate columns (0,1,2) with (0,3,4), (0,5,6), etc. vertically.</p>
<p><strong>Data</strong></p>
<pre><code>df.columns = ["TRAIN NO"] + ["901", "902"] * 3
print(df)
TRAIN NO 901 902 901 902 901 902
0 DA 05:40:00 06:00:00 06:... | python-3.x|excel|pandas|dataframe | 0 |
355,886 | 64,526,592 | can't install h5py (error failed building wheel for h5py) | <p>I m trying to install h5py on raspberry pi using</p>
<pre><code>pip install h5py
</code></pre>
<p>and the installation always failed with</p>
<pre><code>error:failed building wheel for h5py
</code></pre> | <p>Please try
<code>sudo -H pip3 install h5py</code>
It works for me.</p> | python-2.7|tensorflow|keras|deep-learning|h5py | 0 |
355,887 | 64,609,458 | Transition count within a column from one value to another value in Pandas | <p>I have the below dataframe.</p>
<pre><code>df = pd.DataFrame({'Player': [1,1,1,1,2,2,2,3,3,3,4,5], "Team": ['X','X','X','Y','X','X','Y','X','X','Y','X','Y'],'Month': [1,1,1,2,1,1,2,2,2,3,4,5]})
</code></pre>
<p>Input:</p>
<pre><code> Player Team Month
0 1 X 1
1 1 X 1
2 ... | <p>First pick out the entries which (1) changes team but (2) is not the first row of a player. And then compute the size grouped by each month.</p>
<pre><code>mask = df["Team"].shift().ne(df["Team"]) & df["Player"].shift().eq(df["Player"])
out = df[mask].groupby("Month&q... | python|pandas | 2 |
355,888 | 64,305,278 | Pandas loc error: 'Series' objects are mutable, thus they cannot be hashed | <p>I need some help with a problem in handling pandas DataFrames. Here is the Code:</p>
<pre><code>df.drop(df.index[0], inplace=True)
df.columns = ['Mic. No.', 'X', 'Y', 'Z', 'Re. Pre.', 'Im. Pre.']
df['Pre'] = df['Re. Pre.'] + df['Im. Pre.'] * 1j
df.drop(['Mic. No.', 'Re. Pre.', 'Im. Pre.'], axis=1, inplace=True)
if ... | <p>You can use square brackets with <code>df.loc</code>:</p>
<pre class="lang-py prettyprint-override"><code>df = df.loc[df['Z'] == z]
</code></pre> | python|pandas|dataframe|typeerror|pandas-loc | 6 |
355,889 | 64,326,029 | Load tensorflow images and create patches | <p>I am using <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image_dataset_from_directory" rel="nofollow noreferrer">image_dataset_from_directory</a> to load a very large RGB imagery dataset from disk into a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow n... | <p>What you're looking for is <a href="https://www.tensorflow.org/api_docs/python/tf/image/extract_patches" rel="nofollow noreferrer"><code>tf.image.extract_patches</code></a>. Here's an example:</p>
<pre><code>import tensorflow as tf
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import numpy as np... | python|image|tensorflow|patch | 1 |
355,890 | 64,269,183 | How mix rows around in a Pandas DataFrame? | <p>I have a dataset that contains many binary columns. In the first half, each row has at least a 1; on the second half, each row has all zeros across all columns.</p>
<p>Is there a function to randomize rows so that they are not grouped by rows that have at least one 1 and rows that have all zeros?</p>
<p>Thank you!</... | <p>You can use .sample(n) on your pandas dataframe to view a random sample of n items if that is all you need...</p> | python|pandas|dataframe|data-cleaning | 0 |
355,891 | 64,185,919 | Pandas not updating CSV | <p>Dataset:
<a href="https://github.com/Bene939/newsheadlinedatasets" rel="nofollow noreferrer">https://github.com/Bene939/newsheadlinedatasets</a></p>
<p>With my program I am labeling my dataset of news headlines. It worked fine until today.
For some reason it won't write the csv file anymore. As far as I can see the ... | <p>I was trying to add duplicates while using drop_duplicates function without noticing it</p> | python|pandas|dataframe|csv | 0 |
355,892 | 64,195,952 | ValueError: Number of features of the model must match the input. Model n_features is 11 and input n_features is 2 | <p>While running the below code in jupyter notebook, I am getting the value error.</p>
<blockquote>
<p>ValueError: Number of features of the model must match the input. Model n_features is 11 and input n_features is 2</p>
</blockquote>
<p>How to resolve this issue?</p>
<pre><code># Visualising the Training set results
... | <p>I'll fixed your code the way I understand the problem, several extra lines added. Main problem is that you only feed columns 1 and 2 for prediction, but predictor expects 11 columns 1-11. Hence columns 3-11 should be filled somehow. At least you can fill them with zeros.</p>
<p>In my solution I sorted training set b... | python|numpy|machine-learning|jupyter-notebook|data-science | 1 |
355,893 | 47,780,934 | Google vision api vs build your own | <p>I have quite a challenging use case for image recognition. I want to detect composition of mixed recycling e.g. Crushed cans,paper,bottles and detect any anomalies such as glass, bags, shoes etc. </p>
<p>Trying images with the google vision api the results are mainly "trash", "recycling" "plastic" etc likely beca... | <p>So generally, when ever you apply machine learning to a new, real world use case, it is a good idea to get your hands on a representative dataset, in your case it would be images of these trash materials.</p>
<p>Then you can pick an appropriate detection model (VGG, Inception, ResNet), modify the final classificati... | machine-learning|tensorflow|neural-network|deep-learning|image-recognition | 2 |
355,894 | 47,630,927 | Pandas: modifying the dataframe by splitting into columns | <p>I have a dataframe which contains the number of sold cars within 2017.
I want a time series to plot different car models sold.</p>
<p>Here is my current DF</p>
<pre><code> Date Price Location Type
2003-05-16 397500 Texas Ford
2003-05-16 235000 Florida Fiat
2003-05-16 235000 Flor... | <p>It seems you need:</p>
<pre><code>df.groupby(['Date','Type']).size().unstack(fill_value=0).plot.bar()
</code></pre>
<p>Or:</p>
<pre><code>df.reset_index().groupby(['Date','Type']).size().unstack(fill_value=0).plot.bar()
</code></pre> | pandas|numpy | 0 |
355,895 | 47,953,338 | how to replace values of selected row of a column in panda's dataframe? | <p>i have train dataset which has 12 columns.
<a href="https://i.stack.imgur.com/dhVxc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dhVxc.png" alt="enter image description here"></a></p>
<p>I want to select <strong>Cabin</strong> column rows according to <strong>Pclass</strong> column's value 1.
And the... | <p>You can select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="noreferrer"><code>loc</code></a> with condition rows of column <code>Cabin</code> and set to scalar:</p>
<pre><code>train.loc[train['Pclass'] == 1, 'Cabin'] = 1
</code></pre>
<p>And your code replace al... | python|pandas|machine-learning|anaconda | 21 |
355,896 | 47,660,679 | numpy function giving incorrect results - checked by hand and excel | <p>I'm writing some functions in numpy for rock physics modelling and have noticed that one of my functions gives erroneous results. The function is my implimentation of Hertz-Mindlin sphere modelling: </p>
<p><a href="https://i.stack.imgur.com/EHmHO.jpg" rel="nofollow noreferrer">Summary of the Hertz-Mindlin model</a... | <p>In Python2, division of integers (using <code>/</code>) returns an integer. For example, <code>1/3 = 0</code>.
In Python3, division of integers (using <code>/</code>) may return a float.</p>
<p>It appears you are using Python2. To get floating-point division (in both Python2 and Python3), ensure each division opera... | numpy|math|geo | 2 |
355,897 | 47,981,205 | Distributed training with LSTM in tensorflow | <p>Is LSTM an algorithm or a node? If using it in a model will the backpropagation conflict if I use distributed training?</p> | <p>LSTM is neither. It's a <em>recurrent neural network</em> (see <a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/" rel="nofollow noreferrer">this post</a>). In terms of tensorflow, you might get confused, because there's a notion of a <em>cell</em> (e.g., <code>BasicLSTMCell</code>), that's basically... | tensorflow|machine-learning|distributed-computing|lstm|backpropagation | 1 |
355,898 | 47,913,310 | Search over text column in pandas data frame without looping | <p>I have a pandas data frame where one of the columns is a text description string. I need to create a new column which would identify if one of the strings from a list is in the text description. </p>
<pre><code>df = pd.DataFrame({'Description': ['2 Bedroom/1.5 Bathroom end unit Townhouse.
Available now!', 'Very s... | <p>By using <code>str.contains</code></p>
<pre><code>list_ = ['unit', 'apartment']
df.Description.str.contains('|'.join(list_))
Out[724]:
0 True
1 True
2 False
Name: Description, dtype: bool
</code></pre> | python|pandas|nlp | 2 |
355,899 | 47,848,066 | pandas changing df when working with a copy | <p>Has anyone else seen this behavior before?</p>
<p>I've got a short code snippet below:</p>
<pre><code> import pandas as pd
df1= pd.DataFrame({'a':[1,2], 'b': [10,20]})
df2=df1
df2['newcol']=1
print('df1\n',df1)
print('df2\n',df2)
</code></pre>
<p>All day I've been getting very strange behaviour. The output... | <p>For new mutable object in python (here <code>DataFrame</code>) need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow noreferrer"><code>copy</code></a>:</p>
<pre><code>df2 = df1.copy()
</code></pre>
<p>Better explanation is <a href="https://stackoverflow.com/q... | python-3.x|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.