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 |
|---|---|---|---|---|---|---|
377,900 | 57,561,839 | Python Iterating 2D Array, Return Array Value | <p>I have created a 2D 10x10 Array. using Numpy I want to iterate over the array as efficiently as possible.</p>
<p>However I would like to return the array values. essentially iterating over the 10x10 array 10 times and return a 1x10 array each time.</p>
<pre><code> import datetime
import numpy as np
import random... | <p>To directly answer your question, this does exactly what you want:</p>
<pre><code>import numpy as np
a = np.random.uniform(low=-1, high=1, size=(10,10))
print(','.join([str(list(x)) for x in a]))
</code></pre>
<p>This will print</p>
<pre><code>[-0.2403881196886386, ... , 0.8518165986395723],[-0.2403881196886386, ... | arrays|numpy|iteration | 1 |
377,901 | 57,550,935 | Tensorflow Tf.tf.squared_difference is showing a value error with dense layer | <p>Whenever I try to multiply two tensors and then feed them as an input to a dense layer, it is working perfectly. But, when I try to calculate the squared difference between them, it's showing me an error.</p>
<pre><code># working well
out= multiply([user, book])
result = Dense(1, activation='sigmoid', kernel_i... | <p>You probably need to pass <code>keepdims=True</code> argument to <code>reduce_sum</code> function in order to keep the dimensions with length 1 (otherwise, the shape of <code>out</code> would be <code>(batch_size)</code>, whereas the <code>Dense</code> layer expects <code>(batch_size, N)</code>):</p>
<pre><code>out... | python|tensorflow|keras|tensor | 1 |
377,902 | 57,435,469 | How to generate random categorical data in python according to a probability distribution? | <p>I am trying to generate a random column of categorical variable from an existing column to create some synthesized data. For example if my column has 3 values 0,1,2 with 0 appearing 50% of the time and 1 and 2 appearing 30 and 20% of the time I want my new random column to have similar (but not same) proportions as ... | <p>Use <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.choice.html" rel="noreferrer"><code>np.random.choice()</code></a> and specify a vector of probabilities corresponding to the chosen-from arrray:</p>
<pre><code>>>> import numpy as np
>>> np.random.seed(444)
>... | python-3.x|pandas|numpy|random | 18 |
377,903 | 57,705,786 | How to sum specific columns in pandas | <p>I am trying to find the average specific columns of my csv file which has been read into a Dataframe by pandas. I would like to find the mean for 2018 Jul to 2018 Sep and then display them.</p>
<pre><code>Variable | 2018 Jul | 2018 Aug | 2018 Sep | 2018 Oct | 2018 Nov | 2018 Dec | ....
GDP | 100 | 200 ... | <p>I think <code>0:1</code> should be removed if need mean of all rows and add <code>axis=1</code> to <code>mean</code> per rows:</p>
<p>If <code>Variable</code> is column:</p>
<pre><code>#for convert to numeric
vam2.iloc[:, 1:] = vam2.iloc[:, 1:].apply(pd.to_numeric, errors='coerce')
vam2['2018 Jul-Sep'] = vam2.ilo... | python-3.x|pandas | 2 |
377,904 | 57,437,415 | Probability Density Function using pandas data | <p>I would like to model the probability of an event occurring given the existence of the previous event.</p>
<p>To give you more context, I plan to group my data by anonymous_id, sort the values of the grouped dataset by timestamp (ts) and calculate the probability of the sequence of sources (utm_source) the person g... | <p>Here is one way you can do it (if I understand correctly):</p>
<pre><code>from itertools import chain
from collections import Counter
groups = (df
.sort_values(by='ts')
.dropna()
.groupby('anonymous_id').utm_source
.agg(list)
.reset_index()
)
groups['transitions'] = groups.utm_source.apply(lambda x: lis... | python|pandas|scipy | 0 |
377,905 | 57,721,682 | Chinese character insert issue | <p>I have the following dataframe in pandas</p>
<p><a href="https://i.stack.imgur.com/YWmbV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YWmbV.png" alt="enter image description here"></a></p>
<p>need to insert all value into a datawarehouse with chinese characters but chinese characters are inst... | <p>You are using <em>dynamic SQL</em> to construct string literals containing Chinese characters, but you are creating them as</p>
<pre class="lang-sql prettyprint-override"><code>insert into tablename values ('你好')
</code></pre>
<p>when SQL Server expects Unicode string literals to be of the form</p>
<pre class="la... | python|pandas|azure|pypyodbc | 1 |
377,906 | 57,595,921 | Custom sort for histogram | <p>After looking at countless questions and answers on how to do custom sorting of the bars in bar charts (or a histogram in my case) it seemed the answer was to sort the dataframe as desired and then do the plot, only to find that the plot ignores the data and blithely sorts alphabetically. There does not seem to be a... | <p>A histogram was not the right plot here. With the following code the bars, sorted as desired, are created:</p>
<pre><code>from matplotlib import pyplot as plt
import pandas as pd
%matplotlib inline
diamonds = pd.DataFrame({'carat': [0.23, 0.21, 0.23, 0.24, 0.22],
'cut' : ['Ideal', 'Premium', 'G... | python|pandas|matplotlib | 0 |
377,907 | 57,672,738 | Using pandas combine worksheets, iterate through a specific column, add rows to a new list | <p>I have an excel workbook with multiple worksheets that all have the same column headers. I want to iterate through one of the columns within each of the worksheets and add the rows to a new list (or column).</p>
<p>Background: Each of the worksheets represents a different community of farmers and each column of eac... | <pre><code>import pandas as pd
import numpy as np
# read excel file into notebook assign to pro2019
pro2019 = pd.read_excel(path_to_file, sheet_name=None)
# concatenate all of the worksheets within the file removing the index
# from individual sheets
df = pd.concat(pro2019, ignore_index=True)
# create empty list to... | python|excel|pandas|jupyter-notebook | 0 |
377,908 | 24,377,095 | python equivalent of MATLAB statement A(B==1)= C | <p>I have three numpy arrays as follows:</p>
<pre><code>A = [1, 2, 3, 4, 5]
B = [0, 1, 0, 0, 1]
C = [30, 40]
</code></pre>
<p>I would like to replace the elements of A which their equivalent in B is equal to 1. For the above example I would like to get this:</p>
<pre><code>A = [1, 30, 3, 4, 40]
</code></pre>
<p>In ... | <p>The syntax is pretty similar:</p>
<pre><code>>>> import numpy as np
>>> A = np.array([1, 2, 3, 4, 5])
>>> B = np.array([0, 1, 0, 0, 1])
>>> C = np.array([30, 40])
>>> A[B==1] = C
>>> A
array([ 1, 30, 3, 4, 40])
</code></pre> | python|numpy|indexing | 1 |
377,909 | 24,036,028 | reading millisecond data into pandas | <p>I have a file with data like this, and want to load it, and use timestamp column (which denotes milliseconds) as a DateTimeIndex.</p>
<pre><code> x y
timestamp
0 50 90
125 37 ... | <p>Something similar, but simpler I think (python <code>datetime.datetime</code> uses microseconds, so therefore the factor 1000):</p>
<pre><code>In [12]: import datetime
In [13]: def convert_time(a):
...: ms = int(a)
...: return datetime.datetime(2012, 1, 1, 0, 0, 0, ms*1000)
In [14]: pd.read_csv(cu... | python|pandas | 4 |
377,910 | 24,228,050 | Pandas; calculate mean and append mean to original frame | <p>I have a pandas DataFrame where the first column is a country label and the second column contains a number. Most countries are in the list multiple times. In want to do 2 operations:</p>
<ol>
<li>Calculate the mean for every country</li>
<li>Append the mean of every country as a third column</li>
</ol> | <p>Perform a <code>groupby</code> by 'Country' and use <code>transform</code> to apply a function to that group which will return an index aligned to the original df</p>
<pre><code>df.groupby('Country').transform('mean')
</code></pre>
<p>See the online docs: <a href="http://pandas.pydata.org/pandas-docs/stable/groupb... | python|pandas | 3 |
377,911 | 24,377,317 | Download stocks data from google finance | <p>I'm trying to download data from Google Finance from a list of stocks symbols inside a .csv file.</p>
<p>This is the class that I'm trying to adapt from this <a href="http://trading.cheno.net/downloading-google-finance-historical-data-with-python/" rel="nofollow">site</a>:</p>
<pre><code>import urllib,time,datetim... | <p>It should work, but notice that the ticker should be: <strong>BVMF:ABRE11</strong></p>
<pre><code>In [250]:
import pandas.io.data as web
import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
df=web.DataReader("BVMF:ABRE11", 'google', start, end)
print df.head(10)
O... | python|pandas|web-scraping | 2 |
377,912 | 24,215,886 | TypeError when attempting cross validation in sklearn | <p>I really need some help but am new to programming so please forgive my general ignorance. I am trying to perform cross-validation on a data set using ordinary least squares regression from scikit as the estimator.</p>
<p>Here is my code:</p>
<pre><code>from sklearn import cross_validation, linear_model
import nump... | <p>The cross-validation iterators return indices for use in indexing into numpy arrays, but your data are plain Python lists. Python lists don't support the fancy kinds of indexing that numpy arrays do. You're seeing this error because Python is trying to interpret <code>train</code> and <code>test</code> as somethin... | python|numpy|machine-learning|scikit-learn | 4 |
377,913 | 24,143,291 | Combining data from two dataframe columns into one column | <p>I have time series data in two separate <code>DataFrame</code> columns which refer to the same parameter but are of differing lengths. </p>
<p>On dates where data only exist in one column, I'd like this value to be placed in my new column. On dates where there are entries for both columns, I'd like to have the mean... | <p>You are close, but you actually don't need to iterate over the rows when using the isnull() functions. by default</p>
<pre><code>df[(df['DOC_mg/L'].isnull() == False) & (df['TOC_mg/L'].isnull() == True)].index
</code></pre>
<p>Will return just the index of the rows where <code>DOC_mg/L</code> is not null and <... | python-2.7|pandas | 2 |
377,914 | 23,951,876 | Linear fit including all errors with NumPy/SciPy | <p>I have a lot of x-y data points with errors on y that I need to fit non-linear functions to. Those functions can be linear in some cases, but are more usually exponential decay, gauss curves and so on. SciPy supports this kind of fitting with <code>scipy.optimize.curve_fit</code>, and I can also specify the weight o... | <p>One way that works well and actually gives a better result is the bootstrap method. When data points with errors are given, one uses a parametric bootstrap and let each <code>x</code> and <code>y</code> value describe a Gaussian distribution. Then one will draw a point from each of those distributions and obtains a ... | python|numpy|scipy | 5 |
377,915 | 43,605,405 | How to join strings in pandas column based on a condition | <p>Given a dataframe:</p>
<pre><code> text binary
1 apple 1
2 bee 0
3 cider 1
4 honey 0
</code></pre>
<p>I would like to get 2 lists:
one = [apple cider], zero = [bee honey]</p>
<p>How do I join the strings in the 'text' column based on the group (1 or 0) they belong to in the column 'binary'?</p>
... | <p><strong>UPDATE:</strong> Follow up Question</p>
<p>one list for each <code>text*</code> column grouped by <code>binary</code> column</p>
<pre><code>In [56]: df.set_index('binary').stack().groupby(level=[0,1]).apply(list).unstack()
Out[56]:
text1 text2 text3
binary
0 [bee... | python|list|pandas|dataframe|group-by | 1 |
377,916 | 43,744,171 | Create a Combined CSV Files | <p>I have two CSV files <code>reviews_positive.csv</code> and <code>reviews_negative.csv</code>. How can I combine them into one CSV file, but in the following condition:</p>
<ul>
<li>Have odd rows fill with reviews from <code>reviews_positive.csv</code> and even rows fill up with reviews from <code>reviews_negative.c... | <p>Here is a working example</p>
<pre><code>from io Import StringIO
import pandas as pd
pos = """rev
a
b
c"""
neg = """rev
e
f
g
h
i"""
pos_df = pd.read_csv(StringIO(pos))
neg_df = pd.read_csv(StringIO(neg))
</code></pre>
<p><strong><em>Solution</em></strong><br>
<em><code>pd.concat</code> with the <code>keys</cod... | pandas|neural-network|dataset | 3 |
377,917 | 43,697,219 | Select indices in tensorflow that fulfils a certain condition | <p>I wish to select elements of a matrix where the coordinates of the elements in the matrix fulfil a certain condition. For example, a condition could be : (y_coordinate-x_coordinate) == -4
So, those elements whose coordinates fulfil this condition will be selected. How can I do this efficiently without looping throug... | <p>Perhaps you need <a href="https://www.tensorflow.org/api_docs/python/tf/gather_nd" rel="nofollow noreferrer"><code>tf.gather_nd</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>iterSession = tf.InteractiveSession()
vals = tf.constant([[1,2,3], [4,5,6], [7,8,9]])
arr = tf.constant([[x, y] for x in ra... | tensorflow | 2 |
377,918 | 43,844,339 | How to use a TensorFlow LinearClassifier in Java | <p>In Python I've trained a TensorFlow LinearClassifier and saved it like:</p>
<pre><code>model = tf.contrib.learn.LinearClassifier(feature_columns=columns)
model.fit(input_fn=train_input_fn, steps=100)
model.export_savedmodel(export_dir, parsing_serving_input_fn)
</code></pre>
<p>By using the TensorFlow Java API I a... | <p>The names of the nodes to feed would depend on what <code>parsing_serving_input_fn</code> does, in particular they should be the names of the <code>Tensor</code> objects that are returned by <code>parsing_serving_input_fn</code>. The names of the nodes to fetch would depend on what you're predicting (arguments to <c... | java|tensorflow | 7 |
377,919 | 43,485,775 | How to stop gradient of LSTMStateTuple in tensorflow | <p>I am running a basic lstm code for language modeling.
But I don't want to do <code>BPTT</code>. I want to do something like <code>tf.stop_gradient(state)</code></p>
<pre><code>with tf.variable_scope("RNN"):
for time_step in range(N):
if time_step > 0: tf.get_variable_scope().reuse_variables()
(cell_out... | <p>I think this is a pure python question: LSTMStateTuple is just a collections.namedtuple and python doesn't allow you to assign elements there (as in other tuples). The solution is to create a fully new one, e.g. like in <code>stopped_state = LSTMStateTuple(tf.stop_gradient(old_tuple.c), tf.stop_gradient(old_tuple.h)... | python|tensorflow | 0 |
377,920 | 43,530,487 | using shift() to compare row elements | <p>I have the sample data and code below where I'm trying to loop through the dataDF column with the function and find the first case of increasing values then return the Quarter value corresponding the the 1st increasing value from the dataDF column. I'm planning to use the function with apply, but I don't think I'm ... | <p>Try</p>
<pre><code>df.Quarter[df.dataDF > df.dataDF.shift()].iloc[0]
</code></pre>
<p>Returns</p>
<p>'2009q3'</p> | python-3.x|pandas|apply | 2 |
377,921 | 43,921,417 | How to get cell location from pandas diff? | <pre><code>df1 = pd.read_excel(mxln) # Loads master xlsx for comparison
df2 = pd.read_excel(sfcn) # Loads student xlsx for comparison
difference = df2[df2 != df1] # Scans for differences
</code></pre>
<p>Wherever there is a difference, I want to store those cell locations in a list. It needs to be in the format 'A... | <p>To get the difference cells from two <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow noreferrer"><code>pandas.DataFrame</code></a> as excel coordinates you can do:</p>
<p><strong>Code:</strong></p>
<pre><code>def diff_cell_indices(dataframe1, dataframe2):
fro... | python|excel|python-3.x|pandas|openpyxl | 2 |
377,922 | 43,720,337 | PandaTables and Exif - adding columns as needed | <p>So I'm trying to use the incredible Pandastable to display jpeg exif data from a csv file. I'm processing these files with exifread, writing it to a csv and then importing with Pandastable on a tk.button click with the following code:</p>
<pre><code>def load_file():
fname = askopenfilename(filetypes=(("JPEG/TIFF fi... | <p>Below is a basic example. I'm not sure what your final output is supposed to be. Are you trying to concat the two dataframes into one?</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A' : [1,1,3,4,5,5,3,1,5,np.NaN],
'B' : [1,np.NaN,3,5,0,0,np.NaN,9,0,5],
... | python|csv|pandas | 1 |
377,923 | 43,798,895 | Pandas String Replace Error Python | <p>I am doing a bit of webscraping and would like to remove parts of a string.</p>
<pre><code>PlayerDataHeadings = soup.select(".auflistung th")
PlayerDataItems = soup.select(".auflistung td")
PlayerData = pd.DataFrame(
{'PlayerDataHeadings': PlayerDataHeadings,
'PlayerDataItems': PlayerDataItems... | <p>It seems you miss <code>=</code>:</p>
<pre><code>to_replace=
</code></pre>
<p>Or omit keyword and add <code>regex=True</code>:</p>
<pre><code>PlayerData['PlayerDataHeadings'].replace(['<th>', ':</th>'], '', inplace=True, regex=True)
</code></pre>
<p>Sample:</p>
<pre><code>PlayerData = pd.DataFrame({... | python|pandas | 0 |
377,924 | 43,919,240 | Crashes python.exe: ucrtbase.DLL | <p>When I try to run tensorflow Python crashes with the following message:</p>
<pre><code>Problem signature:
Problem Event Name: BEX64
Application Name: python.exe
Application Version: 3.5.3150.1013
Application Timestamp: 58ae5709
Fault Module Name: ucrtbase.DLL
Fault Module Version: 10.0.10... | <p>I was having <a href="https://stackoverflow.com/q/45090994/5330223">same error</a> while trying to run visual studio 15 code using visual studio 12 specific libraries from OpenCV.</p>
<p>So, if you are trying to build a c++ program named <code>python.exe</code> check the dependent libraries or if you are trying to ... | python|tensorflow|jupyter-notebook | 0 |
377,925 | 43,865,813 | Python: Doing Calculations on array elements in a list | <p>I have a list of arrays, in which each array represents a cell and the array elements are the coordinates x,y and z, the time point and the cell id. Here a sector of it:</p>
<pre><code>cells=[ ...,
[ 264.847, 121.056, 30.868, 42. , 375. ],
[ 259.24 , 116.875, 29.973, 43. , 375. ],
[ ... | <p>First off you need to convert your list to a numpy array. It's more proper to create a numpy array instead of a list at first place. Then you can take advantage of numpy's vectorized operation support:</p>
<p>Here is an example:</p>
<pre><code>In [45]: arr = np.arange(100).reshape(4, 5, 5)
In [46]: arr
Out[46]:
... | arrays|numpy|math|scipy | 1 |
377,926 | 43,771,044 | Summing numpy array elements together | <p>i'm trying to make a polinomial calculator in which i can insert the largest coefficient, problem is, the xizes variable, that would be the image of the function is coming as multiple arrays, therefore the function graphic (using matplotlib) is coming like this (this is a third degree polynomial(x³+x²+x¹+x^0)): <a h... | <p>nevermind, already figured it out, if it will help somebody later i added the folowing line to sum it</p>
<pre><code>xizes = np.sum(xizes,axis=1)
</code></pre> | python|numpy|matplotlib | 1 |
377,927 | 43,824,969 | What is the most efficient method for accessing and manipulating a pandas df | <p>I am working on an agent based modelling project and have a 800x800 grid that represents a landscape. Each cell in this grid is assigned certain variables. One of these variables is 'vegetation' (i.e. what functional_types this cell posses). I have a data fame that looks like follows:</p>
<p><a href="https://i.stac... | <p>You need to extract as many calculations as you can into a vectorized preprocessing step. For example in your 800x800 loop you have:</p>
<pre><code>burn_s_m_p = round(2-(1/(1 + (math.exp(- (self.landscape.soil_moisture[x, y] * 3)))) * 2),4)
</code></pre>
<p>Instead of executing this line 800x800 times, just do it... | python|pandas | 0 |
377,928 | 43,922,145 | Run nltk sent_tokenize through Pandas dataframe | <p>I have a dataframe that consists of two columns: ID and TEXT. Pretend data is below:</p>
<pre><code>ID TEXT
265 The farmer plants grain. The fisher catches tuna.
456 The sky is blue.
434 The sun is bright.
921 I own a phone. I own a book.
</code></pre>
<p>I know all nltk functions do not work ... | <p><strong>edit</strong>: as a result of warranted prodding by @alexis here is a better response</p>
<p><strong><em>Sentence Tokenization</em></strong></p>
<p>This should get you a DataFrame with one row for each ID & sentence:</p>
<pre><code>sentences = []
for row in df.itertuples():
for sentence in row[2].... | python|pandas|dataframe|nltk | 6 |
377,929 | 43,695,085 | Tensorflow Deep Learning Memory Leak? | <p>I am doing GPU-accelerated deep learning with Tensorflow, and am experiencing a memory leak (the RAM variety, not on the GPU).</p>
<p>I have narrowed it down, almost beyond all doubt, to the training line</p>
<pre><code>self.sess.run(self.train_step, feed_dict={self.x: trainingdata, self.y_true: traininglabels, se... | <p>This issue is solved in 1.1. Ignore <a href="https://www.tensorflow.org/versions/" rel="nofollow noreferrer">this page</a> which (at the time of writing) says that the latest stable version is r0.12; 1.1 is the latest stable version. See <a href="https://github.com/tensorflow/tensorflow/issues/9590" rel="nofollow ... | memory-leaks|tensorflow | 1 |
377,930 | 43,516,202 | Finding local minima on a 2D map using tensorflow | <p>I am trying to detect location and values of local minima on a 2D image map using tensorflow. Since this is not trivial I was wondering what a robust and efficient way in tf might be?</p>
<p>So far I thought of simple horizontal and vertical convolutions using [-1 1] kernels.</p> | <p>You can find your local maxima with pooling like this:</p>
<pre><code>import tensorflow as tf
def get_local_maxima(in_tensor):
max_pooled_in_tensor = tf.nn.pool(in_tensor, window_shape=(3, 3), pooling_type='MAX', padding='SAME')
maxima = tf.where(tf.equal(in_tensor, max_pooled_in_tensor), in_tensor, tf.zeros_l... | optimization|tensorflow|deep-learning | 6 |
377,931 | 43,645,135 | Boolean indexing assignment of a numpy array to a numpy array | <p>I am seeing some behavior with Boolean indexing that I do not understand, and I was hoping to find some clarification here.</p>
<p>First off, this is the behavior I am seeking...</p>
<pre><code>>>>
>>> a = np.zeros(10, dtype=np.ndarray)
>>> a
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=o... | <pre><code>In [203]: a = np.empty(5, object)
In [204]: a
Out[204]: array([None, None, None, None, None], dtype=object)
In [205]: a[3]=np.arange(3)
In [206]: a
Out[206]: array([None, None, None, array([0, 1, 2]), None], dtype=object)
</code></pre>
<p>So simple indexing works with this object array.</p>
<p>Boolean inde... | numpy|multidimensional-array|indexing|boolean | 1 |
377,932 | 43,543,546 | Python How to convert a float as hex to decimal | <p>I've read in some data from a csv file with pandas. The data is incomplete and therefore contains many nan values.
I want to add a column to the data which converts the hex values to decimal values. Unfortunately, the column with the hex values are all read as floats, not strings because they just happen to have tho... | <p>You can mask the rows of interest and double cast and call <code>apply</code>:</p>
<pre><code>In [126]:
df['valdec'] = df['val'].dropna().astype(int).astype(str).apply(lambda x: int(x, 16))
df
Out[126]:
val valdec
0 20.0 32.0
1 NaN NaN
2 20.0 32.0
</code></pre>
<p>So firstly we call <code>dropn... | python|pandas | 4 |
377,933 | 43,652,161 | "Numpy" TypeError: data type "string" not understood | <p>I am a newbie trying to learn data visuallizaion using python.
Actually, I was just trying to follow the example given by a <a href="https://www.google.co.jp/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwiQ9-Tql8TTAhWMS7wKHScaDNMQFggnMAA&url=https%3A%2F%2Fwww... | <p>Try dtype='str' instead of dtype='string'.</p> | python|csv|numpy | 12 |
377,934 | 43,867,297 | Addition of 2 dataframes column to column by unique column in pandas | <p>I have 2 dataframes </p>
<pre><code>df1
a b c
1 2 3
2 4 5
3 6 7
</code></pre>
<p>and </p>
<pre><code>df2
a b c
1 3 4
3 1 8
</code></pre>
<p>I want output to be</p>
<pre><code>df3
a b c
1 5 7
2 4 5
3 7 15
</code></pre>
<p>I tried <code>df1.add(df2,axis='c')</code> but not getting exact output.</p>
<p>refer... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> by column <code>a</code> in both <code>df</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="nofollow n... | python|pandas | 4 |
377,935 | 43,751,651 | pandas convert datatime column to timestamp | <p>I am beginner in pandas </p>
<p>I have dataframe first column is datatime like "19-Sep-2016 10:30:00" and many records like it.</p>
<p>I am trying to convert this column to timestamp and write it to another dataframe , i am trying to do it with one step.</p>
<p>I am trying to write in python 3.</p>
<pre><code>im... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>:</p>
<pre><code>df = pd.DataFrame({'DateTime':['19-Sep-2016 10:30:00','19-Sep-2016 10:30:00']})
print (df)
DateTime
0 19-Sep-2016 10:30:00
1 19-... | python|python-3.x|pandas | 3 |
377,936 | 43,697,616 | Problems with shuffling arrays in numpy? | <p>I am having this unusual problem with shuffling arrays in numpy</p>
<pre><code>arr = np.arange(9).reshape((3, 3))
print "Original constant array"
print arr
new_arr=arr
for i in range(3):
np.random.shuffle(new_arr)
print "Obtained constant array"
print arr
print "randomized array"
print n... | <p>Use</p>
<pre><code>new_arr = np.copy(arr)
</code></pre>
<p>instead of</p>
<pre><code>new_arr = arr
</code></pre>
<p>When you do <code>new_arr=arr</code> you basically create a reference <code>new_arr</code> for your array <code>arr</code></p>
<hr>
<p>for example (Taken from <a href="https://docs.scipy.org/doc/... | python|arrays|numpy | 1 |
377,937 | 43,690,496 | Comparison of two NumPy arrays without order | <p>I have to compare two numpy arrays regardless of their order. I had hoped that numpy.array_equiv(a, b) will do the trick but unfortunately, it doesn't. Example:</p>
<pre><code>a = np.array([[3, 1], [1,2]])
b = np.array([[1, 2], [3, 1]])
print (np.array_equiv(a, b))`# return false
</code></pre>
<p>Any suggestions? ... | <p>You could use <code>np.array_equal(np.sort(a.flat), np.sort(b.flat))</code></p>
<pre><code>In [56]: a = np.array([[3, 1], [1, 2]])
In [57]: b = np.array([[1, 2], [3, 1]])
In [58]: np.array_equal(np.sort(a.flat), np.sort(b.flat))
Out[58]: True
In [59]: b = np.array([[1, 2], [3, 4]])
In [60]: np.array_equal(np.so... | python|arrays|numpy|comparison | 2 |
377,938 | 43,588,601 | How to implement the 'group' of alexnet in tensorlayer | <p>group are used to group parameters of the convolution kernel (which connects the previous layer and the current layer) into k parts forcibly in alexnet, is there a simple implement for group in tensorlayer?</p> | <p><a href="https://kratzert.github.io/2017/02/24/finetuning-alexnet-with-tensorflow.html" rel="nofollow noreferrer">This</a> might be a useful link. You need to split the conv layers before convolving and then concatenate the result. </p>
<p>If it helps, the explanation of how the weights of <a href="https://github.c... | tensorflow|tflearn | 1 |
377,939 | 43,832,484 | expanding a dataframe based on start and end columns (speed) | <p>I have a <code>pandas.DataFrame</code> containing <code>start</code> and <code>end</code> columns, plus a couple of additional columns. I would like to expand this dataframe into a time series that starts at <code>start</code> values and end at <code>end</code> values, but copying my other columns. So far I came up ... | <p>Inspired by <a href="https://stackoverflow.com/a/43833607/5741205">@StephenRauch's solution</a> I'd like to post mine (which is pretty similar):</p>
<pre><code>dates = [pd.bdate_range(r[0],r[1]).to_series() for r in df[['start','end']].values]
lens = [len(x) for x in dates]
r = pd.DataFrame(
{col:np.repeat... | python|pandas|numpy | 8 |
377,940 | 43,617,382 | pandas: cumsum ignoring first two rows | <p>I have a dataframe which has the following column:</p>
<pre><code>|---------------------|
| A |
|---------------------|
| 0 |
|---------------------|
| 2.63 |
|---------------------|
| 7.10 |
|---------------------|
| 5.70 |
|--------... | <p>You can add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow noreferrer"><code>shift</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a>:</p>
<pre><code>df = d... | python|pandas|dataframe|cumsum | 5 |
377,941 | 43,608,826 | Deleting a csv file which is created using numpy.savetxt in pyspark | <p>I am new to pyspark and python.
After saving a file in local system using <code>numpy.savetxt("test.csv",file,delimiter=',')</code>
I am using <strong>os</strong> to delete that file. <code>os.remove("test.csv")</code>. I am getting an error <strong>java.io.FileNotFoundException File file:/someDir/test.csv does not ... | <p>Looks like your spark workers are not able to access the file. You are probably running the master and workers on different servers. When you are trying to work on files, while having setup workers across different machines make sure these workers can access the file.You could keep the same copy of files among all t... | python|numpy|pyspark | 1 |
377,942 | 43,867,102 | Division with numpy matrices that might result in nan | <p>How can I divide two numpy matrices <code>A</code> and <code>B</code> in python when sometimes the two matrices will have 0 on the same cell?</p>
<p>Basically <code>A[i,j]>=B[i,j]</code> for all <code>i</code>, <code>j</code>. I need to calculate <code>C=A/B</code>. But sometimes <code>A[i,j]==B[i,j]==0</code>. ... | <p>You can use the <a href="https://docs.scipy.org/doc/numpy/reference/ufuncs.html#optional-keyword-arguments" rel="nofollow noreferrer"><code>where</code></a> argument for ufuncs like <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.true_divide.html" rel="nofollow noreferrer"><code>np.true_divide</c... | python|numpy|matrix|division|divide-by-zero | 4 |
377,943 | 43,604,110 | Struggling when appending dataframes | <p>I am looking forward to append various dataframes through a loop that extracts from a web a series of data. The function <code>ratios_funda</code> by its own works correctly, however I don't find a way to loop it according to the different tickers and append them one after the other in the empty <code>dataframe</cod... | <p>the problem is with having <code>return</code> in the <code>for</code> loop.</p>
<pre><code>def resultados():
dataframe=pd.DataFrame()
for titulos in cartera:
ruta=pd.read_html('your url here')
if dataframe.empty:
dataframe= ratios_funda(ruta)
else:
dataframe=pd.conc... | python|pandas | 1 |
377,944 | 2,199,940 | Calculating conditional probabilities from joint pmfs in numpy, too slow. Ideas? (python-numpy) | <p>I have a conjunctive probability mass function array, with shape, for example (1,2,3,4,5,6) and I want to calculate the probability table, conditional to a value for some of the dimensions (export the cpts), for decision-making purposes.</p>
<p>The code I came up with at the moment is the following (the input is th... | <p>Ok, found the answer myself after playing a little with numpy's in-place array manipulations.</p>
<p>Changed the last 3 lines in the loop to:</p>
<pre><code> d = conditionalize(d, dim, val)
</code></pre>
<p>where conditionalize is defined as:</p>
<pre><code> def conditionalize(arr, dim, val):
arr =... | python|numpy|probability|arrays|recarray | 1 |
377,945 | 2,271,565 | How to use numpy with cygwin | <p>I have a bash shell script which calls some python scripts. I am running windows with cygwin which has python in /usr/bin/python. I also have python and numpy installed as a windows package. When I execute the script from cygwin , I get an ImportError - no module named numpy. I have tried running from windows shell... | <p>Windows python and Cygwin Python are independent; if you're using Cygwin's Python, you need to have numpy installed in cygwin.</p>
<p>If you'd prefer to use the Windows python, you should be able to call it from a bash script by either:</p>
<ul>
<li>Calling the windows executable directly:<br> <code>c:/Python/pyth... | python|cygwin|numpy | 4 |
377,946 | 72,943,101 | Pandas: Weird transformation required | <pre><code>Name Start End Units Place
Sam 04-03-2022 06-03-2022 2 CA
Uber 24-04-2022 27-05-2022 1 SVL
Twitter 26-04-2022 28-04-2022 2 FR
</code></pre>
<p>My dataframe is like above. I wish to duplicate each row by n times where n equal to the difference between Start and End entry. But... | <p>You can apply <code>pd.date_range</code> to each row then explode your dataframe:</p>
<pre><code># Not mandatory if it's already the case
df['Start'] = pd.to_datetime(df['Start'], dayfirst=True)
df['End'] = pd.to_datetime(df['End'], dayfirst=True)
date_range = lambda x: pd.date_range(x['Start'], x['End']-pd.DateOff... | pandas | 1 |
377,947 | 73,119,792 | how to multiply three arrays with different dimension in PyTorch | <p><a href="https://i.stack.imgur.com/oJDUk.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>L array dimension is (d,a) ,B is (a,a,N) and R is (a,d). By multiplying these arrays I have to get an array size of (d,d,N). How could I implement this is PyTorch</p> | <p>A possible and straightforward approach is to apply <a href="https://pytorch.org/docs/stable/generated/torch.einsum.html" rel="nofollow noreferrer"><code>torch.einsum</code></a> (read more <a href="https://stackoverflow.com/questions/26089893/understanding-numpys-einsum">here</a>):</p>
<pre><code>>>> torch.... | pytorch | 1 |
377,948 | 72,891,809 | Retain all columns after resample (pandas) | <p>My data looks like so:</p>
<pre><code>import pandas as pd
import numpy as np
BG_test_df = pd.DataFrame(
{'PERSON_ID': [1, 1, 1],
'TS': ['2021-08-14 19:00:27', '2021-08-14 20:00:27', '2021-08-14 22:35:27'],
'bias': ["Not outside of acceptable operation. Refer to patient education"... | <p>You can specify a different aggregation function (e.g. <code>min</code>) for <code>BG_TS</code> to keep it in the result:</p>
<pre class="lang-py prettyprint-override"><code>merged.set_index('CGM_TS').resample('5T').agg({'PERSON_ID':np.sum, 'SG':np.sum, 'BG_TS':np.min}).reset_index()
</code></pre>
<p>Output (for you... | python|pandas | 1 |
377,949 | 73,070,147 | How to define combine loss function in keras? | <p>My model arch is
<a href="https://i.stack.imgur.com/PKDcD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PKDcD.png" alt="enter image description here" /></a></p>
<p>I have two outputs, I want to train a model based on two outputs such as mse, and cross-entropy. At first, I used two keras loss</p>... | <p>It is hard to judge the issues depending on the information given. A reason might be a too small batch size or a too high learning rate, making the training unstable. I also wonder, that you use <code>sparse_categorical_crossentropy</code> in the top example and <code>binary_crossentropy</code> in the lower one. How... | tensorflow|keras|deep-learning|loss-function | 0 |
377,950 | 72,908,478 | Date matching not working on date and object? | <p>I have a variable which holds a date inputted by the user and converts it to date format using this code:</p>
<pre><code>correct_date = "2022-06-08"
correct_date = dt.datetime.strptime(correct_date,'%Y-%m-%d').date()
</code></pre>
<p>I also have some embedded SQL in the same script that returns dates in YY... | <p>In above case, you are comparing 'String' with Date object. which will always return False.</p>
<p>Instead, converting the string to Date, and then comparing will give correct result.
Check below code.</p>
<pre class="lang-py prettyprint-override"><code>if datetime.datetime.strptime(actual_dates["contact_date&q... | python|pandas|date | 0 |
377,951 | 72,869,375 | Merge three different dataframes in Python | <p>I want to merge three data frames in Python, the code I have now provide me with some wrong outputs.</p>
<p>This is the first data frame</p>
<pre><code> df_1
Year Month X_1 Y_1
0 2021 January $90 $100
1 2021 February NaN $120
2 2021 March $100 $130
3 2021 A... | <p>You can try with</p>
<pre><code>df_1.merge(df_2, how='left', on=['Year', 'Month']).merge(df_3, how='left', on=['Year', 'Month'])
</code></pre> | python|pandas|dataframe | 2 |
377,952 | 72,871,984 | Python: correlation co-efficient between two sets of data | <h2>Correlation Co-efficient calculation in Python</h2>
<p>How would I calculate the correlation coefficient using Python between the <em>spring training wins</em> column and the <em>regular-season wins</em> column?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Spr.TR</th>
<... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.corr.html" rel="nofollow noreferrer"><code>corr</code></a> (Pearson correlation by default):</p>
<pre><code>df['Spr.TR'].corr(df['Reg Szn'], method='pearson')
</code></pre>
<p>output: <code>0.10811116955657629</code></p> | python|pandas|numpy|jupyter-notebook|scipy | 0 |
377,953 | 72,881,169 | How to make for loop with pandas DataFrame? | <p>I want to make for loop formation with dataframe but i couldn't find grammar rule with this situation. Below is an overview of the functions I want to implement.
With Detail, i want to make new column named [df] which is calculated with column[f_adj]'s value.
<a href="https://i.stack.imgur.com/QmcuS.png" rel="nofoll... | <p>You should used <code>iloc</code> or <code>loc</code> in your code.</p> | python|pandas | 0 |
377,954 | 72,940,729 | python pandas: attempting to replace value in row updates ALL rows | <p>I have a simple CSV file named <code>input.csv</code> as follows:</p>
<pre><code>name,money
Dan,200
Jimmy,xd
Alice,15
Deborah,30
</code></pre>
<p>I want to write a python script that sanitizes the data in the <code>money</code> column:
every value that has non-numerical characters needs to be replaced with 0</p>
<p>... | <p>You can use:</p>
<pre><code>df['money'] = pd.to_numeric(df['money'], errors='coerce').fillna(0).astype(int)
</code></pre>
<p>The above assumes all valid values are integers. You can leave off the <code>.astype(int)</code> if you want float values.</p>
<p>Another option would be to use a converter function in the <c... | python|pandas|dataframe|csv | 3 |
377,955 | 72,931,249 | How do you lookup a particular pandas dataframe column value in a reference table and copy a reference table value to the dataframe? | <p>I have a reference table that I imported into a dataframe(df2) from a .csv. It's 3 columns and around 400 rows. I have another dataframe (df) that has many columns and rows. I am looking to lookup a value from the reference table and add it to the appropriate column in df.</p>
<p>The data format for the reference... | <p>Another way without <code>merge</code> would be this:</p>
<pre><code>df2 = df2.set_index(['MANUF', 'PRODTYPE'])
output = df2.combine_first(df1.set_index(['MANUF', 'PRODTYPE'])).reset_index()
print(output)
MANUF PRODTYPE INVENTORY PRODCODE SERIALNO
0 ALPHA 1 5 ALPHA1 1
1 ALPHA ... | python|pandas|dataframe | 0 |
377,956 | 73,029,685 | How to account for value counts that doesn't exist in python? | <p>I have the following dataframe:</p>
<pre><code> Name
----------
0 Blue
1 Blue
2 Blue
3 Red
4 Red
5 Blue
6 Blue
7 Red
8 Red
9 Blue
</code></pre>
<p>I want to count the number of times "Name" = "Blue" and "Name" = "Red" and send that to a di... | <p>In Python 3.9+ you can use <a href="https://peps.python.org/pep-0584/" rel="nofollow noreferrer">PEP 584's Union Operator</a>:</p>
<pre><code>base = {'Blue': 0, 'Red': 0}
counts = df['Name'].value_counts().to_dict()
dictionary = base | counts
# or just
dictionary = {'Blue': 0, 'Red': 0} | df['Name'].value_counts().... | python|pandas|dataframe|count | 2 |
377,957 | 72,977,080 | Correlation between two data frames in Python | <p>I have a DataFrame with Job Area Profiles which look similar to this:</p>
<p><a href="https://i.stack.imgur.com/JoLQd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JoLQd.png" alt="Job DF" /></a></p>
<p>Now I have some user input, which creates an user DataFrame. This looks like this:</p>
<p><a h... | <p>The function is working, but you cannot find the correlation with a dataframe consisting of only one datapoint, since you'll get a divide by zero error.</p>
<p>Then numerator and denominator of the correlation coefficient (<a href="https://en.wikipedia.org/wiki/Correlation#Sample_correlation_coefficient" rel="nofoll... | python|pandas|dataframe|correlation|recommendation-engine | 0 |
377,958 | 72,882,427 | Multiplicate Dataframe row with a matrix | <p>I am trying to multiplicate a dataframe with with a matrix consisting of items from the dataframe.</p>
<p>I am able to solve the problem with a for-loop, but with a large dataframe it takes very long.</p>
<pre><code>df = pd.DataFrame({"A": [1, 2, 3, 4],
"B": [5, 6, 7, 8],
... | <p>It may be easier to work with arrays, rather than a dataframe. Indexing will be lot simpler</p>
<p>The frame's numpy values:</p>
<pre><code>In [46]: df.values
Out[46]:
array([[ 1, 5, 9, 1],
[ 2, 6, 10, 1],
[ 3, 7, 11, 1],
[ 4, 8, 12, 1]], dtype=int64)
</code></pre>
<p>And for one &quo... | python|pandas|numpy|matrix | 0 |
377,959 | 72,922,890 | Optimal way for "Lookup" type operations between multiple dataframes | <p>A common task I seem to have is something like this:</p>
<p>DataFrame A contains among its columns an "id" with some kind of "price" and "description". This would typically be a very large dataset.</p>
<p>And there are 2 much smaller DataFrames: one containing columns where the (few) &q... | <p>Let's say you have the following DataFrames:</p>
<p><strong>DataFrame A (df_A)</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th style="text-align: right;">desc</th>
<th style="text-align: right;">price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td style="text-align:... | python|pandas|dataframe | 1 |
377,960 | 73,024,647 | How to show subplots for each row | <p>Currently having an issue getting all of my data to show on my subplots. I'm trying to plot a 7 row 6 column subplot using geodataframes. <a href="https://i.stack.imgur.com/UMtDo.png" rel="nofollow noreferrer">This</a> is what one of the geodataframes looks like (they all look the same).</p>
<p>My data is below:</p>... | <p>I think you need another loop to go through rows as well as columns. Hard to replicate exactly without your data sets, but I'd suggest something like this:</p>
<pre><code>f, axs = plt.subplots(nrows=7, ncols=6, figsize = (12, 12))
for i in range(7):
for j in range(6):
graph[i].plot(column=years[j], ax=a... | python|matplotlib|geopandas|subplot | 0 |
377,961 | 73,104,425 | How to update the data frame column values from another data frame based a conditional match in pandas | <p>I have two dataframes as:</p>
<p><strong>df_A:</strong></p>
<pre><code>{'last_name': {0: 'Williams', 1: 'Henry', 2: 'XYX', 3: 'Smith', 4: 'David', 5: 'Freeman', 6: 'Walter', 7: 'Test_A', 8: 'Mallesham', 9: 'Mallesham', 10: 'Henry', 11: 'Smith'}, 'first_name': {0: 'Henry', 1: 'Williams', 2: 'ABC', 3: 'David', 4: 'Smi... | <p>You can check each unique value in <code>column=name_unique_identifier</code> from <code>df_B</code> where exist in <code>df_A</code> and then insert the value from <code>df_B</code> to <code>df_A</code>.</p>
<pre><code>col = 'name_unique_identifier'
for val in df_B[col]:
msk_A = df_A[col].eq(val)
msk_B = df... | python|pandas | 2 |
377,962 | 72,905,069 | dataframe error when comparing expression levels: TypeError: Unordered Categoricals can only compare equality or not | <p>I am working with an anndata object gleaned from analyzing single-cell RNAseq data using scanpy to obtain clusters. This is far along in the process (near completed) and I am now trying to obtain a list of the average expression of certain marker genes in the leiden clusters from my data. I am getting an error at th... | <p>It seems that your <code>grouping column</code> is a categorical column and not <code>float</code> or <code>int</code>. try adding this line after the instantiation of the dataframe.</p>
<pre><code>df = sc.get.obs_df(hy_bc, markers + [grouping_column])
df[grouping_column] = df[grouping_column].astype('int64')
</code... | python|pandas|scanpy | 0 |
377,963 | 73,116,818 | module 'torch' has no attribute 'frombuffer' in Google Colab | <pre><code>data_root = os.path.join(os.getcwd(), "data")
transform = transforms.Compose(
[
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
]
)
fashion_mnist_dataset = FashionMNIST(data_root, download = True, train = True, transform = transform)
</code></pre>
<p>Error Message</p>
<blockquote>
<p>/... | <p>I tried your code in my Google Colab by adding the codes (to import the libraries) below, but it works well without errors.</p>
<pre><code>import os
from torchvision import transform
from torchvision.datasets import FashionMNIST
</code></pre>
<p>I used</p>
<ul>
<li>torchvision 0.13.0+cu113</li>
<li>google-colab ... | python-3.x|pytorch | 0 |
377,964 | 72,991,225 | How can I print the training and validation graphs, and training and validation loss graphs? | <p>I need to plot the training and validation graphs, and trarining and validation loss for my model.</p>
<pre><code>model.compile(loss=tf.keras.losses.binary_crossentropy,
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
metrics=['accuracy'])
history = model.fit(X_train, y_... | <p><code>history</code> object contains both accuracy and loss for both the training as well as the validation set. We can use matplotlib to plot from that.</p>
<p>In these plots x-axis is no_of_epochs and the y-axis is accuracy and loss value. Below is one basic implementation to achieve that, it can easily be customi... | python|tensorflow|machine-learning|deep-learning|conv-neural-network | 0 |
377,965 | 73,096,479 | python pandas substring based on columns values | <p>Given the following df:</p>
<pre><code>data = {'Description': ['with lemon', 'lemon', 'and orange', 'orange'],
'Start': ['6', '1', '5', '1'],
'Length': ['5', '5', '6', '6']}
df = pd.DataFrame(data)
print (df)
</code></pre>
<p>I would like to substring the "Description" based on what is spec... | <p>You need to loop, a list comprehension will be the most efficient (python ≥3.8 due to the walrus operator, thanks @I'mahdi):</p>
<pre><code>df['Res'] = [s[(start:=int(a)-1):start+int(b)] for (s,a,b)
in zip(df['Description'], df['Start'], df['Length'])]
</code></pre>
<p>Or using pandas for the conversion... | python|pandas|dataframe|substring | 2 |
377,966 | 72,867,109 | What is PyTorch Dataset supposed to return? | <p>I'm trying to get PyTorch to work with DataLoader, this being said to be the easiest way to handle mini batches, which are in some cases necessary for best performance.</p>
<p>DataLoader wants a Dataset as input.</p>
<p>Most of the documentation on Dataset assumes you are working with an off-the-shelf standard data ... | <p>The dataset instance is only tasked with returning a single element of the dataset, which can take many forms: a <em>dict</em>, a <em>list</em>, an <em>int</em>, a <em>float</em>, a tensor, etc...</p>
<p>But the behaviour you are seeing is actually handled by your PyTorch data loader and not by the underlying datase... | pytorch|pytorch-dataloader | 1 |
377,967 | 72,846,592 | How to remove the number of the Excel row? | <p>So I have to sort certain rows from an Excel file with pandas, save them to a text file and show them on a single page website. This is my code:</p>
<pre><code>dataTopDivision = pd.read_excel("files/Volleybal_Topdivisie_tussenstand.xlsx")
dataTopDivision1 = dataTopDivision[['datum', 'team1', 'team2', 'uits... | <p>Can you try by adding <code>index_col=None</code></p>
<p>Replace your first line</p>
<pre class="lang-py prettyprint-override"><code>dataTopDivision = pd.read_excel("files/Volleybal_Topdivisie_tussenstand.xlsx",index_col=None)
</code></pre> | python|excel|pandas | 0 |
377,968 | 72,915,083 | Iterating over rows to find mean of a data frame in Python | <p>I have a dataframe of 100 random numbers and I would like to find the mean as follows:</p>
<p>mean0 should have mean of 0,5,10,... rows</p>
<p>mean1 should have mean of 1,6,11,16,.... rows</p>
<p>.</p>
<p>.</p>
<p>.
mean4 should have mean of 4,9,14,... rows.</p>
<p>So far, I am able to find the mean0 but I am not ab... | <p>Since <code>df[::5]</code> is equivalent to <code>df[0::5]</code>, you could use <code>df[1::5]</code>, <code>df[2::5]</code>, <code>df[3::5]</code>, and <code>df[4::5]</code> for the remaining dataframes with subsequent application of mean by <code>df[i::5].mean()</code>.</p>
<p>It is not explicitly showcased in th... | python|pandas|dataframe|numpy | 2 |
377,969 | 72,974,251 | How to I reshape the 2D array like this? (By using tensor) | <p>I want to resize my image from 32 * 32 to 16 * 16. (By using torch.tensor)
Like decreasing the resolution?
Can anyone help me?</p> | <p>If you have an image (stored in a tensor) and you want to decrease it's <em>resolution</em>, then you are not <code>reshaping</code> it, but rather <em>resizing</em> it.<br />
To that end, you can use pytorch's <a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html" rel="nofollow nor... | python|numpy|pytorch | 0 |
377,970 | 73,030,417 | Creating another column in pandas based on a pre-existing column | <p>I have a third column in my data frame where I want to be able to create a fourth column that looks almost the same, except it has no double quotes and there is a 'user/' prefix before each ID in the list. Also, sometimes it is just a single ID vs. list of IDs (as shown in example DF).</p>
<p>original</p>
<pre><code... | <p>Given:</p>
<pre><code> col1 col2 col3
0 1.0 1.0 "ID278, ID289"
1 2.0 2.0 "ID275"
2 2.0 1.0 NaN
</code></pre>
<p>Doing:</p>
<pre><code>df['col4'] = (df.col3.str.strip('"') # Remove " from both ends.
.str.split(', ') # S... | python|pandas|dataframe|data-cleaning | 1 |
377,971 | 73,003,528 | Split column in several columns by delimiter '\' in pandas | <p>I have a txt file which I read into pandas dataframe. The problem is that inside this file my text data recorded with delimiter ''. I need to split information in 1 column into several columns but it does not work because of this delimiter.</p>
<p>I found this post on stackoverflow just with one string, but I don't ... | <p>It looks like your file is <em>tab-delimited</em>, because of the "\t". This may work</p>
<pre><code>pd.read_csv('file.txt', sep='\t', skiprows=8)
</code></pre> | python|pandas|dataframe|split|delimiter | 2 |
377,972 | 73,151,816 | Hugging face: RuntimeError: model_init should have 0 or 1 argument | <p>I’m trying to tune hyper-params with the following code:</p>
<pre><code>def my_hp_space(trial):
return {
"learning_rate": trial.suggest_float("learning_rate", 5e-3, 5e-5),
"arr_gradient_accumulation_steps": trial.suggest_int("num_train_epochs", 8, 16),
... | <p>According to the <a href="https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Trainer.model_init" rel="nofollow noreferrer">documentation</a> you have to pass the <code>model_init</code> as a callable.</p>
<pre class="lang-py prettyprint-override"><code>trainer = Trainer(
model_init =... | deep-learning|huggingface-transformers|huggingface | 0 |
377,973 | 72,941,143 | Incorrect df. iloc[:, 0] | <p>My df has below columns</p>
<pre><code>ID Number Name
11 ccc-456 dfg
45 ggt-56 ggg
33 67889 ttt
</code></pre>
<p>When I created a new dataframe (need it for merging with another dataframe)</p>
<pre><code>df2 = df[['ID', 'Number']]
</code></pre>
<p>I got an error message stating ID is not in the index. But... | <h2>Your issue:</h2>
<p>Based on the information provided, your "ID" column is set to your dataframe index.</p>
<p>If you run this test code, you will get the same error that you described.</p>
<pre><code>test_dict = {
'ID': [11,45,33],
'Number': ['ccc-456','ggt-56','67889'],
'Name': ['dfg','ggg',... | python|pandas | 0 |
377,974 | 73,044,210 | Is there a way to remove header and split columns with pandas read_csv? | <p>[Edited: working code at the end]</p>
<p>I have a CSV file with many rows, but only one column. I want to separate the rows' values into columns.</p>
<p>I have tried</p>
<pre><code>import pandas as pd
df = pd.read_csv("TEST1.csv")
final = [v.split(";") for v in df]
print(final)
</code></pr... | <p>Try:</p>
<pre><code>import pandas as pd
df = pd.read_csv('TEST1.csv', sep=';')
df.columns = ['Time', 'Type', 'Value', 'Size']
</code></pre> | python|pandas|dataframe|split|multiple-columns | 0 |
377,975 | 72,956,197 | Python + Pandas '>=' not supported between instances of 'str' and 'float' | <blockquote>
<p>Issue 1 - solved by using pd.to_datetime(df.Date, format='%Y-%m-%d'). Thanks to Michael</p>
</blockquote>
<p>I am trying to find the latest date of each user using their ID</p>
<pre><code>df['Latest Date'] = df.groupby(['ID'])['Date'].transform.('max')
df.drop_duplicates(subset='ID', keep='last',inplace... | <p><code>strftime</code> converts a date to string. Did you want to keep it as a datetime object but change the format? Try this instead:</p>
<pre class="lang-py prettyprint-override"><code>df.Date = pd.to_datetime(df.Date, format='%Y-%m-%d')
</code></pre>
<h2>For the Edit</h2>
<p>I'm not sure why you want the "Da... | python|pandas | 2 |
377,976 | 72,852,694 | Why do I get the 'loop of ufunc does not support argument 0 of type numpy.ndarray' error for log method? | <p>First, I used <code>np.array</code> to perform operations on multiple matrices, and it was successful.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
f = np.array([[0.35, 0.65]])
e = np.array([[0.92, 0.08], [0.03, 0.97]])
r = np.array([[0.95, 0.05], [0.06, 0.94]])
d = np.array([[0.99, 0.01], [0.0... | <p>You can't create a <em>batch</em> of matrices <code>e</code> from the variable <code>t</code> using the construct</p>
<pre><code>e = np.array([[1-t, t], [0.03, 0.97]])
</code></pre>
<p>as this would create a ragged array due to <code>[1-t, t]</code> and <code>[0.03, 0.97]</code> having different shapes. Instead, you... | python|google-colaboratory|numpy-ndarray|logarithm|numpy-ufunc | 2 |
377,977 | 73,044,698 | Pandas: str.extract() giving unexpected NaN | <p>I have a data set which has a column that looks like this</p>
<pre><code>Badge Number
1
3
23 / gold
22 / silver
483
</code></pre>
<p>I need only the numbers. Here's my code:</p>
<pre><code>df = pd.read_excel('badges.xlsx')
df['Badge Number'] = df['Badge Number'].str.extract('(\d+)')
print(df)
</code></pre>
<p>I was ... | <p>That's almost certainly because the numbers are actually integers, not strings. Try filling the missing values by the original numbers.</p>
<pre class="lang-py prettyprint-override"><code>df['Badge Number'] = df['Badge Number'].str.extract('(\d+)')[0].fillna(df['Badge Number'])#.astype(int)
</code></pre> | python|pandas|dataframe|numpy | 3 |
377,978 | 72,912,517 | how to install pandas-profiling with markupsafe error | <p>I am trying to install pandas-profiling but I keep getting the error that markupsafe cannot find 2.1.1. version.</p>
<pre><code>
!pip3 install pandas-profiling
>>
ERROR: Could not find a version that satisfies the requirement markupsafe~=2.1.1 (from pandas-profiling) (from versions: 0.9, 0.9.1, 0.9.2, 0.9.3... | <p>MarkupSafe 2.0.1 <a href="https://pypi.org/project/MarkupSafe/2.0.1/" rel="nofollow noreferrer">requires</a> Python >= 3.6. MarkupSafe 2.1.1 <a href="https://pypi.org/project/MarkupSafe/2.1.1/" rel="nofollow noreferrer">requires</a> Python >= 3.7. From this I can deduce you're using Python 3.6. Either use Mar... | python|pandas|pip|pandas-profiling | 1 |
377,979 | 73,027,816 | How to combine values in a dataframe pandas? | <p>I have below dataframe</p>
<p><a href="https://i.stack.imgur.com/iZley.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iZley.png" alt="enter image description here" /></a></p>
<p>Is there anyway we can combine values in column (Fruit) with respect to values in other two columns and get below resul... | <p>Use <code>groupby_agg</code>. If you have other columns, expand the dict with another functions if needed (max, min, first, last, ... or lambda)</p>
<pre><code>out = df.groupby(['SellerName', 'SellerID'], as_index=False).agg({'Fruit': ', '.join})
print(out)
# Output
SellerName SellerID Fruit
0 ... | python|pandas|dataframe | 1 |
377,980 | 73,112,627 | using python want to calculate last 6 months average for each month | <p>I have a dataframe which has 3 columns [user_id ,year_month & value] , i want to calculate last 6months average for the year automatically for each individual unique user_id and assign it to new column</p>
<pre><code> user_id value year_month
1 50 2021-01
1 54 2021-02
.. ... | <p>First index, your datetime column</p>
<pre><code>df = df.set_index('year_month')
</code></pre>
<p>Then do the following</p>
<pre><code>df.groupby('UserId').rolling('6M').transform('avg')
</code></pre>
<p>This is the most correct way but hey here is one more intutitive</p>
<pre><code>df.sort_values('year_month').grou... | python-3.x|pandas|numpy|datetime|average | 0 |
377,981 | 72,956,108 | remove both duplicate rows from DataFrame with negative and positive values pands | <p>DF csv</p>
<blockquote>
<p>This CSV and i am using it as Dataframe</p>
</blockquote>
<pre><code>colA,colB,colC
ABC,3,token
ABC,50,added
ABC,-50,deleted
xyz,20,token
pqr,50,added
pqr,-50,deleted
lmn,50,added
</code></pre>
<blockquote>
<p>output</p>
</blockquote>
<pre><code>colA,colB,colC
ABC,3,token
xyz,20,to... | <p>Methods based on <code>abs</code> would incorrectly remove two positive or two negative values.</p>
<p>I suggest to perform a self-merge using the opposite of colB:</p>
<pre><code># get indices that have a matching positive/negative
idx = (df.reset_index()
.merge(df, left_on=['colA', 'colB'], right_on=['col... | python|pandas | 2 |
377,982 | 72,862,624 | Subdivide values in a tensor | <p>I have a PyTorch tensor that contains the labels of some samples.</p>
<p>I want to split each label into <code>n_groups</code> groups, introducing new virtual labels.</p>
<p>For example, for the labels:</p>
<pre class="lang-py prettyprint-override"><code>labels = torch.as_tensor([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=to... | <p>A variation of OP's approach can be vectorized with a grouped cumcount <a href="https://stackoverflow.com/a/40605209/14277722">(<code>numpy</code> implementation by @divakar)</a>. All tests pass, but the output is slightly different since <code>argsort</code> has no 'stable' option in <code>pytorch</code>, AFAIK.</p... | python|pytorch|vectorization|tensor | 1 |
377,983 | 73,045,979 | Pandas Method Chaining: getting KeyError on calculated column | <p>I’m scraping <a href="https://www.collegepollarchive.com/football/ap/seasons.cfm?seasonid=2019" rel="nofollow noreferrer">web data</a> to get US college football poll top 25 information that I store in a Pandas dataframe. The data has multiple years of poll information, with preseason and final polls for each year.... | <p>Adding to BeRT2me's answer, when chaining, lambda's are pretty much always the way to go. When you use the original dataframe name, pandas looks at the dataframe as it was before the statement was executed. To avoid confusion, go with:</p>
<pre class="lang-py prettyprint-override"><code>df = df.assign(rank_int = lam... | python|pandas|dataframe|assign | 2 |
377,984 | 73,097,506 | Reduce to only row totalRevenue and rename the colunmn names in years using yahoo finance and pandas | <p>I try to scrape the yearly total revenues from yahoo finance using pandas and yahoo_fin by using the following code:</p>
<pre><code>from yahoo_fin import stock_info as si
import yfinance as yf
import pandas as pd
tickers = ('AAPL', 'MSFT', 'IBM')
income_statements_yearly= [] #All numbers in thousands
for ticker i... | <p><strong>CODE</strong></p>
<pre><code>revenues = income_statements_yearly.loc["totalRevenue"].reset_index(drop=True)
revenues.columns = ["Ticker"] + ["revenues_" + str(col) for col in revenues.columns if col != "Ticker"]
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code> ... | python|pandas|yahoo-finance | 2 |
377,985 | 72,919,181 | How to remove Index? | <p><strong>Remove index number in csv, python</strong></p>
<p>how to remove index number, and replace it with eTime value.</p>
<pre><code>import numpy as np
import pandas as pd
# load data from csv
data = pd.read_csv('log_level_out_mini.csv', delimiter=';')
time = data['eTime']
angka = data['eValue']
# Calculating c... | <p>Set <code>index_col</code> equal to <code>False</code>, as per the documentation listed <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>Note: index_col=False can be used to force pandas to not use the first column as the index, e.g. ... | python|pandas | 2 |
377,986 | 73,148,852 | ufunc 'boxcox1p' not supported for the input types. the inputs could not be safely coerced to any supported types according to the casting rule 'safe' | <p>I'm having this code (for machine learning) below:</p>
<pre><code>from scipy.special import boxcox1p
from scipy.special import boxcox
from scipy.special import inv_boxcox
df_trans=df1.apply(lambda x: boxcox1p(x,0.0))
</code></pre>
<p>With <code>df1</code> being a dataframe containing date and some other values</p>
<... | <p>The answer for this is to exclude date column. Special thanks to @AlexK for helping!</p> | python|pandas|scipy | 0 |
377,987 | 72,889,499 | How to group similar numbers with ranges/conditions and merge IDs using dataframes? | <p>Please, I have a dataframe that is listed in ascending order. My goal is to average similar numbers (numbers that are within 10% of each other in ‘both directions’) and concate their ‘Bell’ name together. For example, the image shows the input and output dataframe. I tried coding it but I stuck on how to progress.</... | <p>Assuming you really want to check in both directions that the consecutive values are within 10%, you need to compute two Series with <code>pct_change</code>. Then use it to <code>groupby.agg</code>:</p>
<pre><code>#df = df.sort_values(by='Size') for non-consecutive grouping
m1 = df['Size'].pct_change().abs().gt(0.1... | python|pandas|numpy|sorting|iteration | 0 |
377,988 | 72,933,561 | TypeError: 'int' object is not subscriptable (ImageOps.fit an image that calls cv2.cvtColor) | <p>I'm working with <em><code>Keras</code></em>, <em><code>PIL.ImageGrab</code></em>, <em><code>cv2</code></em> and <em><code>tensorflow</code></em> and there is an error that rises when I run my code(which is edited code from Teachable Machines stock code)</p>
<p>The error I get:</p>
<pre class="lang-py prettyprint-ov... | <p>Prior to <code>ImageOps.fit</code> convert your <em>numpy array</em> to <em>PIL object</em>:</p>
<pre><code>image_PIL = Image.fromarray(image)
</code></pre>
<p>Now perform</p>
<pre><code>size = (224, 224)
image = ImageOps.fit(image_PIL, size, Image.ANTIALIAS)
</code></pre>
<p>Proceed as usual.</p> | python|numpy|python-imaging-library | 1 |
377,989 | 73,004,741 | How to add a value in dataframe columns with multiple excel sheets? | <p>This should be an easy question!! But I'm stuck in it. Hope someone can help me, thanks!</p>
<p>SO I have 3 columns in 2 sheets (Ya, I just simplified to 2 sheets here). The dataset is in <a href="https://docs.google.com/spreadsheets/d/1qxGNShfrOgGXUfJd5t8qg2RoYDIcgNM9/edit?usp=sharing&ouid=103815541757228048284... | <p>Trying an answer because I think I understand. Hopefully this helps.</p>
<pre><code>writer = pd.ExcelWriter('pandas_multiple.xlsx', engine='xlsxwriter')
for i in range(40):
df = pd.read_excel(xls, i)
df['first'] += 2 # constant of your choice
df.to_excel(writer, sheet_name=i)
writer.save()
</code></pre... | python|pandas | 0 |
377,990 | 10,655,142 | faster way to append value | <p>Suppose I have a big list of float values and I want to select only some of them looking at an other array:</p>
<pre><code>result = []
for x,s in zip(xlist, slist):
if f(s): result.append(x)
</code></pre>
<p>at the begin of the loop I can have a rough estimation of how many entries will pass the <code>f</code>... | <p>There may be a better numpy solution to this, but in pure-python you can try iterators:</p>
<pre><code>from itertools import izip
xlist = [1,2,3,4,5,6,7,8]
slist = [0,1,0,1,0,0,0,1]
def f(n):
return n
results = (x for x,s in izip(xlist, slist) if f(s))
# results is an iterator--you don't have values yet
# a... | python|optimization|numpy|append | 3 |
377,991 | 10,418,325 | Basic NumPy data comparison | <p>I have an array of N-dimensional values arranged in a 2D array. Something like:</p>
<pre><code>import numpy as np
data = np.array([[[1,2],[3,4]],[[5,6],[1,2]]])
</code></pre>
<p>I also have a single value <code>x</code> that I want to compare against each data point, and I want to get a 2D array of boolean values ... | <p>Well, <code>(data == x).all(axis=-1)</code> gives you what you want. It's still constructing a 3-d array of results and iterating over it, but at least that iteration isn't at Python-level, so it should be reasonably fast.</p> | python|numpy | 2 |
377,992 | 3,674,409 | How to split/partition a dataset into training and test datasets for, e.g., cross validation? | <p>What is a good way to split a NumPy array randomly into training and testing/validation dataset? Something similar to the <code>cvpartition</code> or <code>crossvalind</code> functions in Matlab.</p> | <p>If you want to split the data set once in two parts, you can use <code>numpy.random.shuffle</code>, or <code>numpy.random.permutation</code> if you need to keep track of the indices (remember to fix the random seed to make everything reproducible):</p>
<pre><code>import numpy
# x is your dataset
x = numpy.random.ran... | python|arrays|optimization|numpy | 152 |
377,993 | 70,614,311 | Different function outputs for integers and numpy arrays | <p>I am having trouble understanding, why I get different values in the following two cases:</p>
<p>-Case 1:</p>
<pre><code>def myfunc(a,b,c):
xx = a+b
yy = b+c
return xx, yy
q,w = myfunc(1,2,3)
print(q,w)
Output 1: 3 5
</code></pre>
<p>-Case 2:</p>
<pre><code>import numpy as np
q=w=np.zeros(3)
def myf... | <p>I won't talk about the first case because it's simple and clear. For the second case, you have defined the variables q and w as following</p>
<blockquote>
<p><code>q=w=np.zeros(3)</code></p>
</blockquote>
<p>In this case, what ever changes you make in <code>q</code> they will be applied to <code>w</code> because the... | python|arrays|numpy | 1 |
377,994 | 70,621,448 | Using groupby() with appending additional rows | <p>With the following csv input file</p>
<pre><code>ID,Name,Metric,Value
0,K1,M1,200
0,K1,M2,5
1,K2,M1,1
1,K2,M2,10
2,K2,M1,500
2,K2,M2,8
</code></pre>
<p>This code, groups the rows by the name column, e.g. two groups. Then it appends the values as columns for the same Name.</p>
<pre><code>df = pd.read_csv('test.csv', ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>DataFrame.pivot</code></a> for DataFrames pe groups and then append <code>df1.columns</code> in <code>np.vstack</code>:</p>
<pre><code>my_array = []
for name, df_group in df.gro... | python-3.x|pandas|dataframe | 3 |
377,995 | 70,609,655 | Multiplie Specific row with specific condition pandas | <p>I want to multiple a column in pandas and replace the old value by the value computed.</p>
<p>Example :</p>
<pre><code>EURUSD = 2
print(df)
Instrument Price,
1 BTC/EUR 40000
2 ETH/EUR 3000
3 SOL/USD 3200
4 ADA/EUR 2.2
5 ... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a>:</p>
<pre><code>In [16... | python|pandas|conditional-statements | 1 |
377,996 | 70,435,621 | Sub setting dataframe | <p>I have <code>Dataframe</code> with three columns as
<code>Date, Id, pages</code>. In <code>pages</code> values are according to time of visit. So I want customers who visit <code>page A</code> after <code>page B</code> on the same date.</p>
<p>As in the image below <code>ID 2</code> visit <code>page A</code> after <... | <p>Try:</p>
<pre><code>A_after_B = lambda x: x.eq('B').idxmax() < x.eq('A').idxmax()
m1 = df['Page'].isin(['A', 'B'])
m2 = df.groupby(['ID', 'Date'])['Page'].transform(A_after_B)
out = df.loc[m1 & m2]
print(out)
# Output:
ID Date Page
5 2 02-Nov B
6 2 02-Nov A
</code></pre>
<p>Setup:</p>
<pr... | python|python-3.x|pandas|dataframe | 0 |
377,997 | 70,687,594 | Multiplication between different rows of a dataframe | <p>I have several dataframes looking like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">time_hr</th>
<th style="text-align: left;">cell_hour</th>
<th style="text-align: left;">id</th>
<th style="text-align: left;">attitude</th>
<th style="text-align: left;"... | <p>It sounds like a cartesian product to me:</p>
<pre class="lang-py prettyprint-override"><code>from io import StringIO
#sample data reading
data1 = """
time_hr cell_hour id attitude hour
0.028611 xxx 1 Cruise 1.0
0.028333 xxx 4 Cruise 1.0
0.004722 xxx 16 Cruise 1.0
""&q... | pandas|dataframe|numpy|row | 0 |
377,998 | 70,660,033 | panda looping large size file how to get the amount of chunks? | <p>I'm using pandas to read a large size file,the file size is 11 GB</p>
<pre><code>chunksize=100000
for df_ia in pd.read_csv(file, chunksize=n,
iterator=True, low_memory=False):
</code></pre>
<p>My question is how to get the amount of the all the chunks,now what I can do is setting a index and... | <p>You can use the <code>enumerate</code> function like:</p>
<pre><code>for i, df_ia in enumerate(pd.read_csv(file, chunksize=5,
iterator=True, low_memory=False)):
</code></pre>
<p>Then after you finish iteration, the value of <code>i</code> will be <code>len(number_of_dataframes)-... | python|pandas|dataframe|numpy|large-files | 0 |
377,999 | 70,726,110 | Cumulative concatenation from last to first within a group in Python | <p>I'm looking to concatenate in cumulative manner values within a column in a data frame. However, the column will be partitioned/grouped by the values in another column.</p>
<p>I have been able to do this from the top down with the following code:</p>
<pre><code>df['Col_to_cum_Concat']=[y.CUM_CONCAT_TOP.tolist()[:z+1... | <p>You can group by <code>Group_Col</code> and for each group, reverse <code>Text</code> and use <code>cumsum</code> to concatenate accumulatively:</p>
<pre><code>df['Col_to_cum_Concat'] = df.Text.groupby(df.Group_Col).transform(lambda g: g[::-1].add(' ').cumsum()).str.rstrip()
df
Group_Col Text Col_to_cum_Concat
0... | python|pandas|dataframe | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.