Questions tagged [in-place]
Use this tag on questions about algorithms that modify the data in-place, as opposed to making a copy. For example, in-place sorting, in-place merge, etc.
354
questions
0
votes
1
answer
35
views
pytorch sets grad attribute to none if I use simple minus instead of -=
This is a simple code to show the problem
import torch
X = torch.arange(-3, 3, step=0.1)
Y = X * 3
Y += 0.1 * torch.randn(Y.shape)
def my_train_model(iter):
w = torch.tensor(-15.0, requires_grad=...
-3
votes
0
answers
34
views
Which pandas methods profit from inplace=True? [closed]
Pandas' inplace=True argument seems to be a bit controversial, many say it's straight harmful and should not be used (e.g. here and here) and it was even discussed to deprecate it.
But there are also ...
0
votes
0
answers
12
views
What is an example of a language where function calls indicate whether a class method modifies the original object or returns a moded copy?
Consider the following passage of pseudocode:
String s1 = new String("how are");
Object x = s1.append(" you ?\n");
print(String(s1));
print(String(x));
There are two possible ...
0
votes
3
answers
41
views
Python: How to subtract value from subselection of cells in a pandas DataFrame IN PLACE?
I try to subtract a value (50) from a subselection of cells in a pandas DataFrame. I want to subtract the value from ‘rt’ where subj == 1 and cond == std. I would like to perform this calculation in ...
1
vote
1
answer
37
views
Puzzling result from boundary condition code in Julia BVP solver
I am trying to solve a boundary value problem in Julia, following the example found here, using the BoundaryValueDiffEq package. In the boundary condition function, the example requires a for loop to ...
0
votes
0
answers
39
views
In-place operations for String objects
I've got an incoming bunch of MultipartFile objects that I need to send through by embedding them into an XML structure and base64-encoding that structure. Initially the code easily consumed 10-20x ...
0
votes
0
answers
18
views
How to Override Values In-Place for List using MultiProcessing in Python 3?
I've been trying to Run the following Code:
from math import inf
import multiprocessing
dist = [[inf] * n for _ in range(n)]
n = 8
data = [i for i in range(n)]
def set_self_distance(data):
for ...
0
votes
3
answers
118
views
Leetcode Reverse String problem not accepting in-place solution
I am posting two solutions below which I tried in leetcode for the problem no : 344
https://leetcode.com/problems/reverse-string/
Solution 1
class Solution:
def reverseString(self, s: List[str]) -> ...
0
votes
0
answers
62
views
How to Decrypt Column Encrypted by Always Encrypted Using sqlcmd in Another way?
As the doc mentioned:
https://docs.microsoft.com/en-us/sql/relational-databases/security/encryption/always-encrypted-enclaves-configure-encryption-tsql?view=sql-server-ver15
Note
Currently, the Invoke-...
0
votes
1
answer
37
views
In place sorting using Quicksort - works for list containing integers but not for list containing tuples. Why?
My quicksort algorithm works fine in sorting a list in place when the list contains individual items. For example
'''
def quicksort(l):
if len(l) <= 1:
return l
pivot = l[0]
lower,upper ...
0
votes
0
answers
48
views
Issues with Iterative quicksort
I am having issues with 2 pivot strategies, median of 3 random elements (corresponding to the quickSortThreeRandomPivot() method) & random element (corresponding to the quickSortRandomPivot() ...
0
votes
1
answer
24
views
Changes to pandas dataframe in for loop is only partially saved
I have two dfs, and want to manipulate them in some way with a for loop.
I have found that creating a new column within the loop updates the df. But not with other commands like set_index, or dropping ...
0
votes
0
answers
115
views
Pytorch: when inplace operation are allowed and when not
I'm trying to understand how the shortcuts work in neural networks models (e.g., ResNet models) implemented using Pytorch.
I'm trying the following ResNet block found on a github repository:
class ...
1
vote
1
answer
101
views
Does inplace matter when we return ReLU(x)
Is there a difference between the following two classes?
I know what inplace is (you don't need to do x = function(x) but only function(x) to modify x if inplace is True). But here because we return ...
0
votes
1
answer
38
views
Does += really do in-place addition in python? [duplicate]
I am trying to test the in-place addition claim of += in python, this is my code:
>>> a=1
>>> id(a)
4346593520
>>> a+=1
>>> id(a)
4346593552
As you can see, the ...
-1
votes
2
answers
44
views
Indexing by row name
Can someone please help me with this. I want to call rows by name, so I used set_index on the 1st column in the dataframe to index the rows by name instead of using integers for indexing.
# Set 'Name' ...
3
votes
2
answers
222
views
Using Julia's dot notation and in place operation
How do I use both Julia's dot notation to do elementwise operations AND ensure that the result is saved in an already existing array?
function myfun(x, y)
return x + y
end
a = myfun(1, 2) # ...
1
vote
0
answers
40
views
How to prevent the default inplace add `__iadd__` calling the reflected add `__radd__` of my class in Python?
I have a class where I have defined the reflected add (__radd__) special method:
class Addable:
def __init__(self, other=0):
if isinstance(other, Addable):
self.id = other.id
...
0
votes
0
answers
182
views
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation:
I am using an LSTM to summarize a trajectory as shown below:
class RolloutEncoder(nn.Module):
def __init__(self, config):
super(RolloutEncoder, self).__init__()
self._input_size = (...
0
votes
1
answer
88
views
Why AVL sort is not in place?
I was recently told that AVL sort is not in place. Can anyone please explain it? From the below code, I am not sure where I assign extra space when sorting. In this code, when a data structure is ...
0
votes
0
answers
34
views
How does slice assignment work with a generator using the same list?
Say, I have a list nums = [1, 0, 1, 0, 0, 1, 1]. I want to rearrange it so that zeroes are at the end of the list. This slice assignment seems to work, but I don't understand why:
>>> from ...
33
votes
1
answer
2k
views
Why aren't Pandas operations in-place?
Pandas operations usually create a copy of the original dataframe. As some answers on SO point out, even when using inplace=True, a lot of operations still create a copy to operate on.
Now, I think I'...
0
votes
0
answers
146
views
Pytorch: multiplication between parameters is inplace for LBFGS optimizer?
I am trying to solve a kind of inverse problem by backward propagation with pytorch. I am trying to recover the parameters (r, theta) that generate a vector field U(r,theta).
As I intended to use the ...
-1
votes
1
answer
87
views
how can i use fillna(inplace=True) in for loop?
df = pd.read_csv('IMDB-Movie-Data.csv')
dp = df.groupby('Director')['Revenue (Millions)'].mean()
for i in dp.index:
df.loc[df['Director']==i,'Revenue (Millions)'].fillna(dp[i],inplace = True)
...
2
votes
0
answers
134
views
Pytorch - Handling in place operation for sequence to sequence Multi-dimensional LSTM layer
I am trying to implement a sequence to sequence LSTM layer in Pytorch. Here a sequence can be of higher dimension than 1 (an image is a sequence, it just has 2 indexes that increase instead of one). ...
1
vote
2
answers
41
views
Trouble operating on my pandas dataframe in a loop?
I am trying to loop through a list that contains two pandas data frames:
dataset = [df_train, df_test]
for df in dataset:
df = pd.get_dummies(df, columns=['A', 'B','C'])
I was expecting this to ...
0
votes
1
answer
178
views
In-place modification of gzip files
I need to modify a gzipped tab-delimited file. I can read from input and write modified reads to an output file as:
output = tempfile.NamedTemporaryFile(mode="w", delete=False)
with gzip....
0
votes
0
answers
79
views
append a string to a modified line
i'll try to do this in steps:
1- problem:
i must rewrite an corrupted m3u file its lines go:
#EXTINF123#, Title - Song # let's say for clarity sake that the n line
d:\music\title - song.mp3 # this ...
0
votes
0
answers
22
views
why pd.drop(inplace = True) will cause SettingWithCopyWarning [duplicate]
I'm new to pandas, I just want to drop some rows in a DataFrame inplace, but there are warnings:
/opt/conda/lib/python3.7/site-packages/pandas/core/frame.py:4315: SettingWithCopyWarning:
A value is ...
0
votes
1
answer
89
views
In-place Mergesort Python
I'm trying out an in-place mergesort that uses rotation to sort items. The problem is that it works for a power-of-two number of items in descending order and fails for other arrangements or number of ...
2
votes
1
answer
106
views
Get differences between two lists of dictionaries (result as two differences lists)
Edit: I need a solution which works with lists of dictionaries (dictionaries are not hashable), so this is not a duplicate of Compute list difference
I have two lists of dictionaries. They contain ...
3
votes
1
answer
53
views
Why mutating the list to be only its first element with this approach does not work in Common Lisp?
I am trying to learn Common Lisp with the book Common Lisp: A gentle introduction to Symbolic Computation. In addition, I am using SBCL, Emacs, and Slime.
By the end of chapter 10, on the advanced ...
2
votes
2
answers
378
views
Counting sort implementation that modifies the input array
On the Wikipedia page about Counting Sort, it states:
It is possible to modify the algorithm so that it places the items into sorted order within the same array that was given to it as the input, ...
1
vote
2
answers
47
views
Remove from file a string and another string and everything after it
Say I have a file teams with contents as follows:
[Desktop Entry]
Version=1.0
Type=Application
Name=Microsoft Teams - Preview
Comment=Microsoft Teams for Linux is your chat-centered workspace in ...
0
votes
1
answer
150
views
How to do in-place sorting a list according to a given index in C++
I have a large list of objects(struct).
They have been sorted and the index have been saved in another list.
How to do in-place sort according to the index?
For example,
FOO A[5] =[a5,a4,a8,a1,a3]
...
2
votes
1
answer
465
views
In-place RGB->BGR color conversion is slower in OpenCV
Is it the case that the in-place RGB->BGR color conversion routine in OpenCV saves some memory, but takes longer? If yes, can anyone explain why?
My application calls the cv::cvtColor(srcMat, ...
0
votes
0
answers
118
views
How to replace string-literal that takes the form of shell variable in bash/with sed? [duplicate]
I'm familiar with sed's ability to replace in-place in a file, as answered here: sed edit file in place.
I.e. sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename
I'm having trouble expanding ...
0
votes
1
answer
46
views
Why does slice assignment only work in-place for my function's list parameter if I slice it before?
For a python course that I am taking, we were assigned to reverse a list of provided strings using an in-place algorithm. While this can be done by directly swapping indexes, I saw that way did not ...
2
votes
0
answers
47
views
Is reference to object still valid after its destruction and recreation in-place? [duplicate]
what will happen to the reference to an object after destruction and creation in-place of that object? Will it be still valid or it is undefined behavior? Here is an example:
#include <iostream>
...
1
vote
0
answers
34
views
Python inplace parameter failed when trying to replace some values of a DataFrame
I have the following dataframe:
2010-01-04 00:00:00 2.874 2.947 2.838 2.91 3609000 0
2010-01-05 00:00:00 2.947 3.118 2.947 3.1 13559646 0
2010-01-06 00:00:00 3.118 3.163 2.974 ...
-1
votes
1
answer
211
views
Convert any base to decimal using Horner's recursively
I have to write a program converting from any base to decimal using recursion and Horner's scheme. All I can use is:
an int method with two parameters like public static int horner (int[] digits, int ...
2
votes
4
answers
581
views
Element swapping in list using one line multiple assignment
I am trying to swap 2 elements in a list. I want to swap the element at index 0 to the element at index arr[0], so basically I want to swap arr[0] <-> arr[arr[0]].
I have always used this method ...
0
votes
1
answer
59
views
How do I iterate through a Python data frame where I occasionally need to replace two rows with one row, in-place?
The "in-place" is the aspect I struggle with- creating a brand new data frame is solved (provided at the end). My specific issue is that my imported data occasionally splits one column's ...
0
votes
3
answers
110
views
(Python) Modify several lists in-place
I'd like to remove duplicates from several lists (in-place). Have tried the following but failed (Python Compiler):
a = [1, 2, 2]
b = [3, 4, 4]
c = [5, 6, 6]
print('===previous')
print(id(a))
print(...
0
votes
1
answer
93
views
Can a counting sort be considered in-place when the problem constrains the number of input values?
I was doing this problem on leetcode:
Given an array nums with n objects colored red, white, or blue, sort
them in-place so that objects of the same color are adjacent, with the
colors in the order ...
1
vote
1
answer
127
views
Python - writing an in-place option in my function [how to prevent overwriting my input vector]
I am writing a function that pulls the top x values from a sparse vector (fewer values if there are less than x). I would like to include an "in-place" option like many functions have, where ...
2
votes
1
answer
233
views
Replace string in big sql file (15 go) bash
I have to replace this string in dump file :
use clients_db;
by
use client;
The name of database is different between the environment src and dest.
I tried with using sed, but it doesn't work ...
-1
votes
1
answer
50
views
Linux- Add/Insert in only the secondlast line with a new value keeping original content intact in same file [duplicate]
I need to add/insert a value "new content" on the secondlast line of the same file without deleting any of the lines or content of my file.
The condition is that the file content keeps ...
-1
votes
1
answer
41
views
How to change a variable by reference like Pandas inplace
So I was working with Pandas and I recently came across the inplace argument, which changes the original variable without having to reassign it.
Example : df.dropna(inplace=True) instead of df = df....
3
votes
2
answers
141
views
Julia "strange" behaviour using fill() and .+=
I observe an unexpected behaviour for ".+=" in my code (it's probably just me, I'm rather new to Julia). Consider the following example:
julia> b = fill(zeros(2,2),1,3)
1×3 Array{...