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 |
|---|---|---|---|---|---|---|
6,700 | 72,869,211 | Mapping set in dataframe column to another dataframe / dict | <p>i have a newbie question - what I want to do is concat 2 columns holding some names separated with comma, create set (to drop duplicates). Then I would have for each dataframe row a set of names and for each of these names I want to look up some dict / df called 'countries'.</p>
<pre><code>countries = pd.DataFrame(
... | <p>Try this:</p>
<pre><code>import pandas as pd
countries = pd.DataFrame(
[["LOW", ["A", "D"]],
["MEDIUM", ["B", "E"]],
["HIGH", ["C", "F"]],], columns=['Risk_level', 'Country_code'])
my_df = pd.DataFrame([['A', 'B,... | python|pandas|dataframe | 0 |
6,701 | 10,346,336 | List of lists into numpy array | <p>How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.</p> | <p>If your list of lists contains lists with varying number of elements then the answer of Ignacio Vazquez-Abrams will not work. Instead there are at least 3 options:</p>
<p>1) Make an array of arrays:</p>
<pre><code>x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
type(y)
>>><type 'nump... | python|list|numpy | 271 |
6,702 | 3,692,401 | creating a masked array from text fields | <p>The <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html" rel="nofollow noreferrer">numpy documentation</a> shows an example of masking existing values with <code>ma.masked</code> a posteriori (after array creation), or creating a masked array from an list of what seem to be valid data types (... | <p>The way you're doing it is fine. (though you could definitely make it a bit more readable by avoiding building the temporary "<code>triple</code>" dict, just to expand it a step later, i.m.o.)</p>
<p>The built-in way is to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="... | python|numpy|scipy | 1 |
6,703 | 70,733,352 | Python: Pandas dataframe and for loop - seperate row variable outside of loop body | <p>I have some table data (based on some pandas dataframe) in following form:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Index</th>
<th style="text-align: center;">Name</th>
<th style="text-align: center;">Region 1</th>
<th style="text-align: center;">...</th>... | <p>First of all, when using pandas, it is better to avoid for-loops as much as we can. It is faster to use pandas methods and there are plenty for everything you can do with a for loop.</p>
<p>For your case, you can define what you want to do in a function and pass it to the <code>apply()</code> method of pandas data f... | python|pandas|dataframe|for-loop | 1 |
6,704 | 70,390,824 | Create a new column based on a condition | <p>I have a dataframe df, need to create a new column, which is a product of <code>price</code> with <code>metric</code>(int calculated before).</p>
<pre><code>df['cost'] = df['price'] * metric if (df['status'] == 'online')
df['cost'] = 0 if df['status'] == 'offline'
</code></pre> | <p>We can leverage the point that <code>True</code> is 1 and <code>False</code> is 0 when used in multiplication.</p>
<pre><code>3 * True -> 3
3 * False -> 0
</code></pre>
<p>We have to check if values are equal to <code>online</code> in the <code>status</code> column.</p>
<pre><code>df['cost'] = df['price'] * d... | python|pandas|dataframe | 5 |
6,705 | 70,515,648 | Reading and saving 12bit Raw bayer image using OpenCV / Python | <p>I'm trying to read and save a 12bit Raw file using Python and openCV. The code I'm using saves an image but the saved image is garbled / distorted.</p>
<p>The image is from a FLIR Oryx Camera 23MP (5320x4600) 12Bit with BayerRG12P pixelformat, which should be RG GB bayer pattern.</p>
<pre><code>import cv2
import num... | <p>We may reuse my answer from the following <a href="https://stackoverflow.com/questions/68039594/find-bayer-pattern-format-from-a-byte-file">post</a>.</p>
<p>OpenCV doesn't support DPX 10bit image format.<br />
You may use Tiff format or 16 bits PNG, but you may need to scale the pixels by 16 (placing the 12 bits in ... | python|numpy|opencv | 3 |
6,706 | 42,725,474 | Numpy vectorize multidimensional function (or, building feature planes for a neural network) | <p>Say we have N color (RGB) images of size 100x100 stored in A[N][100][100][3].
So: </p>
<pre><code>Channel 0 = R
Channel 1 = G
Channel 2 = B
</code></pre>
<p>What is the most efficient way of building some other channels using numpy? For example, let's define:</p>
<pre><code>Channel 3 = R + G * 0.5
Channel 4 = If ... | <p>There are comparatively straight-forward ways, for example:</p>
<pre><code>rgb = np.random.random((1,2,2,3))
r,g,b = np.transpose(rgb, (3,0,1,2))
np.r_["-1, 4, 0", rgb, r+g*0.5, b>128, r==100, (r+g)>b]
# array([[[[ 0.64715017, 0.45204962, 0.28497451, 0.87317498, 0. , 0. , 1. ],
# ... | python|numpy|multidimensional-array|computer-vision | 0 |
6,707 | 42,678,439 | ImportError: libnvidia-fatbinaryloader.so.375.39: cannot open shared object file: No such file or directory | <p>I'm using Ubuntu 16.04, Cuda 8.0 and cudann-v5.1. I uninstalled Tensorflow-CPU version and reinstalled tensorflow-GPU enabled. Followed the instructions given here: <a href="https://alliseesolutions.wordpress.com/2016/09/08/install-gpu-tensorflow-from-sources-w-ubuntu-16-04-and-cuda-8-0-rc/" rel="noreferrer">https:/... | <p>I encountered this issue as well, there were two issues that needed to be resolved.</p>
<ol>
<li><p>I added <code>/usr/lib/nvidia-375</code> to my <code>LD_LIBRARY_PATH</code> environment variable. You can verify that the file <code>libnvidia-fatbinaryloader.so.375.39</code> lives in that directory. If not, find wh... | python-2.7|tensorflow | 14 |
6,708 | 25,244,582 | Python pandas groupby with cumsum and percentage | <p>Given the following dataframe df:</p>
<pre><code> app platform uuid minutes
0 1 0 a696ccf9-22cb-428b-adee-95c9a97a4581 67
1 2 0 8e17a2eb-f0ee-49ae-b8c2-c9f9926aa56d 1
2 2 1 40AD6CD1-4A7B-48DD-8815-1829C093A95C 13
3 ... | <p>It's not clear you came up with 0.26, 0.36 in your desired output - but assuming those are just dummy numbers, to get a running % of total for each group, you could do this:</p>
<pre><code>y['cumsum'] = y.groupby(level=[0,1]).cumsum()
y['running_pct'] = y.groupby(level=[0,1])['cumsum'].transform(lambda x: x / x.ilo... | python|pandas|grouping|percentage | 3 |
6,709 | 39,371,467 | numpy.loadtxt returns string repr of bytestring instead of string | <p>I'm having trouble reading a data file containing mixed strings and floats with numpy.loadtxt in Python 3. Python 2 works fine, but I want my code to work in Py3.</p>
<p>A simplified example:</p>
<pre><code>import numpy as n
strings = ['str1', 'str2']
parsed = n.loadtxt(strings, dtype='str')
print('Result:', pars... | <p><code>loadtxt</code> has passed your input string through a <code>asbytes</code> function before parsing (it normally reads files as bytestrings). But how it converts those to unicode does look buggy.</p>
<p><code>genfromtxt</code> appears to handle this better</p>
<pre><code>In [241]: np.genfromtxt([b'str1', b's... | python-3.x|numpy | 2 |
6,710 | 39,378,510 | Iterating across multiple columns in Pandas DF and slicing dynamically | <p><strong>TLDR:</strong> How to iterate across all options of multiple columns in a pandas dataframe without specifying the columns or their values explicitly?</p>
<p><strong>Long Version:</strong> I have a pandas dataframe that looks like this, only it has a lot more features or drug dose combinations than are liste... | <p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> to generate all possible dosage combinations, and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow"><code>DataFrame.query... | python|pandas|machine-learning|scikit-learn|grid-search | 2 |
6,711 | 38,970,028 | Pandas count occurrence within column on condition being satisfied | <p>I am trying to do count by grouping. see below input and output.</p>
<p>input:</p>
<pre><code>df = pd.DataFrame()
df['col1'] = ['a','a','a','a','b','b','b']
df['col2'] = [4,4,5,5,6,7,8]
df['col3'] = [1,1,1,1,1,1,1]
</code></pre>
<p>output:</p>
<pre><code> col4
0 2
1 2
2 2
3 2
4 1
5 1
6... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a> <code>len</code> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a>:</p>
... | pandas|dataframe|count|group-by|size | 2 |
6,712 | 28,933,596 | Reconstruct a 2D array from a string | <p>In Python, I have a string (<strong>b</strong> in the following example) converted from a 2D array (<strong>a</strong>). How can I reconstruct the 2D array from the string? </p>
<p>I guess I am using the wrong function "numpy.fromstring" since <strong>c</strong> here is a 1D array. </p>
<pre><code>import numpy
a =... | <p>Another approach which saves the shape of the array is to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow"><code>np.savetxt</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow"><code>np.loadtxt</code></a>. Th... | python|numpy | 0 |
6,713 | 33,929,624 | Create a dataframe from a list | <p>I've got a learner that returns a list of values corresponding to dates. </p>
<p>I need the function to return a dataframe for plotting purposes. I've got the dataframe created, but now I need to populate the dataframe with the values from the list. Here is my code:</p>
<pre><code>learner.addEvidence(x,y_values.v... | <p>you can simply create the dataframe with:</p>
<pre><code>y_prediction_df=pd.DataFrame({"Y-Prediction":y_prediction_list},index=dates)
</code></pre> | list|pandas|dataframe | 2 |
6,714 | 23,841,130 | Creating a list of numpy.ndarray of unequal length in Cython | <p>I now have python code to create a list of ndarrays, and these arrays are not equal length. The piece of code snippet that looks like this:</p>
<pre><code>import numpy as np
from mymodule import list_size, array_length # list_size and array_length are two lists of ints, and the len(array_length) == list_size
ndarr... | <p>In order to pass the C <code>double*</code> buffer to a function that requires a <code>numpy.ndarray</code> you can create a temporary buffer and assign to its memory address the address of the <code>double*</code> array.</p>
<p>This <code>malloc()</code>-based solution is orders of magnitude faster than the other ... | python|arrays|object|numpy|cython | 4 |
6,715 | 29,805,372 | Date parse error in Python pandas while reading file | <p>Follow on question to: <a href="https://stackoverflow.com/questions/29804236/python-pandas-for-reading-in-file-with-date/29805004#29805004">Python pandas for reading in file with date</a></p>
<p>I am not able to parse the date on the dataframe below. The code is as follows:</p>
<pre><code>df = pandas.read_csv(file... | <p>OK I see the problem, your file had extraneous blank lines at the end, unfortunately this messes up the parser as it's looking for whitespace, this caused the df to look the following:</p>
<pre><code>Out[25]:
PRCP VWC1
datetime
2006 1 1 0.0 0.17608
2006 1 2 6.0 0.21377... | python|pandas | 1 |
6,716 | 62,341,749 | std.constant' op requires attribute's type to match op's return type | <p>I'm trying to convert a keras model which I trained and fine tuned with quantization <a href="https://www.tensorflow.org/model_optimization/guide/quantization/training_example" rel="nofollow noreferrer">aware training tutorial</a> on their official website to a int tflite model. I am able to follow their steps until... | <p>Greetings this is closed due to finding another way to resolve the problem. The problem was that there was a sequence of layers: -> Dense -> Flatten -> Dense and because of it this error was occurring. For the time being the solution I'm using is to switch places of Flatten layer and 1st Dense layer. If anybody know... | python|tensorflow|quantization|tensorflow-lite|quantization-aware-training | 0 |
6,717 | 62,156,914 | Can I create a dataframe from few 1d arrays as columns? | <p>Is it possible to create a dataframe from few 1d arrays and place them as columns?
If I create a dataframe from 1 1d array everything is ok:</p>
<pre><code>arr1 = np.array([11, 12, 13, 14, 15])
arr1_arr2_df = pd.DataFrame(data=arr1, index=None, columns=None)
arr1_arr2_df
Out:
0
0 11
1 12
2 13
3 14
4 15
<... | <p>You can use a dictionary:</p>
<pre><code>arr1_arr2_df = pd.DataFrame(data={0:arr1,1:arr2})
</code></pre> | python-3.x|pandas|numpy|dataframe | 3 |
6,718 | 62,393,882 | Unable to access list from csv file using pandas | <p>I have below content in my csv file, which I am trying to read last column from csv using pandas. And after successful fetching of last column x2. I am unable to access the column from the output. Instead if I try to index the x2 column, I am getting rows. But I want columns.</p>
<p><strong>CSV File:</strong></p>
... | <p>Try this:</p>
<pre><code>from ast import literal_eval
df2 = pd.DataFrame(df.x2.apply(lambda x: literal_eval(x)).tolist(), columns=['low', 'high', 'change'])
df2.insert(0, column='symbol', value=df.symbol)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code> symbol low high change
0 A... | python|pandas|csv|data-analysis | 0 |
6,719 | 51,386,851 | Tensorflow operation on non-zero vectors | <p>I have spent about two hours on this, but could not find the solution. The closes thing to what I need is probably this <a href="https://www.tensorflow.org/api_docs/python/tf/boolean_mask" rel="nofollow noreferrer">boolen mask</a>, but I am still missing the next step.</p>
<p>My neural network wasn't learning so I ... | <p>I managed to get the right bias, but then noticed that the dimensions are messed up. So this is only a partial answer:</p>
<pre><code>import tensorflow as tf
import numpy as np
dim = 4
# batch x time x events x dim
tensor = np.random.rand(1, 3, 4, dim)
zeros_last_time = np.zeros((4, dim))
tensor[0][2] = zeros_last... | python|tensorflow | 0 |
6,720 | 51,342,213 | How to dynamically hide glyphs and legend items with Bokeh | <p>I am trying to implement checkboxes in bokeh where each checkbox should show/hide the line associated with it. I'm aware it's possible to achieve this with legends, but I want this effect to happen in two plots at the same time. Also, the legend should update as well. In the example below the checkboxes appear, but ... | <p>You will have to manage <code>LegendItem</code> objects manually. Here is a complete example:</p>
<pre><code>import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row
from bokeh.palettes import Viridis3
from bokeh.plotting import figure
from bokeh.models import CheckboxGroup, Legend, LegendItem
... | python|pandas|bokeh | 2 |
6,721 | 51,277,748 | Keras AttributeError: 'Tensor' object has no attribute 'log' | <p>I am having an error - 'Tensor' object has no attribute 'log' that I code in Keras to build a network while apply custom loss function to Keras. I think somehow I need to get rid of np.log but not sure how.</p>
<pre><code>import Numpy
import numpy as np
</code></pre>
<p>Custom Function</p>
<pre><code>def rmsle(... | <p>You must use valid tensor operations from your backend (i.e. from <a href="https://keras.io/backend/" rel="nofollow noreferrer">keras.backend</a>) in order to define a custom loss function. For example, your loss function could be defined as follows:</p>
<pre><code>import keras.backend as K
def rmsle(y_test, y_pre... | python|python-3.x|tensorflow|machine-learning|keras | 1 |
6,722 | 51,520,279 | Tensorflow dynamic/static shapes: Can not convert a int into a Tensor or Operation | <p>In this code, I'm getting the dynamic and static shapes of an input tensor. The problem is that although my Numpy generated array should be considered as a tensor, it does not! Any help will be appreciated!</p>
<pre><code>import tensorflow as tf
import numpy as np
def get_shape(tensor):
"""
Return the... | <p>Just change the line</p>
<pre><code>dim = [s[1] if s[0] is None else s[0] for s in zip(static_shape, dynamic_shape)]
</code></pre>
<p>to</p>
<pre><code> dim = [s[1] if s[0] is None else tf.constant(s[0]) for s in zip(static_shape, dynamic_shape)]
</code></pre>
<p>The thing is that you <code>s[0]</code> in this c... | python|tensorflow | 1 |
6,723 | 51,193,969 | filter by two conditions after a group by | <p>I am willing to filter the ids which have SMS and Phone in the <code>type</code> column and whenever <code>login_method</code> is equal to <code>resend</code></p>
<pre><code>df
id type login_method
1 SMS resend
1 SMS complete
2 phone resend
2 SMS resend
2 S... | <p>Use:</p>
<pre><code>v = ['SMS','phone']
#first filter only valuse by list
df = df[df['type'].isin(v)]
#get id where are all values per groups with resend
m1 = df['login_method'] == 'resend'
s = df[m1].drop_duplicates(['id','type']).groupby('id')['type'].nunique() != len(v)
#filtering by ids
df1 = df[df['id'].isin... | python|pandas | 1 |
6,724 | 51,254,498 | How to test whether pandas.Series contains only certain type (e.g. int)? | <p>I want to test whether a pandas.Series() contains ONLY integers. None of the things below work. I would prefer solutions that use <code>isinstance()</code>. </p>
<pre><code>import pandas as pd
import numpy
print(isinstance(pd.Series([1, 2]).dtype, numpy.int64))
print(isinstance(pd.Series([1, 2]).dtype.type, numpy.i... | <p>If you know the series has only one data type, you could just do
<code>print(s.dtype == 'int64')</code></p>
<p>When it contains multiple data types, the data type of the series would be "object" in which case you might want to check if every element is int:</p>
<pre><code>s = pd.Series([1,'5'])
s.apply(isinstance,... | python|pandas | 6 |
6,725 | 48,116,509 | Capturing multiple groups in a regex does not return any result | <p>I have a python function </p>
<pre><code>def regex(series, regex):
series = series.str.extract(regex)
series1 = series.dropna()
return (series1)
</code></pre>
<p>Aim to match the regex with the pattern as below:</p>
<ul>
<li><p>anything with 'no' followed by (group of words) or a 'not' should not be m... | <h2>Code</h2>
<p>For simplicity sake, you can actually just use lists and list comprehension to build simple regular expression patterns.</p>
<h3>Usage</h3>
<p><a href="https://ideone.com/uvmoaU" rel="nofollow noreferrer">See code in use here</a></p>
<pre><code>import re
negations = ["no", "not"]
words = ["text", ... | python|regex|pandas|text-mining | 1 |
6,726 | 70,883,956 | How can I sample every other value in a grid while ensuring it alternates each row to create an offset? | <p>I would like to take a grid of evenly spaced points and sample every other value while ensuring that each row is offset from the one before. I have been able to make this fairly easily when the number of <code>x</code> points in the grid is odd, but not when they are even.</p>
<p>As an Example the original grid look... | <p>We can create a new map/boolean column to say whether the point should be included in the plot. The pattern for filling that column is adding <code>x</code> and <code>y</code> values for a point and taking the result's modulus 2 and comparing that to <code>0</code>.</p>
<p>Then when we plot we restrict the DF to the... | python|pandas|numpy | 2 |
6,727 | 71,078,186 | Prevent exploding loss function multi-step multi-variate/output forecast ConvLSTM | <p>I have a plausible problem that currently fails to solve. During the training, my loss function explodes becomes inf or NaN, because the MSE of all errors becomes huge if the predictions (at the beginning of the training) are worse. And that is the normal intended behavior and correct. But, how do I train a ConvLSTM... | <p>I can partially answer my own question. One issue is that I used ReLu/LeakyReLu which will lead to exploding gradient problem because the RNN/LSTM Layer applies the same weights over time leading to exploding values as the values add up. Weights will not be reduced by any chance (ReLu min == 0). With Tanh as activat... | tensorflow|tensorflow2.0|tensorflow-datasets | 1 |
6,728 | 71,037,635 | How to generate predictions from new data using trained tensorflow network? | <p>I want to train Googles <a href="https://github.com/tensorflow/models/tree/master/research/audioset/vggish" rel="nofollow noreferrer">VGGish</a> network (<a href="http://10.1109/ICASSP.2017.7952132" rel="nofollow noreferrer">Hershey et al 2017</a>) from scratch to predict classes specific to my own audio files.</p>
... | <p>For anyone who stumbles across this in the future, I wrote this script which does the job. You must save logmel specs for train and test data in the arrays: X_train, y_train, X_test, y_test. The X_train/test are arrays of the (n, 96,64) features and the y_train/test are arrays of shape (n, _NUM_CLASSES) for two clas... | python|tensorflow|audio|deep-learning|neural-network | 1 |
6,729 | 70,821,382 | Pandas - Add items to dataframe | <p>I am trying to add row items to the dataframe, and I am not able to update the dataframe.
What i tried until now is commented out as it doesn't do what I need.</p>
<p>I simply want to download the json file and store it to a dataframe with those given columns. Seems I am not able to extract the child components fron... | <p>It worked with this:</p>
<pre><code>
import requests, json, urllib
import pandas as pd
url = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
data = pd.read_json(url)
headers = []
df = pd.DataFrame()
for key, item in data['vulnerabilities'].items():
for k in item.k... | python-3.x|pandas|dataframe|jupyter-notebook | 0 |
6,730 | 51,883,453 | How to check if two tensors are equal | <p>Given two tensors of any rank, how can I tell if they both are the same, have I to set my propre solution of there is any kind of implementation of this comparaison </p> | <p>To check if two tensors are equal, one can use <code>tf.equal</code>. But it returns a tensor, a result of a bitwise operation. This tensor elements are whether 1 or 0. Therefore computing the sum of the later tensor should give the number of elements of the tensor if both tensors are equal.</p>
<p><div class="snip... | tensorflow.js | 2 |
6,731 | 51,856,485 | Finetuning a tensorflow object detection pretrained model | <p>I'm working on a real-time object detector with tensorflow and opencv.</p>
<p>I've used different SSD and Faster-RCNN based frozen inference graphs and they almost never fail. </p>
<p>The video stream comes from a IR camera fixed to a wall that has a background that almost never changes. There are some misdetectio... | <p>In case of variations in the background lighting, it might be possible to use Background Subtraction</p>
<p><a href="https://docs.opencv.org/3.4.1/d1/dc5/tutorial_background_subtraction.html" rel="nofollow noreferrer">https://docs.opencv.org/3.4.1/d1/dc5/tutorial_background_subtraction.html</a>
,while dynmically u... | python|c++|opencv|tensorflow|object-detection | 0 |
6,732 | 51,952,446 | Pandas, how to take the pd.Dataframe as a argument in functions | <p>Actually, to simplify the code, instead of writing two similar part codes, I decide to use a function with Dataframe as arguments. Like following:</p>
<pre><code>from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_squared_error
train_one = split_one
test_one = split_two
train_two = s... | <p>If <code>train_arg</code> is a dataframe, then <code>train_arg['accomodates']</code> is a series whereas <code>train_arg[['accomodate']]</code> is a dataframe (containing only one column). </p>
<p>Since the data used in fit and predict is supposed to have multiple columns, the functions will on a <code>pandas.DataF... | python|pandas|scikit-learn | 2 |
6,733 | 51,753,549 | Access row elements as compound list from two dataframes | <p>I have a dataframe as below, df </p>
<pre><code> 1 2 3 4 5 6 7 8 9 10
0 C1 S1 S3
1 C2 S4 S1 S2
2 C3 S3 S5 S1 S3
3 C4 S2 S4 S5 S2 S1 S4 S5 S6 S9
4 C5 S1 S5
</code></pre>
<p>and another dataframe df1 </p>
<pre><code> 1 2 3 4 5 6 7 8 9 10
0 S1 1 17 6 67 ... | <p><strong><em>Option 1</em></strong></p>
<p>You can get your template lists using <code>apply</code>:</p>
<pre><code>tmp = df.drop('0', 1).set_index('1').apply(lambda x: list(x.dropna()), 1)
1
C1 [S1, S3]
C2 [S4, S1, S2]
C3 [S3, S5, S1]
C4 [S2, S4, S5]
C5 [S1, S5]
</code></pre>
<p>Prepare <c... | python|pandas|dataframe | 2 |
6,734 | 41,983,943 | tf.parse_example.features for Multi-label photo classification | <p>I am trying to apply the tutorial code from cloudml-samples/flowers/ on a set of photos with multi-label. Environment is Google Cloud Shell. "preprocess"ed all training and evaluation set. Running into error when started the training task. </p>
<p>I called the trainer.task through python and returning the below err... | <p>The flowers sample does not directly support multi-label classification. The exact problem in your code I believe is related to the <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/flowers/trainer/model.py#L226" rel="nofollow noreferrer">shape=[1] in model.py</a>.</p>
<p>Alas plugging in... | tensorflow|google-cloud-ml | 0 |
6,735 | 41,879,770 | how to use MNIST datast on linux using tensorflow | <p>I'm new in machine learning and I am following tensorflow's tutorial to create some simple Neural Networks which learn the MNIST data.</p>
<p>i wanna run a code that do the recognition hand writing digits using the MNIST data but i don't know how to run it ... should i dowload the data on my machine and extracted ... | <p>If you cannot import <em>tensorflow.examples</em> I'm guessing something went wrong with the installation. Try reinstalling tensorflow with the latest version.
You don't need to download the data on your own, tensorflow will put it in the path you provide. But first, try these steps:</p>
<p>I'm currently using tf ... | tensorflow|mnist | 1 |
6,736 | 42,044,256 | Updating a value in a Pandas dataframe seems to update all dataframes | <p>I've built two Pandas dataframes like this:</p>
<pre><code>import panda as pd
d = {'FIPS' : pd.Series(['01001', '01002']), 'count' : pd.Series([3, 4])}
df1 = pd.DataFrame(d)
df2 = df1
</code></pre>
<p>I want to change one of the values in df2. This is what I've tried:</p>
<pre><code>df2.loc[df2['FIPS'] == '0100... | <p>Because <code>df2</code> is only a reference of <code>df1</code>. They point to the same object in the memory, only by different name. If you do <code>df2=df1.copy()</code> it should create a new memory for <code>df2</code> and only update it..plus you have a typo in import pandas :) </p>
<p>You can check what memo... | python|pandas|dataframe | 1 |
6,737 | 64,610,737 | Tensorflow Object Detection API TF Nightly | <p>Is it possible to use the Tensorflow Object Detection API with the current tf-nightly build and how do I replace tensorflow with tf-nightly?
I have a RTX 3080 which needs CUDA 11 and that is only supported in tf-nightly as of now.</p> | <p>I got it working with my RTX 3070 on Windows with TF2.</p>
<ol>
<li>Create a python 3.8 conda environment and install tf-nightly-gpu via pip</li>
</ol>
<p><code>pip install tf-nightly-gpu==2.5.0.dev20210109</code></p>
<ol start="2">
<li><p>Install cuda 11.0 and cuDNN 8.0.2</p>
</li>
<li><p>Install cuda 11.1</p>
</li... | tensorflow|object-detection|object-detection-api | 1 |
6,738 | 64,470,908 | Pandas Merge DataFrames on similar dates (+-7 days) | <p>I have two Pandas DataFrames and want to merge them on two attributes <code>key</code> and <code>date</code>, where <code>date</code> is a datetime and two rows should be merged, if the date of the second table is +-7 days close to the date in the first table.</p>
<p>Currently, I merge the data frames first and sele... | <p>Without seeing a reproducible example, it sounds like you may be looking for the <code>merge_asof</code> function (if I understood your question correctly). <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stab... | pandas|dataframe|datetime|merge | 3 |
6,739 | 64,190,105 | Is there a faster way to split a pandas dataframe into two complementary parts? | <p>Good evening all,</p>
<p>I have a situation where I need to split a dataframe into two complementary parts based on the value of one feature.</p>
<p>What I mean by this is that for every row in dataframe 1, I need a complementary row in dataframe 2 that takes on the opposite value of that specific feature.</p>
<p>In... | <p>A key concept in efficient <code>numpy</code>/<code>scipy</code>/<code>pandas</code> coding is using library-shipped vectorized functions whenever possible. Try to process multiple rows at once instead of iterate explicitly over rows. i.e. avoid <code>for</code> loops and <code>.iterrows()</code>.</p>
<p>The impleme... | python|pandas|dataframe | 1 |
6,740 | 47,550,705 | If value for a column is Nat, update it by subtracting two dates | <p>I have a data frame which looks like this:</p>
<p><a href="https://i.stack.imgur.com/rA3jW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rA3jW.png" alt="enter image description here"></a></p>
<p>What I am trying to do is check if days_diff is NaT using numpy and pandas, if it is NaT then updat... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a>:</p>
<pre><code>df['days_diff'] = pd.to_timedelta(df['days_diff'])
</code></pre>
<p>But better is use <a href="http://pandas.pydata.org/pandas-docs/stabl... | python|pandas|numpy | 0 |
6,741 | 48,957,094 | How can i use "leaky_relu" as an activation in Tensorflow "tf.layers.dense"? | <p>Using Tensorflow 1.5, I am trying to add <code>leaky_relu</code> activation to the output of a dense layer while I am able to change the <code>alpha</code> of <code>leaky_relu</code> (check <a href="https://www.tensorflow.org/api_docs/python/tf/nn/leaky_relu" rel="noreferrer">here</a>). I know I can do it as follows... | <p>If you're really adamant about a one liner for this, you could use the <code>partial()</code> method from the <code>functools</code> module, as follow:</p>
<pre><code>import tensorflow as tf
from functools import partial
output = tf.layers.dense(input, n_units, activation=partial(tf.nn.leaky_relu, alpha=0.01))
</c... | python|tensorflow | 14 |
6,742 | 58,723,212 | Using Pandas in python, how do I change a certain row? | <p>I am working on changing a value inside of a row inside of pandas.</p>
<p>I will include the first two lines of my .csv file, so you can get a feel for the data.</p>
<pre><code>section,price,seats,type
101,50.00,150,matinee
</code></pre>
<p>As you can see, it is pretty straight forward. Here is the issue.</p>
<p... | <p><strong>Edit</strong>: I understood the question now. You are trying to update the original dataframe <code>matineeSeats.df</code> and not <code>localList</code></p>
<h1>Problem</h1>
<p>You are creating a copy with the <code>.loc</code> selection</p>
<pre><code>import pandas as pd
matineeSeats_df = pd.DataFrame([... | python|pandas | 0 |
6,743 | 58,840,462 | Indexing numpy.ndarrays periodically | <p>I am trying to access (read/write) <code>numpy.ndarrays</code> periodically. In other words, if I have <code>my_array</code> with the shape of <strong>10*10</strong> and I use the access operator with the inputs:</p>
<p><code>my_arrray[10, 10]</code> or <code>acess_function(my_array, 10, 10)</code></p>
<p>I can ha... | <p>I think this does what you want but I'm not sure whether there's something more elegant that exists. It's probably possible to write a general function for an Nd array but this does 2D only. As you said it uses modular arithmetic.</p>
<pre><code>import numpy as np
def access(shape, ixr, ixc):
""" Returns a s... | python|numpy|numpy-ndarray | 1 |
6,744 | 70,139,937 | How to randomly fill X of rows in a pandas dataframe? | <p>How to randomly fill the rows of a dataframe by setting a number? For example:</p>
<p>Given a pandas dataframe with 10 elements:</p>
<pre><code>col1
a
b
c
d
e
f
g
h
i
j
</code></pre>
<p>How to fill randomly with <code>1</code> and the rest with <code>0</code> in the rows of another column. For example, I would like ... | <p>This should do the trick. For each row, set the col2 to a random int between 0 and 1</p>
<pre><code>df["col2"] = df.apply(lambda x: randint(0,1), axis=1)
</code></pre>
<p>If you need n random values to exist and the rest to be set, you can try this:</p>
<pre><code>n = 4
df["col2"] = 0
df_to_updat... | python|pandas|dataframe | 1 |
6,745 | 70,187,803 | Compute mean value of rows that has the same column value in Pandas | <p>I'm trying to combine three pandas DataFrames together</p>
<p>One of them (called <code>major</code>) has a column <code>category</code> where each row has a unique label :</p>
<pre class="lang-py prettyprint-override"><code>major_df = pd.DataFrame(np.random.randint(0, 100, size=(3, 2)), columns=list("AB")... | <p>This?</p>
<pre><code>import pandas as pd
df = pd.read_excel('test.xlsx')
df1 = df.groupby(['category']).mean()
print(df)
print(df1)
</code></pre>
<p>output:</p>
<pre><code> C D category
0 71 44 cat_C
1 5 88 cat_C
2 8 78 cat_C
3 31 27 cat_C
4 42 48 cat_B
5 18 18 cat_B
6 84 23 ... | python|pandas|dataframe|loops|vectorization | 3 |
6,746 | 70,240,197 | Cleaning spikes in time series data using neighbouring data points | <p>I am trying to clean spikes in data in time series data in Pandas dataframe.</p>
<pre><code>value = 5000
for index, row in gauteng_df.iterrows():
if index == gauteng_df.shape[0]-1:
break
upper, lower = row['Admissions to Date'] + value, row['Admissions to Date'] - value
a = gauteng_df.iloc[index+... | <p>Here is an alternative approach that might save you the trouble of iterating over DataFrame values: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html" rel="nofollow noreferrer"><code>scipy.signal.find_peaks</code></a>.</p>
<pre><code>import pandas as pd
import numpy as np
fro... | python|pandas|dataframe | 1 |
6,747 | 56,365,415 | How can I import several Excel sheets in a multi-index dataframe in Python? | <p>I am trying to import an Excel file with several sheets containing the same structure of bidimensional arrays in a multi-indexed Dataframe in Python.</p>
<p>Assume each sheet contains an array (A,B)x(a,b). Basically I would like to have something like this </p>
<pre><code> Sheet1 | Sheet2 | Sheet3
a | b ... | <h3><code>sheet_name=None</code> in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer">pd.read_excel</a></h3>
<p>Will produce a dicitonary of all sheets. Pass that to <code>pd.concat</code> with <code>axis=1</code></p>
<pre><code>pd.concat(pd.read_ex... | python|arrays|pandas|dataframe | 3 |
6,748 | 56,137,777 | pandas plot x axis labels overlapping | <pre><code>import matplotlib.pyplot as plt
import pandas as pd
from PIL import Image
import numpy as np
#code here
df = pd.DataFrame(items) #items is a list of dictionaries
counts =df.groupby('Merchant')['Merchant 1'].count().sort_values(ascending=False)counts2 =df.groupby('Merchant 2')['Seller'].count().sort_values(a... | <p>Try to change:</p>
<pre><code>total.plot(kind='bar')
plt.xticks(rotation='horizontal')
</code></pre>
<p>to</p>
<pre><code>total.sort_values(ascending=False).plot(kind='bar')
plt.xticks(rotation=90)
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/otbiS.png" rel="noreferrer"><img src="https://i... | python|pandas | 6 |
6,749 | 55,619,581 | Getting total memory and cpu usage for one python instance | <p>I'm using keras to make and test different types of Neural Nets and need data to compare them. I need data on the cpu and memory used during the training and testing. This is in python and as I looked around I found lot of suggestions for psutil. However everything I see seems to grab the current usage. </p>
<p>Wha... | <p>psutil is a good recommendation to collect that type of information. If you incorporate this code into your existing keras code, you can collect information about the cpu usage of your process at the time the cpu_times() method is called</p>
<pre><code>import psutil
process = psutil.Process()
print(process.cpu_tim... | python|tensorflow|keras|psutil | 1 |
6,750 | 55,923,743 | How to make to_sql method from Pandas DataFrame work with Jaydebeapi? | <p>I tried to write a pandas dataframe into a HIVE table on a remote server using <code>to_sql</code> method. Currently I have the Jaydebeapi connection object created and I'm able to use <code>read_sql</code> method from pandas plus this connection object to query data from that table. However when I tried to write ba... | <p>You cannot do it that way. You need to create manually the table (or with an SQL script executed on the cursor, not on the connection) and then you run an UPDATE statement with all the rows of the DB that are well formatted.
Sorry about that.</p> | python|pandas|python-3.7|jaydebeapi | 0 |
6,751 | 55,912,952 | PyTorch does not converge when approximating square function with linear model | <p>I'm trying to learn some PyTorch and am referencing this discussion <a href="https://discuss.pytorch.org/t/minimal-working-example-of-optim-sgd/11623" rel="nofollow noreferrer">here</a></p>
<p>The author provides a minimum working piece of code that illustrates how you can use PyTorch to solve for an unknown linear... | <p>You cannot fit a 2nd degree polynomial with a linear function. You cannot expect more than random (since you have random samples from the polynomial).<br>
What you can do is try and have two inputs, <code>x</code> and <code>x^2</code> and fit from them:</p>
<pre><code>model = nn.Linear(2, 1) # you have 2 inputs no... | python|machine-learning|neural-network|regression|pytorch | 3 |
6,752 | 55,964,143 | How to define multiple filters in Tensorflow | <p>I have small matrix <strong>4*4</strong>, I want to filter it with two different filters in TensorFlow (1.8.0). I have an example with one filter (<code>my_filter</code>):
I want to change the filter to </p>
<pre><code>my_filter = tf.constant([0.2,0.5], shape=[2, 2, 3, 1])
</code></pre>
<p>One will be <strong>2*2<... | <p><strong>First option</strong></p>
<p>The filter can also be defined as a placeholder</p>
<pre><code>filter = tf.placeholder(filter_type, filter_shape)
...
with tf.Session() as sess:
for i in range (number_filters) :
result =sess.run(mov_avg_layer,feed_dict={x_data: x_val, filter: filter_val})
</code></pre>
<p... | tensorflow | 1 |
6,753 | 64,907,186 | Is there any way to list down datetime range between 2 datatime in python? | <p>i have 2 set of datetime data in different column and i would like to list down, the range within the 2 date and time of a same row.</p>
<p>example, i tried below the output does not shows the range of datetime</p>
<pre><code>import pandas as pd
a = '2020-11-17 13:35:18'
b = '2020-11-17 13:36:09'
tt= pd.date_ra... | <p>Reason of your output is if not set <code>freq</code> parameter is used default.</p>
<p>So set <code>S</code> for seconds frequency:</p>
<pre><code>tt = pd.date_range(start=a,end=b, freq='S')
print(tt)
DatetimeIndex(['2020-11-17 13:35:18', '2020-11-17 13:35:19',
'2020-11-17 13:35:20', '2020-11-17 13:... | python|pandas|datetime | 3 |
6,754 | 44,205,471 | Tensorflow tfprof LSTMCell | <p>I'm using tfprof in order to get number of flops necessary for model forward path.
My model is 3 layer LSTM and fully connected layer afterwards.
I've observed that number of computations grows linearly for fully connected layer, while it doesn't changes for LSTM layers. How that could be possible? </p>
<p>tfprof ... | <p>tfprof does static analysis of your graph and calculate the float operations for each graph node.</p>
<p>I assume you are using dynamic_rnn or something similar that has tf.while_loop. In that case, a graph node appear in graph once
but is actually run multiple times at run time.</p>
<p>In this case, tfprof has no... | tensorflow|lstm | 2 |
6,755 | 44,321,487 | Pandas: How to count Occurrences of Categorical features Grouped by ID | <p>Suppose I have this DataFrame <code>df</code></p>
<pre><code>My_ID My_CAT
1 A
2 B
3 C
1 A
1 B
2 D
</code></pre>
<p>I'd like to know how many occurrences of each distinct <code>My_Cat</code> value occurs for each distinct <code>My_ID</code>.</p>
<p>I need it ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a> (less typing, by slowiest):</p>
<pre><code>df = pd.crosstab(df['My_ID'], df['My_CAT'])
print (df)
My_CAT A B C D
My_ID
1 2 1 0 0
2 0 1 0 1
3... | python|pandas|numpy | 4 |
6,756 | 40,840,539 | How to reshape numpy array of array into single row | <p>I have a numpy array as </p>
<pre><code>[[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
...,
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]]
</code></pre>
<p>I would like to have it as </p>
<pre><code>0
0
0
.
.
0
0
</code></pre>
<p>I know that we have to use the reshape function, but h... | <p>You can also have a look at <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html" rel="nofollow noreferrer">numpy.ndarray.flatten</a>:</p>
<pre><code>a = np.array([[1,2], [3,4]])
a.flatten()
# array([1, 2, 3, 4])
</code></pre>
<p>The difference between <code>flatten</code> and ... | python|arrays|numpy | 7 |
6,757 | 54,101,593 | Conditional Batch Normalization in Keras | <p>I'm trying to implement Conditional Batch Normalization in Keras. I assumed that I will have to create a custom layer, hence, I extended from the <a href="https://github.com/keras-team/keras/blob/master/keras/layers/normalization.py" rel="nofollow noreferrer">Normalization</a> source code from Keras team. </p>
<p>T... | <p>I would use <a href="https://www.tensorflow.org/api_docs/python/tf/case" rel="nofollow noreferrer">tf.case</a> to express your conditional statements:
</p>
<pre class="lang-py prettyprint-override"><code>normed_training, mean, variance = \
tf.case({
c1: lambda: K.normalize_batch_in_train... | python|tensorflow|machine-learning|keras|keras-layer | 2 |
6,758 | 53,843,863 | Pandas top N records in each group sorted by a column's value | <pre><code>import pandas as pd
d = {
'resource': [1,2,3,4,5,6,7],
'branch': ['a', 'b', 'c', 'a', 'a', 'c', 'b'],
'utilization': [0.7, 0.76, 0.9, 0.3, 0.55, 0.87, 0.71]
}
df = pd.DataFrame(data=d)
</code></pre>
<h3>I need to display the top 2 utilized resources by branches</h3>
<p><strong>Something like t... | <p>May using <code>sort_values</code> + <code>tail</code></p>
<pre><code>df.sort_values('utilization').groupby('branch').tail(2)
branch resource utilization
4 a 5 0.55
0 a 1 0.70
6 b 7 0.71
1 b 2 0.76
5 c 6 0.8... | pandas|pandas-groupby | 5 |
6,759 | 54,043,734 | How to split data set into subsets following some criterions? | <p>Though I use machine learning-related terminology, my question is 100% engineering topic and it has nothing to do with statistics and mathematics. Therefore I ask it in this forum instead of Cross Validated.</p>
<p>This is my sample data that I will use to comment my question:</p>
<pre><code>X = pd.DataFrame(colum... | <p>There is an option called stratify, in train_test_split. also take a look at this <a href="https://stackoverflow.com/questions/29438265/stratified-train-test-split-in-scikit-learn">kind of similar question</a></p>
<p>To accomplish the proportions that you need, you can use <code>np.random.choice</code> from numpy:<... | python|pandas|dataframe|scikit-learn | 2 |
6,760 | 53,857,373 | Loading images for multi-class from csv file | <p>I have Train and Test folders and inside each folder there is many folders with images inside each. In .csv file there is label for each folder and class.</p>
<p>here is csv file</p>
<p><a href="https://i.imgur.com/qMLGOpC.png" rel="nofollow noreferrer">https://i.imgur.com/qMLGOpC.png</a></p>
<p>and folders</p>
... | <p>you can use inbuild flow_from_directory() method
check out this link <a href="https://keras.io/preprocessing/image/" rel="nofollow noreferrer">keras docs</a></p> | python|pandas|keras|deep-learning | 0 |
6,761 | 54,166,444 | Removing List Within Pandas Dataframe | <p>I have the following dataframe:</p>
<pre><code>Index Recipe_ID order content
0 1285 1 Heat oil in a large frypan with lid over mediu...
1 1285 2 Meanwhile, add cauliflower to a pot of boiling...
2 1285 3 Remove lid from chicken and let simmer uncover...... | <p>I've created a little example that might solve this problem for you:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'order': [1, 1, 2], 'content': ['hello', 'world', 'sof']})
df
Out[4]:
order content
0 1 hello
1 1 world
2 2 sof
df.groupby(by=['order']).agg(lambda x: ' '.join(x))
Ou... | python|pandas|data-cleaning | 3 |
6,762 | 66,079,643 | How to remove the following error : ImportError: cannot import name 'normalize_data_format' | <p>I am getting stuck by sequential errors for the following code as you can see with the google colab link:
<a href="https://colab.research.google.com/drive/1Tc8WEzqBMRd0Eg7pJijI98eBEKTw45s3?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1Tc8WEzqBMRd0Eg7pJijI98eBEKTw45s3?usp=sharing</a>... | <p>Replace import statement from</p>
<pre><code>from keras.utils import conv_utils
</code></pre>
<p>to</p>
<pre><code>from tensorflow.python.keras.utils import conv_utils
</code></pre> | python|tensorflow|keras | 0 |
6,763 | 65,994,547 | Append a row to pandas dataframe for select columns only | <p>I'd like to append a new row to pandas DataFrame, but only populate select columns. In the code below, I subset the columns list I'd like to populate and assign a list of values.</p>
<pre><code>import pandas as pd
sampleDF = pd.DataFrame(columns=['Tenant','Industry','Square Footage'])
sampleDF = sampleDF.iloc[samp... | <p>You can use the append() method by inserting a dictionary. Does this help ?</p>
<pre><code>sampleDF = sampleDF.append({'Tenant': 'De Shaw', 'Industry': 'Finance'}, ignore_index = True)
</code></pre> | python|pandas | 0 |
6,764 | 66,076,400 | PyTorch: Using a target size (torch.Size([1])) that is different to the input size (torch.Size([1, 1])) | <p>I am new to PyTorch and working on the implementation of recommender systems.</p>
<p>I obtained my models from here:
<a href="https://blog.fastforwardlabs.com/2018/04/10/pytorch-for-recommenders-101.html" rel="nofollow noreferrer">https://blog.fastforwardlabs.com/2018/04/10/pytorch-for-recommenders-101.html</a></p>
... | <p>This is not an error message, it's a warning about the shapes of tensors passed to <code>nn.MSELoss</code>.</p>
<p>Provided that you feed each model with a 1D tensor of shape <code>(n,)</code>. The only difference is that <code>MatrixFactorization</code> will return a 1D tensor (of shape <code>(n,)</code>, while <co... | machine-learning|pytorch | 0 |
6,765 | 66,285,835 | TensorFlow Lite PoseNet on Android crashes because of memory | <p>I am trying to create an Android app that uses TensorFlow Lite PoseNet for human pose estimation.
The problem I have is that native memory slowly increases until it crashes.
Even if I run the <a href="https://github.com/tensorflow/examples/tree/master/lite/examples/posenet/android" rel="nofollow noreferrer">demo app... | <p>There was a memory leak in the Android PoseNet demo app that is not noticeable unless you enable <code>window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)</code></p>
<p>The PosenetActivity.kt captureSession!!.setRepeatingRequest was using a backgroundHandler which was holding a reference that was prevent... | android|tensorflow | 0 |
6,766 | 52,710,348 | How to take and restore snapshots of model training on another VM in Google Colab? | <p>There is a 12 hour <a href="https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/discussion/48320" rel="nofollow noreferrer">time limit</a> for training DL models on GPU, according to google colab. Other people have had similar <a href="https://stackoverflow.com/questions/49469697/how-can-i-keep-th... | <p>As far as I know, there is no way to automatically reconnect to another VM whenever you reach the 12 hours limit. So in any case, you have to manually reconnect when the time is up.</p>
<p>As Bob Smith points out, you can mount Google Drive in Colab VM so that you can save and load data from there. In particular, y... | python|tensorflow|deep-learning|pytorch|google-colaboratory | 1 |
6,767 | 52,859,756 | Using idxmax on a hierarchical dataframe | <p>I'm trying to find the index of the maximum values in multiple columns in a multi-index Pandas dataframe. </p>
<pre><code> Kommune Upplands Vallentuna... Kiruna
Year Party
1973 M 0.9 29.2 ... 20
KD 15 10 ... 2
MP 1.1 4 ... | <p>Seems like you need </p>
<pre><code>df.stack().sort_values().groupby(level=[0,2]).tail(1).reset_index(level=1).Party.unstack()
Out[544]:
Upplands Vallentuna Kiruna
Year
1973 KD M M
1976 KD M M
</code></pre> | python|pandas|multi-index | 3 |
6,768 | 52,762,328 | Issues with using numpy | <p>I have <em>pypy</em> (Python 2.7.13, [PyPy 6.0.0 with GCC 6.2.0 20160901] on linux2) and <em>python</em> (Python 2.7.14 [GCC 4.8.4] on linux2) installed on same machine.</p>
<p>I am seamlessly able to use <em>numpy</em> with <em>pypy</em>. However, with <em>python</em> I get following error.</p>
<pre><code>Traceba... | <p>If you have mixed <code>sudo pip install</code> with <code>sudo apt install</code> you have propbably messed up your system. You might want to explore using <code>virtualenv</code> to set up a self-contained python, one that lives totally inside a single folder that can be managed with usr-level <code>pip install</c... | python|numpy|pypy | 0 |
6,769 | 52,601,904 | I am trying to create a new column to bin values of a time column of a dataframe in python based on time range | <p>Time column values: 09:11:00,10:11:00...NAT</p>
<pre><code>pd.cut(df_master['time_colum`enter code here`n'],bins=
['09:11:00','11:44:00','13:55:00','16:28:00'], labels=
['Morning','Afternoon','Evening'])
TypeError Traceback (most recent call last)
<ipython-input-102-c66025f961bf> in <module>(... | <p>You just have to convert your string time to time delta value </p>
<pre><code> time
0 09:31:00
1 12:04:00
2 14:15:00
3 16:48:00
df1['time'] = pd.to_timedelta(df1['time']
pd.cut(df1['time'],bins=pd.to_timedelta(['09:11:00','11:44:00','13:55:00','16:28:00']), labels=['Morning','Afternoon','Evening'])
</co... | python|pandas | 1 |
6,770 | 52,754,453 | Tensorflow Keras - AttributeError: Layer features has no inbound nodes | <p>Tensorflow version : 1.11.0</p>
<p>I am trying to use TensorBoard with Tensorflow keras model for projector visualisation.
I am getting AttributeError: Layer features has no inbound nodes.
I am not sure why I get this error in below simple code. I indeed google the error but I could not find right solution to fix ... | <p>When defining a network in Keras, the first layer added needs to have input_shape added.</p>
<p>See the docs here: <a href="https://keras.io/getting-started/sequential-model-guide/#specifying-the-input-shape" rel="nofollow noreferrer">https://keras.io/getting-started/sequential-model-guide/#specifying-the-input-sha... | python|tensorflow|keras|tensorboard | 3 |
6,771 | 52,888,715 | How to write a file to S3 using Pandas | <p>I want to write a data frame column in .ann format to S3. </p>
<p>Right now I am using the following code to do that.</p>
<pre><code>df['user_input'].to_csv(ann_file_path, header=None, index=None, sep=' ')
</code></pre>
<p>Where ann_file_path is the full path of the .ann file on the Server.</p>
<p>I am getting f... | <p>I've resolved. We need AWS handshake using <code>access_key_id</code> and <code>secret_key</code> for AWS.</p>
<p>Get URL starting from the bucket name (not https:/...), hence get rid of whatever before it.</p>
<p>My URL: <code>https://s3-eu-west-1.amazonaws.com/bucket/sub_folder/somefile.ann</code></p>
<p>Transf... | python-3.x|pandas|amazon-web-services|amazon-s3|boto3 | 4 |
6,772 | 46,571,137 | Error parsing datetime string "09-11-2017 00:02:00" at position 8 | <p>I created a data frame with a column of datetime objects, re sampled it but would now like to turn the data frame into a list of lists - where the datetimes are now strings again. </p>
<pre><code>for i in range(1, len(dataf.index)):
dataf["Time Stamp"][i] = datetime.strftime(dataf["Time Stamp"][i], '%m-%d-%Y %H... | <p>You ought to be able to</p>
<pre><code>dataf['Time Stamp'].dt.strftime('%m-%d-%Y %H:%M:%S')
</code></pre>
<p>So to rewrite the column</p>
<pre><code>dataf['Time Stamp'] = dataf['Time Stamp'].dt.strftime('%m-%d-%Y %H:%M:%S')
</code></pre>
<p>If you have errors, it's probably because the column isn't actually date... | python|string|pandas|datetime | 1 |
6,773 | 58,320,848 | How to count by time frequency using groupby - pandas | <p>I'm trying to count a frequency of 2 events by the month using 2 columns from my <code>df</code>. What I have done so far has counted all events by the unique time which is not efficient enough as there are too many results. I wish to create a graph with the results afterwards.</p>
<p>I've tried adapting my code by... | <p>One possible solution is convert datetime column to months periods by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.to_period.html" rel="nofollow noreferrer"><code>Series.dt.to_period</code></a>:</p>
<pre><code>print(df.groupby(['Priority', df['Create Time'].dt.to_period('m')])... | python|pandas|pandas-groupby | 2 |
6,774 | 68,948,888 | Panda Dataframe Find rows which does not have equivalent value in the DataFrame | <p>DataFrame:</p>
<pre><code> column1 column2
0 some_data string1
1 some_data string1
2 some_data string2
3 some_data string3
4 some_data string2
5 some_data string4
5 some_data string4
...
20k+ rows in total
</code></pre>
<p>Explanation:
For most rows, column2 data appear in pairs. I... | <p>If possible simplify problem for found all rows without dupes by <code>column2</code> use:</p>
<pre><code>df1 = df[~df['column2'].duplicated(keep=False)]
</code></pre>
<p>If need test counts and filter all rows without pairs (2):</p>
<pre><code>df2 = df[df.groupby('column2')['column2'].transform('size').ne(2)]
</cod... | python|pandas | 1 |
6,775 | 68,913,591 | Merge two arrays with the same dimension based on a condition | <p>I have two arrays with the same dimension:</p>
<pre><code>a = [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 1, 1, 1], ]
b = [
[0, 1, 1, 0],
[0, 0, 0, 0],
[2, 0, 0, 2],
[0, 0, 0, 0], ]
</code></pre>
<p>I would like to create a new one, only changing the values where B is not 0 and is different than A. The result w... | <p>You can do assignment with boolean conditions:</p>
<pre><code>a[b != 0] = b[b != 0]
a
array([[1, 1, 1, 1],
[1, 0, 0, 1],
[2, 0, 0, 2],
[1, 1, 1, 1]])
</code></pre> | python|arrays|numpy | 2 |
6,776 | 44,797,757 | tfslim "Training a model from scratch." some kind of error occured | <p>i'm training tf slim with</p>
<p><a href="https://github.com/tensorflow/models/tree/master/slim" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/slim</a></p>
<p>training a model form scratch. some kind of error occured</p>
<p>i think its kind of gpu and cpu running problem.</p>
<p>othe... | <p>It's trying to run some ops on the GPU, but TensorFlow doesn't see a GPU device (either because you're using the CPU version of TensorFlow, because of a CUDA installation issue, or because there is no GPU). It looks like you can specify <code>--clone_on_cpu=True</code> to use the CPU instead.</p> | python|tensorflow|deep-learning|tf-slim | 0 |
6,777 | 44,541,648 | Loading large dataset into Pandas Python | <p>I would like to load large .csv (3.4m rows, 206k users) open sourced dataset from InstaCart <a href="https://www.instacart.com/datasets/grocery-shopping-2017" rel="nofollow noreferrer">https://www.instacart.com/datasets/grocery-shopping-2017</a></p>
<p>Basically, I have trouble loading orders.csv into Pandas DataFr... | <p>Best option would be to <strong>read the data in chunks instead of loading the whole file into memory</strong>.</p>
<p>Luckily, <code>read_csv</code> method accepts <code>chunksize</code> argument.</p>
<pre><code>for chunk in pd.read_csv(file.csv, chunksize=somesize):
process(chunk)
</code></pre>
<p>Note: By ... | python|csv|pandas | 3 |
6,778 | 44,396,805 | Retrieving index from multi-index based on column values in Pandas | <p>Say I have a table as such:</p>
<pre><code> Attr | Foo | Bar
Name|Val | 1 | 2 | 3 | 4
-----------------------------
OFO |1 | F | T | F | F
|2 | T | F | F | T
-----------------------------
ARB |5 | T | T | F | F
|6 | F | F | F | T
</code></pre>
<p>Where my rows are contr... | <p>You can start with:</p>
<pre><code>df.stack([0,1]).reset_index(name='value').query('value == True')
</code></pre>
<p>Output:</p>
<pre><code> level_0 level_1 level_2 level_3 value
3 OFO 1 Foo 2 True
5 OFO 2 Bar 4 True
6 OFO 2 Foo 1 True
10... | python|pandas | 1 |
6,779 | 60,926,614 | Creating a new column from pairwise row entries in pandas | <p>I have a dataframe as given below</p>
<pre><code>>>> df
t c f e
0 1 100 2 1
1 1 200 1 1
2 1 300 4 0
3 1 400 2 0
4 2 100 3 1
5 2 200 3 1
6 2 300 4 1
7 2 400 1 0
8 3 100 4 0
9 3 200 3 0
10 3 300 1 1
11 3 400 4 1
12 4 100 1 1
13 4 200 4... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>Series.shift</code></a></p>
<pre><code>df['rr'] = df['e'].eq(df['e'].shift(-4)).astype(int)
df['rr2'] = df['e'].eq(df['e'].shift(-1)).astype(int)
print(df)
</code></pre>
<hr>
<pre><cod... | python-3.x|pandas | 1 |
6,780 | 60,994,945 | Get all records from 2 columns, starting from specific row | <p><strong>Set-up</strong></p>
<p>Via gspread I have access to a Google sheet containing data.</p>
<p>Normally, I use <code>df = pd.DataFrame(wsheet.get_all_records())</code> to dump all data into a pandas dataframe. </p>
<hr>
<p><strong>Issue</strong></p>
<p>I only need the data of 5 specific sequential columns, ... | <ul>
<li>You want to retrieve the values from the columns "A" and "E" after the row 5 from the Google Spreadsheet.</li>
<li>You want to achieve this using gspread with python.</li>
<li>You have already been able to get and put values for Spreadsheet using Sheets API.</li>
</ul>
<h3>Modification poin... | python|pandas|dataframe|gspread | 1 |
6,781 | 69,976,066 | Subplots with counter like legends | <p>I have written <code>plot_dataframe()</code> to create two subplots (one for line chart and another for histogram bar chart) for a dataframe that is passed via argument.
Then I call this function from <code>plot_kernels()</code> with multiple dataframs.</p>
<pre><code>def plot_dataframe(df, cnt):
row = df.iloc[... | <p>Change <code>legend</code> to <code>label</code>, then force the legend after you plot everything:</p>
<pre><code>def plot_dataframe(df, cnt,axes):
row = df.iloc[0].astype(int) # First row in the dataframe
row.plot(label=cnt, ax=axes[0]) # Line chart -- use label, not legend
df2 = row.value_counts()
... | pandas | 1 |
6,782 | 69,962,366 | BERT Additional pretraining in TF-Keras | <p>I'm currently developing a project involving sequence multilabel classification. Since I'm using a highly technical dataset, I thought that doing additional pretraining on BERT before fine-tuning it for the classification part would be beneficial. But I can't find any guide to use Huiggingface transformers and Keras... | <p>You can use BERT model to pre-training on your custom dataset.</p>
<p><strong>Sample working code</strong></p>
<pre><code>import os
import tensorflow as tf
import tensorflow_hub as hub
bert_preprocess = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3")
bert_encoder = hub.KerasLay... | python|tensorflow|keras|deep-learning|huggingface-transformers | 1 |
6,783 | 69,843,011 | Pandas Dataframe automatically changing from int8 to float | <p>I have a very large matrix of 100K x 100K and to manage memory better, I am setting this as a dataframe with int8 as datatype (for 1 byte per cell). However, it gets set as a float with 8 bytes per cell. Where am I going wrong?</p>
<pre><code>df = pd.DataFrame()
df=df.astype('int8')
mat_len=100,000
for i in rang... | <p>You should always avoid <code>append</code> to DataFrames/Series, especially avoid using it in a loop. It's very very slow. First, generate the data and then create a DataFrame with it.</p>
<blockquote>
<p>df.iloc[i,j] = i+j #simplified calc for testing purposes</p>
</blockquote>
<p>How complex is your calculation... | python|pandas|dataframe|memory | 2 |
6,784 | 69,949,563 | Python Pandas VLOOKUP function with categorical and non-numeric values | <p>I want to optimize a process of a "vlookup" in Python that works but is not scalable in its current form. I have tried pythons pivot.table and pivot but it's been limited due to alphanumeric and string values in cells. I have two tables:</p>
<p><strong>table1:</strong></p>
<div class="s-table-container">
<... | <p>Assuming the dataframes are named <code>df1</code> and <code>df2</code>, you can reshape and <code>map</code> to perform the <em>VLOOKUP</em>, then <code>groupby</code>+<code>sum</code>:</p>
<pre><code>(df2.set_index('Brand')
.stack()
.map(df1.set_index('ProductID')['Sales'])
.groupby(level='Brand').sum(... | python|pandas|merge|vlookup | 2 |
6,785 | 69,666,353 | Merge two dataframes on multiple columns but only merge on columns if both not NaN | <p>I'm looking to merge two dataframes across multiple columns but with some additional conditions.</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({
'col1': ['a','b','c', 'd'],
'optional_col2': ['X',None,'Z','V'],
'optional_col3': [None,'def', 'ghi','jkl']
})
df2 = pd.DataFrame({
'col1': ['a','b... | <p>This solution works by creating an extra column called "temp" in both dataframes. In <code>df11</code> it will be a column of true values. In <code>df2</code> the values will be true if there is a match between either of the optional columns. I'm not clear whether you consider a <code>NaN</code> value t... | python|pandas|dataframe | 1 |
6,786 | 43,385,303 | tensorflow built from source using cuda or not? | <p>I built tensorflow with GPU support from source for python on macOS following the official instructions. When I import tensorflow though, I don't get the typical CUDA loading messages I do when I use the pip version (as below).</p>
<pre><code>I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA ... | <pre><code>tensorflow.test.is_gpu_available()
tensorflow.test.is_built_with_cuda()
</code></pre>
<p>If you run these codes, and Tensorflow is built with CUDA, then both functions should return <b>True</b>.</p>
<p>I have to use this, because as given in the previous answer, I don't get a output with "successfully open... | python|tensorflow | 0 |
6,787 | 43,215,715 | Pandas 5yr & 10yr Moving average | <p>I have a dataframe where my index is datetime dtype but the dates are not in any sequential ordering. I am looking to calculate the 5 year and 10 year moving averages of my dataset. By using .rolling_mean I can take the average based on what i set the window to, however, as the dates are not sequential, this does no... | <p>This is one of those cases of the rolling function working as advertised but not doing what you want it to do. In the latest versions of Pandas you should get a warning when using <code>rolling_mean</code> as it's being deprecated in favor of <code>rolling</code> so for illustration I'll use <code>rolling</code>:</p... | pandas|moving-average | 4 |
6,788 | 72,253,277 | Pandas Resample OHCL | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>close</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-02-21</td>
<td>3</td>
</tr>
<tr>
<td>2022-02-22</td>
<td>1</td>
</tr>
<tr>
<td>2022-02-23</td>
<td>5</td>
</tr>
<tr>
<td>2022-02-24</td>
<td>5</td>
</tr>
<tr>
<td>2022-02-25</td>
<td>7... | <p>You can assign the index to a new column then keep the first value in this group</p>
<pre class="lang-py prettyprint-override"><code>out = (df.assign(index=df.index)
.groupby(pd.Grouper(freq='W-MON', closed='left', label='left')).agg({'index': 'first', 'close': 'last'})
.reset_index(drop=True))
</code>... | pandas|pandas-resample | 1 |
6,789 | 72,232,619 | Searching a value within range between columns in pandas (not date columns and no sql) | <p>thanks in advance for help. I have two dataframes
as given below. I need to create column category in sold frame based on information in size frame. It should check siz of product within Min and Max sizes for this product and return group. Is it possible to do it in pandas? not SQL. I think merge and join method wil... | <p>Joining condition in pandas must be exact match. It doesn't have the <code>BETWEEN ... AND ...</code> clause like in SQL.</p>
<p>You can use numpy broadcast to compare every row in <code>sold</code> to every row in <code>size</code> and filter for a match:</p>
<pre class="lang-py prettyprint-override"><code># Conver... | python|pandas|search|lookup | 0 |
6,790 | 50,344,335 | Grouping pandas dataframe based on common key | <p>I have a file which I have parsed as pandas DataFrame but want to collectively group by their individual element at column 3 w.r.t column 2.</p>
<pre><code> 0 1 2 3 4
0 00B2 0 -67 39 1.13
1 00B2 85 -72 39 1.13
2 00B2 1 -67 86 1.13
3 00B2 2 -67 87 1.13
4 00B2 ... | <p>I think need create dictionary of <code>Series</code> by converting <code>groupby</code> object to tuples and dicts:</p>
<pre><code>d = dict(tuple(df.groupby(3)[2]))
print (d[39])
0 -67
1 -72
5 -67
26 -71
27 -71
29 -71
Name: 2, dtype: int64
</code></pre>
<p>For <code>DataFrame</code>:</p>
<pre><co... | python|pandas | 1 |
6,791 | 50,608,658 | Iterating Through Multiindex Pandas DataFrame to normalize by specific index level | <p>I have a multiindexed DataFrame and I want to normalize specific sets of columns (of the "second" index level) against their highest value:</p>
<pre><code> Level1 Level2
Thing1 Thing2 Thing1
Norm1 Norm2 Norm1 Norm2 ... | <p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="nofollow noreferrer"><code>max</code></a> by first and second level of <code>MultiIndex</code>:</p>
<pre><code>df = df.max(level=[0,1], axis=1)
</code></pre>
<p>Alternative solution is aggregate <code>max<... | python|pandas | 1 |
6,792 | 62,716,991 | Replacing values in certain columns based on a dictionary of thresholds? | <p>I am trying to get from this Panda df:</p>
<pre><code> mag ip em as_ppm au_ppm
0 820 6447 99 4670 30
1 774 5827 26 35 97
2 800 9089 75 9727 25
3 584 6122 38 2911 80
4 494 7616 78 6673 67
5 742 6626 30 9424 69
6 803 2136 71 4043 7... | <p>Try</p>
<pre><code>s=(df.lt(highThresholds) & df.gt(lowThresholds)).mul(weights)
mag ip em as_ppm au_ppm
0 5 10 0 20 30
1 5 10 5 20 0
2 5 0 5 0 30
3 5 10 5 20 30
4 0 0 5 20 30
5 5 10 5 0 30
6 5 0 5 ... | python|pandas | 5 |
6,793 | 62,732,824 | Convert a string to one hot encoding matrix and then feed to neural network | <p>I have many DNA sequence data, which has been read into <em>xtrain</em>. Each sample has a label (classification problem), which has been read into <em>ytrain</em>.</p>
<pre class="lang-py prettyprint-override"><code>tokenizer = keras.preprocessing.text.Tokenizer(char_level=True, lower=True)
tokenizer.fit_on_texts(&... | <pre><code>tokenizer = keras.preprocessing.text.Tokenizer(char_level=True, lower=True)
tokenizer.fit_on_texts("ATCGN")
x = []
seq = np.array(tokenizer.texts_to_sequences('ATCGN'))
a = keras.utils.to_categorical(seq[:,0]-1)
for i in a:
x = x + list(i)
print(x)
</code></pre> | python|numpy|tensorflow | 0 |
6,794 | 62,761,435 | Koalas GroupBy > Apply > Lambda > Series | <p>I am trying to port some code from Pandas to Koalas to take advantage of Spark's distributed processing. I am taking a dataframe and grouping it on A and B and then applying a series of functions to populate the columns of the new dataframe. Here is the code that I was using in Pandas:</p>
<pre><code>new = old.group... | <ol>
<li>I'm not sure about the error. I am using <code>koalas==1.2.0</code> and <code>pandas==1.0.5</code> and I don't get the error so I wouldn't worry about it</li>
<li>The <code>groupby</code> columns are already called <code>A</code> and <code>B</code> when I run the code. This again may have been a bug which has ... | pandas|pandas-groupby|databricks|pandas-apply|spark-koalas | 1 |
6,795 | 62,858,493 | How to insert a gridline in specific position on seaborn heatmap | <p>I have the following data and heatmap and would like some help with the formatting of the gridlines:</p>
<pre><code>import pandas as pd
import numpy as np
data = [
['tom', 1, 1, 1, '0:00', '10:26'],
['tom', 1, 1, 2, '15:30', '18:50'],
['tom', 1, 2, 1, '2:00', '9:15'],
['tom', 1, 2, 2, '13:10', '22:4... | <p>Grid lines could not be displayed by 'sns', so I used 'matplotlib' to create horizontal and vertical lines painted. <code>ax.hlines()</code>,<code>ax.vlines()</code>.</p>
<pre><code>h = ax.get_yticks()
print(h)
[0.5 1.5]
w = ax.get_xticks()
print(w)
[ 0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5 11.5 12.5 1... | python|pandas|seaborn | 2 |
6,796 | 62,569,780 | access only first 80% columns of a data frame | <p>I want to access only the first 80% columns of my dataframe and store it into new data frame whereas store the remainig 20% in another data frame. Here is something I tried:</p>
<pre><code>ratings_df=ratings_df.iloc[:,:int(ratings_df.shape()[1]*0.8)-1]
</code></pre>
<p>however this gave an error:</p>
<pre><code>Tra... | <p>You should remove the brackets. You only need df.shape[1].
By the way for more readability, I suggest you use rather</p>
<pre><code>shape_80 = int(df.shape[1]*0.8)-1
ratings_df=ratings_df.iloc[:,:shape_80]
</code></pre>
<p>Or something like that</p> | python|pandas|numpy|dataframe|recommendation-system | 2 |
6,797 | 54,683,569 | How to concatenate ResNet50 hidden layer with another model input? | <p>I am trying to concatenate the output of a hidden layer in ResNet with the input of another model but I get the following error: </p>
<p><em>ValueError: Output tensors to a Model must be the output of a Keras <code>Layer</code> (thus holding past layer metadata)</em></p>
<p>I am using the Concatenate layer from Ke... | <p>It looks like you are missing two brackets at your concatenation layer. It should look like this:</p>
<pre><code>all_features = Concatenate()([resnet_features, model2_features])
</code></pre>
<p>Moreover, you have to make sure that the shapes of <code>resnet_features</code> and <code>model2_features</code> are the... | python|tensorflow|keras|resnet|transfer-learning | 2 |
6,798 | 54,362,545 | Calculate the average of the rows for each group | <p>I need to calculate the mean of a certain column in DataFrame, so that means for each row is calculated excluding the previous values of the row for which it's calculated in certain group. Lets assume we have this dataframe, this is the expected output </p>
<p>is there any way that like iterate each row by index, ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.expanding.html#pandas.DataFrame.expanding" rel="nofollow noreferrer"><code>expanding</code></a>:</p>
<pre><code>df2 = df.groupby('unit')['A'].expanding().mean().reset_index()
df['Expected'] = df2['A']
</code></pre> | python|python-3.x|pandas|data-science | 3 |
6,799 | 73,578,221 | Adding columns to pandas not working with Django ORM | <p>I am trying to add columns to existing pandas DataFrame. The added column gets data using Django ORM. My approaches are like the following:</p>
<p>1.</p>
<pre><code>df['name'] = User.objects.get(id=df['id'])
</code></pre>
<ol start="2">
<li></li>
</ol>
<pre><code>df['name'] = df.assign(name=lambda x: User.objects.ge... | <p>you need a <em>number</em> for the <code>id</code> field in <code>User.objects.get</code>, but <code>df['id']</code> returns a <em>pandas Series</em></p>
<p>you can do something like:</p>
<pre class="lang-py prettyprint-override"><code>df = df.assign(name=[User.objects.get(x) for x in df['id']])
</code></pre> | python|django|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.