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
362,100
53,771,065
Less Memory-intense way of copying tables & renaming columns in sqlite/pandas
<p>I have found a very nice way to:</p> <ol> <li>read a table from a sql database</li> <li>rename the columns with a dict (read from a yaml file) </li> <li>rewrite the table to another database</li> </ol> <p>The only problem is, that as the table becomes bigger(10col x several million rows), reading the table into a ...
<p>To elaborate on my comments...</p> <p>If you have a table in foo.db and want to copy that table's data to a new table in bar.db with different column names:</p> <pre><code>$ sqlite3 foo.db sqlite&gt; ATTACH 'bar.db' AS bar; sqlite&gt; CREATE TABLE bar.newtable(newcolumn1, newcolumn2); sqlite&gt; INSERT INTO bar.ne...
python|pandas|sqlite
2
362,101
53,504,745
how to remove attribure error on using iloc function for dataframe?
<p>I am trying to set 0 value for the column 'fare_amount' based on specified conditions in iloc, ended up getting attribute error. 'dataset' is Dataframe object.</p> <p>AttributeError: 'int' object has no attribute 'loc'</p> <pre><code>dataset = dataset.loc[dataset['fare_amount'] != 0 &amp; dataset['passenger_count'...
<p>Check what you are doing,</p> <pre><code>dataset = dataset.loc[dataset['fare_amount'] != 0 &amp; dataset['passenger_count'] == 0, 'fare_amount'] = 0 </code></pre> <p>You are writing dataset <strong>=</strong> ... <strong>=</strong> 0.So you are puting '<strong>=</strong>' two times. You should do this:</p> <pre><...
python|pandas|data-science
1
362,102
53,435,711
Average of the two inputs in multi-input deep learning model
<p>I want to create a multi-input deep learning model. The model takes two inputs (images) from different datasets and calculates the average of them. See the code:</p> <pre class="lang-py prettyprint-override"><code>input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input...
<p>The error is raised because your model has two inputs but in this line:</p> <pre><code>yield X1i[0], X2i[0] </code></pre> <p>The generator would return a tuple of two arrays. In <code>fit_generator</code> the first one would be interpreted as the model input and the second one would be interpreted as the model out...
tensorflow|machine-learning|keras|neural-network|deep-learning
1
362,103
53,436,055
Aggregate dataframe rows into a dictionary
<p>I have a pandas DataFrame object where each row represents one object in an image. </p> <p>One example of a possible row would be:</p> <pre><code>{'img_filename': 'img1.txt', 'img_size':'20', 'obj_size':'5', 'obj_type':'car'} </code></pre> <p>I want to aggregate all the objects that belong to the same image, and ...
<p>One way using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>to_dict</code></a></p> <pre><code>df2 = df1.groupby('img_filename')['obj_size','obj_type'].apply(lambda x: x.to_dict('records')) df2 = df2.reset_index(name='obj') # Assuming ...
python|pandas
1
362,104
53,791,801
Get the position of a substring in a column of DataFrame using regex
<p>I'd like to break up a string into <strong>Pandas DataFrame</strong> columns using a regex. </p> <p>Sample csv data [<strong>Updated</strong>]: </p> <pre><code>Data;Code;Temp;.... 12 364 OPR 4 67474;;33;... 893 73 GDP hdj 747;;34;... hr 777 hr9 GDP;;30;... 463 7g 448 OPR;;28;... </code></pre> <p>Desired situati...
<p>I am fairly new to python so someone might be able to comment if this is not a good approach. My line of thinking was to take the input and process it line by line. drop the trailing semi colon as you dont have it in your output. then using regex split the line by a space char only if its followed by either OPR or G...
python|python-3.x|pandas
2
362,105
17,590,950
Matplotlib fill blank image line by line, when I receive data from socket
<p>I have data coming from a socket. I want in the beginning to create an empty image, then update this image every time I receive the data from the socket. The problem is when I receive a huge amount of data (1024) and I want to display it, it takes time and hangs. Is it possible to speed it up little bit? I think th...
<p>It's unnecessary to create a new image every time new data arrives from the socket. You can create a single image on initialisation, then update the values in the array from the data you are receiving:</p> <pre><code> # on initialisation self.im = imshow(np.zeros((x,y)),cmap='gray',interpolation='nearest', ...
python|numpy|matplotlib
1
362,106
17,567,557
Python not returning all values to system but replacing it with ...
<p>I have a piece of python code which returns values to the system after the input arguments have been defined. I am having problems with the number of samples that have been returned to the system. </p> <p>I have the following bit of code:</p> <pre><code>import sys import numpy.random def Weibull_Random(alpha,beta...
<p>This is not related to the system, but caused by the formatting employed by <code>numpy</code>. The easiest fix is to modify your script to invoke <code>numpy.set_printoptions</code> like:</p> <pre><code>if __name__ == '__main__': alpha = float(sys.argv[1]) beta = float(sys.argv[2]) Iterations = float(...
python|windows-7|numpy|scipy|system
1
362,107
17,556,786
Index contains multiples value dataframe pivots
<p>I currently have data in the following format in a dataframe:</p> <pre><code> metric__name sample sample_date 0 ga:visitBounceRate 100 2012-11-13 1 ga:uniquePageviews 20 2012-11-13 2 ga:newVisits 19 2012-11-13 3 ga:visits 20 2012-11-13 4 ga:percentNewVi...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tools.pivot.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> (which doesn't throw this exception):</p> <pre><code>In [11]: df.pivot_table('sample', 'sample_date', 'metric__name') Out[11]: metric__name ga:newVisits ga:pageviews ...
python|pandas|pivot|dataframe
3
362,108
17,542,524
Pandas DataFrames in reportlab
<p>I have a DataFrame, and want to output it to a pdf. I'm currently trying to use ReportLab for this, but it won't seem to work. I get an error here:</p> <pre><code> mytable = Table(make_pivot_table(data, pivot_cols, column_order, 'criterion')) </code></pre> <p><code>make_pivot_table</code> just returns a piv...
<p>Py</p> <p>Hallo, </p> <p>I'm also needing to print as .pdf some Pandas DataFrame to arrange reports. I tried ReportLab directly with df and had an "AttributeError: 'DataFrame' object has no attribute 'split'." I tried with df.values() and had "TypeError: 'numpy.ndarray' object is not callable".</p> <p>When close ...
python|python-2.7|pandas|reportlab
3
362,109
17,428,621
Python: Differentiating between row and column vectors
<p>Is there a good way of differentiating between row and column vectors in python? So far I'm using numpy and scipy and what I see so far is that If I was to give one a vector, say</p> <pre><code>from numpy import * Vector = array([1,2,3]) </code></pre> <p>they wouldn't be able to say weather I mean a row or a colum...
<p>You can make the distinction explicit by adding another dimension to the array.</p> <pre><code>&gt;&gt;&gt; a = np.array([1, 2, 3]) &gt;&gt;&gt; a array([1, 2, 3]) &gt;&gt;&gt; a.transpose() array([1, 2, 3]) &gt;&gt;&gt; a.dot(a.transpose()) 14 </code></pre> <p>Now force it to be a column vector:</p> <pre><code>&...
python|arrays|numpy|vector|scipy
94
362,110
19,905,927
Delete Pandas DataFrame row where column value is < 0
<p>I already read the answers in <a href="https://stackoverflow.com/questions/18172851/deleting-dataframe-row-in-pandas-based-on-column-value">this</a> thread but it doesn't answer my exact problem. My DataFrame looks like this</p> <pre><code> Lady in the Water The Night Listener Just My Luck C...
<pre><code>df = df[df['Correlation'] &gt;= 0] </code></pre>
python|pandas
27
362,111
20,072,030
Filter an array in Python with 2 conditions
<p>How to filter an array A according to two conditions ?</p> <pre><code>A = array([1, 2.3, 4.3, 10, 23, 42, 23, 12, 1, 1]) B = array([1, 7, 21, 5, 9, 12, 14, 22, 12, 0]) print A[(B &lt; 13)] # here we get all items A[i] with i such that B[i] &lt; 13 print A[(B &gt; 5) and (B &lt; 13)] # here it doesn't work ...
<p>You should use the <em>bitwise</em> (thanks @askewchan) version of the operator <code>and</code> which is <code>&amp;</code>.</p> <p>i.e.</p> <pre><code> print A[(B &gt; 5) &amp; (B &lt; 13)] </code></pre>
python|arrays|list|numpy
5
362,112
19,957,755
Pandas Handling Missing Values when going from Data Frame to Pivot Table
<p>Given the following pandas data frame:</p> <pre><code>df = pd.DataFrame({'A': ['foo' ] * 3 + ['bar'], 'B': ['w','x']*2, 'C': ['y', 'z', 'a','a'], 'D': rand.randn(4), }) print df.to_string() """ A B C D 0 foo w y 0.06075020 1 foo x z 0.21112476 2 foo w...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.reindex.html" rel="noreferrer">reindex()</a> method:</p> <pre><code>&gt;&gt;&gt; df1 = pd.pivot_table(df, rows=['A','B'], cols='C', aggfunc=np.sum) &gt;&gt;&gt; df1 D C a y ...
python|pandas|pivot-table
7
362,113
20,293,614
Divide one numpy array by another only where both arrays are non-zero
<p>What's the easiest, most Pythonic way to divide one numpy array by another (of the same shape, element-wise) only where both arrays are non-zero?</p> <p>Where either the divisor or dividend is zero, the corresponding element in the output array should be zero. (This is the default output when the divisor is zero, ...
<p>This still tries to divide by 0, but it gives the correct result:</p> <pre><code>np.where(b==0, 0, a/b) </code></pre> <p>To avoid doing the divide-by-zero, you can do:</p> <pre><code>m = b!=0 c = np.zeros_like(a) np.place(c, m, a[m]/b[m]) </code></pre>
numpy
5
362,114
20,200,353
Reading data into numpy array from text file
<p>I have a file with some metadata, and then some actual data consisting of 2 columns with headings. Do I need to separate the two types of data before using genfromtxt in numpy? Or can I somehow split the data maybe? What about placing the file pointer to the end of the line just above the headers, and then trying ge...
<p>If you don't want the first <code>n</code> rows, try (if there is no missing data):</p> <pre><code>data = numpy.loadtxt(yourFileName,skiprows=n) </code></pre> <p>or (if there are missing data):</p> <pre><code>data = numpy.genfromtxt(yourFileName,skiprows=n) </code></pre> <p>If you then want to parse the head...
python|arrays|file-io|numpy|genfromtxt
45
362,115
6,551,666
Numpy Index values for each element in 3D array
<p>I have a 3D array created using the numpy mgrid command so that each element has a certain value and the indexes retain the spatial information. For example, if one summed over the z-axis (3rd dimension) then the the resultant 2D array could be used in matplotlib with the function imshow() to obtain an image with di...
<p>I'm not exactly clear on your meaning, but if you are looking for 3d arrays that contain the indices x, y, and z, then the following may suit your needs; assume your data is held in a 3D array called "abc":</p> <pre><code>import numpy as nm x,y,z = nm.mgrid[[slice(dm) for dm in abc.shape]] </code></pre>
python|arrays|numpy|indexing|element
1
362,116
6,702,288
Scientific Problems for Python Coding Dojos
<p>We are organizing a Coding Dojo of scientific applications in the Brazilian Python Community, the main goals are: improve our skills in Numpy (and some others scientific libs); improve the use of TDD in this kind of applications; and better understand of limitations of these APIs.</p> <p>I'm looking for problems th...
<p><a href="http://software-carpentry.org/4_0/" rel="nofollow">Software Carpentry</a>, a set of educational materials for scientific computing, is mostly in Python and has a number of well thought out example problems.</p>
python|numpy|tdd|scientific-computing
3
362,117
15,817,498
Performing Data Analysis on Pivoted DataFrame in Pandas
<p>I'm loading data from a database, and creating a DataFrame,</p> <pre><code>db_resultset = self.result.fetchall() df = DataFrame(db_resultset) df.columns = self.result.keys() pivoted_data = df.pivot(index='id', columns='item') data = id item val 1 A 10 2 A 25 1 B 12 1...
<p>Not sure if it is reading the rows into the data frame correctly. Try:</p> <pre><code>df = pd.DataFrame.from_records(db_curr.fetchall(), index=["id", "item"], columns=[col_desc[0] for col_desc in db_curr.description]) df = df.unstack() </code></pre> <p>...
python|database|pandas|dataframe
0
362,118
15,778,886
how does boxplot in pandas/python work?
<p>I found this link and I'm trying to understand how boxplot works.</p> <p><a href="http://pandas.pydata.org/pandas-docs/dev/visualization.html#box-plotting" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/visualization.html#box-plotting</a></p> <pre><code>df = DataFrame(np.random.rand(10,5)) plt.figure(); ...
<p>Your <code>DataFrame</code> (actual numbers may differ because of <code>rand</code>):</p> <pre><code>In [13]: df = DataFrame(np.random.rand(10, 5)) In [14]: df Out[14]: 0 1 2 3 4 0 0.199953 0.261683 0.582105 0.969489 0.351161 1 0.424425 0.901810 0.942510 0.985630 ...
python|pandas|boxplot
5
362,119
15,884,440
numpy tostring equivalent to numpy fromstring
<p>Numpy has a neat function <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html" rel="nofollow"><code>numpy.fromstring</code></a>.</p> <p>It also seems to have a neat function <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.chararray.tostring.html" rel="nofollow"><cod...
<p>I found what I was looking for here <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html" rel="nofollow"><code>numpy.ndarray.tofile</code></a></p>
python|numpy
2
362,120
15,767,435
Python implementation of statistical Sweep operator
<p>I am learning some techniques for doing statistics with missing data from a book (<strong>Statistical Analysis with Missing Data</strong> by Little and Rubin). One particularly useful function for working with monotone non-response data is the <em>Sweep Operator</em> (details on page 148-151). I know that the R mod...
<pre><code>def sweep(g, k): g = np.asarray(g) n = g.shape[0] if g.shape != (n, n): raise ValueError('Not a square array') if not np.allclose(g - g.T, 0): raise ValueError('Not a symmetrical array') if k &gt;= n: raise ValueError('Not a valid row number') # Fill with the ...
python|numpy|statistics
6
362,121
12,253,447
Converting a list of ints, tuples into an numpy array
<p>I have a list of [float, (float,float,float..) ] ... Which is basically an n-dimensional point along with a fitness value for each point. For eg. </p> <pre><code>4.3, (2,3,4) 3.2, (1,3,5) . . 48.2, (23,1,32) </code></pre> <p>I wish to randomly sample one point based upon the fitness values. I decided the best way...
<p>The following should work:</p> <pre><code>A = np.array([tuple(i) for i in initial_list],dtype=[('fitness',float),('point',(float,3))]) </code></pre> <p>with <code>initial_list = [[4.3, (2, 3, 4)], [3.2, (1, 3, 5)], ...]</code>. Note that we need to transform each item of <code>initial_list</code> into a tuple for ...
python|arrays|list|numpy|tuples
1
362,122
12,497,545
Using NumPy in Pyramid
<p>I'd like to perform some array calculations using NumPy for a view callable in Pyramid. The array I'm using is quite large (3500x3500), so I'm wondering where the best place to load it is for repeated use.</p> <p>Right now my application is a single page and I am using a single view callable.</p> <p>The array wil...
<p>If the array is something that can be shared between threads then you can store it in the registry at application startup (<code>config.registry['my_big_array'] = ??</code>). If it cannot be shared then I'd suggest using a queuing system with workers that can always have the data loaded, probably in another process....
python|numpy|pyramid
3
362,123
12,358,360
Order columns of a pandas dataframe according to the values in a row
<p>How do I order columns according to the values of the last row? In the example below, my final dataframe should have columns in the following order: 'ddd' 'aaa' 'ppp' 'fff'.</p> <pre><code>&gt;&gt;&gt; df = DataFrame(np.random.randn(10, 4), columns=['ddd', 'fff', 'aaa', 'ppp']) &gt;&gt;&gt; df ddd fff...
<p>[updated to simplify]</p> <p>tl;dr:</p> <pre><code>In [29]: new_columns = df.columns[df.ix[df.last_valid_index()].argsort()] In [30]: df[new_columns] Out[30]: aaa ppp fff ddd 0 0.328281 0.375458 1.188905 0.503059 1 0.305457 0.186163 0.077681 -0.543215 2 0.684265 0.681724 0.210...
python|sorting|pandas
31
362,124
71,872,431
How to find rows from df where all elements from search list exists all?
<p>I have a df which contains columns product id and product names. The product names column is tokenized and in list format. For example:</p> <pre><code>Product id Product name 1 [land, cruiser] 1 [land, cruiser] 1 [land, cruiser, toyota] 1 [land, cruiser] 1 [lan...
<p>You can use <code>set</code> operations and a list comprehension.</p> <p>Assuming this input:</p> <pre><code>df = pd.DataFrame({'Product id': [1, 1, 1, 1, 1], 'Product name': [['land', 'cruiser'], ['land', 'cruiser'], ['land',...
python|pandas|sorting
0
362,125
72,051,166
Indexing dataframes with date index
<p>I previously asked on <a href="https://stackoverflow.com/questions/71859494/problems-indexing-dictionary-with-date-index">this question</a> how to properly get the item in the &quot;PM&quot; column of the produced dataframe that has the index given by date_index. This solution provided in the answers worked:</p> <pr...
<p>Add <code>.squeeze()</code> to &quot;squeeze out&quot; the lone value:</p> <pre><code>&gt;&gt;&gt; dct['Station_1']['PM'].loc[date_index, &quot;PM&quot;].squeeze 50 </code></pre>
python|pandas|indexing
1
362,126
72,057,602
How to mask [PAD] and [SEP] tokens to prevent their prediction and loss calculation for NER task on BERT models?
<p>I am trying to fine-tune BERT model for NER tagging task using <a href="https://github.com/tensorflow/models/tree/be0b836562d34ecd703d5d9e9e24c36624aeb3ac/official/nlp" rel="nofollow noreferrer">tensorflow official nlp toolkit</a>. I found there's already a <a href="https://github.com/tensorflow/models/blob/871c4e0a...
<p>Have you found a solution? I'm doing the same task and I found the PADDING TOKEN is dominating the prediction. Passing in an attention mask didn't do anything so I manually chopped down the sequences to just 100 tokens long, and it improves.</p>
tensorflow|bert-language-model|named-entity-recognition|tensorflow-model-garden
0
362,127
71,968,213
Create copy of `pd.Index` with new values
<h3>Example: <code>pd.DatetimeIndex</code></h3> <p>Let's say I have a <code>pd.DatetimeIndex</code>, for example</p> <pre><code>di = pd.date_range(start='2000-01-01', periods=3, freq='B') # di DatetimeIndex(['2000-01-03', '2000-01-04', '2000-01-05'], dtype='datetime64[ns]', freq='B') </code></pre> <p>I now want a new ...
<p>What about using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DatetimeIndex.html" rel="nofollow noreferrer"><code>pandas.DatetimeIndex</code></a> directly?</p> <pre><code>new_di = pd.DatetimeIndex(['2000-01-10', '2000-01-11'], freq='B') </code></pre> <p>or, to match <code>di</code> programmatically:<...
python|pandas|indexing|reindex
0
362,128
71,953,622
manage couple of string slices in Pandas, reverting the order
<p>I have to manage some strange strings: my aim is taking each couple of slices and adding to the string the &quot;mirror&quot; version of the slice (please notice that it's not a &quot;reverse&quot; of the string, e.g. IB is maintained as IB, not BI).</p> <p>I was thinking about something better then splitting-substr...
<p>Another solution, not using regex:</p> <pre class="lang-py prettyprint-override"><code>data_raw[&quot;name&quot;] = ( data_raw[&quot;name&quot;] .str.split(&quot; - &quot;) .apply( lambda x: &quot; - &quot;.join( f&quot;{a} - {b} - {b} - {a}&quot; for a, b in zip(x[::2], x[1::2]) ...
python|pandas|string
0
362,129
71,899,199
how to use pandas to standardlize data while groupby the result by another columns
<p>The goal is to group the data by columns <code>type</code>, then within the groups identified, use Min-Max standardization to process the column called <code>score</code> and assign to a new column called <em>normalization_score</em></p> <pre><code>import pandas as pd import numpy as np from sklearn.preprocessing im...
<p>You can use <code>minmax_scale</code>:</p> <pre><code>from sklearn.preprocessing import minmax_scale df['norm_score'] = df.groupby('type')['score'].transform(minmax_scale) print(df) # Output type score norm_score 0 a 0.848994 0.866129 1 a 0.876353 0.895023 2 a 0.295306 0.281368 3 ...
python|arrays|pandas|dataframe|numpy
1
362,130
71,969,513
Regex for Hashtag but only return true if 5 or more hashtags are in the String
<p>There's a few different ways of using Regex for hashtags that I've been able to find:</p> <ul> <li><code>(#[a-z0-9_]+)</code></li> <li><code>(#+[a-zA-Z0-9(_)]{1,})</code></li> </ul> <p>I have some data where there might be too many hashtags or @ symbols present. Really simply: if I had more than 5 hashtags present i...
<p>You can try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html" rel="nofollow noreferrer"><code>pandas.Series.str.count</code></a> to to count occurrences of pattern in each string of the Series.</p> <pre class="lang-py prettyprint-override"><code>out = df[df['col'].str....
python|pandas|count
2
362,131
72,099,979
How to square-form a dataframe with pair index
<p>I have a JSON data like:</p> <pre class="lang-json prettyprint-override"><code>a={('A', 'B'): 0.8333333333333334, ('A', 'C'): 0.5, ('B', 'C'): 0.625} </code></pre> <p>I need to draw a heatmap based on that data set. but the dataframe I obtained by</p> <pre class="lang-py prettyprint-override"><code>df=pd.DataFrame(a...
<p>Assuming:</p> <pre><code>a = {('A', 'B'): 0.8333333333333334, ('A', 'C'): 0.5, ('B', 'C'): 0.625} </code></pre> <p>you can convert to Series and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> to get a DataFrame:</p> <pre><code>df =...
python|pandas|dataframe
3
362,132
72,079,109
How to drop row with bracket in Pandas
<p>I would like to drop the <code>[]</code> for a given <code>df</code></p> <pre><code>df=pd.DataFrame(dict(a=[1,2,4,[],5])) </code></pre> <p>Such that the expected output will be</p> <pre><code> a 0 1 1 2 2 4 3 5 </code></pre> <p>Edit:</p> <p>or to make thing more interesting, what if we have two columns and som...
<p>One way is to get the string repr and filter:</p> <pre class="lang-py prettyprint-override"><code>df = df[df['a'].map(repr)!='[]'] </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code> a 0 1 1 2 2 4 4 5 </code></pre> <p>For multiple columns, we could <code>apply</code> the above:</p> <p...
python|pandas
2
362,133
71,929,200
Use apply lambda with if else conditional without computing the condition twice
<p>Is there a way to apply the lambda statement without having to compute the <code>x.split(' ')[0]</code> twice? I know it can be done using a function i.e. <code>.apply(lambda x: pre_dir(x)</code> and take care of the logic there, but wondering if it can be done in a one-liner.</p> <pre><code>address.insert(6, 'PRE_...
<p>You could use <code>where</code> instead of <code>apply</code>. In other words, replace</p> <pre><code>address['STREETNAME'].apply(lambda x: x.split(' ')[0] if x.split(' ')[0] in ['N', 'S', 'E', 'W'] else '') </code></pre> <p>by</p> <pre><code>address['STREETNAME'].str.split(' ').str[0].where(lambda x: x.isin(['N', ...
python-3.x|pandas|if-statement|lambda|apply
1
362,134
71,914,976
Python Pandas Filling missing values in dataframe column with 'prefix' + respective Index numbers
<p>I want to fill missing values from object column to be replaced with 'any_fixed_prefix' + '_' + 'corresponding index'.</p> <p>Dataframe look like:</p> <p><a href="https://i.stack.imgur.com/tk6B7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tk6B7.png" alt="enter image description here" /></a></p...
<p>If you only want to fill NaN values in <code>col1</code>, you could use <code>fillna</code>:</p> <pre><code>df['col1'] = df['col1'].fillna('PRE_' + df.index.to_series().astype(str)) </code></pre> <p>If you want to fill NaN values in all object dtype columns, you could use <code>mask</code> on axis to fill in with th...
python|python-3.x|pandas|dataframe|fillna
3
362,135
72,010,029
Excel Sumproduct in Pandas
<p>I have a df:</p> <pre><code>Type price stock a 2 2 b 4 1 b 3 3 a 1 2 a 3 1 </code></pre> <p>The result I would like to get is:</p> <pre><code>Type price*stock a 2*2+1*2+3*1 = 9 b 4*1+3*3 = 13 </code></pre> <p>I can easily do it in Excel, but how...
<p>First multiple columns and then aggregate <code>sum</code> for improve performance:</p> <pre><code>df1 = df.price.mul(df.stock).groupby(df.Type).sum().reset_index(name='price*stock') print (df1) Type price*stock 0 a 9 1 b 13 </code></pre> <p>Another idea is first crete column with multi...
excel|pandas|group-by|sumproduct
3
362,136
71,891,011
Python pandas - grouping and plotting
<p>In <code>df1</code> I have columns for Line, Generation, ID, and Sex.</p> <p>I want to count matching occurrences in <code>df2</code> of the remaining columns for each row.</p> <p>The desired result would look like:</p> <ul> <li><p>Line A, Generation 2020A, has a total of <code>1</code> row for row <code>['A','A','A...
<p>You can use <code>merge</code> and then do <code>value_counts</code> to achieve this.</p> <pre><code>import pandas as pd df1 = pd.DataFrame([['A','2020A', 'A', 'A', 'A', 'A'], ['B','2020B', 'A', 'C', 'T', 'G'],['B','2020B', 'A', 'C', 'T', 'G']], columns= ['Line','Generation','SNP-1'...
python|pandas|dataframe
2
362,137
72,007,003
Easier way of deleting rows in pandas dataframe based on condition from another dataframe
<p>Suppose I have two dataframes</p> <pre><code>df1 = pd.DataFrame({&quot;A&quot; : [1,1,2,5], &quot;B&quot; : [1,1,4,5], &quot;C&quot; : [&quot;Adam&quot;,&quot;Bella&quot;,&quot;Charlie&quot;,&quot;Dan&quot;]}) df2 = pd.DataFrame({&quot;A&quot; : [1,1,3,5], &quot;B&quot; : [1,3...
<p>You can <code>left-merge</code> with the <code>indicator</code> parameter to flag the rows that match; then <code>query</code> to filter the rows that come only from <code>df1</code>:</p> <pre><code>out = df1.merge(df2, how='left', indicator=True).query('_merge==&quot;left_only&quot;').drop(columns=['_merge']) </cod...
python|pandas|dataframe|iteration
1
362,138
71,852,768
Best way to execute multiple lines of pandas in parallel? (Speed up)
<p>Basically, I am performing simple operation and updating 100 columns of my dataframe of size (550 rows and 2700 columns).</p> <p>I am updating 100 columns like this:</p> <pre><code>df[&quot;col1&quot;] = df[&quot;static&quot;]-df[&quot;col1&quot;])/df[&quot;col1&quot;]*100 df[&quot;col2&quot;] = (df[&quot;static&quo...
<p>You can select all columns and subtract with right side by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rsub.html" rel="nofollow noreferrer"><code>DataFrame.rsub</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.div.html" rel="n...
python|pandas
2
362,139
72,062,475
Got Nan while mapping the values in dataframe
<pre><code>df['gender'] = df['gender'].map({&quot;2&quot;: &quot;man&quot;, &quot;1&quot;: &quot;woman&quot;}) </code></pre> <p>Got <code>NaN</code> instead of man&amp;woman</p> <p>What is wrong?</p>
<p>I think the type of gender is int, so this would fix your problem:</p> <pre><code>import pandas as pd df=pd.DataFrame() df[&quot;gender&quot;]=[1,2,1,2,2,1] df['gender'] = df['gender'].map({2: &quot;man&quot;, 1: &quot;woman&quot;}) print(df) </code></pre> <p>The output:</p> <pre><code> gender 0 woman 1 man 2 ...
python|pandas|data-science
0
362,140
71,974,756
Python: searching way to remove duplicates from list of pandas dataframes?
<p>I have some list full of pandas dataframes. Is their a way to remove duplicates from it. Here some example code:</p> <pre><code>import pandas as pd import numpy as np if __name__ == '__main__': data1 = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']} df1 = pd.DataFrame.from_dict(data1, orient='in...
<p>Try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.equals.html" rel="nofollow noreferrer"><code>df.equals()</code></a>:</p> <pre class="lang-py prettyprint-override"><code>out = [] while l_input: d = l_input.pop() if any(d.equals(df) for df in l_input): continue ...
python|pandas|list|dataframe
2
362,141
71,790,727
Get displayed precision of floating point digits in pandas
<p>I have a dataframe of floating point numbers, and I want to work with what I intuitively see to be their precision, or number of digits past zero:</p> <pre><code>dd = pd.DataFrame({'x':[12.123456,10.12345,9.1234]}) dd['digits'] = dd['x'].apply(lambda num: num - int(num)) dd['target'] = [6, 5, 4] </code></pre> <div c...
<p>Here is another way to do it:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({&quot;x&quot;: [12.123456, 10.12345, 9.1234]}) df[&quot;precision&quot;] = df[&quot;x&quot;].apply( lambda x: [i for i in range(pd.options.display.precision + 1) if x == round(x, i)][0] ) p...
python|pandas|numpy|floating-point
0
362,142
71,805,995
Identify values within threshold of others in group in pandas DataFrame
<p>So my question is how to get values of a column 'accuracy' are in + -1 of each other with respect to 'vin' column. if we get +-1 value than minimum 2 values of a particular 'vin' should be there and if it is less than 2 values then it will be false.</p> <p>Below is my Dataframe:</p> <p>import pandas as pd</p> <pre><...
<p>Assuming the data is sorted, you can compute a diff per group, check that the diff is ≤ 1, then use this mask and it's shift to feed to <code>numpy.where</code>:</p> <pre><code># if not sorted # df = df.sort_values(by=['vin', 'accuracy']) mask = df.groupby('vin')['accuracy'].diff().le(1) df['Result'] = np.where(mas...
python|pandas|dataframe|numpy|pandas-groupby
1
362,143
71,928,597
Pandas: Restucture a dataframe to column values
<p>I have the following dataframe where the cities are columns and ages are the values:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>City1</th> <th>City2</th> <th>City3</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>14</td> <td>61</td> </tr> <tr> <td>51</td> <td>73</td> <td>35</td> </tr...
<p>Try this, using <code>pd.cut</code>:</p> <pre><code>dfc = pd.cut(df.rename_axis('Cities', axis=1).stack(), bins=[-np.inf,20,40,60,np.inf], labels='0-20 20-40 40-60 60-80'.split(' ')).reset_index() pd.crosstab(dfc['Cities'], dfc[0]).reset_index() </code></pre> <p>Output:</p> <pre><code>0 ...
python|pandas|dataframe
5
362,144
71,866,045
Google Translating a pandas dataframe column
<p>I would like to translate a column entitled TranslatedText within my pandas data-frame using the google translate package, where it detects the language and converts it to english. I have tried the code below. Loading and encoding the file work correctly however I keep receiving the following error at the translati...
<p>The code seems incomplete</p> <ol> <li>df is not defined</li> <li>pandas module is not imported</li> </ol> <p>I tested this same code , by importing pandas module and a sample dictionary and found that it is working.</p> <pre class="lang-py prettyprint-override"><code>import googletrans from googletrans import Trans...
python|pandas|dataframe|csv|google-translate
0
362,145
71,916,899
How to add multiple layers to an RNN module for sentiment analysis? Pytorch
<p>I am trying to create a sentiment analysis model with Pytorch (newbie)</p> <pre><code>import torch.nn as nn class RNN(nn.Module): def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim, dropout): super().__init__() #to call the functions in the superclass self.embedding = nn.Embedding(input_di...
<p>You were very close, just change your forward call to:</p> <pre><code>import torch.nn.functional as F class model_RNN(nn.Module): def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim, dropout): super().__init__() #to call the functions in the superclass self.embedding = nn.Embedding(input_dim...
machine-learning|pytorch|sentiment-analysis
0
362,146
71,888,913
Clickable hyperlink on Pandas Dataframe and pycharm
<p>I have a code that opens a csv file that has playlist and url links to music. When the frame opens on a tkinter window while using pandas dataframe the url hyperlinks are not clickable.. I have tried doing the following from this <a href="https://stackoverflow.com/questions/50209206/clickable-link-in-pandas-datafram...
<p>If you're using <strong>Tkinter</strong> to create a desktop app, you'll need a way to send a hyperlink to your web browser. Have you tried this example that uses the web browser package?</p> <p><a href="https://www.tutorialspoint.com/how-to-create-a-hyperlink-with-a-label-in-tkinter#:%7E:text=In%20order%20to%20add...
python|pandas|tkinter|hyperlink
0
362,147
72,005,807
How to record the results from Tensorflow to CSV file
<p>I have a CNN model running on tensorflow and would like to save the accuracy, loss, f1, precision and recall values as , i also have plots and confusion matrix (can you save these plots to csv?)i would like to save. how can i save this data with each model run to a csv or text file?</p>
<p>Try using <code>tf.keras.callbacks.CSVLogger</code>:</p> <pre><code>import tensorflow as tf import pandas as pd model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(1, input_dim=40)) model.add(tf.keras.layers.Dense(1, 'sigmoid')) adam_opt = tf.keras.optimizers.Adam(0.1) model.compile(loss='bce', optimizer...
python|tensorflow|keras|conv-neural-network|tensorflow2.0
1
362,148
72,030,278
Using pandas groupby to group by a conditional across rows
<p>I have the a <strong>pandas</strong> dataframe with the following data:</p> <pre><code>date random score 2022-01-01 4324 0.12 2022-01-02 234 0.46 2022-01-03 3456 0.51 2022-01-04 12 0.52 2022-01-05 346 0.41 2022-01-06 12 0.42 2022-01-...
<p>I think <code>first()</code> could work:</p> <pre class="lang-py prettyprint-override"><code>df[df['score']&gt;0.5].groupby('date').first() </code></pre>
python|pandas|dataframe
0
362,149
71,985,665
sqlite3 OperationalError: near "m": syntax error
<pre><code>import pandas as pd import sqlite3 df = pd.read_csv('liked_songs.csv') !sqlite3 spotify.db &lt; spotify.sql connection = sqlite3.connect('spotify.db') df.columns = df.columns.str.replace(' ','_') cursor = connection.cursor() for index in df.index: sr = df.iloc[index] cursor = cursor.execute(f&quot;...
<p>You can directly use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer"><code>to_sql</code></a>:</p> <pre><code>import pandas as pd import sqlite3 df = pd.read_csv('liked_songs.csv') connection = sqlite3.connect('spotify.db') df.columns = df.columns.str.rep...
python|pandas|sqlite
0
362,150
72,103,842
pandas rounding when converting the series to int
<p>How can I round a number of decimals based on an assigned series? My sample data is like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.uniform(1,5,size=(10,1)), columns=['Results']) df['groups'] = ['A', 'B', 'C', 'D'] df['decimal'] = [1, 0, 2, 3] </code></pre> <p>This produ...
<p>You can pass a dict-like object to <code>DataFrame.round</code> to set different precision levels for different columns. So you need to transpose a single column DataFrame (constructed from <code>Results</code> column) twice:</p> <pre class="lang-py prettyprint-override"><code>df['Results'] = df[['Results']].T.round...
python|pandas|rounding
1
362,151
71,810,496
Filter dataframe using startswith twice
<p>I have a dataframe that I want to filter using startswith twice. Something like this</p> <pre><code>df = df.loc[df['Col'].str.startswith('Foo', na=False) | df['Col'].str.startswith('Bar', na=False)] </code></pre> <p>But this not work, how can I fix?</p>
<p>There are two ways to solve your problem. The first is to use paranthesis:</p> <pre><code>df = df.loc[(df['Col'].str.startswith('Foo', na=False)) | (df['Col'].str.startswith('Bar', na=False))] </code></pre> <p>The second is to make use of the string startswith method, that can take any number of arguments:</p> <pre>...
python|pandas
-1
362,152
71,855,476
Plot with conditional data
<p>I have a file abc.dat having data set with column &quot;ec&quot;, &quot;ev&quot;, &quot;eig&quot;, &quot;ep&quot;. I have to plot E vs x graph. Here the values for x, E and other variables related to this are given below.</p> <p><a href="https://i.stack.imgur.com/OQENW.png" rel="nofollow noreferrer"><img src="https:...
<p>Your code has the <code>plt.plot()</code> command buried in loops, which is probably not what you are trying to do. You will need <code>x</code> to be an array the same size as <code>e</code>, and from your question it might have fewer points than you expect since it has shape (409,).</p> <p>Try this:</p> <pre><code...
python|numpy
0
362,153
71,863,080
Append two pandas DataFrame with different shapes
<p>I have two pandas DataFrame of different shapes that I am trying to append. <code>df2</code> is a subset of columns in <code>df1</code>. In the Final resultant DataFrame, I am looking for all columns in <code>df1</code> and columns from <code>df2</code>. For missing columns, the values must be <code>NaN</code>.</p> ...
<p>try</p> <pre><code>df1.append(df2) Out[2]: c0 c1 c2 c3 0 0.0 3 6 3.0 1 0.0 4 7 3.0 2 0.0 5 8 3.0 0 NaN 6 9 NaN 1 NaN 7 10 NaN 2 NaN 8 11 NaN </code></pre>
python|pandas|dataframe
1
362,154
71,896,169
How to pull excel data into a list to use python?
<p>I have a program that works perfectly in placing orders for my company for a list that I define. I want to know how I could pull the list from an excel file instead of manually typing them out each time?</p> <p>code below:</p> <pre><code>Order_List = ['0043777770','003897270','0048377270'] for eachId in Order_List:...
<p>If you want, you can also read only the first column with <code>pd.read_excel</code>. I think this might be a bit more efficient than reading the whole file.</p> <p>As I see it, you don't want repeated orders, that's why you can use <code>set()</code></p> <pre><code>import pandas as pd df = pd.read_excel(&quot;file...
python|excel|pandas|list
2
362,155
71,937,100
How to export large pandas Data Frame to excel format?
<p>I have converted binary files to NumPy array and then pandas data frame. The final shape is 217 rows × 524289 columns.</p> <p>When I tried to save it as .xlsx format:</p> <pre><code>dft.to_excel('dft.xlsx') </code></pre> <p>the below error appeared:</p> <pre><code>ValueError: This sheet is too large! Your sheet siz...
<p>Either save as .csv, or split it into 4 dataframes before saving it as .xlsx. From the error you see that the max amount of columns is 16384, so splitting into 4 smaller dataframes would work.</p>
python|excel|pandas|dataframe|binary
0
362,156
71,956,803
normalize image with opencv in c++?
<p>I have a TfLite model that takes a standardized float32 image as an input, the pixel range should convert from the [0~255] to [-1~1] I wrote a demo function but it didn't work. I couldn't set the color value back to the image; How can I set the color back to the &quot;des&quot; image? and Is there a better way to do...
<p>please do not write for loops. instead:</p> <pre><code>src.convertTo(dst, CV_32F); dst -= 127; dst /= 255; // EDIT </code></pre>
c++|tensorflow|opencv|image-processing
4
362,157
71,956,717
Fill df with empty rows based on index of other df
<p>I am trying to use df.update(), but my dfs have different sizes. Now I want to fill up the smaler df with dummy rows to match the shape the bigger df. Here's a minimal example:</p> <pre><code>import pandas as pd import numpy as np data = { &quot;Feat_A&quot;: [&quot;INVALID&quot;, &quot;INVALID&quot;, &quot;INVA...
<p>This did it:</p> <pre><code>df.update(result.set_index('Key').reindex(df.set_index('Key').index).reset_index()) </code></pre>
python-3.x|pandas
0
362,158
72,084,710
Pandas aggregate with self written function: optimisation issue
<p>The following codes does exactly what I need, however it is very slow when dealing with large number of data (up to 100 000). How could it be improved ?</p> <pre><code>df = pd.DataFrame({ &quot;session&quot;:[&quot;s1&quot;,&quot;s1&quot;,&quot;s1&quot;,&quot;s1&quot;,&quot;s2&quot;,&quot;s2&quot;,&quot;s2&q...
<p>IIUC, intialize the time column as datetime only once and use vectorial code in your function:</p> <pre><code>df['time'] = pd.to_datetime(df['time']) def func(s): return (s-s.iloc[0]).dt.total_seconds().div(60).round(2).to_list() res = df.groupby(['session']).agg( sub_session_path=(&quot;sub sessio...
python|pandas|optimization
3
362,159
71,990,375
How to remove xarray dimension after adding another without deleting the data variables
<p>I have data from ECMWF which when read into xarray looks like this</p> <pre><code>Dimensions: (time: 424, step: 12, latitude: 3, longitude: 2) Coordinates: number int64 0 * time (time) datetime64[ns] 1990-03-01T06:00:00 ... 1993-04-22T18:0... * step (step) timedelta64[ns] 01:00:00 02:0...
<p>All variables in an xarray Dataset must be indexed by named dimensions. You can use <a href="https://xarray.pydata.org/en/latest/generated/xarray.Dataset.reset_index.html" rel="nofollow noreferrer">ds.reset_index`</a> drop any labeled coordinates associated with a dimension, but this isn't what you want. You can't s...
python|numpy|python-xarray
1
362,160
72,045,344
Why pandas cannot read correctly a csv file?
<p>I want to read data from a .csv file into a pandas dataframe. I have the very simple code:</p> <pre><code>import pandas as pd file_name = &quot;C:/Users/Admin/Downloads/Results.csv&quot; df = pd.read_csv (file_name, sep=',') print(df) </code></pre> <p>The file contains one single line: the header:</p> <pre><code>P...
<ol> <li><p>You can first try to open the csv file using Microsoft Excel (or similar apps). This is to validate the file is a valid csv file.</p> </li> <li><p>Then you can try something like (assume you are using pandas 1.3.0+)</p> <p>pd.read_csv(file_name, sep=',', encoding='utf-8', encoding_errors='ignore')</p> </li>...
python|python-3.x|pandas|dataframe
1
362,161
71,896,958
How do I do a validation split on keras dataset
<p>At the moment the code is splitting the dataset in half, 50% for training and 50% for test, how could i split the data in other proportions like 80/20?</p> <pre><code>(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words) </code></pre> <p>i have added the validation_split function in the model.co...
<pre><code># Combine the data and labels and then do the split. (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words) X = np.concatenate((X_train, X_test), axis=0) y = np.concatenate((y_train, y_test), axis=0) # Split into training and testing data X_train, X_test, y_train, y_test = train_test...
python|tensorflow|machine-learning|keras
1
362,162
71,945,143
Pandas function to rename certain column values based off of a boolean condition in another column
<p>I'm trying to clean a dataset that has demographic information for my company.</p> <p>There is a text column for &quot;Race&quot; that contains the values ['White', 'Black', 'Asian', 'Two or More Races']. There is another boolean column for &quot;Hispanic or Latino&quot; that is either a 0 for no or a 1 for yes.</p>...
<p>You can select rows using</p> <pre><code>mask = (df[&quot;Hispanic or Latino&quot;] == 1) &amp; (df['Race'] != 'Two or More Races') df.loc[mask, 'Race'] = 'Hispanic/Latino' </code></pre> <hr /> <p>Tested on simple example</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'Race': ['White', 'Black', 'Asian'...
python|pandas
0
362,163
72,054,629
Python- How to Combine 2 pandas.core.frame =.dataframe with the same column name together in python
<p>So i got 2 pandas.core.frame.DataFrame like this:</p> <p>anomalies:</p> <pre><code> Sales outlet Date 2006-07-01 700 2 </code></pre> <p>and this (anomalies2):</p> <pre><code> Sales outlet Date 2011-03-01 206 1 2012-03-01 900 ...
<p>just use</p> <p>anomalies3 = pd.concat([anomalies, anomalies2])</p>
python|python-3.x|pandas|dataframe|append
0
362,164
71,940,129
shortest distance between a point and a rectangle based on numpy implementation
<h1>Goal:</h1> <p>For a point <code>a</code> and a rectangle <code>B</code>, I would like to calculate the shortest distance between these two objects.</p> <h2>Motivation</h2> <p>Because this calculation is part of the innermost loop of multiple loops, I would like to optimize this calculation as much as possible. With...
<p>I think, this is a nice implementation of the distance function:</p> <pre><code>from math import sqrt class Point: def __init__(self, x, y): self.x = x self.y = y class Rectangle: def __init__(self, center: Point, width: float, height: float): self.center = center self.width...
python|numpy|geometry|distance
0
362,165
71,949,843
Nested Data inside output needing to be expanded
<p>I have the following code</p> <pre><code>import requests import json import pandas as pd import csv import numpy from pandas.io.json import json_normalize url = 'http://URL/api_jsonrpc.php' payload = '{&quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;method&quot;: &quot;event.get&quot;, &quot;params&quot;: {&quot;outp...
<p>Building up on my comment : <code>geteventlist</code> looks like a list of list, with each nested list containing 1 dict.</p> <p>In order to build a correct list :</p> <pre><code>csvList = [] for hosts in geteventlist: try: csvList.append({ 'host': hosts['hosts'][0]['host'], 'host...
python|python-3.x|pandas
1
362,166
72,131,137
How to Improve performance of apply function for more than 5 millions rows?
<p>I have one minute OHLCV data from 2006 to 2022. There are more than 5 millions rows. From the one minute data I made 5 minute and 30 minute data like its calculated every minute the new high and low for 5 minutes data. Below is the example of the 5 minute data and the code. But It takes huge time for running. Is the...
<p>You can try utilizing a GPU, if you have one.</p> <p>I have encountered similar problems in numpy matrix and switched to CuPy (CuPu = Numpy + GPU). So I believe a similar solution exists here. Only I am not familiar with CuDF (Pandas + GPU), the syntax looks almost the same as Pandas.</p> <p>Also I believe the impro...
python|pandas|numpy|performance|vectorization
0
362,167
16,981,306
Trying to calcuate mean and std using float32 numpy arrays. Getting float64 returned
<p>[EDIT]</p> <p>Okay my test case was poorly thought out. I only tested on 1-D arrays. in which case I get a 64bit scalar returned. If I do it on 3D array, I get the 32 bit as expected.</p> <p>I am trying to calculate the mean and standard deviation of a very large numpy array (600*600*4044) and I am close to the ...
<p><strong>Note</strong>: <em>This answer applied to the original question</em></p> <p>You have to switch to 64 bit Python. According to your comments your object has size 5.7GB even with 32 bit floats. That cannot fit in 32 bit address space which is 4GB, at best.</p> <p>Once you've switched to 64 bit Python I think...
python|numpy
1
362,168
16,816,962
Using pandas group operations
<p>I'm trying to better understand pandas' group operations.</p> <p>As an example, let's say I have a dataframe which has a list of sets played in tennis matches.</p> <pre><code>tennis_sets = pd.DataFrame.from_items([ ('date', ['27/05/13', '27/05/13', '28/05/13', '28/05/13', '28/05/13', '29/05/13', '29/...
<p>To answer your question, yes there are ways to do this in pandas. There may be a more elegant solution, but here's a quick one which uses pandas groupby to perform a sum over the dataframe grouped by date:</p> <pre><code>In [13]: tennis_sets Out[13]: date player_A player_B 0 27/05/13 6 4 ...
python|pandas
1
362,169
16,830,577
How to transforme matrix to matrix containing identity matrix
<p>I want to get transformed array contains identity matrix from n*m array using numpy/scipy.</p> <pre><code>from n*m matrix array([[ a, b, c, d, e, f], [ g, h, i, j, k, l], [ m, n, o, p, q, r]]) to array([[ 1, 0, 0, a', b', c'], [ 0, 1, 0, d', e', f'], [ 0, 0, 1, g', h'...
<p>If numpy.linalg is allowed, then</p> <pre><code>import numpy as np n, m = A.shape assert n &lt; m B = np.linalg.solve(A[:, :n], A[:, n:]) C = np.hstack((np.identity(n), B)) </code></pre> <p>will do your job.</p>
python|numpy|scipy|linear-algebra
0
362,170
16,804,513
numpy - Python - Selectively import parts of the .txt file
<p>In my data.txt file, there are 2 types of lines.</p> <ol> <li><p>Normal data: 16 numbers separated by spaces with a '\n' appended at the end.</p></li> <li><p>Incomplete data: In the process of writing the data into data.txt, the writing-in of the last line is always interrupted by the STOP command. Thus, it is alwa...
<p>You can try <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> which provides a use function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html" rel="nofollow">read_csv</a> to load the data more easily.</p> <p>Example data:</p> <pre><code>a b c d e f g h i j k...
python|numpy|analysis
3
362,171
17,115,193
Iterating through a numpy array and then indexing a value in another array
<p>I am struggling to get this code to work I want to iterate through an numpy array and based on the result, index to a value in another numpy array and then save that in a new position based on that value.</p> <pre><code> # Convert the sediment transport and the flow direction rasters into Numpy arrays sedim...
<h2>Cause of the Problem</h2> <p>The error is because you're trying to index beyond the bounds of the <code>sediment_transport</code> grid (e.g. the i+1 and j+1 portions). Right now, you're trying to get a value that doesn't exist when you're at a boundary of the grid. Also, it's not raising an error, but you're curre...
python|arrays|loops|numpy
6
362,172
16,849,996
memory leak in matplotlib histogram
<p>Running the following code will result in memory usage rapidly creeping up. </p> <pre><code>import numpy as np import pylab as p mu, sigma = 100, 15 x = mu + sigma*np.random.randn(100000) for i in range(100): n, bins, patches = p.hist(x, 5000) </code></pre> <p>However, when substituting the call to pylab with ...
<p>Matplotlib generates a diagram. NumPy does not. Add <code>p.show()</code> to your first code to see where the work goes.</p> <pre><code>import numpy as np import pylab as p mu, sigma = 100, 15 x = mu + sigma*np.random.randn(100000) n, bins, patches = p.hist(x, 5000) p.show() </code></pre> <p>You may want to try wi...
python|memory-leaks|numpy|matplotlib|histogram
2
362,173
16,591,923
rename index of a pandas dataframe
<p>I have a pandas dataframe whose indices look like:</p> <pre><code>df.index ['a_1', 'b_2', 'c_3', ... ] </code></pre> <p>I want to rename these indices to:</p> <pre><code>['a', 'b', 'c', ... ] </code></pre> <p>How do I do this without specifying a dictionary with explicit keys for each index value?<br> I tried:<...
<p>Perhaps you could get the best of both worlds by using a MultiIndex:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.arange(8).reshape(4,2), index=['a_1', 'b_2', 'c_3', 'c_4']) print(df) # 0 1 # a_1 0 1 # b_2 2 3 # c_3 4 5 # c_4 6 7 index = pd.MultiIndex.from_tuples([item.s...
python|pandas
5
362,174
19,112,398
Getting list of lists into pandas DataFrame
<p>I am reading contents of a spreadsheet into pandas. DataNitro has a method that returns a rectangular selection of cells as a list of lists. So</p> <pre><code>table = Cell("A1").table </code></pre> <p>gives</p> <pre><code>table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]] headers = table.pop(0) # gives the ...
<p>Call the <code>pd.DataFrame</code> constructor directly:</p> <pre><code>df = pd.DataFrame(table, columns=headers) df Heading1 Heading2 0 1 2 1 3 4 </code></pre>
python|pandas|datanitro
314
362,175
19,300,458
Logical addressing numpy mess up with other matrices
<p>I have just found a problem and I don't know if it is meant to be this way or I am just doing it wrong. When I use logical addressing in a numpy matrix to change all the values of a matrix that are, say, equal to a 1. All other matrices that somehow have something to do with this matrix will also be modified. </p> ...
<p>This is not a bug. Saying <code>B=A</code> in python means that both <code>B</code> and <code>A</code> point to the same object. You need to copy the matrix.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from numpy import matrix as mtx &gt;&gt;&gt; A = mtx(np.eye...
numpy|matrix|indexing|addressing
3
362,176
22,358,174
numpy array elementwise multiply a panda timeseries
<p>I have these two data structures: </p> <pre><code>a = np.array([1,2,3]) ts = pd.TimeSeries([1,2,3]) </code></pre> <p>What I want to get at the end is:</p> <pre><code>1 2 3 2 4 6 3 6 9 </code></pre>
<p>You can use the outer product:</p> <pre><code>In [490]: np.outer(a, ts) Out[490]: array([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) </code></pre> <p>Or align one of them vertically first:</p> <pre><code>In [491]: a * ts[:, None] Out[491]: array([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) </code></pre>...
python|numpy|pandas
5
362,177
21,953,366
How to make sure that solution is global minimum while using python scipy.optimize.minimize
<p>I was implementing logistic regression in python. To find theta , I was struggling to decide which is the best algorithm that always guarantees global optima without bothering about initial parameter theta.</p> <pre><code>import numpy as np import scipy.optimize as op def Sigmoid(z): return 1/(1 + np.exp(-z));...
<p>There is no practical algorithm that is guaranteed to find a global optimum. However, there are some heuristics like DIRECT (see e.g. <a href="http://ab-initio.mit.edu/wiki/index.php/NLopt_Algorithms#DIRECT_and_DIRECT-L" rel="nofollow">here</a>) that work very well in practice for given bounds. These can be used to ...
python|numpy|machine-learning|scipy|logistic-regression
2
362,178
22,124,537
Read_json populates with empty lists; how to remove those rows
<p>I've got a Pandas dataframe created with pd.read_json(). When I read it in, I get a few cells that have just an empty list or None, and I want to detect the rows with those [], None in certain columns. For example:</p> <pre><code> feat 1 feat 2 feat 3 0 [] [] 5 1 6 8 3...
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html" rel="nofollow"><code>applymap</code></a> the <code>[]</code> and <code>None</code> to <code>NaN</code>:</p> <p><em>Note: replace works for the None but not the <code>[]</code>... this solution seems to be a little...
json|pandas
3
362,179
22,402,033
Weird findings initializing the array with numpy.NAN
<p>I'am having some trouble when initializing a numpy array with numpy.NAN as below.</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.zeros(2) &gt;&gt;&gt; a array([ 0., 0.]) &gt;&gt;&gt; a[:] = numpy.NAN &gt;&gt;&gt; a array([ nan, nan]) &gt;&gt;&gt; a[0] is numpy.NAN False </code></pre> <p>Why is...
<p>It's a NaN. It's just that <code>is</code> doesn't work the way you think it does with NumPy arrays. When you assign</p> <pre><code>a[:] = numpy.NAN </code></pre> <p>NumPy doesn't actually fill <code>a</code> with references to the <code>numpy.NAN</code> object. Instead, it fills the array with doubles with NaN va...
python|arrays|numpy
9
362,180
21,968,643
What is a "scalar" in numpy?
<p><a href="http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars">The documentation</a> states the purpose of scalars, such as the fact that conventional Python numbers like float and integer are too primitive therefore more complex data types are neccessary. <br><br> It also states certain kind...
<p>A NumPy scalar is any object which is an instance of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.generic.html"><code>np.generic</code></a> or whose <code>type</code> is in <code>np.ScalarType</code>:</p> <pre><code>In [12]: np.ScalarType Out[13]: (int, float, complex, long, bool, str, ...
python|numpy|scipy
48
362,181
22,180,850
numpy correlation coefficient: np.dot(A, A.T) on large arrays causing seg fault
<p>NOTE:</p> <pre><code>Speed is not as important as getting a final result. However, some speed up over worst case is required as well. </code></pre> <p>I have a large array A:</p> <pre><code>A.shape=(20000,265) # or possibly larger like 50,000 x 265 </code></pre> <p>I need to compute the correlation coefficients...
<p>Python compiled with intel's mkl will run this with 12GB of memory in about 30 seconds:</p> <pre><code>&gt;&gt;&gt; A = np.random.rand(50000,265).astype(np.float32) &gt;&gt;&gt; A.dot(A.T) array([[ 86.54410553, 64.25226593, 67.24698639, ..., 68.5118103 , 64.57299805, 66.69223785], ..., ...
numpy|blas|dot-product
4
362,182
22,213,298
Creating same random number sequence in Python, NumPy and R
<p>Python, NumPy and R all use the same algorithm (Mersenne Twister) for generating random number sequences. Thus, theoretically speaking, setting the same seed should result in same random number sequences in all 3. This is not the case. I think the 3 implementations use different parameters causing this behavior.</p>...
<p>use <code>rpy2</code> to call r in python, here is a demo, the numpy array <code>data</code> is sharing memory with <code>x</code> in R:</p> <pre><code>import rpy2.robjects as robjects data = robjects.r(""" set.seed(1) x &lt;- runif(5) """) print np.array(data) data[1] = 1.0 print robjects.r["x"] </code></pre>
python|arrays|r|random|numpy
10
362,183
17,907,614
Finding local maxima of xy data point graph with numpy?
<p>I would like to get <em>most efficient</em> way to find local maxima in <em>huge</em> data point sets containing thousands of values. As input are used two long lists with x and y values.</p> <p>Consider this simple example:</p> <pre><code>xval = [-0.15, -0.02, 0.1, 0.22, 0.36, 0.43, 0.58, 0.67, 0.79, 0.86, 0.96 ]...
<p>You can let numpy handle the iteration, i.e. vectorize it:</p> <pre><code>def local_maxima(xval, yval): xval = np.asarray(xval) yval = np.asarray(yval) sort_idx = np.argsort(xval) yval = yval[sort_idx] gradient = np.diff(yval) maxima = np.diff((gradient &gt; 0).view(np.int8)) return np....
python|numpy|max|points
4
362,184
17,733,769
Writing string entries in a csv to an array in python?
<p>I'm struggling with getting string values into an array in python. I have a file, about 30k entries long, and each row looks like this:</p> <p>0R1,Sn=0.3M,Sm=0.7M,Sx=1.5M</p> <p>I don't need the 0R1 part; all I need is all the Sn values in one array, the Sm values in another, and the Sx in another (of course, I ha...
<pre><code>reader = csv.reader(f1) rows = list(reader) cols = zip(*rows) Min = cols[1] Mean = cols[2] Max = cols[3] # or if you really want numpy.arrays Min = numpy.array(cols[1]) #dtype will be auto-assigned Mean = numpy.array(cols[2]) #dtype will be auto-assigned Max = numpy.array(cols[3]) #dtype will be auto-assig...
python|arrays|string|numpy
3
362,185
17,948,913
white border while displaying a full image with python and opencv
<p>This question is related with this one: <a href="https://stackoverflow.com/questions/17696061/how-to-display-a-full-screen-images-with-python2-7-and-opencv2-4">how to display a full screen images with python2.7 and opencv2.4</a></p> <p>I want to display a black image full screen, i have created even a black image w...
<p>I have the same problem, there is a white stripe of 1 pixel on the left and on the top side of the window. Tested it with multiple monitors. OpenCV version 3.4.2</p> <p>But there is a workaround which works perfectly fine in my case (see also <a href="https://gist.github.com/goraj/a2916da98806e30423d27671cfee21b6" ...
python|opencv|numpy
1
362,186
18,189,981
Reordering columns/rows of a pivot_table?
<p>pandas's pivot_table seems to return columns only in alphabetical order, such that</p> <p><code>pivot_table(tips, 'tip_pct', rows=['sex', 'day'], cols='smoker', aggfunc=len)</code></p> <p>gives:</p> <pre><code> smoker No Yes sex day Female Fri 2 7 Sat 13 15 Sun 14 4 ...
<p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow noreferrer">Categories</a>, introduced in pandas 0.15, the 'day' and 'smoker' columns can be converted to categories with predefined order. The pivot_table() would keep them sorted.</p> <pre><code>&gt;&gt;&gt; pt = pd.pivot_t...
python|pandas|pivot-table
4
362,187
4,707,623
Construct Numpy index given list of starting and ending positions
<p>I have two identically-sized numpy.array objects (both one-dimensional), one of which contains a list of starting index positions, and the other of which contains a list of ending index positions (alternatively you could say I have a list of starting positions and window lengths). In case it matters, the slices form...
<p>I would use</p> <pre><code>np.r_[tuple(slice(s, e) for s, e in zip(start, end))] </code></pre> <p>EDIT: Here is a solution that does not use a Python loop:</p> <pre><code>def indices(start, end): lens = end - start np.cumsum(lens, out=lens) i = np.ones(lens[-1], dtype=int) i[0] = start[0] i[le...
python|numpy
7
362,188
55,246,654
Lookup row in pandas dataframe
<p>I have two dataframes (A &amp; B). For each row in A I would like to look up some information that is in B. I tried:</p> <pre><code>A = pd.DataFrame({'X' : [1,2]}, index=[4,5]) B = pd.DataFrame({'Y' : [3,4,5]}, index=[4,5,6]) C = pd .DataFrame(A.index) C .columns = ['I'] C['Y'] = B .loc[C.I, 'Y'] </code></pre> ...
<p>Use <code>A.join(B)</code>.</p> <p>The result is:</p> <pre><code> X Y 4 1 3 5 2 4 </code></pre> <p>Joining is by index and value from <code>B</code> for key <code>5</code> is absent, since <code>A</code> does not contain this key.</p>
pandas|lookup
2
362,189
55,247,508
Normalizing while keeping the value of 'dst' as an empty array
<p>I was trying to normalize a simple numpy array <code>a</code> as follows:</p> <pre><code>a = np.ones((3,3)) cv2.normalize(a) </code></pre> <p>On running this, OpenCV throws an error saying <code>TypeError: Required argument 'dst' (pos 2) not found</code>. So I put the <code>dst</code> argument as also mentioned i...
<p>You would need to assign the result of <code>cv2.normalize</code> back to a variable, in the first example. From <a href="https://docs.opencv.org/master/d2/de8/group__core__array.html#ga87eef7ee3970f86906d69a92cbf064bd" rel="nofollow noreferrer">the docs</a>, the signature for <code>cv2.normalize()</code> is:</p> <...
python|numpy|opencv
3
362,190
55,499,467
Count the exact characters of a float number after decimal
<p>I have a cvs file with data that I only want to update once and if by mistake the update runs again I need to ensure the data does not update again. Before the update runs the data has no decimal places, but after the update each value is divided by 100 so each line will have 2 decimal place. My thought here is to c...
<p>I'm not familiar with the <code>pd</code> module. However, you can do something like this, where <code>s</code> is the column's string value:</p> <pre><code>num_decimals = len(s.partition('.')[-1]) </code></pre>
python|pandas|count|decimal
0
362,191
55,549,443
pandas, assign multiple column values
<p>I have user data in a df_user : only 1 row</p> <pre><code>user_id, age, height, item_id, item_height 1, 11, 15, 2, 3 </code></pre> <p>I have df with same columns </p> <pre><code>user_id, age, height, item_id, item_height 2, 22, 33, 3, 4 5, 22, 33, 5, 4 </code></pre> <p>Now I want to assign some columns (user_id,...
<p>you can create <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_indexer.html" rel="nofollow noreferrer"><code>Index.get_indexer</code></a> for positions by columns names and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.i...
pandas|dataframe
2
362,192
55,436,800
How to add values in a new column in Pandas by using kind of VLOOKUP?
<p>I am working on a project for analysing Amazon marketing campaign data sets. The campaigns have the hierachie:</p> <p>"Camapigns" includes "AdGroups" includes "Keywords".</p> <p>While I can see a performance value for all of the record types (Campaign, Adgroup and Keyword) the change of the "Bid" is only possibl...
<p>I would probably use a apply lambda function. i.e.</p> <pre><code>df["Action"] = df.apply(lambda r: 1.1 if r["Record_Type"] == "AdGroup" and r["Performance"] &lt; 1 else r["Action"], axis=1) </code></pre> <p>You could also use iloc with a condition.</p>
python|python-3.x|pandas|performance|vlookup
0
362,193
55,173,951
Combine Multiple Rows in Dataframe with Same Key Value
<p>I have a data structure that looks like this:</p> <pre><code>idtenifier amount dist_type new_value new_value2 1 1.0 normal 1 2.0 new_value 1 1.0 new_value2 3 1.0 normal 5 3.0 normal 5 23...
<p>We do not need using for loop here , after split the dataframe by two , for dist_type not equal to normal , we do <code>pivot</code> , then <code>merge</code> it back </p> <pre><code>df1=df.loc[df.dist_type=='normal'].copy() df2=df.loc[df.dist_type!='normal'].copy() yourdf=df1.merge(df2.pivot('idtenifier','dist_typ...
pandas|loops|dataframe
1
362,194
55,504,723
Sorting multiindex by a column while following specific structure
<p>I am using pandas to sort an n level array based on the integers in a column ("D"). It is very important the heirarchy of the groups remain consistent based on the 1st and 3rd level <em>only</em>. </p> <p>I have tried following <a href="https://stackoverflow.com/questions/47378149/python-pandas-sorting-multiindex-b...
<p>Seems like you need <code>argsort</code></p> <pre><code>df.iloc[(-df.groupby(level=[0,1]).D.transform('max')).argsort().values] Out[416]: D Gran1 Par2 Child1 9 Child2 2 Gran2 Par3 Child1 6 Child2 8 Gran1 Par1 Child1 3 Child2 7 Child3 2 Par...
python|pandas|numpy|sorting|multi-index
0
362,195
55,466,270
Applying Kullback-Leibler (aka kl divergence) element-wise in Pytorch
<p>I have two tensors named <code>x_t</code>, <code>x_k</code> with follwing shapes <code>NxHxW</code> and <code>KxNxHxW</code> respectively, where <code>K</code>, is the number of autoencoders used to reconstruct <code>x_t</code> (if you have no idea what is this, assume they're <code>K</code> different nets aiming to...
<p>It's unclear to me what exactly constitutes a probability distribution in your model. With <code>reduction='none'</code>, <code>kl_div</code>, given <code>log(x_n)</code> and <code>y_n</code>, computes <code>kl_div = y_n * (log(y_n) - log(x_n))</code>, which is the "summed" part of the actual Kullback-Leibler diverg...
python|pytorch
3
362,196
55,506,284
How to plot two columns of a specific index range?
<p>I made a dataframe from a .txt file that has 2 columns. I have a specific indexing range (3751:6252) for which I want to plot column 1 (freq) vs column 2 (phase). </p> <p>How can I do this?</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #open text file...
<p>Maybe you need to add %matplotlib inline after the import.</p> <p><code>import matplotlib.pyplot as plt</code> <br> <code>%matplotlib inline</code></p>
pandas|dataframe|plot|indexing
1
362,197
55,494,885
How do I get the remaining dataframe after using np.where in Pandas?
<p>What I want (but does not work):</p> <pre><code>df = np.where((df['cd_0'].values == 1) &amp; (df['cd_1'].values == 1), df, np.nan) </code></pre> <p>Note the <strong><em>df</em></strong> in the second argument of </p> <pre><code>np.where(... , df, ...) </code></pre> <p>I want to get the entire remaining dataframe...
<p>This is <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>where</code></a> from pandas </p> <pre><code>df=df.where((df['cd_0'] == 1) &amp; (df['cd_1'] == 1)) </code></pre> <p>Another way is <code>reindex</code> back or <code>.loc</code>...
python|pandas|performance|numpy|dataframe
1
362,198
55,320,713
I have a all the rows with a particular column with lists. Select rows that does not contain atleast one element from the target list
<p>I have a data frame which has rows that contain lists (Lets call B) I have a target list (let's call A). I want to store all the rows, that does not have at least one common element in B and A.</p> <pre><code>A = [ 'IAB24', 'IAB9-WS1', 'IAB9-WS2', 'IAB26-WS1', 'IAB9-9', 'IAB14-WS1', 'IAB14-1', 'IAB19-15', 'IAB25-5'...
<p>You can use set intersection. We want to find rows where the intersection is the empty set. </p> <pre><code>df[[not(bool(set(A) &amp; set(x))) for x in df.Category]] </code></pre> <p>A bit more straight-forward:</p> <pre><code>df[[len(set(A) &amp; set(x)) == 0 for x in df.Category]] </code></pre>
python|pandas|list|apply
3
362,199
55,461,167
want to add some columns from multiple dataframe into one specific dataframe
<p>so basically I have downloaded multiple stocks data in and stored in CSV format so I created a function to that and passed a list of stocks name to that user-defined function .so one stock data have multiple columns in like open price, close price etc so I want close price column from every stock df stored in a new ...
<p>Try the following:</p> <pre><code>close_prices = pd.DataFrame() for i in stocks: df = pd.read_csv(i + '_data.csv') close_prices[i] = df['close'] </code></pre>
python|pandas
0