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 |
|---|---|---|---|---|---|---|
350,800 | 17,267,231 | specifying size of a 2d array in python numpy | <p>I would like to statically initialize the size of an N by N 2d array in python's numpy where N is a variable (from a SQL query). The equivalent Java would be:</p>
<pre><code>N = code from sql query
int[][] mat = new int[N][N]
</code></pre>
<p>How would I do this in numpy? Or what about a Matrix type?</p> | <p>You can do it in a number of ways, but to create an empty array that you will later fill, you might consider:</p>
<pre><code>N = 100
mat = np.empty((N,N))
</code></pre>
<p>There are a large number of other methods detailed in the docs:</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/routines.array-creat... | python|arrays|numpy | 2 |
350,801 | 17,409,122 | view does not work with transposed array | <p>Why is it that this works:</p>
<pre><code>>>> f = np.array(([[10,20],[11,21],[11,21],[12,22],[13,23]]))
>>> f
array([[10, 20],
[11, 21],
[11, 21],
[12, 22],
[13, 23]])
>>> f.view([('',f.dtype)]*f.shape[1])
array([[(10, 20)],
[(11, 21)],
[(11, 21)],
[(12, 22)],
[(13... | <p>Your numpy array is by default stored in memory in a single contiguous block in <a href="http://en.wikipedia.org/wiki/Row-major_order">row major order</a>. When you define a structured array, all fields must also be contiguous in memory. In your case, you require that every row be stored in consecutive positions in ... | python|python-2.7|numpy | 5 |
350,802 | 17,552,668 | pyqtgraph compile to executable file fails | <p>I want to create an executable file from pyqtgraph, </p>
<p>finally I tried this tutorial</p>
<p><a href="http://www.pyqtgraph.org/Bundling%20applications%20with%20PyQtGraph_R16.pdf" rel="nofollow">http://www.pyqtgraph.org/Bundling%20applications%20with%20PyQtGraph_R16.pdf</a></p>
<p>After the first run of the co... | <p>Every version of scipy seems to have a different set of bugs that make py2exe fail. For the latest version (0.12.0), I have found that I need these two lines somewhere in my program so that py2exe will include them in the build:</p>
<pre><code>from scipy.stats import futil
from scipy.sparse.csgraph import _validati... | python|python-2.7|numpy|scipy|pyqtgraph | 2 |
350,803 | 17,437,817 | (Python) How to get diagonal(A*B) without having to perform A*B? | <p>Let's say we have two matrices <code>A</code> and <code>B</code> and let matrix <code>C</code> be <code>A*B</code> (matrix multiplication not element-wise). We wish to get only the diagonal entries of <code>C</code>, which can be done via <code>np.diagonal(C)</code>. However, this causes unnecessary time overhead, b... | <p>I might use <code>einsum</code> here:</p>
<pre><code>>>> a = np.random.randint(0, 10, (3,3))
>>> b = np.random.randint(0, 10, (3,3))
>>> a
array([[9, 2, 8],
[5, 4, 0],
[8, 0, 6]])
>>> b
array([[5, 5, 0],
[3, 5, 5],
[9, 4, 3]])
>>> a.dot(b)
arr... | python|numpy|matrix | 18 |
350,804 | 20,209,808 | Pandas dataframe computations | <p>I am trying compute a metric with panda dataframes. In particular, I get a results object</p>
<pre><code>prediction = results.predict(start=1,end=len(test),exog=test)
</code></pre>
<p>The actual values are in a dataframe given by </p>
<pre><code>test['actual'].
</code></pre>
<p>I need to compute two things:</p>... | <p>First one would be</p>
<pre><code>((prediction - test['actual']) ** 2).sum()
</code></pre>
<p>Second one would be:</p>
<pre><code>((prediction - test['actual'].mean()) ** 2).sum()
</code></pre> | python|pandas|dataframe | 8 |
350,805 | 20,176,590 | plot the centroid values over the existing plot using matplotlib | <p>How to plot the centroid values as computed below over the plot? </p>
<pre><code>import numpy as np, matplotlib.pyplot as plt
from scipy.cluster.vq import kmeans, vq
data = np.array(np.random.rand(100))
plt.plot(data, 'ob')
centroids, variances= kmeans(data,3,10)
indices, distances= vq(data,centroids)
print... | <p>You can plot using horizontal lines representing the centroids:</p>
<pre><code>plt.plot([0, len(data)], [centroids[0]]*2, lw=1.)
plt.plot([0, len(data)], [centroids[1]]*2, lw=1.)
plt.plot([0, len(data)], [centroids[2]]*2, lw=1.)
</code></pre>
<hr>
<p>EDIT: or as suggested by @nordev:</p>
<pre><code>plt.hlines(ce... | python|numpy|matplotlib|plot|scipy | 1 |
350,806 | 19,938,598 | Editing a pandas script to ignore but not remove data then match & updating + comparing to prevent wasteful saves + slicing data to match with? | <p>I've got some issue with one of my scripts... I'll put the problems in bullets.</p>
<ul>
<li><strong>Issue/Question 1 - Comparing the original testing.csv to the modified one before saving, if different it should save, if the same it should not save.</strong>
<ul>
<li>In my code below, the data comes out the same b... | <p>Going through your example, here's some answers:</p>
<h1><strong>Question 1</strong></h1>
<p>Comparing the original testing.csv to the modified one before saving, if different it should save, if the same it should not save.</p>
<p><strong>Answer 1</strong> - They are in fact different. For an example, lets output... | python|regex|python-2.7|pandas|assert | 0 |
350,807 | 19,840,425 | scipy.optimize: faster root finding over 2D grid | <p>I wrote some code using scipy to find the root the following equation:</p>
<pre><code>def equation(x, y):
return (x / y) * np.log((a * x / b) + 1.0) - 2.0 * c * c
</code></pre>
<p>with a, b, and c scalars.</p>
<p>I have values for y on a rectangular grid (say Y, shape 300x200), and need to find the correspondin... | <p>(expanding a comment)
As @askewchan shows in his answer, the runtime here is dominated by actually solving the equations. </p>
<p>Here's what I'd do here: absorb <code>2*c*c</code> as a multiplicative constant into <code>y</code>, ditto for <code>a/b</code>. What's left is an equation of the form <code>t log (1 + t... | numpy|scipy|equation-solving | 2 |
350,808 | 20,168,881 | Get norm of numpy sparse matrix rows | <p>I have a sparse matrix that I obtained by using Sklearn's TfidfVectorizer object:</p>
<pre><code>vect = TfidfVectorizer(sublinear_tf=True, max_df=0.5, analyzer='word', vocabulary=my_vocab, stop_words='english')
tfidf = vect.fit_transform([my_docs])
</code></pre>
<p>The sparse matrix is (taking out the numbers for ... | <p>Some simple fake data:</p>
<pre><code>a = np.arange(9.).reshape(3,3)
s = sparse.csr_matrix(a)
</code></pre>
<p>To get the norm of each row from the sparse, you can use:</p>
<pre><code>np.sqrt(s.multiply(s).sum(1))
</code></pre>
<p>And the renormalized <code>s</code> would be</p>
<pre><code>s.multiply(1/np.sqrt(... | python|arrays|numpy|matrix|norm | 10 |
350,809 | 15,621,143 | Pandas: df.set_value() method erases / resets column names of MultiIndex | <p>I am writing an application that makes use of pandas (version 0.10.1) to store the underlying data model as a (3-level) MultiIndex'ed DataFrame. The model is a line spectrum, and the top level of the index is the atomic transition.</p>
<p>A simple dataframe could look like this:</p>
<pre><code> ... | <p>Your index needs to be sorted! See docs here: <a href="http://pandas.pydata.org/pandas-docs/dev/indexing.html#the-need-for-sortedness" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/indexing.html#the-need-for-sortedness</a> and these recipes may help <a href="http://pandas.pydata.org/pandas-docs/dev/cookboo... | python|pandas | 1 |
350,810 | 15,991,640 | Efficiently Reading Large Files with ATpy and numpy? | <p>I've looked all over for an answer to this one, but nothing really seems to fit the bill. I've got very large files that I'm trying to read with ATpy, and the data comes in the form of numpy arrays. For smaller files the following code has been sufficient:</p>
<pre><code>sat = atpy.Table('satellite_data.tbl')
</c... | <p>For very large arrays (larger than your memory capacity) you can use <a href="http://pytables.org" rel="nofollow noreferrer">pytables</a> which stores arrays on disk in some clever ways (using the HDF5 format) so that manipulations can be done on them without loading the entire array into memory at once. Then, you ... | python|numpy|scipy|large-files|astronomy | 0 |
350,811 | 16,020,137 | How to preserve column names while importing data using numpy? | <p>I am using the numpy library in Python to import <code>CSV</code> file data into a <code>ndarray</code> as follows:</p>
<pre><code>data = np.genfromtxt('mydata.csv',
delimiter='\,', dtype=None, names=True)
</code></pre>
<p>The result provides the following column names:</p>
<pre><code>print(... | <p>if you set <code>names=True</code>, then the first line of your data file is passed through this function:</p>
<pre><code>validate_names = NameValidator(excludelist=excludelist,
deletechars=deletechars,
case_sensitive=case_sensitive,
... | python|numpy | 5 |
350,812 | 15,793,224 | Scipy: Speeding up calculation of a 2D complex integral | <p>I want to repeatedly calculate a two-dimensional complex integral using dblquad from scipy.integrate. As the number of evaluations will be quite high I would like to increase the evaluation speed of my code.</p>
<p>Dblquad does not seem to be able to handle complex integrands. Thus, I have split the complex integra... | <p>You can gain a factor of about 10 in speed by using Cython, see below:</p>
<pre><code>In [87]: %timeit cythonmodule.doit(lam=lam, y0=y0, zxp=zxp, z=z, k=k, ra=ra)
1 loops, best of 3: 501 ms per loop
In [85]: %timeit doit()
1 loops, best of 3: 4.97 s per loop
</code></pre>
<p>This is probably not enough, and the ba... | python|numpy|scipy|integration|complex-numbers | 14 |
350,813 | 12,629,644 | "no suitable image found" error when using numpy | <p>I tried to use NumPy in Terminal, but the system gave me an error message like this:</p>
<blockquote>
<p>Traceback (most recent call last): File "", line 1, in
File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/<strong>init</strong>.py",
line 137, in
import... | <p>Your installation of NumPy is borked somehow: it detects that some of its core libraries (eg, <code>multiarray.so</code>) were compiled with a different version of the compiler or for a different architecture.</p>
<p>If you installed NumPy <em>before</em> updating your Python to 2.7.3, you have to reinstall it. You... | python|macos|numpy|osx-lion | 3 |
350,814 | 12,272,642 | Serialize/deserialize float arrays to binary file using BSON in Python | <p>I am used to use JSON and Numpy to store arrays, lists and dicts in python, but I want to use BSON since floating point numbers would occupy only 4 bytes and thus reduce filesize.</p>
<p>With Json, I do the following:</p>
<pre><code>import numpy
import json
a = numpy.random.rand(12).reshape((3,4))
with open('out... | <p>The version of BSON I have installed won't import as shown so maybe I am using a different version. To see your documentation in python type help(bson) after importing...</p>
<p>Something like this should work:</p>
<pre><code>import bson
>>> a = numpy.random.rand(12).reshape((3,4))
>>> b = bson.d... | python|numpy|deserialization|binaryfiles|bson | 2 |
350,815 | 71,968,536 | How to ignore an error raised while using a lambda function on a dataframe rows? | <p>I am doing a Pandas operation on all rows using lambda function</p>
<pre class="lang-py prettyprint-override"><code>match = re.compile(r"([\d]{2,4}[-|/][\d]{1,2}[-|/][\d]{2,4})")
date_to_month = lambda x: pd.to_datetime(x.group(0)).strftime("%B")
data["path"] = data["path"].st... | <p>So, to mimic your use case:</p>
<pre class="lang-py prettyprint-override"><code>import re
import pandas as pd
df = pd.DataFrame({"col": ["a", "b", "c"], "path": ["--10--", "--99--", "--12--"]})
# Should convert '10' to 'October
match =... | python|pandas|exception | 2 |
350,816 | 72,076,723 | AttributeError: 'MapDataset' object has no attribute 'preprocess' in tensorflow_federated tff | <p>I'm testing this tutorial with non-IID distribution for federated learning:
<a href="https://www.tensorflow.org/federated/tutorials/tff_for_federated_learning_research_compression" rel="nofollow noreferrer">https://www.tensorflow.org/federated/tutorials/tff_for_federated_learning_research_compression</a></p>
<p>In t... | <p>Possibly there is some confusion between the <a href="https://www.tensorflow.org/federated/api_docs/python/tff/simulation/datasets/ClientData" rel="nofollow noreferrer"><code>tff.simulation.datasets.ClientData</code></a> and <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferre... | python|tensorflow|google-colaboratory|tensorflow-federated|federated-learning | 1 |
350,817 | 71,871,766 | Confronting values between dataframe | <p>I'm trying to find a way to confront the equality of values contained into a different dataframes having different column names.</p>
<pre><code>label = {
'aoo' : ['a', 'b', 'c'],
'boo' : ['a', 'b', 'c'],
'coo' : ['a', 'b', 'c']
'label': ['label', 'label', 'label']
}
unlabel = {
'unlabel1' : ['a'... | <p>You can use <code>pd.merge</code> and specify the columns to merge with <code>left_on</code> and <code>right_on</code></p>
<pre class="lang-py prettyprint-override"><code>out = unlabel.merge(label, left_on=['unlabel1', 'unlabel2', 'unlabel3'], right_on=['aoo', 'boo', 'coo'], how='left').drop(['unlabel3', 'aoo', 'boo... | python|pandas | 1 |
350,818 | 72,106,779 | How to read mysql data using panda filtering by a specific date | <p>I am trying to read a database stored in MySQL to python.</p>
<p>I understand how to connect and read the whole data, but I am having problem in how to just get the data from a specific date.
Like how to do SELECT * FROM country WHERE TIMESTAMP(date)= '2022-02-19' for example</p>
<p>I can get the whole table doing t... | <pre class="lang-py prettyprint-override"><code>df = pd.read_sql(f"SELECT * FROM {tables[0]} WHERE date = '2022-02-19'", con=engine)
</code></pre> | mysql|pandas|dataframe | 1 |
350,819 | 71,969,367 | Plot Between Certain Y axis Values | <p>I'm plotting some values using Pandas. But my Values are soo close together It doesn't actually show anything. Is there a way to restrict Y-axis to "Zoom in" on the differences?</p>
<pre><code>import pandas as pd
Visualisation_data = [
['Name', 'Precision', 'Recall', 'Fscore'],
['Nearest Neighbors', 0.99... | <p>You can adjust the y-axis start and end by replacing the last line <code>bplot.plot.bar( x = 'Name')</code> by below code.</p>
<pre><code>ax = bplot.plot.bar( x = 'Name')
ax.set_ylim(0.98,1)
</code></pre>
<p>This is the updated graph
<a href="https://i.stack.imgur.com/06NYQ.png" rel="nofollow noreferrer"><img src="h... | python|pandas | 0 |
350,820 | 71,832,940 | Counting unique values or lables in a dataset | <p>Im having a problem counting the diffrent directors and how many films they each released in my data frame, the output i want is
director x, 22 films
director y, 13 films,
my code goes as follows</p>
<pre><code>directors=movies.iloc[:,14]
directors
#this is me selecting out the director column
directors.nunique()
#t... | <p>nuique() returns the number of unique values within a given array. The value 2101 is being returned because there are 2101 values in the selection you have.</p>
<p>If you're trying to find a number of films for each unique directory I would do:</p>
<pre><code>for director in movies.iloc[:,14].unique():
movies.fil... | python|pandas | 1 |
350,821 | 71,919,482 | Transforming rows to columns -> first column not recognized | <p>I am trying to extract emoji counts from text and currently struggle in giving the output columns titles.
If I try to assign columns, it would only recognize one column (the count), not the emoji column itself, which is the first one, so I assume the issue lies there? I thought with setting the index to 0 it would s... | <p>Let us fix the way you are creating the dataframe:</p>
<pre><code>pd.DataFrame(Counter(emoji_list).items(), columns=['emoji', 'count'])
</code></pre>
<hr />
<pre><code> emoji count
0 2
1 2
2 ♦️ 3
</code></pre> | python|pandas|dataframe|counter|series | 2 |
350,822 | 71,949,905 | Reconstructing, filling the gaps in .csv using for line in, and .append in loop | <p>Pls help im tired.
cant see why how to make it work.</p>
<p>Problem to solve:
a .csv file has to have suposedly 1sec data like:</p>
<pre><code>time,open,high,low,close,Extremum,Fib 1,Fib 2,Fib 3,l100
2022-04-03 02:00:00,3.294,3.294,3.294,3.294,3.277,3.332898006846162,3.348093581522788,3.357138566449352,3.36744984926... | <p>Looks like you can just read in the data, and use <code>asfreq</code>:</p>
<pre class="lang-py prettyprint-override"><code>
# instead of read_clipboard, you'd read it with pd.read_csv
df = pd.read_clipboard(sep=',', parse_dates = ['time'])
df.set_index('time').asfreq(freq='1S').ffill()
open ... | python|pandas|dataframe|csv|append | 1 |
350,823 | 71,844,513 | Replacing diagonal elements with another array in Python | <p>I have two matrices, <code>A</code> and <code>P</code>. I would like to replace the diagonal elements of <code>A</code> with the elements of <code>P</code>. The desired output is attached.</p>
<pre><code>A=np.array([[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0]])
P=np.array([[3, 4],
... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html" rel="nofollow noreferrer"><code>fill_diagonal</code></a> with the flattened P as values for the diagonal:</p>
<pre><code>np.fill_diagonal(A, P.ravel())
</code></pre>
<p><em>NB. the operation is in place</em></p>
<p>output:</p>
<p... | python|numpy | 2 |
350,824 | 71,840,221 | Filter dataframe using values from a column | <p>I have a dataframe containing the employee name, employee email, manager name and manager email. I need to filter this dataframe using all the unique values of the manager email and confirm they also appear in the column employee email, this way making sure they are also in the database as an employee.</p>
<p>For ex... | <p>IIUC, you can use masks and boolean indexing:</p>
<pre><code># is the employee email valid? you can use a different pattern e.g. '@company\.com'
m1 = df['Employee E-mail'].str.contains('@').fillna(False)
# is the manager email valid?
m2 = df['Manager E-mail'].str.contains('@').fillna(False)
# is the manager also an ... | python|pandas|search|filter | 1 |
350,825 | 71,938,066 | ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 81), found shape=(None, 77) | <p>I am trying to train a neural network but I am getting the following error:</p>
<pre><code> ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 81), found shape=(None, 77)
</code></pre>
<p>I tried to find the solution to this but am unable to do so. Can someone p... | <p>The problem is that your input data does not have the same shape that you defined in your first layer. Make sure the features dimension of your data corresponds to the input shape in the model's first layer. Here is an example:</p>
<pre><code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layer... | python|tensorflow|keras | 1 |
350,826 | 72,087,875 | How to count unique ids if certain columns have no missing values | <p>I have the following df</p>
<pre><code>ID date v1 v2 v3 v4 v5 v6
A .. 1 2 3 NaN NaN NaN
A .. 0 2 NaN NaN NaN NaN
B .. 0 2 4 5 3 9
B .. 2 6 6 6 3 NaN
D .. 2 NaN NaN NaN NaN NaN
D .. 9 2 2 NaN NaN NaN
D .. ... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>dropna</code></a> with a subset:</p>
<pre><code>cols = ['v1', 'v2', 'v3', 'v4', 'v5']
df2 = df.dropna(subset=cols)
</code></pre>
<p>Or, use <a href="https://pandas.pydata.org/docs/reference/api/pan... | python|pandas|dataframe | 3 |
350,827 | 72,097,603 | python dataframe create one column based on another column | <p>I would like to create another column in a dataframe.</p>
<p>The dataframe is like the following, sub_id is part of the id, say id is the 'parent' for sub_id, it includes id itself and some items included in id.</p>
<p>id has no name but sub_id has corresponding name</p>
<p>I would like to check id with sub_id's nam... | <p>If replace not matched <code>id</code> with <code>sub_id</code> to misisng values in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cor... | python|pandas | 2 |
350,828 | 71,799,689 | Is there a way to extract contents from a JSON list inside a pandas dataframe cell? | <p>I have a column in a pandas dataframe that contains JSONs just like the example below. I want to extract just the zipcode value from either of the banks, but I can't.</p>
<pre><code>[{"Bank1":{"zipcode":"045603", "total_amount":"400000"}}, {"Bank2":{"{... | <p>I think you can use map</p>
<p><code>df['bank_data'].map(lambda x: x['Bank1']['zipcode'])</code></p> | python|json|pandas | 0 |
350,829 | 71,914,834 | Put values from one df in two columns of another df, depending on two columns | <p>How can I achieve putting values from one df in two columns of another df, depending on two columns like:</p>
<pre><code>import pandas as pd
import numpy as np
# data = home away values = team value
# A B A 1
# B A A 2
# C A ... | <p>Let's try this:</p>
<pre><code>df_games = data.rename_axis(index='Game', columns='Location')\
.stack().rename('Team').reset_index()
df_values = values.rename_axis(index='Game', columns='Team')\
.stack().rename('value').reset_index()
df_out = df_games.merge(df_values, on=['Game', 'Te... | python-3.x|pandas|numpy | 0 |
350,830 | 72,121,487 | Change data in a row of a csv file | <p>I'm trying to change specific data into a csv file with a .json i have.</p>
<p>The script does this:</p>
<p>The mainly thing is to search in a website the data for X id that the csv file have.</p>
<p>Then add that data in my .json, so it's not constantly looking at the website (That would take a looong time)</p>
<p>... | <p>I am not sure if I understand why do you have a json and a CSV, and if they are supposed to have duplicated data. From what I gather, you are creating a new output file per row in the CSV since the file writing loop is inside the row-parsing <code>for</code> loop. You should initialize the output file (<code>open(df... | python|python-3.x|pandas|csv | 0 |
350,831 | 71,964,296 | How to convert the dummy variable columns in to several columns? | <p>I know how to unstack rows into columns, but how to deal with the following <code>dataframe</code>?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>date</th>
<th>dummy</th>
<th>avg</th>
<th>lable</th>
</tr>
</thead>
<tbody>
<tr>
<td>1-19</td>
<td>1</td>
<td>20</td>
<td>l1</td>
</tr>
<tr>... | <p>You could also use <code>pivot_wider</code> from <code>janitor</code>:.</p>
<pre><code># pip install pyjanitor
import pandas as pd
import janitor
df.pivot_wider(index = ['date', 'lable'], names_from = 'dummy')
Out[19]:
date lable avg_0 avg_1
0 1-19 l1 40 20
1 1-27 l2 140 100
</code></pr... | python-3.x|pandas|dataframe | 3 |
350,832 | 71,947,002 | error: Dimension out of range (expected to be in range of [-1, 0], but got 1) when training to train a CNN model | <p>I am trying to follow a code snippet which uses resnet18 to train a binary classification model since I am supposed to train a multi-classification model, I modified the code a bit by changing the loss function, activation function</p>
<pre><code>import torchmetrics
class CheastCancer(pl.LightningModule):
def __... | <p>If you see the <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html" rel="nofollow noreferrer">docs</a> you'll see that the targets input into <code>CrossEntropyLoss</code> are the class indices. I'm going to guess that maybe you've got it in one-hot format, so what you'll need to do is:... | python|pytorch | 0 |
350,833 | 72,027,948 | Numpy multiply array with scalar translation to c# | <p>Basically I have this python code using <strong>opencv</strong> to find the contours in a given image. To improve contours recognition, I apply a resize to the original image and then I apply a ratio to the obtained contours to "translate" them to the real image size:</p>
<pre><code>ratio = image.shape[0] ... | <p>Solved it by manually obtaining the contour points and multiplying all them by the ratio</p> | python|c#|numpy|opencv | 0 |
350,834 | 71,952,973 | How to join two pandas dataframe such that the second table repeats | <p>I have tow dataframe df1 & df2:</p>
<pre><code>df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "... | <p>First idea is only forward filling missing values, not working if some missing values in <code>df1</code> - also replace them:</p>
<pre><code>output = df1.join(df2).ffill()
print (output)
A B C D E F G
0 A0 B0 C0 D0 A4 B4 C4
1 A1 B1 C1 D1 A4 B4 C4
2 A2 B2 C2 D2 A4 B4 C4
3 A3 B3... | python|pandas | 3 |
350,835 | 72,077,164 | Pandas:How to apply a complex function to a column of a dataframe, with two other columns as the input of the function? | <p>I have a dataframe that looks like this:</p>
<pre><code>+--------+-------------+----------+---------+
| Worker | Schedule | Overtime | Product |
+--------+-------------+----------+---------+
| 1 | some string | some int | ABC |
+--------+-------------+----------+---------+
| 2 | some string | some i... | <p>You can try <code>apply</code> on rows</p>
<pre class="lang-py prettyprint-override"><code>def edit_schedule(row):
Schedule = row['Schedule']
Overtime = row['Overtime']
Product = row['Product']
*some calculation ...*
return Schedule_edited
df['Schedule_Edited'] = df.apply(edit_schedule, axis=1)... | python|pandas|dataframe | 1 |
350,836 | 71,998,808 | Days Difference between two consecutive Dates in datetime.index column in pandas dataframe | <p>Below is my Dataframe <code>df</code> which contains datetime index.</p>
<pre><code> Open High Low Close Volume Currency
Date
2021-04-20 14526.70 14526.95 14207.30 14296.40 456704720896 INR
2021-04-22 14219.15 14424.75 14151.4... | <p>for the count values set by Currency you'll need to use groupby</p>
<p><code>df['difference'] = df.index.to_series().groupby(df['Currency']).diff().dt.days </code></p> | python|pandas|datetime | 1 |
350,837 | 72,136,502 | Python Subset pandas dataframe based on first n unique elements from a column | <p>I have a pandas dataframe (df) with many subjects.</p>
<pre><code> # Column Non-Null Count Dtype
--- ------ -------------- -----
0 subject 20640 non-null object
1 block 20640 non-null int64
</code></pre>
<p>Say I want to subset the df wi... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with filter first unique values with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><c... | python|pandas | 2 |
350,838 | 71,899,797 | What does df.min() do? | <p>what does this exactly mean? or what does it do?
a is a column in the dataframe
b is another column in the dataframe
both have numbers in each row</p>
<pre><code>df['a'] = df[['a', 'b']].min(axis=1)
</code></pre>
<p>I tried doing the research online but dont seem to find an answer</p> | <p>For each row, it compares columns <code>a</code> and <code>b</code> and takes minimum one and overwrites column <code>a</code> with new minimum values. Check <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.min.html" rel="nofollow noreferrer"><code>pandas.DataFrame.min</code></a>.</p>
<p>Here i... | python|pandas|dataframe | 1 |
350,839 | 72,034,456 | Pandas: Creating indicator column after condition | <pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({
'cond': ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B','B', 'B', 'B', 'B', 'B','B','B'],
'Array': ['S', 'S', 'TT', 'TT','S', 'S', 'TT', 'TT','S', 'S', 'TT', 'TT','S', 'S', 'TT', 'TT','SS','TT'],
'Area': [3.0, 2.0, 2.88, 1.33, 2.44,... | <p>You can make write the conditions, and then group by <code>cond</code> and use <code>cumsum</code> + <code>clip</code>:</p>
<pre><code>mask = (df['cond'].eq('A') & df['Area'].lt(1.5)) | (df['cond'].eq('B') & df['Area'].gt(10))
df['Indicator'] = mask.groupby(df['cond']).cumsum().clip(0, 1)
</code></pre>
<p>Ou... | python|pandas|dataframe|pandas-groupby | 4 |
350,840 | 71,799,347 | how to make a Correlation One Column to Many Columns and return a list? | <p>i would like to create a correlation function between a column and the others, passing the dataframe with all columns, corelating wiht a specif colum and returning a list of metrics and correlation i`am doing this like this.</p>
<pre><code>correlations = df.corr().unstack().sort_values(ascending=True)
correlations ... | <p>Something like this should do</p>
<pre><code>def get_nonself_correlation(df,self_name):
temp = df.corr()
temp = temp.loc[temp.index!=self_name,temp.columns==self_name]
temp = temp.unstack().reset_index()
temp.columns = ['corr_matrix', 'dfbase', 'correlation']
return temp
</code></pre> | python|pandas|dataframe|data-science|pearson-correlation | 1 |
350,841 | 72,020,457 | Error in virtualenv_install for tensorflow in R | <p>I am trying to train a model using keras library in RStudio.</p>
<pre><code>library(keras)
N <- 100
x <- runif(N, -2, 3)
# Build a Gompertz function with some noise
a <- 10 # ceiling parameter
b <- 0 # horizontal shift parameter
c <- 2 # growth rate parameter
y <- a*exp(-exp(b - c*x)) + rnorm(N, me... | <p>Many installation issues are resolved by running the following in a <strong>fresh R session</strong> (you can restart R in Rstudio with Ctrl+Shift+F10) :</p>
<pre><code># install the development version of packages, in case the
# issue is already fixed but not on CRAN yet.
install.packages("remotes")
remot... | python|r|tensorflow|keras | 0 |
350,842 | 71,903,660 | Failed to apply delegate: TfLiteGpuDelegate Init: MUL: Expected a 3D tensor of shape HxWxC or a 4D tensor of shape 1xHxWxC but got 98x8 (Android) | <p>I upgraded tensorflow-lite and tensorflow-lite-gpu from 2.3.0 to 2.4.0
And getting this error on initialization interpeteur</p>
<p>java.lang.IllegalArgumentException: Internal error: Failed to apply delegate: TfLiteGpuDelegate Init: MUL: Expected a 3D tensor of shape HxWxC or a 4D tensor of shape 1xHxWxC but got 98x... | <p>I found a workaround for this issue, before converting to tflite I changed</p>
<pre><code>tf.math.multiply(weights, var)
</code></pre>
<p>to</p>
<pre><code>tf.linalg.matmul(weights, var, transpose_a=True)
</code></pre>
<p>Looks like from version 2.4.0 Gpu Delegate can't proceed this operation to multiply 2d arrays w... | tensorflow|tensorflow2.0|tensorflow-lite | 0 |
350,843 | 72,014,538 | How to get prediction label and percentage from pipeline? | <p>I am using the following Hugging Face transformer code.</p>
<pre><code>from transformers import pipeline
classifier = pipeline("sentiment-analysis",model='bhadresh-savani/distilbert-base-uncased-emotion', return_all_scores=True)
prediction = classifier("I love using transformers. The best part is wide... | <p>You are using a <a href="https://huggingface.co/docs/transformers/main_classes/pipelines#transformers.TextClassificationPipeline" rel="nofollow noreferrer">TextClassificationPipeline</a>. When you <code>__call__</code> the pipeline you get a list of <code>dict</code> if <code>return_all_scores=False</code> or a list... | python|huggingface-transformers | 2 |
350,844 | 71,846,842 | Pandas dataframe to_csv escape double quotes | <p>I am trying to export pandas dataframe in csv. Some of data contains double quotes and I can't get it escaped properly.</p>
<pre><code>import pandas as pd
from io import StringIO
inp = [{'c1':10, 'c2':'some text'}, {'c1':11,'c2':'some "text"'}]
df = pd.DataFrame(inp)
output = StringIO()
df.to_csv(output, ... | <p>I managed to fix this issue with following settings.</p>
<pre><code>df.to_csv(output, sep="\t", escapechar="\\", header=False, index=False, doublequote=False)
</code></pre>
<p><code>escapechar="\\"</code> will put a single back-slash with the double quotes in your value as you have alre... | pandas|dataframe|csv|escaping|double-quotes | 0 |
350,845 | 72,049,692 | What is the inconsistency in pixels colors? | <p>This program gets the r, g, b, a values of a pixels two ways. One by converting into a 2d array of tuples and reading the values. The other uses the default PIL method. However they give me different reading of RGB values. I tried few tests to make sure they were reading the same pixel, but it still gives different ... | <p>I tried on a couple of images and the two approaches returned exactly the same values. Keep in mind that <code>a</code> is a transpose of <code>pixels</code>. This means that you have to use <code>a[i, j]</code> and <code>pixels[j, i]</code> to target the same pixel!</p> | python|numpy|io|python-imaging-library|binaryfiles | 1 |
350,846 | 71,940,617 | Code for changing multiple .img files into .png, then into numpy array | <p>I'm doing a convolutional neural network classification and currently all my tiles are in .img format (thanks ArcMap). I know I need to get them in .png format, but haven't found code that could convert a whole folder of them. Is that doable?</p>
<p>Eventually I also need to get all those .pngs into a numpy array. I... | <p>Yes it is doable, just use Python <a href="https://python-pillow.org/" rel="nofollow noreferrer" title="PIL is an acronym for Python Imaging Library.">Pil</a>! and loop over all files in the folder with glob.</p>
<p>Some example code:</p>
<pre><code>import os
from PIL import Image
import glob
counter = 0
for image ... | numpy|deep-learning|conv-neural-network|default.png | 0 |
350,847 | 72,097,351 | Create a dataframe in pandas from the rows following a given record for each ID | <p>Given the following Python DataFrame:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>direction</th>
<th>other</th>
<th>color</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>OUT</td>
<td>TT</td>
<td>red</td>
<td>2022-01-03</td>
</tr>
<tr>
<td>0</td>
<td>IN</td>
... | <p>You can swap order in original <code>DataFrame</code> by slice <code>[::-1]</code>, then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cummax.html" rel="nofollow noreferrer"><code>GroupBy.cummax</code></a> with condition <code>direction='OUT'</code>, change order ... | python|pandas|dataframe | 1 |
350,848 | 72,043,855 | How to replace nan with a certain value across rows but only between values | <p>I have the following dataframe, and I want to replace nan with a certain value, let's say, 0.0001, only if there is a value right to the missing value.</p>
<pre><code>ID 2021_12 2021_09 2021_06 2021_03 2020_12 2020_09
A 0.020637713 nan nan nan nan nan
B 0.... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a> with mask for test not missing values after back filling missing values chained for test missing values:</p>
<pre><code>#if misisng values are strings
df = df.r... | python|pandas | 2 |
350,849 | 71,970,277 | Loading a numpy array into Tensorflow input pipeline | <p>So I am following a tutorial for making a dataloader for images (<a href="https://github.com/codebasics/deep-learning-keras-tf-tutorial/blob/master/44_tf_data_pipeline/tf_data_pipeline.ipynb" rel="nofollow noreferrer">https://github.com/codebasics/deep-learning-keras-tf-tutorial/blob/master/44_tf_data_pipeline/tf_da... | <p>The comment of @André put me in the right direction. The code below works.</p>
<pre><code>
def process_image(file_path):
label = get_label(file_path)
label = np.uint8(label)
img = np.load(file_path)
img = tf.convert_to_tensor(img/255, dtype=tf.float32)
return img , label
train_ds = images_ds... | python|numpy|tensorflow|pipeline|dataloader | 0 |
350,850 | 71,948,303 | How to parse geojson files with python? | <p>I added .geojson files that I try to parse, but when I run the code it gives an error like;
KeyError: 'area', I know its means but my question is how can I achieve the keys inside raw_airport.loc</p>
<p><a href="https://dosya.co/93s8tuqpr86m/gates-and-ramps.geojson.html%20https://dosya.co/5to7l7ngutew/taxiways-and-r... | <p>After running, at the right side you will see the "Variable Explorer" you can see the details on there.</p> | python|dictionary|geopandas | 0 |
350,851 | 72,104,810 | How subtract a Dataframe with totals another Dataframe based on condition and until 0 | <p>I'm new with python and pandas so here's my question:</p>
<p>I have two dataframes, df1 has two columns one for labels and one for integers which correspond to the Toal of each label while df2 contains the quantity used by day. I would like to subtract each row of df2 until df1 is equal or closer to 0 and add a colu... | <p>Welcome to StackOverflow!</p>
<p>I believe a .cumsum() and .idxmin() will help with this.</p>
<ol>
<li>Join your dataframes on label</li>
<li>Create a new "Running Quantity" column that is a .cumsum() on the "Quantity" column (<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame... | python|pandas|dataframe|iteration|subtraction | 0 |
350,852 | 71,928,968 | Dataframe is Offset by -1 Days From Source Data | <p>I am using a connector to query some tables in Dynamics 365 Business Central and when I view my dataframe all of my dates are offset by -1 days.</p>
<p>I generated a logfile for a specific invoice to use as an example, and in the logfile, I see the correct Posting_Date of "2022-04-01" and the query is comp... | <p>I am not familiar with PostgreSQL databases and dataframes.</p>
<p>However Business Central stores <code>DateTimes</code> in the database as UTC timestamps, which I guess could explain the offset, given that you are using PST as the timezone when reading the data.</p>
<p>Dates are also stored as <code>DateTime</code... | python|pandas|dataframe|dynamics-business-central | 0 |
350,853 | 72,089,532 | Add elements to 2-D array | <p>I have the following Arrays</p>
<pre><code>import numpy as np
A = np.array([[1,2], [3,4]])
B = np.array([5,6])
</code></pre>
<p>Now I want to add the second element of A to B using the append function:</p>
<pre><code>B = np.append(B, A[1])
</code></pre>
<p>What I want to get is:</p>
<pre><code>B = np.array([[5, 6],[... | <pre><code>import numpy as np
A = np.array([[1,2], [3,4]])
B = np.array([[5,6]])
B = np.append(B, [A[1]], axis=0)
print(B)
</code></pre>
<h4>Output</h4>
<pre><code>array([[5, 6],
[3, 4]])
</code></pre>
<p>This would be one of the way using <code>np.append()</code> specifying the <code>axis = 0</code>.</p> | python|arrays|numpy | 0 |
350,854 | 71,842,748 | return zero instead of nothing when no rows in the corresponding index | <p>I have the following code</p>
<pre><code>count_by_month=df.groupby('month')['activity'].nunique()
month=list(range(0,12,1))
count_by_month.loc[count_by_week.index.isin(month),:]
</code></pre>
<p>The above code return the following data:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th st... | <p>I figured out the solution:
modifying the code to looks like the following work :</p>
<pre><code>count_by_month.loc[count_by_week.index.isin(month),:].reindex(month, fill_value=0)
</code></pre> | python|pandas|matplotlib|plot|indexing | 0 |
350,855 | 72,001,665 | Data Frame % column by groupping | <p>I am working on a forecast accuracy report which measure the deviation between actual & pervious projection. The measurement would be = 1- ('Actual' - 'M-1') / 'Actual' .
There measure need to be groupped based different gratuity, say 'Product Category' / 'Line' / 'Product'. However, the <code>df.groupby('Produc... | <p>You can also create a custom function and <code>apply</code> it on every row of a pandas data frame as follows. Just note that I set the <code>axis</code> argument to <code>1</code> so that the custom function is applied on each row or across columns:</p>
<pre><code>import pandas as pd
def func(row):
row['M1 Ga... | pandas|dataframe|pandas-groupby | 2 |
350,856 | 71,882,530 | Why pd.read_csv get wrong value when using dtype = 'Int64'? | <pre class="lang-py prettyprint-override"><code>import pandas as pd
When there is no na values, It's right.
!cat id1
</code></pre>
<pre><code>1471341653427101696 1458379213265436885
</code></pre>
<pre class="lang-py prettyprint-override"><code>pd.read_csv('id1',sep ='\t',header=None, na_values=['\\N'],dtype = 'Int64... | <p>This is an old issue for pandas: github.com/pandas-dev/pandas/issues/30268.</p>
<p>So the only way is using str,remove na ,then convert to int</p> | python|pandas|dataframe|na|int64 | 2 |
350,857 | 71,857,265 | Encoder weights are not initialized when loading pre trained model | <p>I'm writing a custom class on top of <code>XLMRobertaModel</code>, but when initializing the model from a pre-trained checkpoint, I get a warning saying the <code>encoder.layer.*</code> weights were not initialized from the respective checkpoint.</p>
<p>Here is a minimal example to reproduce the error:</p>
<pre clas... | <p>Since I dont have the code and pretrianed model, I can only tell you how to load the model accurately.</p>
<p>Before you load load the model weights, I suggest you first print the model parameter names you define by</p>
<pre class="lang-py prettyprint-override"><code>model = XXXNet()
for names, params in model.name... | python|nlp|pytorch|huggingface-transformers|huggingface | -1 |
350,858 | 72,134,390 | Order in dataframe generation | <p>Could you explain to me why the <code>Properties</code> column was the third column and not the first one? As you can see I insert it as the first in <code>pd.DataFrame</code>, but when I do <code>print(df)</code>, it appears as the third column.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Properties':[1... | <p>Try using <code>columns</code> argument to assign the order of columns:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'C1':[1, 2, 3,4],
'C2':[-24.930473, -24.95575,-24.924161,-24.95579],
'C3':[-24.930473, -24.95575,-24.924161,-24.95579],
'C4': (1,2,1,2... | python|pandas|dataframe | 0 |
350,859 | 72,038,969 | module 'pandas' has no attribute 'read_csv': AttributeError | <p>I have written a lambda function for AWS which will use pandas for handling dataframe. When I tested this lambda function - I faced error - <code>No module name pandas</code>.
I further kept pandas and other dependencies libraries in library folder of my repository.</p>
<p>Now I am facing other issue which I am unab... | <p>Pandas is indeed not available by default on AWS lambda.
If you want to use Pandas with AWS lamdba, the easiest way is to use the AWS Data Wrangler layer.
When you add a new layer, select AWS layers , then in the dropdown menu you can select the AWSDataWrangler-Python39 one.
Once you have added the layer, you will ... | python|pandas|amazon-web-services|lambda | 0 |
350,860 | 71,851,584 | how to loop through a folder of csv files and read header of each? then output in a folder | <p>I'm a newbie in python and need help with this piece of code. I did a lot of search to get to this stage but couldn't fix it on my own. Thanks in advance for your help.</p>
<p>What I'm trying to do is that I have to compare 100+ csv files in a folder, and not all have the same number of columns or columns name. So I... | <p>You can create a dictionary whose key is filename and value is dataframe columns. Using this dictionary to create dataframe results in filename as index and column names as column value.</p>
<pre class="lang-py prettyprint-override"><code>d = {}
for filename in all_files:
df = pd.read_csv(filename, index_col=No... | python|pandas|csv | 0 |
350,861 | 72,135,542 | How to group and merge mutil cell in one string without for loop? | <p><a href="https://i.stack.imgur.com/aFfei.png" rel="nofollow noreferrer">The table looks like this</a></p>
<p>I have a table something like this, how can I merge each id's dtl_details to one string and order by seq, the output should be like this:</p>
<pre><code>id | dtl_details
123 | rm 123, 11/F, 123 abc st, CWB,... | <p>In SQL Server, <code>string_agg()</code> should do the trick</p>
<pre><code>Select ID
,dtl_details = string_agg(dtl_details ,',') within group (order by seq)
From YourTable
Group By ID
</code></pre> | sql-server|python-3.x|pandas|dataframe | 1 |
350,862 | 72,103,063 | Filter pandas DataFrame with condition | <p>I am trying to filter a pandas DataFrame with a specific condition.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'name': ['A','A','C','C','E','E'],
'cat': [1, 1, 1, 0, 2, 3]
})
</code></pre>
<p>I'd like to filter by <code>cat == 1</code>. <code>df[df... | <p>Another version:</p>
<pre class="lang-py prettyprint-override"><code>out = df.sort_values(
"cat", kind="stable", key=lambda x: x != 1
).drop_duplicates("name")
print(out)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code> name cat
0 A 1
2 C ... | python|pandas|dataframe|pandas-groupby | 2 |
350,863 | 71,926,493 | Python: Fill nan values in column with the previous string, which changes every few rows | <p>Can't find this in the q&a although feel it probably has been asked before, so please direct me if that's the case.</p>
<p>I have a df with around 10 columns and many rows. One of these columns is an identifier, let's say "Site". The data isn't well labelled, and only the first row of each site has the... | <pre><code>df = pd.DataFrame({'Site': ['aa', np.nan, np.nan, 'bb', np.nan, 'cc', np.nan, np.nan, np.nan],
'data1': [2, 5, 2, 5, 2, 5, 2, 2, 2], 'data2': [3, 6, 3, 6, 3, 6, 3, 3, 3]})
print(df.fillna(method='ffill'))
</code></pre>
<p>filling in the "forward" direction</p> | python|pandas|dataframe|replace|nan | 2 |
350,864 | 72,060,381 | Is possible to use sklearn.neighbors.KNeighborsClassifier into a tensorflow Session i.e with Tensor? | <p>I am trying to use the KNN classifier inside a Tensorflow session.</p>
<p>But I am getting the following error:</p>
<p><code>NotImplementedError: Cannot convert a symbolic Tensor (Const:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported</code></p>... | <p>This code may help you solve your problem.</p>
<pre><code>import tensorflow as tf
from sklearn.neighbors import KNeighborsClassifier
tf.config.run_functions_eagerly(True)
@tf.function
def add():
model = KNeighborsClassifier(n_neighbors=3)
features= tf.constant([[1., 1.], [2., 2.],[2., 2.],[2., 2.],[2.... | python|tensorflow|scikit-learn | 1 |
350,865 | 71,973,393 | Pandas: Incorrect Result when multiplying two columns | <p>I am going through the Pandas-Kaggle information here:</p>
<p><strong>DataSet</strong>
<a href="https://www.dropbox.com/s/16cwjq5ibtcmzgi/Lookup211.csv?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/16cwjq5ibtcmzgi/Lookup211.csv?dl=0</a></p>
<p><strong>Action I want to take</strong>
I want to combine the ... | <p>I can not reproduce your error, to mee seems fine. Seems like a cliche for IT but try to restar your kernel if you are in Jupyter notebook:
with "Restart & Clear Output" + "Restar & Run All"</p>
<p><a href="https://i.stack.imgur.com/tVqOy.png" rel="nofollow noreferrer"><img src="https://i... | python|pandas | 0 |
350,866 | 71,956,897 | How to print top 10 elements of a dataframe column | <pre><code>mask = df.groupby('prod_title')['trans_quantity'].sum().reset_index()
mask = mask.sort_values(by='trans_quantity',ascending=False)
top_num_sales = mask['prod_title'].head(10)
</code></pre>
<p>I want to print only the names from the top 10 elements from <code>prod_title</code></p>
<p>I tried <code>df[... | <p>You're looking for help on <a href="https://pandas.pydata.org/docs/user_guide/indexing.html" rel="nofollow noreferrer">indexing and selecting data</a>.
This should work for your specific problem</p>
<pre><code>df = pd.DataFrame({
'prod_title' : np.random.permutation([l for l in 'abcdefghijklmnopqrstuvwxyz']),
... | python|pandas|dataframe | 0 |
350,867 | 16,902,282 | Optimising iterative loop | <p>I'm gradually moving from Matlab to Python and would like to get some advice on optimising an iterative loop.
This is how I am currently running the loop, and for info I've included the code that defines the variables.</p>
<pre><code>nh = 2000
h = np.array(range(nh))
nt = 10000
wmin = 1
wmax = 10
hw = np.array(w... | <p>Not specifically about the loop, you're doing a ton of extra work in calls that look like:</p>
<pre><code>np.array(zeros((nh,nt)))
</code></pre>
<p>Just use:</p>
<pre><code>np.zeros((nh,nt))
</code></pre>
<p>in its place. Additionally, you could replace:</p>
<pre><code>h = np.array(range(nh))
</code></pre>
<p>... | python|matlab|loops|numpy|iteration | 0 |
350,868 | 16,899,764 | Numpy array assignment inside class | <p>I am using Python 3.2.3 with NumPy 1.6.1.
I would be very grateful if someone could explain me what does NumPy do when I try to access (in two different ways) an element of a NumPy array.</p>
<p><strong>Code</strong>:</p>
<pre><code>import numpy as np
class MyClass:
def __init__(self,q):
self.coord =... | <p>The <code>firstel</code> variable is a (immutable) <em>value</em> and thus never updated:</p>
<pre><code>self.firstel = q[0] # and stays this value once and for all
</code></pre>
<p>whilst the <code>secontel</code> variable is a <em>view</em> on the original array and so will be updated:</p>
<pre><code>self.seco... | python|class|numpy|python-3.x | 4 |
350,869 | 17,035,767 | Kronecker product in Python and Matlab | <p>I was trying to reproduce a result in Python from MATLAB. However, I can't seem to get it right. This is the correct MATLAB code:</p>
<pre><code>nx = 5;
ny = 7;
x = linspace(0, 1, nx); dx = x(2) - x(1);
y = linspace(0, 1, ny); dy = y(2) - y(1);
onex = ones(nx, 1);
oney = ones(ny, 1);
Dx = spdiags([onex -2*onex o... | <p>Use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.kron.html" rel="noreferrer"><code>sparse.kron</code></a> for the Kronecker product of sparse matrices.</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html" rel="noreferrer"><code>numpy.kron</code></a> does ... | python|matlab|numpy|scipy | 5 |
350,870 | 16,975,318 | Pandas: aggregate when column contains numpy arrays | <p>I'm using a pandas DataFrame in which one column contains numpy arrays. When trying to sum that column via aggregation I get an error stating 'Must produce aggregated value'.</p>
<p>e.g. </p>
<pre><code>import pandas as pd
import numpy as np
DF = pd.DataFrame([[1,np.array([10,20,30])],
[1,np.array... | <p>One, perhaps more clunky way to do it would be to iterate over the <code>GroupBy</code> object (it generates <code>(grouping_value, df_subgroup)</code> tuples. For example, to achieve what you want here, you could do:</p>
<pre><code>grouped = DF.groupby("category")
aggregate = list((k, v["arraydata&q... | python|numpy|pandas|aggregation | 15 |
350,871 | 17,063,458 | Reading an Excel file in python using pandas | <p>I am trying to read an excel file this way :</p>
<pre><code>newFile = pd.ExcelFile(PATH\FileName.xlsx)
ParsedData = pd.io.parsers.ExcelFile.parse(newFile)
</code></pre>
<p>which throws an error that says two arguments expected, I don't know what the second argument is and also what I am trying to achieve here is t... | <p>Close: first you call <code>ExcelFile</code>, but then you call the <code>.parse</code> method and pass it the sheet name.</p>
<pre><code>>>> xl = pd.ExcelFile("dummydata.xlsx")
>>> xl.sheet_names
[u'Sheet1', u'Sheet2', u'Sheet3']
>>> df = xl.parse("Sheet1")
>>> df.head()
... | python|python-2.7|pandas | 254 |
350,872 | 18,986,864 | How to create multiple value dictionary from pandas data frame | <p>Lets say I have a pandas data frame with 2 columns(column A and Column B):
For values in column 'A' there are multiple values in column 'B'.
I want to create a dictionary with multiple values for each key those values should be unique as well. Please suggest me a way to do this.</p> | <p>One way is to groupby columns A:</p>
<pre><code>In [1]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
In [2]: df
Out[2]:
A B
0 1 2
1 1 4
2 5 6
In [3]: g = df.groupby('A')
</code></pre>
<p>Apply <code>tolist</code> on each of the group's column B:</p>
<pre><code>In [4]: g['B'].tolist(... | python-3.x|pandas | 8 |
350,873 | 18,966,425 | How do I create a custom 4x4 array using NumPy? | <p>I am new to Python and I am having a bit of trouble with the array functions.
I want to make a 4 by 4 array which contains the numbers from 1 to 16.</p>
<p>I know that using <code>np.zeros((4,4))</code> outputs a 4x4 array with all zeros.
Using <code>np.array(range(17))</code> I can get an array of the required nu... | <p>The problem is that you are creating an array of 17 values (zero through 16), which can't be reshaped to 4x4. Instead:</p>
<pre><code>>>> a = np.arange(1, 17).reshape(4,4)
>>> a
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
</code></pre> | python|arrays|numpy | 9 |
350,874 | 19,002,631 | Conditional reset of data in pandas dataframe | <p>I am looking for an efficient way (without looping/iteration, if possible) of getting my output below using inputs a and b. a is an array with random numbers and b is and array which defines reset points. </p>
<pre><code>a = pd.DataFrame([2, 5, 4, 1, 6, 6, 4, 7])
b = pd.DataFrame([1, 0, 0, 1, 0, 0, 1, 0])
</code></... | <p>You can simply index with <code>b</code> as a boolean array, and then fill the <code>NaN</code> values, in this case with a forward fill (<code>ffill</code> method):</p>
<pre><code>a[b.astype(bool)].fillna(method='ffill')
</code></pre>
<p>For <code>fillna</code> docs, see: <a href="http://pandas.pydata.org/pandas-... | python-2.7|pandas | 7 |
350,875 | 18,855,387 | Efficient Kalman filter implementation on gridded data | <p>I have written a very simple Kalman filter that operates on time series (with data gaps included). It works nicely, but I happen to have a <em>data cube</em> of data (an array of shape <code>Nt, Ny, Nx</code>, say), and I want to apply my temporal Kalman filter for each pixel in the data cube. I have done the obviou... | <p>I made a simple vectorised Kalman filter like this for processing movie frames. It's pretty quick but currently limited to 1D inputs and outputs, and it doesn't do EM optimisation of any of the filter parameters.</p>
<pre><code>import numpy as np
def runkalman(y, RQratio=10., meanwindow=10):
"""
A simple v... | python|numpy|kalman-filter | 3 |
350,876 | 22,210,811 | Plot specific column after DataFrame aggregation | <p>I would like to plot a bar and line graph of specific columns. </p>
<p>Using <code>agg</code> function I got as many new columns as there are functions.
What can I do if I want to plot only column sum of <strong><code>A</code></strong> and mean of <strong><code>B</code></strong> column ?</p>
<p><img src="https://... | <p>You have a hierarchical index. So you just need to select the right columns using the <code>tuple</code> syntax.</p>
<p>So instead of:</p>
<pre><code>ax = df2['A'].plot(kind="bar")
</code></pre>
<p>use:</p>
<pre><code>ax = df2[('A', 'sum')].plot(kind="bar")
</code></pre>
<p>and instead of:</p>
<pre><code>ax2.... | python|matplotlib|pandas | 7 |
350,877 | 21,998,354 | Pandas won't fillna() inplace | <p>I'm trying to fill NAs with "" on 4 specific columns in a data frame that are string/object types. I can assign these columns to a new variable as I fillna(), but when I fillna() inplace the underlying data doesn't change.</p>
<pre><code>a_n6 = a_n6[["PROV LAST", "PROV FIRST", "PROV MID", "SPEC NM"]].fillna("")
a_... | <h2>Use a <code>dict</code> as the <code>value</code> argument to <code>fillna()</code></h2>
<p>As mentioned in the comment by @rhkarls on @Jeff's answer, using <code>.loc</code> indexed to a list of columns won't support <code>inplace</code> operations, which I too find frustrating. Here's a workaround.</p>
<p>Exampl... | python|pandas|dataframe | 31 |
350,878 | 21,989,513 | Finding index of maximum value in array with NumPy | <p>I would like to find a maximum in a <code>float64</code> array, excluding <code>nan</code> values.</p>
<p>I saw <code>np.nanmax</code> function but it doesn't give the index corresponding to the found value.</p>
<p>it 's quite strange to scan after to the value specially the function necessarily use the index ??? ... | <p>Numpy has an <code>argmax</code> function that returns just that, although you will have to deal with the <code>nan</code>s manually. <code>nan</code>s always get sorted to the end of an array, so with that in mind you can do:</p>
<pre><code>a = np.random.rand(10000)
a[np.random.randint(10000, size=(10,))] = np.nan... | python|arrays|numpy|max | 18 |
350,879 | 22,018,816 | join or merge values calculated on grouped pandas dataframe | <p>I have a DataFrame containing density values. I'd like to group by the 'hour' value, bin the densities, and add a new column to my original df, containing the bin number. This is failing, however:</p>
<pre><code>df = pd.DataFrame({
'hours': np.random.randint(0, 24, 10000),
'density' : np.random.sample(10000... | <p>Try to transform on column like this - </p>
<pre><code>df['bins'] = df.groupby(df.hours).density.transform(func)
</code></pre>
<p>Note: func needs to be changed to receive Series as arg</p> | python|pandas | 0 |
350,880 | 22,214,463 | One minus a small number equals one? Dealing with small numbers | <p>The title is self explanatory. What is going on here? How can I get this not to happen? Do I really have to change all of my units (it's a physics problem) just so that I can get a big enough answer that python doesn't round 1-x to 1?</p>
<p>code:</p>
<pre><code>import numpy as np
import math
vel=np.array([5e-30,... | <p>In python <a href="http://docs.python.org/library/decimal.html#module-decimal" rel="nofollow noreferrer">decimal</a> may work and maybe <a href="https://code.google.com/p/mpmath/" rel="nofollow noreferrer">mpmath</a>.</p>
<p>as is discussed in this SO <a href="https://stackoverflow.com/questions/11522933/python-flo... | python|numpy|floating-accuracy | 2 |
350,881 | 22,425,921 | Pass a 2d numpy array to c using ctypes | <p>What is the correct way to pass a numpy 2d - array to a c function using ctypes ?
My current approach so far (leads to a segfault):</p>
<p>C code :</p>
<pre><code>void test(double **in_array, int N) {
int i, j;
for(i = 0; i<N; i++) {
for(j = 0; j<N; j++) {
printf("%e \t", in_arra... | <p>This is probably a late answer, but I finally got it working. All credit goes to Sturla Molden at <a href="http://numpy-discussion.10968.n7.nabble.com/Pass-2d-ndarray-into-C-double-using-ctypes-td39414.html">this link</a>.</p>
<p>The key is, note that <code>double**</code> is an array of type <code>np.uintp</code>.... | python|c|numpy|ctypes | 27 |
350,882 | 17,975,653 | Vectorizing feature hashing in python | <p>I'm wondering if anyone knows how to vectorize feature hashing in Python.
For example, this is my code:</p>
<pre><code> import numpy as np
hashlen = 5
x = np.array([4, 7, 4, 2, 6, 8, 0, 6, 3, 1])
h = np.array([0, 3, 1, 2, 4, 2, 1, 0, 3, 1])
</code></pre>
<p>In feature hashing, h represents the indic... | <p>You can use bincount with weights to do what you are asking:</p>
<pre><code>>>> np.bincount(h,weights=x)
array([ 10., 5., 10., 10., 6.])
</code></pre>
<p>For matrices:</p>
<pre><code>>>> import numpy as np
>>> a=np.random.randint(0,5,(50,50))
>>> rand=np.random.rand(5)
&g... | python|arrays|hash|numpy|vectorization | 5 |
350,883 | 17,907,460 | Serialize a dictionary containing pandas data-frames (Python) | <p>I have a dict containing several pandas Dataframe (identified by keys) , any suggestion to effectively serialize (and cleanly load) it . Here is the structure (a pprint display output ). Each of dict['method_x_']['meas_x_'] is a pandas Dataframe. The goal is to save the dataframes for a further plotting with some s... | <p>Use <a href="http://docs.python.org/3/library/pickle.html" rel="noreferrer">pickle.dump(s) and pickle.load(s)</a>. It actually works. Pandas DataFrames also have their own method df.save("filename") that you can use to serialize a single DataFrame...</p> | python|serialization|dictionary|pandas|dataframe | 6 |
350,884 | 18,003,179 | Python Pandas: get same column from all keys of concatenated dataframe (with Multindex) | <p>Given a dataframe that was created by concatenating other dataframes with exactly the same columns/rows, how do you get all of one column for all keys?</p>
<p>Here is a concrete example:</p>
<pre><code>In [9]: df = pd.DataFrame(np.random.randn(nrow, ncol), columns=list(string.uppercase[:ncol]))
In [10]: df
Out[10... | <p>Should be able to just take out a slice with xs</p>
<pre><code>df_concat.xs('A', level=1, axis=1)
</code></pre> | python|pandas | 2 |
350,885 | 17,793,041 | Python script saving over input variables | <p>I'm writing a Python script as part of research on climate change and forest fires. This may be a novice question, but I am a beginner programmer.
I have large numpy arrays (1) of meteorological variables (for instance: temperature, relative humidity, etc). In one part of the program, I define another array ('t0') ... | <pre><code>t0 = temp
</code></pre>
<p>doesn't actually perform a copy. It makes the names <code>t0</code> and <code>temp</code> both refer to the same array. You probably want</p>
<pre><code>t0 = temp.copy()
</code></pre>
<p>which makes a new, independent array.</p> | python|numpy | 0 |
350,886 | 18,180,763 | set difference for pandas | <p>A simple pandas question: </p>
<p>Is there a <code>drop_duplicates()</code> functionality to drop every row involved in the duplication? </p>
<p>An equivalent question is the following: Does pandas have a set difference for dataframes? </p>
<p>For example:</p>
<pre><code>In [5]: df1 = pd.DataFrame({'col1':[1,2,3... | <p>Bit convoluted but if you want to totally ignore the index data. Convert the contents of the dataframes to sets of tuples containing the columns:</p>
<pre><code>ds1 = set(map(tuple, df1.values))
ds2 = set(map(tuple, df2.values))
</code></pre>
<p>This step will get rid of any duplicates in the dataframes as well (... | python|pandas|dataframe | 69 |
350,887 | 4,150,542 | Determine Index of Highest Value in Python's NumPy | <p>I want to generate an array with the index of the highest max value of each row. </p>
<pre><code>a = np.array([ [1,2,3], [6,5,4], [0,1,0] ])
maxIndexArray = getMaxIndexOnEachRow(a)
print maxIndexArray
[[2], [0], [1]]
</code></pre>
<p>There's a np.argmax function but it doesn't appear to do what I want...</p> | <p>The <code>argmax()</code> function <em>does</em> do what you want:</p>
<pre><code>print a.argmax(axis=1)
array([2, 0, 1])
</code></pre> | python|numpy | 20 |
350,888 | 4,155,888 | Freeze of pip requirements, NumPy and SciPy on OS X | <p>I've got a pip requirements file that I'm using with virtualenv to automatically grab dependencies for my application.</p>
<p>The application depends on both NumPy and SciPy and as such my pip requirements file includes:</p>
<pre><code>numpy==1.5.0
scipy==0.8.0
</code></pre>
<p>However, when running this pip in a... | <p>I don't think you can. Pip and setuptools are not standard tools - we try to support them on a good-will basis, but it is brittle. In particular, because scipy setup.py needs numpy to run, it cannot work using the install_requires argument. </p> | python|numpy|scipy|virtualenv|pip | 4 |
350,889 | 8,745,023 | making histogram from a csv file | <p>I am trying to read a column of data from a csv file and create a histogram for it. I could read the data into an array but was not able to make the histogram. Here is what I did:</p>
<pre><code>thimar=csv.reader(open('thimar.csv', 'rb'))
thimar_list=[]
thimar_list.extend(thimar)
z=[]
for data in thimar_list:
z... | <p>modify the sixth line to cast string to numeric</p>
<pre><code> z.append(float(data[7]))
</code></pre>
<p>with this i got some plot with my made up data.</p> | arrays|csv|numpy|histogram | 1 |
350,890 | 55,527,651 | pandas compare 2 columns and only keep matching words strings | <p>I am trying to compare words or stings in 1 dataframe column with another column in the same df and output a 3rd column with only the matching words.</p>
<pre><code>input
Col1
the cat crossed a road
the dog barked
the chicken barked
Col2
the cat alligator
some words here
chicken soup
desired result
Col3
the cat
N... | <p>Use <code>apply</code>, with an <code>' '.join</code>, and than use a list comprehension to get the values that match</p>
<p>Also, you have to use <code>axis=1</code> for it to work:</p>
<pre><code>print(df.apply(lambda x: ' '.join([i for i in x['Col1'].split() if i in x['Col2'].split()]), axis=1))
</code></pre>
... | python|pandas|dataframe|lambda | 3 |
350,891 | 55,283,469 | How to convert a specific range of elements in a panda DataFrame into float numbers? | <p>I have a panda Dataframe like the following</p>
<p><a href="https://i.stack.imgur.com/hDWad.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hDWad.png" alt="enter image description here"></a></p>
<p>and this is the data:</p>
<pre><code> 0 1 2 3 4 ... | <p>Use:</p>
<pre><code>#set columns by first row
df.columns = df.iloc[0]
#set index by first column
df.index = df.iloc[:, 0]
#remove first row, first col and cast to floats
df = df.iloc[1:, 1:].astype(float)
print (df)
0 Total/Target Jaccard Dice VolumeSimilarity \
Label ... | python|python-3.x|pandas|python-2.7|numpy | 1 |
350,892 | 55,544,225 | How to get the tensor of a layer from the name | <p>In order to re-use some hidden layers of a DNN model, I would like to get the tensor of a hidden layer</p>
<p>Here I have a simple example of what I want to do:</p>
<pre><code>import tensorflow as tf
graph = tf.Graph()
with graph.as_default():
X = tf.placeholder(tf.float32, shape=(None, 28*28), name="X")
y = ... | <p>It's because <code>tf.layers</code> calls internal variables differently.
To be able to view it, just print global variables like this </p>
<pre class="lang-py prettyprint-override"><code>...
logits = tf.layers.dense(dnn, 5, name="outputs", kernel_initializer=he_init)
print(tf.global_variables())
hidden =... | python|tensorflow | 0 |
350,893 | 55,474,861 | How to add a column to a dataframe with statistics from a grouping | <p>let's consider the following DataFrame:</p>
<pre><code>d = {'timestamp': ['2019-04-01', '2019-04-01', '2019-04-02', '2019-04-02', '2019-04-02'],\
'type': ['A', 'B', 'B', 'B', 'A'],\
'value': [3, 4, 4, 2, 5]}
df = pd.DataFrame(data=d)
timestamp type value
0 2019-04-01 A 3
1 2019-04-01... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.std.html" rel="nofollow noreferrer"><code>GroupBy.std</code></a>:</p>
<pre><code>df = df.groupby(['timestamp','type'])['value'].std().reset_index()
print (df)
timestamp type value
0 2019-04-01 A NaN
... | python|pandas|dataframe | 1 |
350,894 | 55,357,692 | Why my customized neural network not work, and with high MAE | <p>This is a regression problem using the DNN, which estimate the income.<br>
The network looks like the following picture:
<a href="https://i.stack.imgur.com/f5ZGK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f5ZGK.jpg" alt="enter image description here"></a></p>
<p><a href="https://ibb.co/jH02n... | <p>It makes no sense to multiply <code>x</code> to the output of right network if you can not figure out what <code>x</code> means exactly. The variable <code>x</code> may be a feature of your sample. If so, you better input it into the right network with other features, not multiply it to the output simply.</p> | tensorflow|neural-network|deep-learning|regression | 0 |
350,895 | 55,341,884 | Count indices to array to produce heatmap | <p>I'd like to accumulate indices that point to a <code>m-by-n</code> array to another array of that very shape to produce a heatmap. For example, these indices:</p>
<pre><code>[
[0, 1, 2, 0, 1, 2]
[0, 1, 0, 0, 0, 2]
]
</code></pre>
<p>would produce the following array:</p>
<pre><code>[
[2, 0, 0]
[1,... | <p>Two methods could be suggested. </p>
<p>With <code>np.add.at</code> -</p>
<pre><code>heat = np.zeros(shape,dtype=int)
np.add.at(heat,(a[0],a[1]),1)
</code></pre>
<p>Or with <code>tuple()</code> based one for a more <em>aesthetic</em> one -</p>
<pre><code>np.add.at(heat,tuple(a),1)
</code></pre>
<p>With <code>bi... | python|numpy | 1 |
350,896 | 55,352,409 | python setuptools compile fortran code and make an entry points | <p>Here's my directory structure,</p>
<pre><code>├── test
│ ├── test.f90
│ ├── __init__.py
│ └── test.py
</code></pre>
<p>Now I want to make a package from this with an command line tool <code>test</code>.
Now I have two options, 1. numpy distutils and 2. setuptools.</p>
<p>Problem with <code>distutils</code> ... | <p>It's actually a pretty simple trick. Just import <code>setuptools</code> before importing <code>setup</code> from <code>numpy.distutils.core</code> and you're good to go. The explanation for this is that <code>numpy.distutils</code> is much more than just the vanilla <code>distutils</code> with some package-specific... | python|numpy|setuptools|setup.py|python-packaging | 7 |
350,897 | 55,178,749 | How to check if any of the entries in each column of my dataframe is a number? | <p>I am impressed by using a simple code that enables me to check if there is an entry of my DataFrame that contains integer or a float in my the columns</p>
<p>Consider the following DataFrame</p>
<pre><code>import numpy as np
import pandas as pd
index =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ... | <p>Use <code>pandas.to_numeric</code> with argument <code>errors='coerce'</code> and create a list comprehension of any column that contains any valid number.</p>
<pre><code>number_cols = new_df.columns[[pd.to_numeric(new_df[col], errors='coerce').notna().any() for col in new_df]]
</code></pre>
<p>And you can index b... | python-3.x|pandas | 4 |
350,898 | 55,407,047 | How to cycle a Pandas dataframe grouping by hierarchical multiindex from top to bottom and store results | <p>I'm trying to create a forecasting process using hierarchical time series. My problem is that I can't find a way to create a for loop that hierarchically extracts daily time series from a pandas dataframe grouping the sum of quantities by date. The resulting daily time series should be passed to a function inside th... | <p>I'm currently working on a switch dataset that I polled from an sql database where each port on the respective switch has a data frame which has a time series. So to access this time series information for each specific port I represented the switches by their IP addresses and the various number of ports on the swit... | python-3.x|for-loop|pandas-groupby|hierarchical-data | 0 |
350,899 | 55,540,010 | Shifting rows with multiindex Pandas | <p>I want to create a table of stocks consisting of three columns:</p>
<p>Quantity Day - 1 | Quantity traded | Quantity Day 0</p>
<p>The stocks come in a frame like :</p>
<pre><code>> df
Date Stock Quantity
2019-04-01 ALSC3 19600
AMAR3 3080
2019-04-02 ALSC3 4000
... | <p>Here you go, assuming the date index are countinuous.</p>
<pre><code>df.Quantity.groupby(level=1).shift(-1)
</code></pre>
<p>This matches your expected output. Although I think "Quantity Day-1" means <code>shift()</code> instead of <code>shift(-1)</code>.</p> | python|pandas|indexing|timestamp | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.