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 |
|---|---|---|---|---|---|---|
300 | 45,541,188 | Sample x number of days from a data frame with multiple entries per day in pandas | <p>I have a data frame with multiple time indexed entries per day. I want to sample and x number of days (eg 2 days) and the iterate forward 1 day to the end of the range of days. How can I achieve this.</p>
<p>For example if each day has greater than one entry:</p>
<pre><code> datetime value
2015-12-02 ... | <p>You can use:</p>
<pre><code>#https://stackoverflow.com/a/6822773/2901002
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice... | python|pandas | 1 |
301 | 62,646,775 | PyTorch arguments not valid on android | <p>I want to use <a href="https://github.com/wolverinn/Depth-Estimation-PyTorch" rel="nofollow noreferrer">this</a> model in my android app. But when I start the app it falls with an error. The model works fine on my PC.</p>
<h2>To Reproduce</h2>
<p>Steps to reproduce the behavior:</p>
<ol>
<li>Clone <a href="https://g... | <p>My pc PyTorch version was 1.5 and in dependences were 1.4. So solution is:</p>
<pre><code>implementation 'org.pytorch:pytorch_android:1.5.0'
implementation 'org.pytorch:pytorch_android_torchvision:1.5.0'
</code></pre> | android|pytorch | 0 |
302 | 54,581,339 | Pass series instead of integer to pandas offsets | <p>I have a dataframe (df) with a date and a number. I want to add the number to the date. How do I add the df['additional_days'] series to the df['start_date'] series using pd.offsets()? Is there a better way to do this?</p>
<blockquote>
<p>start_date additional_days</p>
<p>2018-03-29 360</p>
<p>... | <p>Use <code>pd.to_timedelta</code></p>
<pre><code>import pandas as pd
#df['start_date'] = pd.to_datetime(df.start_date)
df['start_date'] + pd.to_timedelta(df.additional_days, unit='d')
#0 2019-03-24
#1 2018-07-31
#2 2019-10-27
#3 2018-10-24
#4 2020-03-28
#dtype: datetime64[ns]
</code></pre> | python|pandas | 2 |
303 | 73,781,386 | tensorflow sequential model outputting nan | <p>Why is my code outputting nan? I'm using a sequential model with a 30x1 input vector and a single value output. I'm using tensorflow and python. This is one of my firs</p>
<pre><code>While True:
# Define a simple sequential model
def create_model():
model = tf.keras.Sequential([
keras.layers.Dense(30, act... | <p>You are using SparseCategoricalCrossentropy. It expects labels to be integers starting from 0. So, you have only one label <code>1</code>, but it means you have at least two categories - 0 and 1. So you need at least two neurons in the last layer:</p>
<pre><code>keras.layers.Dense(2, activation = 'sigmoid')
</code><... | keras|deep-learning|tensorflow2.0 | 0 |
304 | 73,836,043 | Extracting keys from dataframe of json | <p>I'm sorry, I am new to Python and wondering if anyone can help me with extracting data? I've been trying to extract data from a df with json-content.</p>
<pre><code>0 [{'@context': 'https://schema.org', '@type': '...
1 [{'@context': 'https://schema.org', '@type': '...
2 [{'@context': 'https://schema.org', '... | <p>Considering that the dataframe looks like this</p>
<pre><code>df = pd.DataFrame({'json_data': ['[{"@context": "https://schema.org", "@type": "Audiobook", "bookFormat": "AudiobookFormat", "name": "Balle-Lars og mordet i Ugledige 1858", &q... | python|json|pandas|key|extract | 1 |
305 | 73,803,762 | Python: Add dictionary to an existing dataframe where dict.keys() match dataframe row | <p>I'm trying to add a dictionary to a 26x26 dataframe with row and column both go from a to z:
<a href="https://i.stack.imgur.com/gisCe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gisCe.png" alt="my existing dataframe" /></a></p>
<p>My dictionary where I want to put in the dataframe is:</p>
<p><... | <p>You can use:</p>
<pre><code>df.loc[list(dic), 'a'] = pd.Series(dic)
</code></pre>
<p>Or:</p>
<pre><code>df.loc[list(dic), 'a'] = list(dic.values())
</code></pre>
<p>Full example:</p>
<pre><code>dic = {'b': 74, 'c': 725, 'd': 93, 'e': 601, 'f': 134, 'g': 200, 'h': 1253,
'i': 355, 'j': 5, 'k': 2, 'l': 324, 'm':... | python|pandas|dataframe|dictionary | 0 |
306 | 71,203,685 | Splitting strings in dataframe | <p>I have a column with strings. I want to split and create a new column in the dataframe.</p>
<p>For example:</p>
<pre><code>2022-01-28 15-43-45 150
</code></pre>
<p>I want to split after <code>45</code> and create a new column.</p> | <p>We can use <code>str.extract</code> here:</p>
<pre class="lang-py prettyprint-override"><code>df["new_col"] = df["filename"].str.extract(r'(\d+)$')
df["filename"] = df["filename"].str.extract(r'(.*)\s+\d+$')
</code></pre> | pandas|string|dataframe|split | 0 |
307 | 71,288,635 | Is there a way to covert date (with different format) into a standardized format in python? | <p>I have a column calls "date" which is an object and it has very different date format like dd.m.yy, dd.mm.yyyy, dd/mm/yyyy, dd/mm, m/d/yyyy etc as below. Obviously by simply using df['date'] = pd.to_datetime(df['date']) will not work. I wonder for messy date value like that, is there anyway to standardized... | <p>Coerce the dates to datetime and allow invalid entries to be turned into nulls.Also, allow pandas to infer the format. code below</p>
<pre><code>df['date'] = pd.to_datetime(df['date'], errors='coerce',infer_datetime_format=True)
date
0 2022-02-17
1 2022-02-23
2 2022-02-17
3 2022-02-18
4 2022-02-22
5 2022-03-01... | python|pandas|date|python-re | 1 |
308 | 52,256,503 | Why does tf.variable_scope has a default_name argument? | <p>The first two arguments of <a href="https://www.tensorflow.org/api_docs/python/tf/variable_scope#__init__" rel="nofollow noreferrer"><code>tf.variable_scope</code>'s <code>__init__</code> method</a> are</p>
<blockquote>
<ul>
<li><code>name_or_scope</code>: <code>string</code> or <code>VariableScope</code>: the ... | <p>You are right. It is just a convenience. </p>
<p>Take the case of TensorFlow models defined <a href="https://github.com/tensorflow/models/tree/master/research/slim/nets" rel="nofollow noreferrer">here</a>. If you take a specific look at <a href="https://github.com/tensorflow/models/blob/master/research/slim/nets/in... | python|tensorflow | 0 |
309 | 52,243,060 | Get row value of maximum count after applying group by in pandas | <p>I have the following df</p>
<pre><code>>In [260]: df
>Out[260]:
size market vegetable confirm availability
0 Large ABC Tomato NaN
1 Large XYZ Tomato NaN
2 Small ABC Tomato NaN
3 Large ABC Onion NaN
4 Sma... | <p>1)</p>
<pre><code>required_df = veg_df.groupby(['vegetable','size'], as_index=False)['market'].count()\
.sort_values(by=['vegetable', 'market'])\
.drop_duplicates(subset='vegetable', keep='last')
</code></pre>
<p>2)</p>
<pre><code>merged_df = veg_df.merge(required_df, on='vegetable')
cols = ['si... | python|pandas|dataframe|pandas-groupby | 2 |
310 | 60,549,871 | How to continuously update the empty rows within specific columns using pandas and openpyxl | <p>Currently I'm running a live test that uses 3 variables data1, data2 and data 3. The Problem is that whenever I run my python code that it only writes to the first row within the respective columns and overwrites any previous data I had. </p>
<pre><code>import pandas as pd
import xlsxwriter
from openpyxl import loa... | <p>Use <code>startrow=...</code> of <code>to_excel</code> to shift every subsequent update down.</p> | python|pandas|openpyxl | 0 |
311 | 60,347,228 | How to confirm convergence of LSTM network? | <p>I am using LSTM for time-series prediction using Keras. I am using 3 LSTM layers with dropout=0.3, hence my training loss is higher than validation loss. To monitor convergence, I using plotting training loss and validation loss together. Results looks like the following. </p>
<p><a href="https://i.stack.imgur.com/... | <p>Convergence implies you have something to converge <em>to</em>. For a learning system to converge, you would need to know the right model beforehand. Then you would train your model until it was the same as the right model. At that point you could say the model converged! ... but the whole point of machine learning ... | python|tensorflow|keras|lstm|recurrent-neural-network | 0 |
312 | 72,832,661 | Adding or replacing a Column based on values of a current Column | <p>I am attempting to add a new column and base its value from another column of a dataframe, on the following 2 conditions, which will not change and will be written to a file after.</p>
<ol>
<li>If number -> (##) (4 character string)</li>
<li>If NaN -> (4 character string of white space)</li>
</ol>
<p>T... | <p>In this solution, first use <code>convert_dtypes</code> which converts <code>float</code> into <code>int</code>. Then change to <code>str</code>. This is just to remove the decimal point. Change <code><NA></code> to 4 white spaces. The last step, if the the string isnumeric, use left padding which will ensure ... | python|python-3.x|pandas|dataframe | 0 |
313 | 72,526,514 | Tensorboard: How to view pytorch model summary? | <p>I have the following network.</p>
<pre><code>import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
class Net(nn.Module):
def __init__(self,input_shape, num_classes):
super(Net, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=(3... | <p>I can see everything is going right but there is just a formatting issue. Tensorboard understands markdown so you can actually replace <code>\n</code> with <code><br/></code> and <code> </code> with <code>&nbsp;</code>.</p>
<p>Here is a detailed walkthrough. Suppose you have the following model:-</p>
<pre>... | deep-learning|pytorch|tensorboard|modelsummary | 0 |
314 | 72,670,305 | How to plot histogram for chosen cells using mean as condition in python? | <p>I have some data as x,y arrays and an array of v values corresponding to them, i.e for every x and y there is a v with matching index.</p>
<p><strong>What I have done</strong>: I am creating a grid on the x-y plane and then the v-values fall in cells of that grid. I am then taking mean of the v-values in each cell o... | <p>Maybe there is a better way, but you can create an empty list and append the lists that you want to plot:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x=np.array([11,12,12,13,21,14])
y=np.array([28,5,15,16,12,4])
v=np.array([10,5,2,10,6,7])
x = x // 4
y = y // 4
k=10
cells = [[[] for y in ra... | python|arrays|numpy|histogram|mean | 1 |
315 | 72,622,081 | Cannot export QNN brevitas to ONNX | <p>I have trained my model as QNN with brevitas. Basically my input shape is:</p>
<blockquote>
<p>torch.Size([1, 3, 1024])</p>
</blockquote>
<p>I have exported the .pt extended file. As I try my model and generate a confusion matrix I was able to observe everything that I want.
So I believe that there is no problem abo... | <p>The problem is related to pytorch version > 1.10. Where "enable_onnx_checker" is no more a parameter of torch.onnx.export function.</p>
<p>This is the official solution from the repository.
<a href="https://github.com/Xilinx/brevitas/pull/408/files" rel="nofollow noreferrer">https://github.com/Xilinx/br... | python|machine-learning|pytorch|fpga|onnx | 0 |
316 | 59,806,689 | Remove values above/below standard deviation | <p>I have a database that is made out of 18 columns and 15 million rows, in each column there are outliers and I wanted to remove values above and below 2 standard deviations. My code doesn't seem to edit anything in the database though.</p>
<p>Thank you.</p>
<pre><code>import pandas as pd
import random as r
import n... | <p>Perhaps because you didn't assign the results back to <code>df</code>?</p>
<p>From:</p>
<pre class="lang-py prettyprint-override"><code>df[df.apply(lambda x :(x-x.mean()).abs()<(2*x.std()) ).all(1)]
</code></pre>
<p>To:</p>
<pre class="lang-py prettyprint-override"><code>df = df[df.apply(lambda x :(x-x.mean()... | python|python-3.x|pandas|csv|jupyter-notebook | 1 |
317 | 59,481,895 | How to differentiate between trees and buildings in OpenCV and NumPy in Python | <p>I am trying to classify buildings and trees in digital elevation models. </p>
<p>Trees normally look like this: <a href="https://i.stack.imgur.com/ovnq1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ovnq1.png" alt="enter image description here"></a></p>
<p>Buildings normally look something lik... | <p>Disclaimer: My answer might be super overfitted and wrong, as it is based on just the two sample images</p>
<p>Approach 1 : </p>
<p>Just classify based on the 'squareness' - </p>
<pre><code>delta_x = |x_min - x_max|, delta_y = |y_min - y_max|
spread_ratio = delta_y/delta_x
if spread_ratio > thresh:
classify... | python|numpy|opencv|image-processing|classification | 0 |
318 | 61,787,472 | Reshape input layer 'requested shape' size always 'input shape' size squared | <p>I am trying to run a SavedModel using the C-API.
When it comes to running <code>TF_SessionRun</code> it always fails on various input nodes with the same error.</p>
<pre><code>TF_SessionRun status: 3:Input to reshape is a tensor with 6 values, but the requested shape has 36
TF_SessionRun status: 3:Input to reshape ... | <p>It turns out that the issue was caused by me not using the TF_AllocateTensor function correctly.</p>
<p>The original code was like:</p>
<pre><code>TF_Tensor* t = TF_AllocateTensor(TF_STRING, nullptr, 0, sz);
</code></pre>
<p>when it appears it should have been:</p>
<pre><code>int64_t dims = 0;
TF_Tensor* t = TF_... | tensorflow|predict|c-api | 0 |
319 | 61,939,491 | Two questions on DCGAN: data normalization and fake/real batch | <p>I am analyzing a meta-learning <a href="https://github.com/LuEE-C/FIGR/blob/master/train.py" rel="nofollow noreferrer">class</a> that uses DCGAN + Reptile within the image generation.</p>
<p>I have two questions about this code. </p>
<p>First question: why during DCGAN training (line 74)</p>
<pre><code>training_b... | <p>Training GANs involves giving the discriminator real and fake examples. Usually, you will see that they are given in two separate occasions. By default <a href="https://pytorch.org/docs/stable/torch.html#torch.cat" rel="nofollow noreferrer"><code>torch.cat</code></a> concatenates the tensors on the first dimension (... | deep-learning|pytorch|generative-adversarial-network|dcgan | 1 |
320 | 58,052,135 | separate 2D gaussian kernel into two 1D kernels | <p>A gaussian kernel is calculated and checked that it can be separable by looking in to the rank of the kernel. </p>
<pre><code>kernel = gaussian_kernel(kernel_size,sigma)
print(kernel)
[[ 0.01054991 0.02267864 0.0292689 0.02267864 0.01054991]
[ 0.02267864 0.04875119 0.06291796 0.04875119 0.02267864]
[ 0.... | <p>matrix rank 1 means that all the rows are either zero or the same up to scaling and the same is true for columns. They are also up to scaling equal to the two factors.
Therefore you can recover them using something like</p>
<pre><code>I,J = np.unravel_index(np.abs(kernel).argmax(), kernel.shape)
f1 = np.nansum(kern... | numpy|convolution | 0 |
321 | 54,783,721 | Add a fix value to a dataframe (accumulating to future ones) | <p>I am trying to simulate inventory level during the next 6 months:</p>
<p>1- I have the expected accumulated demand for each day of next 6 months.
<a href="https://i.stack.imgur.com/hEYd6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hEYd6.png" alt="enter image description here"></a>
So, with n... | <p>You forgot to assign the value i think. use <code>row['saldo'] += 10000</code> instead of <code>row['saldo'] + 10000</code></p> | python|pandas|numpy|dataframe | 1 |
322 | 54,818,602 | How to get pandas to return datetime64 rather than Timestamp? | <p>How can I tell pandas to return <code>datetime64</code> rather than <code>Timestamp</code>? For example, in the following code <code>df['dates'][0]</code> returns a pandas <code>Timestamp</code> object rather than the numpy <code>datetime64</code> object that I put in.</p>
<p>Yes, I can convert it after getting it,... | <p>Adding <code>values</code> </p>
<pre><code>df.dates.values[0]
Out[55]: numpy.datetime64('2019-02-15T00:00:00.000000000')
type(df.dates.values[0])
Out[56]: numpy.datetime64
</code></pre> | pandas|datetime64 | 0 |
323 | 49,438,360 | In Pandas how can I use the values in one table as an index to extract data from another table? | <p>I feel like this should be really simple but I'm having a hard time with it. Suppose I have this:</p>
<pre><code>df1:
ticker hhmm <--- The hhmm value corresponds to the column in df2
====== ====
AAPL 0931
IBM 0930
XRX 1559
df2:
ticker 0930 0931 0932 ... 1559 <<---- 390 columns
====== ... | <p>There is a function called <code>lookup</code></p>
<pre><code>df1['val']=df2.set_index('ticker').lookup(df1.ticker,df1.hhmm)
df1
Out[290]:
ticker hhmm val
0 AAPL 0931 4.57
1 IBM 0930 7.98
2 XRX 1559 33.00# I make up this number
</code></pre> | python|pandas|numpy|dataframe | 1 |
324 | 73,367,040 | Is there a way in python to read a text block within a csv cell and only select cell data based on key word with in text block? | <p>I am working with a CSV file in <strong>Pandas/Python</strong> and I need to find when a supplier response was submitted.
The column "time Line" contains the info I'm looking for and can vary on how much information was put into the response at the time but the keyword I am looking for is the same.</p>
<p>... | <p>Assuming your dataframe has a "time line" column:</p>
<p><code>new_df = df.loc[df['time Line'].str.contains('the string you are looking for')]</code></p>
<p>this will create a new dataframe with all rows that contains the string you need, is this what you are looking for?</p> | python|pandas|csv|data-analysis|data-extraction | 0 |
325 | 73,196,008 | How to replace a dataframe rows with other rows based on column values? | <p>I have a dataframe of this type:</p>
<pre><code> Time Copy_from_Time Rest_of_data
0 1 1 foo1
1 2 1 foo2
2 3 3 foo3
3 4 4 foo4
4 5 4 foo5
5 6 4 foo6
</code... | <p>use map in updating the value in rest_of_data column</p>
<pre><code>df['Rest_of_data']=df['Copy_from_Time'].map(df.set_index('Time')['Rest_of_data'])
df
</code></pre>
<pre><code> Time Copy_from_Time Rest_of_data
0 1 1 foo1
1 2 1 foo1
2 3 ... | python|pandas|dataframe | 1 |
326 | 73,314,741 | How to combine two columns | <p>I have a merged Pandas dataframe in the following format</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>value_x</th>
<th>value_y</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>nan</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>nan</td>
</tr>
<tr>
<td>2</td>
<td>nan... | <p>You can use <code>max</code></p>
<pre><code>df["value"] = df[["value_x", "value_y"]].max(axis=1)
</code></pre>
<p>as this will pick the non-nan value for each row. For this question:</p>
<blockquote>
<p>In addition, I would like to know if I could avoid the column combining process duri... | python|pandas | 2 |
327 | 67,522,909 | Create a new dataframe from an old dataframe where the new dataframe contains row-wise avergae of columns at different locations in the old dataframe | <p>I have a dataframe called "frame" with 16 columns and 201 rows. A screenshot is attached that provides an example dataframe</p>
<p><a href="https://i.stack.imgur.com/kEFnU.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Please note the screenshot is just an example, the original data... | <p>based on your desire "I would rather like to automate this process since this is repeated for other data files too"
what I can think of is this below:</p>
<pre><code>in [1]: frame = pd.read_csv('your path')
</code></pre>
<p>result shown below, now as you can see what you want to average are columns 1,5 an... | python|pandas|dataframe|loops|mean | 0 |
328 | 60,079,541 | Using tensorflow when a session is already running on the gpu | <p>I am training a neural network with tensorflow 2 (gpu) on my local machine, I'd like to do some tensorflow code in parallel (just loading a model and saving it's graph).</p>
<p>When loading the model I get a cuda error. How can I use tensorflow 2 on cpu to load and save a model, when another instance of tensorflow ... | <p>It took me a while to find this answer:</p>
<pre><code>import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import tensorflow as tf
</code></pre>
<p>Starting your code with those lines allows you to run your tf code on CPU (avoid using CUDA is the solution, obviously) while at the same time runnin... | python|tensorflow|tensorflow2.0 | 1 |
329 | 59,952,399 | pandas multiindex - remove rows based on number of sub index | <p>Here is my dataframe :</p>
<pre><code>df = pd.DataFrame(pd.DataFrame({"C1" : [0.5, 0.9, 0.1, 0.2, 0.3, 0.5, 0.2],
"C2" : [200, 158, 698, 666, 325, 224, 584],
"C3" : [15, 99, 36, 14, 55, 62, 37]},
index = pd.MultiIndex.from_tuples([... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="noreferrer"><code>GroupBy.transform</code></a> by first level with any column with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nor... | python|python-3.x|pandas|multi-index | 6 |
330 | 65,352,321 | Optimize the Weight of a layer while training CNN | <p>I am trying to train a neural network whose last layer like this,</p>
<pre><code>add_5_proba = Add()([out_of_1,out_of_2,out_of_3,out_of_4, out_of_5 ])
# Here I am adding 5 probability from 5 different layer
model = Model(inputs=inp, outputs=add_5_proba)
</code></pre>
<p>But now I want to give weight to them ,Like</... | <p>Just create <code>tf.Variables</code>:</p>
<pre><code>a = tf.Variable(1.)
b = tf.Variable(1.)
c = tf.Variable(1.)
d = tf.Variable(1.)
e = tf.Variable(1.)
add_5_proba = Add()([a * out_of_1, b * out_of_2, c * out_of_3, d * out_of_4, e * out_of_5 ])
model = Model(inputs=inp, outputs=add_5_proba)
</code></pre>
<p>These ... | python|python-3.x|tensorflow|keras | 1 |
331 | 49,820,811 | What does sess.run( LAYER ) return? | <p>I have tried to search around, but oddly enough, I can't find anything similar. </p>
<p>Let's say I have a few fully connected layers:</p>
<pre><code>fc_1 = tf.contrib.layers.fully_connected(fc_input, 100)
fc_2 = tf.contrib.layers.fully_connected(fc_1, 10)
fc_3 = tf.contrib.layers.fully_connected(fc_2, 1)
</code>... | <p>A fully-connected layer is a math operation that transforms an input tensor into an output tensor. The output tensor contains the values returned by the layer's activation function, which operates on the sum of the weighted values in the layer's input tensor.</p>
<p>When you execute <code>sess.run(fc_3)</code>, Ten... | python|tensorflow | 1 |
332 | 63,995,367 | Bin using cumulative sum rather than observations in python | <p>Let's say that I have a data frame that has a column like this:</p>
<pre><code>Weight
1
1
0.75
0.5
0.25
0.5
1
1
1
1
</code></pre>
<p>I want to create two bins and add a column to my data frame that shows which bin each row is in, but I don't want to bin on the observations (i.e. the first 5 observations got to bin 1... | <p>This should do it:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(
{'Weight': [1, 1, 0.75, 0.5, 0.25, 0.5, 1, 1, 1, 1]})
weight_sum = df.Weight.sum()
df['bin'] = 1
df.loc[df.Weight.cumsum() > weight_sum / 2, 'bin'] = 2
print(df)
</code></pre>
<p>Output:</p>
<pre><code> Weight bi... | python|pandas | 3 |
333 | 63,750,679 | Find the remainder mask between 2 masks in numpy for 2D array | <p>Let's say I have a 2D array:</p>
<pre><code>main = np.random.random((300, 200))
</code></pre>
<p>And I have two masks for this array:
e.g.,</p>
<pre><code>mask1 = list((np.random.randint((100), size = 50), np.random.randint((200), size = 50)))
mask2 = list((np.random.randint((20), size = 10), np.random.randint((20),... | <p>I think for your requirement a better approach is constructing a zero filled array same shape as <code>main</code> and assign <code>1</code> and <code>2</code> using <code>mask1</code> and <code>mask2</code></p>
<pre><code>main = np.zeros(main.shape)
main[mask1]=2
main[mask2]=1
</code></pre> | numpy|multidimensional-array|mask | 1 |
334 | 63,792,503 | How to color nodes within networkx using a column in Pandas | <p>I have this dataset:</p>
<pre><code> User Val Color
92 Laura NaN red
100 Laura John red
148 Laura Mike red
168 Laura Mirk red
293 Laura Sara red
313 Laura Sim red
440 Martyn Pierre orange
440 Martyn Hugh orange
440 Martyn Lauren orange
440 Martyn Sim orange... | <p>Looks like you're in the right track, but got a couple of things wrong. Along with using <code>drop_duplicates</code>, build a dictionary and use it to lookup the color in <code>nx.draw</code>. Also, you don't need to construct a <code>labels</code> dictionary, <code>nx.draw</code> can handle that for you.</p>
<pre>... | python|pandas|networkx | 2 |
335 | 63,298,842 | Placing dataframes into excel sheets | <p>i have two dataframes; df and df2. I need to place them into an excel, with df being in one sheet and df2 being in another sheet. What would be the easiest way to do this in python?</p> | <p>Refer <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer">Documentation</a>:</p>
<pre><code>with pd.ExcelWriter('output.xlsx') as writer:
df.to_excel(writer, sheet_name='Sheet_name_1')
df2.to_excel(writer, sheet_name='Sheet_name_2')
... | python|excel|pandas|dataframe | 1 |
336 | 67,935,182 | Website crawling based on keyword in Excel file | <p>I would like to crawl the website price based on the search keyword on my keyword.xlsx file , the first input should be dyson, second is lego, third input should be sony, but my result in the attached image only has dyson, do you know why?</p>
<p><a href="https://i.stack.imgur.com/sL7lw.jpg" rel="nofollow noreferrer... | <p>There's a few issues here. First, I'm not sure what <code>lowest_first=lowest.split("",1)[0]</code> is supposed to be doing in your code. It is throwing an error in your code preventing it from hitting the next iteration of your for loop. You can't split a string on nothing (""). If you are tryin... | python|excel|pandas | 0 |
337 | 67,997,979 | Pandas DataFrame create new columns based on a logic dependent on other columns with cumulative counting rule | <p>I have a DataFrame originally as follows:</p>
<p><code>d1={'on':[0,1,0,1,0,0,0,1,0,0,0],'off':[0,0,0,0,0,0,1,0,1,0,1]}</code></p>
<p><a href="https://i.stack.imgur.com/DCbJ6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DCbJ6.png" alt="Original" /></a></p>
<p>My end objective is to add a new col... | <p>One solution using a "state machine" implemented with <code>yield</code>:</p>
<pre class="lang-py prettyprint-override"><code>def state_machine():
on, off = yield
cnt, current = 0, on
while True:
current = int(on or current)
cnt += current
if off and cnt > 3:
... | python|pandas|dataframe | 2 |
338 | 67,980,140 | How to change a non top 3 values columns in a dataframe in Python | <p>I have a dataframe that was made out of BOW results called df_BOW</p>
<p>dataframe looks like this</p>
<pre><code>df_BOW
Out[42]:
blue drama this ... book mask
0 3 0 1 ... 1 0
1 0 1 0 ... 0 4
2 ... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.nlargest.html" rel="nofollow noreferrer"><code>pandas.Series.nlargest</code></a>, pass keep as <code>first</code> to include the first record only if multiple value exists for top 3 largest values. Finally use <code>fillna(0)</code> to f... | python|pandas | 3 |
339 | 67,840,664 | CNN-LSTM with TimeDistributed Layers behaving weirdly when trying to use tf.keras.utils.plot_model | <p>I have a CNN-LSTM that looks as follows;</p>
<pre><code>SEQUENCE_LENGTH = 32
BATCH_SIZE = 32
EPOCHS = 30
n_filters = 64
n_kernel = 1
n_subsequences = 4
n_steps = 8
def DNN_Model(X_train):
model = Sequential()
model.add(TimeDistributed(
Conv1D(filters=n_filters, kernel_size=n_kernel, activation='relu... | <p>An alternative to using an <code>Input</code> layer is to simply pass the <code>input_shape</code> to the <code>TimeDistributed</code> wrapper, and not the <code>Conv1D</code> layer:</p>
<pre class="lang-py prettyprint-override"><code>def DNN_Model(X_train):
model = Sequential()
model.add(TimeDistributed(
... | python|tensorflow|keras|deep-learning|conv-neural-network | 2 |
340 | 61,518,032 | problem with pandas drop_duplicates removing empty values | <p>Im using drop_duplicates to remove duplicates from my dataframe based on a column, the problem is this column is empty for some entries and those ended being removed to is there a way to make the function ignore the empty value.
here is an example </p>
<pre><code> Title summary ... | <p>Fill missing values with the index number? Maybe not the prettiest way but it works</p>
<pre><code>df = pd.DataFrame(
{'Title':['TITLE A', 'TITLE A', None, None], 'summary':['summaryA', 'summaryB',
'summaryC', 'summaryD']}
)
df['_id'] = df.index
df['_id'] = df['_id'].apply(str)
df['Title2'] = df['Titl... | pandas|drop-duplicates | 0 |
341 | 61,194,028 | Adding labels at end of line chart in Altair | <p>So I have been trying to get it so there is a label at the end of each line giving the name of the country, then I can remove the legend. Have tried playing with <code>transform_filter</code> but no luck.</p>
<p>I used data from here <a href="https://ourworldindata.org/coronavirus-source-data" rel="nofollow noreferr... | <p>You can do this by aggregating the x and y encodings. You want the text to be at the maximum x value, so you can use a <code>'max'</code> aggregate in x. For the y-value, you want the y value associated with the max x-value, so you can use an <code>{"argmax": "x"}</code> aggregate.</p>
<p>With a bit of adjustment o... | python|pandas|label|altair | 8 |
342 | 61,309,146 | Using the Python WITH statement to create temporary variable | <p>Suppose I have Pandas data. Any data. I import <code>seaborn</code> to make a colored version of the correlation between varibales. Instead of passing the correlation expression into the heatmap fuction, and instead of creating a one-time variable to store the correlation output, how can I use the <code>with</code>... | <p>You need to implement <strong>enter</strong> and <strong>exit</strong> for the class you want to use it.
see: <a href="https://stackoverflow.com/questions/3774328/implementing-use-of-with-object-as-f-in-custom-class-in-python">Implementing use of 'with object() as f' in custom class in python</a></p> | python-3.x|pandas|with-statement | 1 |
343 | 61,504,356 | Cross-validation of neural network: How to treat the number of epochs? | <p>I'm implementing a pytorch neural network (regression) and want to identify the best network topology, optimizer etc.. I use cross validation, because I have x databases of measurements and I want to evaluate whether I can train a neural network with a subset of the x databases and apply the neural network to the un... | <p>The number of epochs is better not to be fine-tuned.
Option 2 is a better option.
Actually, if the # of epochs is fixed, you need not to have validation set. Validation set gives you the optimal epoch of the saved model.</p> | python|neural-network|pytorch|cross-validation | 0 |
344 | 68,549,090 | pandas concat two column into a new one | <p>I have a csv file with the following column:</p>
<pre><code>timestamp. message. name. DestinationUsername. sourceUsername
13.05. hello. hello. name1.
13.05. hello. hello. name2. 43565
</code></pre>
<p>what I would like to achieve ... | <p>you can typecast the column to string and then remove 'nan' by <code>replace()</code> method:</p>
<pre><code>df['ID']=(df['DestinationUsername'].astype(str)
+
df['sourceUsername'].astype(str).replace('nan','',regex=True))
</code></pre>
<p><strong>OR</strong></p>
<pre><code>df['ID']=df[['Destina... | python-3.x|pandas|dataframe | 1 |
345 | 68,704,376 | Transform or change values of columns in based on values of others columns | <p>I have a dataframe that contains 5 columns. What I would like to do is to change the last 4 columns to the first column.</p>
<p>Basically if the value of the first column is below a certain threshold, the following columns are modified and if this value is higher than the threshold there is no change.</p>
<p>So I tr... | <p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> to select rows where <code>col1</code> is less than or equal to <code>.15</code> then multiply the rest of the columns by <code>.15</code>:</p>
<pre><code>df.loc[df... | python|pandas|dataframe | 3 |
346 | 68,656,060 | KeyError: 'Failed to format this callback filepath: Reason: \'lr\'' | <p>I recently switched form Tensorflow 2.2.0 to 2.4.1 and now I have a problem with <code>ModelCheckpoint</code> callback path. This code works fine if I use an environment with tf 2.2 but get an error when I use tf 2.4.1.</p>
<pre><code>checkpoint_filepath = 'path_to/temp_checkpoints/model/epoch-{epoch}_loss-{lr:.2e}_... | <p>In <a href="https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint" rel="nofollow noreferrer"><code>ModelCheckpoint</code></a>, formatted name of <code>filepath</code> argument, can only be contain: <strong><code>epoch</code> + keys in <code>logs</code> after epoch ends</strong>.</p>
<p>You ca... | tensorflow|keras|callback | 1 |
347 | 53,309,583 | Reading a datafile (abalone) and converting to numpy array | <p>When I try to load the UCI abalone data file as follows:</p>
<pre><code>dattyp = [('sex',object),('length',float),('diameter',float),('height',float),('whole weight',float),('shucked weight',float),('viscera weight',float),('shell weight',float),('rings',int)]
abalone_data = np.loadtxt('C:/path/abalone.dat',dtype ... | <p>You can use pandas:</p>
<pre><code>import pandas as pd
abalone_data = pd.read_csv('C:/path/abalone.dat', header=None).values
abalone_data.shape
</code></pre>
<p>OUtput:</p>
<pre><code>(4177, 9)
</code></pre> | python|numpy | 2 |
348 | 65,638,874 | Python error messages including "ImportError: cannot import name 'string_int_label_map_pb2'" | <p>So I have been trying to get a captcha solver I found <a href="https://drive.google.com/file/d/1tSrLELxq4YMn1-whRQ5yvU4Ns7n61MPQ/view" rel="nofollow noreferrer">here</a> to work for quite some time now. I have fixed many weird problems with that time, but I honestly don't know what's wrong this time. So I am startin... | <p>Read through the answer, few them contains step to step guide on installing protoc,many useful answers on issues thread.
<a href="https://github.com/tensorflow/models/issues/1595" rel="nofollow noreferrer">https://github.com/tensorflow/models/issues/1595</a></p> | python|python-3.x|tensorflow|object-detection | 0 |
349 | 63,388,627 | How am I able to separate a DataFrame into many DataFrames, based on a label and then do computation for each DataFrame? | <p>I have the following DataFrame:</p>
<p><img src="https://i.stack.imgur.com/ISzkd.png" alt="1" /></p>
<p>I am trying to make one DataFrame for each unique value in df1['Tub']. Right now I am creating a dictionary and trying to append to each new DataFrame instances where there is a matching Tub. I think my logic is o... | <p>Here is a shorter version, identify unique values in <code>Tub</code> & use dict comprehension to create a filtered <code>dict</code></p>
<pre><code>{tub: df1[df1.Tub.eq(tub)] for tub in df1.Tub.unique()}
</code></pre> | python|pandas|dataframe | 2 |
350 | 63,535,578 | how to i change the format of date from dd-mm-yyyy to dd/mm/yyyy in a csv file | <p><a href="https://i.stack.imgur.com/198ak.png" rel="nofollow noreferrer">image</a></p>
<p>I have CSV with date in this format which is to be changed? how can I do that?</p> | <pre><code>import pandas as pd
# I have taken an example. You could do a pd.read_csv(filename) to read from file
#Input in dd-mm-yyyy format
df = pd.DataFrame({'DOB': {0: '26-01-2016', 1: '26-01-2016'}})
#Convert to pandas datetime object
df['DOB'] = pd.to_datetime(df.DOB)
#Convert to dd/mm/yyyy format('%d/%m/%Y')
... | python|pandas|date | 0 |
351 | 63,569,743 | Equalizing indexes of Pandas Series to fit into Dataframe | <p>I have a pandas Dataframe that uses a datetime index. I want to add a column onto the dataframe that returns an average of a particular slice of the data. This column does not always include the entire index, I need a way to fill in the missing portions with zeros.</p>
<p>Dataframe:<br />
<code>[2020-7-26 | 29.3] ... | <p>If I'm understanding you correctly, you simply want to join the two together on their datetime index. Let <code>df</code> be your dataframe with more indices and <code>ser</code> be your series with missing indices.</p>
<p>if <code>df</code> is:</p>
<pre><code> val
date
2019-08-01 1
2019-08-02 2
2019... | python|pandas|dataframe | 0 |
352 | 63,408,380 | Locating columns values in pandas dataframe with conditions | <p>We have a dataframe (<code>df_source</code>):</p>
<pre><code>Unnamed: 0 DATETIME DEVICE_ID COD_1 DAT_1 COD_2 DAT_2 COD_3 DAT_3 COD_4 DAT_4 COD_5 DAT_5 COD_6 DAT_6 COD_7 DAT_7
0 0 200520160941 002222111188 35 200408100500.0 12 200408100400 16 200408100300 11 200408... | <ul>
<li>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with aggregate join for <code>ID</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.... | python|pandas | 1 |
353 | 72,079,647 | How to count the values of multiple '0' and '1' columns and group by another binary column ('Male' and Female')? | <p>I'd like to group the binary information by 'Gender' and count the values of the other/ following fields 'Married', 'Citizen' and 'License'</p>
<p>The below code was my attempt, but it was unsucessful.</p>
<pre><code>dmo_df.groupby(['Gender'], as_index = True)['Married', 'Citizen','License'].apply(pd.Series.value_co... | <p>I think you're trying to get <code>sum</code> and not <code>value_counts</code>:</p>
<pre><code>>>> df.groupby('Gender')[["Married","Citizen","License"]].sum()
Married Citizen License
Gender
Female 3 3 0
Male 5 ... | python|python-3.x|pandas|python-2.7|pandas-groupby | 1 |
354 | 55,541,644 | Is there a function to split rows in the dataframe if one of the column contains more than one keyword? | <p>My dataset contains the column "High-Level-Keyword(s)" and it contains more than one keywords separated by '\n'. I want to group the data on the basis of these Keywords.</p>
<p>I tried using function unique() but it treats 'Multilangant Systems', 'Multilangant Systems\nMachine Learning' and 'Machine Learning' diff... | <p>You should <code>.split</code> on the separator, then count.</p>
<pre><code>from collections import Counter
from itertools import chain
Counter(chain.from_iterable(df["High-Level-Keyword(s)"].str.split('\n')))
#Counter({'Machine Learning': 2, 'Multilangant': 2})
</code></pre>
<p>Or make it a Series:</p>
<pre><co... | python|pandas|dataframe|data-analysis | 1 |
355 | 66,916,275 | Which way is right in tf-idf? Fit all then transform train set and test set or fit train set then transform test set | <p>1.Fit train set then transform test set
<a href="https://scikit-learn.org/stable/auto_examples/text/plot_document_classification_20newsgroups.html#sphx-glr-auto-examples-text-plot-document-classification-20newsgroups-py" rel="nofollow noreferrer">scikit-learn provide this example</a></p>
<pre><code>from sklearn.feat... | <p>It really depends on your use case.</p>
<p>In the first situation, your test set TF-IDF values are only based on the frequencies in the train set. This allows you to control the "reference" corpus and decorrelates your results to data in the testing set which makes sense when data in your test set is sampl... | python|numpy|scikit-learn|tf-idf|tfidfvectorizer | 0 |
356 | 47,289,057 | How to group and pivot(?) dataframe | <p>I have a dataframe looking like this:</p>
<pre><code>ID Species Count
1 Pine 1000
1 Spruce 1000
2 Pine 2000
3 Pine 1000
3 Spruce 500
3 Birch 500
</code></pre>
<p>What i want is this:</p>
<pre><code> Pine Spruce Birch
ID Count Count Count
1 1000 1000
2 2000
... | <p>Simple <code>pivot</code> </p>
<pre><code>df.pivot('ID','Species','Count')
Out[493]:
Species Birch Pine Spruce
ID
1 NaN 1000.0 1000.0
2 NaN 2000.0 NaN
3 500.0 1000.0 500.0
</code></pre> | python|pandas | 2 |
357 | 47,117,498 | Does `tf.data.Dataset.repeat()` buffer the entire dataset in memory? | <p>
Looking at this code example from the TF documentation:</p>
<pre class="lang-py prettyprint-override"><code>filenames = ["/var/data/file1.tfrecord", "/var/data/file2.tfrecord"]
dataset = tf.data.TFRecordDataset(filenames)
dataset = dataset.map(...)
dataset = dataset.shuffle(buffer_size=10000)
dataset = dataset.bat... | <p>
Based on this simple test it appears that <code>repeat</code> does <em>not</em> buffer the dataset, it must be re-initializing the upstream datasets.</p>
<pre class="lang-py prettyprint-override"><code>n = tf.data.Dataset.range(5).shuffle(buffer_size=5).repeat(2).make_one_shot_iterator().get_next()
[sess.run(n) fo... | tensorflow | 0 |
358 | 68,391,775 | Creating a df with index = years and columns = mean length of an event occurring in a year, from previous df columns | <p>I have the df_winter as viewed below, and would like to create a new df that displays the year, and the average length of storms occuring in a 1 year, so I can visualize the change in length of storms over time.</p>
<p>I thought I could use groupby like this:</p>
<pre><code>df_winter_length= df_winter.groupby(['Star... | <p>There may be an easier route but I ended up dropping the unused columns from df_Winter -- ei county and disaster type, and then using .groupby and .mean like so:</p>
<pre><code>df_winter_length = df_winter.drop(columns=['County','Disaster_Type'])
df_winter_length = df_winter_length.groupby(['Start_year']).mean()
<... | python|pandas|dataframe | 0 |
359 | 68,197,672 | "Invalid argument: indices[0,0,0,0] = 30 is not in [0, 30)" | <p><strong>Error:</strong></p>
<pre><code>InvalidArgumentError: indices[0,0,0,0] = 30 is not in [0, 30)
[[{{node GatherV2}}]] [Op:IteratorGetNext]
</code></pre>
<p><strong>History:</strong></p>
<p>I have a custom data loader for a <code>tf.keras</code> based U-Net for semantic segmentation, based on <a href="https... | <p>Picture <code>tf.gather</code> as a fancy way to do indexing. The error you get is akin to the following example in python:</p>
<pre><code>>>> my_list = [1,2,3]
>>> my_list[3]
IndexError: list index out of range
</code></pre>
<p>If you want to use <code>tf.gather</code>, then the range of value of... | python|tensorflow|keras|tf.keras | 1 |
360 | 68,364,213 | pandas multi index sort with several conditions | <p>I have a dataframe like below,</p>
<pre><code> MATERIALNAME CURINGMACHINE HEADERCOUNTER
0 1015 PPU03R 1529
1 3005 PPY12L 305
2 3005 PPY12R 359
3 3005 PPY12R 404
4 K843 PPZB06L 435
5 ... | <p>Fix it by adding <code>argsort</code></p>
<pre><code>pivot = pivot.sort_values('HEADERCOUNTER',ascending=False)
out = pivot.iloc[(-pivot.groupby(level=0)['HEADERCOUNTER'].transform('max')).argsort()]
Out[136]:
HEADERCOUNTER
MATERIALNAME CURINGMACHINE
Grand Total ... | python|pandas | 2 |
361 | 56,996,633 | saving the numpy image datasets. without increase in size and easy to save and load data | <p>i have saved my train test val array into pickle file. but the size of images is 1.5GB ,pickle file is 16GB i.e size increased. is another any another way to save those numpy images array without increase in size?</p> | <p>Use <code>numpy.save</code> function (<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html" rel="nofollow noreferrer">documentation</a>) or <code>numpy.savez_compresion</code> function (<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.savez_compressed.html" rel="nofollow n... | python|numpy | 0 |
362 | 57,017,398 | TypeErorr: 'Tensor' object cannot be interpreted as an integer | <p>I want to make the some dynamic shape weight matrix.</p>
<p>The matrix has 3-dimension, [x, y, z].</p>
<p>So I define some function.</p>
<pre class="lang-py prettyprint-override"><code>x = tf.reduce_max(some_tensor_x_length)
y = tf.reduce_max(some_tensor_y_length)
z = tf.reduce_max(some_tensor_z_length)
w = self... | <p>The calls:</p>
<pre><code>x = tf.reduce_max(some_tensor_x_length)
y = tf.reduce_max(some_tensor_y_length)
z = tf.reduce_max(some_tensor_z_length)
</code></pre>
<p>return scalar tensors, and integers. As such, when you call:</p>
<pre><code>W = np.zeros(x, y, z)
</code></pre>
<p>you're passing tensors as argument... | python|tensorflow | 0 |
363 | 57,032,082 | Pandas groupby: combine distinct values into another column | <p>I need to group by a subset of columns and count the number of distinct combinations of their values. However, there are other columns that may or may not have distinct values, and I want to somehow retain this information in my output. Here is an example: </p>
<pre><code>gb1 gb2 text1 text2
beb... | <p>You can check with </p>
<pre><code>s=df.assign(count=1).groupby(['gb1','gb2']).agg({'count':'sum','text1':lambda x : ','.join(set(x)),'text2':lambda x : ','.join(set(x))}).reset_index()
s
gb1 gb2 count text1 text2
0 bebop skeletor 2 blue wright,fisher
1 rockste... | python|pandas|pandas-groupby | 4 |
364 | 57,294,262 | Empty results from concurrent psycopg2 postgres select queries | <p>I am attempting to retrieve my label and feature datasets from a postgres database using the <strong>getitem</strong> method from a custom pytorch dataset. When I attempt to sample with random indexes my queries return no results</p>
<p>I have checked to see if my queries work directly on the psql cli. They do.
I ... | <p>This is a properly constructed getitem for pytorch from a postgres table with indexable keys. </p>
<pre><code>def __getitem__(self, idx: int) -> tuple:
query = """SELECT ls.taxonomic_id, it.tensor
FROM genomics.tensors2 AS it
INNER JOIN genomics.labeled_sequences AS ls
... | python|postgresql|concurrency|pytorch|psycopg2 | 0 |
365 | 57,004,603 | Interpolate values in one column of a dataframe (python) | <p>I have a dataframe with three columns (timestamp, temperature and waterlevel).
What I want to do is to replace all NaN values in the waterlevel column with interpolated values. For example: </p>
<p><a href="https://i.stack.imgur.com/MuaSH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MuaSH.png"... | <p>I assume NaN is <code>np.nan</code> Object </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"waterlevel": ['A',np.nan,np.nan,'D'],"interpolated values":['Ai','Bi','Ci','D']})
print(df)
df.loc[df['waterlevel'].isnull(),'waterlevel'] = df['interpolated values']
print(df)
</code></pre>
<p>O... | python|pandas|numpy|interpolation|linear-interpolation | 0 |
366 | 46,117,577 | How to merge DataFrame in for loop? | <p>Am trying to merge the multiindexed dataframe in a for loop into a single dataframe on index.</p>
<p>i have a reproducible code at <a href="https://gist.github.com/RJUNS/f4ad32d9b6da8cf4bedde0046a26f368#file-prices-py" rel="nofollow noreferrer">https://gist.github.com/RJUNS/f4ad32d9b6da8cf4bedde0046a26f368#file-pri... | <p>I think you need append <code>df</code> to <code>list of DataFrames</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.... | python|database|pandas|numpy|dataframe | 5 |
367 | 46,035,718 | Add a number to a element in a tensor rank 1 if a condition is met in tensorflow | <p>I have a tensor rank 1, which may look like this: <code>[-1,2,3,-2,5]</code> now I want to add a constant to the absolut value of an element, if the element is negative. If the element is positive, nothing shall happen.</p>
<p>I know how to do this with a scalar like:</p>
<pre><code>res = tf.cond(tensor < 0,\
l... | <p>you can just use <a href="https://www.tensorflow.org/api_docs/python/tf/where" rel="nofollow noreferrer"><code>tf.where</code></a></p>
<pre><code>a = tf.Variable([-1,2,3,-2,5])
b = tf.where(tf.less(a, 0), tf.abs(a)+tf.constant(m.pi), a)
</code></pre> | python|tensorflow | 1 |
368 | 50,914,335 | How to plot in Wireframe with CSV file - Numpy / Matplotlib | <p>I would like to plot in 3D with Pandas / MatplotLib / Numpy as a Wireframe</p>
<p>I'm using RFID sensors and I'm trying to record the signal I receive at different distance + different angles. And I want to see the correlation between the rising of the distance and the angle.</p>
<p>I've already a full CSV file wh... | <p>I read the data in with pandas then grabbed the numpy arrays. Note the use of .values.</p>
<pre><code>import pandas as pd
import matplotlib.pylab as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d
df= pd.read_csv('test.txt', sep=';')
df.index = df.Distance
del df['Distance']
raw_data = df
angle =... | python|pandas|numpy|matplotlib | 2 |
369 | 66,638,217 | Append dataframes in a loop from files located in different directories? | <p>I want to create one pandas dataframe from files which are in different directories. In this directories are also other files and I want to read only .parquet files.</p>
<p>I created a function but it returns nothing:</p>
<pre><code>def all_files(root, extensions):
files = pd.DataFrame()
for dir_path, dir_names,... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer">pandas.DataFrame.append</a> does not work in place, it is <em>returning a new object</em> (unlike <code>append</code> method of built-in python <code>list</code>), try replacing</p>
<pre><code>... | python|pandas | 1 |
370 | 51,352,544 | Groupby and how value_counts work | <p>I've got a dataframe with the following data</p>
<pre><code> idpresm teamid competicion fecha local \
0 12345 dummy1 ECU D1 2018-07-07 Deportivo Cuenca
1 12345 dummy1 ECU D1 2018-07-03 Liga Dep. Universitaria Quito
2 12345 dummy1 EC... | <p>You are looking for <code>'size'</code>. For common functions, you should trust strings are mapped to efficient algorithms. For example:</p>
<pre><code>d = {'media': 'mean', 'contador': 'size'}
res = homedata.groupby('local')['r1'].agg(d)
</code></pre>
<hr>
<blockquote>
<p>I would expect a column of integers in... | python|python-3.x|pandas|count|pandas-groupby | 1 |
371 | 51,476,960 | I have a worksheet of multiple sheets and i want each of them to be get assigned as individual dataframe in python | <p>Example :- </p>
<p>Example_workbook has 20 sheets.
I want each of them to get assign as individual dataframe in python.I have tried
as below but this would be only helpful to get single sheet at a time.
Do anyone know how can we use "<strong>Def</strong>" function to iterate through sheets and assign each of them ... | <p>The <code>read_excel</code> method reads all the sheets at once if you set the <code>sheet_name</code> kwarg to be <code>None</code>.</p>
<pre><code>sheets = pd.read_excel("practice1.xlsx",sheet_name=None) # this is a dict
for sheet_name, df in sheets.items():
"calculations on the dataframe df"
</code></pre>
... | python|pandas | 3 |
372 | 51,529,545 | Python Pandas | Create separate lists for each of the columns | <p>I am not sure how to use tolist to achieve the following. I have a dataframe like this:</p>
<pre><code>Param_1 Param_2 Param_3
-0.171321 0.0118587 -0.148752
1.93377 0.011752 1.9707
4.10144 0.0112963 4.06861
6.25064 0.0103071 5.83927
</code></pre>
<p>What I want is to create separate ... | <p>Adding <code>.T</code></p>
<pre><code>df.values.T.tolist()
Out[465]:
[[-0.171321, 1.93377, 4.10144, 6.25064],
[0.0118587, 0.011752, 0.011296299999999999, 0.0103071],
[-0.148752, 1.9707, 4.06861, 5.83927]]
</code></pre>
<p>Or we can create the <code>dict</code> </p>
<pre><code>{x:df[x].tolist() for x in df.colu... | python|list|pandas|dataframe|tolist | 3 |
373 | 70,780,842 | Python-Pandas: How do I create a create columns from rows in a DataFrame without redundancy? | <p>I Joined multiple DataFrames and now I got only one DataFrame. Now I want to make the same ID rows to columns without redundancy. To make it clear:</p>
<p>The DataFrame that I have now:</p>
<pre><code> column1 column2 column3
row1 2 4 8
row2 1 18 7
row3 54... | <p>This is a weird reshaping as you will have ambiguity if there are also duplicates in column1 or column2. Thus having a MultiIndex is probably a good solution.</p>
<p>This solution reshapes using a combination of <code>melt</code> + <code>drop_duplicates</code> and <code>pivot</code></p>
<pre><code>from string import... | python|pandas|dataframe | 0 |
374 | 51,817,742 | How could I detect subtypes in pandas object columns? | <p>I have the next DataFrame:</p>
<pre><code>df = pd.DataFrame({'a': [100, 3,4], 'b': [20.1, 2.3,45.3], 'c': [datetime.time(23,52), 30,1.00]})
</code></pre>
<p>and I would like to <em>detect <strong>subtypes</strong></em> in columns without explicit programming a loop, if possible.</p>
<p>I am looking for the next o... | <p>You should appreciate that with Pandas you can have 2 broad types of series:</p>
<ol>
<li>Optimised structures: Usually numeric data, this includes <code>np.datetime64</code> and <code>bool</code>.</li>
<li><code>object</code> dtype: Used for series with mixed types or types which cannot be held natively in a NumPy... | python|pandas | 11 |
375 | 51,986,601 | How to check if a file contains email addresses or md5 using python | <p>How to check if a source_file contains email addresses or md5 once you download</p>
<pre><code>data2 = pd.read_csv(source_file, header=None)
</code></pre>
<p>tried using regrex and str.contains...but not able to figure out how to proceed</p>
<p>if that is checked then according to that i need to proceed for rest ... | <p>Try this pattern <code>r'@\w+\.com'</code>.</p>
<p><strong>Ex:</strong></p>
<pre><code>import pandas as pd
df1 = pd.read_csv(filename1, names=['email/md5'])
if df1['email/md5'].str.contains(r'@\w+\.com').all():
print("Email")
else:
print("md5")
</code></pre> | python|pandas | 1 |
376 | 51,844,794 | Finding hierarchical structure in messy energy data | <p>I have energy profile data (sampled at 3 hour intervals) for about 25 electricity meters in a building as pandas dataframe time series.</p>
<p>The meters form a hierarchical structure where the top level meters include consumption data for the lower level meters.</p>
<p>For example , ( a possible layered structure... | <p>This general problem is very close to <a href="https://en.wikipedia.org/wiki/3SUM" rel="nofollow noreferrer">3SUM</a>, unfortunately a solution has not been found with a complexity less than quadratic. </p>
<p>It is likely that your best solution won't be much better than exhaustively trying combinations, however w... | python|algorithm|pandas|numpy|energy | 2 |
377 | 41,679,110 | How to use tensorflow-wavenet | <p>I am trying to use the <a href="https://github.com/ibab/tensorflow-wavenet" rel="noreferrer">tensorflow-wavenet</a> program for text to speech.</p>
<p>These are the steps:</p>
<ol>
<li>Download Tensorflow</li>
<li>Download librosa</li>
<li>Install requirements <code>pip install -r requirements.txt</code></li>
<li>... | <p>According to the <a href="https://github.com/ibab/tensorflow-wavenet/blob/master/README.md#missing-features" rel="nofollow noreferrer">tensorflow-wavenet page</a>: </p>
<blockquote>
<p>Currently there is no local conditioning on extra information which would allow context stacks or controlling what speech is gene... | tensorflow | 4 |
378 | 64,200,512 | tensorflow evalutaion and earlystopping gives infinity overflow error | <p>I a model as seen in the code below, but when trying to evaluate it or using earlystopping on it it gives me the following error:</p>
<pre><code> numdigits = int(np.log10(self.target)) + 1
OverflowError: cannot convert float infinity to integer
</code></pre>
<p>I must state that without using <code>.EarlyStoppin... | <p>Well it's hard to tell exactly as I can't run code without <code>some_get_data_function()</code> realization but recently I've got same error when <strong>mistakenly passed EMPTY array</strong> to <code>model.evaluate</code>. Taking into account that @meTchaikovsky comment solved your issue it's certainly due to mes... | python|numpy|tensorflow|keras|overflow | 8 |
379 | 64,583,123 | Two different numpy arrays are being assigned the same values when only one array is being referenced | <p>I'm trying to write some code to carry out the Jacobi method for solving linear equations (I realise my method is not the most efficient way to do this but I am trying to figure out why it's not working).</p>
<p>I have tried to debug the problem and noticed the following issue.
The code finishes after 2 iterations b... | <pre><code>x = xnew
</code></pre>
<p>This line assigns <code>xnew</code> to <code>x</code>. Not the <em>contents</em> of xnew, but the array itself. So after your first iteration, <code>x</code> and <code>xnew</code> reference the same array in memory.</p>
<p>Try instead <code>x[:] = xnew[:]</code></p> | python|numpy | 2 |
380 | 47,836,347 | Python 2.7 - pandas.read_table - how to import quadruple-pipe-separated fields from flat file | <p>I am a decent SAS programmer, but I am quite new in Python. Now, I have been given Twitter feeds, each saved into <strong>very large</strong> flat files, with headers in row #1 and a data structure like the below:</p>
<pre>
CREATED_AT||||ID||||TEXT||||IN_REPLY_TO_USER_ID||||NAME||||SCREEN_NAME||||DESCRIPTION||||FOL... | <p>Using just the data in your question:</p>
<pre><code>>>> df = pd.read_csv('rio.txt', sep='\|{4}', skip_blank_lines=True, engine='python')
>>> df
CREATED_AT ID \
0 Tue Nov 14 12:33:00 +0000 2017 930413253766791168
1 Tue Nov 14 12:34:00 +0000 2017 9304... | python|pandas|separator | 3 |
381 | 49,161,208 | Keras - method on_batch_end is slow but only callback I have is checkpoint | <p>I set up a network with keras using TensorFlow backend.</p>
<p>When I train my network I often times keep getting message:</p>
<pre><code>UserWarning: Method on_batch_end() is slow compared to the batch update (0.195523). Check your callbacks.
% delta_t_median)
</code></pre>
<p>The issue is that my network is s... | <p>This is most probably a Generator (<code>fit_generator()</code>) issue. When using a generator as data source it has to be called at the end of a batch. Consider revisiting your generator code, using multiprocessing (<code>workers > 1</code>) or a higher batchsize (if possible) </p> | python|tensorflow|machine-learning|callback|keras | 6 |
382 | 58,700,108 | How can create an empty arrayin python like a C++ array | <p>I need to create an empty nd-array in python without zeros or ones functions looks like in c++ with this command for array 3*4 for integers:</p>
<pre><code>int x[3][4]
</code></pre>
<p>Please help me</p> | <p>Numpy has a function for that. <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html#numpy.empty" rel="nofollow noreferrer">empty</a></p> | python|python-3.x|numpy|numpy-ndarray | 2 |
383 | 56,305,466 | Why might pandas resort the dataframe after joining? | <p>I am writing an application where I need to pull in a single column from another dataframe. I'm getting some strange behavior. When I run the function using one dataset, everything works great. When it executes on a secondary dataset, the same code <em>resorts</em> the data based on the index. I'm pulling my hair ou... | <p>Pandas' left join operation reorders the index of the right dataframe so that it matches the index of the left dataframe.</p>
<p>For example, the following code produces a dataframe where the index of b is rearranged to match the index of a:</p>
<pre><code>a = pd.DataFrame({'x':[1,2,3]})
b = pd.DataFrame({'y':[1,2... | python|pandas | 0 |
384 | 56,174,211 | Concat 2 columns in a new phrase column using pandas DataFrame | <p>I have a DataFrame like this:</p>
<pre><code>>>> df = pd.DataFrame({'id_sin':['s123','s124','s125','s126','s127'],
'num1':[12,10,23,6,np.nan],
'num2':['BG','TC','AB','RC',np.nan],
'fr':[1,1,1,1,0],
})
>>> df
fr id_sin num1 num2
0 1 s... | <p><strong>Edit</strong>:<br>
if you want <code>num1</code> has no decimal <code>.0</code>, convert it to <code>Int64</code>:</p>
<pre><code>df.num1 = df.num1.astype('Int64')
Out[32]:
id_sin num1 num2 fr
0 s123 12 BG 1
1 s124 10 TC 1
2 s125 23 AB 1
3 s126 6 RC 1
4 s127 NaN... | python|pandas|dataframe | 1 |
385 | 55,923,319 | Transform time series data set to supervised learning data set | <p>I have a data set with time series (on daily basis) for multiple items (e.g. users).
The data looks simlified like this:
<a href="https://i.ibb.co/Pj4TnHW/trans-original.jpg" rel="nofollow noreferrer">https://i.ibb.co/Pj4TnHW/trans-original.jpg</a> (I can't post images, because of missing rep. points, sorry)</p>
<p... | <p>I used to do stuff like this with <a href="https://en.wikipedia.org/wiki/R_(programming_language)" rel="nofollow noreferrer">R</a>, it's a language well designed to manipulate rows (functional programming). You can use the library <a href="https://cran.r-project.org/web/packages/data.table/vignettes/datatable-intro.... | python|pandas|time-series|supervised-learning | 0 |
386 | 39,707,080 | Pandas - Alternative to rank() function that gives unique ordinal ranks for a column | <p>At this moment I am writing a Python script that aggregates data from multiple Excel sheets. The module I choose to use is Pandas, because of its speed and ease of use with Excel files. The question is only related to the use of Pandas and me trying to create a additional column that contains <em>unique, integer-onl... | <p>I think the way you were trying to use the <code>method=first</code> to rank them after sorting were causing problems. </p>
<p>You could simply use the rank method with <code>first</code> arg on the grouped object itself giving you the desired unique ranks per group.</p>
<pre><code>df['new_rank'] = df.groupby(['we... | python|pandas|ranking|rank|ordinal | 3 |
387 | 39,745,881 | Speed-up cython code | <p>I have code that is working in python and want to use cython to speed up the calculation. The function that I've copied is in a .pyx file and gets called from my python code. V, C, train, I_k are 2-d numpy arrays and lambda_u, user, hidden are ints.
I don't have any experience in using C or cython. What is an effic... | <p>You are trying to use <code>cython</code> by diving into the deep end of pool. You should start with something small, such as some of the numpy examples. Or even try to improve on <code>np.diag</code>.</p>
<pre><code> i = 0
C_i = np.zeros((m, m), dtype=float)
for j in range(m):
C_i[j,j]=C[i,j]
... | python|numpy|cython | 3 |
388 | 44,308,300 | Fill gaps in Pandas multi index with start and end timestamp | <p>From a DataFrame like the following:</p>
<pre><code> value fill
start end
2016-07-15 00:46:11 2016-07-19 03:35:34 1 a
2016-08-21 07:55:31 2016-08-22 18:24:49 2 b
2016-09-26 03:09:12 2016-09-26 06:06:12... | <p>use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer">DataFrame.stack()</a> method:</p>
<pre><code>In [189]: df.stack().reset_index(level=2, drop=True).to_frame('value')
Out[189]:
value
start e... | python|pandas | 2 |
389 | 44,030,114 | Pandas between range lookup filtering | <p>My data looks like this:</p>
<pre><code>import pandas as pd
pd.DataFrame({
'x_range':['101-200','101-200','201-300','201-300'],
'y':[5,6,5,6],
'z': ['Cat', 'Dog', 'Fish', 'Snake']
})
</code></pre>
<p>How might I filter on an <code>x</code> value (that fit's inside x_range) and a <code>y</code> value... | <p>Simple filtering exercise:</p>
<p>Save your dataframe:</p>
<pre><code>df['x_range_start'] = [int(i.split('-')[0]) for i in df.x_range]
</code></pre>
<p>Add two columns for range start and end:</p>
<pre><code>df['x_range_start'] = [int(i.split('-')[0]) for i in df.x_range]
df['x_range_end'] = [int(i.split('-')[1]... | python|python-3.x|pandas | 1 |
390 | 69,544,050 | Geopandas: How to associate a Point to a Linestring using the original Linestring order | <p>Using Geopandas, Shapely</p>
<pre><code>import geopandas as gpd
from shapely.geometry import Point, LineString
street = gpd.GeoDataFrame({'street': ['st'], 'geometry': LineString([(1, 1), (2, 2), (3, 1)])})
pp = gpd.GeoDataFrame({'geometry': [Point((1.9, 1.9)), Point((1.5, 1.5)), Point((2.5, 1.5)), Point((1.2, 1.2))... | <p><strong>Comment:</strong></p>
<blockquote>
<p>I wouldn't know there's an existing function to do that. It seems as your challenge is to identify the segment of the street where you have to add a point. You can calculate the linear distance of the point to each segment. The segment with the min distance is the one yo... | python|geopandas|shapely | 0 |
391 | 69,467,417 | reduce Pandas DataFrame by selecting specific rows (max/min) groupby | <p>I have a long pandas DataFrame and like to select a single row of a subset if a criterion applies (min of 'value' in my case).</p>
<p>I have a dataframe that starts like this:</p>
<pre><code> time name_1 name_2 idx value
0 0 A B 0 0.927323
1 0 A B 1 0.417376
2 0 ... | <p>you could try to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmin.html" rel="nofollow noreferrer">idxmin()</a> and use the following line of code:</p>
<pre><code>out_df = df.loc[df.loc[:,['time','name_1','idx','value']].groupby(by=['time','name_1','i... | python|pandas|dataframe|subset | 0 |
392 | 69,659,219 | Convert a data frame in which one column contains array of numbers as string to a json file | <p>I'd like to convert a data frame into a json file. One of the columns of the data frame contains time series as a string. Thus, the final json looks like this:</p>
<p><code>[{"...":"...","Dauer":"24h","Wertereihe":"8619.0,9130.0,8302.0,8140.0"}, {...}, {...... | <p>IIUC, you need:</p>
<pre><code>df['Wertereihe'] = df['Wertereihe'].apply(lambda x: list(map(float, x.split(','))))
df.to_json(jsonFile, orient = "records")
</code></pre> | python|json|pandas|csv|csvtojson | 1 |
393 | 38,508,458 | Comparing scalars to Numpy arrays | <p>What I am trying to do is make a table based on a piece-wise function in Python. For example, say I wrote this code:</p>
<pre><code>import numpy as np
from astropy.table import Table, Column
from astropy.io import ascii
x = np.array([1, 2, 3, 4, 5])
y = x * 2
data = Table([x, y], names = ['x', 'y'])
ascii.write(dat... | <p>You can possibly use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html#numpy.where" rel="nofollow"><code>numpy.where()</code></a>:</p>
<pre><code>In [196]: y = np.where(x > 3, x + 2, y)
In [197]: y
Out[197]: array([2, 4, 6, 6, 7])
</code></pre>
<p>The code above gets the job done in... | python|arrays|variables|numpy|astropy | 3 |
394 | 66,034,080 | make correlation plot on time series data in python | <p>I want to see a correlation on a rolling week basis in time series data. The reason because I want to see how rolling correlation moves each year. To do so, I tried to use <code>pandas.corr()</code>, <code>pandas.rolling_corr()</code> built-in function for getting rolling correlation and tried to make line plot, but... | <p>Using your code and description as a starting point.
Panda's <code>Rolling</code> class has an <code>apply</code> function which can be leveraged (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.rolling.Rolling.apply.html#pandas.core.window.rolling.Rolling.apply" rel="nofollow ... | python|pandas|matplotlib | 1 |
395 | 66,133,811 | Need to sort a nested tuple with numbers | <p>I trying to sort a tuple as below</p>
<pre><code>input: ROI:
[[191 60 23 18]
[143 60 23 19]
[ 95 52 24 21]
[237 51 24 21]
[ 47 38 27 22]
[281 35 25 22]
[ 4 17 26 24]
[324 13 22 21]]
Expected Output = S_ROI:
[[4 17 26 24]
[47 38 27 22]
[ 95 52 24 21]
[143 60 23 19]
[... | <p>Do you mean just this:</p>
<pre><code>print(ROI[ROI[:,0].argsort()])
</code></pre>
<p>Output:</p>
<pre><code>[[ 4 17 26 24]
[ 47 38 27 22]
[ 95 52 24 21]
[143 60 23 19]
[191 60 23 18]
[237 51 24 21]
[281 35 25 22]
[324 13 22 21]]
</code></pre> | python|numpy|opencv | 1 |
396 | 66,011,974 | How to get x_train and y_train from ImageDataGenerator? | <p>I am working on some image classification problem and I made Y Network for it. Y Network is a type of Neural Network which has two inputs and one output. If we want to fit our Tensorflow model we have to feed x_train and y_train in model.fit().
Like this -</p>
<pre><code>model.fit([x_train, x_train], y_train, epochs... | <p>you can get the list of all images and labels from</p>
<pre><code>class_dict=train_generator.class_indices
labels= train_generator.labels
file_names= train_generator.filenames
</code></pre>
<p>the class dictionary is useful to correlate the class index to the class name, it is of the form {class name, index} I find... | tensorflow|machine-learning|keras|deep-learning|conv-neural-network | 1 |
397 | 65,957,329 | problem with importing @tensorflow/tfjs-node while working with face-api.js package (node.js) | <p>i use @tensorflow/tfjs-node package for face-api.js package to speed up things (as they said )
that is my code :</p>
<pre><code> // import nodejs bindings to native tensorflow,
// not required, but will speed up things drastically (python required)
require('@tensorflow/tfjs-node');
// implements nodejs wrappe... | <p>As explained <a href="https://github.com/justadudewhohacks/face-api.js/issues/768#issuecomment-798908869" rel="nofollow noreferrer">in this github issue</a></p>
<blockquote>
<p>The version of face-api.js you are using is not compatible with tfjs 2.0+ or 3.0+, only obsolete 1.x.
Why it worked before you added tfjs-no... | javascript|node.js|tensorflow|face-recognition|face-api | 2 |
398 | 52,667,035 | Python + Pandas + dataframe : couldn't append one dataframe to another | <p>I have two big CSV files. I have converted them to Pandas dataframes. Both of them have columns of same names and in same order : event_name, category, category_id, description. I want to append one dataframe to another, and, finally want to write the resultant dataframe to a CSV. I wrote a code for that:</p>
<pre>... | <p>Whats wrong with a simple:</p>
<pre><code>pd.concat([df1, df2], ignore_index=True)).to_csv('File.csv', index=False)
</code></pre>
<p>this will work if they have the <strong>same columns</strong>.</p>
<p>A more verbose way to extract specific columns would be:</p>
<pre><code>(pd.concat([df1[['event_name','categor... | python|pandas|csv|dataframe | 1 |
399 | 58,572,345 | How to write a program using Numpy to generate and print 5 random number between 0 & 1 | <p>How to write a program using Numpy to generate and print 5 random number between 0 and 1</p> | <pre><code>import numpy as np
numbers = np.random.rand(5)
print(numbers)
</code></pre>
<p><a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.rand.html" rel="nofollow noreferrer">np.random.rand</a> will produce a sample from the uniform distribution over [0,1]</p>
<p>If you want to gener... | python|numpy|random | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.