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 |
|---|---|---|---|---|---|---|
7,700 | 62,567,073 | Invalid syntax error when setting root = to in PyTorch | <pre><code>import torchvision
from torchvision import transforms
train_data_path="./train/"
transforms = transforms.Compose([
transforms.Resize(64),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225] )
])
train_data = torchvision.datasets.ImageFolder
(root=train_... | <p>You need the opening parentheses to be directly connected to the function, without any whitespace separating them. Try replacing the final two lines with:</p>
<pre class="lang-py prettyprint-override"><code>train_data = torchvision.datasets.ImageFolder(
root=train_data_path, transform=transforms
)
</code></pre> | python|syntax-error|pytorch | 1 |
7,701 | 62,777,583 | Keras timeseriesgenerator: how to predict multiple data points in one step? | <p>I have meteorological data that looks like this:</p>
<pre><code>DateIdx winddir windspeed hum press temp
2017-04-17 00:00:00 0.369397 0.155039 0.386792 0.196721 0.238889
2017-04-17 00:15:00 0.363214 0.147287 0.429245 0.196721 0.233333
2017-04-17 00:30:00 0.35... | <p>What you can do with the TimeSeries generator is to change the target entry. Concretely, since you want to predict the next thee timesteps, your target should be something of the form</p>
<pre><code> target=np.concatenate((np.roll(X, -1, axis=0),
np.roll(X, -2, axi... | python|tensorflow|keras|time-series|recurrent-neural-network | 0 |
7,702 | 54,526,939 | Converting column in pandas to datetime | <p>I am trying to convert a pandas data frame column from string to a datetime type.I am sure I am doing it correctly but am getting an error saying that the format does not match and I can not work out why.
My strings I want to convert look like this</p>
<pre><code>Date
2019-02-03 04:09:34
2019-02-02 14:21:03
2019-0... | <p>The problem is your additional <code>:</code> before <code>%:H</code> in your format string. <code>pandas</code> is looking for a colon and can't find it in the data you provide.</p>
<p>Additionally, I tested <code>pd.to_datetime</code> without a format string, and it appears to be able to infer the format, so you ... | python|pandas|datetime | 1 |
7,703 | 54,534,963 | Make my Nested loops Works simpler (Operating Time is Higher) | <p>I am a learner in nested loops in python.</p>
<p>Below I have written my code. I want to make my code simpler, since when I run the code it takes so much time to produce the result.</p>
<p>I have a list which contains 1000 values:</p>
<pre><code>Brake_index_values = [ 44990678, 44990679, 44990680, 44990681, 4... | <p>We can use the <code>bisect</code> module to shorten the elements we actually have to lookup by finding the smallest element that's greater or less than the current value. We will use recipes from <a href="https://docs.python.org/3/library/bisect.html#searching-sorted-lists" rel="nofollow noreferrer">here</a></p>
<... | python|arrays|loops|numpy|for-loop | 1 |
7,704 | 73,590,483 | How to append multiple lists in Python | <p>I want to append two lists <code>A[0]</code> and <code>A</code> but I am getting an error. I present the expected output.</p>
<pre><code>import numpy as np
A=[]
A[0]=[np.array([[0.4]])]
A=[np.array([[0.15]])]
print("A =",A)
</code></pre>
<p>The error is</p>
<pre><code>in <module>
A[0]=[np.array([... | <p>In your code, <code>A[0]</code> is not a list; it's an element (the first one, to be precise) in list <code>A</code>. But <code>A</code> is empty, so there is no element <code>A[0]</code>in it that you can assign a value to, hence the "index out of range" error. Try the following instead:</p>
<pre><code>im... | python|list|numpy | 2 |
7,705 | 73,787,437 | Convert python output to csv file | <p>I have 500 files with their file size. Now I want to put them in a csv file.</p>
<pre><code>Name size
A.jpg 16.3
B.jpg 310.11
</code></pre>
<p>I have converted Name and Value in two lists.</p>
<pre><code>Result=[]
for i in name:
for j in value:
Result.append(zip(i,j))
print(Result)
</code></pre>... | <pre><code>import pandas as pd
read_file = pd.read_csv (r'Path where the Text file is stored\File name.txt')
read_file.to_csv (r'Path where the CSV will be saved\File name.csv', index=None)
</code></pre> | python|pandas|csv | 0 |
7,706 | 71,432,173 | Pandas Time series manipulation with large panel data | <p>Here is my large panel dataset:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>x1</th>
<th>x2</th>
<th>x3</th>
</tr>
</thead>
<tbody>
<tr>
<td>2017-07-20</td>
<td>50</td>
<td>60</td>
<td>Kevin</td>
</tr>
<tr>
<td>2017-07-21</td>
<td>51</td>
<td>80</td>
<td>Kevin</td>
</tr>... | <p>You could <code>groupby</code> + <code>shift</code> "x1" and subtract "x2" from it:</p>
<pre><code>df['target'] = (df.groupby('x3')['x1'].shift(-1) - df['x2']) / df['x2']
</code></pre>
<p>Output:</p>
<pre><code> Date x1 x2 x3 target
0 2017-07-20 50 60 Kevin -0.15
1 2017-... | python|pandas|dataframe|pandas-groupby | 1 |
7,707 | 71,399,081 | How to save empty pyspark dataframe with header into csv file? | <p>Hi I have dataframe which is having only columns. There is no data for columns. But I am trying to save into file, no header is saving. File is totally blank.</p>
<p>Example:</p>
<p>df.show()</p>
<pre><code>+-----+----------------------+-------+---------------------+------------------------+-------------------------... | <p>To do what you are asking you will have to define a schema.</p>
<p>So for example:</p>
<pre><code>schema = StructType([ \
StructField("firstname",StringType(),True), \
StructField("middlename",StringType(),True), \
StructField("lastname",StringType(),True), \
StructField... | pyspark|apache-spark-sql|pyspark-pandas | -1 |
7,708 | 71,382,478 | Difficulty in using subplots to shows multiple boxplots side-by-side | <p>I am using the heart_failure_clinical_records_dataset.csv dataset, you can find it here: <a href="https://www.kaggle.com/abdallahwagih/heart-failure-clinical-records-dataset-eda" rel="nofollow noreferrer">https://www.kaggle.com/abdallahwagih/heart-failure-clinical-records-dataset-eda</a>
Now I created two subsets of... | <p>Changing <code>axis[0, 0]</code> to <code>axis[0]</code> will fix the issue.</p>
<pre><code>axis[0].plot(x1, y1)
axis[1].plot(x2, y2)
</code></pre>
<p>If you only want to plot those boxplots side by side then:</p>
<pre><code>fig, ax =plt.subplots(1, 2, figsize=(25, 8))
sns.boxplot(x = group1['age'], y = group1['crea... | python|pandas|matplotlib|jupyter-notebook | 1 |
7,709 | 52,312,950 | Replicate a numpy list m times | <p>I am trying to pair two different databases of images that I have in python (lets say database A and database B, they are stored in list of numpy arrays). For the database A I have x images (for example 6) and for database B y images (for example 78). Each image from database A is correspond to 78/6 = 13 images from... | <p>Assuming the images are in <code>(n, x, y)</code> or <code>(n, x, y, RGB)</code> shaped arrays:</p>
<pre><code>np.repeat(A, B.shape[0] // A.shape[0], axis = 0)
</code></pre>
<p>If you really want to keep lists, I still recommend doing the repetition in <code>numpy</code></p>
<pre><code>list(np.repeat(np.array(A),... | python|list|numpy | 2 |
7,710 | 52,371,578 | How to detect and remove lines above data set while reading from csv? | <p>I have a csv that looks like this: </p>
<pre><code>name: john
date modified: 2018-09
from: jane
colum1 column2 column3
data data data
</code></pre>
<p>Is there any function I can apply that would strip off any lines before the tabular data begins when reading from csv? currently the lines above <code>column... | <p>I would do something like this:</p>
<pre><code>from io import StringIO
with open('filename.csv') as f:
lines = f.readlines()
s = StringIO(''.join((l for l in lines if ':' not in l)))
pd.read_csv(s)
</code></pre>
<p>Alternatively:</p>
<pre><code>with open('filename.csv') as f:
lines = f.readlines()
skip_ro... | python|python-3.x|pandas|csv | 2 |
7,711 | 60,619,900 | Numerical errors in Keras vs Numpy | <p>In order to really understand convolutional layers, I have reimplemented the forward method of a single keras Conv2D layer in basic numpy. The outputs of both seam almost identical, but there are some minor differences.</p>
<p>Getting the keras output:</p>
<pre><code>inp = K.constant(test_x)
true_output = model.la... | <p>Given how small the differences are, I would say that they are rounding errors.<br>
I recommend using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html" rel="nofollow noreferrer">np.isclose</a> (or <a href="https://docs.python.org/dev/library/math.html#math.isclose" rel="nofollow noref... | python|numpy|keras|floating-point|precision | 2 |
7,712 | 60,639,069 | Remove rows from dataframe whose text does not contain items from a list | <p>I am importing data from a table with inconsistent naming conventions. I have created a list of manufacturer names that I would like to use as a basis of comparison against the imported name. Ideally, I will delete all rows from the dataframe that do not align with the manufacturer list. I am trying to create an ind... | <p>you can use <code>pd.DataFrame.apply</code>:</p>
<pre><code>meltdat[meltdat.Products.apply(lambda x: any(m in x for m in mfgs))]
</code></pre> | python|pandas|list|dataframe|text | 0 |
7,713 | 60,406,058 | How do you load a csv file format to jupyter notebook? | <p>I tried reading a file with a CSV extension from my local storage but it gave me the following error message.</p>
<pre><code>File "<ipython-input-12-bbfa50761a08>", line 5
data=pd.read_csv("C:\Users\user\Documents\Projects\Data Science\weather_data.csv")
^
SyntaxError: (unicode error) ... | <p>First try loading packages like numpy and pandas and then try loading the data</p>
<pre><code>import numpy as np
import pandas as pd
data=pd.read_csv("C:\Users\user\Documents\Projects\Data Science\weather_data.csv")
print(data)
data.head
</code></pre> | python|pandas | 0 |
7,714 | 60,736,766 | How to create the given jSON format from a pandas dataframe? | <blockquote>
<p>The data looks like this :</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/WmDRw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WmDRw.png" alt="enter image description here"></a></p>
<blockquote>
<p>The expected Json fomat is like this</p>
</blockquote>
<pre><code> ... | <p>With so many nested structures, you should use marshmallow. It is built with your use case in mind. Please check out the excellent documentation: <a href="https://marshmallow.readthedocs.io/en/stable/" rel="nofollow noreferrer">https://marshmallow.readthedocs.io/en/stable/</a> . All you need is the masic usage.</p>
... | python|json|pandas|csv|dictionary | 2 |
7,715 | 32,395,890 | plotting data from columns from the same dataframe in pandas | <p>I have a dataframe with 60 columns of data (column 1 = I 1, column 2 = S 1.... column 3 = I 2, column 4 =S 2.. and so on)... </p>
<p>I want to create a function that selects two columns at a time for slicing, plotting and finding the integral of the slice. I can do this for two columns but I don't know how to imple... | <p>Alas, i have found the solution. </p>
<pre><code>def get_slice():
area_list = []
df = pd.DataFrame.from_csv(filepath, index_col =None)
Raman = df['I 1']
Intensity = df['S 1']
for i in range(1,31):
df_slice = df.iloc[23500:25053]
R = df_slice['I %i' %i... | python|numpy|pandas|matplotlib | 0 |
7,716 | 40,662,773 | Image similarity detection with TensorFlow | <p>Recently I started to play with tensorflow, while trying to learn the popular algorithms i am in a situation where i need to find similarity between images.</p>
<p>Image A is supplied to the system by me, and userx supplies an image B and the system should retrieve image A to the userx if image B is similar(color a... | <blockquote>
<p>Do we consider this scenario to be supervised learning?</p>
</blockquote>
<p>It is supervised learning when you have labels to optimize your model. So for most neural networks, it is supervised.</p>
<p>However, you might also look at the complete task. I guess you don't have any ground truth for ima... | machine-learning|scikit-learn|computer-vision|tensorflow|deep-learning | 9 |
7,717 | 61,740,933 | Python/Pandas: How to detect if trend is suddenly increasing "X" amount | <p>I want to detect if I have some certain log event that is increasing "X" amount of percent, and then get the top 10 increased trends.</p>
<p>I would have thought that pct_change().mean() would give me what I needed, but it seems I am getting some weird results.</p>
<p>So this is what I got</p>
<pre><code>import p... | <p>the mean pct change and the linear trend have different behavior. look at my simulate example:</p>
<pre><code>start = 100
end = 0
peak = 1000
steps = 50
series = pd.Series(np.append(start, np.arange(end, peak+steps, steps)[::-1]))
series.plot()
</code></pre>
<p><a href="https://i.stack.imgur.com/jkqOm.png" rel="n... | python-3.x|pandas | 1 |
7,718 | 61,841,921 | pandas create column with names from values and substitute with True/False | <p>I have a dataframe like this:</p>
<pre><code>df = pd.DataFrame({"id":[1, 1, 1, 2, 2, 2, 2, 3, 3], "val":["A12", "B23", "C34", "A12", "C34", "E45", "F56", "G67", "B23"]})
print(df)
</code></pre>
<pre><code> id val
0 1 A12
1 1 B23
2 1 C34
3 2 A12
4 2 C34
5 2 E45
6 2 F56
7 3 G67
8 3 B23
... | <p>Try crosstab:</p>
<pre><code>pd.crosstab(df.id, df.val).reset_index()
</code></pre> | python|pandas | 4 |
7,719 | 62,019,234 | Lifetimes package: float() argument must be a string or a number, not 'Day' | <p>Getting the following error while using the summary_data_from_transaction_data utility function included within the Lifestyles python package. Using pandas version 0.2 on Google Colab.</p>
<p>TypeError: float() argument must be a string or a number, not 'Day'</p>
<p>Any help will be much appreciated.</p>
<h1>Code... | <p>Apologies folks - I was able to resolve my issue after updating the Lifetimes package to the latest 0.11.1 version in Colab!</p> | python|pandas|lifetimes-python | 1 |
7,720 | 61,622,123 | Best way to read data from S3 into pandas | <p>I have two CSV files one is around 60 GB and other is around 70GB in S3. I need to load both the CSV files into pandas dataframes and perform operations such as joins and merges on the data.</p>
<p>I have an EC2 instance with sufficient amount of memory for both the dataframes to be loaded into memory at a time.</p... | <p>For reading from S3, you can do:</p>
<pre><code>import pandas as pd
df = pd.read_csv('s3://bucket-name/file.csv')
</code></pre>
<p>Then do all the joins and merges on this dataframe and upload it back to S3:</p>
<pre><code>df.to_csv('s3://bucket-name/file.csv', index=False)
</code></pre> | python|pandas|amazon-web-services|amazon-s3|amazon-ec2 | 2 |
7,721 | 57,775,930 | Value error when populating a new column in a dataframe based on conditional values | <p>I am trying to write a function that will populate a new column called <code>'BS_Trigger'</code> based on the values in another column in the same <code>dataframe</code> (<code>'cnms_df'</code>). </p>
<pre><code>today = datetime.datetime.today().strftime('%Y%m%d')
....
def bs_trigger(dataframe):
dataframe['BS_T... | <p>Try replacing:</p>
<pre class="lang-py prettyprint-override"><code>dataframe['BS_Trigger'] = np.where((dataframe['PRELIM_DATE'] != None) and (dataframe['PRELIM_DATE'] <= today), "Yes", "No")
</code></pre>
<p>with:</p>
<pre class="lang-py prettyprint-override"><code>dataframe["BS_Trigger"]="No"
dataframe.BS_Tri... | python-3.x|pandas|dataframe|conditional-statements | 1 |
7,722 | 58,015,383 | how to generate dynamic columns in pandas | <p>I have following dataframe in pandas</p>
<pre><code>code tank nozzle_1 nozzle_2 nozzle_var
123 1 1 1 10
123 1 2 2 12
123 2 1 1 10
123 2 2 2 12
</code></pre>
<p>I want to calcula... | <p>How about this fancy solution:</p>
<pre><code>cols= df.columns[df.columns.str.contains(pat='nozzle_\d+$', regex=True)]
df.assign(**df.groupby('tank')[cols].agg(['cumsum'])\
.pipe(lambda x: x.set_axis(x.columns.map('_'.join), axis=1, inplace=False)))
</code></pre>
<p>Output:</p>
<pre><code> tank ... | python|pandas | 2 |
7,723 | 57,942,516 | Understanding the output of fftfreq function and the fft plot for a single row in an image | <p>I am trying to understand the function <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftfreq.html" rel="nofollow noreferrer">fftfreq</a> and the resulting plot generated by adding real and imaginary components for one row in the image. Here is what I did:</p>
<pre><code>import numpy as np
... | <p>I don't think that you really need <code>fftfreq</code> to look for frequency-domain information in images, but I'll try to explain it anyway.</p>
<p><code>fftfreq</code> is used to calculate the frequencies that correspond to each bin in an FFT that you calculate. You are using <code>fftfreq</code> to define the ... | python|numpy|opencv|image-processing|fft | 2 |
7,724 | 58,067,051 | Pandas - read_csv scientific notation large number | <p>I am trying to read a csv file with pandas that has some rows in scientific notation.</p>
<p>When it reads the values it is not capturing the true underlying number. When I re-purpose the data the true value gets lost. </p>
<pre><code>df = pd.read_csv('0_IDI_Submitter_out.csv')
</code></pre>
<p>The underlying tru... | <p>The problem appears to be that opening a CSV file in Excel which contains large numbers or strings that appear as large numbers like product codes, SKU's, UPC's etc are automatically converted into scientific notation. Once this has been done, you'll have to manually go into Excel and re-format but trying to do this... | python|pandas|scientific-notation | 2 |
7,725 | 34,241,426 | pandas automatically create dataframe from list of series with column names | <p>I have a list of pandas series objects. I have a list of functions that generate them. How do I create a dataframe of the objects with the column names being the names of the functions that created the objects?</p>
<p>So, to create the regular dataframe, I've got:</p>
<pre><code>pandas.concat([list of series obj... | <p>You can set the column names in a second step:</p>
<pre><code>df = pandas.concat([list of series objects],axis=1,join='inner')
df.columns = [functionA.__name__, functionB.__name__]
</code></pre> | python|pandas | 2 |
7,726 | 34,252,755 | How to compute integrals dependent upon two variables with SciPy? | <p>How to compute integrals of this kind with SciPy?</p>
<p>Product of functions P1 and P2 depends of <em>x</em> and integration variable <em>du</em></p>
<p>It would be nice to express result as lambda function, like:</p>
<p>joint_p = lambda x: quad(<em>[some code here]</em>, ...</p>
<p><a href="https://i.stack.img... | <p>Is there any reason why a straightforward use of <code>scipy.integrate.quad</code> won't work? I mean:</p>
<pre><code>import scipy as sp
import scipy.integrate
#define some dummy p1 and p2
def p1(y):
return 3*y+2
def p2(y):
return -4*y-4
#define p_{xi1+xi2}
def pplus(x):
return sp.integrate.quad(lambd... | python|numpy|scipy | 1 |
7,727 | 34,226,605 | Bizarre behavior of scipy.linalg.eigvalsh in Python | <p>I wanted to compare <code>scipy</code>'s and <code>numpy</code>'s routine for calculating eigenvalues of Hermitian matrices (<code>eigvalsh</code>), and ran into some unexpected behavior.</p>
<p>In particular, <code>scipy</code>'s <code>eigvalsh</code> routine returns practically the same eigenvalues as <code>numpy... | <p>For <code>*.linalg.eigvalsh</code> routines, <code>numpy</code> invokes LAPACK <code>-EVD</code> routines, which are based on a divide-and-conquer algorithm. <code>scipy</code> invokes LAPACK <code>-EVR</code>, which uses a different algorithm.</p>
<p>For LAPACK docs, <a href="http://www.netlib.org/lapack/lug/node3... | python|numpy|scipy | 0 |
7,728 | 36,776,494 | How to load Image as binary image with threshold in Scipy? | <p>I have a grayscale image--the MNIST dataset, actually--and I need to convert it to a binary image with a threshold of, say, 240 so that all values below 240 are ones and all values above are zeros. </p>
<p>This is a function in matlab, so I'm sure there is some corresponding function in scipy...but it is eluding m... | <p>If A is your matrix, the binary matrix B is:</p>
<p>B = np.where(A <= 240, 1, 0)</p> | python|numpy|scipy | 1 |
7,729 | 37,049,887 | Print highest peak value of the frequency domain plot | <p>I've attempted to plot the oscillations of my home made quad in the time and frequency domain.
How do I print the value of my highest peak in the frequency domain plot?</p>
<p>code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy import fft, arange
csv = np.genfromtxt ('/Users/shaunba... | <p>Since you're using <code>numpy</code>, just simply use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ndarray.argmax.html#numpy.ndarray.argmax" rel="noreferrer"><code>numpy.max</code></a> and <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.argmax.html" rel="norefe... | python|matlab|numpy|matplotlib|scipy | 5 |
7,730 | 36,861,380 | Merge pandas dataframe with unequal length | <p>I have two Pandas dataframes that I would like to merge into one. They have unequal length, but contain some of the same information.</p>
<p>Here is the first dataframe:</p>
<pre><code>BOROUGH TYPE TCOUNT
MAN SPORT 5
MAN CONV 3
MAN WAGON 2
BRO SPORT 2
BRO CONV 3
</code></pre>
<... | <p>Perform a <code>left</code> type <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/merging.html#database-style-dataframe-joining-merging" rel="nofollow"><code>merge</code></a> on columns 'A','B' for the lhs and 'A','D' for the rhs as these are your key columns</p>
<pre><code>In [16]:
df.merge(df1, left_o... | python|pandas|dataframe|merge | 5 |
7,731 | 54,789,591 | How to find all triplets of nodes (connected components of size 3) from a tsv file? | <p>From the matrix given below, i have to make a network and find all connected components of size 3.
The dataset i use is:</p>
<pre><code>0 1 1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 ... | <p>You can find all connected components using the function <code>connected_componets()</code>. Subsequently you can filter out the components, which consist of three nodes:</p>
<pre><code>import networkx as nx
import pandas as pd
from itertools import chain
adj_matrix = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, ... | python|python-3.x|pandas|networkx | 2 |
7,732 | 49,530,410 | Python `expm` of an `(N,M,M)` matrix | <p>Let <code>A</code> be an <code>(N,M,M)</code> matrix (with <code>N</code> very large) and I would like to compute <code>scipy.linalg.expm(A[n,:,:])</code> for each <code>n in range(N)</code>. I can of course just use a <code>for</code> loop but I was wondering if there was some trick to do this in a better way (some... | <p>Depending on the size and structure of your matrices you can do better than loop.</p>
<p>Assuming your matrices can be diagonalized as <code>A = V D V^(-1)</code> (where <code>D</code> has the eigenvalues in its diagonal and <code>V</code> contains the corresponding eigenvectors as columns), you can compute the mat... | python|numpy|scipy|linear-algebra|numpy-einsum | 4 |
7,733 | 49,639,523 | What is going on behind the Pandas scenes that is causing a level in a MultiIndex not to be dropped? | <p>Consider the data frame <code>df</code><br>
Note that the columns object is a single level MultiIndex.</p>
<pre><code>midx = pd.MultiIndex.from_product([list('AB')])
df = pd.DataFrame(1, range(3), midx)
A B
0 1 1
1 1 1
2 1 1
</code></pre>
<p>Now when I reference column <code>'A'</code></p>
<pre><code>d... | <p>I wrote this to fix the problem.</p>
<pre><code>def fix_single_level_multiindex(midx):
return midx.get_level_values(0) if midx.nlevels == 1 else midx
</code></pre>
<p>Or</p>
<pre><code>def fix_single_level_multiindex(midx):
return midx.levels[0][midx.labels[0]] if midx.nlevels == 1 else midx
</code></pre> | python|pandas|multi-index | 1 |
7,734 | 28,095,803 | Using linalg.block_diag for variable number of blocks | <p>So I have a code that generates various matrices. These matrices need to be stored in a block diagonal matrix. This should be fairly simply as I can use scipy's:</p>
<pre><code>scipy.linalg.block_diag(*arrs)
</code></pre>
<p>However the problem I have is I don't know how many matrices will need to be stored like t... | <p>When you do:</p>
<pre><code>scipy.linalg.block_diag( matrix_list[ii] for ii in range(len(matrix_list)) )
</code></pre>
<p>you're passing a generator expression to <code>block_diag</code>, which is not the way to use it.</p>
<p>Instead, use the <code>*</code> opertor, for expanding the argument list in the functi... | python|numpy|matrix|scipy|parameter-passing | 6 |
7,735 | 28,353,414 | Converting a matlab script into python | <p>I'm an undergrad at university particapting in a research credit with a professor, so this is pretty much an independent project for me. </p>
<p>I am converting a matlab script into a python (3.4) script for easier use on the rest of my project. The 'find' function is employed in the script, like so:</p>
<pre><cod... | <p>A quick search led me to the <code>argwhere</code> function which you can combine with <code>[0]</code> to get the first index satisfying your condition. For example,</p>
<pre><code>>> import numpy as np
>> x = np.array(range(1,10))
>> np.argwhere(x > 5)[0]
array([5])
</code></pre>
<p>This isn... | matlab|numpy|python-3.4 | 2 |
7,736 | 73,241,736 | Fill the missing value in Age column values by (means of the age of the players belonging to that particular game) | <p>Let's suppose there is a missing value of Age where the sport is Swimming, then replace that missing value of age with the mean age of all the players who belong to Swimming. Similarly for all other sports.
How can I do that?</p>
<p><a href="https://i.stack.imgur.com/OTROf.png" rel="nofollow noreferrer">enter image ... | <p>This is how you can fill the age with the mean value of the column.</p>
<pre><code>df['Age'].fillna(int(df['Age'].mean()), inplace=True)
</code></pre>
<p>You can also use sklearn to achieve that in the whole df:</p>
<pre><code>import pandas as pd
import numpy as np
df= pd.read_csv("data.csv")
X = df.ilo... | pandas | 0 |
7,737 | 73,242,757 | using a for loop to rename columns of a list of data frames | <p>I have a list of dataframes I have saved in a variable x.</p>
<pre><code>x=[df_1963,df_1974,df_1985,df_1996,df_2007,df_2018]
</code></pre>
<p>I wish to change all the headers to lowercase but nothing happens after the running the code below.</p>
<pre><code>for df in x:
for column in df.columns:
df = df.w... | <p>You can do it in a list and dict comprehension way. Try with:</p>
<pre><code>renamed_x = [a.rename(columns={y:y.lower() for y in a}) for a in x]
</code></pre>
<p>The inner dict comprehension generates a dictionary with the columns' original values and its lowercase, so that is how each dataframe's columns will be r... | python|pandas|dataframe | 0 |
7,738 | 73,365,975 | Appending series to list, then converting to dataframe. Everything works, but if list gets too large it returns a numpy memory error | <p>The code works fine and outputs exactly what I need, but when db_diff_3 gets above about 5k lines, it spits out a memory error and breaks. It is using a lot of memory here (almost 7gbs) when running. A 5K list should be small for a list of series which is why I'm not understanding why its doing this. Any help would ... | <p>I'm not sure why your code gives a memory error but I wanted to share an approach that doesn't require the <code>for</code> loop and I believe shouldn't cause a memory issue.</p>
<p>The main idea is to separate the <code>old</code> and <code>new</code> parts of your <code>df2</code> table into separate tables to mak... | python|pandas|dataframe|memory|append | 0 |
7,739 | 35,284,883 | How to search by Date given Datetime index | <p>Given a DataFrame, where the index is Datetime, how can I retrieve the row(s) by matching only on the Date portion?</p>
<p>For example:</p>
<pre><code>df1 =
A B C D
2011-01-13 16:00:00 344 144 616 73
2011-01-14 16:00:00 346 145 624 74
2011-01-18 16:00:00 339 146 639 77
..... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.to_series.html" rel="nofollow"><code>to_series</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>date</code></a> and <a href="http://pandas.pydata.org/pand... | python|datetime|pandas | 3 |
7,740 | 31,214,916 | How can I read successive arrays from a binary file using `np.fromfile`? | <p>I want to read a binary file in Python, the exact layout of which is stored in the binary file itself.</p>
<p>The file contains a sequence of two-dimensional arrays, with the row and column dimensions of each array stored as a pair of integers preceding its contents. I want to successively read all of the arrays co... | <p>You can pass an open file object to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html" rel="noreferrer"><code>np.fromfile</code></a>, read the dimensions of the first array, then read the array contents (again using <code>np.fromfile</code>), and repeat the process for additional array... | python|numpy | 5 |
7,741 | 31,057,197 | Should I use `random.seed` or `numpy.random.seed` to control random number generation in `scikit-learn`? | <p>I'm using scikit-learn and numpy and I want to set the global seed so that my work is reproducible.</p>
<p>Should I use <code>numpy.random.seed</code> or <code>random.seed</code>?</p>
<p>From the link in the comments, I understand that they are different, and that the numpy version is not thread-safe. I want to know... | <blockquote>
<p>Should I use np.random.seed or random.seed?</p>
</blockquote>
<p>That depends on whether in your code you are using numpy's random number generator or the one in <code>random</code>.</p>
<p>The random number generators in <code>numpy.random</code> and <code>random</code> have totally separate intern... | python|numpy|random|scikit-learn|random-seed | 57 |
7,742 | 31,069,951 | Python: list vs. np.array: switching to use certain attributes | <p>I know, there are plenty of threads about list vs. array but I've got a slightly different problem.</p>
<p>Using Python, I find myself converting between np.array and list quite often as I want to use attributes like</p>
<p>remove, append, extend, sort, index, … for lists</p>
<p>and on the other hand modify the c... | <p>A numpy array:</p>
<pre><code>>>> A=np.array([1,4,9,2,7])
</code></pre>
<p>delete:</p>
<pre><code>>>> A=np.delete(A, [2,3])
>>> A
array([1, 4, 7])
</code></pre>
<p>append (beware: it's <strong>O(n)</strong>, unlike list.append which is <strong>O(1)</strong>):</p>
<pre><code>>>&g... | python|arrays|list|numpy|type-conversion | 3 |
7,743 | 67,452,037 | How to preprocess a dataset for BERT model implemented in Tensorflow 2.x? | <h2>Overview</h2>
<p>I have a dataset made for classification problem. There are two columns one is <code>sentences</code> and the other is <code>labels</code> (total: 10 labels). I'm trying to convert this dataset to implement it in a BERT model made for classification and that is implemented in Tensorflow 2.x. Howeve... | <p><strong>Working sample BERT model</strong></p>
<pre><code>#importing neccessary modules
import os
import tensorflow as tf
import tensorflow_hub as hub
data = {'input' :['i hate megavideo stupid time limits',
'wow this class got wild quick functions are a butt',
'got in trouble no cell phone or compu... | python|tensorflow|tokenize|bert-language-model | 1 |
7,744 | 67,455,124 | How to combine data from two columns based on multipe conditions in pandas? | <p>I have this dataframe where I am trying to combine <code>Email_x</code> and <code>Email_y</code> to be a column <code>email</code>.</p>
<ol>
<li>If both are <code>NaN</code> then the result should be <code>""</code> or <code>np.nan</code>.</li>
<li><code>Email_y</code> has a value and <code>Email_x</code> ... | <p>Via <code>np.select</code></p>
<pre><code>condlist = [
(df.Email_x.isna()) & (~df.Email_y.isna()), # 1st column NAN but 2nd is not
(df.Email_y.isna()) & (~df.Email_x.isna()), # 2nd column NAN but 1st is not
(~df.Email_x.isna()) & (~df.Email_y.isna()) # both is not NAN
]
choicelist = [
d... | python|pandas | 2 |
7,745 | 67,591,044 | Docker container with Python modules gets too big | <p>I want my Docker container to use tensorflow lite (tflite) in a python script. My Dockerfile looks like this:</p>
<pre><code>FROM arm32v7/python:3.7-slim-buster
COPY model.tflite /
COPY docker_tflite.py /
COPY numpy-1.20.2-cp37-cp37m-linux_armv7l.whl /
RUN apt-get update \
&& apt-get -y install libatlas-... | <p>You end up with two copies of numpy: the wheel, and the installed version. The way to solve that is with a multi-stage build, where the second stage doesn't have the wheel, or development headers, or any other unnecessary build files.</p>
<pre><code>FROM arm32v7/python:3.7-slim-buster as dev
# ...
RUN pip install --... | python|docker|arm|dockerfile|tensorflow-lite | 2 |
7,746 | 67,577,054 | Pandas and python: deduplication of dataset by several fields | <p>I have a dataset of companies. Each company has tax payer number, address, phone and some other fields. Here is a Pandas code I take from Roméo Després:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
"tax_id": ["A", "B", "C", "D", "E", "A&... | <p>You could solve this using the graph analysis library <a href="https://networkx.org" rel="nofollow noreferrer"><code>networkx</code></a>.</p>
<pre class="lang-py prettyprint-override"><code>import itertools
import networkx as nx
import pandas as pd
df = pd.DataFrame({
"tax_id": ["A", "... | python|pandas|algorithm|duplicates|dataset | 1 |
7,747 | 34,605,249 | sklearn Convert Text Series to Sparse Matrix, Then Scale Numeric, Then Combine Into Single X | <p>If I have both text and numeric values, and I want to:</p>
<ol>
<li>Convert the text to numeric (I'm using <code>CountVectorizer</code> as a general example)</li>
<li>Convert numeric data to the same scale</li>
<li>Combine 1 and 2 into a single <code>X</code> matrix to pass to an estimator</li>
</ol>
<p>How do I c... | <p>I think you are misunderstanding how <code>FeatureUnion</code> works. <code>FeatureUnion</code> applies multiple feature extractors / preprocessors and combines the resulting features into a single matrix. Since you do not have multiple preprocessors, but instead have multiple matricies, you should probably use <cod... | python|pandas|scikit-learn | 1 |
7,748 | 34,865,791 | NumPy unique() returns indices that are out-of-bounds | <p>I am trying to remove points from a point cloud that are too close to each other. My input is an mx3 matrix where the columns represent xyz coordinates. Code is as follows:</p>
<pre><code>def remove_duplicates(points, threshold):
# Convert to numpy
points = np.array(points)
# Round to within the thresh... | <p>So <code>points</code> is a 2d array, <code>(m,3)</code> in shape, right?</p>
<p><code>point_tuples</code> is a list of tuples, i.e. row of <code>rounded_points</code> is now a tuple of 3 floats.</p>
<p><code>np.unique</code> is going to turn that into an array to do it's thing</p>
<p><code>np.array(point_tuples)... | python|numpy|matrix|indexing|point-clouds | 2 |
7,749 | 60,096,717 | Pandas groupby and subtract rows | <p>I have the following dataframe:</p>
<pre><code>id variable year value
1 a 2020 2
1 a 2021 3
1 a 2022 5
1 b 2020 3
1 b 2021 8
1 b 2022 10
</code></pre>
<p>I want to groupby id and variable and subtract 2020 values from all the rows of the group. So I will ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> if not sure if <code>2020</code> is first per groups:</p>
<pre><code>df1 = df[df['year'].eq(2020)]
df['value'] -= df.merge(df1,how='left',on=['id','variable'... | python|pandas|dataframe|group-by | 3 |
7,750 | 60,053,378 | How do I count the features percentage when only the label is true in Python machine learning? | <p>I'm using Jupyter to learn machine learning.</p>
<p>I would like to know how to count the features percentage (Style, Typo, Layout percentage) when only the "Like" column is 1?</p>
<p><img src="https://i.stack.imgur.com/bYpP4.png" alt="enter image description here"></p> | <p>I'm assuming you want to find the percentage of each unique value for each column when Like == 1. If that's the case, you can do:</p>
<pre><code>df[df['Like'] == 1]['Style'].value_counts(normalize=True) * 100
df[df['Like'] == 1]['Typo'].value_counts(normalize=True) * 100
df[df['Like'] == 1]['Layout'].value_counts... | python|pandas|machine-learning|count|jupyter | 0 |
7,751 | 60,171,858 | Why machine learning algorithms focus on speed and not accuracy? | <p>I study ML and I see that most of the time the focus of the algorithms is run time and not accuracy. Reducing features, taking sample from the data set, using approximation and so on.</p>
<p>Im not sure why its the focus since once I trained my model I dont need to train it anymore if my accuracy is high enough and... | <p>Speed is relative term. Accuracy is also relative depending on the difficulty of the task. Currently the goal is to achieve human-like performance for application at reasonable costs because this will replace human labor and cut costs.</p>
<p>From what I have seen in reading papers, people usually focus on accuracy... | tensorflow|machine-learning | 1 |
7,752 | 65,215,320 | openCV doesn't always actualize the display/show the image | <p>I am displaying some very simple numpy array with openCV by using <code>cv2.imshow()</code> and <code>cv2.waitKey()</code>. Sometimes, I want a display to stay for a few seconds and then resume my program. I simply add a <code>time.sleep()</code> with the desired sleep value. Most of the time, everything works fine;... | <p>I would suggest that you <em>not</em> use <code>time.sleep</code> in GUI programs (OpenCV's imshow counts as a GUI).</p>
<p>work with the delay argument to <code>waitKey()</code>. pass 1000 for one second of maximum delay.</p>
<p>the GUI locks up if waitKey() isn't running enough. waitKey runs the event/message loop... | python|numpy|opencv | 0 |
7,753 | 50,048,786 | Apply property pandas.DataFrame.shape to multiple dataframe stored in a tuple | <p>I have a function which returns as output a tuple containing multiple <code>pd.DataFrame</code> objects.</p>
<p>Take the example:</p>
<pre><code>import pandas as pd
def myfunction():
x = pd.DataFrame(data = [1,2,3])
y = pd.DataFrame(data = [[1,2,3],[4,5,6]])
return x, y
myfunction()
</code></pre>
<p>I ... | <p>One way is to use <code>operator.attrgetter</code>:</p>
<pre><code>from operator import attrgetter
shapes = list(map(attrgetter('shape'), myfunction()))
[(3, 1), (2, 3)]
</code></pre>
<p>Although you are not looking for an explicit loop, this is the more readable version:</p>
<pre><code>shapes = [x.shape for x ... | python|pandas | 1 |
7,754 | 49,810,707 | compare list of data with CSV file and sort the matching | <p>I have a data set of product names and a brands list.
I need to find the how much branded products are there in my list.</p>
<pre><code>**Brands sample :** ['HM International', 'Sara', 'Wildcraft', 'Nike']
**Product name sample :** [Attache backpack11Green Waterproof Backpack
Simba BTSPOKEMON POKÈMON POKÈ BALLS 18... | <p>I suggest use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.findall.html" rel="nofollow noreferrer"><code>str.findall</code></a> with <code>word boundary regex</code> for search multiple values, then flatten nested lists and use <a href="https://docs.python.org/3.5/library/collecti... | python|pandas|analytics|data-analysis|text-analysis | 0 |
7,755 | 49,977,236 | TensorFlow broadcasting | <p>Broadcasting is the process of making arrays with different shapes have compatible shapes for arithmetic operations. In numpy, we can broadcast arrays.
Does TensorFlow graph support broadcasting similar to the numpy one?</p> | <p>yes it is supported. Open a terminal and try this:</p>
<pre><code>import tensorflow as tf
#define tensors
a=tf.constant([[10,20],[30,40]]) #Dimension 2X2
b=tf.constant([5])
c=tf.constant([2,2])
d=tf.constant([[3],[3]])
sess=tf.Session() #start a session
#Run tensors to generate arrays
mat,scalar,one_d,two_d = se... | python|tensorflow|array-broadcasting | 3 |
7,756 | 50,199,829 | how to calculation cost time | <pre><code>id|order_id|order_no|order_status|remark|handle_time|create_time|update_time
11237|3942|2018050307542800005985|新建订单||20180503075428|2018/5/3 07:54:28|2018/5/3 07:54:28
11238|3943|2018050307591600005986|新建订单||20180503075916|2018/5/3 07:59:16|2018/5/3 07:59:16
11239|3943|2018050307591600005986|新建订单||2018050308... | <p>I think I understand what you're asking. You just want to have a new dataframe that calculates the time difference between the three different entries for each unique order id?</p>
<p>So, I start by creating the dataframe:</p>
<pre><code>data = [
[11238,3943,201805030759165986,'新建订单',20180503075916,'2018/5/3 ... | python|pandas|dataframe | 0 |
7,757 | 64,015,321 | Escaping missing parenthesis using pandas str.match | <p>I'm having trouble with regex. I'm trying to check if my database fully matches with the item name I'm working. The problem is that sometimes the data is incomplete and I'll get errors. I would like to ignore regex completely as it is not necessary at this point.</p>
<p>For example the code below returns <code>re.er... | <p>If I understand your post correctly, you are trying to use the data read to create a regex. Since you don't want these treated as regexes, you might simply use string comparisons.</p>
<p>However, if your application requires the use of regex, you can use re.escape() render the string as literal so the paren won’t be... | python|pandas|match | 0 |
7,758 | 63,835,532 | Input 0 of layer sequential is incompatible with the layer expected ndim=3, found ndim=2. Full shape received: [None, 1] | <p>I am working with keras for text classification. After pre-processing and vectorization my train and validation data details is like bellow:</p>
<pre><code>print(X_train.shape, ',', X_train.ndim, ',', type(X_train))
print(y_train.shape, ',', y_train.ndim, ',', type(y_train))
print(X_valid.shape, ',', X_valid.ndim, '... | <p>I finally overcame the problem with the help of <a href="https://www.kaggle.com/hassanamin/time-series-analysis-using-lstm-keras/notebook" rel="noreferrer">this kaggle notebook</a>.</p>
<p>I change data dimensions to:</p>
<pre><code>print(X_train.shape)
print(y_train.shape)
print(X_valid.shape)
print(y_valid.shape)
... | python|tensorflow|keras|model-fitting | 8 |
7,759 | 46,883,276 | How long does tensorflow object detection API train.py complete training using CPU only? | <p>I am a beginner in machine learning. Recently, I had successfully running a machine learning application using <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Tensorflow object detection API</a>.
My dataset is 200 images of object with 300*300 resolution... | <p>It depends on your desired accuracy and data set of course but I generally stop training when the loss value gets around 4 or less. What is your current loss value after 9000 steps?</p> | python|tensorflow|object-detection | 2 |
7,760 | 47,048,846 | How can I output csv of groupby object? | <p>I get the follow data with code :</p>
<pre><code>import pandas as pd
df = {'ID': ['H1','H2','H3','H4','H5','H6'],
'AA1': ['C','B','B','X','G','G'],
'AA2': ['W','K','K','A','B','B'],
'name':['n1','n2','n3','n4','n5','n6']
}
df = pd.DataFrame(df)
df.groupby('AA1').apply(lambda x:x.sort_values('name... | <p>CSV formats have its limitations. One of them being keeping information about multi-indexes. You will have to keep track and judiciously load your data. Here's an example. </p>
<pre><code>df
AA1 AA2 ID name
AA1
B 1 B K H2 n2
2 B K H3 n3
C 0 C W H1 n1
G 4 ... | python|pandas|csv | 4 |
7,761 | 38,667,350 | function to return copy of np.array with some elements replaced | <p>I have a Numpy array and a list of indices, as well as an array with the values which need to go into these indices.</p>
<p>The quickest way I know how to achieve this is:</p>
<pre><code>In [1]: a1 = np.array([1,2,3,4,5,6,7])
In [2]: x = np.array([10,11,12])
In [3]: ind = np.array([2,4,5])
In [4]: a2 = np.copy(... | <p>Well you asked for a one-liner, here's one using sparse matrices with <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html" rel="nofollow"><code>Scipy's csr_matrix</code></a> -</p>
<pre><code>In [280]: a1 = np.array([1,2,3,4,5,6,7])
...: x = np.array([10,11,12])
...: i... | python|python-2.7|numpy | 2 |
7,762 | 38,584,494 | Python generator to read large CSV file | <p>I need to write a Python generator that yields tuples (X, Y) coming from two different CSV files. </p>
<p>It should receive a batch size on init, read line after line from the two CSVs, yield a tuple (X, Y) for each line, where X and Y are arrays (the columns of the CSV files).</p>
<p>I've looked at examples of la... | <p>You can have a generator, that reads lines from two different csv readers and yield their lines as pairs of arrays. The code for that is:</p>
<pre><code>import csv
import numpy as np
def getData(filename1, filename2):
with open(filename1, "rb") as csv1, open(filename2, "rb") as csv2:
reader1 = csv.read... | python|csv|numpy|bigdata | 28 |
7,763 | 38,694,292 | When create an optimizer in Tensorflow, how to deal with AttributeError happens? | <p>I try to incorporate a self-designed optimization algorithm PSGLD into TensorFlow. And that algorithm is similar to the concept of RMSProp. So I didn't create a new Op, but complement PSGLD following RMSProp. My procedure of incorporating is as follows:</p>
<ol>
<li><p>In Python side, create a <code>psgld.py</code>... | <p>(I'm assuming that you've rebuilt TensorFlow from source, as <a href="https://stackoverflow.com/questions/38694292/when-create-an-optimizer-in-tensorflow-how-to-deal-with-attributeerror-happens#comment64768151_38694292">Olivier suggested in his comment</a>, and you are trying to construct your optimizer as <code>opt... | optimization|tensorflow|deep-learning|attributeerror | 0 |
7,764 | 63,135,485 | How to use PyTorch's torchaudio in Android? | <p>Starting from <a href="https://pytorch.org/mobile/android/" rel="nofollow noreferrer">here</a>, I downloaded the tutorial project and got it to build and run. Then I tried adding this to the project's app build.gradle (after upping the pytorch version to 1.5.0):</p>
<pre><code>implementation 'org.pytorch:pytorch_and... | <p>Got this answer from <a href="https://github.com/pytorch/audio/issues/408#issuecomment-665052963" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>There is no android package dedicated for torchaudio. You build your model or pipeline in Python, then dump it as a Torchscript file, then load it from your app an... | android|pytorch | 0 |
7,765 | 67,869,267 | 'Subset' object is not an iterator for updating torch' legacy IMDB dataset | <p>I'm updating a pytorch network from legacy code to the current code. Following documentation such as that <a href="https://colab.research.google.com/github/pytorch/text/blob/master/examples/legacy_tutorial/migration_tutorial.ipynb#scrollTo=opQ6LcnigTKx" rel="nofollow noreferrer">here</a>.</p>
<p>I used to have:</p>
... | <p>Try <code>next(iter(train_data))</code>. It seems one have to create iterator over <code>dataset</code> explicitly. And use <code>Dataloader</code> when effectiveness is required.</p> | pytorch|sentiment-analysis|imdb | 0 |
7,766 | 67,834,173 | AttributeError : has no attribute 'BatchNormalizationBase | <p>when I run the script, there is error</p>
<pre><code>File "akurasi.py", line 3, in <module>
import keras
File "C:\projeku\Lib\site-packages\keras\__init__.py", line 21, in <module>
from tensorflow.python import tf2
File "C:\projeku\Lib\site-packages\tensorflow\__init__.py... | <p>Your issue can be resolved, once you modify imports as shown below</p>
<pre><code>import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout
from tensorflow.keras.preprocessing.image im... | python|tensorflow|keras|conv-neural-network | 1 |
7,767 | 67,944,419 | set values to columns but using indexes | <p>I have a dataframe like this:</p>
<pre><code>a b c d e
42 1 0 1 0
42 0 0 0 1
42 0 1 0 0
42 1 1 0 0
</code></pre>
<p>I want to do something that can make all 1 in column bcde equal to column a, so it will basically be this:</p>
<pre><code>a b c d e
42 42 0 42... | <p>Edit:
You can simply use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer">pandas.DataFrame.where()</a> and give it the <code>df["a"] Series</code> as replacement. This way, it will work for both numbers and strings.</p>
<pre><code># df is your Dat... | python|pandas | 0 |
7,768 | 67,668,520 | group gps data on haversine distance and calculate the mean | <p>I have a dataframe like following (cannot show from original due to NDA):</p>
<pre><code>points = [(-57.213878612138828, 17.916958304169601),
(76.392039480378514, 0.060882542482108504),
(0.12417670682730897, 1.0417670682730924),
(-64.840321976787706, 21.374279296143762),
(-48.... | <p>I took a different approach on some steps by utilizing pandas functionality, but that should do it.</p>
<p>First, from your provided data set, I created a helper dataframe that gives me a point I and the point as list.</p>
<pre><code>points = (df
.assign(
id = lambda x : np.arange(len(x)),
point ... | python|pandas|dataframe|grouping|cluster-analysis | 1 |
7,769 | 67,793,711 | Plot argmax of numpy array | <p>I have a numpy array with shape (20,20,6).</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.cm as cm
num_channels = 6
a = np.random.choice(range(100),(20,20,num_channels))
</code></pre>
<p>I want to get an array with shape (20,20,4), 20x20 times an RGBA colour indicating whic... | <p>This should do what you want.</p>
<pre class="lang-py prettyprint-override"><code>import random
import numpy as np
import matplotlib.cm as cm
# get colormap
num_channels = 6
color_list = cm.rainbow(np.linspace(0, 1, num_channels))
# generate an array
a = np.random.rand(20,20,6)
a = np.argmax(a, axis=-1)
print(a)
... | python|arrays|numpy | 0 |
7,770 | 41,236,061 | python pandas how to combine the pandas with the same column value | <p>convert this frame: </p>
<pre><code>1, 2
----
a, g
a, a
a, j
d, b
c, e
</code></pre>
<p>into:</p>
<pre><code>1, 2
----
a, g,a,j
d, b
c, e
</code></pre>
<p>what can I do, can I use groupby? what other methods?</p> | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <code>apply</code> function <code>join</code>:</p>
<pre><code>df.columns = list('AB')
print (df)
A B
0 a g
1 a a
2 a j
3 d b
4 c e
df = df.... | python|python-2.7|pandas | 2 |
7,771 | 41,538,692 | Using sparse matrices with Keras and Tensorflow | <p>My data can be viewed as a matrix of 10B entries (100M x 100), which is very sparse (< 1/100 * 1/100 of entries are non-zero). I would like to feed the data into into a Keras Neural Network model which I have made, using a Tensorflow backend.</p>
<p>My first thought was to expand the data to be dense, that is, ... | <p>Sorry, don't have the reputation to comment, but I think you should take a look at the answer here: <a href="https://stackoverflow.com/questions/37609892/keras-sparse-matrix-issue">Keras, sparse matrix issue</a>. I have tried it and it works correctly, just one note though, at least in my case, the shuffling led to ... | tensorflow|sparse-matrix|keras | 19 |
7,772 | 41,510,045 | Pandas groupby().apply() - returning None from the applied function messes up the results | <p>I perform groupby() and apply() on a few data frames with the same structure:</p>
<pre><code>d = d.groupby( 'groupby_col', as_index = False ).apply( some_function )
</code></pre>
<p>For some it works as expected, for some it fails. The way it fails is that the dataframe becomes a series where each element contains... | <p>The problem goes away if instead of returning None from the applied function I alway return a frame - replaced</p>
<pre><code>if some_condition:
return
</code></pre>
<p>with</p>
<pre><code>if some_condition:
return d[:0] # return the empty frame so that the columns match
</code></pre> | python|pandas|data-structures|dataframe | 0 |
7,773 | 61,304,463 | Issue with keras fit_generator epoch | <p>I'm creating an LSTM Model for Text generation using Keras. As the dataset(around 25 novels,which has around 1.4 million words) I'm using can't be processed at once(An Memory issue with converting my outputs to_Categorical()) I created a custom generator function to read the Data in. </p>
<pre><code># Data generato... | <p>From many sources in the Internet, this issue seems to occur while using <code>LSTM Layer</code> along with <code>Masking Layer</code> and while training on <code>GPU</code>.</p>
<p>Mentioned below can be the workarounds for this problem:</p>
<ol>
<li><p>If you can compromise on speed, you can Train your <code>Mod... | python|tensorflow|keras|deep-learning | 0 |
7,774 | 61,607,694 | pandas df.fillna() not replacing na values | <p>I have a dataframe that looks like this <strong>(For clarity: This represents a df with 5 rows and 8 columns)</strong>: </p>
<pre><code> BTC-USD_close BTC-USD_volume LTC-USD_close LTC-USD_volume \
time
1528968660 6489.549805 ... | <p>Ah.</p>
<p>You cannot <code>ffill</code> a <code>NaN</code> value if it is the first value of a series: it has no previous value.</p>
<p>Using <code>.ffill().bfill()</code> could solve this but might be creating false data.</p> | python|pandas | 1 |
7,775 | 61,600,636 | Adding new element into 3 dimensional array NUMPY | <p>I have an array, which shape's is equal to (1,59,1)
It looks in the following way:</p>
<pre><code>[[[0.93169003]
[0.96923472]
[0.97881434]
[0.99266784]
[0.97358235]
............
[0.83777312]
[0.82086134]]]
</code></pre>
<p>I wish I could add new element to the end, which is equal to [[0.86442673]], s... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>arr=np.append(arr,[[[0.86442673]]], axis=1)
</code></pre>
<p>Where <code>arr</code> is your input array</p> | python|arrays|numpy | 0 |
7,776 | 61,443,044 | Find words from one DataFrame in string of another DataFrame | <p>I have two DataFrames and need to find out how many times a word from the second DataFrame occurs in the first DataFrame.</p>
<pre><code>df = pd.DataFrame({"Field_6" : ["THE SURGEON RECEIVED A WARNING MESSAGE ON THE SCREEN INDICATING THE INSTRUMENT WAS BROKEN.",
"ON MAY 10 2015, THE REPORTER CONTACTED THE COMPANY ... | <p>You can use existing packages to meet your goal here and process the data much faster.</p>
<p>packages needed to use below solution flashtext and inflection (there are other packages as well, we need any package having functionality to change plural english words to singular). Better option is to expand your df2 an... | python|pandas | 0 |
7,777 | 68,836,573 | Sorting 2 single dimensional arrays into a 1 dimensional array | <p>I am trying to write a code that chooses one by one from <code>a</code> and <code>b</code>. I want to make a 2 dimensional array where the first index is either <code>0 or 1</code>. <code>0</code> representing <code>a</code> and <code>1</code> representing <code>b</code> and the second index would just be the values... | <p>This isn't a Numpy solution, but may work if you are okay processing these as lists. You can make iterators out of the lists, then alternate between them using <code>itertools.dropwhile</code> to proceed through the elements until you get the next in line. It might look something like:</p>
<pre><code>from itertools ... | python|arrays|function|numpy|multidimensional-array | 1 |
7,778 | 68,775,953 | Cant read xlsx file with pandas | <p>I am trying read .xlsx file as dataframe. File itself has two worksheet but when I tried to read it returns empty worksheet. Even though I have specified the sheet_name, it returns there is not a worksheet named like you have provided.</p>
<p>I have used several methods but all returns [].
'''</p>
<pre><code>from op... | <p>Thanks everyone, I found the problem. It was because of excel.</p> | python|excel|pandas | 0 |
7,779 | 68,474,569 | How to skip duplicates and blank values from JSON dataframe and store into an array? | <p>The following code displays data from a JSON Line file.</p>
<pre><code>import pandas as pd
import numpy
start = time.time()
with open('stela_zerrl_t01_201222_084053_test_edited.json', 'r') as fin:
df = pd.read_json(fin, lines=True)
parsed_data = df[["SRC/Word1"]].drop_duplicates().replace('', np.... | <p>Yup! Pandas has built-in functions for all of these operations:</p>
<pre><code>import pandas as pd
df = pd.read_json('stela_zerrl_t01_201222_084053_test_edited.json', lines=True)
series = df['SRC/Word1']
no_dupes = series.drop_duplicates()
no_blanks = no_dupes.dropna()
final_list = no_blanks.tolist()
</code></pre>
<... | python|json|pandas | 1 |
7,780 | 36,521,388 | multi column selection with pandas xs function is failed | <p>I have a following multiindex time-series data.</p>
<pre><code>first 001 \
second open high low close jdiff_vol value
date time
20150721 90100 2082.18 2082.18 ... | <p>Example:</p>
<pre><code>df = pd.DataFrame(
[[1,2,3,4,5,6,7,8]],
columns=pd.MultiIndex.from_product([['A','B'], ['a', 'b', 'c', 'd']])
)
Out:
A B
a b c d a b c d
1 2 3 4 5 6 7 8
</code></pre>
<p>we want to select columns <code>a</code> and <code>b</code>.</p>
<pre... | python|pandas|multiple-columns|multi-index | 2 |
7,781 | 52,922,131 | Adjusting dataframe columns in Pandas | <p>I have a dataframe output that looks like this:</p>
<pre><code>Index Region Date
0 W S CENTRAL Sep 2018
1 388
0 MOUNTAIN Sep 2018
1 229
0 PACIFIC Sep 2018
1 145
</code></pre>
<p>I would like to put each iteration of ... | <p>You can use the shift function in your case. (looking at how your dataframe looks like)</p>
<pre><code>df['Total'] = df['Region'].shift(-1)
df = df[df.index %2 == 0]
order = [0,2,1]
df = df[df.columns[order]]
</code></pre> | python|python-3.x|pandas|list|dataframe | 1 |
7,782 | 53,274,668 | Creating a data frame during a for loop | <p>So, I have the following bit of code</p>
<pre><code>for category in ['a','b','c','d']:
'HML_Flag_'+ category = pd.merge(category,HML_base_table,'inner','random')
'HML_Flag_'+ category = 'HML_Flag_'+ category[['random','HML']]
'HML_Flag_'+ category = 'HML_Flag_'+ category.groupby('HML').count()
</code></pre>
<p... | <p>try this,</p>
<p>Note: This method is highly not recommended</p>
<pre><code>for category in ['a','b','c','d']:
exec("%s=%d" % ('HML_Flag_'+ category , 5))
print HML_Flag_a
</code></pre>
<p>Instead of above code use below,</p>
<pre><code>dic={}
for category in ['a','b','c','d']:
dic['HML_Flag_'+ category]... | python|pandas | 0 |
7,783 | 53,008,798 | Complete pandas dataframe with zero values for large datasets | <p>I have a dataframe that looks like this:</p>
<pre><code>>> df
index week day hour count
5 10 2 10 70
5 10 3 11 80
7 10 2 18 15
7 10 2 19 12
</code></pre>
<p>where <code>week</code> is the week of the year, <code>day</code> is day of the week (<code>... | <p>As an alternative, you can use <code>itertools.product</code> for the creation of <code>dummy_df</code> as a product of lists:</p>
<pre><code>import itertools
index = range(100)
weeks = range(53)
days = range(7)
hours = range(24)
dummy_df = pd.DataFrame(list(itertools.product(index, weeks, days, hours)), columns=[... | python|pandas | 1 |
7,784 | 53,163,862 | What is the maximum number of pseudo-random numbers that can be generated with numpy.random before the sequence begins to repeat? | <p>I need to generate many hundreds of millions of random numbers for a clustering analysis. I am using numpy.random and was wondering if anyone knows the maximum number of pseudo-randoms that can be generated with numpy.random before the sequence begins to repeat? A quick look in the numpy documentation didn't help.</... | <p>It is, I believe, Mersenne Twister with period 2<sup>19937</sup>-1</p>
<p><a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.set_state.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.set_state.html</a></p> | python|numpy|random|numpy-random | 3 |
7,785 | 21,189,107 | Getting the index and value from a Series | <p>I'm having a bit of a slow moment with selection and indexing in pandas.</p>
<p>I have a Date Time series from which I am trying to select certain elements, along with their date time index in order to append them to a new series.
Example:</p>
<pre><code>import pandas as pd
x=pd.Series([11,12,13,14,15,16,17,18,19... | <p>To get both index and value, you can iterate over series. Note that default index starts from <code>0</code>, not from <code>1</code>:</p>
<pre><code>>>> for i, v in x.iteritems():
... print i, v
...
0 11
1 12
2 13
3 14
4 15
5 16
6 17
7 18
8 19
9 20
</code></pre>
<p>Sure you can assign a custom index t... | python|indexing|pandas|append|series | 4 |
7,786 | 63,355,338 | extracting data with different columns from different rows from pd dataframe | <p>Is there any way to extract data from dataframe by selecting different columns and different rows. For example, I want 3rd column data from row 1-100 and 2nd column data from row 101-200. I am currently using for loop but would be nice if there is any faster option.</p>
<pre><code>low_data =[]
up_data = []
for i in... | <p>you coud create your indexer:</p>
<pre><code>ix = np.array([np.arange(100), np.arange(100, 200)]).T
iy = np.array([[1, 2]])
</code></pre>
<p>and the values are then</p>
<pre class="lang-py prettyprint-override"><code>df.values[ix, iy]
</code></pre> | python|pandas | 0 |
7,787 | 63,630,933 | Expected input batch_size (1) to match target batch_size (10) | <p>I'm trying to run MNIST dataset in PyTorch, I'm using cross-entropy loss and simple Neural network of neurons(748,512,128,10) for the process. But I'm getting this error:</p>
<pre><code>ValueError: Expected input batch_size (1) to match target batch_size (10).
</code></pre>
<p>My Model:</p>
<pre><code>class Netz(nn.... | <p>I believe that your</p>
<pre><code>loss=criterion(y_pred,y.flatten())
</code></pre>
<p>should be modified to</p>
<pre><code>loss=criterion(y_pred.squeeze(0),y.flatten())
</code></pre>
<p>to match the size at the first dimension.</p> | python|pytorch|mnist | 0 |
7,788 | 21,603,275 | How could I make logarithmic bins between 0 and 1? | <p>I want to bin my data logarithmically while they are distributed between zero and one. I use this command :</p>
<pre><code>nstep=10
loglvl=np.logspace(np.log10(0.0),np.log10(1.0),nstep)
</code></pre>
<p>but it doesn't work. any idea how it can be done in python?</p> | <p>How about:</p>
<pre><code>np.logspace(0.0, 1.0, nstep) / 10.
</code></pre> | python|numpy|scipy | 2 |
7,789 | 21,750,012 | Is there a way to make a complex number in NumPy with the accuracy of a Decimal type? | <p>I'm working in Python with NumPy arrays of complex numbers that extend well past the normal floating point limits of NumPy’s default <em>Complex</em> type (numbers greater than 10^500). I wanted to know if there was some way I could extend NumPy so that it will be able to handle complex numbers with this sort of mag... | <p>Depending on your platform, you may have support for complex192 and/or complex256. These are generally not available on Intel platforms under Windows, but they are on some others—if your code is running on <a href="https://en.wikipedia.org/wiki/Solaris_%28operating_system%29" rel="nofollow noreferrer">Solaris</a> or... | python|numpy|decimal|precision|complex-numbers | 2 |
7,790 | 24,821,390 | Read columns from file where first row is string | <p>What I would like to do is to read in columns from a <code>.dat</code> file. I have been able to do this using <code>scitools.filetable.read_columns()</code>. The problem that I am having is that the first row of my <code>.dat</code> file contains <code>strings</code>. How can I skip the first row?</p>
<p>So for a ... | <h1>Use <code>fp.next</code> to advance one line further</h1>
<p>As <code>fp</code> is file descriptor for file open in text mode, iterating over it reads it line by line.</p>
<p>You can ask <code>fp</code> to read one line further by <code>fp.next()</code> and then pass it to your `scitools.filetable.read_colums(fp)... | python|numpy|scitools | 1 |
7,791 | 24,777,820 | Numpy array within a specific range | <p>I have a numpy array, <code>z</code>, of around 400,000 values. The range of <code>z</code> is from <code>0 to 2.9</code></p>
<p>I want to divide this array into four parts: </p>
<pre><code>z1 = 0.0<z<=0.5
z2 = 0.5<z<=1.0
z3 = 1.0<z<=1.5
z4 = 1.5<z<=2.9
</code></pre>
<p>I have been using: ... | <p>The problem is that <code>np.where()</code> returns the indices. To get the values you can do:</p>
<pre><code>z1 = np.take(z, np.where(np.logical_and(z>0, z<=0.5))[0])
</code></pre>
<p>and so forth...</p>
<p>It is perhaps faster to directly use the mask to obtain the values through fancy indexing:</p>
<pre... | python|arrays|numpy|range | 0 |
7,792 | 24,847,560 | best way to plot web based graph in Python | <p>Is there a python package to generate web based interactive bar graphs?</p>
<p>I have the following requirements:</p>
<ul>
<li><p>I cannot use plotly, matplotlib as they depend on numpy (lots of dependencies). My environment cannot install any such packages, however I can try using the source of the package.</p></... | <p>You need to rely on d3.js if you want to do without any packages.
Generate data from python , render in d3.js for plotting , and interactivity.
Not reusable much , not suitalbe if project is huge.
<a href="http://d3js.org" rel="nofollow noreferrer">http://d3js.org</a></p>
<p>If you are looking for full stack (which... | python|numpy|plotly | 1 |
7,793 | 24,528,218 | Aligning array values | <p>Lets say I have two arrays, both with values representing a brightness of the sun. The first array has values measured in the morning and second one has values measured in the evening. In the real case I have around 80 arrays. I'm going to plot the pictures using matplotlib. The plotted circle will (in both cases) b... | <p>One thing that may cause problems with this kind of data is that the images are not nicely aligned with the pixels. I try to illustrate my point with two arrays with a square in them:</p>
<pre><code>array1:
0 0 0 0 0
0 2 2 2 0
0 2 2 2 0
0 2 2 2 0
0 0 0 0 0
array2:
0 0 0 0 0
0 1 2 2 1
0 1 2 2 1
0 1 2 2 1
0 0 0 0 0
<... | python|arrays|numpy|matplotlib | 3 |
7,794 | 53,474,945 | Cannot plot dataframe as barh because TypeError: Empty 'DataFrame': no numeric data to plot | <p>I have been all over this site and google trying to solve this problem.<br>
It appears as though I'm missing a fundamental concept in making a plottable dataframe.<br>
I've tried to ensure that I have a column of strings for the "Teams" and a column of ints for the "Points"<br>
Still I get: TypeError: Empty 'DataFra... | <pre><code>df.plot(x = "Team", y="Points", kind="barh");
</code></pre>
<p><a href="https://i.stack.imgur.com/1kN2a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1kN2a.png" alt="enter image description here"></a></p> | python-3.x|pandas|matplotlib | 3 |
7,795 | 53,562,669 | how to average all rows of the data set when a certain column's row has similar value | <p>Consider the Time column there are two 18 values so i want to average those two rows which contain that 18 value.
<a href="https://i.stack.imgur.com/II1hS.png" rel="nofollow noreferrer">this is a picture of the data set</a></p> | <p>I'm not sure how you have your columns and rows indexed in your actual code, how the table was generated, etc. so you can't just copy and paste this but something in this vein might work.</p>
<pre><code> for i in time
if i==i+1:
rows[i]=(rows[i]+rows[i+1])/2
rows.remove(rows[i+1]
... | python|pandas | 0 |
7,796 | 53,753,929 | I can't solve issue "axis -1 is out of bounds for array of dimension 0" | <p>I'm trying to model the motion of a spring pendulum and this is my code:</p>
<pre><code>import numpy as np
from scipy.integrate import odeint
from numpy import sin, cos, pi, array
import matplotlib.pyplot as plt
#Specify initial conditions
init = array([pi/18, 0]) # initial values
def deriv(z, t):
x,y=z
... | <p>The problem happens because <code>x</code> and <code>y</code> are integers, not arrays, so you can't do <code>np.diff(y,1)</code>.</p>
<p>But your problem is deeper. Each entry of the <code>y</code> array must fully describe your system, this means that every value needed to compute <code>dx2dt2</code> and <code>dy... | python|numpy|indexoutofboundsexception|odeint|index-error | 3 |
7,797 | 53,645,041 | CSV Files and pandas | <p>I assume this is a trick question on this hw i'm working on but maybe it's not?</p>
<p>What object do you get after reading a csv file?</p>
<p>data frame</p>
<p>character vector</p>
<p>panel</p>
<p>all of the above</p>
<p>From what I know, you can use pandas to read in a csv file into a dataframe. But i know a... | <p>The time when you read a CSV file into a variable it is stored as a <code>pandas.core.frame.DataFrame</code> object which you are familiar of. </p>
<p>Now, talking about <code>Panel</code>, which represents wide format panel data, stored as 3-dimensional array have been deprecated since version 0.20.0 as listed <a ... | python|pandas|csv | 1 |
7,798 | 53,619,239 | How to adjust Moving Average for weekly analysis? | <p>I need to plot moving average on the basis of weekly intervals like 3 week interval or 21 days, but while adjusting for the missed dates it now counts 0 and thus it gives incorrect result.</p>
<pre><code>from nsepy import get_history as gh
from datetime import date
import pandas as pd
nifty = gh(symbol="NIFTY IT",... | <p>The simplest thing that comes to mind is that just remove the weekend values from your data:</p>
<pre><code>nifty=nifty[nifty['Close']!=0]
</code></pre>
<p>And then perform the moving average:</p>
<pre><code>nifty["3weekMA"]=nifty["Close"].rolling(15).mean()
</code></pre>
<p>Just instead of 21, use 15 and well, ... | python|pandas|algorithm|dataframe|nsepy | 1 |
7,799 | 53,363,060 | keras unable to call model.predict_classes for multiple times | <pre><code>def predictOne(imgPath):
model = load_model("withImageMagic.h5")
image = read_image(imgPath)
test_sample = preprocess(image)
predicted_class = model.predict_classes(([test_sample]))
return predicted_class
</code></pre>
<p>I have already trained a model. In this function, I load my model... | <p>Try loading model from file outside the function, and give the model object as argument to the function <code>def predictOne(imgPath, model)</code>. This will also be much faster, since the weights don't need to be loaded from disk every time a prediction is needed. </p>
<p>If you want to keep loading model inside ... | python|tensorflow|machine-learning|keras|prediction | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.