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 |
|---|---|---|---|---|---|---|
365,600 | 65,782,073 | Updating JIRA custom field with multi-line comments using Panda dataframe | <p>I am trying to update a JIRA custom field from a panda dataframe.</p>
<p>The attribute DATA_HISTORY contains the following values -</p>
<p><code>update_dict[data_history] = df[df.EID==employee_id].DATA_HISTORY.values[0]</code></p>
<p><strong>'01/18/2021: CRITICAL\r01/17/2021: HIGH'</strong></p>
<p><code>issue.update... | <p>Using Jira REST API FOR adding comment, in the content block add</p>
<pre><code>{
"type": "hardBreak"
}
</code></pre>
<p>to achieve this. This is as per Jira Atlassian Document Format (ADF) guidelines</p> | python|pandas|jira|jira-rest-api | 0 |
365,601 | 65,683,082 | ValueError: Shapes (None, 1) and (None, 90) are incompatible | <p>I want to build a <code>deep RNN</code> where my x_train and my y_train. When I execute the code below:</p>
<pre><code>print(X_train_fea.shape, y_train_fea.shape)
X_train_res = np.reshape(X_train_fea,(10510,10,1))
y_train_res = np.reshape(y_train_fea.to_numpy(),(-1,1))
print(X_train_res.shape, y_train_res.shape)
</c... | <p>Looks like <code>y_train_res</code> comprise of integer indices not one-hot vectors. If so you have to use <code>sparse_categorical_crossentropy</code>:</p>
<pre><code>model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
</code></pre>
<p>and change its shape to 1D:</p>
<pre><code>y_train_res = np.... | python-3.x|tensorflow|lstm | 0 |
365,602 | 65,903,070 | Instance Normalization Error while converting model from tensorflow to Coreml (4.0) | <p>I try to convert my model from Tensorflow to Coreml however I get below error. Isn't it possible to convert instance normalization layer to CoreML? Any workaround to overcome?</p>
<p>ValueError Traceback (most recent call last)
in ()
6
7 model = ct.convert(
----> 8 tf_keras_mod... | <p>I use keras-contrib instead and it works fine. Please see issue and its solution below. It is still open for tensorflow_addons.</p>
<p><a href="https://github.com/apple/coremltools/issues/1007" rel="nofollow noreferrer">https://github.com/apple/coremltools/issues/1007</a></p> | tensorflow|normalization|coreml|coremltools | 0 |
365,603 | 65,811,056 | Numpy bitwise xor on signed int | <p>I am reading in some binary data that is in offset binary format. The signed integers in <code>numpy</code> are in twos compliment so the values are incorrect. To fix the data I need to flip the most significant bit. However, I am getting some unexpected results from the bitwise xor and not entirely sure what is ... | <p>Your <code>mask = 0b10000000</code> is an unsigned integer representation:</p>
<pre><code>>>> mask
... 128
</code></pre>
<p>This would need 16 bits to represent as a signed integer, hence numpy casts all the ints to 16 bits to accommodate this operation. You are looking for the signed integer that has the b... | python|numpy | 1 |
365,604 | 65,876,228 | How was the ssd_mobilenet_v1 tflite model in TFHub trained? | <p>How do I find more info on how the <a href="https://tfhub.dev/tensorflow/lite-model/ssd_mobilenet_v1/1/default/1" rel="nofollow noreferrer">ssd_mobilenet_v1</a> tflite model on TFHub was trained?</p>
<p>Was it trained in such a way that made it easy to convert it to tflite by avoiding certain ops not supported by tf... | <p>I am not sure about about the exact origin of the model, but looks like it does have TFLite-compatible ops. From my experience, the best place to start for TFLite-compatible SSD models is with the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" rel="nof... | tensorflow|tensorflow-lite | 1 |
365,605 | 65,521,041 | How to Install Cuda 10.1 with Tensorflow V.2.4 RTX 2070 Super Ubuntu 18.04 | <p>I'm new and studying Machine Learning.
When I try install nvidia cuda following instruction <a href="https://www.tensorflow.org/install/gpu?hl=en" rel="nofollow noreferrer">https://www.tensorflow.org/install/gpu?hl=en</a>,
Installing failed.</p>
<p>To use Cuda in tensorflow 2.4, It requires Cuda v10.1 and when I try... | <p>If you're on Ubuntu 18.04, you can use <code>sudo apt install nvidia-cuda-toolkit</code>. The version of CUDA in that package (as of January 20, 2021) is 10.1.</p>
<p>Once you've run that you can confirm that it is indeed 10.1 with <code>nvcc --version</code>.</p> | tensorflow|gpu|ubuntu-18.04|nvidia | 0 |
365,606 | 65,595,039 | Python&Pandas How to get all the rows that belongs to each one of the 4 quartiles of the method "describe"? | <p>Good night!</p>
<p>I'm new in coding, my english isn't so good and it's my second post here, so please be patient with me =]</p>
<p>I have a huuuge csv file (more than 500k rows) with a huge amount of interest rates in the last column.</p>
<p><a href="https://i.stack.imgur.com/aGl8w.png" rel="nofollow noreferrer"><i... | <p>Is this what you are looking for:</p>
<pre><code># Quartile value
qtile_value = 0.95
# Make new dataframe of original, being a subset as it filters for all values lower than # quartile value
quart_1 = df[df['vr_tx_jrs']<=np.quantile(df['vr_tx_jrs'], qtile_value )]
</code></pre>
<p>Just repeat quart_1 for your o... | python|pandas|dataframe|numpy|analytics | 1 |
365,607 | 65,827,031 | Pytorch Global Pruning is not reducing the size of the model | <p>I am trying to Prune my Deep Learning model via Global Pruning. The original UnPruned model is about 77.5 MB. However after pruning, when I am saving the model, the size of the model is the same as the original. Can anyone help me with this issue?</p>
<p>Below is the Pruning code:-</p>
<pre><code>import torch.nn.uti... | <p>Prunning <strong>won't change the model size</strong> if applied like this.</p>
<p>If you have a tensor, say something like:</p>
<pre><code>[1., 2., 3., 4., 5., 6., 7., 8.]
</code></pre>
<p>And you prune <code>50%</code> of data, so for example this:</p>
<pre><code>[1., 2., 0., 4., 0., 6., 0., 0.]
</code></pre>
<p>Y... | deep-learning|computer-vision|pytorch|vision|pruning | 1 |
365,608 | 65,795,924 | How to subplot multiple categorical columns in a dataframe? | <p>So I can plot all my columns individually like so:</p>
<pre><code>df['cat1'].value_counts().plot.bar()
</code></pre>
<p>But I can't figure out how to plot all of my cateogical columns in a nice looking subplot structure so I'm not endlessly scrolling.</p>
<p>My thinking so far is perhaps looping through my columns a... | <p>You can create an array of subplots and pass along the plot command:</p>
<pre><code># assuming you have 12 columns:
fig,axes = plt.subplots(nrows=3, ncols=4, figsize=(12,8))
# use `select_dtypes` to filter instead of `describe`
for col, ax in zip(df.select_dtypes(include='O'), axes.ravel()):
df[col].value_count... | pandas|dataframe|matplotlib|seaborn | 1 |
365,609 | 65,874,859 | how to used if else with for loop in pandas data Frame with Column value | <p>I am having an csv (code.csv) file which contains some words/data available in rows. in columns 'A' and I want to count that words in a text file (data.txt) and want to print count in txt file (test.txt). with words which is at least came 1 time. if word is not available in excel don't print. but counter printing a... | <p>You could simply apply a for loop on column A for each word and search for it in the string as follows:</p>
<pre><code>import pandas as pd
df = pd.read_csv('df.csv')
df.columns = ['A']
df.dropna(subset = ["A"], inplace=True)
df['A'] = df['A'].astype('string')
with open('data.txt', 'r') as txtfile:
te... | python|pandas|dataframe|for-loop|if-statement | 0 |
365,610 | 65,672,557 | How to calculate between the rows in pandas Dataframe? | <p>I want to calculate what percentage of original value my new values are.
What I want to receive is new columns in my Pandas DataFrame.</p>
<p>My DataFrame looks like this:</p>
<pre><code> Feature Precision Accuracy Recall Specificity F1 score
0 original 0.949367 0.911765 0.9375 0.818182 0... | <p>Dividing by the first row with <code>div</code> and <code>iloc[0]</code>, adding suffix to column names with <code>add_suffix</code>, and then joining to the original DataFrame with <code>join</code>:</p>
<pre><code>df.join(
df.select_dtypes(float).div(
df.select_dtypes(float).iloc[0]).add_suffix(' %'))
... | python|pandas | 2 |
365,611 | 65,551,203 | Which input's shape for timeseries_dataset_from_array? | <p>I have a dataset with <code>n</code> columns, of which the firsts <code>n-1</code> are features, and the <code>n</code>th is the label.</p>
<p>After read <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/timeseries_dataset_from_array" rel="nofollow noreferrer">this</a> documentation, I have ... | <p>Yes, it is necessary to shift. You can see it in the code below, using the variable <code>seq_length</code> for indexing.</p>
<p>The input can be of any shape, as long as <code>data</code> and <code>targets</code> share the same first dimension.</p>
<p>The data format can be univariate:</p>
<pre><code>import tensorf... | python|tensorflow|keras|time-series|tensorflow2.0 | 1 |
365,612 | 65,867,400 | Obtaining just the last row when using beautiful soup | <p>I have the following code:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import pandas as pd
def Get_Top_List_BR(url):
response = requests.get(url)
page = response.text
soup = BeautifulSoup(page)
table = soup.find(id='table')
rows = [row for row in table.find_al... | <p>First, I'm not sure as to what Python version you are using but how you implement BeautifulSoup is incorrect, at least in my version. BeautifulSoup heavily recommends using a parser <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow noreferrer">here</a>. Your following... | python|pandas|web-scraping|beautifulsoup | 1 |
365,613 | 65,800,820 | New Column Based on Last Delimiter Split | <p>I am getting an index error while trying to use a lambdas function like below... I am trying to extract just the last 2-3 characters from the string based on a space as a delimiter. Why would this not work?</p>
<p>Error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\robert.carmody\OneDrive ... | <p>If you are looking for the last element of the list, then you would need to use <code>[-1]</code> instead of <code>[1]</code>. Furthermore, there's no need for apply + lambda, you can use <code>.str.split()</code>. Try with the following:</p>
<pre><code>report_demand['Industry'] = report_demand['Industry'].str.split... | python|pandas | 1 |
365,614 | 65,893,054 | importing from yfinance rounds data | <p>I have been hitting my head against a wall here for the last couple of hours, I'm not that familiar with python and I'm trying to import historical data from Yahoo finance.</p>
<p>I've got it set up to import the data I want, but ran into a problem with the actual data, when trying to add some technical indicators. ... | <p>I don't know why yfinance has the same high and low values, but if you set yfinance to 1 hour intervals, the high and low values will be different, so if you adjust the alpha side to 1 hour, you can handle it. If the specification requires 1 minute intervals, then this answer is useless.</p>
<pre><code>import dateti... | python|numpy|alpha-vantage|yfinance | 0 |
365,615 | 65,506,925 | Pivot Pandas Dataframe adding columns | <p>I have the following dataframe:</p>
<pre><code>date product ... cost quantity
2018-01-02 orange ... 7.5 2
2018-01-02 apples ... 10 5
2018-01-02 apples ... 12 4
2018-01-04 melon ... 6.5 10
2018-01-04 melon ... 5 4
2... | <p>Just modifying <code>user3483203</code>'s <a href="https://stackoverflow.com/a/52681150/6660373">answer</a></p>
<pre><code>x = (df.assign(flag=df.groupby(['date', 'product']).cost.cumcount())
.pivot_table(index=['date', 'product'], columns='flag', values='cost', aggfunc='first')
.add_prefix('cost_'))
y = (d... | python|pandas|pivot | 0 |
365,616 | 65,665,723 | Extract Datetime information from a string in a DataFrame column | <p>So I have the Edition Column which contains data in unevenly pattern, as some have ',' followed by the date and some have ',-' pattern.</p>
<pre><code>df.head()
17 Paperback,– 1 Nov 2016
18 Mass Market Paperback,– 1 Jan 1991
19 Paperback,– 2016
20 Hardcover,– 24 ... | <pre><code>obj = df['Edition']
obj.str.split('((?:\d+\s+\w+\s+)?\d{4}$)', expand=True)
</code></pre>
<p>or</p>
<pre><code>obj.str.split('[,–]+').str[0]
obj.str.split('[,–]+').str[-1] # date
</code></pre> | python-3.x|pandas|dataframe|machine-learning|feature-engineering | 3 |
365,617 | 65,877,365 | Python sklearn linear regression error: fit() missing 1 required positional argument: 'y'" | <p>I'm very new to Python and scikit-learn. I'm having difficulty working with the scikit-learn Boston data house prices data set. Please find my code below.</p>
<p>Thanks!</p>
<pre><code>import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import sklearn
bos = pd.DataFram... | <p>Your <code>lm = LinearRegression</code> is missing the parentheses, thus the Model Object constructor is not called. Furthermore, you are not correctly fitting the model you just created. The line <code>LinearRegression.fit</code> is not needed.</p>
<p>Try the following and see if it helps:</p>
<pre><code>import pan... | python|pandas|numpy|scikit-learn|linear-regression | 0 |
365,618 | 65,661,486 | Pandas read data row by row | <p>I have a csv file that looks like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>lon</th>
<th>lat</th>
<th>date1</th>
<th>date2</th>
<th>date3</th>
</tr>
</thead>
<tbody>
<tr>
<td>120.55</td>
<td>23.2</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1.66</td>
<td>2.3</td>
<td>4... | <p>You have two options. Option one using <code>stack</code>:</p>
<pre><code>df.set_index(['lon', 'lat'])
.stack()
.rename('date')
.reset_index(level=2, drop=True)
.reset_index()
lon lat date
0 120.55 23.2 1
1 120.55 23.2 2
2 120.55 23.2 3
3 120.66 23.3 4
4 120.66 23.3 ... | python|pandas|sqlite | 2 |
365,619 | 65,494,855 | Seed for reproducible results is not working (Tensorflow) | <p>I'm having a problem that concern the reproducibility of my results using Tensorflow (v1.15.3). I set all the seeds (os, random, numpy and tensorflow) but the results of a convolutional neural networks changes always between executions (even if similar).</p>
<p>I set my seeds in this way:</p>
<pre><code>seed_value =... | <p>I suggest, after</p>
<pre><code>weights = {
'conv1/conv2d': tf.get_variable('conv1/weights', shape=[3,3,512,1024], initializer=tf.contrib.layers.xavier_initializer()),
# and more ...
}
</code></pre>
<p>store the weight externally in a file, for example, then next time you run, do not go through that previous... | python|tensorflow|seed | 1 |
365,620 | 65,806,658 | Pandas rolling conditional sum on time and group | <br>
I got an apparently hard task to do, in Python/Pandas.
<p>I have a dataframe like this:</p>
<pre><code>| DATETIME | PRODUCT | AMOUNT |
</code></pre>
<p>I need to produce the last column, with the cumulative sum of the (let's say sold product) amounts in the last 5 minutes, for each product (I have more than two pr... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pd.DataFrame.groupby</code></a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>g... | python|pandas|time-series|rolling-computation|cumsum | 1 |
365,621 | 65,596,986 | How to define a function on numpy array that uses array indexes to lookup a dictionary? | <p>I have a large numpy matrix 'mat' of size (150,000 * 150,000). I'm trying to apply a function on each element of this numpy array. The function uses a dictionary whose key range from 0 to 149,999:</p>
<p>Step1:</p>
<p>Converting the 1-d array to a dictionary</p>
<pre><code>dict1 = dict(enumerate(arr)) # arr is a 1d ... | <p>I think there is no need to create dictionary from <code>1-d</code> array you can directly transform the <code>arr</code> by taking the outer product then you can divide the matrix by this transformed <code>arr</code> to get the final result:</p>
<pre><code>mat / (arr[:, None] * arr)
</code></pre>
<hr />
<pre><code... | python-3.x|pandas|numpy|vectorization | 0 |
365,622 | 65,678,363 | Mask of an image with a list of pixel values | <p>I want to create a mask of an image with the values in a list. For example I have an RGB image with dimension (2, 5):</p>
<pre><code>a = (np.random.rand(2, 5, 3) * 10).astype(int)
array([[[0, 5, 8],
[9, 0, 2],
[2, 2, 9],
[9, 2, 4],
[2, 5, 3]],
[[7, 5, 7],
[1, 9, 3],
... | <p>Try this solution using broadcasting.</p>
<pre class="lang-py prettyprint-override"><code>aa = a[:, :, None, :]
bb = b[None, None]
mask = (aa == bb).any(axis=2).all(axis=-1)
</code></pre>
<p>We get:</p>
<pre><code>In [57]: mask
Out[57]:
array([[ True, False, False, False, False],
[ True, False, True, False, ... | python|numpy|opencv|image-processing|matrix | 3 |
365,623 | 65,541,235 | Conditional mapping among columns of two data frames with Pandas Data frame | <p>I needed your advice regarding how to map columns between data-frames:</p>
<p><strong>I have put it in simple way so that it's easier for you to understand:</strong></p>
<p>df = dataframe</p>
<p><strong>EXAMPLE:</strong></p>
<pre><code>df1 = pd.DataFrame({
"X": [],
"Y": [],
... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>def first_non_empty(df, cols):
"""Return the first non-empty, non-null value among the specified columns per row"""
return df[cols].replace('', pd.NA).bfill(axis=1).iloc[:, 0]
col_x = first_non_empty(df2, ['A','C... | pandas|dataframe|conditional-statements | 1 |
365,624 | 65,529,663 | Implementation of Deep learning model in Keras | <p>I am trying to implement the neural network model in Keras but I am getting a dimensionality issue. As per the Model architecture, I should get 1 as the output dimension from the last(Fully connected) layer but I am getting 2D data as output.</p>
<p>I am trying to implement the figure-4 from the <a href="https://iee... | <p>You need return_sequences = False in your last LSTM layer so it only returns last hidden state. That way it only returns a vector. So 4 branches return 4 vectors which are concatenated into one.</p>
<p>More details: <a href="https://stackoverflow.com/questions/42755820/how-to-use-return-sequences-option-and-timedist... | machine-learning|keras|deep-learning|tensorflow2.0 | 1 |
365,625 | 65,776,409 | pandas merge dataframes where rows match and append value | <p>I have two data frames:</p>
<p>df1:</p>
<pre><code> Chr Pos qual
0 1 1234 2
1 2 5678 6
2 1 1111 4
3 5 0123 30
</code></pre>
<p>df2:</p>
<pre><code> Chr Pos
0 1 1234
1 5 0123
2 3 1111
3 1 01234
</code></pre>
<p>if the row in df2 matches the row in df1 then append qual ... | <p>If I understood correctly should be:</p>
<pre><code>import numpy as np
df3 = pd.merge(df1,df2,how='outer',on=['Chr','Pos'],indicator=True)
df3.loc[df3._merge != "both",'qual']= np.nan
df3.drop(columns='_merge',inplace=True)
df3
</code></pre> | python|pandas | 0 |
365,626 | 65,877,638 | What's the function of “keep_aspect_ratio_resizer {” in the config file of Tensorflow Object Detection API? | <p>I use the Tensorflow Object Detection API to create an AI for Faster-RCNN.
<a href="https://github.com/tensorflow/models.git" rel="nofollow noreferrer">GitHub:Tensorflow/models</a></p>
<p>What kind of resizing function does "keep_aspect_ratio_resizer {" in the config file have?</p>
<p>I prepared images of ... | <p>The definition of the different fields of the configuration files can be seen following this link: <a href="https://github.com/tensorflow/models/tree/master/research/object_detection/protos" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/research/object_detection/protos</a></p>
<p>The <em... | python|tensorflow|object-detection|object-detection-api | 2 |
365,627 | 65,857,308 | Cannot install Fastquant using pip on OSX | <p>Problem description
Can't install Fastquant</p>
<p>Environment</p>
<pre><code>platform (e.g. Linux, OSX, Windows): OSX
fastquant version (e.g. 0.1.3.17): latest version
installation method (e.g. pip, conda, source): pip
</code></pre>
<p>I'm getting this error message: <a href="https://gist.github.com/datomnurdin/931... | <p>Can you try updating your fastquant package? We've just fixed an issue with the new python 3.9</p>
<p><code>pip install fastquant --upgrade</code></p> | python|python-3.x|macos|numpy|pip | 0 |
365,628 | 65,722,752 | Neural Network accuracy is always 0 while training classification problem in Keras | <p>I am making a neural network for the titanic classification problem but my training accuracy is always 0. I checked other solutions but couldn't find a solution that works. The loss reduces but accuracy is 0.</p>
<pre><code>model= keras.Sequential(
[
layers.Dense(10,activation="relu",input_shape=(... | <p>First, you are incorrectly using <code>metrics=['accuracy']</code>. Second, this points to a much deeper bug which I think is unintentional. <a href="https://github.com/tensorflow/tensorflow/issues/46436" rel="nofollow noreferrer">I have raised an Issue</a> for this on tensorflow repo. Let's hope someone responds.</... | python|tensorflow|machine-learning|keras|neural-network | 1 |
365,629 | 65,609,285 | In Tensorflow, adding data augmentation layers to my keras model slows down training by over 10x | <p>I'm adding data augmentation to my tensorflow model like so:</p>
<pre><code>data_augmentation = keras.Sequential([
layers.experimental.preprocessing.RandomRotation(factor=0.4, fill_mode="wrap"),
layers.experimental.preprocessing.RandomTranslation(height_factor=0.2, width_factor=0.2, fill_mode="wra... | <p>There are two ways of adding data augmentation:
1- Inside the model, just like the way you did.
2- Outside the model, and before training, using tf.data.Dataset.map()</p>
<p>Maybe trying option2 could make your model training faster. Try it!
More details here: <a href="https://keras.io/guides/preprocessing_layers/" ... | tensorflow|keras|keras-layer|data-augmentation | 0 |
365,630 | 65,764,908 | How do I join dataframes in python where each dataframe has a column which represents different processes values at a specific time | <p>My title is a bit messy but hopefully the information below is specific enough.</p>
<p>I have a script that scrapes the name and price of items from a online store and stores them in a pandas dataframe with 2 columns, Name and Price. The script runs at regular time periods and exports the data to a csv.
Now I want t... | <p>Maybe you can partition the data and generate a pivot table to produce your desired outcome.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
"Item": ["Car", "Bike", "Car", "Bike", "Car", "Bike",],
"Price": ["... | python|pandas|dataframe|time-series | 0 |
365,631 | 65,693,305 | pandas key error only when using merge only in a function | <p>I have two data frames "base_level" and "raw_inventory" with the following columns:</p>
<p>"base_level" columns -> "a" , "b", "c" , "inventory_id"...</p>
<p>"raw_inventory" columns -> "1", "2", "3", &q... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>test = inv_level(left, right, left['user_id'], right['new_id'], 'left')
</code></pre> | python|pandas | 0 |
365,632 | 65,738,799 | RuntimeError: stack expects each tensor to be equal size, but got [205] at entry 0 and [229] at entry 1 | <p>I am a secondary level practitioner, and in my practice they sent me to program a neural network that classifies complaints, I need someone's help because it gives me the following error:</p>
<p>It is based on a youtube tutorial, only adapted to work with BETO and does not classify between positive and negative but ... | <p>@Andrey</p>
<pre><code># Iteración entrenamiento
def train_model(model, data_loader, loss_fn, optimizer, device, scheduler, n_examples):
model = model.train()
losses = []
correct_predictions = 0
for batch in data_loader:
input_ids = batch['input_ids'].to(device)
attention_... | tensorflow | 0 |
365,633 | 65,842,712 | Why does my Keras Custom Layer only gets called once? | <p>I have to work with tensorflow 1.15 and need a custom layer. A very simplistic layer can look like this:</p>
<pre><code>class Dummy(keras.layers.Layer):
def __init__(self, units=32, input_dim=32):
super(Dummy, self).__init__()
self.cnt = 1
def call(self, inputs):
self.cnt += 1
... | <p>Have to use <code>tf.Variable</code> and <code>assign_add</code> for initialization and adding</p>
<pre><code>class Dummy(keras.layers.Layer):
def __init__(self, units=32, input_dim=32):
super(Dummy, self).__init__()
self.cnt = tf.Variable(1, trainable=False)
def call(self, inputs):
... | python|tensorflow|keras|tensorflow1.15 | 0 |
365,634 | 65,619,603 | Scipy raise error, TypeError: unsupported operand type(s) for +: 'float' and 'dict' however the variables are float | <p>I'm trying to optimize one constrained, nonlinear model with scipy.</p>
<pre><code>import numpy as np; from scipy.optimize import minimize; import math
# initial guesses
n = 2
x0 = np.zeros(n)
T = 0.1
L = 0.1
def objective(T, L):
try:
return (350 / T) + (35 * ((312.5 * (T / 2)) + (11.69 * (math.sqrt(T... | <p>I ran your code to debug it. I noticed the following and made the changes accordingly:</p>
<ul>
<li>The function <code>constraint1(T, L)</code> did not return anything.</li>
<li>As <a href="https://stackoverflow.com/users/4354477/forcebru">@ForceBru</a> mentioned, using <code>args=cons</code> will pass the dictionar... | python|numpy|optimization|scipy|nonlinear-optimization | 1 |
365,635 | 21,088,052 | square root of sum of square of columns in multidimensional array | <p>I am using multidimensional list with numpy</p>
<p>I have a list.</p>
<pre><code>l = [[0 2 8] [0 2 7] [0 2 5] [2 4 5] [ 8 4 7]]
</code></pre>
<p>I need to find square root of sum of square of columns.</p>
<pre><code>0 2 8
0 2 7
0 2 5
2 4 5
8 4 7
</code></pre>
<p>output as,</p>
<pre><code>l = [sqrt((square(0) +... | <pre><code>>>> import numpy as np
>>> a = np.array([[0, 2, 8], [0, 2, 7], [0, 2, 5], [2, 4, 5], [ 8, 4, 7]])
>>> np.sqrt(np.sum(np.square(a), axis=0))
array([ 8.24621125, 6.63324958, 14.56021978])
</code></pre> | python|numpy | 12 |
365,636 | 21,381,106 | How to trim a series of string objects in python? | <p>is there any way to trim a series of string objects with out using for loop. I can do this element by element. I have a series <code>a</code></p>
<pre><code>print a
0 164
1 164
2 164
3 164
4 164
5 164
</code></pre>
<p>now I have to remove space at the start of each " 164"s.
<code>a.strip()... | <p>Use <code>str.strip</code> to remove the spaces:</p>
<pre><code>df = pd.DataFrame({'a': ['164', ' 164', ' 164']})
for item in df.a:
print (len(item))
3
4
7
In [11]:
df.a = df.a.str.strip(' ')
for item in df.a:
print (len(item))
3
3
3
</code></pre>
<p>To convert to ints do this:</p>
<pre><code>In [20]:... | python|pandas|strip | 4 |
365,637 | 21,138,492 | For Python, how to sort and lump elements in a fixed-sized list | <p>Sorry if this is a trivial question. If I have a list:</p>
<pre><code>inputlist = [(0,0), (_,_), (_,_), (0,0), (0,0), (_,_), (0,0)]
</code></pre>
<p>What is an efficient way to sort it so that all the non-zero elements get lumped to the left (in any order):</p>
<pre><code>sortlist = [(_,_), (_,_), (_,_), (0,0), (... | <p>Use a key that returns a lower for anything non-zero, like <code>-1</code> vs. <code>0</code>:</p>
<pre><code>sorted(inputlist, key=lambda t: -1 if t != (0, 0) else 0)
</code></pre>
<p>This can be simplified to:</p>
<pre><code>sorted(inputlist, key=lambda t: t == (0, 0))
</code></pre>
<p>since <code>False</code>... | python|list|sorting|numpy | 3 |
365,638 | 21,069,716 | Plot numpy array built from a .tiff image using pyqtplot | <p>I'm trying to plot a tiff image in pyqtgraph.</p>
<pre><code>import numpy as np
import gdal
import pyqtgraph as pg
from PyQt4 import QtCore
gd = gdal.Open('myImage.tif')
data = np.array(gd.GetRasterBand(1).ReadAsArray())
pg.plot(data, title="my picture")
if __name__ == '__main__':
import sys
if sys.flags.... | <p>I think you want <a href="http://www.pyqtgraph.org/documentation/images.html" rel="nofollow noreferrer">pyqtgraph.image</a>. For example, here's a modifed version of your script (I have PySide installed):</p>
<pre><code>import numpy as np
import pyqtgraph as pg
from PySide import QtCore
from scipy.ndimage import g... | python|numpy|pyqtgraph | 3 |
365,639 | 21,335,957 | Fast way to select n items (drawn from a Poisson distribution) for each element in array x | <p>I am having some trouble with solving a problem I encountered.</p>
<p>I have an array with prices:</p>
<pre><code>>>> x = np.random.randint(10, size=10)
array([6, 1, 7, 6, 9, 0, 8, 2, 1, 8])
</code></pre>
<p>And a (randomly) generated array of Poisson distributed arrivals:</p>
<pre><code>>>> ar... | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow">np.repeat</a>:</p>
<pre><code>In [43]: x = np.array([6, 1, 7, 6, 9, 0, 8, 2, 1, 8])
In [44]: arrivals = np.array([4, 0, 1, 1, 3, 2, 1, 3, 2, 1])
In [45]: np.repeat(x, arrivals)
Out[45]: array([6, 6, 6, 6, ... | python|arrays|algorithm|numpy | 6 |
365,640 | 21,207,990 | Display multiple output tables in IPython notebook using Pandas | <p>I now know that I can output multiple charts from IPython pandas by embedding them in one plot space which will appear in a single output cell in the notebook.</p>
<p>Can I do something similar with Pandas HTML Tables?</p>
<p>I am getting data from multiple tabs (about 15-20) on a spreadsheet and running them thou... | <p>This does it:</p>
<pre><code>area-tabs=list(map(str, range(1, 28))) # for all 27 tabs
#area_tabs=['1','2'] # for specific tabs
for area_tabs in area_tabs:
actdf,aname = get_data(area_tabs) #get_data gets the data and does a bunch or regression and table building
aname,actdf,merged2,mergederrs,montdist,ols_t... | pandas|ipython|ipython-notebook | 3 |
365,641 | 21,160,036 | Find Unique Values Across Data Frames without looping | <p>How do I find unique values across Data Frames without looping?</p>
<pre><code>df1 = pd.DataFrame(np.random.randint(0,105673,size=100).reshape(10,10))
df2 = pd.DataFrame(np.random.randint(0,206782,size=100).reshape(10,10))
df3 = pd.DataFrame(np.random.randint(0,435612,size=100).reshape(10,10))
</code></pre>
<p>To ... | <p>You can try to get the unique values in a dataframe <code>df</code> by converting its flattened values to a set <code>set(df.values.ravel())</code> (in the set data structure duplicate values will automatically be removed).</p> | python|pandas | 0 |
365,642 | 20,940,805 | Python particles simulator: out-of-core processing | <h1>Problem description</h1>
<p>In writing a Monte Carlo particle simulator (brownian motion and photon emission) in python/numpy. I need to save the simulation output (>>10GB) to a file and process the data in a second step. Compatibility with both Windows and Linux is important.</p>
<p>The number of particles (<cod... | <p>Dask.array can perform chunked operations like <code>max</code>, <code>cumsum</code>, etc. on an on-disk array like PyTables or h5py.</p>
<pre><code>import h5py
d = h5py.File('myfile.hdf5')['/data']
import dask.array as da
x = da.from_array(d, chunks=(1000, 1000))
</code></pre>
<p>X looks and feels like a numpy a... | numpy|pandas|pytables|h5py|blaze | 3 |
365,643 | 21,036,348 | Numpy, sorting based on column twice | <p>I have data that looks like this:</p>
<pre><code>[[ 361 2 2]
[ 259 4 3]
[ 361 6 5]
[ 259 8 5]
...
]
</code></pre>
<p>In the original data, the first column is a <code>person id</code>, the second column is a <code>test id</code>, while the third is <code>mark</code> (for example).</p>
<p>I want... | <p>It would be great if you could provide a minimum data set and an expected output, but from your description, if your person and test id's are consecutive integers starting at 0, and you have no repeated person-test pair, you can simply do:</p>
<pre><code>people, tests = np.max(data[:, :2], axis=0)
sorted_scores = n... | python|numpy | 0 |
365,644 | 2,641,701 | storing record arrays in object arrays | <p>I'd like to convert a list of record arrays -- dtype is (uint32, float32) -- into a numpy array of dtype <code>np.object</code>: </p>
<pre><code>X = np.array(instances, dtype = np.object)
</code></pre>
<p>where <code>instances</code> is a list of arrays with data type <code>np.dtype([('f0', '<u4'), ('f1', '<... | <p>Stéfan van der Walt (a numpy developer) <a href="http://numpy-discussion.10968.n7.nabble.com/Structured-array-inititialization-weirdness-td23335.html#a23337" rel="nofollow noreferrer">explains</a>:</p>
<blockquote>
<p>The ndarray constructor does its best
to guess what kind of data you are
feeding it, but som... | python|numpy | 2 |
365,645 | 3,157,374 | How do you 'remove' a numpy array from a list of numpy arrays? | <p>If I have a list of numpy arrays, then using remove method returns a value error.</p>
<p>For example:</p>
<pre><code>import numpy as np
l = [np.array([1,1,1]),np.array([2,2,2]),np.array([3,3,3])]
l.remove(np.array([2,2,2]))
</code></pre>
<p>Would give me </p>
<blockquote>
<p>ValueError: The truth value of an... | <p>The problem here is that when two numpy arrays are compared with ==, as in the remove() and index() methods, a numpy array of boolean values (the element by element comparisons) is returned which is interpretted as being ambiguous. A good way to compare two numpy arrays for equality is to use numpy's array_equal() f... | python|numpy | 15 |
365,646 | 2,417,794 | How to make the angles in a matplotlib polar plot go clockwise with 0° at the top? | <p>I am using matplotlib and numpy to make a polar plot. Here is some sample code:</p>
<pre><code>import numpy as N
import matplotlib.pyplot as P
angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0
arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5)
P.clf()
P.polar(angl... | <p>Updating this question, in Matplotlib 1.1, there are now two methods in <code>PolarAxes</code> for setting the theta direction (CW/CCW) and location for theta=0. </p>
<p>Check out
<a href="http://matplotlib.sourceforge.net/devel/add_new_projection.html#matplotlib.projections.polar.PolarAxes" rel="noreferrer">http... | python|numpy|matplotlib|plot | 33 |
365,647 | 63,361,688 | rolling statistics in numpy or pytroch | <p>I have a tensors data of sensors, each tensor is of shape (4,1500)
This is 1500 timepoints and for each time point I have 4 features.
I want to "smooth" the sequences with rolling average or other rolling statistics. The end goal is to try to improve an lstm autoencoder with rolling statistics instead of t... | <p>Since you're striding the output by the size of the window this is actually more akin to downsampling by averaging than to a computing rolling statistics. We can take advantage of the fact that there are no overlaps by simply reshaping the initial tensor.</p>
<hr />
<h3>Using <code>Tensor.reshape</code></h3>
<p>Assu... | python|pandas|numpy|pytorch | 2 |
365,648 | 63,658,141 | How to annotate pandas date-time format in Matplotlib like Plotly? | <p>How to add annotate text example <code>1st Lockdown, 2nd Lockdown</code> in Matplotlib like Plotly?</p>
<p><a href="https://i.stack.imgur.com/4WDsN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4WDsN.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/s8axf.p... | <p>Here is an example using <a href="https://matplotlib.org/3.3.1/api/_as_gen/matplotlib.axes.Axes.annotate.html" rel="nofollow noreferrer"><code>ax.annotate</code></a>, as another answer suggested:</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
dr = pd.date_range('02-01-2020', '07-01-2020', freq='... | python|pandas|matplotlib | 7 |
365,649 | 63,661,197 | Latent vector variance much larger in CoreML than PyTorch | <p>I have a PyTorch model that I've converted to CoreML. In PyTorch, the inferred latent vector's values range to a limit of around ±1.6, but the converted mlmodel varies as much as ±55.0. What might be causing this huge discrepancy? The conversion is pretty straightforward:</p>
<pre><code>encoder = Encoder_CNN(latent_... | <p>You probably are using different input normalization for PyTorch and Core ML. Your <code>img_in</code> consists of values between 0 and 1. I don't see the inference code for Core ML, but your input pixels are probably between 0 and 255 there. You can fix this by specifying image preprocessing settings when you conve... | pytorch|coreml | 1 |
365,650 | 63,601,854 | Pivot multiple combination - Dataframe - Python | <p>I have an dataframe with multiple combination with their respective rankings as shown below:</p>
<pre><code>+--------------+--------------+--------------+------+
| Combination1 | Combination2 | Combination3 | Rank |
+--------------+--------------+--------------+------+
| VAR1 : VAL11 | VAR2 : VAL21 | VAR3 : VAL31 | ... | <p>I tried separating the columns and values along with the rank, renamed them and then union-ed it.</p>
<pre><code>+-----------+-----------+-------+ +-----------+-----------+-------+
| Comb_Col1 | Comb_Val1 | Rank | | Comb_Col1 | Comb_Val1 | Rank |
+-----------+-----------+-------+ +-----------+-----------+... | python|python-3.x|pandas|pivot | 0 |
365,651 | 63,488,261 | Conditional replacement across data frames using Pandas | <p>I am rather new to Python and have a question about conditional replacement across data frames.</p>
<p>I have two data frames, A and B and I would like to update the dates in A with the dates in B whenever there are matching id (nid).</p>
<pre><code>import pandas as pd
import numpy as np
nid1 = (1, 3, 4, 8)
date1 =... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a>:</p>
<pre><code>print (dfb.set_index("nid").combine_first(dfa.set_index("nid")))
date info
nid ... | python|pandas|dataframe|replace|conditional-statements | 3 |
365,652 | 63,683,290 | pandas construct multi index for columns | <p>How can I construct a multi-index in pandas for an example dataframe of:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'day':['2020-01-01', '2020-01-02'], 'value_mean':[1,5], 'value_max':[40,100]})
</code></pre>
<p>Transform the existing:</p>
<pre><code> day value_mean value_max
0 2020-01-01 ... | <p>There is problem join no <code>Multiindex</code> with <code>MultiIndex columns</code>, only trick should be use empty strings for second level:</p>
<pre><code>df.columns = df.columns.str.split('_', expand=True)
df = df.rename(columns = lambda x: x if pd.notna(x) else '')
print (df)
day value
... | python|pandas|multi-index | 2 |
365,653 | 63,601,707 | Calculating the share of each code, by ID | <p>I have this data-frame:</p>
<pre><code>ID code X X_total
A 456 40 40
A 789 0 40
B 123 75 100
B 987 25 100
C 789 13 91
C 987 0 91
C 123 35 91
C 456 43 91
</code></pre>
<p>I want the calculate the <em>share</em> of each code (from <cod... | <p>Let us do <code>crosstab</code></p>
<pre><code>s = pd.crosstab(df.ID, df.code, df.X ,aggfunc='sum', normalize='index').add_prefix("share_")
Out[70]:
code 123 456 789 987
ID
A 0.000000 1.000000 0.000000 0.00
B 0.750000 0.000000 0.000000... | python|pandas|numpy | 4 |
365,654 | 63,482,695 | Task: I am trying to create a pandas dataframe from a list of dictionaries. Problem: This creates a dataframe for each dictionary item | <p>I am trying to create a dataframe from three lists which I have generated using webscraped data. However, when I try and turn these lists into dictionaries and then use them to build my pandas dataframe it outputs a dataframe for each dictionary item (row) rather than one dataframe including all of these items as ro... | <p>Firstly you should do <code>price_list=[]</code> and <code>bedroom_list=[]</code> and <code>bathroom_list=[]</code> before your <code>for</code> loop - otherwise they were 1-element long at most as it in every turn they would be reseted to <code>[]</code> then appended with single element. Secondly if you wish to ha... | python|pandas|dataframe|dictionary | 1 |
365,655 | 63,428,536 | How to add two dataframes | <p>Hi I am trying to append one dataframe to another</p>
<pre><code>Name roll_no House
John A_1 Red
Mark A_2 Green
Twain N_1 Yellow
Mark A_2 Red
</code></pre> | <p>You can concat both using <code>pd.concat</code> and then remove duplicates rows using <code>drop_duplicates</code></p>
<pre><code>pd.concat([df1,df2]).drop_duplicates()
Name ID House
0 John A_1 Red
1 Mark A_2 Red
2 Twain N_1 Yellow
1 Mark A_2 Green
</code></pre> | python|pandas|dataframe | 0 |
365,656 | 63,612,982 | Python pandas: Get first values of group | <p>I have a list of recorded diagnoses like this:</p>
<pre><code>df = pd.DataFrame({
"DiagnosisTime": ["2017-01-01 08:23:00", "2017-01-01 08:23:00", "2017-01-01 08:23:03", "2017-01-01 08:27:00", "2019-12-31 20:19:39", "2019-12-31 20:19:39"],
... | <p>You can add lambda function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.factorize.html" rel="nofollow nore... | python|pandas|pandas-groupby | 1 |
365,657 | 63,395,480 | Pandas scoring n.lowest value of each date into a new column | <p>I have been spending too long for this what should be easy but..</p>
<p>I have dataset:</p>
<pre><code> date score1 score2
0 1.8.2020 10 11
1 1.8.2020 15 10
2 1.8.2020 16 7
3 2.8.2020 8 7
4 2.8.2020 2 9
5 2.8.2020 6 8
6 3.8.202... | <p>This is an application of <code>rank</code>:</p>
<pre><code>rank = df.groupby('date')['score1'].rank(method='dense')-1
df['result1'] = rank.eq(1).astype(int)
</code></pre>
<p>Output:</p>
<pre><code> date score1 score2 result1
0 1.8.2020 10 11 0
1 1.8.2020 15 10 1
2 1... | python|pandas|dataframe|group-by | 1 |
365,658 | 63,509,939 | How to merge two dataframes with preserving the same order of one of them? | <p>I have two <strong>large</strong> dataframes and I want to merge them with the same order of the first one (dataframe).</p>
<p>for simplisity, I will create dummy data.</p>
<pre><code>import pandas as pd
data = {'name': pd.Series(['A','A','A','B',"C",'C','C']),
'text': pd.Series(['txt2','txt1','tx... | <p>try first <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html#pandas-dataframe-stack" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html#pandas-dataframe-merge" rel... | python|python-3.x|pandas|dataframe|merge | 1 |
365,659 | 63,517,650 | pandas convert integer to time | <p>I have time column in seconds like this</p>
<pre><code>100
100000
235900
</code></pre>
<p>I want to convert to time format, i.e.</p>
<pre><code>00:01
01:00
23:59
</code></pre>
<p>I have tried</p>
<pre><code>time = pd.to_datetime(temp['time'], format='%H%M%S').dt.time
</code></pre>
<p>but it throw</p>
<pre><code>Valu... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.zfill.html" rel="nofollow noreferrer"><code>Series.str.zfill</code></a> with convert integers to strings:</p>
<pre><code>time = pd.to_datetime(temp['time'].astype(str).str.zfill(6), format='%H%M%S').dt.time
print (time)
0 00:... | pandas|time | 1 |
365,660 | 63,553,871 | If-else statement with group_by in Pandas dataframe | <p>I’ve a pd df consists four columns: <code>ID</code>, <code>t</code>, <code>x1</code> and <code>x2</code>.</p>
<pre><code>import pandas as pd
dat = {'ID': [1,1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6,6],
't': [0,1,2,3,0,1,2,0,1,2,3,0,1,2,0,1,0,1,2],
'x1' : [3.5,3.5,3.5,3.5,2.01,2.01,2.01,3.9,3.9,3.9,3.9,2.2,2... | <p>We can combine <code>transform</code> <code>max</code> with <code>np.where</code></p>
<pre><code>df['y'] = np.where(df.t != df.groupby('ID').t.transform('max'), 1, df.x1-df.x2+1)
df
Out[221]:
ID t x1 x2 y
0 1 0 3.50 4 1.00
1 1 1 3.50 4 1.00
2 1 2 3.50 4 1.00
3 1 3 3.50 4 ... | python|pandas|if-statement | 3 |
365,661 | 63,374,659 | Pandas MultiIndex single level look up is much slower than alternative access patterns | <p>I have this isolated code snippet that should be self-explanatory:</p>
<pre><code>import string
import itertools
import numpy as np
import timeit
index = list(itertools.product(range(100_000), string.ascii_uppercase))
df = pd.DataFrame(index, columns=['i', 'p'])
df['n'] = np.random.randn(len(df))
df_2 = df.set_ind... | <p>I need to update my answer, since some additional timings show completely different results:</p>
<pre><code>import string
import itertools
import numpy as np
import timeit
index = list(itertools.product(range(100_000), string.ascii_uppercase))
df = pd.DataFrame(index, columns=['i', 'p'])
df['n'] = np.random.randn(... | python|pandas | 1 |
365,662 | 63,558,553 | How do we create a dictionary from a dataframe? | <p>dataframe is like below:</p>
<pre><code>ENV INVOCATION SSM_ID ANA_ID VALUE
env1 invo1 A oas 1.6
env1 invo1 A default 2.0
env1 invo1 B oas 0.8
env1 invo2 C oas 0.4
env2 invo1 A oas 3.1
env2 invo2 B default 0.6
<... | <p>Just <code>set_index</code> to all the columns except VALUE:</p>
<pre><code>print (df.set_index(list(df.columns[:-1]))["VALUE"].to_dict())
{('env1', 'invo1', 'A', 'oas'): 1.6,
('env1', 'invo1', 'A', 'default'): 2.0,
('env1', 'invo1', 'B', 'oas'): 0.8,
('env1', 'invo2', 'C', 'oas'): 0.4,
('env2', 'invo... | python|pandas|dataframe|dictionary | 2 |
365,663 | 63,560,484 | Bad predictions but good model accuracy using GCN | <p>I am using Graph Convolutional Network for Information Extraction from an Image with OCR Results. my Training set has a 45-50 set of data. At training the model I am able to get 85-90 percentage Accuracy with loss of 0.63094 But with that model when I try to predict it gives bad results. Please Help me to solve this... | <p>This may be because of a few things.</p>
<ol>
<li><strong>don't have enough data</strong></li>
<li><strong>your features aren't sufficient for reliable predictions</strong></li>
<li><strong>you are overfitting</strong></li>
</ol>
<p>But beyond what you've given I'm not sure. If you can provide some more information ... | python|tensorflow|machine-learning|deep-learning | 0 |
365,664 | 63,404,849 | Backpropagation in Tensorflow.js | <p>I am making an RNN for sentiment classification while using a many to one structure. In order to make my RNN be able to run within an HTML file.</p>
<p>To make the question short and simple:</p>
<blockquote>
<p>What is the Tensorflow.js equivalent of Tensorflow's (the python
version) <code>tf.train.GradientDescentOp... | <p>By gradient descent, you probably would prefer stochastic gradient descent (sampling random batches) and it would look like:</p>
<pre><code>tf.train.stg(learningRate).minimize(loss)
</code></pre>
<p>Read more here: <a href="https://js.tensorflow.org/api/latest/#tf.train.Optimizer.minimize" rel="nofollow noreferrer">... | javascript|python|tensorflow|artificial-intelligence|tensorflow.js | 1 |
365,665 | 63,391,771 | How to convert Array to pandas dataframe with datetime ohlcv efficiently, also divide column values by 100? | <p>Following is the json output I am getting from api</p>
<pre><code>
{
"data": [
[
1594373520,
43625,
43640,
43565,
43600,
59561
],
[
1594373820,
43600,
43650,
4... | <p>If you want to run it all together, I think you can also use the following method. Is this the best way to answer your question?</p>
<pre><code>df[['open','high','low','close']] = df[['open','high','low','close']].astype(float).div(100)
datetime open high low close volume
0 2020-07-10 15:02:00+05:3... | python|pandas | 1 |
365,666 | 63,388,566 | Analyzing learning curves for facial expression recognition | <p>I have a neural network set up in tensorflow (in python) that is operating on the fer2013 dataset (can be found on kaggle). My network architecture is this</p>
<pre><code>emotion_model = Sequential()
emotion_model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48,48,1)))
emotion_model.add(Conv2D(... | <p>You're quite correct: this is the very definition of over-fitting.</p>
<ul>
<li>Validation and training losses diverge</li>
<li>Validation and training accuracies diverge</li>
<li>Validation loss later increases</li>
</ul>
<p>In general, we also expect that the validation loss will reach a relative minimum at about ... | python|tensorflow|machine-learning|keras | 1 |
365,667 | 63,553,375 | Outputting all values of an large tensor in Tensorflow.js | <p>I have an <code>[174,48]</code> dimensional tensor and I would like to output <strong>all</strong> (without them being compressed in a manner similar to <a href="https://ibb.co/Jm2LW59" rel="nofollow noreferrer">this</a> values of it into the developer console present in the browser. How would I be able to achieve t... | <p><strong>Example</strong></p>
<pre class="lang-js prettyprint-override"><code>const tensor = tf.tensor([[1, 2], [3, 4]]);
console.log(JSON.stringify(tensor.arraySync())); // [[1,2],[3,4]]
</code></pre>
<p><a href="https://js.tensorflow.org/api/latest/#tf.Tensor.arraySync" rel="nofollow noreferrer"><code>tensor.array... | javascript|tensorflow|output|tensor|tensorflow.js | 1 |
365,668 | 63,436,424 | ValueError: Argument U has a size 4 which does not match 1, the number of arrow positions | <p><strong>Code:</strong></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
import math as mt
from numpy import linalg as LA
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets import fetch_olivetti_faces
%matplotlib inline
x=np.array([1,0]) # Original vector
the... | <p>So I am not sure if you are using an older or newer version of quiver which doesn't support the <code>t1[:,0]</code> notation, but what it is expecting is a single value for each <code>t1</code>'s. So it should be broken up into 2 lines and look like</p>
<pre><code>ax1.quiver(x_pos, y_pos, t1[0,0], t1[0,1], color=['... | python|numpy|matplotlib|jupyter-notebook | 0 |
365,669 | 63,326,772 | Does pandas df.to_sql() rollback? | <p>I am using pandas to write data to an SQL database via SQLalchemy.</p>
<p>I am loading data to a DataFrame and then using the to_sql() method.</p>
<p>Does the pandas to_sql() method rollback?
As in, if an error occurs during the insertion of the data to the database, can I roll it back to the original?</p> | <p>Using the context manager, rollback is taken care of automatically if there's an error:</p>
<pre><code>with engine.begin() as conn:
df1.to_sql(con=conn, ...)
df2.to_sql(con=conn, ...)
</code></pre>
<p>For more information, read this: <a href="https://capelastegui.wordpress.com/2018/05/21/commit-and-rollback-... | python-3.x|pandas|sqlalchemy | 2 |
365,670 | 63,653,124 | Extracting a nested tuples from list (Python) | <p>I have a list that has nested tuples.</p>
<pre><code>nested = [['53062423-690f-4923-8f65-db710c038566', [('12253996-b2f7-46c7-b49f-09ca87cac84f', 'AFC_PoCv1.0'), ('b17bd025-611f-4728-9396-e59388ee59f6', 'Customer Profitability Sample'), ('b4a5d199-2c6f-4f8d-9fcb-5e4971254f73', 'Jammers vs Floaty Pants')]], ['988f64e... | <p>We do <code>explode</code></p>
<pre><code>s = pd.DataFrame(nested,columns=['c1','c2']).explode('c2').reset_index(drop=True)
# if only need to split the tuple , you do not need to do the next steps
</code></pre>
<hr />
<p>Split the tuple into single columns</p>
<pre><code>s = s.join(pd.DataFrame(s['c2'].tolist()))
s... | python|pandas|list-comprehension | 2 |
365,671 | 63,320,721 | How to click on next button to scrape data from all pages using selenium python? | <p>I've just started learning data scraping. I am using Selenium for that and storing the data in excel sheet. The issue is I am not able to figure out that how do I make selenium to loop click on next pages and scrape their data too until the pages run out.
To understand it better below is my complete code.</p>
<pre><... | <p>Try a while loop, it would look something like this:</p>
<pre><code>links = driver.find_elements_by_css_selector('[rel=next]')
while len(links) > 0:
driver.get(links[0].get_attribute('href'))
# do stuff
links = driver.find_elements_by_css_selector('[rel=next]')
</code></pre> | python|python-3.x|pandas|selenium|web-scraping | 1 |
365,672 | 63,681,625 | Pandas UDF (PySpark) - Incorrect type Error | <p>I'm trying entity extraction with spaCy and Pandas UDF (PySpark) but I get an error.<br />
Using a UDF works without errors but is slow. What am I doing wrong?</p>
<p>Loading the model every time is to avoid load error - <code> Can't find model 'en_core_web_lg'. It doesn't seem to be a shortcut link, a Python packag... | <p>You need to see the input as <code>pd.Series</code> instead of single value</p>
<p>I was able to get it working by refactoring the code a bit. Notice <code>x.apply</code> call which is pandas specific and applies function to a <code>pd.Series</code>.</p>
<pre><code>def entities(x):
global nlp
import spacy
... | pandas|apache-spark|pyspark|user-defined-functions|spacy | 1 |
365,673 | 63,323,464 | how to get the correct embedding from Roberta transformers? | <p>I got confused by which hidden state should I use as the output of fine-tuned Roberta transformer models.</p>
<pre><code>from transformers import AutoConfig, AutoModelForMaskedLM, AutoTokenizer
config = AutoConfig.from_pretrained("roberta-base")
config.output_hidden_states = True
tok = AutoTokenizer.from_... | <p><code>output[-1][-1]</code> is correct if you are looking for the output of the last encoding layer. You can figure this out by looking at the <a href="https://github.com/huggingface/transformers/blob/6e8a38568eb874f31eb49c42285c3a634fca12e7/src/transformers/modeling_bert.py#L419" rel="nofollow noreferrer">source co... | bert-language-model|huggingface-transformers | 0 |
365,674 | 63,565,465 | New Dataframe Column Name based on old data - issue with code | <p>I had a piece of code that used to work to generate a new field based on server names truncated.
Essentially I wanted to only use the first 11 characters in a string.</p>
<p>This used to be</p>
<pre><code>df['newname'] = df.(ServerName).str[:11]
</code></pre>
<p>However the source of the servername (api) has been ch... | <p>You can just use this syntax for accessing columns:</p>
<pre><code>>>> df = pd.DataFrame(['aa', 'ab', 'ac', 'cd'], columns=['column:name'])
>>> df['newname'] = df['column:name'].str[:1]
>>> df
column:name newname
0 aa a
1 ab a
2 ac a
3 ... | python|pandas | 1 |
365,675 | 63,371,291 | Update for Dataframe python check if string in column is in another column | <p>I asked this question on <a href="https://stackoverflow.com/q/63370246/13666184">pandas dataframe-python check if string exists in another column ignoring upper/lower case</a> but i have a new update</p>
<p>I have a new row in a new dataframe :</p>
<pre><code>Id CompanyName ... | <p>try this,</p>
<pre><code>mask = (
df.apply(lambda x :
x['CompanyName'].split("-")[0].strip().lower() in x['EDescription'].lower(), axis=1)
)
df[mask]
</code></pre>
<hr />
<pre><code> Id ... EDescription
0 4 ... Project manager at finance company
</code></pre> | python|pandas|dataframe | 0 |
365,676 | 63,581,332 | How to calculate a simple function for different groups of the same dataframe? | <p>I have a dataframe (df)</p>
<pre><code> Index A B
0 1 1
1 2 2
2 3 3
</code></pre>
<p>and generated 20 resample data from this original data set all combined in one big data frame.</p>
<p>For instance:</p>
<pre><code> Resample Nr. Index A B
... | <p>You can use df.apply() function</p>
<pre><code>def sum_func(df): # defined funtion
return (df['A']+ df['B']/df['A'])
df = pd.DataFrame({'A':[1,2,3], 'B':[1,2,3]} ) # dataframe
# new column
df['C'] = df.apply(sum_func, axis=1) # function applied on dataframe
#Output
A B C
0 1 1 2.0
1 2 ... | python|pandas|numpy | 0 |
365,677 | 63,446,766 | How to print all the columns in single line from dataframe on Jenkins console? | <pre><code> I have created a data frame which contains lot of columns:
for eg.
col1 col2 col3 col4 col4 col5 col6 col7
and each row contains plenty of data in it.
I tried this:
</code></pre>
<p>pd.set_option('expand_frame_repr', False)</p>
<p>pd.set_option('display.max_rows', None)</p>
<p... | <p>you could use to_string</p>
<pre><code>print(data_frame[row:row].to_string())
</code></pre> | python|pandas|dataframe | 0 |
365,678 | 63,578,840 | Can anyone suggest better ASSERT method to compare two columns of a single dataframe in pytest? | <p>I am using <strong>pytest</strong> for comparing two columns of a dataframe
by using below <code>assert</code> method</p>
<pre><code>def test_compare():
np.testing.assert_almost_equal(v['col1'].values, v['col2'].values, decimal=4,verbose=True)
</code></pre>
<p>but the issue with this <code>assert_almost_equal()... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.isclose.html" rel="nofollow noreferrer"><code>np.isclose</code></a> for these situations, where you can control the precision if you wish</p>
<pre class="lang-py prettyprint-override"><code>assert np.all(np.isclose(v['col1'].values, v['col2'... | python|pandas|numpy|testing|pytest | 0 |
365,679 | 63,648,506 | numpy select multiple ranges from a 1d array | <p>Let's say I have a 1D array of values:</p>
<pre><code>T = np.array([1.3, 8.9, 1.4, 3.2, 4.4, 7.0, 2.0, 6.9]
</code></pre>
<p>and I have a list of start indices:</p>
<pre><code>I = np.array([5, 2, 4, 1])
</code></pre>
<p>For each start index, I would like to grab <code>m</code> consecutive values from <code>T</code> ... | <p>Here's an answer that does not require installing additional dependencies:</p>
<pre><code>def rolling_window(a, window):
a = np.asarray(a)
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=s... | python|arrays|numpy|indexing | 0 |
365,680 | 63,588,328 | Minimum absolute difference between elements in two numpy arrays | <p>Consider two 1d numpy arrays.</p>
<pre><code>import numpy as np
X = np.array([-43, 21, 4, 6, -1, 22, 8])
Y = np.array([13, 5, -12, 0])
</code></pre>
<p>I want to find the value(s) from <code>X</code> that have the <strong>minimum absolute difference</strong> with the value(s) from <code>Y</code>. In the example sh... | <p>You can calculate the absolute distance array and then find the minimum in that array. This method works for different <code>X</code> and <code>Y</code> lengths. If they are multi-dimensional, simply flatten them first (using <code>X.flatten()</code>, ...) and apply this solution to the flattened arrays:</p>
<p>If y... | python|arrays|numpy | 1 |
365,681 | 63,518,432 | Memory leak issue in tensorflow | <p>I have a memory leak with TensorFlow 1.14. I referred to various GitHub issues and <a href="https://stackoverflow.com/questions/44327803/memory-leak-with-tensorflow">Memory leak with TensorFlow</a> to address my issue, and I followed the advice of the answer, that seemed to have solved the problem. However it does n... | <p>I ran into similar issue when I tried to use pre-trained embedding model to generate embedding as input feature set. While using universal-sentence-encoder-4, memory used for generate embedding is not released. Neiether <code>tf.keras.backend.clear_session()</code> nor <code>gc.collect()</code> helped.</p>
<p>I ende... | python|tensorflow|keras|memory-leaks | 0 |
365,682 | 63,320,225 | AttributeError: 'list' object has no attribute 'rank' When converting Keras Model To CoreML | <p>I am trying to convert my Keras model that contains GRU layers to generate Shakespeares text to a coreml model, although when I try to convert it, I get the error "AttributeError: 'list' object has no attribute 'rank'". I followed the instructions on <a href="https://coremltools.readme.io/docs/tensorflow-2... | <p>Looks like the error is because of the recurrent_dropout parameter. Removing this parameter solves the error.</p>
<p>Also note that I have added batch_size parameter to the first GRU layer. This is necessary because CoreML inputs should be either rank 3 (Seq,B,C) or rank 5 (Seq,B,C,H,W) for RNNs.</p>
<p>This is the ... | python|tensorflow|keras|coreml|coremltools | 1 |
365,683 | 63,597,467 | How can I correct my code to create the file to save weights in python? | <p>I want to create a .h5 file to store my weights into it. I will use these weights in validation and testing.
This is my code. I don't understand, is my path incorrect or there is something else.</p>
<pre><code>import numpy as np
import h5py
hf = h5py.File(r"E:\weights.h5", 'w')
</code></pre>
<p>I am not g... | <p>It seems like you're passing the arguments wrong. I don't have experience with h5py, however according to the docs, the line should look like this:</p>
<pre><code>hf = h5py.File("E:\weights.h5", 'a')
</code></pre>
<p>The first argument passed is the file itself, whereas the second one is the mode you'd lik... | python|numpy|h5py | 0 |
365,684 | 63,494,925 | Adding a column to pandas dataframe conditionally | <p>I am working on a personal project collecting the data on Covid-19 cases. The data set only shows the total number of Covid-19 cases per state cumulatively. I would like to add a column that contains the new cases added that day. This is what I have so far:</p>
<pre><code>import pandas as pd
from datetime import dat... | <p>Because you defined <code>total_cases</code> as a concatenation (via append) of <code>yesterday_cases</code> and <code>day_before_yesterday_cases</code>, its number of rows is equal to the sum of the other two dataframes. It looks like <code>yesterday_cases</code> and <code>day_before_yesterday_cases</code> both ha... | python|pandas | 1 |
365,685 | 63,585,711 | Resampling a timeseries pandas with forward data | <p>My 30min df is like below:</p>
<pre><code> open high low close volume
t
2020-08-24 09:30:00 514.7900 515.1400 502.240 507.3700 12123388
2020-08-24 10:00:00 507.3200 513.9800 500.000 502.8899 6652496
2020-08-24 10:30:00 502.8190 503.7700 495.745 496.4879 59254... | <p>You should use parameter <code>offset</code> in method <code>pd.resample</code> instead of <code>loffset</code>:</p>
<pre><code>df2 = df.resample('1H', offset='30Min').agg({'open': 'first',
'high': 'max',
'low': 'min',
... | python|pandas|time-series | 1 |
365,686 | 63,552,761 | Append the count of the occurrence of the word in python Dataframe | <p>My original data</p>
<p><a href="https://i.stack.imgur.com/uu2B0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uu2B0.png" alt="" /></a></p>
<p>I want to convert the text data into a dataframe which will contain the 500 words like the below picture in which each sentence will contain the occurren... | <pre><code>from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twenty_train.data)
</code></pre>
<p><a href="https://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html" rel="nofollow noreferrer">https://scikit-lea... | python|pandas|dataframe|nlp | 0 |
365,687 | 63,345,335 | NumPy - Random Seed not working when sample size changes? | <p>Can anyone help me understand why the following code will not keep random_list_2 the same when I change the sample size, say from 3000 to 5000?</p>
<pre><code>import numpy as np
np.random.seed(2)
sample_size = 3000
random_list_1 = np.random.randint(low = 1, high = 3, size = sample_size).tolist()
random_list_2 = np.... | <p>The seed is only the starting value for the RNG (Random Number Generator). Each random number you generate updates the seed. When you specify a starting seed, then you get a deterministic, reproducible sequence of seed values.</p>
<p>When you change the sample size, you change the quantity of updates in the <code>... | python|numpy|random|random-seed | 0 |
365,688 | 63,659,659 | how do you create subarray from 1st column of a 2d array in numpy | <p>Using numpy, how is it possible to take the array</p>
<p><code>np.array([[1,2,3],[4,5,6],[7,8,9]])</code></p>
<p>and get out the arrays</p>
<p><code>[1,4,7] and [[2,3],[5,6],[8,9]]</code></p> | <p>You can use indexing as such :</p>
<pre><code>In [9]: a = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [10]: a[:,0]
Out[10]: array([1, 4, 7])
In [11]: a[:,1:]
Out[11]:
array([[2, 3],
[5, 6],
[8, 9]])
</code></pre> | python|python-3.x|numpy | 1 |
365,689 | 63,619,435 | How to rotate a Torch Tensor by a random number of degrees | <p>as part of training a CNN, I am working with an array <code>inputs</code> that contain <code><class 'torch.Tensor'></code> objects. I want to rotate an individual <code><class 'torch.Tensor'></code> object by some random number of degrees <code>x</code>, as shown here:</p>
<pre><code>def rotate(inputs, x... | <p>To transform an <code>torch.tensor</code> you can use <code>scipy.ndimage.rotate</code> function (read <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.rotate.html" rel="nofollow noreferrer">here</a>),that rotates a <code>torch.tensor</code> but also it converts it to <code>numpy.ndarray</... | python|rotation|pytorch | 1 |
365,690 | 63,412,782 | Pandas DataFrame Filling missing values in a column | <p>I have a large DataFrame with the following columns:</p>
<pre><code>import pandas as pd
x = pd.read_csv('age_year.csv')
x.head()
ID Year age
22445 1991
29925 1991
76165 1991
223725 1991 16.0
280165 1991
</code></pre>
<p>The <code>Year</code> column has values ranging from <code>199... | <p>try doing:</p>
<pre><code>def get_age(s):
present = s.age.notna().idxmax()
diff = s.loc[[present]].eval('age - Year').iat[0]
s['age'] = diff + s.Year
return s
df.groupby(['ID']).apply(get_age)
</code></pre> | python|pandas|dataframe|missing-data | 4 |
365,691 | 63,515,366 | Value to Assign to Missing Values in uint Numpy Array | <p>A numpy array <code>z</code> is constructed from 2 Python lists <code>x</code> and <code>y</code> where values of <code>y</code> can be <code>0</code> and values of <code>x</code> are not continuously incrementing (i.e. values can be skipped).</p>
<p>Since <code>y</code> values can also be <code>0</code>, it will be... | <h1>Solution</h1>
<p>You could typically assign <code>np.nan</code> or any other value for the non-existing indices in <code>x</code>.</p>
<p>Also, no need for the <em>for loop</em>. You can directly assign all values of <code>y</code> in one line, as I showed here.</p>
<p>However, since you are typecasting to <em>uint... | python|python-3.x|numpy|missing-data|numpy-ndarray | 2 |
365,692 | 63,349,832 | pytorch code sudden fails on colab with NVIDIA driver on your system is too old | <p>I had some code which worked on colab (gpu runtime) just a short while ago. Suddenly I am getting</p>
<p>The NVIDIA driver on your system is too old (found version 10010).</p>
<p>nvcc shows
Cuda compilation tools, release 10.1, V10.1.243</p>
<p>I tried torch versions 1.5.1, then 1.13.0. Both keep getting this error.... | <p>The light-the-torch package is designed to solve exactly this type of issue. Try this:</p>
<pre><code>!pip install light-the-torch
!ltt install torch torchvision
</code></pre> | pytorch|google-colaboratory | 8 |
365,693 | 63,531,097 | Group dataframe by column, then get the top 3 .count() values for another column? | <p>I have a dataframe which I named parking which has multiple columns, in this case Registration State, Violation Code, and Summons Number.</p>
<p>For each Registration State, I want the 3 Violation Codes which the highest row count. The best I've been able to get is:</p>
<p>parking_state_group = parking.groupby(['Reg... | <p>Lets try</p>
<pre><code>df[['Registration State', 'Violation Code', 'Summons Number']].groupby('Registration State')['Summons Number'].nlargest(3).reset_index().rename(columns={'level_1':'Violation Code'})
</code></pre> | python|python-3.x|pandas|pandas-groupby | 0 |
365,694 | 63,418,873 | In decorated tf function, I get error: 'Tensor' object has no attribute 'numpy' | <p>I've looked all over but can't find anyone who's previous answers help.</p>
<p>I have a tensorflow model with an @tf.function in it that does the training (tf version 2.3.0). Within the train_step call, I need to pass the data from a tensor on to a numpy function that performs a cwt transform on it. There is (afaik)... | <p>As you have mentioned, as per <code>tf.function</code> rules you can not use <code>.numpy()</code> functions inside <code>tf.fucntion</code>.<br />
There is still some workaround you can do to convert <strong>Tensor to a NumPy array</strong> when graph mode is enabled using <code>eval()</code>.</p>
<p>Below is the m... | python|numpy|tensorflow|tensor | 1 |
365,695 | 63,720,562 | Pandas split each row by delimiter into two columns (5GB CSV) | <p>Relatively new and trying to split some data with python from a CSV file.
My data is structured as follows:</p>
<pre><code>Time| Signature
--------------------
0 | Class1#Method1
1 | Class4#Method5
2 | Class5# <--note that Class 5 has no method
</code></pre>
<p>What I try to accomplish is to manipulate the ... | <p>You can probably use something like <code>df[['Class','Method']] = df['Signature'].str.split('#',expand=True)</code></p>
<p>(from <a href="https://stackoverflow.com/questions/37333299/splitting-a-column-by-delimiter-pandas-python">splitting a column by delimiter pandas python</a>)</p> | python|python-3.x|pandas | 1 |
365,696 | 63,455,207 | Iterating over sub-folders and converting file format from txt to csv | <p>For a current project, I am planning to run through a number of sub-folders, each of them containing the files <code>num.txt</code> and <code>sub.txt</code> (but all having a different content).</p>
<p>I have already attempted to set up the loops through <code>for subdir, dirs, files in os.walk(rootdir):</code> with... | <p>You keep reading and writing the same two files. All you need to do is to complete the path you hand to <code>pd.read_csv</code>.</p>
<pre class="lang-py prettyprint-override"><code>for subdir, dirs, files in os.walk(rootdir):
read_file1 = pd.read_csv(os.path.join(subdir, "num.txt"),delimiter="\t... | python|pandas|loops | 1 |
365,697 | 63,406,167 | Pandas transform method performing slow | <p>I have a canonical Pandas <code>transform</code> example in which performance seems inexplicably slow. I have read the <a href="https://stackoverflow.com/questions/54432583/when-should-i-ever-want-to-use-pandas-apply-in-my-code">Q&A on the <code>apply</code> method</a>, which is related but, in my humble opinion... | <p>This answer is due to the insightful comment from @sammywemmy, who deserves all credit and no blame for any inaccuracy here. Because a similar usage of <code>transform</code> is illustrated in the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#transformation" rel="nofollow noreferrer">... | python|pandas|performance|transform | 2 |
365,698 | 63,505,224 | Reading a particular row in csv file with Python | <p>How to read string row in python?</p>
<p>I got a football csv file.</p>
<p><a href="https://www.football-data.co.uk/mmz4281/1920/F1.csv" rel="nofollow noreferrer">https://www.football-data.co.uk/mmz4281/1920/F1.csv</a>
I would like to retrieve all the lines where there is the PS Germain.</p>
<pre><code>import pandas... | <p>You need to select rows from your Pandas DataFrame.
You can use the following logic to select rows from Pandas DataFrame based on specific conditions:</p>
<p><em>df.loc[df['column name'] condition]</em></p>
<p>In pratice that means:</p>
<pre><code>result = df.loc[df['HomeTeam'] == 'PS Germain']
</code></pre>
<p>You'... | python|pandas|numpy | 2 |
365,699 | 63,683,496 | How to trigger a particular version of lambda from s3 events | <p>I am using lambda as an ETL tool to process raw files coming in the s3 bucket.</p>
<p>As time will pass, functionality of lambda function will grow.</p>
<p>Each month, I will change lambda function. so, I want to publish version 1,2,3</p>
<p>How do I make the s3 bucket trigger particular version of lambda for the fi... | <p>From <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html" rel="nofollow noreferrer">AWS Lambda function aliases - Documentation</a>:</p>
<blockquote>
<p>When you use a resource-based policy to give a service, resource, or account access to your function, the scope of that permission depe... | python-3.x|pandas|amazon-web-services|amazon-s3|aws-lambda | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.