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 |
|---|---|---|---|---|---|---|
9,300 | 58,101,126 | Using Scikit-Learn OneHotEncoder with a Pandas DataFrame | <p>I'm trying to replace a column within a Pandas DataFrame containing strings into a one-hot encoded equivalent using Scikit-Learn's OneHotEncoder. My code below doesn't work:</p>
<pre class="lang-py prettyprint-override"><code>from sklearn.preprocessing import OneHotEncoder
# data is a Pandas DataFrame
jobs_encoder... | <p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="noreferrer"><strong>OneHotEncoder</strong></a> Encodes categorical integer features as a one-hot numeric array. Its <strong>Transform</strong> method returns a sparse matrix if <code>sparse=True</code>, otherwis... | python|pandas|machine-learning|scikit-learn|one-hot-encoding | 35 |
9,301 | 57,928,437 | Pandas groupby to get percent of total rows by specific label | <p>Working with Pandas, I would like to calculate the percentage of rows that have a positive value in a specific column for a distinct breakdown.</p>
<hr />
<h1>Input</h1>
<p>An example likely illustrates this easiest so assume I have a table named <code>table</code> shown below:</p>
<pre><code>| ID | Name | Sex | ... | <p>Most efficient is to take the mean of a Boolean Series within group (<code>GroupBy.mean</code> will use cython). Since the Series we create shares the same index of the DataFrame, you can group in this way:</p>
<pre><code>df['Number'].gt(0).groupby(df['Sex']).mean()
#Sex
#F 0.500000
#M 0.333333
#Name: Number,... | python|python-3.x|pandas|dataframe | 5 |
9,302 | 57,785,687 | Filter Pandas Dataframe based on List of substrings | <p>I have a Pandas Dataframe containing multiple colums of strings.
I now like to check a certain column against a list of allowed substrings and then get a new subset with the result.</p>
<pre><code>substr = ['A', 'C', 'D']
df = pd.read_excel('output.xlsx')
df = df.dropna()
# now filter all rows where the string in t... | <p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>pandas.Series.isin</code></a></p>
<pre class="lang-py prettyprint-override"><code>>>> df.loc[df['type'].isin(substr)]
year type value price
0 2000 A 500 10... | python|pandas | 3 |
9,303 | 58,089,920 | how to group data and calculating a specific task | <p>I have a practice task below:</p>
<p>Calculate the total births over the sample period by grouping the data by name and sex. Subset the group into male and female. Using these subsets, select the top and bottom 3 male and female names. Report them in a single table.</p>
<p>So I have a .csv file ([1]) containing na... | <p>IIUC, this is what you need.</p>
<pre><code>g=g=df.groupby(['name','sex'])['births'].sum().reset_index(name='birth_sum').sort_values('birth_sum',ascending=False)
top_names=g.loc[g.sex=='F'].head(3).append(g.loc[g.sex=='M'].head(3))
bottom_names=g.loc[g.sex=='F'].tail(3).append(g.loc[g.sex=='M'].tail(3))
</code></pr... | python|pandas|csv|group-by|pivot-table | 0 |
9,304 | 34,170,055 | Grouping a row into multiple groups with pandas | <p>I have a set of sentences, and I want to group them such all the rows in a group should share one particular word. However a sentence can belong to many groups because it has many words in it.</p>
<p>So in the example below, there should be a groups like this:</p>
<ul>
<li>A 'temperature' group that includes all t... | <p>My current solution uses pandas' MultiIndex feature. I'm sure it can be improved with some more efficient use of numpy, but I believe this will perform significantly better than the other python-only answer:</p>
<pre><code>import pandas as pd
import numpy as np
# An example data set
df = pd.DataFrame({"sentences":... | python|python-3.x|pandas|group-by | 1 |
9,305 | 34,086,776 | Cumsum with pandas on financial data | <p>I'm very new to python and I have managed to import data from an excel datasheet using the <code>pd.read_excel</code> function. The data is arranged in the following manner in a dataframe :</p>
<p><a href="https://i.stack.imgur.com/Yw3jR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yw3jR.jpg" ... | <p>Seeing as your 'Dates' are just daily entries you can temporarily set the index to that column, call <code>cumsum</code> and then <code>reset_index</code>:</p>
<pre><code>oFX.set_index('Dates').cumsum().reset_index()
</code></pre> | python|pandas|dataframe | 0 |
9,306 | 36,847,022 | What numbers that I can put in numpy.random.seed()? | <p>I have noticed that you can put various numbers inside of <code>numpy.random.seed()</code>, for example <code>numpy.random.seed(1)</code>, <code>numpy.random.seed(101)</code>. What do the different numbers mean? How do you choose the numbers?</p> | <p>Consider a very basic random number generator:</p>
<pre><code>Z[i] = (a*Z[i-1] + c) % m
</code></pre>
<p>Here, <code>Z[i]</code> is the <code>ith</code> random number, <code>a</code> is the multiplier and <code>c</code> is the increment - for different <code>a</code>, <code>c</code> and <code>m</code> combinations... | python|numpy-random | 13 |
9,307 | 49,516,188 | Difference between 'ctx' and 'self' in python? | <p>While using the deep learning library PyTorch I came across definitions like this. Does <code>ctx</code> have the same behavior as <code>self</code>? </p>
<pre><code>class LinearFunction(Function):
@staticmethod
def forward(ctx, input, weight, bias=None):
ctx.save_for_backward(input, weight, bias)
... | <p><strong>A static method (<code>@staticmethod</code>) is called using the class <em>type</em> directly, not an <em>instance</em> of this class:</strong></p>
<pre><code>LinearFunction.backward(x, y)
</code></pre>
<p>Since you have no instance, it does not make sense to use <code>self</code> in a static method.</p>
... | python|pytorch | 9 |
9,308 | 73,436,440 | Replace and merge rows in pandas according to condition | <p>I have a dataframe:</p>
<pre><code> lft rel rgt num
0 t3 r3 z2 3
1 t1 r3 x1 9
2 x2 r3 t2 8
3 x4 r1 t2 4
4 t1 r1 z3 1
5 x1 r1 t2 2
6 x2 r2 t4 4
7 z3 r2 t4 5
8 t4 r3 x3 4
9 z1 r2 t3 4
</code></pre>
<p>And a reference dictionary:</p>
<pre><code>replacement_dict = {
... | <p>Reverse the <code>replacement_dict</code> mapping and <code>map()</code> this new mapping to each of lft and rgt columns to substitute certain values (e.g. x1->X1, y2->Y1 etc.). As some values in lft and rgt columns don't exist in the mapping (e.g. t1, t2 etc.), call <code>fillna()</code> to fill in these valu... | python|pandas|dataframe|numpy | 9 |
9,309 | 73,519,653 | Create sorting dictionary | <p>Write the function dataframe that takes a
dictionary as input and creates a dataframe
from the dictionary, Sort the dictionary.</p>
<p>Instructions</p>
<pre><code>1. Create a dataframe with the input dictionary
2. Columns should be Name Age
3. Print "Before Sorting"
4. Print a Newline
5. Print the datafram... | <pre><code>def dataframe(data):
df = pd.DataFrame(data)
print("Before Sorting")
print(df)
df.sort_values(by=['Age'], inplace=True)
print("After Sorting")
print(df)
</code></pre>
<p>Output :</p>
<pre><code>Before Sorting
Name Age
0 William 42
1 George 10
2 ... | python|pandas|dataframe|dictionary | 1 |
9,310 | 73,515,252 | Special case of counting empty cells "before" an occupied cell in Pandas | <p>Pandas question here.</p>
<p>I have a specific dataset in which we are sampling subjective ratings several times over a second. The information is sorted as below. What I need is a way to "count" the number of blank cells before every "second" (i.e. "1" in the second's column that occur... | <p>If you just want to count the number of NaNs before the first <code>1</code>:</p>
<pre><code>df['seconds'].isna().cummin().sum()
</code></pre>
<p>If you have another value (e.g. empty string)</p>
<pre><code>df['seconds'].eq('').cummin().sum()
</code></pre>
<p>Output: <code>2</code></p>
<p>Or, if you have a range Ind... | python|pandas|timestamp|counting | 1 |
9,311 | 73,451,970 | try convert string to date row per row in pandas or similar | <p>I need to join dataframes with dates in the format <code>'%Y%m%d'</code>. Some data is wrong or missing and when I put pandas with:</p>
<pre><code>try: df['data'] = pd.to_datetime(df['data'], format='%Y%m%d')
except: pass
</code></pre>
<p>If 1 row is wrong, it fails to convert the whole column. I would like it to sk... | <p>Pass <code>errors = 'coerce'</code> to <code>pd.to_datetime</code> to convert the values with wrong date format to NaT. Then you can use <code>Series.fillna</code> to fill those NaT with the input values.</p>
<pre><code>df['data'] = (
pd.to_datetime(df['data'], format='%Y%m%d', errors='coerce')
.fillna(df[... | python-3.x|pandas|datetime | 2 |
9,312 | 73,518,448 | IndexingError: Too many indexers with Dataframe.loc | <p>I got this error while I tried to make telegram alarm bot using FinanceDataReader</p>
<p>Here is the code:</p>
<pre><code>code = 'KQ11'
df = fdr.DataReader('KR11', '2022-08').reset_index()
df['close_sma3d'] = df['Close'].rolling(3).mean()
df['close_sma5d'] = df['Close'].rolling(5).mean()
df['close_sma10d'] = df['Clo... | <p>You use <code>.loc</code> with wrong values. It rather need <code>.loc[ row_indexes, columns_names ]</code> but you use some strange <code>code</code> and value <code>prev_date</code></p>
<p>To select some date it would need</p>
<pre><code>df.loc[ df["Date"] == prev_date, 'Close']
</code></pre>
<p>But you ... | python|pandas | 0 |
9,313 | 35,213,402 | Make a "linear-within-logspace" array that goes like [1, 2, 3, ..., 10, 20, 30, ...] | <p>I'm trying to run a certain simulation that takes one parameter as input. I need to run it for a range of different parameter values that spans several orders of magnitude, but also gives a picture of the variation within each order of magnitude.</p>
<p>In short, I need my parameter to take values <code>param = [1,... | <p>You can easily make such an array with two loops:</p>
<pre><code>param = [multiplier * magnitude for magnitude in [1, 10, 100] for multiplier in [1, 2, 3, 4, 5, 6, 7, 8, 9]]
</code></pre> | python|arrays|numpy | 2 |
9,314 | 35,061,261 | how to merge pandas dataframe with different lengths | <p>I have a pandas dataframe like following.. </p>
<pre><code>df_fav_dish
item_id buyer_id dish_count dish_name
121 261 2 Null
126 261 3 Null
131 261 7 Null
132 261 6 Null
133 261 2 Null
135 261 ... | <p>Your column <code>item_id</code> in dataframe <code>data</code> contains duplicity, so:</p>
<p>If no duplicity:</p>
<pre><code>print data
item_id item_name
0 121 Paneer
1 140 Chicken
2 131 Prawns
print df_fav_dish
item_id buyer_id dish_count dish_name
0 139 309 ... | python|pandas | 2 |
9,315 | 67,191,136 | How to add a new date column derived from existing date column based on the shelf life of the products to my csv file using pandas? | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Room</th>
<th style="text-align: center;">rack</th>
<th style="text-align: right;">type</th>
<th style="text-align: right;">no.of items</th>
<th style="text-align: right;">manufacturing date</th>
<th style="text-align: ri... | <p>Date data from csv is recognized as a string. So you first convert it into datetime format</p>
<pre><code>from datetime import datetime
from datetime import timedelta
df['LLQ'] = df['manufacturing date'].apply(lambda x: (datetime.strptime(x, "%m/%d/%Y") + timedelta(days=21)).strftime("%m/%d/%Y&quo... | python|pandas|csv | 0 |
9,316 | 67,220,775 | single column in dataframe needs to be broken up into 3 columns | <p>I have been using stack overflow a lot lately and I appreciate the community here.</p>
<p>I have a code that I have been working on that is finally starting to look like it should be I have one glitch that I haven't been able to get past.</p>
<p>I pulled data from a site for different states, they all have the same ... | <p>you can set a custom index then use <code>unstack()</code> and rename. This is based on the assumption that the headers in your pic above match your target dataset, (i.e the index is repeated in multiples of 3)</p>
<pre><code>df1 = df.set_index(df.groupby(level=0)\
.cumcount(),append=True).stack()... | pandas|selenium|beautifulsoup|multiple-columns | 3 |
9,317 | 67,245,275 | Extracting str from pandas dataframe using json | <p>I read csv file into a dataframe named df</p>
<p>Each rows contains str below.</p>
<blockquote>
<p>'{"id":2140043003,"name":"Olallo Rubio",...}'</p>
</blockquote>
<p>I would like to extract "name" and "id" from each row and make a new dataframe to store the str.</p>
... | <pre class="lang-py prettyprint-override"><code>text={
"id": 2140043003,
"name": "Olallo Rubio",
"is_registered": True,
"chosen_currency": 'Null',
"avatar": {
"thumb": "https://ksr-ugc.imgix.net/assets/019/223/259/165... | python|json|python-3.x|pandas|dataframe | 0 |
9,318 | 67,541,324 | Augmenting image in tensorflow 1 cause to have an tensor in return | <p>I want to augment my images without using keras. I came across with that website: <a href="https://www.wouterbulten.nl/blog/tech/data-augmentation-using-tensorflow-data-dataset/" rel="nofollow noreferrer">https://www.wouterbulten.nl/blog/tech/data-augmentation-using-tensorflow-data-dataset/</a></p>
<p>The problem is... | <p>Tensorflow provides image augmentation in two ways, one s using tf.keras preprocessing libraries and other one is using tf.image.
Use the following sample code with tf.image performing image augmentation.</p>
<pre><code>def augment(image_label, seed):
image, label = image_label
image, label = resize_and_rescale(... | tensorflow | 1 |
9,319 | 67,300,269 | Using groupby() and value_counts() | <p>The goal is to identify the count of colors in each <code>groupby()</code>.</p>
<p><img src="https://i.stack.imgur.com/IYhBU.png" alt="" /></p>
<p>If you see the outcome below shows the first group color blue appears 3 times.</p>
<p>The second group yellow appears 2 times and third group blue appears 5 times</p>
<p... | <p>If you give size to the transform function, it will be in tabular form without aggregation.</p>
<pre><code>df['Count'] = df.groupby(['X','Y']).Color.transform('size')
df.set_index(['X','Y'], inplace=True)
df
Color Count
X Y
A B Blue 3
B Blue 3
B Blue 3
C D Yellow 2
... | python|pandas | 1 |
9,320 | 67,255,661 | Compare Array numbers with DF column. If exists in df, than write to new df | <p>I have the following problem:
I have an array with multiple ID's and i also have a column in a df, with which I want to match these ID's.
If equal, the row should be written to a new DF.</p>
<p>This is my array, called manhatten_ids</p>
<pre><code>array([ 4, 12, 13, 24, 41, 42, 43, 45, 48, 50, 68, 74, 7... | <p>So we can do this iteratively by using the enumerate function two look through the values of the location column like so:</p>
<pre><code>newdf = pd.DataFrame()
row_ind = 0 #row of new dataframe that you will write on
vals = df.DOLocationID.values #get values of location column
for i, val in enumerate(vals):
if ... | python|pandas|data-science|jupyter | 0 |
9,321 | 34,654,220 | tensorflow check image is in reader | <p>I'm not sure whether TensorFlow actually has actually decoded an image when the output is only: <code>Tensor("DecodeJpeg:0", shape=TensorShape([Dimension(None), Dimension(None), Dimension(None)]), dtype=uint8)</code></p>
<p><strong>How can I show the image and label from the Tensor object?</strong></p>
<p>(code pa... | <p>It seems there is code omitted in your second code section, no?</p>
<p>Try the solution suggested <a href="http://andyljones.tumblr.com/post/133267887103/tensorflow-placeholder-queue-errors" rel="nofollow noreferrer">here</a>. You have to initialize the placeholders before you start the queue runner. That fixed a s... | python|image|tensorflow | 1 |
9,322 | 34,609,531 | Select size filtered elements in a large array (raster) | <p>I could need help on this:</p>
<p>On a large boolean numpy array (imported raster) (2000x2000), I try to select only elements that are greater than 800 units. (number of total elements > 1000)</p>
<p>I tried a loop:</p>
<pre><code>labeled_array, num_features = scipy.ndimage.label(my_np_array, structure = None, ou... | <p>Here's a vectorized approach based on binning with <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> and performing the cumulative ORing at <code>big_zones += zone_array</code> with <a href="http://docs.scipy.org/doc/numpy-1.10.1/ref... | python|arrays|numpy|raster|ndimage | 1 |
9,323 | 34,549,974 | Pandas: Writing data frame to Excel (.xls) file issue | <p>I am trying to write the data frame to excel and also making the cell width (20) and trying to hide grid lines. So far I did like :</p>
<pre><code>writer = ExcelWriter('output.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()
worksheet = writer.sheets['Sheet1']
# Trying to set column width as 18
worksheet.set_c... | <p>IIUC, for the <code>set_column</code> width you're actually write your <code>df</code> twice; the correct workflow should be the following (EDIT: add <code>engine</code> keyword):</p>
<pre><code>import pandas as pd
writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter')
df.to_excel(writer,'Sheet1')
worksheet... | python|pandas|dataframe|xls | 2 |
9,324 | 60,178,705 | Dask Map Tensorflow across Partitions | <p>I have a Tensorflow model that I want to run (not train) on my Dask Dataframe. I'm using <code>map_partitions</code>. However, when I look at the dashboard to check progress, it is only running 1 task for all of the work . I expected it to process the partitions concurrently. What am I doing wrong?</p>
<p>Start my ... | <p>The answer, as I discovered, is quite simple. Since I'm calling <code>head</code> as opposed to <code>compute</code> I guess Dask only uses 1 worker... If one uses <code>compute</code> the tasks are spread across the workers.</p> | tensorflow|dask|dask-distributed | 0 |
9,325 | 60,324,897 | Unable to Pass Video Frame for Object Detection Tensorflow python | <p>I am able to process the video frames by saing the frame as an image and then processing it. But was unable to pass frame directly to the object detection.
Saving image with imwrite is making program slow...</p>
<p>Here is my main method:</p>
<pre><code>cap = cv2.VideoCapture(gstreamer_pipeline(flip_method=2), cv... | <p>open cv reads image in bgr colour spectrum conver it to rgb and send the image for detection, api for the same is - </p>
<p>frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)</p> | opencv|tensorflow|object-detection|nvidia-jetson-nano | 0 |
9,326 | 60,041,461 | How to determine the differences in parquet files | <p>I'm storing a pandas DataFrame in a parquet file with this code snippet:</p>
<pre><code>df.to_parquet(path, engine="pyarrow", compression="snappy")
</code></pre>
<p>As part of a regression test, I save the file and compare it to a previously generated file. I tried comparing the file contents in 3 different ways:<... | <blockquote>
<p>How can I dig deeper to find the differences between the parquet
files?</p>
</blockquote>
<p>You can compare the metadata dictionaries and show possible differences using <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertDictEqual" rel="nofollow noreferrer"><code>assertDic... | pandas|parquet|pyarrow | 1 |
9,327 | 60,077,538 | How to speed up intersection of dict of sets in Python | <p>I have a dictionary with a set of integers.</p>
<pre><code>{'A': {9, 203, 404, 481},
'B': {9},
'C': {110},
'D': {9, 314, 426},
'E': {59, 395, 405}
}
</code></pre>
<p>You can generate the data with this:</p>
<pre><code>data = {}
for i in string.ascii_uppercase:
n = 25
rng = np.random.default_rng()
... | <p>The problem here is how to efficiently find the intersection of several sets. According to the comments: <em>"Max n is 10 million - 30 million and the columns a,b,c,d can be almost unique rows to 1 million in common."</em> So the sets are large, but not all the same size. Set intersection is an <a href="https://en.w... | python|pandas|set | 6 |
9,328 | 65,287,506 | getting correct index of numpy array | <p>I have to compare np.arrays pairwise and I need the index back.</p>
<p>My code is:</p>
<pre><code>import numpy as np
Vals = np.array([[1.0, 1.0], [2., 2.], [1., 2.], [2., 1.], [3., 3.], [3., 3.]])
for Val in itertools.combinations(Vals,2):
X1 = Val[0][0]
X2 = Val[1][0]
Y1 = Val[0][1]
Y2 = Val[1][1]
... | <pre><code>for i, j in itertools.combinations(range(len(Vals)), 2):
print(Vals[i], i, "|", Vals[j], j)
</code></pre>
<pre class="lang-none prettyprint-override"><code>[1. 1.] 0 | [2. 2.] 1
[1. 1.] 0 | [1. 2.] 2
[1. 1.] 0 | [2. 1.] 3
[1. 1.] 0 | [3. 3.] 4
[1. 1.] 0 | [3. 3.] 5
[2. 2.] 1 | [1. 2.] 2
[2. 2.]... | python|numpy|numpy-ndarray | 0 |
9,329 | 65,424,771 | How to convert one-hot vector to label index and back in Pytorch? | <p>How to transform vectors of labels to one-hot encoding and back in Pytorch?</p>
<p>The solution to the question was copied to here after having to go through the entire forum discussion, instead of just finding an easy one from googling.</p> | <p>From <a href="https://discuss.pytorch.org/t/pytocrh-way-for-one-hot-encoding-multiclass-target-variable/68321" rel="noreferrer">the Pytorch forums</a></p>
<pre><code>import torch
import numpy as np
labels = torch.randint(0, 10, (10,))
# labels --> one-hot
one_hot = torch.nn.functional.one_hot(target)
# one-ho... | python|pytorch|one-hot-encoding|multiclass-classification | 5 |
9,330 | 65,203,030 | Get all possible pairs within a cell in df python | <p>I have a df such as :</p>
<pre><code>COL1 COL2 COL3
G1 1 ['B_-__Canis_lupus']
G1 2 ['A_-__Felis_cattus','O_+__Felis_cattus','D_-__Felis_sylvestris]
G2 1 ['Q_-__Mus_musculus','S_-__Mus_griseus','P_-__Mus_rattus']
</code></pre>
<p>and I would like from that to create 1 new column :</p>
<p><strong>COL4</... | <p>Use <code>itertools.combinations</code>. The <code>COL3</code> column contains list as string which requires <code>literal_eval</code> to convert to <code>list</code>.</p>
<pre><code>from itertools import combinations
from ast import literal_eval
def all_combinations(x):
return [list(combinations(x, i)) for i i... | python|python-3.x|pandas|dataframe | 1 |
9,331 | 65,133,881 | lambda function on list in dataframe column error | <p>I have a list of numbers inside of a pandas dataframe and i am trying to use a lambda function + list comprehension to remove values from these lists.</p>
<p>col 1 col2</p>
<p>a [-1, 2, 10, 600, -10]</p>
<p>b [-0, -5, -6, -200, -30]</p>
<p>c .....</p>
<p>etc.</p>
<pre><code>df.col2.apply(lamb... | <p>Because <code>x</code> in your lambda is a float number, and you cant loop over float :p.
if you need to do so. you can</p>
<pre class="lang-python prettyprint-override"><code>In [2]: np.random.seed(4)
...: df = pd.DataFrame(np.random.randint(-5,5, 7)).rename(columns={0:"col2"})
...: df.col2 = df.col... | python|pandas|numpy|lambda | 1 |
9,332 | 49,887,488 | Frequency of Values by Date in a Pandas DataFrame | <p>I have a DataFrame in Pandas that looks like this. <code>date</code> is an index of dtype <code>datetime64</code>.</p>
<pre><code> keyword id
date
2017-03-31 21:22:33+00:00 cat 0
2017-07-07 11:28:36+00:00 dog 1
2017-03-31 01:18:50+00:00 cat 2
... | <p>By using <code>get_level_values</code> with <code>date</code>(Get the date part from the datetime format)</p>
<pre><code>df.groupby([df.index.get_level_values(0).date,df.keyword]).size()
Out[867]:
keyword
2017-03-31 cat 3
2017-07-07 dog 1
2017-08-23 elephant 1
dtype: int64
</code... | python|pandas | 2 |
9,333 | 49,793,557 | How to perform Kernel Density Estimation in Tensorflow | <p>I'm trying to write a Kernel Density Estimation algorithm in Tensorflow.</p>
<p>When fitting the KDE model, I am iterating through all the data in the current batch and, for each, I am creating a kernel using the <code>tensorflow.contrib.distributions.MultivariateNormalDiag</code> object:
<code>
self.kernels = [Mul... | <p>One answer that I found for this problem tackles the problem of fitting the KDE and predicting the probabilities in one fell swoop. The implementation is a bit hacky, though.</p>
<pre><code>def fit_predict(self, data):
return tf.map_fn(lambda x: \
tf.div(tf.reduce_sum(
tf.map_fn(lambda x_i:... | python|tensorflow|kernel-density | 0 |
9,334 | 49,916,607 | What does pandas index.searchsorted() do? | <p>I'm working on two dataframes <code>df1</code> and <code>df2</code>.
I used the code : </p>
<pre><code>df1.index.searchsorted(df2.index)
</code></pre>
<p>But I'm not sure about how does it work.
Could someone please explain me how ?</p> | <p>The method applies a <a href="https://en.wikipedia.org/wiki/Binary_search_algorithm" rel="noreferrer">binary search</a> to the index. This is a well-known algorithm that uses the fact that values are already in sorted order to find an insertion index in as few steps as possible.</p>
<p>Binary search works by pickin... | python|pandas|dataframe|indexing | 9 |
9,335 | 63,824,157 | While using np.arange() it was incrementing with wrong step size | <pre><code>for i in np.arange(0.0,1.1,0.1):
print(i)
</code></pre>
<p>Output:</p>
<pre><code>0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6000000000000001
0.7000000000000001
0.8
0.9
1.0
</code></pre>
<p>Expected output:</p>
<pre><code>0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
</code></pre> | <p>It's not incrementing by the wrong step size, those are just floating point errors. From <a href="https://www.geeksforgeeks.org/floating-point-error-in-python/" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>This can be considered as a bug in Python, but it is not. This has little to do with Python, and muc... | python|numpy | 0 |
9,336 | 63,781,144 | TypeError: expected string or bytes-like object in Pandas | <p>I want to tokenize text, but couldn't. How can I solve this?
Here is my problem:
<img src="https://i.stack.imgur.com/BbjlW.png" alt="enter image description here" /></p>
<p><img src="https://i.stack.imgur.com/GX5rW.png" alt="2nd image is my problem" /></p>
<pre><code>#read_text from file
data = pd.read_csv("in... | <p>Try this:</p>
<pre><code>for column in data:
a = data.apply(lambda row: t.bn_word_tokenizer(row), axis=1)
print(a)
</code></pre>
<p>This will print one column at a time. If you want to convert the entire dataframe rather than just print then replace a with data[column] in the code above.</p> | python|pandas | 0 |
9,337 | 63,913,629 | Fast vectorized way to convert row vector to inptrs for sparse matrix? | <p>For sparse matrices, we usually pass in column indices (<code>indices</code>) and an <code>indptr</code> vector that indexes the <code>indices</code> vector so that <code>indices[indptr[i]:indptr[i+1]]</code> are the elements of row <code>i</code> in the sparse matrix.</p>
<p>Is there a fast, vectorized, preferably ... | <p>I think what you are looking for is this:</p>
<pre><code>np.bincount(rows).cumsum()
#[1 3 6 7 7 8]
</code></pre>
<p>And if there are rows at the bottom of your matrix that might be empty, simply add that as argument to <code>bincount</code> (per @CJR's recommendation):</p>
<pre><code>np.bincount(rows, minlength=num_... | python|arrays|numpy|scipy|sparse-matrix | 6 |
9,338 | 47,016,371 | Increasing column value pandas | <p>I have a dataframe of 143999 rows which contains position and time data.
I already made a column "dt" which calulates the time difference between rows.
Now I want to create a new column which gives the dt values a group number.
So it starts with group = 0 and when dt > 60 the group number should increase by 1.
I tri... | <p>You can take advantage of the fact that <code>True</code> evaluates to 1 and use <code>.cumsum()</code>.</p>
<pre><code>densdata = pd.DataFrame({'dt': np.random.randint(low=50,high=70,size=20),
'group' : np.zeros(20, dtype=np.int32)})
print(densdata.head())
dt group
0 52 0
1 59 ... | python|pandas | 0 |
9,339 | 47,000,799 | Indexing 2nd dimension in tensorflow | <p>I have an array of xyz coordinates of points of shape <code>(nsamples, npoints, 3)</code>.</p>
<p>I am trying to build a tensorflow graph that selects the two points closest to the origin.</p>
<p>I've gotten this far</p>
<pre><code>r2 = tf.reduce_sum(tf.pow(centeredxyz, 2), axis=2)
idx = tf.nn.top_k(-r2, 2)[1]
</... | <p>I managed to patch together an ugly version. Hurts the brain but seems to work.</p>
<pre><code>def gather_second_multicol(data, idx):
nsamples = tf.shape(idx)[0]
nselcol = tf.shape(idx)[1]
idx = tf.reshape(idx, [-1, 1])
range = tf.range(nsamples)
range = tf.tile(tf.expand_dims(range, 0), [nselco... | tensorflow | 0 |
9,340 | 47,039,760 | Dataset API, Iterators and tf.contrib.data.rejection_resample | <p><strong>[Edit #1 after @mrry comment]</strong>
I am using the (great & amazing) Dataset API along with tf.contrib.data.rejection_resample
to set a specific distribution function to the input training pipeline. </p>
<p>Before adding the tf.contrib.data.rejection_resample to the input_fn I used the one shot Iter... | <p>Following @mrry response I could come up with a solution on how to use the Dataset API with tf.contrib.data.rejection_resample (using TF1.3).</p>
<p><strong>The goal</strong></p>
<p>Given a feature/label dataset with some distribution, have the input pipeline reshape the distribution to specific target distributio... | tensorflow|iterator | 12 |
9,341 | 46,738,941 | Pandas duplicated and drop_duplicated does not work properly | <p>The dataset named 'changes' was obtained from a merge by RID:</p>
<pre><code>changes.head()
DX_bl RID DX_m12
0 1 3 1
1 0 4 0
2 0 6 0
3 0 8 0
4 1 10 1
</code></pre>
<p>I've used the two following commands with the intention of identifying l... | <p>OK, i missed your comment "with the intention of identifying lines in which DX_bl and DX_m12 are different". </p>
<p>If you want to list all lines where these 2 columns differ, you can use this:</p>
<pre><code>changes[changes['DX_bl'] != changes['DX_m12']]
</code></pre>
<p>or, equivalently:</p>
<pre><code>change... | python|pandas | 0 |
9,342 | 46,684,027 | does pip install -U break virtualenv? | <p>I have a virtualenv where I'm running python 2.7.13. I did install numpy a while ago. Today I wanted to install statsmodels as well in the same virtualenv. That's why I did (according to the webpage):</p>
<pre><code>pip install -U statsmodels
</code></pre>
<p>and several packages where updated (numpy among others)... | <p>Yes, the compatibility with Python is guaranteed: look at the filename of the wheel that is installed: <code>numpy-1.13.3-cp27-cp27mu-manylinux1_x86_64.whl</code>. That matches the Python version you're using (including your OS). </p>
<p>As for <code>statsmodels</code> and the upgraded NumPy: if statsmodels require... | python-2.7|numpy|virtualenv | 1 |
9,343 | 32,979,836 | How can I get records from an array into a table in python? | <p>I have an xml file, with some data that I am extracting and placing in a numpy record array. I print the array and I see the data is in the correct location. I am wondering how I can take that information in my numpy record array and place it in a table. Also I am getting the letter b when I print my record, how do ... | <p>You are using Python3, which uses unicode strings. It displays byte strings with the <code>b</code>. The xml file may also be bytes, for example, <code>encoding='UTF-8'</code>.</p>
<p>You can get rid of the <code>b</code>, by passing the strings through <code>decode()</code> before printing.</p>
<p>More on writi... | python|arrays|xml|numpy|datatable | 0 |
9,344 | 38,923,280 | Using the .loc function of the pandas dataframe | <p>i have a pandas dataframe whose one of the column is : </p>
<pre><code> a = [1,0,1,0,1,3,4,6,4,6]
</code></pre>
<p>now i want to create another column such that any value greater than 0 and less than 5 is assigned 1 and rest is assigned 0 ie:</p>
<pre><code>a = [1,0,1,0,1,3,4,6,4,6]
b = [1,0,1,0,1,1,1,0,1,0]
</co... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow"><code>between</code></a> to get Boolean values, then <code>astype</code> to convert from Boolean values to 0/1:</p>
<pre><code>dtaframe['b'] = dtaframe['a'].between(0, 5, inclusive=False).astype(int... | python|pandas|dataframe | 4 |
9,345 | 63,011,806 | Searching for keywords irrespective of special characters in dataframe | <p>I have a dataframe df with a column of some texts:</p>
<pre><code>texts
This is really important(actually) because it has really some value
This is not at all necessary for it @ to get that
</code></pre>
<p>I want to perform a search and obtain the texts with keywords like "important(actually)", and it doe... | <p>Just escape the special characters in regex</p>
<pre><code>df = pd.DataFrame({'texts': [
'This is really important(actually) because it has really some value',
'This is not at all necessary for it @ to get that']})
keyword = 'important(actually)'
df[df.apply... | python|python-3.x|pandas|dataframe | 1 |
9,346 | 62,996,281 | How to convert OpenCV Mat input frame to Tensorflow tensor in Android Studio? | <p>I've been trying to run a Tensorflow model on android. The solution to do this was to create a tensorflow model(I used a pretrained Mobilenetv2 model) first. After training it on my own dataset, I converted it to a .tflite model which is supported by Android. Since I want to work with realtime video analysis, I am a... | <p>I suggest that you convert <code>Mat</code> into <code>FloatBuffer</code> as follows:</p>
<pre><code>Mat floatMat = new Mat();
mat.convertTo(floatMat, CV_32F);
FloatBuffer floatBuffer = floatMat.createBuffer();
</code></pre>
<p>Note that the <code>createBuffer</code> method is found within the <code>Mat</code> class... | java|python|android|tensorflow|opencv | 1 |
9,347 | 62,903,828 | Faking whether an object is an Instance of a Class in Python | <p>Suppose I have a class <code>FakePerson</code> which imitates all the attributes and functionality of a base class <code>RealPerson</code> <strong>without extending it</strong>. In Python 3, is it possible to fake <code>isinstance()</code> in order to recognise <code>FakePerson</code> as a <code>RealPerson</code> ob... | <p>You may need to subclass your <code>RealPerson</code> class.</p>
<pre class="lang-py prettyprint-override"><code>class RealPerson:
def __init__(self, age):
self.age = age
def are_you_real(self):
return 'Yes, I can confirm I am a real person'
def do_something(self):
return 'I did... | python|pandas|dataframe|isinstance | 1 |
9,348 | 67,628,293 | Got DatetimeIndex. Now how do I get these records to excel? | <p><strong>Goal:</strong>
From an excel file, I want to get all the records which have dates that fall within a range and write them to a new excel file. The infile I'm working with has 500K+ rows and 21 columns.</p>
<p><strong>What I've tried:</strong>
I've read the infile to a Pandas dataframe then returned the <code... | <blockquote>
<p>Goal: From an excel file, I want to get all the records which have dates that fall within a range and write them to a new excel file. The infile I'm working with has 500K+ rows and 21 columns.</p>
</blockquote>
<p>You could use an indexing operation to select only the data you need from the original Dat... | python|excel|pandas|datetimeindex | 1 |
9,349 | 67,871,922 | I want my Neural network output to be either 0 or 1, and not probabilities between 0 and 1, with customised step function at output layer | <p>I want my Neural network output to be either 0 or 1, and not probabilities between 0 and 1.</p>
<p>for the same I have designed step function for output layer, I want my output layer to just roundoff the output of previous(softmax) layer i.e. converting probabilities into 0 and 1.</p>
<p>My customised function is no... | <p>First of all, note that obtaining the class probabilities is always yielding more information than a pure 0-1 classification, and thus your model will almost always train better and faster.</p>
<p>That being said, and considering that you do have an underlying reason to limit your NN, a hard decision like the one yo... | tensorflow|keras|neural-network|activation-function | 1 |
9,350 | 31,918,400 | Python Bilinear regression | <p>I want to perform a 2 variable (linear) regression according to the following bilinear equation:</p>
<pre><code>f(x,y) = a + b*x + c*y + d*x*y,
</code></pre>
<p>where the f(x,y) data is, for example, given by the following matrix:</p>
<pre><code>x\y 6.0 7.0 8.0 9.0
00000 005804.69 ... | <p>Indeed, the x and y values must have the same dimensions, from the viewpoint of a solver. You should organize your data in the format of [(x_0,y_0,f(x_0, y_0)),...,(x_n,y_n,f(x_n, y_n))] for n data points. So if your data for the function f is a matrix of dimension P X Q, you should represent it as a new matrix of d... | python|function|numpy|scipy|regression | 0 |
9,351 | 31,997,859 | Bulk Insert A Pandas DataFrame Using SQLAlchemy | <p>I have some rather large pandas DataFrames and I'd like to use the new bulk SQL mappings to upload them to a Microsoft SQL Server via SQL Alchemy. The pandas.to_sql method, while nice, is slow. </p>
<p>I'm having trouble writing the code...</p>
<p>I'd like to be able to pass this function a pandas DataFrame which ... | <p>I ran into a similar issue with pd.to_sql taking hours to upload data. The below code bulk inserted the same data in a few seconds. </p>
<pre><code>from sqlalchemy import create_engine
import psycopg2 as pg
#load python script that batch loads pandas df to sql
import cStringIO
address = 'postgresql://<usernam... | python|pandas|sqlalchemy | 38 |
9,352 | 41,419,161 | Mapping multiple columns to a single dataframe with pandas | <p>I'm trying to create a dataframe (e.g., <code>df3</code>) that overwrites salary information onto people's names. I currently working with df1 with a list of around 1,000 names. Here's an example of what df1 looks like.</p>
<pre><code> print df1.head()
Salary
Name
Joe Smith 8700
... | <p>You can lookup the salary for each name in <code>df1</code> with <code>df1.loc[name, 'Salary']</code>.
Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html#pandas.DataFrame.applymap" rel="nofollow noreferrer"><code>.applymap()</code></a>, you can do this for all entrie... | python|pandas | 1 |
9,353 | 41,657,172 | What does * (asterisk) do when applied to a TensorFlow layer? | <p>Currently reading a Python implementation of Inception-ResNet to assist in building a model in a different language (Deeplearning4j). This implementation is Inception-ResNet-v1 and I was trying to figure out how it implements the residual shortcuts in ResNet style.</p>
<p>In the following code block is <code>net +=... | <p>Each layer in <code>up</code> is being multiplied by the scalar value in <code>scale</code>. And then <code>net</code> is being redefined as <code>net + scale * up</code>. So <code>net</code> should have the same dimensions as <code>up</code>.</p> | python|tensorflow|deep-learning | 1 |
9,354 | 41,656,290 | Support Vector Machine Python 3.5.2 | <p>While searching some tutorial on <code>SVM</code>, I've found online - <a href="https://www.youtube.com/watch?v=SSu00IRRraY" rel="nofollow noreferrer">Support Vector Machine _ Illustration</a> - the below code, which is however yielding a <code>weird</code> chart. After debugging the code, I wonder if the cause lies... | <p>I have been working with that SVM code from a number of examples (Siraj, Chaitjo, Jaihad, and others)...and found out that the Date needs to be in DD-MM-YYYY format...so the data used is the day date...not the year date (As dark.vapor has described).</p>
<p>And the data can only be for 30 days...as seen in this cod... | python|numpy|matplotlib|machine-learning|svm | 0 |
9,355 | 61,516,921 | How can i create a NxM array/matrix using numpy from the list items | <p>i have a file comprising of the following numbers</p>
<pre><code>AAFF
ADFF
7689
7FAD
AAFF
ADFF
7689
7FAD
... and so on for 200 lines of the file
</code></pre>
<p>I want to create 2 matrices using numpy. matrix 1 will have rows 8 and col 1(this will use the first 8 lines of the data from file), Matrix 2 will have 8... | <p>You can create a simple array from a list and reshape it:</p>
<pre><code>import numpy as np
import random
random.seed(42)
d = "0123456789ABCDEF"
data = [''.join(random.choices(d, k = 4)) for _ in range(72)]
print(data)
first8, next64 = data[:8],data[8:8+64]
farr = np.array(first8)
arr = np.array(next64).resh... | python|numpy|matrix | 2 |
9,356 | 68,720,130 | How can I get the values satisfying some conditions in a dataframe | <p>I read excel data as dataframe of pandas in which each row has two non-NaN values(others are all NaN)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">names</th>
<th style="text-align: center;">Unnamed:1</th>
<th style="text-align: center;">Unnamed:2</th>
<th s... | <p>You can pass na parameter in <code>str.contains()</code> so basically the na parameter set NaN values to True/False according to your input:</p>
<pre><code>mask = df[df.columns[0]].str.contains('ccdd',na=False)
</code></pre>
<p>Now finally pass that mask to your df:</p>
<pre><code>df[mask]
#OR
df.loc[mask]
</code></... | python|pandas|dataframe | 2 |
9,357 | 68,837,104 | ValueError: logits and labels must have the same shape ((None, 10) vs (None, 1)) | <p>I am new to tensorflow I was trying to build a simple model that would output the probability of installation (install colum).</p>
<p>Here a subset of the dataset:</p>
<pre><code>{'A': {0: 12, 2: 28, 3: 26, 4: 9, 5: 36},
'B': {0: 10, 2: 17, 3: 22, 4: 2, 5: 31},
'C': {0: 1, 2: 0, 3: 5, 4: 0, 5: 1},
'D': {0: 5, 2: ... | <p>Note: You have not specified which class the <code>ss</code> object belongs to and hence I will discuss everything removing it.</p>
<p>First let's discuss your target. i.e. the install column. From the values I assume that that your problem is Binary Classification i.e. predicting <code>0</code> and <code>1</code> a... | python|tensorflow|keras|deep-learning | 2 |
9,358 | 68,568,004 | Deleting observations when the value of a variable is 0 for that observation using loops in Python | <p>I have a dataset looking like this pattern:</p>
<pre><code>person x1 x2 x3
1 0 0 1
2 0 1 0
3 1 0 0
4 0 1 1
</code></pre>
<p>I want to create a loop through x1 to x3 to delete observations (person) whenever x1 is 0, and then x2 is 0, then x3 is 0. Each time I will have a... | <p>One approach is to create a dictionary of dataframes corresponding to which <code>x_</code> variable you are using to delete observations.</p>
<pre><code>df = pd.DataFrame({'person': {0: 1, 1: 2, 2: 3, 3: 4},
'x1': {0: 0, 1: 0, 2: 1, 3: 0},
'x2': {0: 0, 1: 1, 2: 0, 3: 1},
... | python|pandas|dataframe | 0 |
9,359 | 68,551,015 | extracting the indices from pandas series that are values in the dictionary | <p>I have a dictionary where keys are of string type and values are pandas series that have the 'index value' structure. I want to extract pandas series indices and make them keys in another dictionary with values per each index. Are there any ways I can transform one dictionary into another? Thanks.</p>
<p>This is the... | <p>My apologies if I was not clear enough. I will update the post.</p>
<p>I figured out another way to do so:</p>
<pre><code>rec = pd.Series([])
for item in key:
rec=rec.append(dic[item])
</code></pre> | python|pandas | 0 |
9,360 | 68,743,916 | How to update column value of CSV in Python? | <p>How can i change the rows in my csv data? I have a csv data which contains a column <code>class</code> and the coordinates.</p>
<pre><code>class x1 y1 ... x45 y45
A 0.187087 0.668525 ... -0.024700 0.220235
B 0.202503 0.669253 ... -0.107100 0.240229
....
C 0.248009 0.6763... | <p>If you have a large number of class values and don't want to write the dictionary by hand you can convert to a categorical variable and then take an encoding.</p>
<pre><code>df['class'] = df['class'].astype('category').cat.codes
</code></pre> | python|pandas | 1 |
9,361 | 68,545,110 | Using curve_fit to estimate common model parameters over datasets with different sizes | <p>I am working on a curve fitting problem, where I have the intention of estimating shared model parameters globally over several datasets of unequal size. I started working from the code in the link below, where a common a-parameter for a linear regression y = a*x + b is estimated on three different y-vectors with a ... | <p>In general I agree that the implications for least-squares fitting are rather complicated... some quick thoughts:</p>
<ul>
<li>can you be certain that the obtained <code>b</code> parameters are equally valid if they are estimated from different-length datasets?</li>
<li>the more b-parameters you get the more uncerta... | python|arrays|numpy|curve-fitting | 0 |
9,362 | 68,824,990 | Iterate through df rows faster | <p>I am trying to iterate through rows of a Pandas df to get data from one column of the row, and using that data to add new columns. The code is listed below but it is VERY slow. Is there any way to do what I am trying to do without iterating thru the individual rows of the dataframe?</p>
<pre><code>ctqparam = []
wwy ... | <p>It's hard to say exactly what your trying to do. However, if you're looping through rows chances are that there is a better way to do it.</p>
<p>For example, given a csv file that looks like this..</p>
<pre><code>Event_Start_Time,TPRev,Subtest
4/12/19 06:00,"this. string. has dots.. in it.",{'A_Dict':'may... | python|pandas | 1 |
9,363 | 36,555,773 | Defining x ticks in pandas | <p>I have a df like so:</p>
<pre><code> bnw_Percent bnw_Value mtgp_Percent mtgp_Value php_Percent php_Value
0 0.004414 1.48150 0.010767 2.03548 0.028395 3.91826
1 0.015450 5.44825 0.020337 6.01205 0.352093 7.77627
2 0.059593 9.41501 0.043067... | <p>you can do it this way:</p>
<pre><code>df.plot(x=df[[col for col in df.columns if 'Value' in col]].min(axis=1),
y=['bnw_Percent', 'php_Percent', 'mtgp_Percent'],
title='Frequency Distribution of Fuzzy Accumulated Values')
</code></pre>
<p><a href="https://i.stack.imgur.com/uGoV4.png" rel="nofollow ... | python|pandas | 1 |
9,364 | 36,449,688 | Python: how to concatenate multiple pandas dataframes to produce a box-and-whisker plot? | <p>Say I have a dataset of values that were binned. The bins are stored in a dictionary called <code>mydict</code>. To obtain the histogram quantities needed to plot a Box-and-Whisker, I have done:</p>
<p><code>df_dataset = pd.DataFrame.from_dict(dict([ (k, pd.Series(v)) for k,v in mydict.items() ]))</code></p>
<p>To... | <p>After a brief search I have figured out there is no need to concatenate anything. The simple answer is to construct the Box-and-Whisker from the <code>df_dataset</code>, as it already is a <code>series</code> and as such it stores all the relevant histogram quantities.</p>
<p>The line creating the Box-and-Whisker i... | python|pandas|matplotlib|plot|boxplot | 1 |
9,365 | 65,660,379 | psycopg2.errors.UndefinedTable: table "live" does not exist Pushing large dataframe to postgres database | <p>Am trying to push a large dataframe to the Postgres db, am using df_to_sql for this, the problem is it takes forever to complete this task, I have up to 1millions of dataframe rows, so I decided to use the python multiprocessing.</p>
<p>below are my codes</p>
<pre><code>def parallelize_push_to_db(df, table, chunk_si... | <p>Before i start, i will like to say, you will be better off using the threading modules, before making the decisions of using this sort of techniques you must understand the task you are doing. some tasks are cpu tasks whiles others are I/O heavy task. so try and understand all this before you choose which one you wa... | python|pandas|postgresql|multithreading|multiprocessing | 2 |
9,366 | 21,264,291 | Counting consecutive events on pandas dataframe by their index | <p>I'm trying to use dataframe to select events. Let's say I have only two kinds of events: 1, -1 and the following dataframe:</p>
<pre><code>a=pd.DataFrame({'ev':[1,1,-1,1,1,1,-1,-1]})
</code></pre>
<p>with:</p>
<pre><code>a[a['ev']>0]
</code></pre>
<p>I can select only the 1 events. Now I would like to count h... | <p>add <code>.index</code> to return a list of the indexes </p>
<pre><code>In [43]: a=pd.DataFrame({'ev':[1,1,-1,1,1,1,-1,-1]})
In [44]: b = list(a[a['ev']>0].index)
In [45]: b
Out[45]: [0, 1, 3, 4, 5]
</code></pre> | python|indexing|pandas | -1 |
9,367 | 21,412,280 | Iterating over frames for dropping columns | <p>The following for-loop iterating over two data frames doesn't work:</p>
<pre><code>for frame in [df_train, df_test]:
frame = frame.drop('Embarked', axis=1)
</code></pre>
<p>I don't get an error message, but the column 'Embarked' is not dropped in the two data frames. Why?</p> | <p>From <code>help(frame.drop)</code>:</p>
<pre><code>def drop(self, labels, axis=0, level=None, inplace=False, **kwargs):
"""
Return new object with labels in requested axis removed
...
inplace : bool, default False
If True, do operation inplace and return None.
</code></pre>
<p>Right now, ... | python|pandas | 4 |
9,368 | 53,634,265 | tensorflow lite issue : output labels file size is fixed ?? output or input tensor dimension mismatch issue in android | <p>Demo is available by Tensorflow in following link :</p>
<p><a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/java/demo" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/java/demo</a></p>
<p>Please change labels.txt file in above file by addi... | <p>As a feature request, you should generally file things to Github.</p>
<p>If you're looking for a local fix, I'm guessing the issue is that the model outputs a 1x1000 and you'll need to modify the actual model to be 1x1001 (and all the shapes of everything that comes before it).</p> | android|tensorflow|bytebuffer|tensor|tensorflow-lite | 0 |
9,369 | 6,527,641 | Speed up python code for computing matrix cofactors | <p>As part of a complex task, I need to compute <a href="http://en.wikipedia.org/wiki/Cofactor_%28linear_algebra%29" rel="nofollow noreferrer">matrix cofactors</a>. I did this in a straightforward way using this <a href="https://stackoverflow.com/questions/3858213/numpy-routine-for-computing-matrix-minors">nice code f... | <p>If your matrix is invertible, the cofactor is related to the inverse:</p>
<pre><code>def matrix_cofactor(matrix):
return np.linalg.inv(matrix).T * np.linalg.det(matrix)
</code></pre>
<p>This gives large speedups (~ 1000x for 50x50 matrices). The main reason is fundamental: this is an <code>O(n^3)</code> algori... | python|matrix|performance|numpy|linear-algebra | 14 |
9,370 | 12,114,863 | Permuting numpy's 2d array indexes | <p>are there any numpy function or clever use of views to accomplish what the following function do?</p>
<pre><code> import numpy as np
def permuteIndexes(array, perm):
newarray = np.empty_like(array)
max_i, max_j = newarray.shape
for i in xrange(max_i):
for j in xrange(max_j):
n... | <pre><code>def permutateIndexes(array, perm):
return array[perm][:, perm]
</code></pre>
<hr>
<p>Actually, this is better as it does it in a single go:</p>
<pre><code>def permutateIndexes(array, perm):
return array[np.ix_(perm, perm)]
</code></pre>
<p>To work with non-square arrays:</p>
<pre><code>def permu... | python|arrays|numpy|multidimensional-array | 6 |
9,371 | 71,833,667 | Keras Confusion Matrix does not look right | <p>I am running a Keras model on the Breast Cancer dataset. I got around 96% accuracy with it, but the confusion matrix is completely off. Here are the graphs:</p>
<p><a href="https://i.stack.imgur.com/7S6EI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7S6EI.png" alt="enter image description here"... | <p>Check the confusion matrix values from the <code>sklearn.metrics.confusion_matrix</code> <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html" rel="nofollow noreferrer">official documentation</a>. The values are so organized:</p>
<ul>
<li><code>TN</code>: upper left corner... | python|tensorflow|keras|deep-learning|confusion-matrix | 1 |
9,372 | 71,884,072 | Is it possible to use a docker image that has both pyspark and pandas installed? | <p>My flask application uses pandas and pyspark.</p>
<p>I created a Dockerfile where it uses a docker Pandas image:</p>
<pre><code>FROM amancevice/pandas
RUN mkdir /app
ADD . /app
WORKDIR /app
EXPOSE 5000
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
</code></pre>
<p>In requirements.t... | <p><code>pyspark</code> (aka Spark) requires java, which doesn't seems to be installed in your image.</p>
<p>You can try something like:</p>
<pre><code>FROM amancevice/pandas
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
openjdk-11-jre-headless \
&& apt-get autoremov... | java|pandas|docker|pyspark|dockerfile | 0 |
9,373 | 72,017,161 | How to assign values based on column value, then take the average of the sum | <p>I have a df with 6 columns (category 1, 2, ..., 6), all with values either "I", "II", "III", or "IV". These string values are the categories that applies to each column. I want to make another column ("Score), that, based on the values for each column, assign a value to e... | <p>You can create a dictionary to map the values and use <code>np.mean</code> to get the average:</p>
<pre><code>d = {'I': 100, 'II': 70, 'III': 35, 'IV': 0}
df['Average Value'] = df.apply(lambda x: np.mean(x.map(d)), axis = 1)
</code></pre> | python|pandas|dataframe|numpy|apply | 1 |
9,374 | 71,871,741 | Specifically change all elements in a numpy array based on a condition without iterating over each element | <p>Hi I would like to <strong>change all the values</strong> in this array (test) simultaneously based on a second boolean array (test_map) <strong>without iterating over each item</strong>.</p>
<pre><code>test = np.array([1,1,1,1,1,1,1,1])
test_map = np.array([True,False,False,False,False,False,False,True])
test[test_... | <p>One possible solution is to generate a random array of "bits", with <code>np.random.randint</code>:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
test = np.array([1,1,1,1,1,1,1,1])
test_map = np.array([True,False,False,False,False,False,False,True])
# array of random 1/0 of the sa... | python|numpy|vectorization | 2 |
9,375 | 71,877,483 | Store series with different length in for loop | <p>The original df is like below:</p>
<pre><code>Hour Count
0 15
0 0
0 0
0 17
0 18
0 12
1 55
1 0
1 0
1 0
1 53
1 51
...
</code></pre>
<p>I was looping through this df hour by hour and remove Count=0 in that hour, then drew a boxplot of Count in that hour. Then I ended up ... | <p>One option is to <code>pivot</code> the filtered DataFrame and plot the <code>boxplot</code>:</p>
<pre><code>df.query('Count!=0').assign(i=lambda x: x.groupby('Hour').cumcount()).pivot('i', 'Hour', 'Count').boxplot();
</code></pre>
<p><a href="https://i.stack.imgur.com/W5oKp.png" rel="nofollow noreferrer"><img src="... | python-3.x|pandas|loops|concatenation | 1 |
9,376 | 71,885,701 | How can I blur a mask and smooth its edges? | <p><strong>I want to change the color of the cheeks of this photo.
I got a mask with sharp edges</strong>
<strong>How can I blur a mask and smooth its edges?</strong>
<a href="https://i.stack.imgur.com/BB54C.png" rel="nofollow noreferrer">image</a>
<a href="https://i.stack.imgur.com/pca8e.png" rel="nofollow noreferrer"... | <pre><code># import the necessary packages
import argparse
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", type=str, default="pca8e.png",
help="path to input image")
args = vars(ap.parse_args()... | python|numpy|opencv|mediapipe | 1 |
9,377 | 22,410,803 | Why np.array([1e5])**2 is different from np.array([100000])**2 in Python? | <p>May someone please explain me why <code>np.array([1e5])**2</code> is not the equivalent of <code>np.array([100000])**2</code>? Coming from Matlab, I found it confusing!</p>
<pre><code>>>> np.array([1e5])**2
array([ 1.00000000e+10]) # correct
>>> np.array([100000])**2
array([1410065408]) ... | <p><code>1e5</code> is a floating point number, but 10000 is an integer:</p>
<pre><code>In [1]: import numpy as np
In [2]: np.array([1e5]).dtype
Out[2]: dtype('float64')
In [3]: np.array([10000]).dtype
Out[3]: dtype('int64')
</code></pre>
<p>But in numpy, integers have a fixed width (as opposed to python itself in ... | python|arrays|numpy|exponent | 7 |
9,378 | 55,319,623 | Large dataset processing for Tensorflow Federated | <p>What is the efficient way to prepare ImageNet (or other big datasets) for Tensorflow federated simulations? Particularly with applying custom map function on tf.Dataset object? I looked into the tutorials and docs but did not find anything helpful for this usecase. This tutorial (<a href="https://www.tensorflow.org/... | <p>Could you please clarify what exactly you mean by "efficient" in this context. I presume you've tried something, and it wasn't working as expected. Could you please describe here how you went about setting it up, and what problems you ran into. Thanks!</p>
<p>One thing to note is that the runtime included in the fi... | tensorflow-federated | 1 |
9,379 | 55,245,290 | loop over a dataframe and populate with values | <p>I am trying to loop over a dataframe and fill a new column with values according to a rule:</p>
<pre><code>#formula for trading strategy
df['new_column'] = ""
for index,row in df.iterrows():
if row.reversal == 1:
row.new_column = 1
index += 126
row.new_column = -1
... | <p>new_column could have values: 0, 1 or -1,
i suggest you to initially load 0 your column, so no need to set 0:</p>
<pre><code>df['new_column'] = 0
index = 0
while index < df.shape[0]:
if df['reversal'][index] == 1:
df.loc[index,'new_column'] = 1 #set 1 to same index
df.loc[index + ... | pandas | 0 |
9,380 | 55,235,691 | Pandas: concat multiple .csv files and return Dataframe with columns of the same name aggregated | <p>I have 100 csv files. Each file contains columns that may or may not be in the other .csv files. I need to merge all of the csv files into one and sum all columns that have the same column name. Below is an example with two csv files, but imagine it can go up to 100 csv files: </p>
<p><strong>first csv file:</stron... | <p>You can create index by <code>User</code> column and use <code>sum</code> by first level:</p>
<pre><code>csvArray = []
for x in range(1,101):
csvArray.append(pd.read_csv("myCsv{}.csv".format(x), index_col=['User']))
</code></pre>
<p>Or:</p>
<pre><code>csvArray = [pd.read_csv("myCsv{}.csv".format(x), index_col... | python|pandas|csv|concat | 5 |
9,381 | 55,150,829 | Numpy memmap in-place sort of a large matrix by column | <p>I'd like to sort a matrix of shape <code>(N, 2)</code> on the first column where <code>N</code> >> system memory.</p>
<p>With in-memory numpy you can do:</p>
<pre><code>x = np.array([[2, 10],[1, 20]])
sortix = x[:,0].argsort()
x = x[sortix]
</code></pre>
<p>But that appears to require that <code>x[:,0].argsort()<... | <p>The solution may be simple, using the order argument to an in place <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sort.html#numpy.ndarray.sort" rel="nofollow noreferrer">sort</a>. Of course, <code>order</code> requires fieldnames, so those have to be added first.</p>
<pre><code>d = x.d... | python|numpy|python-3.6|memmap | 2 |
9,382 | 55,505,119 | Conditional drop of identical pairs of columns in pandas | <p>I have a somewhat big pandas dataframe (100,000x9). The first two columns are a combination of names associated with a value (in both sides). I want to delete the lower value associated with a given combination.</p>
<p>I haven't tried anything yet, because I'm not sure how to tackle this problem. My first impressio... | <p>First we use <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.sort.html" rel="nofollow noreferrer"><code>np.sort</code></a> to sort horizontally, then we use <code>groupby</code> with <code>max</code> function to get the highest value per unique value of first, second:</p>
<pre><code>df[['... | python|pandas|numpy | 2 |
9,383 | 55,227,270 | How to keep ordering when saving dict as pandas data frame? | <p>If I have some example data as:</p>
<pre><code>dic = {'common': {'value': 18, 'attr': 20, 'param': 22},
'fuzzy': {'value': 14, 'attr': 21, 'param': 24},
'adhead': {'value': 13, 'attr': 20, 'param': 29}}
</code></pre>
<p>Executing <code>pd.DataFrame(dic)</code> I get:</p>
<pre><code> common fu... | <p>Then using <code>reindex</code> as protection </p>
<pre><code>pd.DataFrame(dic).reindex(index=['value','attr','param'])
Out[553]:
common fuzzy adhead
value 18 14 13
attr 20 21 20
param 22 24 29
</code></pre> | python|pandas | 2 |
9,384 | 56,646,345 | Is it possible to use pyspark to speed up regression analysis on each column of a very large size of an array? | <p>I have an array of very large size. I want to do linear regression on each column of the array. To speed up the calculation, I created a list with each column of the array as its element. I then employed pyspark to create a RDD and further applied a defined function on it. I had memory problems in creating that RDD ... | <p>That is not going to work that way. You are basically doing three things:</p>
<ol>
<li>you are using a RDD for parallelization,</li>
<li>you are calling your getLinearCoefficients() function and finally</li>
<li>you call <a href="http://spark.apache.org/docs/2.2.1/api/python/pyspark.sql.html#pyspark.sql.DataFrame.c... | numpy|pyspark | 1 |
9,385 | 56,522,831 | Is there a more concise way to count rows in a group in pandas? | <p>here is a data table</p>
<p><a href="https://i.stack.imgur.com/dgDr1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dgDr1.png" alt="enter image description here"></a></p>
<p>to count the rows conditional on 'Age'=='young', group by Class, I use this piece of code</p>
<pre><code>df.loc[(df['Age... | <p>You can use:</p>
<pre><code>print(df.groupby('Class').size())
</code></pre>
<p>If you want only <code>'young'</code>:</p>
<pre><code>print(df[df['Age'].eq('young')].groupby('Class').size())
</code></pre> | python|pandas | 2 |
9,386 | 56,478,762 | Pandas & Python: Is there a way to import the contents of an excel file, add text content to the end of the file, and save down? | <p>I have a list of names that are stored in an excel file. The user needs to be able to import that list, which is a single column, and add additional names to the list, and save down the file. </p>
<p>I've imported the excel file using pandas and created a dataframe (df). I've tried to append the df using a loop fun... | <p>I was able to figure it out. Thanks for everyone's help. </p>
<pre><code>import numpy as np
import pandas as pd
#create list of deals in the 'main' consolidation spreadsheet
path = 'C:\\NY_Operations\\EdV\\Streaman\\Python\\CES Fee Calc\\'
file_main = 'Main.xlsx'
df_main = pd.read_excel(path + file_main)
new_de... | python|pandas | 1 |
9,387 | 56,650,337 | apply if else condition using dataframe | <p>With below code I can see the data, there is one row and two columns.
I want to do a selection:</p>
<ol>
<li>if both columns are 0 then do something</li>
<li>if both are greater than 0 then do something.</li>
</ol>
<p>I am getting error in if condition. Can anyone please help me to this done? </p>
<blockquote>
... | <p>There are multiple syntactical errors in your script. Try the below-modified code.</p>
<pre><code>import numpy as np
if np.sum((df1["empID"]==0) & (df1["empDept"]==0)):
print("less than zero")
elif np.sum((df1["empID"]>0) & (df1["empDept"]>0)):
print("greather than 0")
else:
print("do not... | python|sql-server|pandas|dataframe|databricks | 0 |
9,388 | 56,853,946 | Is there any alternative for pd.notna ( pandas 0.24.2). It is not working in pandas 0.20.1? | <p>"Code was developed in pandas=0.24.2, and I need to make the code work in pandas=0.20.1. What is the alternative for pd.notna as it is not working in pandas version 0.20.1. </p>
<pre><code>df.loc[pd.notna(df["column_name"])].query(....).drop(....)
</code></pre>
<p>I need an alternative to pd.notna to fit in this l... | <pre><code>import os
import subprocess
import pandas as pd
import sys
from StringIO import StringIO
from io import StringIO
cmd = 'NSLOOKUP email.fullcontact.com'
df = pd.DataFrame()
a = subprocess.Popen(cmd, stdout=subprocess.PIPE)
b = StringIO(a.communicate()[0].decode('utf-8'))
df = pd.read_csv(b, sep=",")
column = ... | python-3.x|pandas | 0 |
9,389 | 25,528,395 | Python - Mask specific values of a grid | <p>I would like to mask values of a grid.
As example i want to mask all values of "t < 0" to do calculation after.
I try to use a conditionnal if but it doesnt work...</p>
<pre><code>import numpy as np
Lx=10.
Ly=10.
x0 = 2
YA, XA = np.mgrid[0:Ly, 0:Lx]
t = XA - 2
</code></pre> | <p>You need to explain what you want to do <em>after</em> you mask the array. Do you want to alter the unmasked values? Then </p>
<pre><code>mask = t < 0
YA[~mask] = ...
</code></pre>
<p>might be all you need.</p>
<p>On the other hand, if you need to compute statistics on arrays with masked value, you may find us... | numpy|grid|mask | 1 |
9,390 | 26,047,209 | What is the difference between a pandas Series and a single-column DataFrame? | <p>Why does pandas make a distinction between a <code>Series</code> and a single-column <code>DataFrame</code>?<br>
In other words: what is the reason of existence of the <code>Series</code> class? </p>
<p>I'm mainly using time series with datetime index, maybe that helps to set the context. </p> | <p>Quoting the <a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html" rel="noreferrer">Pandas docs</a></p>
<blockquote>
<p><code>pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)</code></p>
<p>Two-dimensional size-mutable, potentially heterogeneous tabu... | python|pandas | 253 |
9,391 | 67,018,234 | Tensorflow 2 - How to apply adapted TextVectorization to a text dataset | <h1>Question</h1>
<p>Please help understand the cause of the error when applying the adapted <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization" rel="nofollow noreferrer">TextVectorization</a> to a text Dataset.</p>
<h1>Background</h1>
<p><a href="https://ke... | <p><code>tf.data.Dataset.map</code> applies a function to each element (a Tensor) of a dataset. The <code>__call__</code> method of the <code>TextVectorization</code> object expects a <code>Tensor</code>, not a <code>tf.data.Dataset</code> object. Whenever you want to apply a function to the elements of a <code>tf.dat... | tensorflow|word-embedding | 1 |
9,392 | 67,088,524 | Python Pandas xlsxriter stacked line chart type setting standard line chart in Excel | <p>I am trying to created stacked line charts in excel using pandas and xlsxwriter.</p>
<p>When entering the chart type dict into add chart I use what the documentation states should configure a stacked line in Excel. (So I think anyway!) When I open Excel I get a standard line chart, which means I need to manually cha... | <p>The code should work as expected. Here is the output when I run it:</p>
<p><a href="https://i.stack.imgur.com/UUHLx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UUHLx.png" alt="enter image description here" /></a></p>
<p>Note, stacked line support was added in <a href="https://xlsxwriter.readth... | python|excel|pandas|xlsxwriter | 2 |
9,393 | 66,866,690 | TypeError: ("x() got an unexpected keyword argument 'result_type'", 'occurred at index 1'), pandas 0.23.4 | <p>I am getting a Type error using the result_type keyword applying a function to a dataframe in order to add 2 columns.</p>
<p>I can see the usual cause of this is due to a pandas version, but I have 0.23.4 running and am receiving this error.</p>
<pre><code>def parse_allocation(x):
direction = {'En':'entry',
... | <p>The error is because pandas treats the parameter <code>result_type='expand'</code> as a parameter for the custom function <code>parse_allocation</code> rather than parameter of the <code>apply()</code> function. You can solve it by using lambda function as follows:</p>
<pre><code>df_allocation[['curvename', 'Direct... | python|pandas|dataframe | 0 |
9,394 | 66,840,550 | How to convert Python JSON to API call string from dataframe | <p>My script reads parameters from an Excel file using <em>pandas</em>.</p>
<ol>
<li>The code first reads from an excel file and creates a <code>DataFrame</code>, <code>df</code>.</li>
<li>The <code>df</code> is filtered on <code>df['Team'] == 'IT'</code>.</li>
<li>Filtered <code>df</code> is converted to JSON to get a... | <p>I suggest using groupby to lump together the users, and then orientation <code>'records'</code> instead of <code>'columns'</code>:</p>
<pre><code>df = df.groupby(['Team', 'StartDate', 'EndDate', 'RotationID']).agg(tuple).reset_index()
for record in df.to_dict(orient='records'):
payload = {
"name&qu... | python|json|python-3.x|pandas|python-requests | 0 |
9,395 | 66,850,493 | Using a Nested For Loop to create a new column in Pandas | <p>I am trying to create a new column using information from a list and also an existing column.
I created a nested FOR LOOP to go through the existing and the list simultaneously, checking if the information in the list is the same as that of the existing column, if Yes, then it should perform a task, if no then do so... | <p>Let us say we have the following parameters :</p>
<pre class="lang-py prettyprint-override"><code>>>> monthinviewlist
AGENT_NAME
0 Old Mutual Abuja Branch Direct
1 Old Mutual Lagos Branch Direct
2 Old Mutual Rivers Branch Direct
3 Old Mutual Ibadan Branch Direct
4 ... | python|pandas|list|loops | 0 |
9,396 | 66,842,767 | Pandas: How select rows by multiple criteria (if not nan and equals to specific value) | <p>I have a DataFrame</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">index</th>
<th style="text-align: center;">Street</th>
<th style="text-align: center;">House</th>
<th style="text-align: right;">Building</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: l... | <p>A rather simple way to do it would be this:</p>
<pre><code>if df[df['Building'].isnull()].empty:
df[df['Street'] == str_filter][df['House'] == house_filter][df['Building'] == build_filter]
else:
df[df['Street'] == str_filter][df['House'] == house_filter][df['Building'].isnull()]
</code></pre>
<p>I'm not sure... | python|pandas|selection|nan | 0 |
9,397 | 66,804,306 | why loop saves only results from last file in pandas | <p>I am using a loop to open consecutive files and then a second loop to calculate the average of y at specific row nrs (x). Why is the second loop showing the average only of the last file? I would like to append the average from each file into one new dataframe.</p>
<pre><code>path = '...../'
for file in os.listdir(... | <p>You're main issue is with indentation and the fact your'e not saving <code>df</code> to a dictionary or list.</p>
<p>additionally, you're first opening the file and then passing it to pandas, there is no need for this as pandas handles <code>I/O</code> for you.</p>
<p>a simplified version of your code would be.</p>
... | pandas|loops|iteritems | 0 |
9,398 | 10,943,088 | numpy.max or max ? Which one is faster? | <p>In python, which one is faster ? </p>
<pre><code>numpy.max(), numpy.min()
</code></pre>
<p>or</p>
<pre><code>max(), min()
</code></pre>
<p>My list/array length varies from 2 to 600. Which one should I use to save some run time ?</p> | <p>Well from my timings it follows if you already have numpy array <code>a</code> you should use <code>a.max</code> (the source tells it's the same as <code>np.max</code> if <code>a.max</code> available). But if you have built-in list then most of the time takes <em>converting</em> it into np.ndarray => that's why <cod... | python|numpy|runtime|max|min | 57 |
9,399 | 68,413,687 | batched tensor slice, slice B x N x M with B x 1 | <p>I have an B x M x N tensor, X, and I have and B x 1 tensor, Y, which corresponds to the index of tensor X at dimension=1 that I want to keep. What is the shorthand for this slice so that I can avoid a loop?</p>
<p>Essentially I want to do this:</p>
<pre><code>Z = torch.zeros(B,N)
for i in range(B):
Z[i] = X[i]... | <p>the following code is similar to the code in the loop. the difference is that instead of sequentially indexing the array <code>Z</code>,<code>X</code> and <code>Y</code> we are indexing them in parallel using the array <code>i</code></p>
<pre><code>B, M, N = 13, 7, 19
X = np.random.randint(100, size= [B,M,N])
Y = n... | numpy|pytorch|slice|tensor|numpy-slicing | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.