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 |
|---|---|---|---|---|---|---|
16,100 | 73,588,420 | Adding a new row/column with a single filled element containing a sum with Pandas | <p>I have a python dataframe that looks like the excel image below. I would like to add a single cell on the bottom corner that contains the sum. I'm certain that someone else has asked this question but I can't seem to find the answer. If anyone could help me with the code needed to place that sum item in the same loc... | <p>This isn't the best way to use a pandas DataFrame but if you need to do it anyway then here is one way you can do it:</p>
<pre><code>import pandas as pd
# Create your dataframe
df = pd.DataFrame({'A': ['Jerry', 'Tom', 'Larry', 'Jill'],
'B': [5, 8, 12, 4]})
# Add empty line at the bottom
df.loc[l... | python|pandas|dataframe | 1 |
16,101 | 73,542,089 | merge json file with csv file to pandas | <p>I have a json file like</p>
<pre><code>{
"type" : "FeatureCollection",
"name" : "NBG_DATA.CBSWBI",
"features" : [
{
"type" : "Feature",
"geometry" : {
"type" : "P... | <p>First you have to load your json from a file:</p>
<pre><code>import json
with open('path/to/file.json') as fh:
json_data = json.load(fh)
</code></pre>
<p>For our sake, let's say you loaded the data and it looks like this:</p>
<pre><code>json_data = {
"type" : "Feature",
"geome... | python|json|pandas|csv | 0 |
16,102 | 71,150,328 | How to filter tensorflow dataset by value of single feature | <p>How to filter tensorflow dataset by value of single feature?</p>
<p>I spent a lot of time to understand how to filter tensorflow datasets with filter method, unfortunatelly the documentation is not clear enough for me <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#filter" rel="nofollow noreferre... | <p>You can try something like this:</p>
<pre><code>import tensorflow as tf
import pandas as pd
df = pd.DataFrame(data={'Status': ['Success', 'Failure','Failure', 'Success'], 'Cost': [0.0, 1.0, 1.0, 2.0]})
df.to_csv('data.csv', index=False)
dataset = tf.data.experimental.make_csv_dataset('/content/data.csv', batch_siz... | python|tensorflow|filter|dataset|tensorflow-datasets | 2 |
16,103 | 71,430,824 | convert whole List from Float to integer in Pandas | <p>Im new to Pandas. I have fetched some values from the database, created a dataframe and used this dataframe to create a pivot table. The problem i am facing is, that if i loop through the list, the integer values are per default floats. I want them to be integers.</p>
<p>so here is my code:</p>
<pre><code>resTable =... | <p>use <code>apply</code> and <code>pandas.to_numeric</code> to convert your values and replace <code>NaN</code> values using <code>astype(int)</code>, for example:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df=pd.DataFrame([[1.0, 1.0, 1.0],[1.0, 1.0, 1.0],[1.0, 1.0, 1.0],[None, 1.0, None]... | python|pandas|dataframe | 0 |
16,104 | 52,104,947 | Python Pandas - Cummulative Columns | <p>We have this code:</p>
<pre><code>import pandas as pd
depth = {"lastUpdateId":{"0":121305065,"1":121305065,"2":121305065,"3":121305065,"4":121305065,"5":121305065,"6":121305065,"7":121305065,"8":121305065,"9":121305065},"bids":{"0":["0.00152230","8.12000000",[]],"1":["0.00152220","15.74000000",[]],"2":["0.00152210"... | <p>Assuming <code>bids</code> and <code>asks</code> is calculated the same way, call <code>applymap</code> + <code>cumsum</code>:</p>
<pre><code>depthdf[['bids', 'asks']].applymap(
lambda x: float(x[0]) * float(x[1]) * usdprice).cumsum()
bids asks
0 86.527532 105.138166
1 254.243528 ... | python|pandas | 4 |
16,105 | 52,325,566 | Numpy returns .00...002 | <p>Sorry if this post is a dupli,I couldn't find an answer... I have the following code:</p>
<pre><code>import numpy as np
V = np.array([[6, 10, 0],
[2, 5, 0],
[0, 0, 0]])
subarr = np.array([[arr[0][0], arr[0][1]], [arr[1][0], arr[1][1]]])
det = np.linalg.det(subarr)
cross = np.cross(arr[... | <p>What you're seeing is <a href="https://docs.python.org/3/tutorial/floatingpoint.html" rel="nofollow noreferrer">floating point inaccuracies.</a></p>
<p>And in case you're wondering how you end up with floats when finding the determinant of a matrix made up of integers (where the usual calculation method is just <co... | python|numpy | 2 |
16,106 | 52,445,925 | Tensorflow 1.11 support on python 3.7? | <p>I'm hesitate to choose between downgrading to python 3.6 or installing 1.11 tensorflow.
Does anyone know if 1.11 version now support python 3.7?</p> | <p>Tensorflow 1.11 not supports Python 3.7.</p>
<p>Tensorflow supports Python 3.7 since <a href="https://github.com/tensorflow/tensorflow/releases/tag/v1.13.1" rel="nofollow noreferrer">1.13.1</a>.</p> | python|tensorflow | 1 |
16,107 | 52,257,356 | What to use to load large file and join it with the smaller one in Python? | <p>I have a large file ~5TB (> 2000 columns and 250 mln rows) and want to join it with the other file which is pretty small ~10 GB (10 columns and 20 mln rows). </p>
<p>This is my current approach in Python:</p>
<ol>
<li>Load smaller file into memory and set index. </li>
<li>Split larger file into 250 parts that eac... | <p>I would consider converting your file to file formats more efficient than CSV. You may want to consider HD5 and <a href="https://github.com/wesm/feather" rel="nofollow noreferrer">Feather</a> file formats, for example, which would give you a boost in read/write operations.
See also <a href="https://stackoverflow.com... | python|pandas|join|large-data|large-files | 0 |
16,108 | 72,552,953 | Input contains NaN, infinity or a value too large for dtype('float64') LinearRegression: but there are no empty values | <p>Originally, my input dataset had blank spaces. But I have cleaned it, and checked with:
df.isnull().sum()
And everthing is 0.
Now, after fitting my dataset into the LinearRegression model and about to make predictions, it's bringing the above error.</p> | <p>Since you did mention that the error is happening during the prediction time, I would suggest that you make the testing data go through the same pipeline as the training data.</p>
<p>For example:</p>
<p>raw training input -> preprocessing -> training input</p>
<p>It is necessary the test data also goes through... | python|pandas|numpy|data-science|linear-regression | 1 |
16,109 | 72,576,831 | 'float' object is not subscriptable in column | <p>I want to change some values on my dataframe (actually my dataframe is using pandas library). then i made a function and i was using apply to change this column. After I run it, there is appear that 'float' object is not subscriptable in column'. i'm confused right now because, before i am starting this question, th... | <p>assuming your <code>Latitude</code> column contains float values. Since you are applying the changes to a single column (<code>df['Latitude'].apply(...</code>) there's no need to do <code>x['Latitude']</code> again.
You can do:</p>
<pre><code>df['Latitude'] = df['Latitude'].apply(lambda x : true_latitude(x))
</code>... | python|pandas|function | 2 |
16,110 | 72,710,792 | Creating Pearson Correlation metrics using Tensorflow Tensor | <p>I wanted to create a pearson correlation coefficient metrics using tensorflow tensor. They do have a tensorflow probability package <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/stats/correlation" rel="nofollow noreferrer">https://www.tensorflow.org/probability/api_docs/python/tfp/stats/correla... | <p>This works fine:</p>
<pre class="lang-py prettyprint-override"><code>
from keras import backend as K
def pearson_r(y_true, y_pred):
# use smoothing for not resulting in NaN values
# pearson correlation coefficient
# https://github.com/WenYanger/Keras_Metrics
epsilon = 10e-5
x = y_true
y = y_... | tensorflow|deep-learning|metrics|tensor|pearson-correlation | 0 |
16,111 | 59,595,770 | Python3 Numpy array concatenation with stride? | <p>I have some arrays</p>
<pre><code>x = np.empty(3)
y = np.empty(3)
for i in range(len(x)):
x[i] = float(i)
y[i] = float(i + 3)
print(x, y)
</code></pre>
<p>Output ~ <code>[0., 1., 2.], [3., 4., 5.]</code></p>
<p>I would like to be able to get this instead</p>
<pre><code>[0., 3., 1., 4., 2., 5.]
</code><... | <p>You can use <code>np.stack((x, y), axis=1).ravel()</code>.</p> | python-3.x|numpy | 1 |
16,112 | 59,728,678 | How can I eliminate "unsupported operand type(s) for -: 'str' and 'str'" error as follows? | <p>When I run the following code,</p>
<pre><code>def difference(dataset, interval=1):
diff = list()
for i in range(interval, len(dataset)):
value = dataset[i] - dataset[i - interval]
diff.append(value)
return numpy.array(diff)
series = read_csv('Houston_weather.csv', header=None)
X = serie... | <p>It simply says that "you are trying to use <strong>-</strong> operator between 2 strings". You should convert them to number.</p>
<p><code>value = int(dataset[i]) - int(dataset[i - interval])</code> might help if they are integers.</p>
<p><code>value = float(dataset[i]) - float(dataset[i - interval])</code> might ... | python|pandas|numpy | 2 |
16,113 | 59,709,376 | How to convert multi-row JSON file to Dataframe | <p>I'm using an instagram scraper that outputs a multi-row JSON file and I'd like to select certain values from that file and assign them to a DataFrame.</p>
<p>When I try to use panda's pd.read_json it only saves the first level to each dataframe.</p>
<p>As an example, I'd like to have a dataframe with the first row... | <p>The following should work,</p>
<pre><code>import json
with open('ig.json') as json_file:
dct = json.load(json_file)
df = pd.io.json.json_normalize(dct, record_path="GraphImages")[["edge_media_preview_like.count", "edge_media_to_comment.count"]].rename({"edge_media_preview_like.count":"Likes", "edge_media_to_co... | python|json|pandas|dataframe | 1 |
16,114 | 40,394,910 | What do classes tf.train.Coordinator and class tf.train.QueueRunner do in tensorflow? | <p>I understand that both classes deal with threads. According to the documentation, tf.train.Coordinator coordinates the termination of a set of threads and tf.train.QueueRunner holds a list of enqueue operations for a queue, each to be run in a thread. </p>
<p>However, what is their role in simple words? When are th... | <p>QueueRunner:
When TensorFlow is reading the input, it needs to maintain multiple queues for it. The queue serves all the workers that are responsible for executing the training step. We use a queue because we want to have the inputs ready for the workers to operate on. If you don't have a queue, you will be block... | multithreading|tensorflow | 7 |
16,115 | 40,401,565 | Forcing data to fit points with curve_fit | <p>I have a little problem using the curve_fit function included in Scipy. Here is the function I would like to fit :</p>
<pre><code>def funclog(x, a, b, c, d):
return a * np.log(b * x + c) + d
</code></pre>
<p>The problem I have is that I would like the fit function to have a specific value on some points (y(min)... | <p>The requirement of the fit having specific values at <code>x=0</code>, <code>x=1</code>, implies that the parameters <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code> are constrained according to the set of two equations:</p>
<p><code>funclog(0, a, b, c, d) = 0</code>, <code>funclog(1, a, b, c, d) = 1<... | python|numpy|scipy | 1 |
16,116 | 18,656,088 | python sliding window average for letters | <p>I have a file like this:</p>
<pre><code>chr1 1 A 3
chr1 2 G 3
chr1 3 T 3
chr1 4 C 2
chr1 5 G 1
chr1 6 T 2
chr1 7 G 3
chr1 8 C 3
chr1 9 A 5
chr1 10 A 8
chr2 5 A 1
chr2 6 G 0
chr2 7 G 0
chr2 8 G 0
chr2 9 C 2
chr2 10 T 3
chr2 11 A 3
</code></pre>
<p>What I would like to do is:
setting a window size (let's say 2), mov... | <p>If I have understood what you want to do, here is one way (not optimal but works):</p>
<p>First data file <strong>file.data</strong></p>
<pre><code>chr1 1 A 3
chr1 2 G 3
chr1 3 T 3
chr1 4 C 2
chr1 5 G 1
chr1 6 T 2
chr1 7 G 3
chr1 8 C 3
chr1 9 A 5
chr1 10 A 8
chr2 5 A 1
chr2 6 G 0
chr2 7 G 0
chr2 8 G 0
chr2 9 C 2
c... | python|numpy | 1 |
16,117 | 61,873,379 | Implementing backpropagation in Convolutional layer using Numpy | <p>I'm having trouble with implementing Conv2D backpropagation using Numpy.
The shape of the input is [channels, height, width].
The shape of the filters is [n_filters, channels, height, width]
This is what I've done in forward propagation:</p>
<pre><code>ch, h, w = x.shape
Hout = (h - self.filters.shape[-2]) // self.... | <p>I managed to find a solution, the tensordot for calculating dA is taking too much time but at least it's working.</p>
<pre><code>as_strided = np.lib.stride_tricks.as_strided
F = as_strided(x,
shape=(ch_img, h_filt, w_filt, dA_h, dA_w),
strides=(x.strides[0], x.strides[1] * self.stride... | python|numpy|conv-neural-network | 0 |
16,118 | 57,885,634 | Tensorflow model fit method throws exception for dimensions | <p>I want to exercise this tensorflow tutorial about image classification <a href="https://www.tensorflow.org/tutorials/keras/basic_classification" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/keras/basic_classification</a></p>
<p>and have loaded my data into a dataset with this tutorial
<a href="htt... | <p>I just included the command</p>
<p>'''
image_label_ds= image_label_ds.batch(2)
'''</p>
<p>and it worked</p> | tensorflow|model|dataset | 0 |
16,119 | 57,771,138 | Find N largest elements in a list with a minimum distance | <p>I want to extract from a list the N largest elements, but I want that for any two elements <code>x[i]</code> and <code>x[j]</code>, <code>abs(i-j) > min_distance</code>. </p>
<p><code>scipy.signal.find_peaks(x, distance=min_distance)</code> offers this functionality. However I need to repeat this operation milli... | <p>Improving your code in python could possibly give you some improvement, but as your code seems clean and the algorithm's idea sound, I don't think you will beat <code>find_peaks</code> with a python approach.</p>
<p>Hence I suggest you write your own library in a language that is closer to the metal, and write your... | python|numpy|scipy | 1 |
16,120 | 34,208,336 | Tensorflow multivariate linear regression not converging | <p>I am trying to train a multivariate linear regression model with regularization using tensorflow. For some reason I am not able to get the training piece of the below code to calculate the error I want to use for the gradient descent update. Am I doing something wrong in setting up my graph?</p>
<pre><code>def norm... | <p>it seems indeed a problem with the learning rate: <code>0.03</code> may be too high depending on how does your data look like. Also, you probably want to create your graph separated from the session in a more explicit way, or even use the <em>normal equations</em> to reach the optimal solution without having to iter... | python|tensorflow | 2 |
16,121 | 34,368,813 | How to calculate a correlation from a list of tuples - each tuple has pair values | <p>I have a list of tuples which hold pair values in Python, for example:
[(0.2324,4),(0.8742,2), (0.11123,5)....]
I need to calculate the correlation between the paired values and the total correlation for this list.
I know about Scipy and Numpy, but I didn't find any function there to accommodate me.</p>
<p>Any Idea... | <p>Hej there,</p>
<p>I ran into the same difficulties and ended up doing this:</p>
<pre><code>from pyspark.mllib.stat import Statistics
x = result_rdd.map(lambda x: x[0])
y = result_rdd.map(lambda x: x[1])
Statistics.corr(x, y)
</code></pre>
<p>Not very efficient but it does the job.</p> | python-3.x|numpy|scipy|statistics|correlation | 0 |
16,122 | 34,173,859 | Filtering a large dataframe in pandas using multiprocessing | <p>I have a dataframe and I need to filter it according to the following conditions</p>
<pre><code>CITY == 'Mumbai' & LANGUAGE == 'English' & GENRE == 'ACTION' & count_GENRE >= 1
CITY == 'Mumbai' & LANGUAGE == 'English' & GENRE == 'ROMANCE' & count_GENRE >= 1
CITY == 'Mumbai' & LANGUA... | <p>This looks like a problem suitable for <a href="http://dask.pydata.org/en/latest/index.html#"><code>dask</code></a>, the python module that helps you deal with larger-than-memory data. </p>
<p>I will show how to solve this problem using the <code>dask.dataframe</code>. Let's start by creating some data:</p>
<pre><... | python|pandas|dataframe|nodes|traversal | 20 |
16,123 | 36,824,580 | TensorFlow, how to index so that (batch_size x num_labels)+(batch_size) -> (batch_size) | <p>Suppose I just have got a matrix (<code>2D tensor</code>) <code>X</code>, whose shape is (<code>batch_size x num_labels</code>). And the scores of labels for each sample are stored in the matrix. Now I want to extract the true labels' scores, while the true labels are stored in another <code>1D tensor</code> <code>y... | <p>I understand that X is a vector containing probabilities for each class and batch instance and that you want to get the probability of the true label. I propose on solution, though it may not be the optimal one:</p>
<pre><code># Create mask for values
increasing = tf.range(start=0, limit=tf.shape(X)[0], delta=1)
#... | python|numpy|neural-network|tensorflow | 0 |
16,124 | 54,715,835 | Numpy is installed but still getting error | <p>I am trying to run jupyter notebook and getting following error.
I am using Win 7 with anaconda python 3.7.</p>
<blockquote>
<p><code>ImportError</code>: Something is wrong with the numpy installation. While importing we detected an older version of numpy in ['c:\users\paperspace\anaconda3\envs\tensorflow10\lib\s... | <p>Run</p>
<p><code>pip3 uninstall numpy</code> </p>
<p>until you receive a message stating <code>no files available with numpy to uninstall</code> and then you can freshly install numpy using</p>
<p><code>pip install numpy</code></p>
<p>and that will fix the issue.</p> | python|numpy|tensorflow | 23 |
16,125 | 49,721,835 | Python - Pandas - Unique constraint for 'normal' column | <p>Ist there something like a unique-constraint (like in sql) for 'normal' (not-index) columns in Pandas ?</p>
<p>Thanks</p>
<p>Egirus</p> | <p>Comments from this answer makes some sense:</p>
<p><a href="https://stackoverflow.com/q/32353732/3645903">Python pandas: can I add constraints like I would in a database?</a></p>
<p>You can’t directly put constraints on the pandas data frame. However you can always put constraints programmatically before putting d... | python|python-3.x|pandas | 2 |
16,126 | 28,339,454 | python - simple way to join 2 arrays/lists based on common values | <p>I have tried for a while but can't find a simple way to join 2 lists or arrays based only on common values. Similar to an SQL inner join but with arrays/lists and not dict, or some other data type. eg.</p>
<pre><code>a = [1, 2, 3]
b = [2, 3, 4]
join(a, b)
</code></pre>
<p>prints</p>
<pre><code>[2, 3]
</code></pre... | <p>Probably a duplicate, but in case it is not:</p>
<pre><code>>>> a = [1,2,3]
>>> b = [2,3,4]
>>> list(set(a) & set(b))
[2, 3]
</code></pre>
<p>For large lists (external data), see <a href="https://stackoverflow.com/questions/14614512/merging-two-tables-with-millions-of-rows-in-python"... | python|arrays|numpy | 32 |
16,127 | 73,516,020 | Multiply pd DataFrame column with 7-digit scalar | <p>I am trying to modify a pandas dataframe column this way:</p>
<pre><code>Temporary=DF.loc[start:end].copy()
SLICE=Temporary.unstack("time").copy()
SLICE["Var"]["Jan"] = 2678400*SLICE["Var"]["Jan"]
</code></pre>
<p>However, this does not work. The resulting column SLI... | <p>Your first method might give <code>SettingWithCopyWarning</code> which basically means the changes are not made to the actual dataframe. You can use <code>.loc</code> instead:</p>
<pre><code>SLICE.loc[:,('Var', 'Jan')] = SLICE.loc[:,('Var', 'Jan')]*2678400
</code></pre> | python|pandas|dataframe|scalar | 1 |
16,128 | 35,185,187 | Can't read csv data correctly | <p>I have this code, where <code>wine.csv</code> (I added the names of columns) is data from <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data" rel="nofollow">here</a>:</p>
<pre><code>import pandas
data = pandas.read_csv("wine.csv")
df = pandas.DataFrame(data, columns=['W', 'E', 'R', '... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> with <code>url</code> address and parameter <code>names</code> for columns <code>names</code>:</p>
<pre><code>import pandas
df = pandas.read_csv("https://archive.ics.uci... | python|csv|pandas | 3 |
16,129 | 35,281,193 | Assigning numpy array based on condition | <p>What is a better way to write this numpy python code?</p>
<pre><code>age[age < 20.0] = 0.0
age[age > 0.0] = 1.0
mature = age
</code></pre>
<p>Here, mature contains 1.0 for all values of age > 20.0, else 0.0</p> | <pre><code>mature = age = (age > 20.0).astype(float)
</code></pre>
<p><code>age > 20.0</code> is a boolean array. The <code>astype(float)</code> converts the array to float dtype, which changes True to 1.0 and False to 0.0.
Note that this also converts NaNs to 0. </p>
<hr>
<p>To preserve NaNs, like your origin... | python|numpy | 4 |
16,130 | 35,261,136 | How to change line width of a pandas plot if another variable satisfies a condtition | <p>I want to plot a series of data:</p>
<pre><code>s = pd.DataFrame(np.random.randn(5,2))
ind = pd.DataFrame({'ind0':np.random.random_integers(0,1, 5), \
'ind1':np.random.random_integers(0,1, 5)})
data = pd.concat([s,ind], axis=1)
</code></pre>
<p>Where the "0" and "1" series are plot and the ... | <p>I'm not familiar with how pandas <code>DataFrame</code>s work on the small scale, but it's enough that they are compatible with numpy <code>ndarray</code>s. So I'll assume that you have the latter, as my point is just that you should mask your values based on the variables <code>ind0</code> and <code>ind1</code>. I ... | python|pandas|matplotlib|series | 1 |
16,131 | 30,997,007 | Pandas DataFrame: Delete specific date in all leap years | <p>The following sequence is an extract of the pandas DataFrame that I've got:</p>
<pre><code>>>> df_t
value
2011-01-31 -5.575000
2011-03-31 7.700000
2011-05-31 15.966667
2011-07-31 10.683333
2011-08-31 10.454167
2011-10-31 9.320833
2011-12-31 -0.358333
2012-01-31 -11.55... | <p>Here is an example to do that in a vectorized way. You shall note that <code>and</code> and <code>or</code> are not appropriate for a vector of booleans, use <code>&</code> and <code>|</code> instead.</p>
<pre><code>import pandas as pd
import numpy as np
s = pd.Series(np.random.randn(600), index=pd.date_range(... | python|select|pandas|leap-year | 2 |
16,132 | 67,375,000 | how to create an augmented dataset in pythorch | <p>I have to add to the original CIFAR dataset, for each image, the corrispondent ones, rotated by 90 deg. The idea is to create the a RotationDateset, a class which extends datasets.VisionDataset, which takes the CIFAR and does what describes above.</p>
<pre class="lang-py prettyprint-override"><code>from __future__ i... | <p>the issue comes from your relying on <code>org_dataset.data</code>, which is a numpy array of shape <code>(N, 32, 32, 3)</code> (where you would like it to be <code>(N, 3, 32, 32)</code>)</p>
<p>So with the line <code>self.targets.append(k)</code>, you put incorrect shapes in your targets list. Then, the tensor <cod... | pytorch|image-rotation|torchvision|image-augmentation | 0 |
16,133 | 67,267,959 | How to find outliers within groups in a dataframe | <p>I have a df which looks like the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Group.</th>
<th>Score.</th>
</tr>
</thead>
<tbody>
<tr>
<td>red</td>
<td>34</td>
</tr>
<tr>
<td>blue</td>
<td>42</td>
</tr>
<tr>
<td>green</td>
<td>1000</td>
</tr>
<tr>
<td>green</td>
<td>34</td>
... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>df["is_outlier"] = df.groupby("Group.").transform(lambda x: (x -... | python|pandas|statistics|outliers | 3 |
16,134 | 34,871,128 | Pandas dropna does not work as expected on a MultiIndex | <p>I have a Pandas DataFrame with a multiIndex. The index consists of a date and a text string. Some of the values are NaN and when I use dropna(), the row disappears as expected. However, when I look at the index using df.index, the dropped dates are still there. This is problematic as when I use the to_panel function... | <p>I think it is issue <a href="https://github.com/pydata/pandas/issues/2770" rel="nofollow">2770</a>.</p>
<p>And solution is decribe <a href="https://github.com/pydata/pandas/issues/2770#issuecomment-76500001" rel="nofollow">here</a>.</p>
<pre><code>index.get_level_values(level)
</code></pre> | python|pandas | 1 |
16,135 | 34,770,389 | Sort a Numpy Python matrix progressively according to rows | <p>I have searched around and tried to find a solution to what seems to be a simple problem, but have come up with nothing. The problem is to sort a matrix based on its columns, progressively. So, if I have a numpy matrix like:</p>
<pre><code>import numpy as np
X=np.matrix([[0,0,1,2],[0,0,1,1],[0,0,0,4],[0,0,0,3],[0,1... | <p>It's not going to be particularly fast, but you can always convert your rows to tuples, then use Python's sort:</p>
<pre><code>np.matrix(sorted(map(tuple, X.A)))
</code></pre>
<p>You can also use <code>np.lexsort</code>, as suggested in <a href="https://stackoverflow.com/a/26036376/10601">this answer</a> to a <a h... | python|sorting|numpy|matrix | 2 |
16,136 | 60,049,685 | Python Passing Dynamic Table Name in For Loop | <pre><code>table_name = []
counter=0
for year in ['2017', '2018', '2019']:
table_name.append(f'temp_df_{year}')
print(table_name[counter])
table_name[counter] = pd.merge(table1, table2.loc[table2.loc[:, 'year'] == year, :], left_on='col1', right_on='col1', how='left')
counter += 1
temp_df_2017
</code><... | <p>I think the easiest/most practical approach would be to create a dictionary to store names/df.</p>
<pre><code>import pandas as pd
import numpy as np
# Create dummy data
data = np.arange(9).reshape(3,3)
df = pd.DataFrame(data, columns=['a', 'b', 'c'])
df
Out:
a b c
0 0 1 2
1 3 4 5
2 6 7 8... | python-3.x|pandas | 1 |
16,137 | 60,076,239 | Pandas: Filter rows by comparing a column's value to another value for the same column in a different row | <p>I have searched the heck out of this one, and I don't think I've found anything applicable. But I'm new to Pandas, so I may have missed something-apologies in this case. </p>
<p>Suppose I have a dataframe, df, with the following contents:</p>
<pre><code>Column1 Column2
A Apple
B ... | <p>You can use a groupby and filter:</p>
<pre><code>(
df.groupby('Column2')
.filter(lambda x: len(x.drop_duplicates(subset='Column1'))>1)
)
Column1 Column2
0 A Apple
1 B Apple
3 A Orange
4 B Orange
</code></pre> | pandas | 1 |
16,138 | 65,466,318 | How to use or command in pandas to categorize my Data | <p>I think it might be a noob question, but I'm new to coding. I used the following code to categorize my data. But I need to command that if, e.g., not all my conditions together fulfill the categories terms, e.g., consider only 4 out of 7 conditions, and give me the mentioned category. How can I do it? I really appre... | <p>Let`s say this is your dataframe:</p>
<pre><code> Stroage Condition refrigerate Profit Per Unit Inventory Qty
0 0 1 0 20
1 1 1 102 1
2 2 2 5 2
3 ... | python|pandas | 0 |
16,139 | 65,395,336 | UnimplementedError with Neural Network Using Linear Regression and Tensorflow2 | <p>I'm just working through my own sandbox project wanting to try and implement NLP but with a linear regression as an outcome. As reference, the dataset I am working with comes <a href="https://www.kaggle.com/zynicide/wine-reviews" rel="nofollow noreferrer">Kaggle wine-reviews</a> which has the wine reviews and a corr... | <p>From comments</p>
<blockquote>
<p>Passing <code>X</code> to <code>model.fit</code>, which literally has string values, a neural
network cannot be input string values (paraphrased from Dr. Snoopy)</p>
</blockquote> | python|tensorflow|neural-network|nlp|word-embedding | 1 |
16,140 | 65,452,953 | Summing a column based on a condition in another column in a pandas data frame | <p>I just started using Python and I am trying to create programs to help monitor some of my investments. Right now I have a definition set up that will give me my current returns based on my initial buy price and the current price. Here is what my data frame looks like:</p>
<pre><code> Ticker Expiration Contra... | <p>You can use list comprehension to filter for <code>notnull()</code> rows by column and do the calculation per column. To only apply to the columns with <code>Prem</code> in them, I create a <code>cols</code> index object so we can dynamically apply changes to those indexed columns:</p>
<pre><code>cols = df.columns[d... | python|pandas|dataframe | 1 |
16,141 | 65,099,156 | Eliminating array rows that fail to meet two conditions | <p>Consider arrays m and n. Both have identical shapes. m and n always have an even number of columns, and I have added spaces to emphasize that each array row is made up of <strong>PAIRS</strong> of elements.</p>
<pre><code>import numpy as np
m = np.array([[5,3, 6,7, 3,8],
[5,4, 5,1, 4,5],
... | <p>Here is a vectorized solution for the above 2 tests you mention. I have modified the code a bit for test1 as well so that it flows nicely into test2.</p>
<pre><code>import numpy as np
m = np.array([[5,3, 6,7, 3,7],
[5,4, 5,1, 4,5],
[5,4, 2,4, 4,6],
[2,2, 2,3, 8,5],
... | python|arrays|numpy | 1 |
16,142 | 65,452,435 | Return count of 1's preceding 0's for each group and each zero within group | <p>i work on a big data file (10 millions rows), here is the two columns i care about for now:</p>
<pre><code>| id | v1 |
| 101 | 0 |
| 101 | 0 |
| 101 | 1 |
| 101 | 0 |
| 101 | 1 |
| 101 | 1 |
... | <p>The goal below is to create groups, which you can do by grouping all <code>0</code> and preceding <code>1</code> values into a "subgroup" and take the <code>size() - 1</code> (minus 1 to subtract the counting of each zero in each subgroup):</p>
<pre><code>z = df1['v1'].eq(0) # return True for values equal ... | python|pandas|dataframe | 1 |
16,143 | 64,076,869 | Get average of columns in pandas based on particular rows | <p>I have a data that stores % change in value for stocks over one day, month, three months and year.</p>
<pre><code>ID daychange monthchange trimonthchange yearchange
UNITY 0.001666 0.398450 0.411581 0.689139
SSOM -0.033359 0.040816 1.174840 3.047619
PNSC -0.004953 -0.053006... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html#pandas.DataFrame.loc" rel="nofollow noreferrer">loc</a> to access a group of rows by label (<code>ID</code> column) and then calculate the mean for each time period column using <code>axis=0</code>. Create a <code>Serie... | python|pandas|dataframe|average | 1 |
16,144 | 63,857,428 | Python Pandas apply function with series data as argument | <p>I am using apply function to process name1 column. I can pass in a fix value like 8 into the function but I wish to use the value (num_of_bit) from each row to process name1 column. When I use the code as below, I will get the error. I understand why I got this error but I do not know how to achieve what I want.</p>... | <p>If I understand the question correctly and you need to change the 'name1' value by the applying the function, where the 'range_type' is 'SIGNED', then you are not passing the 'num_of_bit' to apply, so it tries to use the whole column for each row. I suggest using a lambda function:</p>
<pre><code>out_df.loc['name1']... | python|pandas|apply | 1 |
16,145 | 64,132,738 | Faulty correlation | <p>I'm new to python and pandas/matplotlib. I'm trying to calculate the correlation between two closing stock prices of Disney and Netflix (as an example), but not sure if I've done it correctly? When I output my data as seen in the picture below, it looks weird and not as I expected (since I expected it to be one row ... | <p>If you just want just the correlation between two columns, you can use buit-in <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html" rel="nofollow noreferrer"><code>pearsonr</code></a> module in <code>scipy</code>, which returns <strong>Pearson correlation</strong> and the <strong>... | python|pandas|matplotlib | 3 |
16,146 | 64,110,340 | Count number of times each item in list occurs in a pandas dataframe column with comma separates values with additional aggregation of other columns | <p>I have a list :</p>
<pre><code>citylist = ['New York', 'San Francisco', 'Los Angeles', 'Chicago', 'Miami']
</code></pre>
<p>and a pandas Dataframe df1 with these values</p>
<pre><code>first last city email duration
John Travis New York ... | <ol>
<li>You can explode the dataframe on the <code>city</code> column</li>
<li>Then groupby <code>city</code> and use <code>.agg</code> for some of the calculations.</li>
<li>For the <code>%time</code>, you can create a variable <code>var</code> in the beginning that gets the sum total of the <code>duration</code> col... | python|pandas|dataframe|aggregation | 1 |
16,147 | 46,907,881 | How to set class_weight in keras package of R? | <p>I am using <code>keras</code> package in R to train a deep learning model. My data set is highly imbalanced. Therefore, I want to set <code>class_weight</code> argument in the <code>fit</code> function. Here is the fit function and its arguments that I used for my model</p>
<pre><code>history <- model %>% fit... | <p>Class_weight needs to be a list, so </p>
<pre><code> history <- model %>% fit(
trainData, trainClass,
epochs = 5, batch_size = 1000,
class_weight = list("0"=1,"1"=30),
validation_split = 0.2
)
</code></pre>
<p>seems to work. Keras internally uses a function called as_... | r|tensorflow|deep-learning|keras | 15 |
16,148 | 46,924,891 | How to fit 2-D function if some of the data points are NaNs? | <p>I am trying to fit a 2-D surface to a data. More specifically, I want to find a function which maps pixel coordinate to wavelength coordinate, just as <code>FITCOORDS</code> in IRAF does.</p>
<p>As an example, I want to find the fit to <code>test</code> array in the following snippet:</p>
<pre><code>import numpy a... | <p>You can simply remove the <code>nan</code>s in your data and the corresponding "indices" of your grid. For example with <a href="https://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow noreferrer">boolean indexing</a>:</p>
<pre><code>notnans = np.isfinite(test) # arra... | python|numpy|missing-data|astropy|model-fitting | 5 |
16,149 | 63,109,611 | `Einsum is not implemented` error when convert onnx model to .pb model? | <p>I am trying to convert onnx model to TensorFlow's .pb model. But when I do the <code>prepare</code> function, I got this error: <code>NotImplementedError: Einsum is not implemented.</code>
Are there some suggestions to solve this problem? Thanks!</p>
<p>By the way, here are the code I use to convert the model:</p>
<... | <p>I have solved this by changing <code>torch.einsum</code> to the correlated matrix multiplication :)</p> | tensorflow|onnx | 0 |
16,150 | 63,294,563 | Is it possible to write an Excel Pivot Table object from pandas? | <p>I'm replacing a lot of my Excel workload with pandas. I need to generate a standard Excel Pivot Table object (with the interactive UI such that users can define filters as they see fit). I'm not too well versed in pandas.pivot_table(), but before digging in want to know if this is possible.
For example, given this D... | <p>A user interface could easily be built for a pivot table.</p>
<pre><code>import pandas as pd
data = {'name': ['George', 'Maria', 'Andrew', 'Wyatt', 'Celeste', 'Peter'],
'year': [1987, 1987, 1992, 1994, 1987, 1992],
'color': ['Red', 'Orange', 'Blue', 'Red', 'Blue', 'Blue']}
df = pd.DataFrame(data)
#... | python|excel|pandas|pivot-table | 1 |
16,151 | 67,994,630 | “Offset” function for python index | <p>I’m a beginner with Python coming from VBA. I’m wondering if there is a way to perform a similar function from vba as range(2,4).offset(5,) within Python? I am finding the iloc of a column and need to move from the found row down x “cells” or index. Not really sure what it’s called in Python yet. I can provide a cod... | <p>As Jonathan has mentioned df.iloc[foundindex,column].idxmax()+(neededoffset)) is ultimately what solved my issue. Thanks for the help!</p> | python|pandas|numpy|indexing|offset | 0 |
16,152 | 67,958,944 | Apply calculation to data occuring before current row in Pandas Groupby | <p>I have the following dataframe:</p>
<pre><code>import pandas as pd
#Create DF
d = {
'Date': ['1/01/2021','2/01/2021','3/01/2021','4/01/2021','5/01/2021','6/01/2021','7/01/2021','8/01/2021','9/01/2021','10/01/2021','11/01/2021','12/01/2021','13/01/2021',
'14/01/2021','15/01/2021','16/01/2021'],
'Name': ['Jo... | <p>Basically you could just execute the groupby on a subset of the dataframe instead of applying it over the whole dataframe.</p>
<p>Since you have a <code>Date</code>column which contains the observation date for each data point, you could basically create your subset based on this column.</p>
<p>Say you have a <code>... | python|pandas | 1 |
16,153 | 31,762,556 | remove items with low frequency | <p>Let's consider the array of length <code>n</code>:</p>
<pre><code>y=np.array([1,1,1,1,2,2,2,3,3,3,3,3,2,2,2,2,1,4,1,1,1])
</code></pre>
<p>and the matrix <code>X</code> of size <code>n</code> x <code>m</code>.</p>
<p>I want to remove items of <code>y</code> and rows of <code>X</code>, for which the corresponding ... | <p>You can use an additional output parameter <code>return_inverse</code> in <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique</code></a> like so -</p>
<pre><code>def unique_where(y):
_, idx, count = np.unique(y, return_inverse=True,return_cou... | python|numpy | 3 |
16,154 | 32,051,256 | Pandas dataframe from series of series | <p>I have a pandas series of series, like so:</p>
<pre><code>series_list = [pd.Series([1,2], index = ['A', 'B']), pd.Series([3,4], index = ['A', 'B'])]
data = pd.Series(series_list, index = ['i', 'ii'])
</code></pre>
<p>I would like to turn this data into a dataframe, using one index as the dataframe's column index, ... | <p>Strict approach works fine:</p>
<pre><code>pd.DataFrame(series_list,index = ['i', 'ii'])
</code></pre> | python|pandas | 1 |
16,155 | 41,245,349 | Numpy array indexing behavior | <p>I was playing with numpy array indexing and find this odd behavior. When I index with <code>np.array</code> or <code>list</code> it works as expected: </p>
<pre><code> In[1]: arr = np.arange(10).reshape(5,2)
arr[ [1, 1] ]
Out[1]: array([[2, 3],
[2, 3]])
</code></pre>
<p>But when I put <code... | <p>What's happening is called fancy indexing, or <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">advanced indexing</a>. There's a difference between indexing with slices, or with a list/array. The trick is that multidimensional indexing actually works... | python|numpy|indexing | 3 |
16,156 | 41,644,920 | dropped column in pandas reappearing | <p>I am trying to convert a pandas dataframe to a recarray after dropping a column. The original data has 33 columns and after dropping column 'a', I am left with 32 columns as expected. However, after calling to_records() on the dataframe, the original column has been reinserted with blank values. Is there a way to pr... | <p>You are dropping the column as expected but you have to assign the new data frame to your original data frame so it's overwritten.
So,</p>
<pre><code>dat=dat.drop(['a'], axis=1, inplace=true)
</code></pre>
<p>That's it </p> | python|python-3.x|pandas | 3 |
16,157 | 61,542,946 | Removing whitespaces from a string based on a condition | <p>I'm looking for help in splitting my data. My data has spaces as thousand separators but there's also spaces between my timestamps.</p>
<p>This is an example of what the data looks like (this is currently 1 column):</p>
<pre><code>Date/Time Var1 Var2 Var3 Var4 Var5 Var6
17/04/2020 00:00:00 133 579.20 31 978.90 377... | <p>Assuming <code>df</code> is your present dataframe and it has one column named simply <code>'D'</code> (if it is not <code>'D'</code>, change accordingly):</p>
<pre><code>tmplist = df['D'].str.findall(r'(.+?[:.]\S+\s+)').to_list()
tmplist = [ [ e.replace(' ','') if i>0 else e.rstrip() for i, e in enumerate(row) ... | python|pandas|whitespace|strip | 2 |
16,158 | 61,216,840 | Combining Pandas Dataframe with Numpy Arrays | <p>I have an array of arrays that I want to combine with a data frame.</p>
<pre><code>arrays=[np.array(i) for i in [[1,2],[5,6,7],[]]] #let me illustrate the arrays like this
df=pd.DataFrame({'Col':['x','y','z']})
</code></pre>
<p>Each array element corresponds to a row in the df.
This is my desired output:</p>
<p... | <p>You could do the following:</p>
<pre><code>import numpy as np
import pandas as pd
from itertools import product
arrays = [np.array(i) for i in [[1, 2], [5, 6, 7], []]]
df = pd.DataFrame({'Col': ['x', 'y', 'z']})
# this creates a mesh (cross-product) Dataframe
mesh = pd.DataFrame([pair for co in zip(df['Col'], arr... | python|pandas|numpy | 1 |
16,159 | 61,529,748 | Pandas to compare a column with list object with another column containing int | <p>I have below panads dataframe where I want to compare between a list object(name in a list) of a column with an integer value in another column.</p>
<h2>Dataframe construct:</h2>
<pre><code>+------------+-----------------------+----------------------+-----------------+--------------------+------------+---------+
|... | <p>Just for the sake of posterity, we need to use boolean indexing...</p>
<h2>Boolean indexing:</h2>
<p>Another common operation is the use of boolean vectors to filter the data. The operators are: <code>|</code> for or, <code>&</code> for and, and <code>~</code> for not. These must be grouped by using parenthese... | python|python-3.x|pandas|operators | 0 |
16,160 | 68,489,193 | How to cut dataset into X and Y parameters | <p>I have a time-series dataset that consists of evenly spaced timesteps and another parameter (say volume). I want to cut/split the dataset into X and Y parameters to train my ML model. I am looking for a logic/algorithm for Python that will be useful in tacking the simplified version below.</p>
<p>I have an array of ... | <p>A very simple way to get all the values of <code>X</code> is to create a sliding window view into <code>array</code>. You can do this directly with <a href="https://numpy.org/devdocs/reference/generated/numpy.lib.stride_tricks.sliding_window_view.html" rel="nofollow noreferrer"><code>np.lib.stride_tricks.sliding_win... | python|arrays|python-3.x|algorithm|numpy | 3 |
16,161 | 36,456,320 | Access DataFrame object in DataFrame method call | <p>Instead of using the name of the dataframe object I am calling the method on, is there a shorthand name for it?
Eg., Suppose I want to do something like</p>
<pre><code> long_data_frame_name.long_column_name.fillna(long_data_frame_name.long_column_name.mean())
</code></pre>
<p>I'd like to be able to shorten this ... | <p>No, but you can create a shorthand reference beforehand. For example:</p>
<pre><code>ldfn = long_data_frame_name.long_column_name
</code></pre>
<p>and then do:</p>
<pre><code>ldfn.fillna(ldfn.mean(), inplace=True)
</code></pre>
<p>The <code>inplace=True</code> is required, because otherwise <code>.fillna</code> ... | python|r|pandas|dataframe | 1 |
16,162 | 5,284,646 | Rank items in an array using Python/NumPy, without sorting array twice | <p>I have an array of numbers and I'd like to create another array that represents the rank of each item in the first array. I'm using Python and NumPy.</p>
<p>For example:</p>
<pre><code>array = [4,2,7,1]
ranks = [2,1,3,0]
</code></pre>
<p>Here's the best method I've come up with:</p>
<pre><code>array = numpy.arr... | <p>Use argsort twice, first to obtain the order of the array, then to obtain ranking:</p>
<pre><code>array = numpy.array([4,2,7,1])
order = array.argsort()
ranks = order.argsort()
</code></pre>
<p>When dealing with 2D (or higher dimensional) arrays, be sure to pass an axis argument to argsort to order over the correc... | python|sorting|numpy | 126 |
16,163 | 53,082,545 | Write the output to same output Excel File | <p>I am doing web scraping and I am writing the output of data frames to a new Excel workbook every day. I want to add the output of each day to already existing excel file and I have no idea of how to do so. Can anyone please help me with`` this!!!</p>
<pre><code>writer = pd.ExcelWriter('output'+dte.strftime("%Y-%m-%... | <p>Use <code>openpyxl</code>:</p>
<p>Suppose you have an existing <code>excel file-- 'output'+dte.strftime("%Y-%m-%d")+'.xlsx'</code> with Sheet name <code>Sheet1</code>. You can do something like this:</p>
<pre><code>from openpyxl import load_workbook
book = load_workbook('output'+dte.strftime("%Y-%m-%d")+'.xlsx')
... | python|excel|python-3.x|pandas | 0 |
16,164 | 53,048,513 | Getting low, high, and mean from column | <p>I am trying to get the low, high and mean from a column. However, I'd like to only aggregate by the column value. For example, if we have 2 rows with the same column value, then we aggregate these two together. Also, they have to be of the same carrier. Something like this:</p>
<p>Before processing:</p>
<pre><code... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a> with list of tuples foe new columns names with aggregate function and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas... | python|pandas | 3 |
16,165 | 53,102,594 | how to load csv file data into pandas using request.FILES(django 1.11) without saving file on server | <p>i just want to upload .csv file via form, directly in to pandas dataframe in django without saving physically file on to server. </p>
<pre><code>def post(self, request, format=None):
try:
from io import StringIO, BytesIO
import io
print("data===",request.FILES['file']... | <p>You can use <strong>StringIO</strong> for reading and decoding your <code>csv</code> :</p>
<pre class="lang-py prettyprint-override"><code>import csv
from io import StringIO
csv_file = request.FILES["csv_file"]
content = StringIO(csv_file.read().decode('utf-8'))
reader = csv.reader(content)
</code></pre>... | django|python-3.x|pandas|csv | 0 |
16,166 | 65,507,784 | Pytorch, standard layer to convert sequential output to binary? | <p>I am working on a new Pytorch model which takes sequential data as input and I need to output just a single value, which I will then use a binary cross-entropy function to evaluate as a probability of 1 or 0.</p>
<p>To be more concrete, lets say my sequence is 1000 time steps and only 2 dimensions, like a 2-dimensio... | <p>I think this <a href="https://openreview.net/pdf?id=YicbFdNTTy" rel="nofollow noreferrer">paper</a> does what you wanted :) (Probably not the first paper that does this but it is the one that I recently read)</p>
<ol>
<li>Prepend an extra token to your sequence. The token can have a learnable embedding.</li>
<li>Aft... | python|neural-network|pytorch|sequential|transformer-model | 1 |
16,167 | 65,514,184 | Keras checkpoints not being saved to google cloud bucket | <p>I'm using the following code to save checkpoints while a google cloud build runs my model:</p>
<pre><code> cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath = "gs://mybucket/checkpoints",
verbose=0,
... | <p>I was having this problem for several reasons:</p>
<ul>
<li>Dataset was not on the storage bucket, and so the code had no access to it.</li>
<li>Use of generator for dataset without files creates an infinite loop, but no crash.</li>
</ul>
<p>I switched to AI Platform and sourced my data from the GCS Bucket and the p... | tensorflow|google-cloud-storage|google-cloud-build | 0 |
16,168 | 65,623,519 | Pandas : want to explode data based on start and end date | <p>i want to explode dataframe based on start and end data. It should be in an interval of 10 days or last number of days for each month. For example, my input dataframe looks like :</p>
<p>df</p>
<pre><code>id,start_date,end_date,points
1,2020-01-01,2020-01-20,100
2,2020-01-11,2020-02-10,200
3,2020-04-21,2020-05-10,30... | <p>This can be quite tricky. First of all, I assume your data is indexed by the <code>id</code> column, if it's not, you can do it easily with:</p>
<pre><code>df.set_index("id", inplace = True)
</code></pre>
<p>Also, make sure to use <code>datetime</code> columns:</p>
<pre><code>df["start_date"] = p... | python|python-3.x|pandas|dataframe | 2 |
16,169 | 2,483,696 | undo or reverse argsort(), python | <p>Given an array 'a' I would like to sort the array by columns <code>sort(a, axis=0)</code> do some stuff to the array and then undo the sort. By that I don't mean re sort but basically reversing how each element was moved. I assume <code>argsort()</code> is what I need but it is not clear to me how to sort an array w... | <p>There are probably better solutions to the problem you are actually trying to solve than this (performing an argsort usually precludes the need to actually sort), but here you go:</p>
<pre><code>>>> import numpy as np
>>> a = np.random.randint(0,10,10)
>>> aa = np.argsort(a)
>>> ... | python|arrays|sorting|numpy | 71 |
16,170 | 63,368,128 | how to plot pie chart in python based on two features in my dataset | <p>I have data set that count the default of credit card, the dataset have information about male and female and if they are default 0 or 1</p>
<p>I want to plot a pie chart of all default = 0 and how percent of male and how percent of female</p>
<p>also I want to print the percentage of the value of the total number ... | <p>Check with</p>
<pre><code>df.loc[df['default']==0,'gender'].value_counts().plot(kind='pie',autopct='%1.1f%%')
</code></pre> | python|pandas|matplotlib | 0 |
16,171 | 63,600,157 | TypeError in pandas Dateframe with 'datetime.date' | <p>I'm new to pandas and I would like to create a DataFrame for each weekday based on a bigger DataFrame with all kind of dates.</p>
<p>I read my initial data from a csv with the method <code>data = pd.read_csv()</code> and then my "Timestamp" column is set to datetime this way : <code>data["Timestamp&qu... | <p>Here is a way to add a column with the name of the weekday. This approach uses the <code>.dt</code> date accessor, and operates on the series, which is fast.</p>
<pre><code>import pandas as pd
n = 8
t = pd.DataFrame({'x': [*range(n)],
'Timestamp': pd.date_range(start='2020-01-01', periods=n, fre... | python|pandas|dataframe|datetime | 1 |
16,172 | 63,589,340 | How to append a dataframe to another dataframe when indexes are not existed, fill the nan values when they do? | <p>Firstly, I have an empty dataframe <code>df</code> with two columns <code>['A','B']</code> and two series <code>s1, s2</code> which have the same index, What I want to do is to append two series to the dataframe in two steps:
At first, it's empty</p>
<pre><code> A B
</code></pre>
<p>Two series are:</p>
<pre><code>... | <p>You should use an outer join :</p>
<pre class="lang-py prettyprint-override"><code>df = s1.to_frame(name = 'A').join(s2.to_frame(name='B'), how='outer')
</code></pre>
<p>See comment on <a href="https://stackoverflow.com/a/35616082/9892619">this post</a></p> | python|pandas | 0 |
16,173 | 24,767,627 | Fastest way to get bounding boxes around segments in a label map | <p>A 3D label map is matrix in which every pixel (voxel) has an integer label. These values are expected to be contiguous, meaning that a segment with label <code>k</code> will not be fragmented.</p>
<p><strong>Given such label map (segmentation), what is the fastest way to obtain the coordinates of a minimum bounding... | <p>If I understood your problem correctly, you have groups of voxels, and you would like to have the extremes of a group in each axis.</p>
<p>Let'd define:</p>
<ul>
<li><p><code>arr</code>: 3D array of integer labels</p></li>
<li><p><code>labels</code>: list of labels (integers 0..labmax)</p></li>
</ul>
<p>The code:... | python|performance|algorithm|numpy | 4 |
16,174 | 53,675,972 | Is there a way to go through rows in a pandas data frame more efficiently? | <p>I have a huge pandas data frame where each row corresponds to a single sports match. It looks like the following:</p>
<p>**EDIT: I'll change the example code to better reflect the actual data:
This made me realize the presence of values other than 'lost' or 'won' makes this a lot more difficult.</p>
<pre><code>d =... | <p>IIUC, <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a></p>
<pre><code>d... | python|pandas | 2 |
16,175 | 72,113,294 | Linear Projection of a 2D Matrix to a Vector in Pytorch | <p>My problem is that I want to apply a linear projection, followed by batch normalization and ReLU but I don't know pytorch good enough to apply it.</p>
<p>My input data are features for 1024 datapoints with dimension 10x10 so (16, 1024, 10, 10) while 16 is the batch size.
I want to project that 10x10 feature Matrix t... | <p><code>torch.bmm</code> <a href="https://pytorch.org/docs/stable/generated/torch.bmm.html" rel="nofollow noreferrer">only supports 3D inputs</a>. It would be nice if the functionality was extended to further broadcasting dimensions but currently this isn't the case. Since you are reducing the dimension eventually, yo... | pytorch | 0 |
16,176 | 71,795,377 | Data Grouping with Pandas | <p>I have a data frame</p>
<pre><code>Name Subset Type System
A00 IU00-A OP A
A00 IT00 PP A
B01 IT-01A PP B
B01 IU OP B
B03 IM-09-B LP A
B03 IM03A OP A
B03 IT-09 OP A
D09 IT OP A
D09 IM LP ... | <p>Double <code>groupby</code> where we first group by "Name", then again by "Subset Cluster" and "Type Cluster" does the trick:</p>
<pre><code>out = df.assign(**{'Subset Cluster': df['Subset'].str.extractall(r'[^a-zA-Z]*([a-zA-Z]+)[^,]*')\
... | python|python-3.x|pandas|pandas-groupby | 3 |
16,177 | 17,743,870 | Calculate Similarity of Sparse Matrix | <p>I am using Python with numpy, scipy and scikit-learn module.</p>
<p>I'd like to classify the arrays in very big sparse matrix. (100,000 * 100,000)</p>
<p>The values in the matrix are equal to 0 or 1. The only thing I have is the index of value = 1.</p>
<pre><code>a = [1,3,5,7,9]
b = [2,4,6,8,10]
</code></pre>
<... | <p>If you choose the sparse <code>coo_matrix</code> you can create it passing the indices like:</p>
<pre><code>from scipy.sparse import coo_matrix
import scipy
nrows = 100000
ncols = 100000
row = scipy.array([1,3,5,7,9])
col = scipy.array([2,4,6,8,10])
values = scipy.ones(col.size)
m = coo_matrix((values, (row,col)), ... | python|numpy|scipy|classification|sparse-matrix | 4 |
16,178 | 17,688,155 | Complicated (for me) reshaping from wide to long in Pandas | <p>Individuals (indexed from 0 to 5) choose between two locations: A and B.
My data has a wide format containing characteristics that vary by individual (ind_var) and characteristics that vary only by location (location_var).</p>
<p>For example, I have:</p>
<pre><code>In [281]:
df_reshape_test = pd.DataFrame( {'loca... | <p>In fact, pandas has a <code>wide_to_long</code> command that can conveniently do what you intend to do. </p>
<pre><code>df = pd.DataFrame( {'location' : ['A', 'A', 'A', 'B', 'B', 'B'],
'dist_to_A' : [0, 0, 0, 50, 50, 50],
'dist_to_B' : [50, 50, 50, 0, 0, 0],
'locat... | python|pandas|reshape | 6 |
16,179 | 8,385,602 | Why are NumPy arrays so fast? | <p>I just changed a program I am writing to hold my data as numpy arrays as I was having performance issues, and the difference was incredible. It originally took 30 minutes to run and now takes 2.5 seconds!</p>
<p>I was wondering how it does it. I assume it is that the because it removes the need for <code>for</code>... | <p>Numpy arrays are densely packed arrays of homogeneous type. Python lists, by contrast, are arrays of pointers to objects, even when all of them are of the same type. So, you get the benefits of <a href="https://en.wikipedia.org/wiki/Locality_of_reference">locality of reference</a>.</p>
<p>Also, many Numpy operation... | python|arrays|numpy | 119 |
16,180 | 55,457,194 | How to group by values but keep data structure? | <p>I have a dataset which contains a list of units (stores) selling a system with sales and units for every week. I have grouped them into a test and control group as a new column.</p>
<p>What I want to do now is to use these new groups in the dataset, as I want to plot them against each other for all the weeks. </p>
... | <p>let's play:</p>
<pre><code>import pandas as pd
df = pd.read_table('c:/4/AAA.txt', sep=',')
df.head(10)
df.groupby(['Week','Sales']).sum().sort_values('Sales')
df[(df['Sales']>30000)&(df['Year']==2019)].sort_values('Sales')
df[df['System_Type']=='Component2'].groupby('Sales').filter(lambda x: len(x)<2500... | python|python-3.x|pandas|pandas-groupby | 0 |
16,181 | 55,206,169 | Optimization of numpy mesh creation for efficient interpolation | <p>I am reading magnetic field data from a text file. My goal is to correctly and efficiently load the mesh points (in 3 dimensions) and the associated fields (for simplicity I will assume below that I have a scalar field).</p>
<p>I managed to make it work, however I feel that some steps might not be necessary. In par... | <p>Here's one with <code>broadcasted-assignment</code> to generate <code>data</code> directly from <code>x,y,z</code> and hence avoid the memory overhead of creating all the mesh-grids and hopefully lead to better performance -</p>
<pre><code>m,n,r = len(x),len(y),len(z)
out = np.empty((m,n,r,4))
out[...,0] = x[:,Non... | python|numpy|scipy | 1 |
16,182 | 9,830,620 | Efficient way of taking Logarithm function in a sparse matrix | <p>I have a big sparse matrix. I want to take <code>log4</code> for all element in that sparse matrix. </p>
<p>I try to use <code>numpy.log()</code> but it doesn't work with matrices. </p>
<p>I can also take logarithm row by row. Then I crush old row with a new one.</p>
<pre><code># Assume A is a sparse matrix (Link... | <p>You can modify the <code>data</code> attribute directly:</p>
<pre><code>>>> a = np.array([[5,0,0,0,0,0,0],[0,0,0,0,2,0,0]])
>>> coo = coo_matrix(a)
>>> coo.data
array([5, 2])
>>> coo.data = np.log(coo.data)
>>> coo.data
array([ 1.60943791, 0.69314718])
>>> coo.... | python|matrix|numpy|scipy|sparse-matrix | 9 |
16,183 | 56,650,656 | Resampling a dataframe into a new one while doing some additional operations | <p>I am working with a dataframe where each entry (row) comes with a start time, a duration and other attributes. I would like to create a new dataframe from this one where I would sort of transform each entry from the original one into 15 minutes intervals while keeping all other attributes the same. The amount of ent... | <p>So, starting with your df:</p>
<pre><code>testdict = {'start':['2018-01-05 11:48:00', '2018-05-04 09:05:00', '2018-08-09 07:15:00', '2018-09-27 15:00:00'], 'duration':[22,8,35,2], 'Attribute_A':['abc', 'def', 'hij', 'klm']}
df = pd.DataFrame(testdict)
df.loc[:,['start']] = pd.to_datetime(df['start'])
print(df)
</co... | python|pandas|time-series | 0 |
16,184 | 26,406,084 | Indexing a 2d array with a 3d array in numpy | <p>I have two arrays. </p>
<p>"a", a 2d numpy array.</p>
<pre><code>import numpy.random as npr
a = array([[5,6,7,8,9],[10,11,12,14,15]])
array([[ 5, 6, 7, 8, 9],
[10, 11, 12, 14, 15]])
</code></pre>
<p>"idx", a 3d numpy array constituting three index variants I want to use to index "a".</p>
<pre><code>i... | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.choose.html" rel="nofollow noreferrer"><code>choose</code></a> to make the selection from <code>a</code>:</p>
<pre><code>>>> np.choose(idx, a.T[:,:,np.newaxis])
array([[[ 6, 7, 6, 8, 9],
[12, 10, 12, 10, 11]],
... | python|python-3.x|numpy|multidimensional-array | 3 |
16,185 | 26,088,411 | Unable to import numpy: Error: /usr/lib/liblapack.so.3: undefined symbol: gotoblas | <p>When I try to import numpy, I get the following error:</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/numpy/linalg/__init__.py in <module>()
49 from .info import __doc__
50
---> 51 from .linalg import *
52
53 from numpy.testing import Tester
/usr/local/lib/python2.7/dist-packa... | <p>To solve these issues, I followed the install bash script here: <a href="https://gist.github.com/amirsani/d2aa0763cc138902bf73" rel="noreferrer">https://gist.github.com/amirsani/d2aa0763cc138902bf73</a></p>
<p>I still had the same error occur during testing at the ending of all the installation so I did this</p>
<... | python|numpy|lapack|blas|openblas | 5 |
16,186 | 67,161,171 | how to store model.state_dict() in a temp var for later use? | <p>I tried to store the state dict of my model in a variable temporarily and wanted to restore it to my model later, but the content of this variable changed automatically as the model updated.</p>
<p>There is a minimal example:</p>
<pre class="lang-py prettyprint-override"><code>import torch as t
import torch.nn as nn... | <p>That's how <code>OrderedDict</code> works. Here's a simpler example:</p>
<pre class="lang-py prettyprint-override"><code>from collections import OrderedDict
# a mutable variable
l = [1,2,3]
# an OrderedDict with an entry pointing to that mutable variable
x = OrderedDict([("a", l)])
# if you change the l... | python|pytorch | 4 |
16,187 | 67,111,082 | tensorflow segmentation fault in Nvidia Xavier Jetson when trying to load model with memory growth enabled | <p>I have a segmentation fault with a very specific code sequence and only on Xavier Jetson:</p>
<pre><code>import os
import requests
import tensorflow as tf
# 1
print('SET MEMORY GROWTH')
physical_devices = tf.config.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True... | <p>this error happens because the system is trying to use more memory than it should. When the system does not allow this, it gives a Segmentation Fault error.
First, check the error file as follows.</p>
<pre><code>$gdb python3
(gdb) run pythonfile.py
</code></pre>
<p>If the error is libapt-pkg5.0 install the appropria... | python|tensorflow|keras|segmentation-fault|jetson-xavier | 0 |
16,188 | 66,892,856 | Remove Key from json/Dict Python | <p>Iam trying to remove some key,value from my json output, but none of the things seems to be working.</p>
<p>The code solution is basically to convert a csv to json and then removed the unwanted keys from it.</p>
<pre><code>import csv, json
import pandas as pd
import os
def make_json(csvFilePath, jsonFilePath):
... | <p>You are looking for <code>dict.pop()</code>, which does exactly what you need.</p> | python|json|pandas | 0 |
16,189 | 67,134,465 | How do I obtain URL to download the csv files of Tensorflow datasets? | <p>In TensorFlow examples, I can see URLs to download the csv format of the dataset.
For example,</p>
<p>Iris- <a href="https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv" rel="nofollow noreferrer">https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv</a></p>
<p>Titani... | <p>you don't need the URLs. Tensorflow datasets are already ready to use. check out the tutorial here <a href="https://www.tensorflow.org/datasets/overview" rel="nofollow noreferrer">tfds guide</a></p>
<p>For titanic, it is available here <a href="https://www.tensorflow.org/datasets/catalog/titanic" rel="nofollow noref... | tensorflow|tensorflow-datasets | 2 |
16,190 | 67,024,926 | How does a Pytorch neural network load dataset into GPU | <p>When loading a dataset into the GPU for training, would a Pytorch NN load the entire dataset or just the batch?</p>
<p>I have a 33GB dataset that fits comfortably on my normal RAM (64GB) but i only have a 16GB of GPU RAM (T4). As long as Pytorch only loads one batch at a time into the GPU, that should work fine with... | <p>You can load one batch of data at a time into GPU. You should use data loader to fetch a batch of data and also initialize a torch device instance to use GPU.</p>
<p>You can check the following tutorial. It uses data loader to get data as batches and load them to GPU by using torch device.</p>
<p><a href="https://py... | neural-network|pytorch|gpu | 0 |
16,191 | 66,766,546 | Create and append pandas dummy variables with pipe | <p>I am trying to create a Pandas pipeline that creates dummy variables and append the column to the existing dataframe.
Unfortunately I can't get the appended columns to stick when the pipeline is finished.</p>
<p>Example:</p>
<pre><code>
def function(df):
pass
def create_dummy(df):
a = pd.get_dummy(df['col']... | <p>This is because <code>print</code> in Python returns <code>None</code>. Since you are not making a copy of <code>df</code> on your pipes, your <code>df</code> dies after <code>print</code>.</p>
<h2>pipes in Pandas</h2>
<p>Unless used as last pipe, in Pandas, we except <code>(df) -> [pipe] -> (df_1)-> [pipe2... | python|pandas|dataframe | 0 |
16,192 | 67,029,992 | numpy einsum: Elementwise product between 3D matrix and 2D matrix | <p>I have two numy matrices :</p>
<ol>
<li>A with shape (N,M,d)</li>
<li>B with shape (N,d)</li>
</ol>
<p>So, I am trying to get a Matrix with shape (N,M,d) in such manner that I do element wise product between B and each element of A (which are M elements). I used numpy's einsum as follows :</p>
<pre><code>product = n... | <blockquote>
<p>I am trying to get a Matrix with shape (N,M,d) in such manner that I do element wise product between B and each element of A (which are M elements).</p>
</blockquote>
<p>The operation you are trying to perform is a broadcasted element wise product over axis = 1 of <code>A</code> (M size) -</p>
<pre><cod... | python|numpy|numpy-einsum | 3 |
16,193 | 66,900,999 | How to integrate a function w.r.t time; i.e 'y' is an array and values of time(t) is varying from 1 to 3000 | <p>How do I integrate a function <code>f(y)</code> w.r.t time; i.e <code>'y'</code> is an array of 3000 values and values of <code>time(t)</code> is varying from 1 to 3000. So, I need 3000 values after integrating <code>f(y)</code>.
Integration would be indefinite and the integral values must be without <code>'x'</code... | <p>There are symbolical libraries that totally suit your task, like <a href="https://www.sympy.org/" rel="nofollow noreferrer">SymPy</a> - very advanced symbolical library. You can use it.</p>
<p>Numpy library is doing only numerical computations, no symbolics, you have to do all symbolics in your mind.</p>
<p>As I und... | python|arrays|pandas|numpy|integration | 2 |
16,194 | 47,187,768 | Tensorflow slice operator to strided_slice | <p>I would like to access the first channel of a tensor, which has a shape of: <code>[batch_size, img_width, img_height, channel_size]</code></p>
<p>Currently I do it like this:</p>
<pre><code>ch1 = X[...,0]
</code></pre>
<p>But I would like to give this operation a name, so I have to use <a href="https://www.tensor... | <p><code>tf.strided_slice(ch1,[0,0,0,0],[batch_size, img_width, img_height,1])
</code></p>
<p>You'll need to use <code>tf.reshape</code> to get exact same shape returned by <code>X[...,0]</code>.</p> | python|tensorflow | 0 |
16,195 | 47,115,448 | Pandas => get index of first and last element by group | <p>I have a dataframe with roughly 100M rows, (1.4Gb in memory)</p>
<p>Given the input:</p>
<pre><code>df.head()
Out[1]:
id term x
0 1 A 3
1 1 B 2
2 2 A 1
3 2 B 1
4 2 F 1
5 2 G 1
6 2 Z 1
7 3 K ... | <h3>I. For generic case</h3>
<p><strong>Approach #1</strong> With <code>np.unique</code> -</p>
<pre><code>idx = np.unique(df.id.values, return_index=1)[1]
</code></pre>
<p>To get the last indices for each <code>ID</code>, simply use <code>flipped</code> version and subtract from dataframe's length -</p>
<pre><code>len(... | python|pandas|numpy|dataframe|optimization | 7 |
16,196 | 47,289,132 | Basic Python: How do I normalize a data series? | <p>I have a dataframe with 5 columns indexed by date. I would like to normalize these data series by the first item in their lists.</p>
<pre><code> A B C D E
1/1/2017 3 4 1 2 3
1/2/2017 7 4 4 3 3
1/3/2017 2 5 5 4 3
1/4/2017 2 5 3 6 3
... | <pre><code>In [100]: df.div(df.iloc[0])
Out[100]:
A B C D E
1/1/2017 1.000000 1.00 1.0 1.0 1.0
1/2/2017 2.333333 1.00 4.0 1.5 1.0
1/3/2017 0.666667 1.25 5.0 2.0 1.0
1/4/2017 0.666667 1.25 3.0 3.0 1.0
1/5/2017 0.666667 0.50 2.0 3.0 2.0
</code></pre>
<p>or</p>
<pre... | python|pandas | 5 |
16,197 | 68,159,969 | How to keep all elements of a list in one row while creating a dataframe from it | <p>I have a list <code>lst = ['a', 'b', 'c']</code> .
Now, if I create a dataframe from it like below:</p>
<pre><code>df = pd.DataFrame(lst, columns=['char'])
</code></pre>
<p>Then, it becomes like below:</p>
<pre><code> char
0 a
1 b
2 c
</code></pre>
<p>But, I want to keep all elements in a row. For example:<... | <p>Use nested list:</p>
<pre><code>lst = ['a', 'b', 'c']
df = pd.DataFrame([[lst]], columns=['char'])
print (df)
char
0 [a, b, c]
</code></pre> | python|pandas|dataframe | 3 |
16,198 | 68,215,724 | What is causing the allocation of 12 GB of memory and causing CUDA out of memory error? Model, Data or something else? | <p>I am trying to build a 3D CNN based video classifier using Pytorch. When i try to run a single datapoint i run into this error:</p>
<pre><code>CUDA out of memory. Tried to allocate 1.20 GiB (GPU 0; 14.76 GiB total capacity; 12.60 GiB already allocated; 1.09 GiB free; 12.61 GiB reserved in total by PyTorch)
</code></... | <p>It's important to note that the real reason you have out of memory issues most of the time is not necessarily the inherent size of the model itself (though it is directly related to this). Even 100,000,000 parameters, with single floating point precision, only takes about 1 GB to store. (Now, in your case, your mode... | pytorch|conv-neural-network | 2 |
16,199 | 68,428,691 | Convert column with month and year ("August 2020"...) to datetime | <p>I have dataframe which contains one column of month and year as string :</p>
<pre><code>>>>time index value
January 2021 y 5
January 2021 v 8
May 2020 y 25
June 2020 Y 13
June 2020 x 11
June 2020 v 1... | <p>Sample dataframe:</p>
<pre><code>df=pd.DataFrame({'time':['January 2021','May 2020','June 2020']})
</code></pre>
<p>If you want to specify the format parameter then that should be <code>'%B %Y'</code> instead of <code>'%Y-%m-%d'</code>:</p>
<pre><code>df['time']=pd.to_datetime(df['time'],format='%B %Y')
#OR
#you can... | python|pandas|string|datetime | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.