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
15,800
41,381,596
How to calculate gradients in a numerically stable fashion
<p>I would like to compute derivatives of a ratio <code>f = - a / b</code> in a numerically stable fashion using tensorflow but am running into problems when <code>a</code> and <code>b</code> are small (<code>&lt;1e-20</code> when using 32-bit floating point representation). Of course, the derivative of <code>f</code> ...
<p>Thanks to Yaroslav Bulatov's pointer, I was able to implement a custom function with the desired gradient.</p> <pre><code># Define the division function and its gradient @function.Defun(tf.float32, tf.float32, tf.float32) def newDivGrad(x, y, grad): return tf.reciprocal(y) * grad, - tf.div(tf.div(x, y), y) * gr...
python|tensorflow
3
15,801
41,481,319
I would like to know is it possible to achieve the pandas.groupby operation using list comprehension or apply method of dataframe
<p>Pandas dataframe methods include a groupby,</p> <pre><code>import pandas as pd df=pd.read_csv('battle.csv') df[['region','location']].groupby('region').count() </code></pre> <p>This methods generates a dataframe that looks like</p> <pre><code>region count A 5 B 2 C 6 </cod...
<p>Consider a <code>DF</code> constructed as shown:</p> <pre><code>np.random.seed(42) df = pd.DataFrame(dict(region=np.random.choice(list('ABC'), 10, p='0.3 0.3 0.4'.split()), location=['loc_'+'{}'.format(i) for i in range(10)])) </code></pre> <p>1) An obvious solution would be to <code>groupby</co...
python-3.x|pandas
0
15,802
61,367,496
Convert hierarchical index to column in Pandas
<p>Here's the input data</p> <pre><code>df1 = pd.DataFrame( { "author" : ["A","B","A","A","C","B"] , "topic" : ["cat", "dog", "dog", "cat", "dog", "dog"] } ) df1 </code></pre> <pre><code> author topic 0 A cat 1 B dog 2 A dog 3 A cat 4 C dog 5 B dog </code></pre> <p>I'm u...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>Series.unstack</code></a> here:</p> <pre><code>df = df1.groupby('author')['topic'].value_counts().unstack(fill_value=0) </code></pre> <p>Another solution with <a href="http://pandas.py...
python|pandas
1
15,803
61,599,120
How to convert this text file into dataframe using pandas?
<p>I have a text file<a href="https://i.stack.imgur.com/BZBO1.png" rel="nofollow noreferrer">Univerity_towns.txt</a> where the data is newline seperated but, I want two columns namely State and town but as the data is vertical, I just went: <code>df = pd.read_csv('university_towns.txt', delimiter= '\n', index_col=Fa...
<p>I got the data from WikiPedia and tried it out. If it's just a division of state and university names, I think it's possible with the following</p> <pre><code> data = ''' Alabama [edit] Auburn (Auburn University, Edward Via College of Osteopathic Medicine)[6] Birmingham (University of Alabama at Birmingham, Birm...
python|pandas
0
15,804
68,859,222
Pandas isin equivalent for float or int
<p>I have a dataframe with column A populated with numbers 1-9. I want to filter just on numbers 2 and 3. isin does not work for float dtypes. Is there an alternative?</p> <p>something similar to:</p> <pre><code>df=df.loc[df['ColA'].isin([2,3])] </code></pre>
<p>Or you could try <code>pd.to_numeric</code> to convert <code>float</code> to <code>int</code>:</p> <pre><code>df = df.loc[pd.to_numeric(df['ColA'], downcast=int).isin([2, 3])] </code></pre>
python|pandas|integer|isin
1
15,805
68,810,845
How to preserve leading zeros with read_json in Python
<p>I get JSON from a URL. I then want to put it into a dataframe and insert it into a SQL table:</p> <pre><code>import requests import json import pandas as pd import pyodbc from sqlalchemy import create_engine # Make the database connection conn = pyodbc.connect('Driver={SQL Server};' 'Server=S...
<p>As mentioned by @Jonathan Leon in the comments, you can solve this by providing the dtypes.</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd json_str = '{&quot;data&quot;:[&quot;00123456789&quot;,&quot;00223456789&quot;]}' df = pd.read_json(json_str, dtype={'data': str}) </co...
python|python-3.x|pandas|dataframe
1
15,806
36,387,675
Python - expanding numpy array changes all values of vectorized function
<p>I am noticing some odd behavior when trying to vectorize the following bump function. It should return positive values for any inputs in the open interval (-1,1), and return 0 for inputs elsewhere:</p> <pre><code>&gt;&gt;import numpy as np &gt;&gt;def bump(x): if np.abs(x)&lt;1: return np.exp(-1/(1-x*...
<p>As the documentation for <code>np.vectorize</code> explains:</p> <blockquote> <p>The data type of the output of <code>vectorized</code> is determined by calling the function with the first element of the input. This can be avoided by specifying the <code>otypes</code> argument.</p> </blockquote> <p>When the fir...
python|arrays|numpy|vectorization
2
15,807
36,526,708
Comparing Python, Numpy, Numba and C++ for matrix multiplication
<p>In a program I am working on, I need to multiply two matrices repeatedly. Because of the size of one of the matrices, this operation takes some time and I wanted to see which method would be the most efficient. The matrices have dimensions <code>(m x n)*(n x p)</code> where <code>m = n = 3</code> and <code>10^5 &lt;...
<p>Definitely use <code>-O3</code> for optimization. This turns <a href="https://stackoverflow.com/a/29292944/871910">vectorizations</a> on, which should significantly speed your code up.</p> <p>Numba is supposed to do that already.</p>
python|c++|numpy|optimization|numba
11
15,808
5,274,243
Split array at value in numpy
<p>I have a file containing data in the format:</p> <pre><code>0.0 x1 0.1 x2 0.2 x3 0.0 x4 0.1 x5 0.2 x6 0.3 x7 ... </code></pre> <p>The data consists of multiple datasets, each starting with 0 in the first column (so x1,x2,x3 would be one set and x4,x5,x6,x7 another one). I need to plot each dataset separately so I ...
<p>I actually liked Benjamin's answer, a slightly shorter solution would be:</p> <pre><code>B= np.split(A, np.where(A[:, 0]== 0.)[0][1:]) </code></pre>
python|numpy
27
15,809
53,102,731
Pandas: compare list objects in Series
<p>In my dataframe a column is made up of lists, for example:</p> <pre><code>df = pd.DataFrame({'A':[[1,2],[2,4],[3,1]]}) </code></pre> <p>I need to find out the location of list [1,2] in this dataframe. I tried:</p> <pre><code>df.loc[df['A'] == [1,2]] </code></pre> <p>and</p> <pre><code>df.loc[df['A'] == [[1,2]]]...
<p>Do not use <code>list</code> in cell, it creates a lot of problem for <code>pandas</code>. If you do need an <code>object</code> column, using <code>tuple</code>:</p> <pre><code>df.A.map(tuple).isin([(1,2)]) Out[293]: 0 True 1 False 2 False Name: A, dtype: bool #df[df.A.map(tuple).isin([(1,2)])] </code><...
python|pandas
19
15,810
65,789,921
Columns 2D tenson times rows 2D tensor equals a 3d pytorch tensor
<p>Given 2 tensors 2-D in PyTorch <code>A</code> (a X m) and <code>B</code> (m X b), is there any efficient way to obtain a tensor <code>C</code> (m X a X b), where <code>C[i,:,:] = A[:,i] @ B[i,:]</code>?</p> <p>Here I will give an example of the problem:</p> <pre><code>A = torch.FloatTensor([[1,2],[3,4]]) B = torch.F...
<p>look at <a href="https://pytorch.org/docs/stable/generated/torch.einsum.html#torch.einsum" rel="nofollow noreferrer"><code>torch.einsum</code></a>:</p> <pre class="lang-py prettyprint-override"><code>C = torch.einsum('im,mj-&gt;mij', A, B) </code></pre>
python|pytorch
0
15,811
65,877,624
How can I vectorize a masked weighted average with condition using numpy?
<p>The unvectorized code reads:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import numpy.ma as ma np.random.seed(42) H = np.random.uniform(0.1, 1.0, size=(6,8)) r, c = H.shape mask = H.max(axis=1) &gt; 0.95 x = np.linspace(0, 10, c) weighted_averages = ma.masked_all((r,), dtype=H.dtype) ...
<p>How about this -</p> <pre><code>import numpy as np import numpy.ma as ma np.random.seed(42) H = np.random.uniform(0.1, 1.0, size=(6,8)) r, c = H.shape mask = H.max(axis=1) &gt; 0.95 x = np.linspace(0, 10, c) H_mask = H[mask] wa = (np.sum(x * H_mask, axis=1))/np.sum(H_mask, axis=1) weighted_averages = ma.masked_a...
python|numpy|weighted-average|masked-array
1
15,812
65,722,169
How to create a pandas dataframe with days and hours in a year in Python?
<p>I want to create a pandas dataframe consisting of all hours in a year. Therefore, there needs to be rows for each of the 8760 hours (365 days * 24 hours per day). This is relatively straightforward.</p> <p>However, I also want to have another column in the dataframe for days that corresponds to the hour. It means, u...
<p>Maybe you could use np.arange to create the number of hours, and then divide them by 24 to get the days?</p> <p>Something like this:</p> <pre><code>import pandas as pd import numpy as np hours = np.arange(1, 8761) df= pd.DataFrame(data=hours, columns = [&quot;Hours of a Year&quot;]) df['Days of a Year'] = ((df[&quo...
python|python-3.x|pandas|loops|for-loop
1
15,813
21,251,515
Why astype(uint) on np.array doesn't change type of an element of the np.array?
<p>When converting an np.array to uint8 using <strong>astype</strong> the type of an element of the array doesn't change.</p> <pre><code>&gt;&gt;&gt; x = np.array([[1.0, 2.3], [1.3, 2.9]]) &gt;&gt;&gt; x.astype(uint8) array([[1, 2], [1, 2]], dtype=uint8) &gt;&gt;&gt; type(x[0,0]) &lt;type 'numpy.float64'&gt; <...
<p><code>astype</code> returns a copy of the origin array.</p> <p>Use <code>x = x.astype(uint8)</code> instead</p>
python|python-2.7|numpy
7
15,814
21,040,766
Python pandas rolling_apply two column input into function
<p>Following on from this question <a href="https://stackoverflow.com/questions/21025821/python-custom-function-using-rolling-apply-for-pandas">Python custom function using rolling_apply for pandas</a>, about using <code>rolling_apply</code>. Although I have progressed with my function, I am struggling to deal with a f...
<p>Not sure if still relevant here, with the new <code>rolling</code> classes on pandas, whenever we pass <code>raw=False</code> to <code>apply</code>, we are actually passing the series to the wraper, which means we have access to the index of each observation, and can use that to further handle multiple columns.</p> ...
python|pandas
11
15,815
63,389,274
Plotting a scatter plot of each 15 rows of a dataframe?
<p>I want to create a scatter plot of my data frame which contains 800 rows. Instead of plotting them in a whole graph, I want to separate the graph by 15 rows of my data frame. I supposed to see 54 graphs as the result. How can I do this by using python?</p>
<p>I created some random data with two columns in a dataframe. You can then use numpy to loop through every 15 rows of your dataframe (don't use <code>DataFrame.iterrows</code> as it is extremely inefficient), and created a simple scatter plot for each chunk of data.</p> <pre><code>import numpy as np import pandas as p...
python|pandas|plot|rows|scatter
0
15,816
63,663,518
tf.where() not behaving as expected for manipulating tensors
<p>I have tried the following code:</p> <pre><code>a = tf.where(tf.greater_equal(x,1.0),x*tf.math.log(b + 1e-19), (1-x)*tf.math.log(1 - b + 1e-19)) </code></pre> <p>does not produce the same results as:</p> <pre><code>a = x*tf.math.log(b + 1e-19) + (1-x)*tf.math.log(1 - b + 1e-19) </code></pre> <p>Here x is a binary va...
<p>Code sample:</p> <pre><code># When x = 0.0 x = 0.0 b = 0.5 a = tf.where(tf.greater_equal(x,1.0),x*tf.math.log(b + 1e-19), (1-x)*tf.math.log(1 - b + 1e-19)) # -0.6931472 from (1-x)*tf.math.log(1 - b + 1e-19) c = x*tf.math.log(b + 1e-19) + (1-x)*tf.math.log(1 - b + 1e-19) # 0 + (1-x)*tf.math.log(1 - b + 1e-19) = -0....
tensorflow|multiplexing
1
15,817
63,635,005
Pandas - Flatten irregular nested JSON
<p>I have following JSON object and try to convert it into a DataFrame.</p> <p>Data:</p> <pre><code>{ &quot;data&quot;: { &quot;docs&quot;: [ { &quot;id&quot;: &quot;1&quot;, &quot;col1&quot;: &quot;foo&quot;, &quot;col2&quot;: &quot;123&quot;, &quot;list&quot;: [&quot;foo ba...
<p>I cannot add comment (yet) to complete the answer above but you can convert your column list to string using this code</p> <pre><code>df['list']=df['list'].apply(lambda x: str(x).strip('[\']')) </code></pre>
python|json|pandas
2
15,818
53,571,432
Replacing Queue-based input pipelines with tf.data
<p>I am reading Ganegedara‘s NLP with Tensorflow. The introduction to input pipieline has the following example</p> <pre><code>import tensorflow as tf import numpy as np import os # Defining the graph and session graph = tf.Graph() # Creates a graph session = tf.InteractiveSession(graph=graph) # Creates a session # ...
<p>I ended up finding my answer through someone else's code, which was <a href="https://github.com/tensorflow/tensorflow/issues/18784" rel="nofollow noreferrer">inquiring about the poor performance of TextLineDataset and decode_csv</a>.</p> <p>Here's my code that uses tf.data to do something similar to the code on Gan...
tensorflow|tensorflow-datasets
0
15,819
53,518,558
Ramp signal python
<p>I would like to generate a ramp signal to 0 to 5 V so I use the function sawtooth waveform and it has a period 2*pi, rises from -1 to 1 but how can I do to change the rising to 0 and 5? </p> <pre><code>from scipy import signal import matplotlib.pyplot as plt import numpy as np import matplotlib.gridspec as gridsp...
<p>If you only want to work with output of existing function, you can add 1 to the output of sawtooth to make it go from 0 to 2. if you want it to go from 0 to 5, you can multiply the above output with 5/2.</p> <pre><code>from scipy import signal import matplotlib.pyplot as plt t = np.linspace(0, 1, 500) plt.plot(t, 2...
python|numpy|scipy
1
15,820
53,415,682
Using df['C'] vs. df.loc[:, 'C'] to assign new column in Pandas dataframe
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame({'A':np.random.randint(1,10, 10), 'B':np.random.randint(1,10, 10)}) def sumf(row): result = None if row['A']&gt;= row['B']: result = row['A'] - row['B'] else: result = row['B'] - row['A'] return result df.loc[:,'C'] = df.apply(su...
<p>The <code>SettingWithCopyWarning</code> is a warning related to the possibility of chained assignment. From the <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow noreferrer">docs</a> on "Returning a view versus a copy", it states "The chained assignment warn...
python-3.x|pandas|dataframe
0
15,821
19,853,086
Error in filtering groupby results in pandas
<p>I am trying to filter groupby results in pandas using the example provided at:</p> <p><a href="http://pandas.pydata.org/pandas-docs/dev/groupby.html#filtration" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/groupby.html#filtration</a></p> <p>but getting the following error (pandas 0.12):</p> <pre><code>...
<p>This was a quasi-bug in 0.12 and will be <a href="https://github.com/pydata/pandas/blob/master/pandas/core/groupby.py#L2161" rel="nofollow">fixed in 0.13</a>, the res is now protected by a type check:</p> <pre><code>if isinstance(res,(bool,np.bool_)): if res: add_indices() </code></pre> <p>I'm not quit...
pandas
2
15,822
20,348,931
Speed for filling a matrix in python vs matlab
<p>I am testing the speed of Python in comparison with Matlab. I decided to move to Python because of the many advantages it has but I wanted to compare the speed to see what is the difference in this regard.</p> <p>I tested some for loops to fill a 1000 x 1000 matrix, like this:</p> <pre><code>from numpy import * s...
<p>I hope you are aware that in both languages you should write vectorized code!</p> <ol> <li>Matlab has a just in time accelerator I believe, which may kicks in for such an expression, I am not sure what happens if you would call your own function in the inside loop.</li> <li>Looping itself is not everything, most of...
python|performance|matlab|python-2.7|numpy
3
15,823
20,005,163
python datetime: How to get next period (using aliases such as 'D', 'M')
<p>Is there any way to get from a date to the next period? I.e. I am looking for a funaction <code>next</code> that takes </p> <pre><code>now = datetime.datetime(2013, 11, 15, 0, 0) </code></pre> <p>to </p> <pre><code>next(now, 'D') = datetime.datetime(2013, 11, 16, 0, 0) #moving to next day next(now, 'M') = datetim...
<p>How about using <code>dateutil</code>, like this:</p> <pre><code>from datetime import date from dateutil.relativedelta import relativedelta one_day = date.today() + relativedelta (days =+ 1) one_month = date.today() + relativedelta( months =+ 1 ) </code></pre>
python|pandas
1
15,824
16,619,664
Concatenating and sorting thousands of CSV files
<p>I have thousands of csv files in disk. Each of them with a size of approximately ~10MB (~10K columns). Most of these columns hold real (float) values.</p> <p>I would like to create a dataframe by concatenating these files. Once I have this dataframe, I would like to sort its entries by the first two columns.</p> <...
<p>Loading them into a database is easy, flexible for making changes later on and takes advantage of all the optimization work that goes into databases. Once you've loaded it, if you wanted to get an iterable of the data, you could run the following query and be done:</p> <pre><code>SELECT * FROM my_table ORDER BY co...
python|pandas
4
15,825
55,367,725
Pandas filter dataframe based on condition for the first n rows
<p>I have a dataframe of shape [600 000, 19]. I want to filter the first 100 000 rows based on one condition, the next 300 000 based on another condition, and a 3rd condition for the last rows. I was wondering how this can be done.</p> <p>Currently, I split the data frame into 3 segments and apply their respective c...
<p>You can try the following approach:</p> <pre><code>import pandas as pd sample = pd.DataFrame({'x' : pd.np.arange(100), 'colname': pd.np.arange(100)}) conditions = [('index &lt; 5', 'colname &lt; 3'), ('index &gt; 50', 'index &lt; 100', 'colname &lt; 55')] sample.query('|'.join...
python|pandas|filtering|conditional-statements
2
15,826
55,347,792
Is MongoDB faster for storing data than pandas read/write to_excel?
<p>I am developing a database of information and currently storing the data in various sheet in multiple XLSX files and considering switching my data to a MongoDB database. Is it quicker read/write for MongoDB than read/write for Pandas? Is Pandas just a nice way to analyze a relational database versus storing informat...
<p>Use <a href="https://docs.python.org/3/library/timeit.html" rel="nofollow noreferrer">timeit</a> to compare running time of the code snippet you provided, on your hardware, with running time of a similar mongo snippet, on your hardware.</p>
python-3.x|mongodb|pandas
1
15,827
7,068,126
2D Interpolation of Large Irregular Grid to Regular Grid
<p>I have 2048x2048 mesh of irregular data <code>zi = f(xi, yi)</code> which are essentially three independent sets of 2048 real values. I need to smoothly interpolate (perhaps bicubic spline) that into a regular mesh of <code>wi = f(ui, vi)</code> where <code>ui</code> and <code>vi</code> are integer values from 0 to...
<p>I tried to reproduce your errors without success. Are you on a 32 bit system? I had problems with scipy/numpy and large arrays so switched to 64 bit, and have had no problems since then.</p> <p>Here's the code I used to try to reproduce your error (it will generate nothing useful, but should at least experience t...
python|numpy|grid|scipy|interpolation
2
15,828
7,569,553
Working with TIFFs (import, export) in Python using numpy
<p>I need a python method to open and import TIFF images into numpy arrays so I can analyze and modify the pixel data and then save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel)</p> <p>I couldn't find any documentation on PIL methods concernin...
<p>First, I downloaded a test TIFF image from <a href="http://www-eng-x.llnl.gov/documents/tests/tiff.html" rel="noreferrer">this page</a> called <code>a_image.tif</code>. Then I opened with PIL like this:</p> <pre><code>&gt;&gt;&gt; from PIL import Image &gt;&gt;&gt; im = Image.open('a_image.tif') &gt;&gt;&gt; im.sho...
python|numpy|python-imaging-library|tiff
130
15,829
56,668,702
Keras and AutoGraph
<p>Reading <a href="https://www.tensorflow.org/beta/guide/autograph#keras_and_autograph" rel="nofollow noreferrer">this</a> and <a href="https://stackoverflow.com/questions/55171526/tensorflow-2-0-keras-is-training-4x-slower-than-2-0-estimator#comment97183315_55172506">this answer</a> I understood that with non-dynami...
<p>If you mean to use <code>@tf.function</code> on the outer loop, i.e. the 'epoch' loop, it would probably not benefit your model much. It would just make development harder. With more code comes complexity.</p> <p>However, you must absolutely use <code>tf.function</code> on custom loss functions and other functions t...
python|tensorflow|keras|tensorflow2.0
0
15,830
56,856,996
Difference in shape of tensor torch.Size([]) and torch.Size([1]) in pytorch
<p>I am new to pytorch. While playing around with tensors I observed 2 types of tensors-</p> <pre><code>tensor(58) tensor([57.3895]) </code></pre> <p>I printed their shape and the output was respectively -</p> <pre><code>torch.Size([]) torch.Size([1]) </code></pre> <p>What is the difference between the two?</p>
<p>You can play with tensors having the single scalar value like this:</p> <pre><code>import torch t = torch.tensor(1) print(t, t.shape) # tensor(1) torch.Size([]) t = torch.tensor([1]) print(t, t.shape) # tensor([1]) torch.Size([1]) t = torch.tensor([[1]]) print(t, t.shape) # tensor([[1]]) torch.Size([1, 1]) t = ...
pytorch|tensor
6
15,831
25,876,065
Pandas: update dataframe using rows as index but keeping original index safe
<p>i want to know if there is a fastest method to update dataframe using rows as index but keeping original index safe.</p> <p>My working method:</p> <pre><code>df = DataFrame( { "name": ['SEBASTIEN', 'JOHN', 'JENNY'] , "age": [39, 34, 32], "city": ['denver','chicago','los angeles'] } ) updt = DataFrame( { "firstnam...
<p>This is a simple merge and combine_first. Much faster than direct indexing. You can also specify <code>left_on</code> and <code>right_on</code> rather than renaming if you wish.</p> <pre><code>In [28]: result = pd.merge(df,updt.rename(columns={'firstname' : 'name'}),on=['name'],suffixes=['_l','_r'],how='outer') In...
python|pandas
2
15,832
67,163,425
calculate weighted mean of 3 arrays with nans in data python
<p>I have 3, two dimensional arrays that represent geospatial data. Each array shape is <code>(721,1440)</code>, i.e., 721 latitude values and 1440 longitude values. I want to compute a weighted mean of these 3 arrays. Normally that is simple and would generally be sum(array*weight)/sum(weights). This works great excep...
<p>You can use <code>np.nansum()</code> and <code>np.isnan()</code>:</p> <pre><code>import numpy as np # Dummy example x = np.ones((5,5)) y = np.ones((5,5))*2 x[0,0] = np.nan # Stack your array stack = np.stack((x,y)) # Compute the weight for each value: weight = np.apply_along_axis(np.multiply,0,~...
python|numpy|python-xarray
2
15,833
66,846,209
TextBlob error: too many values to unpack
<p>I am trying to run the following code, but I have gotten an error that are too many values to unpack</p> <p>The code is:</p> <pre><code>import csv import json import pandas as pd df = pd.read_csv(&quot;job/my_data_frame_test.csv&quot;, encoding=&quot;utf-8&quot;) df.info() print(df) </code></pre> <div class="s-tab...
<p><code>NaiveBayesClassifier()</code> <a href="https://textblob.readthedocs.io/en/dev/classifiers.html" rel="nofollow noreferrer">expects a list of tuples</a> of the form <code>(text, label)</code>:</p> <pre class="lang-py prettyprint-override"><code>train = list(zip(df['TEXT'], df['text recommended'])) # [('ABC', 'y...
python|pandas|dataframe|text-mining|textblob
1
15,834
66,859,113
How to split on commas and then remove the commas in a python pandas dataframe
<p>I want to split on commas, and then remove the commas. I start out with a dataframe with 2 columns that I read in from a csv file.</p> <p>[name] [feature1, feature2, feature3] - the features are all in one cell and each row may have a different number of features.</p> <p>I made a sub-df from the main df with this ...
<p>You are really close to the answer. What you miss is the <code>pat</code> argument of <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer">pandas.Series.str.split()</a>.</p> <pre class="lang-py prettyprint-override"><code>df_features_split = df.features.str.sp...
python|pandas
1
15,835
67,039,009
How to find the index of an element in an numpy array?
<p>I have an array <code>df</code> in which each element is a list of 2 numbers. Given an element <code>p = [18, 169]</code>. I would like to find the indices of such elements <code>p</code> in <code>df</code>. Given <code>df</code></p> <pre><code>[[[13, 169], [18, 169], [183, 169]], [[-183, 169], [18, 169], [18...
<p>What you've computed with <code>(df==p).all(-1)</code> is a <em>mask</em>. They have lots of uses, but you can use that directly to compute the value you want.</p> <pre><code># True or false at each coordinate mask = (df==p).all(-1) # Extract the coordinates where the mask is True result = np.argwhere(mask) </code>...
python|numpy|numpy-ndarray
3
15,836
47,442,741
Error: setting an array with a sequence
<pre><code>import numpy as np # constants n=1000 # number of time steps to simulate m=90 # number of angles rho=1.225 # kg/m^3 g=-9.8 # m/s^2 start=0.0 # seconds end=10 # seconds initial_velocity=70 # meters/second in...
<p>Just running your code to see your error, at the point where I get the error you mention:</p> <pre><code>ValueError Traceback (most recent call last) &lt;ipython-input-12-2458d409946f&gt; in &lt;module&gt;() 46 ay = g - ( 0.5*rho*C*A/mass ) * v**2 * ( vy[ j-1 ] / v ) ...
python|arrays|python-3.x|numpy
0
15,837
68,052,056
TPU returning "failed call to cuInit: UNKNOWN ERROR (303)" on Google Cloud with Kubernetes Cluster
<p>I am trying to use a TPU with Google Cloud's Kubernetes engine. My code returns several errors when I try to initialize the TPU, and any other operations only run on the CPU. To run this program, I am transferring a Python file from my Dockerhub workspace to Kubernetes, then executing it on a single v2 preemptible T...
<p>There are actually no errors in this workload you've provided or the logs. A few comments which I think might help:</p> <ul> <li><code>pip install tensorflow</code> as you have noted installs <code>tensorflow-gpu</code>. By default, it tries to run GPU specific initializations and fails (<code>failed call to cuInit:...
tensorflow|kubernetes|google-cloud-platform|tpu|google-cloud-tpu
1
15,838
68,322,707
Extracting from a 2D dataframe and adding value to 1D dataframe based on value locations in the 2D dataframe using spyder
<p>I have two dataframes</p> <pre><code>df1 = pd.DataFrame({ 1: {'A': 237, 'B': 435, 'C': 900}, 2: {'A': 543, 'B': 313, 'C': 1200}, 3: {'A': 300, 'B': 150, 'C': 1600}, 4: {'A': 256, 'B': 635, 'C': 900}, 5: {'A': 343, 'B': 847, 'C': 1200}, 6: {'A': 122, 'B': 321, 'C': 1600} }) df2 = pd.DataFrame(...
<p>Let's try <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.T.html" rel="nofollow noreferrer"><code>T</code></a> + <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt</code></a> to go to long-form, then compressing the index with...
python|pandas|dataframe|spyder
0
15,839
68,089,112
Pandas - Add colums for mean und std after groupby statement
<p>I have a following dataframe:</p> <pre><code> d = {'City' : ['Paris', 'London', 'NYC', 'Paris', 'NYC'], 'ppl' : [3000,4646,33543,85687568,34545]} df = pd.DataFrame(data=d) df_mean = df.groupby('City').mean() </code></pre> <p>now I want to instead just calc the mean (and .std()) of the ppl column, I want ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html#" rel="nofollow noreferrer"><code>.GroupBy.agg()</code></a>, as follows:</p> <pre><code>df.groupby('City').agg({'ppl': ['min', 'std']}) </code></pre> <p>If you don't want the column <co...
python|pandas
1
15,840
68,175,970
moving data in excel with python
<p>I would like to be able to move a data of the table automatically to place it on a new column and duplicate it as many times as I have rows before a row with only one data but I don't know which tool to use.</p> <p><a href="https://i.stack.imgur.com/meDGv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgu...
<p>Using ffill answer directly the question.</p> <blockquote> <p>df['col'] = df['col'].ffill()</p> </blockquote>
python|excel|pandas|dataframe|reshape
0
15,841
59,288,242
Merging two dataframe using index as key and date
<p>I am trying to merge two dataframe using a FK and between two dates then save the output in a new dataframe.</p> <p>Consider the below example:</p> <pre><code># first_df FK date value1 value2 ... (more columns) 1 2019-01-01 50 50 1 2019-01-02 40 80 1 2019-01-03 80 ...
<p>In your case we use <code>merge_asof</code></p> <pre><code>df=pd.merge_asof(df1.sort_values('date'),df2.sort_values('date'),by='FK',on='date').sort_values('FK') </code></pre> <p>Then we have <code>percentage</code> and values in same df, we can do multiple </p> <pre><code>df[['value1','value2']]=df[['value1','val...
python|pandas|dataframe
3
15,842
59,132,295
Python series where values are lists, get another series with list of indexes correspond to each item list
<p>Sorry the title is hard to understand—not sure how to phrase this one. Say I have a series that looks like this </p> <pre><code>s = pd.Series(index = ['a','b','c'], data = [['x','y','z'], ['y','z'], ['x','z']]). </code></pre> <p>I would want something like this </p> <pre><code>{'x':['a','c'], 'y':['a','b'], 'z':...
<p>Let us use <code>explode</code></p> <pre><code>s.explode().reset_index().groupby(0)['index'].agg(list).to_dict() {'x': ['a', 'c'], 'y': ['a', 'b'], 'z': ['a', 'b', 'c']} </code></pre>
python|pandas
4
15,843
59,146,183
How do I select the specific data in a data frame based on thee contents of other columns?
<p>I'm new to pandas and I'm currently trying to use it on a data set I have on my tablet using qPython (temporary situation, laptop's being fixed). I have a csv file with a set of data organised by country, region, market and item label, with additional columns price, year and month. These are set out in the following...
<p>I hesitate to guess, but it seems that you are probably iterating through rows (you said you were using <code>iloc</code>). This is the slowest operation in pandas. Pandas data frames are optimized for series access.</p> <p>If your plotting you can use matplotlib directly with pandas data frames and use the <code>g...
python|pandas|qpython
0
15,844
45,005,313
How to visualize an attention mechanism in a classification task?
<p>I've managed to finish experiments using attention mechanism adopted from <a href="https://gist.github.com/cbaziotis/7ef97ccf71cbc14366835198c09809d2" rel="nofollow noreferrer">@cbaziotis implementation</a> and now i'm confused with the visualization. I don't really understand the heatmap as well. If you guys can ex...
<p>Usually, a "heat map" is a 2D intensity image, where dark region = "cool" regions, and bright regions = "hot" regions.<br> In the context of "attention map", the "cool"/dark regions of the map indicates places the net does not attend to while the "hot"/bright" regions are regions the net attends to more.<br> It is u...
machine-learning|tensorflow|deep-learning|artificial-intelligence|keras
0
15,845
44,901,441
Find shared sub-ranges defined by start and endpoints in pandas dataframe
<p>I need to combine two dataframes that contain information about train track sections: while the "Line" identifies a track section, the two attributes "A" and "B" are given for subsections of the Line defined by start point and end point on the line; these subsections do not match between the two dataframes:</p> <pr...
<p>Here is my solution, a bit long but it works:</p> <p>First step is finding the intervals:</p> <pre><code>all_start_points = set(df1['startpoint'].values.tolist() + df2['startpoint'].values.tolist()) all_end_points = set(df1['endpoint'].values.tolist() + df2['endpoint'].values.tolist()) all_points = sorted(list(al...
python|pandas
1
15,846
45,204,021
Pandas merge fail to extract common Index values
<p>I'm trying to merge 2 DataFrames of different sizes, both are indexed by 'Country'. The first dataframe 'GDP_EN' contains every country in the world, and the second dataframe 'ScimEn' contains 15 countries.</p> <p>When I try to merge these DataFrames,instead of merging the columns based on index countries of ScimEn...
<p>I think both <code>DataFrames</code> are not indexes by <code>Country</code>, but <code>Country</code> is column add parameter <code>on='Country'</code>:</p> <pre><code>GDP_EN = pd.DataFrame({'Country':['USA','France','Slovakia', 'Russia'], 'a':[4,8,6,9]}) print (GDP_EN) Country a 0 ...
python|pandas|dataframe|merge
1
15,847
44,978,037
TypeError: 'float' object has no attribute '__getitem__' in function
<p>I am trying to pass a dataframe to a function and compute mean and std dev from different columns of the dataframe. When I execute each line of the function step by step (without writing a function as such) it works fine. However, when I try to write a function to compute, I keep getting this error:</p> <pre><code>...
<pre><code>meandata = np.array(data['mean']) TypeError: 'float' object has no attribute '__getitem__' </code></pre> <p><code>__getitem__</code> is the method that Python tries to call when you use indexing. In the marked line that means <code>data['mean']</code> is producing the error. Evidently <code>data</code> is...
python|pandas|numpy
1
15,848
57,177,765
Why do np.std(X) and X.std() return different values?
<p>I am trying to calculate normalized scores for my dataset using mean normalization. When I write <code>(X - np.mean(X))/np.std(X)</code>, it gives me different score than doing <code>((X - X.mean())/X.std()</code>. </p> <p>Problem seems to be coming from calculation of standard deviation. <code>X.std()</code> retur...
<blockquote> <p>Pandas uses the unbiased estimator (N-1 in the denominator), whereas Numpy by default does not.</p> <p>To make them behave the same, pass <code>ddof=1</code> to <code>numpy.std()</code>.</p> </blockquote> <p><a href="https://stackoverflow.com/questions/24984178/different-std-in-pandas-vs-numpy...
pandas|numpy|statistics|standard-deviation
5
15,849
57,166,713
Is there any good alternative for pd.read_sas ? i'm facing few issues when loading huge amount of data from sas system to Jypter notebook
<p>Is there any good alternative for pd.read_sas ? i'm facing few issues when loading huge amount of data from sas system to Jypter notebook.</p>
<p>In my opinion</p> <pre><code> pyreadstat </code></pre> <p>is one of the most proper solutions. You can look at it here:</p> <p><a href="https://github.com/Roche/pyreadstat" rel="nofollow noreferrer">Pyreadstat repo</a></p> <p>I tried it few days ago and it seems to be promising, mainly because of processing tim...
python|pandas|sas|data-analysis
0
15,850
45,806,597
Pandas conditional creating columns issues
<p>I have a sample data set, </p> <pre><code>import pandas as pd df = { 'columA':['1A','ws rank','rank','ws rank','rank','Drank'], 'value': [ 1, 12, 34, 50, 3,2] } df = pd.DataFrame(df) </code></pre> <p><strong>1. I want to create a column 'HP', for columnA rows that are 'ws rank' and 'rank' and 'Drank', if val...
<p>Interesting....</p> <p>Not sure I fully get all your question but here is my take on the first half....</p> <pre><code>import pandas as pd df = { 'columA':['1A','ws rank','rank','ws rank','rank','Drank'], 'value': [ 1, 12, 34, 50, 3,2] } df = pd.DataFrame(df) df["hp"]=0 def calc_hp(row): rv=0 if row...
python|pandas
1
15,851
45,766,183
Need faster code for replacing strings with values from dictionary
<p>This is how i applied dictionary for stemming. My dictionary (d) is imported and it's in this format now <code>d={'nada.*':'nadas', 'mila.*':'milas'}</code> I wrote this code to stemm tokens, but it runs TOO SLOW, so i stopped it before it finished. I guess it's problem because dict is large, and there is large numb...
<p>Notice that while the keys in your stem dict are regexes, they all start with a short string of some specific characters. Let's say the minimum length of specific characters is 3. Then, construct a dict like this:</p> <pre><code>'ban' : [('bank.$', 'banka'), ('banke', 'banka'), ('banaka', 'banka...
python|python-3.x|pandas|nltk|sklearn-pandas
0
15,852
28,826,849
How to extract rows based on two conditions
<p>Hi I have a dataset d1.</p> <pre><code>import pandas as pd d1 = { 'customers': pd.Series([1, 1, 1, 2, 2, 3, 3, 4, 4]), 'channel': pd.Series(['a', 'a', 'b', 'c', 'a', 'a', 'b', 'b', 'c']), 'freq': pd.Series([3, 3, 3, 2, 2, 2, 2, 2, 2]) } d1=pd.DataFrame(d1) </code></pre> <p>I want to get list of customers who have ...
<p>This is a little convuluted but basically we perform multiply filters on the df using groupby, filtering and 2 levels of boolean indexing:</p> <pre><code>In [140]: d1[d1.customers.isin(d1[d1.channel=='a'].customers)].groupby('customers').filter(lambda x: x['channel'].nunique() == 2) Out[140]: channel custome...
python|pandas
0
15,853
28,839,507
How do I fix my error with PIL and numpy images
<p>You have to run it in the folder with a couple images and run <code>shuffle_all_images()</code> and it will create new folder and randomly generate all of the values for each pixel. I think it has to do with not converting to numpy images as opposed to PIL images?, but I can't figure it out.</p> <pre><code>import r...
<p>The image_shuffle function is wrong. It should be:</p> <pre><code>for row in range(original_image.size[0]): for col in range(original_image.size[1]): r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) original_image.putpixel((row, col), (r,g,b)) </code>...
python|image|python-3.x|numpy|python-imaging-library
0
15,854
50,865,421
Lazy version of numpy.unpackbits
<p>I use <strong><code>numpy.memmap</code> to load only the parts of arrays</strong> into memory that I need, instead of loading an entire huge array. I would like to do the same with <code>bool</code> arrays.</p> <p>Unfortunately, <strong><code>bool</code> memmap arrays aren't stored economically</strong>: according ...
<p>Not possible. The memory layout of a bit-packed array is incompatible with what you're looking for. The NumPy shape-and-strides model of array layout does not have sub-byte resolution. Even if you were to create a class that emulated the view you want, trying to use it with normal NumPy operations would require mate...
python|numpy|boolean|mmap|numpy-memmap
2
15,855
50,702,503
Selecting rows in which more than one value are in another DataFrame
<p>I have a DataFrame with the following form: </p> <pre><code> day u a 0 2018-03-01 5658599 suggestion 1 2018-03-01 10405594 suggestion 2 2018-03-01 4142545 suggestion 3 2018-03-01 10397546 suggestion 4 2018-03-01 10296737 suggestion </code></pre> <p>And I want to select the p...
<p>One way is an inner merge:</p> <pre><code>res = df1.merge(df2, how='inner', left_on=['day', 'u'], right_on=['access_date', 'user_id'])\ .loc[:, df1.columns] print(res) day u a 0 2018-03-01 10405594 suggestion </code></pre>
python|pandas|dataframe
2
15,856
50,859,653
How to read polyfit function in python?
<p>I want to generate a polynomial equation by giving values and get an equaiton. However when I control it with given x values I get different values from equation here is my code and outputs:</p> <pre><code>points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)]) x = points[:,0] y = points[:,1] # calculate polynomial z...
<p>You seem to misunderstand the concept of polynomial fitting. When you call <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.polyfit.html" rel="nofollow noreferrer"><code>polyfit(x, y, n)</code></a>, what it does is give you the n-th (or lesser) degree polynomial that best fits the set of po...
python|python-3.x|numpy
2
15,857
33,101,914
Combine the dataframe in Pandas
<p>I have a data frame: </p> <pre><code>&gt;&gt;&gt; data Name Score 0 a 3 1 b 2 2 a 1 3 c 4 4 c 5 5 d 3 </code></pre> <p>I want to combine the rows with same name, adding score rows, so I want to get the following result:</p> <pre><code> Name Score 0 a...
<pre><code>data.groupby('Name').sum()['Score'].reset_index() </code></pre>
python|pandas
2
15,858
33,457,621
Efficient storage of UNICODED text for processing with Blaze/Pandas
<p>I have about 5 million (&amp; growing) rows of twitter feed and I want to store them efficiently for faster read / write access using Pandas (Preferably <a href="http://blaze.pydata.org" rel="nofollow">Blaze</a>). From that huge metadata of a single tweet, I am just storing <code>[username, tweet time, tweet &amp; t...
<p>Yes, <code>PostgresSQL</code> is a perfectly fine choice for your 10s of GB application. I've had an easy time using <code>sqlalchemy</code> with the <code>psycopg2</code> driver, and the <code>psql</code> command line tool is fine.</p> <p><a href="http://pgcli.com/" rel="nofollow">There is an incredible command-li...
postgresql|pandas|unicode|blaze|nosql
1
15,859
33,510,131
How to aggregate some rows based on their column value in Python
<p>I wan to aggregate the values in in some columns if they share the same value in a specific column of the data frame?</p> <p>In otherwords, how can I get data frame B from A? In this example, I want to check based on the values in column c1, if there are rows with the same value, then I want to put sum of columns c...
<pre><code>import pandas as pd import io import numpy as np import datetime data = """ c0 c1 c2 c3 c4 c5 0 1 a d 3 4 0 1 1 a c 0 0 6 2 1 b d 3 1 0 1 1 b c 0 0 1 """ df = pd.read_csv(io.StringIO(data), delimiter='\s+') df2 = pd.DataFrame(df.g...
python|pandas|dataframe
1
15,860
66,520,201
How a dataframe with a dynamic number of columns can be filtered?
<p>I download data using url calls. The dataframe' columns are not static. For example, with one url call the dataframe can contain <code>x</code> columns while with another url call it can contain <code>y</code> columns etc.</p> <p>The column which is always included in the dataframe is the <code>id</code> column. The...
<p>Use:</p> <pre><code>df.set_index('id').dropna(how='all').reset_index() </code></pre> <p><strong>Explanation</strong></p> <p>As you are a beginner, let me explain it a bit.</p> <p>This will (Step 1) temporarily set column <code>id</code> as index and then (Step 2) drop all rows with ALL <code>nan</code> elements (exc...
python|pandas|filter|dynamic|nan
1
15,861
57,485,480
Why does feather need pyarrow? (or: How to load feather data without downgrading to pandas 24?)
<p>I get this error message: <code>Missing optional dependency 'pyarrow'. Use pip or conda to install pyarrow.</code> when I run a simple command to load feather data, ie: <code>pd.read_feather("data.feather")</code>.</p> <p>Surely I can install pyarrow from conda-forge, but that forces a downgrade from Pandas 25 to ...
<p>The Conda's version of pyarrow does not work properly. Uninstall it and then install it again via pip (the current version is 0.15.1 vs 0.13.something of Conda) - it works fine with Pandas 25.x</p>
python|pandas|pyarrow|feather
3
15,862
57,455,390
How to run Tensorboard in parallel
<p><a href="https://github.com/NVIDIA/DeepRecommender" rel="nofollow noreferrer">https://github.com/NVIDIA/DeepRecommender</a></p> <p>According to the above page, I tried to run the NVIDIA's DeepRecommender program.After I activated the pytorch, I run the program as below but it failed.</p> <p>[I run this Command]</p...
<p>Try either installing <code>tensorflow-gpu</code> in your <code>pytorch</code> environment or <code>pytorch</code> in your <code>tensorflow-gpu</code> environemnt and use that environment to run your program.</p>
python|pytorch|tensorboard
2
15,863
57,457,817
Adding batch normalization decreases the performance
<p>I'm using PyTorch to implement a classification network for skeleton-based action recognition. The model consists of three convolutional layers and two fully connected layers. This base model gave me an accuracy of around 70% in the NTU-RGB+D dataset. I wanted to learn more about batch normalization, so I added a ba...
<p>My interpretation of the phenomenon you are observing,, is that instead of reducing the covariance shift, which is what the Batch Normalization is meant for, you are increasing it. In other words, instead of decrease the distribution differences between train and test, you are increasing it and that's what it is cau...
python|deep-learning|pytorch|batch-normalization
7
15,864
43,586,789
Python VTK: Coordinates directly to PolyData
<p>I want to convert all coordinate combinations for x,y and z in specific range with for now step 1 directly to vtk.polyData or vtk.points. My first approach was to use itertools.product, but I thought this would have a very bad runtime. So i came to another approach with vtk, which i need anyway for the next part sof...
<p>Stack those <code>coords</code> in columns with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html" rel="nofollow noreferrer"><code>np.column_stack</code></a> or <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html" rel="nofollow noreferrer"><code>np.c_</code...
python|numpy|vtk
1
15,865
43,594,658
Using TensorFlow’s Supervisor
<p>I'm trying to run textsum model from tensorflow open source models, inside seq2seq_attention.py they are using Supervisor to manage saving the model, the problem is after running the app the supervisor starts by creatin checkpoints and graph ... etc but it doesnt save the model after 60sec as the param given, it too...
<p>Did you try to specify the duration between saves when you instantiate your saver? I mean (for saving a model every 15 minutes) :</p> <pre><code>saver = tf.train.Saver(keep_checkpoint_every_n_hours=0.25) </code></pre>
python|machine-learning|tensorflow|deep-learning
0
15,866
43,728,359
Why is my 1-hidden layer neural network with ReLUs not getting more than 18% accuracy on the notMNIST dataset?
<p>I'm trying to implement a 1-hidden layer neural network with rectified linear units and 1024 hidden nodes using Tensorflow.</p> <pre><code>def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) batch_size = 128 graph = tf.Gr...
<p>Here are some suggestions that may improve your accuracy:</p> <p>First of all, your hidden layer, which is of size 1024, seems too large. This may cause overfitting. I would try to reduce it to around 50-100 or so, see whether it improves and continue from there.</p> <p>In addition, regarding this line:</p> <pre>...
machine-learning|tensorflow|neural-network|deep-learning
6
15,867
43,851,517
Using a ''for loop'' to copy numpy arrays
<p>I have 2 numpy arrays:</p> <pre><code>array1 = np.load(r'C:\Users\x\array1.npy') array2 = np.load(r'C:\Users\x\array2.npy') </code></pre> <p>I have to merge them in single array, so what I did was:</p> <pre><code>merg_arr = np.zeros((len(array1)+len(array2), 4, 100, 100), dtype=input_img.dtype) for i in range(le...
<p>You could simply <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer">concatenate</a> them along the first axis:</p> <pre><code>merg_arr = np.concatenate([array1, array2, array3, array4, array5], axis=0) </code></pre> <p>You can also do it with the <code>f...
python|arrays|numpy|for-loop
3
15,868
72,995,392
Use Spacy NER to identify person and make person one word?
<p>I want to use Spacy NER to identify the PERSON and make it one word.</p> <p>My dataset looks like this:</p> <pre><code>text use your superpowers vote for Barack Obama vote for Marine Le Pen play with Michael Jordan support the supporters </code></pre> <p>I want my final output to look like this:</p> <pre><code>...
<p>If you use <code>Spacy</code>, you code should be:</p> <pre><code>nlp = spacy.load('en_core_web_trf') def get_ner(txt): doc = nlp(txt) for ent in doc.ents: if ent.label_ == 'PERSON': s = ent.start_char e = ent.end_char txt = txt[:s] + txt[s:e+1].replace(' ', '_') ...
pandas|spacy|named-entity-recognition
0
15,869
73,117,866
BART loading from HuggingFace requires logging in
<p>I'm trying to use pretrained model from HuggingFace. However, I get the following error,</p> <pre><code>OSError: bart-large is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models' If this is a private repository, make sure to pass a token having permission to this repo wit...
<p>The correct model identifier is <a href="https://huggingface.co/facebook/bart-large" rel="nofollow noreferrer">facebook/bart-large</a> and not <code>bart-large</code>:</p> <pre class="lang-py prettyprint-override"><code>from transformers import BartTokenizer, BartModel tokenizer = BartTokenizer.from_pretrained('fac...
huggingface-transformers|bart
1
15,870
72,895,179
List vs Numpy array computing speed: for loops
<p>I was wondering if appending to a list in python would be faster or slower than filling up an 'empty' numpy array. I know that numpy is written directly in C and therefore I expect it to be faster than build in functions in python. I wrote a code to see if this was indeed the case. What I found, however, is that a f...
<p>First, you are using appending method for list and filling method for NumPy array.</p> <p>However, you can also use filling method for list.</p> <pre><code>list = [] for i in range(n): list.append(i) </code></pre> <pre><code>list = [None] * n for i in range(n): list[i] = [i] </code></pre> <p>The fastest meth...
python|list|numpy|performance|loops
0
15,871
73,169,216
Reading CSV file as a key value pair
<p>I have a CSV file as mentioned below. CSV file content :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">NAME</th> <th style="text-align: center;">SURNAME</th> <th style="text-align: right;">AGE</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Shri...
<p>Use <code>records</code> argument</p> <pre><code>df.to_dict('records') </code></pre> <p>Or to get output as the one you provided</p> <pre><code>df1 = df.to_dict('records') _list =[] for i in range(len(df1)): _list.append(df1[i]) _list </code></pre>
python-3.x|pandas|dataframe|python-2.7|file
1
15,872
70,651,294
Validation Accuracy and training accuracy not improving after applying Transfer learning
<p>I am working on a project in which i am trying to implement transfer learning to classify ECG signals (1-Dimentional). I have a pretrained model with pretty good accuracy, but the model was trained on a different dataset which have an input shape of (4096,12) and output shape (6). I want to fine tune this pre-traine...
<p>The idea behind transfer learning is that you concatenate new <strong>trainable</strong> layers to the <strong>end</strong> of a pre-trained model, freeze the pre-trained layers, and train the new layers. When you add these new layers to the <strong>beginning</strong> of the pre-trained model and training the whole ...
python|tensorflow|transfer-learning|pre-trained-model|conv1d
1
15,873
70,560,973
AttributeError 'Series' object has no attribute 'to_numeric'
<p>I have A pandas dataframe, and I want to change the content of a column, depending on its current value. If the record has the value 'INFINITY', assign a constant, elsewhere, assign its current value casted to number. This is my code so far:</p> <p><code>data_frame['my_column'] = np.where(data_frame['my_column'] == ...
<p>Your issue had nothing to do with <code>where</code>. <code>to_numeric</code> is not a valid Series method. However, the top level <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>pandas.to_numeric</code></a> method exists.</p> <p>Thus, you should replace ...
python|pandas|numpy
-1
15,874
70,594,396
Pandas get equivalent positive number
<p>I have data similar to this</p> <pre><code>data = {'A': [10,20,30,10,-10], 'B': [100,200,300,100,-100], 'C':[1000,2000,3000,1000, -1000]} df = pd.DataFrame(data) df </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Index</th> <th style="text-align: cent...
<p>Like this maybe:</p> <pre><code>In [69]: import numpy as np # Create column 'D' with exact duplicate rows using 'abs' In [68]: df['D'] = np.where(df.abs().duplicated(keep=False), 'Duplicate', '') # If the sum of duplicated rows = 0, this means they are 'exact opposite' In [78]: if df[df.D.eq('Duplicate')].sum(1)....
python|pandas
2
15,875
42,649,234
move from pandas to dask to utilize all local cpu cores
<p>Recently I stumbled upon <a href="http://dask.pydata.org/en/latest/" rel="noreferrer">http://dask.pydata.org/en/latest/</a> As I have some pandas code which only runs on a single core I wonder how to make use of my other CPU cores. Would dask work well to use all (local) CPU cores? If yes how compatible is it to pa...
<blockquote> <p>Would dask work well to use all (local) CPU cores?</p> </blockquote> <p>Yes.</p> <blockquote> <p>how compatible is it to pandas?</p> </blockquote> <p>Pretty compatible. Not 100%. You can mix in Pandas and NumPy and even pure Python stuff with Dask if needed.</p> <blockquote> <p>Could I use m...
python|pandas|cpu|multicore|dask
5
15,876
26,951,720
String Formating In/out using %s
<p>I have the following statement that I can't seem to find the problem:</p> <pre><code>Analysis = 'Trythis' TestName = 'ThisOne' NumberIteration = 25 for num in range(NumberIteration): x= np.loadtxt("%s/results/data_%s/Outputs/$s/%sLCOE.txt" % (Analysis, num , TestName, TestName)) </code></pre> <p>I keep rec...
<p>Python is complaining that you gave four arguments to <code>%</code> but only have three <code>%s</code> in your format string. </p> <p>I think the <code>$s</code> is meant to be a <code>%s</code>:</p> <pre><code>x= np.loadtxt("%s/results/data_%s/Outputs/%s/%sLCOE.txt" % (Analysis, num, TestName, TestName)) # ...
python|string|numpy|scipy
2
15,877
27,157,087
Append data to end of human-readable file Python
<p>In one run my python script calculates and returns the results for the variables A, B, C. </p> <p>I would like to append the results run by run, row by row to a human-readable file. After the runs i, I want to read the data back as numpy.arrays of the columns.</p> <p>i | A B C </p> <p>1 | 3 4 6 </p> <p>2 | 4 ...
<p>Thanks for your thoughts. These two options came to my mind too but I need the mixture of both: My specific use case requires the file to be human readable - as far as I know pickling does not provide that and saving to a dictionary destroys the order. I need the data to be dropped as they need to be manipulated in ...
python|numpy|save|append
0
15,878
26,595,819
double quoted elements in csv cant read with pandas
<p>I have an input file where every value is stored as a string. It is inside a csv file with each entry inside double quotes.</p> <p>Example file:</p> <pre><code>"column1","column2", "column3", "column4", "column5", "column6" "AM", "07", "1", "SD", "SD", "CR" "AM", "08", "1,2,3", "PR,SD,SD", "PR,SD,SD", "PR,SD,SD" "...
<p>This will work. It falls back to the python parser (as you have non-regular separators, e.g. they are comma and sometimes space). If you only have commas it would use the c-parser and be much faster.</p> <pre><code>In [1]: import csv In [2]: !cat test.csv "column1","column2", "column3", "column4", "column5", "colu...
python|csv|pandas
27
15,879
39,381,099
Softmax Returns Identity Matrix
<p>My input to <code>softmax</code>, <code>y = tf.nn.softmax(tf.matmul(x, W) + b)</code>, is a valued matrix</p> <pre><code>tf.matmul(x, W) + b = [[ 9.77206726e+02] [ 5.72391296e+02] [ 3.53560760e+02] [ 4.75727379e-01] [ 6.58911804e+02]] </code></pre> <p>But when this is inputted into <code>softmax</code>, ...
<p>Seems like your softmax function is applied to every distinct value in the output vector. Try to transpose your output, i.e. change <code>tf.nn.softmax(tf.matmul(x, W) + b))</code> to <code>tf.nn.softmax(tf.transpose(tf.matmul(x, W) + b)))</code>.</p>
tensorflow|softmax
1
15,880
39,397,389
Creating new columns from unique values across rows in pandas
<p>I'm trying to use unique values in a pandas column to generate a new set of column. Here's an example <code>DataFrame</code>:</p> <pre><code> meas1 meas2 side newindex 0 1 3 L 0 1 2 4 R 0 2 6 8 L 1 3 7 9 R 1 </code></p...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>DataFrame.pivot</code></a>:</p> <pre><code># Perform the pivot. df = df.pivot(index='newindex', columns='side').rename_axis(None) # Format the columns. df.columns = df.columns.map('_'.join) </code><...
python|pandas|dataframe
4
15,881
39,294,469
How can I find start and end occurrence of character in Python
<p>I have a dataframe <code>df</code> with the following ids (in <code>Col</code>). The last occurrence of A/B/C represents the start, and the last occurrence of X is the end. I should ignore any other A,B,C between start and end (e.g. rows 8 and 9).</p> <p>I have to find start and end records from this data and assi...
<p>To find your indices of A, B, and C you can do:</p> <pre><code>df[(df.Col =='A')|(df.Col =='B')|(df.Col =='C')].index </code></pre> <p>Print your start counts:</p> <pre><code>df1 = df[df['count'] != df['count'].shift(+1)] print df1[df1['count'] != 0]['count'] </code></pre> <p>Print your end counts:</p> <pre><co...
python|pandas|indexing|shift|find-occurrences
2
15,882
39,359,843
how to convert string to numeric in python
<p>I would like to convert string (%) to float.but my method didnt work well. the result slightly differ from correct number. for example,</p> <pre><code>a=pd.Series(data=["0.1%","0.2%"]) 0 0.1% 1 0.2% dtype: object </code></pre> <p>first, I strip "%"</p> <pre><code>a.str.rstrip("%") 0 0.1 1 0.2 dtype:...
<p>Many rational numbers can't be represented exactly as a floating-point number. In particular, any number that has to have a five as a factor in the denominator, like 1/(2*5), can't be represented exactly. There isn't much you can do about this: either round the displayed number so it looks right, or use an infinite-...
python|pandas|numpy|floating-point
2
15,883
39,174,768
Reading file as array
<p>I have a <em>cvs</em> file which has three columns of numbers up to three digits each:</p> <pre><code>1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8 0 0 9 0 0 10 0 0 11 0 0 </code></pre> <p>I want to read the columns separately and be able to use them as arrays with:</p> <pre><code>data = np.loadtxt('file.csv') x = ...
<p>With your sample:</p> <pre><code>In [1]: data=np.loadtxt('stack39174768.txt') In [2]: data Out[2]: array([[ 1., 0., 0.], [ 2., 0., 0.], [ 3., 0., 0.], [ 4., 0., 0.], [ 5., 0., 0.], [ 6., 0., 0.], [ 7., 0., 0.], [ 8., 0., 0.], ...
python|arrays|numpy
0
15,884
19,428,904
Saving and Loading of dataframe to csv results in Unnamed columns
<p>prob in the title. exaple:</p> <pre><code>x=[('a','a','c') for i in range(5)] df = DataFrame(x,columns=['col1','col2','col3']) df.to_csv('test.csv') df1 = read_csv('test.csv') Unnamed: 0 col1 col2 col3 0 0 a a c 1 1 a a c 2 2 a a c 3 3 a a...
<p>You can remove row labels via the <code>index</code> and <code>index_label</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html">parameters of to_csv</a>.</p>
python|pandas
8
15,885
19,781,609
How do you remove the column name row when exporting a pandas DataFrame?
<p>Say I import the following Excel spreadsheet into a dataframe:</p> <pre><code>Val1 Val2 Val3 1 2 3 5 6 7 9 1 2 </code></pre> <p>How do I delete the column name row (in this case <code>Val1, Val2, Val3</code>) so that I can export a csv with no column names, just the data?</p> <p>I have trie...
<p>You can write to csv without the header using <code>header=False</code> and without the index using <code>index=False</code>. If desired, you also can modify the separator using <code>sep</code>.</p> <p>CSV example with no header row, omitting the header row:</p> <pre><code>df.to_csv('filename.csv', header=False) ...
python|pandas|csv|dataframe|header
206
15,886
19,578,736
Timespan of groups in Pandas timeseries
<p>Can I receive the covered timespans of groups resulting from groupby operations without using my own lambda function?</p> <p>Currently I have the below solution but I am wondering if the pandas API not already has this built-in somehow? To describe what I'm doing in the data prep part: My task is to find out when a...
<p>Try like this</p> <pre><code>In [11]: df Out[11]: &lt;class 'pandas.core.frame.DataFrame'&gt; DatetimeIndex: 100 entries, 2013-10-25 00:45:49 to 2013-10-25 02:24:49 Freq: T Data columns (total 3 columns): data 100 non-null values mybool 100 non-null values label 100 non-null values dtypes: bool(1), ...
python|pandas
5
15,887
19,551,336
Using isin() with
<p>I am working with a pandas Series and I am trying to use the <code>isin()</code> method to find some of the members of the series. However, for pandas timestamp objects, this function does not appear to be working correctly.</p> <pre><code>import pandas data = pandas.date_range('jan-01-2013','jan-05-2013') s = pa...
<p>it's working like this:</p> <pre><code>s.isin(data[0:2].values) </code></pre>
python|pandas
3
15,888
13,051,103
Numpy cumsum considering NaNs
<p>I am looking for a succinct way to go from:</p> <pre><code> a = numpy.array([1,4,1,numpy.nan,2,numpy.nan]) </code></pre> <p>to:</p> <pre><code> b = numpy.array([1,5,6,numpy.nan,8,numpy.nan]) </code></pre> <p>The best I can do currently is:</p> <pre><code>b = numpy.insert(numpy.cumsum(a[numpy.isfinite(a)]), (nu...
<p><a href="http://pandas.pydata.org/"><code>Pandas</code></a> is a library build on top of <code>numpy</code>. It's <a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html#series"><code>Series</code></a> class has a <code>cumsum</code> method, which preserves the <code>nan</code>'s and is considerably faster...
python|arrays|numpy|nan|cumsum
8
15,889
28,880,195
Getting rows from a PANDAS dataframe that fulfill (a dictionary?) of requirements
<p>I want to filter rows of a pandas <code>DataFrame</code> by specifying a <em>variable</em> set of <code>column==value</code> conditions.</p> <p>Let's say we have a toy <code>DataFrame</code> like this one:</p> <pre><code>from itertools import product from numpy.random import rand df = pd.DataFrame([[i,j,k,rand()] ...
<p>You could make a Series of <code>conditions</code> and select only those columns:</p> <pre><code>&gt;&gt;&gt; df[(df[list(conditions)] == pd.Series(conditions)).all(axis=1)] par1 par2 par3 val 4 1 0 0 0.937192 6 1 1 0 0.536029 </code></pre> <p>This works because after we make t...
python|pandas
4
15,890
33,708,993
How to operate on list of data frame in one instruction
<p>For example:<br> I have four pandas Dateframe <code>df1,df2,df3,df4</code>. And my work process to these 4 dataframe are the same?<br> How to define <code>i =(1,2,3,4) link with "df"</code></p> <p>So, I don't have to change <code>"df1"-&gt; "df2/3/4"</code> so many time. </p>
<p>Whenever you have numbered variable names, think about using a list instead. For example:</p> <pre><code>dfs = [df1, df2, df3, df4] for df in dfs: .... </code></pre> <p>Moreover, it might behoove you to refactor the code defining <code>df1</code>, <code>df2</code>, <code>df3</code> and <code>df4</code> so as t...
python-2.7|pandas
3
15,891
33,901,226
How do I use TensorFlow to add Predicted Value to an empty column in a CSV file?
<p>So I have this great bit of code that comes out with approximately a 93% accuracy rate on its predictions. What I'm wondering how to do now is to take the trained program, make it look at actual test data without the answer on it, and make it fill in the answer regardless of the accuracy. Here's the code that I have...
<p>The program above doesn't appear to be saving the trained session. I think you want to do this in two steps.</p> <ol> <li>Train and save the session</li> <li>Restore the save session, and run test data through it.</li> </ol> <p><strong>Step 1:</strong> </p> <pre><code> #!/usr/bin/env python import tensorflow as...
python|csv|tensorflow
3
15,892
33,890,385
Set possible parameters for numpy curve_fit
<p>I want to fit data in python using the curve_fit function. For that I am using the basic functions</p> <pre><code>def a(x): return x*x def b(x): return x*x*x </code></pre> <p>and combine them into multiple functions:</p> <pre><code>def fit_func(x, n1, n2, n3): return n1*a(x)+n2*b(x)+n3*a(x) </code></...
<p>As stated, there is not enough information in your data to solve for all the parameters you are interested in. Consider the simple case where you have</p> <pre><code>n1*a(x) + n2*a(x) </code></pre> <p>Say the inputs are <code>n1, n2 = (1, 1)</code>. Then an equally valid output is <code>n1, n2 = (0, 2)</code> or ...
python|numpy|curve-fitting
0
15,893
23,638,854
Pandas stock regression chart
<p>I would like to create a simple linear regression chart just like in excel. With the shortest way possible.</p> <p>Which is the easiest way to to plot a stock returns chart with a regression line using the pandas .plot ? </p>
<p>It would be pretty simple with <a href="http://statsmodels.sourceforge.net/stable/generated/statsmodels.graphics.regressionplots.abline_plot.html#statsmodels.graphics.regressionplots.abline_plot" rel="nofollow">statsmodels</a></p> <pre><code>import statsmodels.api as sm mod = sm.OLS.from_formula('y ~ x', data=df) ...
python|matplotlib|pandas
1
15,894
23,461,502
Evaluating pandas series values with logical expressions and if-statements
<p>I'm having trouble evaluating values from a dictionary using if statements.</p> <p>Given the following dictionary, which I imported from a dataframe (in case it matters):</p> <pre><code>&gt;&gt;&gt; pnl[company] 29: Active Credit Date Debit Strike Type 0 1 0 2013-01-08 2.3265 21.15 Put 1 ...
<p>What you yield is a Pandas Series object and this cannot be evaluated in the manner you are attempting even though it is just a single value you need to change your line to:</p> <pre><code>if pnl[company].tail(1)['Active'].any()==1: print 'yay' </code></pre> <p>With respect to your second question see my comment...
python|pandas|if-statement|series
7
15,895
22,916,855
Fitting a Gaussian to a set of x,y data
<p>Firstly this is an assignment I've been set so I'm only after pointers, and I am restricted to using the following libraries, NumPy, SciPy and MatPlotLib.</p> <p>We have been given a txt file which includes x and y data for a resonance experiment and have to fit both a gaussian and lorentzian fit. I'm working on th...
<p>Looks like your data skews heavily to the left, why Gaussian? Not Boltzmann, Log-Normal, or anything else?</p> <p>Much of these are already implemented in <code>scipy.stats</code>. See <code>scipy.stats.cauchy</code> for lorentzian and <code>scipy.stats.normal</code> gaussian. An example:</p> <pre><code>import sci...
python|numpy|matplotlib|curve
0
15,896
14,942,582
Model I-V in Python
<p>Model I-V.</p> <p>Method: Perform an integral, as a function of E, which outputs Current for each Voltage value used. This is repeated for an array of v_values. The equation can be found below.</p> <p><img src="https://i.stack.imgur.com/5Dvz3.png" alt="enter image description here"></p> <p>Although the limits in ...
<p>This question is better suited for the <a href="https://scicomp.stackexchange.com/">Computational Science</a> site. Still here are some points for you to think about.</p> <p>First, the range of integration is the intersection of <code>(-oo, -eV-gap) U (-eV+gap, +oo)</code> and <code>(-oo, -gap) U (gap, +oo)</code>....
python|numpy|scipy|integration|physics
4
15,897
62,289,394
Create new Dataframe from matching two dataframe index's
<p>I'm looking create a new dataframe from data in two separate dataframes - effectively matching the index of each cell and input into a two column dataframe. My real datasets have the exact same number of rows and columns, FWIW. Example below:</p> <pre><code> DF1: Col1 Col2 Col3 1 2 3 3 8 7 ...
<p>here is your code</p> <pre><code>df3 = pd.Series(df1.values.ravel('F')) df4 = pd.Series(df2.values.ravel('F')) df = pd.concat([df3, df4], axis=1) </code></pre>
python|pandas|dataframe
2
15,898
62,249,508
How can I fix the last column in a malformatted csv file?
<p>I have a very large (~80gb) csv file that is formatted with spaces as delimiters, however the final column has spaces and so is causing me a huge headache trying to read it in with pandas.</p> <p>Here's a small segment of the csv i am dealing with:</p> <pre><code>7.942891 7.3e-004 14.64 14.28 14 8 1.2e+001 0.00 6....
<p>Your own solution looks quite efficient, but I'd write the output to a file rather than trying to capture the output. Also, for a loop that is going to be executed about one billion times, it's good to have the contents of the loop as compact as possible:</p> <pre><code>with open(dat_file, 'r') as fin, open(f'fixed...
python|pandas|csv
0
15,899
51,391,250
Compare Columns Row-Wise for Partial String Match
<p>My question is similar to this: <a href="https://stackoverflow.com/questions/36942399/how-to-check-whether-the-content-of-column-a-is-contained-in-column-b-using-pyth?noredirect=1&amp;lq=1">How to check whether the content of Column A is contained in Column B using Python DataFrame?</a></p> <p>Unfortunately, the ch...
<p>Building on @Onyambu's answer.</p> <p><code>in</code> can be used in place of <code>re.findall()</code></p> <pre><code>df["match"] = df.apply(lambda v: int(v[2] in v[1]),axis=1) print(df["match"] </code></pre> <p><strong>Output:</strong></p> <pre><code>0 1 1 0 2 1 3 0 4 1 </code></pre>
python|python-3.x|pandas
1