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 |
|---|---|---|---|---|---|---|
363,100 | 48,011,588 | Understanding tensorboard: why 12 tensors sent to optimizer? | <p>So I made the simplest model I could (a perceptron/autoencoder) which (aside from input generation) is the following:</p>
<pre><code>N = 64 * 64 * 3
def main():
x = tf.placeholder(tf.float32, shape=(None, 64, 64, 3), name="x")
with tf.name_scope("perceptron"):
W = tf.Variable(tf.random_normal([N, ... | <p>I think the reason is that when you add the <code>tf.train.AdamOptimizer(0.005).minimize(cost)</code> op, it is implicitly assumed that you optimize over all trainable variables (because you didn't specify otherwise).
Therefore, you need to know the values of these variables and of all the intermediate tensors whic... | tensorflow|tensorboard | 2 |
363,101 | 48,138,483 | Random results from pre-trained InceptionV3 CNN | <p>I'm trying to create an InceptionV3 CNN which has previously been trained on Imagenet. While the creation and the loading of the checkpoint seems to be working correctly, the result seems to be random, as everytime I run the script, I get a different result, even though I don't change anything. The network is recrea... | <p>Since I set isTraining to true, it applied the dropout rate every time the network was used. I was under the impression that this only happened during back propagation.</p>
<p>To get it to work correctly, the code should be </p>
<pre><code>logits, endpoints = nn_architecture.inception_v3(input, # input
... | python-3.x|tensorflow|conv-neural-network|image-recognition | 0 |
363,102 | 48,352,482 | How to force set x ticks on matplotlib, or set datetime type with no year | <p>So I have a function that will take a pandas dataframe and plot it, along with displaying some error metrics, and I also have a function that will take a pandas dataframe with a datetime type index, and take the daily average of the values in the dataframe. The problem is, when I try to plot the daily average, it lo... | <p>You can set the ticks used for the x axis via <a href="https://matplotlib.org/api/axis_api.html#matplotlib.axis.Axis.set_ticks" rel="noreferrer"><code>ax.set_xticks()</code></a> and labels via <a href="https://matplotlib.org/devdocs/api/_as_gen/matplotlib.axes.Axes.set_xticklabels.html" rel="noreferrer"><code>ax.set... | python|pandas|matplotlib|plot | 7 |
363,103 | 48,343,781 | ValueError: List argument 'values' to 'ConcatV2' Op with length 0 shorter than minimum length 2 3Dball | <p>Executing "3Dball" creates some errors in Unity ml-agent</p>
<p>When I execute PPO.ipynb, there is no error till "Load the environment".</p>
<p>Executing "Train the Agents" there are some errors</p>
<blockquote>
<p>ValueError: List argument 'values' to 'ConcatV2' Op with length 0
shorter than minimum length 2... | <p>I had the same error, the way I fixed it is by replacing line 222 under the file: "ml-agents/python/ppo/models.py":</p>
<p>REPLACE Line 222: </p>
<pre><code> hidden_visual = tf.concat(encoders, axis=2)
</code></pre>
<p>BY:</p>
<pre><code> if encoders:
hidden_visual = tf.concat(encoders, axis=2)
</... | unity3d|tensorflow|ml-agent | 0 |
363,104 | 48,233,780 | Advantages and Disadvantages of MXNet compared to other Deep Learning APIs | <p>Recently I decided to learn MXNet, as some code I need to use, is written using this API.</p>
<p>However, I would like to know which are the advantages and disadvantages of MXNet compared to the other Deep Learning Libraries out there.</p> | <p>Perhaps the biggest reason for considering MXNet is its high-performance imperative API. This is one of the most important advantages of MXNet to other platforms. Imperative API with autograd makes it much easier and more intuitive to compose and debug a network. PyTorch also supports imperative API, but MXNet is th... | tensorflow|deep-learning|caffe|pytorch|mxnet | 5 |
363,105 | 48,063,307 | Pandas Multiindex selecting row skipping one level | <p>It seems to simple but my solution ends up being quite complicated.</p>
<p>I have df with 3 level multiindex and I want to pick row based on levels 0 and 2 while ignoring values at level 1 (but not deleting this level).</p>
<p><code>df
L0 L1 L2 colA colB
A1 B1 C1 1 2
C2 3 4
B2 C1 5 6
C2... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow noreferrer">slicers</a>:</p>
<pre><code>idx = pd.IndexSlice
df1 = df.loc[idx['A1',:,'C1'],'colB']
</code></pre>
<p>Or:</p>
<pre><code>df1 = df.loc[('A1',slice(None),'C1'),'colB']
print (df1)
L0 L1 L2
A1 B1 C1... | pandas | 4 |
363,106 | 48,044,980 | Return array of counts for each feature of input | <p>I have an array of integer labels and I would like to determine how many of each label is present and store those values in an array of the same size as the input.
This can be accomplished with the following loop:</p>
<pre><code>def counter(labels):
sizes = numpy.zeros(labels.shape)
for num in numpy.unique(... | <p><strong>Approach #1</strong></p>
<p>Here's one using <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique</code></a> -</p>
<pre><code>_, tags, count = np.unique(labels, return_counts=1, return_inverse=1)
sizes = count[tags]
</code></pre>
... | python|arrays|numpy | 6 |
363,107 | 48,134,313 | Create a column of counts in a pandas dataframe | <p>I want to create a column of counts in a pandas dataframe. Here is the input:</p>
<pre><code>dict = {'id': [1,2,3,4,5,6], 'cat': ['A', 'A', 'A', 'A', 'A', 'B'], 'status': [1, 1, 1, 1, 2, 1]}
id cat status
0 1 A 1
1 2 A 1
2 3 A 1
3 4 A 1
4 5 A 2
5 6 B 1
</code></pre>
<p>Preferred output:</p>
... | <p>Another option, use <code>pd.crosstab</code> to create a two way table with <code>cat</code> as index, then join back with the original data frame on <code>cat</code> column:</p>
<pre><code>df.join(pd.crosstab(df.cat, 'status_' + df.status.astype(str)), on='cat')
# cat id status status_1 status_2
#0 A 1 ... | pandas|pandas-groupby | 4 |
363,108 | 48,357,948 | Tensorflow Adagrad optimizer isn't working | <p>When I run the following script, I notice the following couple of errors:</p>
<pre><code>import tensorflow as tf
import numpy as np
import seaborn as sns
import random
#set random seed:
random.seed(42)
def potential(N):
points = np.random.rand(N,2)*10
values = np.array([np.exp((points[i][0]-5.0)**2 + (... | <blockquote>
<p>Right now my hunch is that this might simply be a numerics problem</p>
</blockquote>
<p>indeed, when running <code>potential(100)</code> I sometimes get values as large as <code>1E21</code>. The largest points will dominate your loss function and will drive the network parameters.</p>
<p>Even when n... | python-3.x|tensorflow|neural-network | 1 |
363,109 | 48,100,243 | Array swapping in python | <p>I want to swap elements between two array starting from a particular array index value keeping other values prior to the array index intact. </p>
<pre><code>import numpy as np
r = np.array([10, 20, 30, 40, 50, 60])
p = np.array([70, 80, 90, 100, 110, 120])
t = []
for i in range(len(r)):
for j in range(len(p... | <pre><code>import numpy as np
r = np.array([10, 20, 30, 40, 50, 60])
p = np.array([70, 80, 90, 100, 110, 120])
for i in range(len(r)):
if (i>=3):
p[i],r[i] = r[i],p[i]
</code></pre>
<p>Above code will do the work for you. You don't need to run two for loop and t array if I understand your problem right... | python-3.x|numpy | 3 |
363,110 | 48,224,839 | joining and renaming columns in pandas | <p>Following are my dataframes:</p>
<p>df1:</p>
<pre><code>pri sec0 sec1 sec2
ACL EMR DFG XHD
ABC MKB JKL KLF
XYZ LMN SDF GHY
</code></pre>
<p>df2:</p>
<pre><code>name loc
ACL 12
EMR 23
DFG 431
XHD 48
ABC 55
MKB 699
JKL 70
KLF 82
XYZ 93
LMN 10
SDF 235
GHY 53
</code></pre>
<p>I'm trying to join ea... | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>join</code></a> new <code>DataFrame</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>replac... | python|pandas|dataframe | 1 |
363,111 | 48,415,850 | How can I interpret @expand_dims within a Python Class? | <p>I am new to Python and I am trying to use the function '<code>one_hot_to_label_batch</code>' which can be found on line 115 from this <a href="https://github.com/SUZhaoyu/keras-semantic-segmentation/blob/develop/src/semseg/data/isprs.py" rel="nofollow noreferrer">website</a>. </p>
<p>However, directly above this fu... | <p>This is a decorator. See the top of the <a href="https://github.com/SUZhaoyu/keras-semantic-segmentation/blob/develop/src/semseg/data/isprs.py" rel="nofollow noreferrer">file</a>:</p>
<pre><code>from .util import expand_dims
</code></pre>
<p>From this line, we can tell the decorator is defined in the <code>util.py... | python|numpy | 2 |
363,112 | 48,208,044 | How to create a dictionary of a dictionary of a dictionary from a pandas data frame | <p>I have a pandas dataframe that looks like this:</p>
<pre><code>Copy sequence type ntv
1 1 A 0.45
1 1 R2 0.878
1 1 R3 1.234
1 2 A -7.890
1 2 R2 2.345
1 2 R3 -0.871
2 1 ... | <p>You can do sth along these lines, using a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow noreferrer"><code>collections.defaultdict</code></a>:</p>
<pre><code>from collections import defaultdict
def nested_dict():
return defaultdict(nested_dict)
d = nested_di... | python|pandas|dictionary | 3 |
363,113 | 48,068,270 | Pandas - delete rows based on multiple `or` conditions | <p>Let's assume my dataframe looks like this:</p>
<pre><code>emp_id, age, salary
39239, 32, 2000
11010, 33, 3232
...
</code></pre>
<p>I have a list of <code>emp_id</code>'s that I would like to drop from the dataframe. The list is over 200 long so multiple <code>or</code> filters would be too cumbersome.</p>
<p>Is t... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow noreferrer">DataFrame.isin</a>:</p>
<pre><code>df[~df['emp_id'].isin(bad_emp_ids_list)]
</code></pre> | python|pandas | 4 |
363,114 | 48,254,090 | Numpy: how to generate a random noisy curve resembling a "training curve" | <p>I'd like to know how I can generate some random data whose plot resembles a "training curve." By training curve, I mean an array of training loss values from a learning model. These typically have larger values and variance at the beginning, and over time converge to some value with very little variance. It looks a ... | <p>Here is the illustration how to do it with gamma distribution for the noise</p>
<pre><code>x = np.arange(2000)
y = 0.00025 + 0.001 * np.exp(-x/100.) + scipy.stats.gamma(3).rvs(len(x))*(1-np.exp(-x/100))*2e-5
</code></pre>
<p>You can adjust the parameters here, to reduce the amount of noise etc</p>
<p><a href="htt... | python|numpy | 1 |
363,115 | 48,375,115 | how to average a tensor axis with specified mask in tensorflow | <p>For example:</p>
<p>I have a input <code>tensor(input)</code>, shaped <code>(?,10)</code> <code>dtype=float32</code>, the first dimension means <code>batch_size</code>.</p>
<p>And a mask <code>tensor(mask)</code>, shaped <code>(?,10)</code>. <code>mask[sample_number]</code> is like <code>[True,True,False,...]</cod... | <p>You can use <code>tf.ragged.boolean_mask</code> to keep the dimensionality.</p>
<pre><code>tf.reduce_mean(tf.ragged.boolean_mask(x, mask=mask), axis=1)
</code></pre> | python|tensorflow|artificial-intelligence|conv-neural-network | 10 |
363,116 | 48,053,207 | Writing single CSV header with pandas | <p>I'm parsing data into lists and using pandas to frame and write to an CSV file. First my data is taken into a set where <em>inv</em>, <em>name</em>, and <em>date</em> are all lists with numerous entries. Then I use <em>concat</em> to concatenate each iteration through the datasets I parse through to a CSV file like ... | <p>It's hard to tell what might be going wrong without seeing the rest of the code. I've developed some test data and logic that works; you can adapt it to fit your needs.</p>
<p>Please try this:</p>
<pre><code>import pandas as pd
early_inventions = ['wheel', 'fire', 'bronze']
later_inventions = ['automobile', 'compu... | python|pandas|csv|dataframe|header | 7 |
363,117 | 48,272,609 | i think an error appears to have occurred during "If" | <pre><code>from astropy.io import fits
from scipy.ndimage import gaussian_filter
import numpy as np
import matplotlib.pyplot as plt
import pdb
# Create empty image
nx, ny = 512, 512
image = np.zeros((ny, nx))
# Set number of stars
n = 10000
# Generate random positions
r = np.random.random(n) * nx
theta = np.random.u... | <p>You have to put <code>y[i]</code> and <code>x[i]</code> as int:</p>
<pre><code>image[int(y[i]),int(x[i])]
</code></pre>
<p>to be sure is not a float number. </p> | python|numpy | 0 |
363,118 | 48,393,259 | Count unique pairs and store counts in a matrix | <p>My question is similar to <a href="https://stackoverflow.com/q/7549410">stackoverflow.com/q/7549410</a></p>
<p>I have paired data which look like this:</p>
<pre><code>ID ATTR
3 10
1 20
1 20
4 30
</code></pre>
<p>I want to count the unique pairs and store those frequency counts in a matrix like this:... | <p>It looks like you want to perform a cross tabulation, followed by a reindexing operation. For the cross tabulation, there are many ways to skin a cat. </p>
<p>First, using <code>pivot_table</code> -</p>
<pre><code>v = x.pivot_table(
index=0,
columns=1,
values=1,
aggfunc='size',
fi... | python|pandas|pivot | 4 |
363,119 | 47,994,638 | keras resume training with different learning rate | <p>I built a simple LSTM model using keras and trained as follows:</p>
<pre><code>model = Sequential()
model.add(LSTM(activation='tanh',input_dim=6,output_dim=50,return_sequences=False))
model.add(Dense(output_dim=1,activation = 'sigmoid'))
model.compile(loss='binary_crossentropy', optimizer =optimizers.Adam(lr = 0.01... | <p><strong>New answer</strong></p>
<p>If your optimizer has an <code>lr</code> property, and this property is a tensor, you can change it with:</p>
<pre><code>keras.backend.set_value(model.optimizer.lr, new_value)
</code></pre>
<p><strong>Old answer, with some side effects</strong></p>
<p>You just need to compile t... | tensorflow|machine-learning|deep-learning|keras | 4 |
363,120 | 48,066,933 | Pandas, sorting days whilst preserving order | <p>I've received a CSV file that is a combination of several other csv files. </p>
<p>It has a datetime index (in the format of '2017-01-16' , year, month, day)
However, two problems arise. </p>
<ol>
<li><p>The combination was not done in order.</p>
<pre><code> Date string number (different)
1 ... | <p>By using a new para and prefix the original order :</p>
<pre><code>df['G']=df.groupby(level='Date').cumcount()
df
Out[125]:
string number G
Date
2017-01-16 stringvalue 90 0
2017-01-16 stringvalue 912 1
2017-01-16 stringvalue 29 2
2017-01-17 stri... | python|pandas | 1 |
363,121 | 48,083,226 | Fancy indexing with portion of string in pandas | <p>I have a pandas DataFrame that looks something like this:</p>
<pre><code> Loc WT Var Change AO DP VAF IntEx Upstream Downstream Individual
0 10 A T C>T 40 30000 0.003 Exon ATGCTCGTAG AGTCGATCGT 1
1 10 A T C>T 40 30000 0.003 Exon ATGCTCGTAG AGTCGATCGT 1
... | <p>The condition you're looking for is - </p>
<pre><code>df[df.Downstream.str[0].eq('G')]
</code></pre>
<p>Or,</p>
<pre><code>df[df.Downstream.str.startswith('G')]
</code></pre>
<hr>
<p>Sample data - </p>
<pre><code>df
Loc WT Var Change AO DP VAF IntEx Upstream Downstream \
0 10 A T C>... | python|pandas | 1 |
363,122 | 48,102,450 | Python Two dimensional condition | <p>I am unsure how to phrase a conditional loop. I would like to create a NxN array consisting of elements which are equal to either 1 or -1. I have created a 3x3 array to begin with, which when printed consists of numbers between 0 and 1.</p>
<pre><code>col = 3
row = 3
mymatrix = np.random.rand(col,row)
</code></pre... | <h2>Your Problem</h2>
<p>You need to loop over all rows and columns:</p>
<pre><code>for i in range(row):
for j in range(col):
</code></pre>
<p>You only loop over the first two:</p>
<pre><code>col = 3
row = 3
</code></pre>
<p>In Python <code>range(start, end)</code> gives a range starting form <code>start</code> in... | python|python-2.7|numpy | 4 |
363,123 | 48,247,401 | How do I get the sum of years from date column in reference to each ticker?(Pandas) | <p>I have a data frame that looks like that one below: </p>
<pre><code> Date Open High Low Close Symbol
1990-11-05 3.88 4.25 3.25 4.25 WIKI/DDD
1990-11-06 3.50 4.25 3.50 3.62 WIKI/DDD
1991-11-07 3.50 4.00 3.50 4.00 WIKI/... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> for new column:</p>
<pre><code>mydata['Yrs_Publ_Trd'] = (mydata.groupby('Symbol').Date
.transform(lambda x:... | python|pandas|datetime | 1 |
363,124 | 48,244,794 | Changing values of elements in an array based on first encounter | <p>I have an array of arrays that look like the following:</p>
<pre><code>array([[0, 0, 1, 1],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[1, 0, 1, 1],
[1, 0, 1, 1],
[0, 0, 0, 0],
[1, 0, 0, 1]])
</code></pre>
<p>I want to change this array so that the first time it enco... | <p>This looks like a numpy array to me. </p>
<p><strong>Option 1</strong><br>
You can leverage <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.cumsum.html" rel="nofollow noreferrer"><code>np.cumsum</code></a> to come up with an efficient solution.</p>
<pre><code>>>> (x.cums... | python|arrays|numpy | 2 |
363,125 | 48,836,280 | Python Resize Images | <p>I have a data set containing over 10,000 images of dogs. I plan to use tensorflow to classify dog breeds, however the images are random sizes. For example, some are 200x280 pixels, 100x140 pixels, etc. I would like to standardize the images so that they are smaller and all the same dimensions. Is this possible? I re... | <p>See the <a href="https://www.tensorflow.org/api_guides/python/image#Resizing" rel="nofollow noreferrer">Tensorflow image resizing docs.</a></p>
<p>It's also worth noting that you don't have to resize the images with Tensorflow. You could do it as a preprocessing step with OpenCV. Whether you do it with Tensorflow c... | python-3.x|image|tensorflow|resize|image-recognition | 2 |
363,126 | 48,779,293 | Upgrade to tf.dataset not working properly when parsing csv | <p>I have a GCMLE experiment and I am trying to upgrade my <code>input_fn</code> to use the new <code>tf.data</code> functionality. I have created the following input_fn based off of this <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/census/customestimator/trainer/model.py#L321" rel="nofol... | <ol>
<li><p>When you use <a href="https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset" rel="nofollow noreferrer"><code>tf.data.TextLineDataset</code></a>, each element is a scalar string. In this respect, it is more similar to using <code>tf.TextLineReader.read()</code>, rather than the batch version <co... | tensorflow|google-cloud-ml|tensorflow-datasets | 2 |
363,127 | 48,634,271 | Finding the index of the first element (e.g "True") from a series/column | <p>How do I find the index of an element (e.g "True") in a series or a column?</p>
<p>For example I have a column, where I want to identify the first instance where an event occur. So I write it as </p>
<pre><code>Variable = df["Force"] < event
</code></pre>
<p>This then creates a boolen series of Data where it i... | <p>Use <code>idxmax</code> to find the first instance of the maximum value. In this case, <code>True</code> is the maximum value.</p>
<pre><code>df['Force'].lt(event).idxmax()
</code></pre>
<p>Consider the sample <code>df</code>: </p>
<pre><code>df = pd.DataFrame(dict(Force=[5, 4, 3, 2, 1]), list('abcde'))
df
... | python|pandas|indexing | 19 |
363,128 | 48,810,639 | How can I create an image mask tensor from unknown number of bounding boxes? | <p>I'm trying to fill zeros inside the bounding boxes of an image in TensorFlow. To be specific, I'm trying to implement <code>create_mask_from_bounding_boxes(image, boxes)</code> function in the following code.</p>
<pre><code># Tensor <?, 4>, where each element contains [ymin, xmin, ymax, xmax]
boxes
# Tensor ... | <p>The general answer to "what to do when I have unknown shape?" question is "Use <a href="https://www.tensorflow.org/api_docs/python/tf/TensorArray" rel="nofollow noreferrer">TensorArray</a>". TensorArray gives a way of dealing with statically unknown number of Tensors.</p>
<p>Here are a couple of ways of addressing ... | tensorflow | 3 |
363,129 | 48,757,469 | Finding all checkpoints path in Tensorflow | <p>So far I have used saving and loading checkpoints in Tensorflow only for loading the last checkpoint. Usually the code I use to this is along the lines:</p>
<pre><code>ckpt = tf.train.get_checkpoint_state(load_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(session, ckpt.model_checkpoint_path)
else:
... | <p>The <code>ckpt</code> object in your code snippet is <a href="https://github.com/tensorflow/tensorflow/blob/754048a0453a04a761e112ae5d99c149eb9910dd/tensorflow/python/training/checkpoint_state.proto#L9" rel="nofollow noreferrer">CheckpointState</a> protocol buffer. Instead of accessing the most recent model path (<c... | python|tensorflow | 3 |
363,130 | 48,815,842 | How to efficiently add multiple columns to pandas data frame with values that depend on other dynamic columns | <p>How can I use better solution instead of following codes? in big data set with lots of columns this code takes too much time</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Jan':[10,20], 'Feb':[3,5],'Mar':[30,4],'Month':
[3,2],'Year':[2016,2016]})
# Jan Feb Mar Month Year
# 0... | <p>You should see a marginal speed-up by using <code>df.apply</code> instead of iterating rows:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Jan': [10, 20], 'Feb': [3, 5], 'Mar': [30, 4],
'Month': [3, 2],'Year': [2016, 2016]})
df = df[['Jan', 'Feb', 'Mar', 'Month', 'Year']]
def calculat... | python|performance|pandas|dynamic | 1 |
363,131 | 48,468,731 | How to Pivot a Pandas dataframe into a new format with mixed data type and possible doublicate values | <p>I am working with a large dataset. I extract all the data from the dataset in a table that look like this (Out Put 1): </p>
<pre><code>Label Value
Time
2010-01-01 00:00:30.560 AAAAA [3]
2010-01-01 00:00:30.560 BB -2.6000 ... | <p>You want to use pivot_table not pivot.
It's hard to tell without example data but this should work</p>
<pre><code>pd.pivot_table(df,values="Value",index='Time', columns='Code',aggfunc='mean')
</code></pre>
<p>If you have non numeric data, you should handle that separately then combine it with the numeric data. </p... | python|pandas|dataframe|logging|pivot | 1 |
363,132 | 48,667,422 | Tensor-flow object detection API match resolution of output images to the input test images | <p>I am using Tensorflow object-detection API, to be specific I am referring to detection part of this Ipython notebook (<a href="https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/researc... | <p>It is resolved if you closely observe the output image is similar to what we get when we plot graph in matplotlib. Zoom in and you will see x and y dimensions of the image, these x and y dimensions remain same no matter you change IMAGE_SIZE variable </p> | python-3.x|tensorflow|computer-vision|deep-learning|object-detection | 0 |
363,133 | 48,633,288 | How to assign elements into the diagonal of a 3d matrix efficiently? | <pre><code>a=np.zeros((3,3,3))
b=np.arange(3)
c=np.arange(9).reshape(3,3)
</code></pre>
<p>I wanna put the elements of the array <code>b</code> or <code>c</code> along the diagonal (or above/below the diagonal) of the 3d matrix (tensor) <code>a</code> with respect to a specific axis.</p>
<p>I tired <code>numpy.diagfl... | <p>For the main diagonals you can use <code>np.einsum</code>. For example:</p>
<pre><code>>> np.einsum('iii->i', a)[...] = b
>>> a
array([[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 0.]],
[[ 0., 0... | python|numpy|matrix|scipy|diagonal | 6 |
363,134 | 48,531,571 | Counting masked values from masked arrays | <p>I have a numpy masked array called 'mask' and I was wondering how I would be able to count the amount of either True or False values in the mask?</p>
<p>The mask variable is created when looping through different datasets so it would be helpful if it would work for any random array size.</p> | <p>It's very simple:</p>
<pre><code>import numpy as np
# create random T/F array
Q = np.random.choice([True, False], (100, 100))
n_true = Q.sum()
</code></pre> | python|numpy|masked-array | 1 |
363,135 | 48,704,440 | How to use pd.concat to merge multiple DataFrames together in a For Loop | <p>I am using the Dark Sky API and the darkskylib library to create a yearly, hourly forecast for New York City. </p>
<p>nyc.hourly returns a DataBlock with all weather data, from which I can call the temperature for the next 24hrs. </p>
<p>Basically, my problem is that the variable holding does not seem to add the t... | <p>Try this set-up. You need to store all the <code>holding</code> dataframes and combine them at the end. Dictionaries are a convenient way to do this.</p>
<pre><code>holding = {}
l = 2
for i in range(0, l):
# perform calculations
holding[i] = pd.DataFrame(temp)
final = pd.concat(list(holding.values()), ign... | python|python-3.x|pandas|concatenation|concat | 2 |
363,136 | 48,780,155 | TensorFlow MLP always returns 0 or 1 when float values between 0 and 1 are expected | <p>I am a beginner in TensorFlow. I implemented a tensorFlow MLP network to predict values between 0 and - 1. Input values are float values between 0 and 1 and weights are random float between 0 and 1. But the output always returns 0 or 1 where I expect to return float values between 0 and 1. The code is given below.</... | <p><code>tf.argmax</code> returns the index in the vector which has the max value.</p>
<p>If you want to find the exact class probabilities, you can get that using <code>tf.max</code></p> | python|tensorflow | 3 |
363,137 | 48,833,158 | Merge two lists in pandas groupby and apply | <p>I have a dataframe such as:</p>
<pre><code> make model year range
0 Audi A3 [1991, 1992, 1993]
1 Audi A3 [1997, 1998]
</code></pre>
<p>I need:</p>
<pre><code> make model year range
0 Audi A3 [1991, 1992, 1993, 1997, 1998]
</code></pre>
<p>I have tried</p>
... | <p>Concatenating lists is done by addition, so you can simply apply <code>sum</code> to the relevant column:</p>
<pre><code>In [24]: df
Out[24]:
make model year
0 Audi A3 [1991, 1992, 1993]
1 Audi A3 [1997, 1998]
In [25]: df.groupby([df.make, df.model]).year.apply(sum)
Out[25]:
make ... | python|pandas | 7 |
363,138 | 48,521,560 | How do I create many filtered dataframes using a for loop in Python and Pandas? | <p>I find myself having to create dataframes which are filters of a larger dataframe quite often and I was wondering whether there is a way to program Python to do this for me?</p>
<p>For example, the dataset I'm working on now is app version data, looks like:</p>
<pre><code>user_id | session_id | timestamp | time_se... | <p>I think you need create <code>dictionary of DataFrame</code>s:</p>
<pre><code>d = dict(tuple(df.groupby('app_version')))
print (d)
{'v2': user_id session_id timestamp time_seconds app_version
3 3 477 2014-01-03 221 v2
4 4 121 2014-01-03 120 ... | python|pandas | 5 |
363,139 | 48,440,449 | t-distribution in Python | <p>I have a question regarding non standardized t-distribution in python. I have the location, degrees of freedom and scale parameters for which I use the notation <code>a</code>, <code>b</code> and <code>c</code> respectively. What I want to do is sample from the non standardized t-distribution with these parameters. ... | <p>As noted in your link, the format for <code>scipy.stat.t.rvs</code> is:</p>
<blockquote>
<p>rvs(df, loc=0, scale=1, size=1, random_state=None)</p>
</blockquote>
<p>without that explicit designator, the inputs are asigned based on order specified in the function definition (with anything omitted replaced by the d... | python|numpy|scipy | 0 |
363,140 | 48,467,759 | Removing strings from df column in Python | <p>I'm working in a python3 jupyter notebook.</p>
<p>I'm trying to do some numerical calculations on a column in my dataframe which is made up of dollar amounts. Some of the lines have "$- " instead of numbers. How do I tell python to ignore those rows so I can look at the valid data?</p>
<p>movie is my dataframe
... | <p>This is one way.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[' $- '], ['1'], ['10'], ['100'],
['10000'], ['97250400'], ['98000000'],
['99000000']], columns=['A'])
df['A'] = df['A'].apply(pd.to_numeric, errors='coerce')
df.dtypes
# A float64
# dtype: object
<... | python|pandas|dataframe | 2 |
363,141 | 48,881,499 | Why is numpy's covariance slightly different to manually computing? | <p>I'm just curious, and thought I'd ask this question. How come when I manually compute the covariance matrix of a set of data are my values slightly different to numpy's values? </p>
<p>I have two sets of data <code>X</code> and <code>Y</code></p>
<pre><code>data = io.loadmat("datafile.mat")['data']
X = data[:,0]
Y... | <p>By default <code>np.cov</code> calculates the unbiased covariance which uses a factor <code>(N-1)</code> instead of <code>N</code> as you calculated.</p>
<p>If you check the documentation for <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html" rel="noreferrer"><code>np.cov</code></a> you s... | python|numpy | 6 |
363,142 | 48,787,670 | Convert hours into seconds con pandas | <p>I have hours extracted from the timestamp of my dataframe by the command lines:</p>
<pre><code>import pandas as pd
from datetime import *
from datetime import datetime
import datetime as dt
import time
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['time'] = df['timestamp'].dt.time
df['time']
... | <p>Convert datetimes to <code>hour</code>s, <code>minute</code>s and <code>second</code>s:</p>
<pre><code>df['time'] = df['timestamp'].dt.hour * 3600 +
df['timestamp'].dt.minute * 60 +
df['timestamp'].dt.second
</code></pre>
<p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/genera... | pandas|time-series | 2 |
363,143 | 48,794,501 | How fast to derive new features (pandas) shift one period or n periods at same time? (Performance issue) | <p>I have a dataframe with some continuos freatures (about 14), and I need to derivate more 14 (shift 1 period of hour) until n hours.</p>
<p>Supposing that I need until 6 hours before, so I will have more 84 columns (14*6).</p>
<p>For example, <strong>prcp</strong> (precipitation) derivates <strong>prcp_1</strong>, ... | <p>I solved my perfomance issue using a personalized function based on <strong>dataframe.shift</strong>:</p>
<blockquote>
<p>DataFrame.shift(periods=1, freq=None, axis=0)[source]</p>
<pre><code>Shift index by desired number of periods with an optional time freq
</code></pre>
</blockquote>
<p>This my function:</p>
... | python|performance|pandas | 0 |
363,144 | 48,837,777 | pandas to_sql only writing first row to db | <p>I am using the below code to read a tab delimited file into a postgres database</p>
<pre><code>enginestring = cfg.dbuser+":"+cfg.dbpwd+"@"+server.local_bind_host+":"+str(server.local_bind_port)+"/"+cfg.dbname
engine = create_engine('postgresql://' + enginestring)
rows = []
for line in smart_open.smart_open(key):
... | <p>OK here is an update:</p>
<ul>
<li>I solved the single row issue by stripping EOL chars (could see ¶ at the end of the last inserted field)</li>
<li>Then I was just getting empty tables so I added chunksize parameter to to_sql - not sure why it didn't fail instead of just proceeding but whatever it's OK now</li>
</... | python|pandas|pandas-to-sql | 0 |
363,145 | 48,709,128 | Plot Gradients of Individual Layers in Tensorboard | <p>I have a GCMLE experiment and I want to plot the global norm of layer wise gradients in tensorflow. I can ploy the global norm of all gradients in tensorflow, but I'd like to specifically plot the gradients for only the embeddings. Here is my current code</p>
<pre><code>gradients, variables = zip(*train_op.compute... | <p>Something like this:</p>
<pre><code> grads_and_vars=train_op.compute_gradients(loss)
for g, v in grads_and_vars:
if g is not None:
#print(format(v.name))
grad_hist_summary = tf.summary.histogram("{}/grad_histogram".format(v.name), g)
sparsit... | python|tensorflow|tensorboard|google-cloud-ml | 4 |
363,146 | 48,764,427 | Keras GAN (generator) not training well despite accurate discriminator | <p>I've tried sorting this out for a few days now, following many pieces of advice found on forums etc, and now would welcome any suggestions to what is wrong!</p>
<p>I'm attempting to get my first GAN training - a simple feedforward deep net - very similar to using MNIST dataset, but with spectrum power windows deriv... | <p>What the solution actually was that I didn't swap my True/False class in Generator training (suggested <a href="https://github.com/soumith/ganhacks" rel="nofollow noreferrer">https://github.com/soumith/ganhacks</a>), which I think effectively makes it gradient ascent.</p>
<p>Clarification on this would be nice to h... | tensorflow|keras | 1 |
363,147 | 48,549,844 | pandas get the name of the column that contains a value | <p>I am working on a script and using the <code>pandas</code> lib. I am new to the pandas lib so the question may be silly. I've imported my data from a <code>csv</code> into a <code>pandas.dataframe</code>. My data frame looks like below:</p>
<pre><code> set1 set2 set3 ... | <pre><code>import numpy as np
import pandas as pd
""" set1 set2 set3 set4
0 744110.0 507121.0 790001.0 785693.0
1 744107.0 507126.0 791002.0 788107.0
2 744208.0 535214.0 791103.0 788108.0
3 744210.0 534195.0 790116.0 784170.0
"""
df = pd.read_clipboard(sep='\s{2,}', engine='python', dtype = 'int'... | python|pandas | 2 |
363,148 | 48,552,406 | How to use pandas isin() with IF statement | <p>I have a column(INT_STATUS) in a data frame(file1) and INT_STATUS has values from A to Z and 1 to 9. If INT_STATUS columns has values in this list ['B','C','F','H','P','R','T','X','Z','8','9'] then I want to create a new column "rcut" and give a value '01' <strong>file1['rcut'] == '01'</strong>.</p> | <p>You can assign using loc</p>
<pre><code>file1.loc[file1['INT_STATUS'].isin(l), 'rcut'] = '01'
</code></pre> | python|pandas|if-statement | 3 |
363,149 | 48,536,802 | Iterating over different data frames using an iterator | <p>Suppose I have n number of data frames <code>df_1</code>, <code>df_2</code>, <code>df_3</code>, ... <code>df_n</code>, containing respectively columns named <code>SPEED1</code> ,<code>SPEED2</code>, <code>SPEED3</code>, ..., <code>SPEEDn</code>, for instance:</p>
<pre><code>import numpy as np
df_1 = pd.DataFrame({'... | <p>You can use the <code>globals()</code> function which allows you to get a variable by his name.</p>
<p>I just add <code>df_i = globals()["df_"+str(i)]</code> at the begining of the for loop : </p>
<pre><code>for i in range(1,n+1):
df_i = globals()["df_"+str(i)]
df_invalid_i=df_i.loc[df_i['SPEED'+str(i)]>... | python|pandas|loops|dataframe | 1 |
363,150 | 48,528,404 | Create index dictionary from integer list | <p>I have a (long) array <code>a</code> of a handful of different integers. I would now like to create a dictionary where the keys are the integers and the values are arrays of indices where in <code>a</code> the respective integer occurs. This</p>
<pre><code>import numpy
a = numpy.array([1, 1, 5, 5, 1])
u = numpy.... | <p><strong>Approach #1</strong></p>
<p>One approach based on sorting would be -</p>
<pre><code>def group_into_dict(a):
# Get argsort indices
sidx = a.argsort()
# Use argsort indices to sort input array
sorted_a = a[sidx]
# Get indices that define the grouping boundaries based on identical elems... | python|numpy | 5 |
363,151 | 48,810,937 | keras/tensorflow does not find weights file imagenet | <p>The following minimal example code</p>
<pre><code>#!/usr/bin/env python3
from tensorflow.contrib.keras.api import keras
model = keras.applications.xception.Xception(input_shape=(299, 299, 3))
</code></pre>
<p>fails with</p>
<pre><code>File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/_impl/kera... | <p>It's an issue specific to TF-Keras. It's discussed in this <a href="https://github.com/tensorflow/tensorflow/issues/16683#issuecomment-363621409" rel="nofollow noreferrer">GitHub issue</a> and has been fixed. According to the author,</p>
<blockquote>
<p>It was introduced in PR <a href="https://github.com/tensorfl... | tensorflow|keras|imagenet | 1 |
363,152 | 48,875,609 | Pandas Data Frame Summary Table | <p>How can I make a summary of a data frame in Pandas, stacking individual operations.</p>
<p>For example, I used the following code: </p>
<pre><code> df=pd.DataFrame(wb)
# Get list with headers
header1 = list(df)
count=df.count()
NaNs=df.isnull().sum()
sum=df.sum(0)
mean=df.mean()
median=df.median()
min= df.min()
... | <p>Seems like you may get use out of <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.agg.html" rel="nofollow noreferrer"><code>DataFrame.agg()</code></a>, with which you can essentially build a customized <code>.describe()</code> output. Here's an example to get you started:</p>
<pre>... | python|pandas | 2 |
363,153 | 48,870,463 | pd.to_datetime is getting half my dates with flipped day / months | <p>My dataset has dates in the European format, and I'm struggling to convert it into the correct format before I pass it through a pd.to_datetime, so for all day < 12, my month and day switch.
Is there an easy solution to this?</p>
<pre><code>import pandas as pd
import datetime as dt
df = pd.read_csv(loc,dayfirst=... | <p>Add <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer">format</a>.</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
</code></pre> | python|pandas|datetime | 4 |
363,154 | 48,452,933 | Python comparison ignoring nan | <p>While <code>nan == nan</code> is always <code>False</code>, in many cases people want to treat them as equal, and this is enshrined in <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.equals.html" rel="noreferrer"><code>pandas.DataFrame.equals</code></a>:</p>
<blockquote>
<p>NaNs i... | <p>Suppose you have a data-frame with <code>nan</code> values:</p>
<pre><code>In [10]: df = pd.DataFrame(np.random.randint(0, 20, (10, 10)).astype(float), columns=["c%d"%d for d in range(10)])
In [10]: df.where(np.random.randint(0,2, df.shape).astype(bool), np.nan, inplace=True)
In [10]: df
Out[10]:
c0 c1 ... | python|python-2.7|pandas|nan|equality | 11 |
363,155 | 71,073,003 | Change pandas dataframe first row to become column names | <p>I have the following response from reading a gsheet from google API.</p>
<pre><code>response = [['Owner', 'Database', 'Schema', 'Table', 'Column', 'Comment', 'Status'], ['', 'VICE_DEV', 'AIRFLOW', 'TASK_INSTANCE', '_LOAD_DATETIME', 'Load datetime'], ['', 'VICE_DEV', 'AIRFLOW', 'TEST', '_LOAD_FILENAME', 'load file n... | <p>You can for example directly set the first row as columns and use the rest as rows:</p>
<pre><code>response = [['Owner', 'Database', 'Schema', 'Table', 'Column', 'Comment', 'Status'], ['', 'VICE_DEV', 'AIRFLOW', 'TASK_INSTANCE', '_LOAD_DATETIME', 'Load datetime'], ['', 'VICE_DEV', 'AIRFLOW', 'TEST', '_LOAD_FILENAME... | pandas | 2 |
363,156 | 70,775,971 | Transform table from start/end records to timeseries | <p>I have a dataset that is organized as the first table below, and I would like to transform it into a table like the second, in a relatively efficient way. Thanks !</p>
<p><strong>Input</strong>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th style="text-align: left;">start</... | <p>You can use <code>melt</code>+<code>pivot</code>:</p>
<pre><code>(df.melt(id_vars=['id', 'value'], value_name='col')
.pivot_table(index='id', columns='col', values='value', fill_value=0)
.reset_index() # optional
)
</code></pre>
<p>output:</p>
<pre><code>id 01-01-2021 01-02-2021 01-03-2021 01-04-2021 ... | python|python-3.x|pandas|dataframe | 0 |
363,157 | 70,912,685 | Dataframes - equivalent to JOIN with LIKE condition, or value in sublist | <p>I have 2 dataframes from 2 different sources.</p>
<p><strong>System A</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">system_a_id</th>
<th style="text-align: center;">designation</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">A10001</td>... | <p>Looks like "designation" appears after comma in "other_ids". You could split "other_ids" on comma, take the second parts and <code>assign</code> it as "designation" column to <code>systemB</code>. Then merge it with <code>systemA</code> on "designation":</p>
<pre><co... | python|pandas|dataframe | 0 |
363,158 | 71,052,250 | Why do I get nan from a new column consisting of the average of other columns? | <p>I need to create a new column consisting of the average of other columns in the dataframe. If I add the columns to be averaged manually everything works, as in this case:</p>
<p>Case 1 - It works and give me a new column "BL_SFI_AV" with float</p>
<pre><code>matrice_clean['BL_SFI_AV'] = matrice_clean[['BL_... | <p>First, I think your "case 2" example contains an error. The columns are in the second axis, so you need to include a row indexer first:</p>
<pre><code>matrice_clean.loc[:, 'BL_SFI_01':'BL_SFI_03'].mean (axis = 1)
# ^^
# Don't forget this
</code></pre>
<p>Next, I have a theo... | python|pandas|dataframe|mean|python-3.9 | 0 |
363,159 | 70,824,552 | Fill cell within a dataframe according to another dataframe [python] | <p>I have two dataframes such as</p>
<p><strong>Tab1 :</strong></p>
<pre><code>ORFs_values Groups SP1 SP2 SP3
SP_ORF1 Group1 1 1 0
SP_ORF1 Group2 0 0 0
SP_ORF1 Group3 0 1 0
SP_ORF1 Group4 1 1 1
SP_ORF1 Group5 ... | <p>Here is a solution using <code>mask()</code></p>
<p><code>df</code> is Tab1 and <code>df2</code> is Tab2</p>
<pre><code>df = df.set_index('Groups')
(df.mask(df.eq(1),
df2.set_index(['Groups','SP_names'])['SP_names2'].unstack())
.reset_index())
</code></pre>
<p>Output:</p>
<pre><code> Groups ORFs_values ... | python|python-3.x|pandas | 1 |
363,160 | 70,862,726 | How to add seconds to a date in pandas | <p>I have a Pandas DataFrame <code>df</code>, where <code>time</code> is given in <code>seconds</code> (from the beginning of the day)</p>
<pre><code>df["time"]
0 43200
1 43240
2 43280
3 43320
</code></pre>
<p><code>43200</code> corresponds to <code>12:00:00</code></p>
<p>How can I add a date (2019-07-21) ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <code>unit</code> and <code>origin</code> parameters:</p>
<pre><code>df["time"] = pd.to_datetime(df["time"], unit='s', origin='2019-07-21')
p... | python|pandas|dataframe | 2 |
363,161 | 70,778,057 | Pandas Dataframe: Change each value's ones-digit | <p>I am writing unit tests for 2 data frames to test for equality by converting them to dictionaries and using unittest's assertDictEqual(). The context is that I'm converting Excel functions to Python but due to their different rounding system, some values are off by merely +/- 1</p>
<p>I've attempted to use the DF.ro... | <p>I'm not 100 pourcent sure I got what you are trying to do but why not just divide by 10 to lose the last digit that is bothering you?
division with "//" will keep only the significant numbers. You can then multiply by ten if you want to keep the overall number size.</p> | python|pandas | 1 |
363,162 | 70,836,639 | Create new row in a dataframe if values from two columns are different | <p>Lets say I have a dataframe like this one:</p>
<pre><code> Col1 Col2 Tag_history New_tag Col5 created
0 Name1 Value1 Tag10 Tag10 Rank4 2021-03-21 12:58:09
1 Name1 Value2 Tag10 Tag10 Rank4 2021-03-21 13:58:09
2 Name1 Value3 Tag10 Tag10 ... | <p>First of all, I don't recommend using any loops because they are not very effective.</p>
<pre><code>different_value = df[~(df['Tag_history'] == df['New_tag'])] #First check and search for rows that contains different "Tag_history" and "New_tag"
different_value.loc[:,'New_tag'] = different_value[... | python|python-3.x|pandas|dataframe | 2 |
363,163 | 70,826,873 | Pytorch Matrix Multiplication Error while extracting features from VGG Model | <p>I am trying to implement Neural Style Transfer Algorithm. I am using the pretrained VGG model in Pytorch. In the given Code below, i tried to extract particular layers from the model so that i can pass my image through them. But i keep getting an error on <code>x=layer(x)</code></p>
<pre><code>def get_features(img,m... | <p>The PyTorch torch vision library has a very intuitive VGG_16 model you can extract the features from:</p>
<pre><code>import torch, torchvision as tv
model = tv.models.vgg16()
img_batch = torch.randn([1,3,512,512])
feature_extractor = model.features
Features=[]
x = img_batch.clone()
for name,layer in feature_extract... | python|deep-learning|neural-network|pytorch|matrix-multiplication | 0 |
363,164 | 70,760,909 | How to merge two pandas DataFrames into single Multi-Index DataFrame? | <p>I have two DataFrames that are equally indexed, but each represents a different aspect of my full dataset.<br />
For instance:</p>
<pre><code>import pandas as pd
from datetime import date
df_price = pd.DataFrame(
index=pd.date_range(start=date(2021, 1, 1), end=date(2021, 1, 3), freq="D"),
columns=... | <p>One option:</p>
<p>(i) <code>join</code> the two DataFrames</p>
<p>(ii) split column names on <code>'_'</code> and because we want to use <code>from_tuples</code>, map the sublists to tuples</p>
<p>(iii) use <code>pd.MultiIndex</code> to convert the column to MultiIndex</p>
<p>(iv) sort column names to match the des... | python|pandas|dataframe | 2 |
363,165 | 70,878,351 | Numpy unpackbits type error when trying to convert bytes to bits | <p>To get bits from bytes:</p>
<pre><code>bytes = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
bits = numpy.unpackbits(bytes)
</code></pre>
<p>throws this error:<br />
<code>TypeError: Expected an input array of unsigned byte data type</code><br />
but if I get bytes in this way it works:</p>
<pre><code>bytes = numpy.... | <p>bytes should be unsigned array, why not use a numpy unsigned?</p>
<pre><code>bytearray = numpy.array([0x13, 0x00, 0x00, 0x00, 0x08, 0x00],dtype=numpy.uint8)
bits = numpy.unpackbits(bytearray)
</code></pre> | python|numpy | 1 |
363,166 | 70,948,320 | How Do I match two Data Frames in Pandas with multiple matches? | <p>I have 2 data frames I want to match some data from one data frame and append it on another.</p>
<p>df1 looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>sourceId</th>
<th>firstName</th>
<th>lastName</th>
</tr>
</thead>
<tbody>
<tr>
<td>1234</td>
<td>John</td>
<td>Doe</td>... | <p>This works. It's long and not the most elegant, but it works well :)</p>
<pre><code>tmp = df2.assign(agentId=df2['agentId'].str.split(',')).explode('agentId').set_index('agentId')['sourceId'].astype(str).groupby(level=0).agg(list).str.join(',').reset_index()
df1['sourceId'] = df1['sourceId'].astype(str)
new_df = df1... | python|pandas|dataframe | 0 |
363,167 | 70,987,427 | (Python)Selecting most closest date to the end of month | <p>My goal is to choose the most closest date to end of month.
For instance, how to choose '2021-01-29', '2021-02-26' ?
(Some sort of masking method is available?)</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'date': ['2021-01-28', '2021-01-29', '2021-02-25','2021-02-26']})
date
0 2021-01-28
1 2021-0... | <p>You can grouping by month periods and get maximal value of datetimes:</p>
<pre><code>df['date'] = pd.to_datetime(df['date'])
df = df.groupby(df['date'].dt.to_period('m')).max()
print (df)
date
date
2021-01 2021-01-29
2021-02 2021-02-26
</code></pre>
<p>Or use <a href="http://pandas.pydat... | pandas|dataframe | 2 |
363,168 | 70,812,272 | Pytorch Lightning Loaded Model Gives Different Results Each Time | <p>I have a U-Net architecture and when I train the model and print out some results without loading it, the model gives good results but when I load the model checkpoint file and try to make predictions it predicts random noise, even worse it gives different predictions for each run with the same test set</p>
<p>Here ... | <p><code>load_from_checkpoint()</code> is not an inner function, you need to assign it to <code>model</code> variable. Otherwise, you just used a randomly initialized model which results in different results.</p>
<pre><code>model = model.load_from_checkpoint('Model/last.ckpt', in_channels=1, out_channels=N_CLASSES, fea... | python|pytorch|conv-neural-network|image-segmentation|pytorch-lightning | 0 |
363,169 | 70,859,276 | Image Feature Extraction in PyTorch | <p>I am going through difficulties to understand this code snippet.</p>
<pre><code>import torch
import torch.nn as nn
import torchvision.models as models
def ResNet152(out_features = 10):
return getattr(models, "resnet152")(pretrained=False, num_classes = out_features)
def VGG(out_features = 10):
... | <p>Note that <code>getattr(models, 'resnet152')</code> is equivalent to <code>models.resent152</code>.</p>
<p>Hence, the code below is returning the model itself.</p>
<pre><code>getattr(models, "resnet152")(pretrained=False, num_classes = out_features)
# is same as
models.resnet152(pretrained=False, num_class... | python|pytorch|conv-neural-network|feature-extraction|image-classification | 1 |
363,170 | 70,962,584 | call dataframe from list of dataframes python | <p>I have a use case where i have an unknown list of dfs that are generated from a groupby. The groupby is contained in a list. Once the groupby gets done, a unique df is created for each iteration.</p>
<p>I can dynamically create a list and dictionary of the dataframe names, however, I cannot figure out how to use the... | <p>You can use the <code>globals()</code> method to index the global variable (here a DataFrame) based on the string value i in the loop. See below:</p>
<pre><code># loop through every dataframe and transpose the dataframe
for i in df_names:
# call globals() to return a dictionary of global vars and index on i
... | python|pandas|dataframe|dictionary|for-loop | 1 |
363,171 | 70,834,544 | Pandas: Split and/or update columns, based on inconsistent data? | <p>So I have a column that contains baseball team names, and I want to split it into the 2 new columns, that will contain separately city name and team name.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Team</th>
</tr>
</thead>
<tbody>
<tr>
<td>New York Giants</td>
</tr>
<tr>
<td>Atlanta... | <p>Use:</p>
<pre><code>#part of cities with space
cities = ['York','Angeles']
#test rows
m = df['Team'].str.contains('|'.join(cities))
#first split by first space to 2 new columns
df[['City','Franchise']] = df['Team'].str.split(n=1, expand=True)
#split by second space only filtered rows
s = df.loc[m, 'Team'].str.spli... | python|pandas|split | 2 |
363,172 | 70,911,875 | Issue with .loc and np.nan | <p>I'm running into issues with the following bit of code:</p>
<pre><code>student_data_df.loc[(student_data_df.school_name=="Thomas High School") & (student_data_df.grade=='9th'), student_data_df.reading_score] = np.nan
</code></pre>
<p>Basically I'm trying to use .loc on a dataframe to pull a specific sc... | <p>Break your code into separate lines to make it understandable and debuggable:</p>
<pre><code>school_matches = student_data_df.school_name=="Thomas High School"
grade_matches = student_data_df.grade=='9th'
rows = school_matches & grade_matches
column = student_data_df.reading_score
student_data_df.loc[... | python|pandas|jupyter-notebook|nan|.loc | 1 |
363,173 | 71,063,661 | plot histogram after averaging images | <p>I have the following code to average a set of images (say 100 images) and to plot the histogram of the averaged image (one image). I am not getting the histogram with this code. Could you please help me in this code.</p>
<hr />
<pre><code># reading multiple images
S01=[i for i in glob.glob("C:/Users/experiment... | <p>No need to convert s_avg to an Image, you can compute the histogram of the array using <code>.ravel()</code></p>
<pre><code>fnames = [i for i in glob.glob("C:/Users/experiment 1/S01/*.tif")]
s=np.array([np.array(Image.open(fname)) for fname in fnames])
s_avg=np.mean(s,axis=(0))
#plot histogram
plt.hist(... | numpy|matplotlib|image-processing|python-imaging-library|histogram | 0 |
363,174 | 70,853,658 | How do I remove the b'' after retrieving data from mysql to Python | <ol>
<li>I get the data from MySQL server, and format it into a list of lists.</li>
</ol>
<pre><code>raw_data = read_query(connection, query)
csv_data = []
for row in raw_data:
row = list(row)
csv_data.append(row)
</code></pre>
<ol start="2">
<li>Convert the data into Dataframe, and export as CSV</li>
</ol>
<pr... | <p>Decode the members of <code>row</code>.</p>
<pre><code>raw_data = read_query(connection, query)
csv_data = []
for row in raw_data:
row = list(row)
row = [x.decode() for x in row]
csv_data.append(row)
</code></pre> | python|pandas|encoding|byte | 0 |
363,175 | 70,986,177 | How to append records from one table to another table in SQL | <p>I have two tables, first table contains 244 columns with 4945 records, where as in second table 11 columns with 3737 records, but 4 columns are common in both id, name, tocken, tockenold. How to combine this two tables</p>
<p>I tried with UNION but columns must be equal in both .
Tried with full join getting the exa... | <p>try this:</p>
<pre><code>select *
from (
select id, name, tocken, tockenold
from table_1
union
select id, name, tocken, tockenold
from table_2
) m
join table_1 t1
on m.id = t1.id and m.name = t1.name and m.tocken = t1.tocken and m.tockenold = t1.tockenold ... | python|sql|pandas-groupby|snowflake-cloud-data-platform | 0 |
363,176 | 70,992,229 | Make axes unequal in matplotlib or seaborn | <p>In MATLAB, using <code>surf</code> a colleague was able to make the heatmap/surface below. I have been trying to generate plots using the same data in both <em>matplotlib</em> and <em>seaborn</em>, but cannot seem to find any way to make the x-axis unequally spaces like MATLAB does.</p>
<p>Is there a way out of the... | <p>Seaborn's heatmap (based on matplotlib's <code>imshow</code>) always creates categorical axes. You can use matplotlib's <code>pcolor</code> or <code>pcolormesh</code> to set numeric x and y values for the cell edges.</p>
<p>Here is an example. Note that the number of data values is one less in both directions compar... | python|pandas|matplotlib|seaborn | 2 |
363,177 | 70,955,450 | How to return all labels and scores in SageMaker Inference? | <p>I am using the <code>HuggingFacePredictor</code> from <code>sagemaker.huggingface</code> to inference some text and I would like to get all label scores.</p>
<p>Is there any way of getting, as response from the endpoint:</p>
<pre class="lang-json prettyprint-override"><code>{
"labels": ["help"... | <p>With your current code sample, it is not quite clear what specific task you are performing, but for the sake of this answer, I'll assume you're doing text classification.</p>
<p>Most importantly, though, we can read the following in <a href="https://huggingface.co/docs/sagemaker/reference#inference-toolkit-api" rel=... | python|amazon-web-services|nlp|amazon-sagemaker|huggingface-transformers | 1 |
363,178 | 70,988,623 | json data formatting using pandas | <p>Here, having the input data in this format (json) :</p>
<pre><code>[
{
"timestamp": "2019-05-25T00:00:00",
"name": "sample_name",
"keys": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5&qu... | <p>You can simply use Python here to reformat your json file, like this:</p>
<pre class="lang-py prettyprint-override"><code># Define a helper function
def reformat(input_item):
output_item = {
key: value for key, value in zip(input_item["keys"], input_item["values"])
}
output_it... | python|json|pandas | 0 |
363,179 | 70,881,421 | tensorflow: logging custom loss function? | <p>I've written a custom loss function as follows:</p>
<pre><code>def distance_loss(y_actual, y_pred):
return tf.math.sqrt(
tf.math.add(
tf.math.pow(
tf.math.subtract(y_actual[0], y_pred[0]),
tf.constant(2.0)
),
tf.m... | <p>Use <code>tf.print</code>:</p>
<pre class="lang-py prettyprint-override"><code>def distance_loss(y_actual, y_pred):
x = tf.math.pow(
tf.math.subtract(y_actual[0], y_pred[0]),
tf.constant(2.0)
)
y = tf.math.pow(
tf.math.subtract(y_ac... | python|python-3.x|tensorflow|tensorflow2.0 | 1 |
363,180 | 71,052,621 | How to get line chart to show 3 columns from CSV files? | <p>i have a CSV file showcasing the reduction of Methane in the atmosphere from the UK over a 9 year period. I'm attempting to get the file to show the data visually while using matplotlib, later on, I hope to add more countries to the script so that I can showcase how counties have reduced their emissions throughout t... | <p>You could reformat your dataframe after reading your csv and put the countryname into the columnname (Multiindex). This way you can plot multiple states against one time column in one plots with different colors using Dataframe.plot(x='Year'). I didnt test the pandas plot function, but this was my code to rearrange ... | python|pandas|matplotlib | 0 |
363,181 | 70,802,363 | Why does Pandas throw 'NoneType' object is not callable during plotting? | <p>I have Pandas series:</p>
<pre><code>results
Out[75]:
job_id
294 PASSED 115
FAILED 1
FIXED 0
Failed 0
REGRESSION 0
SKIPPED 0
295 PASSED 191
FAILED 0
FIXED 0
F... | <p>I'm assuming you want to produce something along the lines of:</p>
<p><a href="https://i.stack.imgur.com/lyBNL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lyBNL.png" alt="enter image description here" /></a></p>
<p>Below is a fully reproducible Python script that generated the above plot.</p>
... | python|pandas|matplotlib | 0 |
363,182 | 71,019,551 | Spyder 5 & Windows: Variable Explorer doesn't show pandas dataframes | <p>Windows 10, installed Python 3.10, then Spyder 5 from Windows Installer. Changed python interpreter (preferences) to the previously installed Python 10. Basically it works fine. However if I want to see in the Variable Explorer more complex objects like pandas dataframes, it gives back:</p>
<p>Spyder was unable to r... | <p>Downgrading pandas worked for me. I had version 1.4.2 of pandas and the Spyder installer I used (5.15) had come with pandas version 1.3.3. I think that version of spyder isn't compatible with the newer pandas version so I downgraded the pandas package that's used in the python interpreter (not the one that comes wit... | python|pandas|windows|ide|spyder | 1 |
363,183 | 70,807,989 | How to efficiently fix JSON file converted from pandas dataframe | <p>I have a JSON file that I read in pandas and converted to a dataframe. I then exported this file as a CSV so I could edit it easier. Once finished, I read the CSV file back into a dataframe and then wanted to convert it back to a JSON file. However, in that process a whole lot of extra data was automatically added t... | <p>The issue is that you are adding an index at two places.</p>
<p>Once while writing your file to csv. This adds the "Unnamed: 0" fields in the final JSON files. You can use <code>index = False</code> in the <code>to_csv</code> method while writing CSV to disk or specify the <code>index_col</code> parameter ... | python|json|pandas | 2 |
363,184 | 71,037,975 | How to find maximum number of occurrences for a character in a cell in a column in a CSV table in Python | <p>I'm trying to find the maximum number of occurrences of '/' (a slash) in a cell in a column in a CSV file. Here's the table below. It has hundreds of rows.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Person Full Name</th>
<th>Person CRD Number</th>
<th>ID Number</th>
</tr>
</thead>
<... | <pre><code>print(max(df['Person CRD Number'].str.count('/')))
</code></pre>
<p>output:</p>
<pre><code>>>> 3
</code></pre> | python|pandas|dataframe|csv | 1 |
363,185 | 70,898,144 | numpy.resize throws valueError despite image matrix product equaling the total image size | <p>I am trying to resize a grayscale image into a numpy array like so:</p>
<pre><code>return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
</code></pre>
<p>and getting this error:</p>
<blockquote>
<p>ValueError: cannot reshape array of size 1909760 into shape
(1024,1865,3)</p>
</blockquot... | <p>If you're using the <code>PIL</code> module for your image, you could try converting it to an RGB before getting the data. Something like this should work:</p>
<pre><code>image = image.convert("RGB")
return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
</code></pre>
<p>This w... | python|numpy|image-processing|python-imaging-library | 0 |
363,186 | 71,061,839 | Tensorflow gradient null for VAE with custom transformation layer with numpy_function | <p>I am new to tensorflow and I wanted to start with a modified version of the VAE implementation of the official <a href="https://www.tensorflow.org/tutorials/generative/cvae" rel="nofollow noreferrer">tensorflow tutorials</a>. I modified it that way, that I am having a custom input layer in the encoder which does a t... | <p>Using the <a href="https://www.tensorflow.org/api_docs/python/tf/custom_gradient" rel="nofollow noreferrer"><code>tf.custom_gradient</code></a> decorator with the numpy function call will at least run the training with valid gradients for all trainable weights. A minimal implementation could just forward the incomin... | tensorflow|machine-learning|gradient | 0 |
363,187 | 70,927,463 | Is there a way to read and plot the nth file in a folder in python? | <p>Im trying to find a quick and easy way to read and plot the nth csv file in a folder,</p>
<p>im currently working with the following, to read all files in the folder></p>
<pre><code>import os
import glob
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
path = os.g... | <pre><code>for file, count in enumerate(csv_files, start=1):
if count % 4:
Data = pd.read_csv(file,header=33)
sns.lineplot(x=Data['x'],y=Data['y'],data=Data)
</code></pre>
<p><code>count</code> will keep increasing and only read every 4th file.</p> | python|pandas|file|plot | 1 |
363,188 | 70,985,884 | Delimiter of read csv is in text field | <p>I received extracted data from a server, the problem is the extract has the delimiter ";" in the csv file.</p>
<p>I read the folder with the following command:</p>
<pre><code>files = glob.glob(r"path/*.csv")
dfs = [pd.read_csv(f, sep=";", engine='c') for f in files]
df2 = pd.concat(dfs,... | <p>I wasn't aware of a programmatic approach to solve this (see my comment), but out of interest, a quick search led me to <a href="https://stackoverflow.com/questions/43273976/escaping-quotes-and-delimiters-in-csv-files-with-excel">Escaping quotes and delimiters in CSV files with Excel</a>. Perhaps you could try the s... | python|pandas|csv|text | 0 |
363,189 | 71,058,390 | Python Script Stops Silently | <p>I'm running Python scripts as child processes, spawned using Nodejs.</p>
<p>When running locally, or locally using Docker / Kubernetes installation, it works as expected and completes all functions in the script. When running the container in Kubernetes Azure, the script silently stops / fails at just under 1 hour, ... | <p>Unix was killing the Python processes due to high memory usage, I was able to find OOM errors in the system logs by using ssh into the pod, then using <code>dmesg</code> for the kill logs and <code>ps aux --sort -pmem</code> to see the memory usage in the pod.</p>
<p>Reason for OOM was that the default memory alloca... | python|pandas|docker|kubernetes|swifter | 0 |
363,190 | 70,997,307 | No module named 'keras_tuner' even though i installed it | <p>i'm working on a classifier that uses CNN and i need to use the keras tuner so i can find the best CNN architecture</p>
<p>i executed this command "pip install keras-tuner" and it was installed successfully</p>
<p>but when i import it "import keras_tuner as kt" and run the python script</p>
<pre>... | <p>so i used</p>
<pre><code>pip install keras_tuner
</code></pre>
<p>in VSCode and the packge was really installed but in the global site-packages folder and not in venv/lib folder</p>
<p>so all i did is that i went to venv/pyvenv.cfg file in VSCode</p>
<p>and set</p>
<pre><code>include-system-site-packages = true
</co... | python|tensorflow|visual-studio-code|keras-tuner | 1 |
363,191 | 51,858,580 | Pytorch Double DQN not working properly | <p>I'm trying to make a double dqn network for cartpole-v0, but the network doesn't seem to be working as expected and stagnates at around 8-9 reward. What am I doing wrong?</p>
<p>Each step in the learning phase:</p>
<pre><code>def make_step(model, target_model, optimizer, criterion, observation, action, reward, nex... | <p>Increase the target network update frequency can solve the problem.</p>
<pre class="lang-py prettyprint-override"><code>optimizer.zero_grad() #RMSprop on net
if e % 100 == 0:
target_net.load_state_dict(net.state_dict())
for i in range(len(data)):
observation, action, reward, next_observation = data[i]
m... | python|pytorch|reinforcement-learning | 0 |
363,192 | 51,654,259 | Make predictions with an old model without losing the current model | <p>I am training a model that incrementally learns new classes, e.g. n target classes during the first 70 or so epochs, then the original n classes plus m new target classes, etc. When training the model on n+m target classes, the loss function requires predictions from the model trained on n target classes. How can I ... | <p>Would it be possible to use the weights to do it?
Put the weigh of your targets to 1 and the weights of your not-targets to 0</p>
<p>At first, you'd have your weight tensor at <code>[1]*n + [0]*m</code> (+ as in concat).
Then you'd assign it to <code>[1]*(n+m)</code> when you want to add you m new targets
and so fo... | python|tensorflow | 0 |
363,193 | 51,826,383 | Retrieve column name of last month of transactions in Pandas | <p>Let's say I have a dataframe formatted the following way:</p>
<pre><code>id | name | 052017 | 062017 | 072017 | 092017 | 102017
20 | abcd | 0 | 100 | 200 | 50 | 0
</code></pre>
<p>I need to retrieve the column name of the last month an organization had any transactions. In this case, I would like t... | <p><code>replace</code> 0 to <code>np.nan</code> then using <code>last_valid_index</code></p>
<pre><code>df.replace(0,np.nan).apply(lambda x :x.last_valid_index(),1)
Out[602]:
0 092017
dtype: object
#df['newcol'] = df.replace(0,np.nan).apply(lambda x :x.last_valid_index(),1)
</code></pre> | python|pandas | 5 |
363,194 | 51,952,231 | Keras: How to expand validation_split to generate a third set i.e. test set? | <p>I am using Keras with a TensorFlow backend. I am using the ImageDataGenerator with the validation_split argument to split my data into train set and validation set. As such, I use flow_from_directory with the subset set to "training" and "testing" like so:</p>
<pre><code>total_gen = ImageDataGenerator(validation_sp... | <p>This is not possible out of the box. You should be able to do it with some minor modifications to the <a href="https://github.com/keras-team/keras-preprocessing/blob/master/keras_preprocessing/image.py#L1411" rel="nofollow noreferrer">source code</a> of <code>ImageDataGenerator</code>:</p>
<pre><code>if subset is n... | python|tensorflow|keras | 2 |
363,195 | 51,805,336 | Deep learning vocabulary: images/second and step time? | <p>There's a table at the bottom of
<a href="https://www.tensorflow.org/performance/performance_guide#optimizing_for_cpu" rel="nofollow noreferrer">https://www.tensorflow.org/performance/performance_guide#optimizing_for_cpu</a> that talks about <em>images per second</em> and <em>step time</em>, in the context of perfo... | <p>global_step/sec means how many steps per second your tensorflow model is doing. A step is usually a minibatch. So the inverse of global_step/sec is your step time and batch_size * global_step/sec is your number of images per second.</p>
<p>Because these numbers are throughput numbers computed on the steady state of... | performance|tensorflow|deep-learning|benchmarking | 0 |
363,196 | 51,977,012 | Python Pandas - Groupby multiple columns, filter for certain value certain column, and fillna | <p>I have a large dataset with messy data. The data looks like this:</p>
<pre><code>df1 = pd.DataFrame({'Batch':[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
'Case':[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2],
'Live':['Yes', 'Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'Yes', 'Yes'... | <p>You do not need to <code>filter</code> , you can slice the Yes of live before <code>groupby</code> </p>
<pre><code>df1.Task=df1.loc[df1.Live=='Yes'].groupby(['Batch','Case']).Task.ffill()
df1
Out[620]:
Batch Case Live Task
0 1 1 Yes Download
1 1 1 Yes Download
2 1 1 No... | python|pandas | 1 |
363,197 | 51,630,204 | How to make tf.data.Dataset.from_generator yield batches with a custom generator | <p>I want to use the <code>tf.data</code> API. My expected workflow looks like the following: </p>
<ul>
<li><p>Input image is a 5D tensor with <code>(batch_size, width, height,
channels, frames)</code></p></li>
<li><p>First layer is a 3D convolution </p></li>
</ul>
<p>I use the <code>tf.data.from_generator</code> fu... | <p>The <code>Dataset</code> construction process in that example is ill-formed. It should be done in this order, as also established by the official guide on <a href="https://www.tensorflow.org/guide/datasets" rel="nofollow noreferrer">Importing Data</a>:</p>
<ol>
<li>A base dataset creation function or static method s... | python|tensorflow|tensorflow-datasets | 3 |
363,198 | 51,746,797 | Find that start date and end dates are available using python pandas | <p>I am having a dataframe like this </p>
<pre><code>year end id start
1949 1954.0 ABc 1949.0
1950 1954.0 ABc 1949.0
1951 1954.0 ABc 1949.0
1952 1954.0 ABc 1949.0
1953 1954.0 ABc 1949.0
1954 1954.0 ABc 1949.0
1950... | <p>This should work; see comments in code for clarification on what I am doing:</p>
<pre><code>import pandas as pd
from functools import reduce
# reading the dataframe from your sample
df = pd.read_clipboard()
df['start'] = df['start'].astype('int')
df['end'] = df['end'].astype('int')
# create a function that finds... | python|pandas | 0 |
363,199 | 51,945,430 | Python DataFrame How to split or extract date from a datetime stamp | <p>I want to extract the date from a datetime stamp to write in Print function for title purpose of figure. Following is my code: </p>
<pre><code>plt.title('%s day IV curves of sample Module'%(module_allData_df['Time'].loc[i].replace(hour=0,minute=0,second=0,microsecond=0)))
</code></pre>
<p>output is: </p>
<p><a hr... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.strftime.html" rel="nofollow noreferrer"><code>Timestamp.strftime</code></a>:</p>
<pre><code>val = module_allData_df['Time'].loc[i].strftime('%Y-%m-%d')
plt.title('{} day IV curves of sample Module'.format(val))
</code></pre>
<p>A... | python|python-3.x|pandas|datetime|matplotlib | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.