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
8,400
51,736,715
Numpy Dynamic Slicing Per Row
<p>How do I dynamically slice each row given a starting and ending index without using a for loop. I can do it with loop listed below, but it is way too slow for something where the x.shape[0] > 1 mill</p> <pre><code>x= np.arange(0,100) x = x.reshape(20,5) s_idx = np.random.randint(0,3,x.shape[0]) e_idx = np.random...
<p>You can work with <a href="https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html" rel="nofollow noreferrer">masked arrays</a>:</p> <pre><code>import numpy as np np.random.seed(100) x = np.arange(0, 100) x = x.reshape(20, 5) s_idx = np.random.randint(0, 3, x.shape[0]) e_idx = np.random.randint(3, 6, ...
python|numpy|dynamic|slice
2
8,401
51,827,030
How to replace old string values in Series/column of dataframe with values from dict?
<p>This question is somewhat similar to: <a href="https://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict">Remap values in pandas column with a dict</a>, however, the answers are quite dated and do not cover the "SettingWithCopyWarning".</p> <p>I am simply trying to replace the original ...
<p>By changing the deep copy to a shallow copy, I was able to have changes to the original dataframe, "df". It is stated in the docs: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFr...
python-3.x|pandas|dataframe|series
0
8,402
51,667,881
Lossy compression of numpy array (image, uint8) in memory
<p>I am trying to load a data set of 1.000.000 images into memory. As standard numpy arrays (uint8) all images combined fill around 100 GB of RAM, but I need to get this down to &lt; 50 GB while still being able to quickly read the images back into numpy (that's the whole point of keeping everything in memory). Lossles...
<p>I am still not certain I understand what you are trying to do, but I created some dummy images and did some tests as follows. I'll show how I did that in case other folks feel like trying other methods and want a data set.</p> <p>First, I created 1,000 images using <strong>GNU Parallel</strong> and <strong>ImageMag...
python|performance|numpy|compression|image-compression
5
8,403
37,562,111
Currency and Exchange Name from Yahoo
<p>I'm quite new to pandas (and coding in general), but am really enjoying messing around with pulling stock data from Yahoo Finance.</p> <p>I was just wondering if there's a way to also pull the name of the exchange that the stock is listed on (i.e. LSE, NYSE, AIM etc), as well as the currency the stock is listed in ...
<p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> from <a href="http://www.nasdaq.com/screening/company-list.aspx" rel="nofollow">link</a>, filter columns and then <a href="http://pandas.pydata.org/pandas-docs/stable/generate...
pandas|currency|yahoo|yahoo-finance
0
8,404
37,214,482
Saving with h5py arrays of different sizes
<p>I am trying to store about 3000 numpy arrays using HDF5 data format. Arrays vary in length from 5306 to 121999 np.float64 </p> <p>I am getting <code>Object dtype dtype('O') has no native HDF5 equivalent</code> error since due to the irregular nature of the data numpy uses the general object class.</p> <p>My idea w...
<p>Looks like you tried something like:</p> <pre><code>In [364]: f=h5py.File('test.hdf5','w') In [365]: grp=f.create_group('alist') In [366]: grp.create_dataset('alist',data=[a,b,c]) ... TypeError: Object dtype dtype('O') has no native HDF5 equivalent </code></pre> <p>But if instead you save the arrays as separa...
python|arrays|numpy|hdf5|h5py
21
8,405
37,468,869
Python, opposite of conditional array
<p>I have two <code>numpy</code> arrays, let's say <code>A</code> and <code>B</code></p> <pre><code>In [3]: import numpy as np In [4]: A = np.array([0.10,0.20,0.30,0.40,0.50]) In [5]: B = np.array([0.15,0.23,0.33,0.41,0.57]) </code></pre> <p>I apply a condition like this:</p> <pre><code>In [6]: condition_array = A...
<p>You can use the <code>~</code> operator to invert the array ...</p> <pre><code>A[~((B&gt;0.2)*(B&lt;0.5))] </code></pre> <p>Note that your use of <code>*</code> seems like it's meant to do a logical "and". Many people would prefer that you use the binary "and" operator (<code>&amp;</code>) instead -- Personally, ...
python|arrays|numpy|conditional
3
8,406
41,743,773
Python3 - convert csv to json using pandas
<p>I've got a <code>.csv</code> files with 5 columns but I only need the <code>json</code> file to contain 3 of these how would i go about doing it?</p> <p>csv file:</p> <pre><code>Ncode Ocode name a b c 1 1.1 1x 1a 1b 1c 2 2.2 2x 2a 2b 2c 3 3.3 3x ...
<pre><code>txt = """Ncode Ocode name a b c 1 1.1 1x 1a 1b 1c 2 2.2 2x 2a 2b 2c 3 3.3 3x 3a 3b 3c """ df = pd.read_csv(StringIO(txt), delim_whitespace=True) json.dumps( {'{:0.2f}'.format(r.Ocode): [{'a': r.a}, {'b': r.b}, {'c': r.c}] ...
python|json|pandas|csv|data-conversion
1
8,407
37,842,120
When does advanced indexing on structured masked arrays *really* return a copy?
<p>When I have a structured masked array with boolean indexing, under what conditions do I get a view and when do I get a copy? The <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">documentation</a> says that advanced indexing always returns a copy, but this is ...
<p>The issue of <code>__setitem__</code> v. <code>__getitem__</code> is important, but with structured array and masking it's a little harder to sort out when a <code>__getitem__</code> is first making a copy.</p> <p>Regarding the structured arrays, it shouldn't matter whether the field index occurs first or the eleme...
numpy|indexing|structured-array|masked-array
1
8,408
31,643,178
How to retain Index information when calculating euclidean distances in a dataframe?
<p>Hi I would like to calculate euclidean distances between all points with X,Y coordinates in a dataframe and return the ID(the index) of the closest point.</p> <p>currently I am using this to create a distance matrix:</p> <pre><code>diatancematrix=squareform(pdist(group)) df=pd.DataFrame(dists) </code></pre> <...
<p>The distance matrix includes each point's distance to itself, which will always be zero. Thus, you should expect each row to just see itself as its own minimum.</p>
python|pandas|scipy
0
8,409
31,485,576
Fast basic linear algebra in Cython for recurrent calls
<p>I'm trying to program a function in cython for a monte-carlo simulation. The function involves multiple small linear algebra operations, like dot products and matrix inversions. As the function is being called hundred of thousands of times the numpy overhead is getting a large share of the cost. Three years ago some...
<p>The answer <a href="https://stackoverflow.com/questions/16114100/calling-dot-products-and-linear-algebra-operations-in-cython">you link to</a> is still a good way to call BLAS function from Cython. It is not really a python wrapper, Python is merely used so get the C pointer to the function and this can be done at i...
python|numpy|scipy|cython
1
8,410
64,396,493
The most efficient way to search every element of a list in a dataframe
<p>I have a over 1M dataset like d. I need to find indexes of a dataframe like seekingframe which is over 1500 element in that dataset.</p> <pre><code>import pandas as pd d=pd.DataFrame([225,230,235,240,245,250,255,260,265,270,275,280,285,290,295,300,305,310,315,320]) seekingframe=pd.DataFrame([275,280,285,290,295,30...
<p>It's likely faster to use numpy. On these small unique arrays, numpy was more than 100x faster than pandas <code>.isin()</code> without passing <code>assume_unique=True</code> to the numpy function that finds the intersection of two arrays ( <code>np.in1d</code> ) and returns <code>True</code> or <code>False</code>....
python-3.x|pandas|numpy|dataframe|data-science
3
8,411
47,984,941
python count occurrences in csv with pandas
<p>I'm new to Python and I'm trying to work on a small project and got a little confused.</p> <p>I have 2 csv files that looks like this:</p> <p>all_cars:</p> <pre><code>first_Car,second_car Mazda, Skoda Ferrari, Volkswagen Volkswagen, Toyota BMW, Ferrari BMW, Mercedes </code></pre> <p>super_cars:</p> <pre><code>s...
<p>I'd do it this way:</p> <pre><code>In [220]: d1.stack().value_counts().to_frame('car').loc[d2.super_car_name] Out[220]: car Ferrari 2 BMW 2 Mercedes 1 </code></pre> <p>where <code>d1</code> and <code>d2</code> - your source DataFrames (which can be easily parsed from CSV files using <code>...
python|pandas
2
8,412
58,811,975
How to find a specific value from a pandas Data Frame
<p>I would like to know how will I find a specific value from a Dataframe. I have a value <strong>?</strong> spread across my data frame and its time consuming to check every column in a data frame. Is there any easy way to get the columns name that contains that specific value? For example, I have <strong>?</strong> s...
<p>Do you mean to find all columns with <code>?</code> or <code>0</code> in them? </p> <p>Then you can use <code>df.isin()</code>, it's find some value whether in <code>df</code></p> <p>This example will show how to find df's column where them include value <code>"italy"</code> and <code>1</code>. </p> <pre class=...
python-3.x|pandas|numpy|dataframe
0
8,413
58,655,574
How to read a file .txt containing an array in it?
<p>I want to read data from file into a <strong>DataFrame</strong>. But this file is a special format. Include so many lines like this: </p> <p><code>year = [1, 2, 3]</code></p> <p><code>age = [4, 5, 6]</code></p> <p>And this is the link go to the special file: <a href="https://github.com/cuongpiger/Py-for-ML-DS-DV/...
<p>If need all values to <code>DataFrame</code> create dictionary of Series and pass to <code>DataFrame</code> constructor with <code>ast.literal_eval</code> for parse lists:</p> <pre><code>import ast d = {} with open('dulieu_year_gap_pop_life.txt') as file: splitted = file.readlines() for x in splitted: ...
python|pandas
3
8,414
58,909,689
Compare a column in one dataframe with two other columns in a different dataframe?
<p>I have created two data frames from two tsv files. The data frames are as follows:</p> <pre><code>Dataframe1 (df1) chr position 5 745 7 963 8 1024 Dataframe2 (df2) chr start end 1 10 100 1 500 600 5 250 600 5 784 1045 7 98 980 7 11 ...
<p>Merge the dataframes, evaluate, then drop the unused columns.</p> <pre><code>&gt;&gt;&gt; (df1 .merge(df2, on='chr', how='left') .assign(Valid=lambda df: df.eval('start &lt;= position &lt;= end')) .drop(columns=['start', 'end']) ) chr position Valid 0 5 745 False 1 7 963 True 2 8 ...
python|pandas
2
8,415
70,240,935
Filling Missing Values Based on String Condition
<p>I'm trying to write a function to impute some null values from a Numeric column based on string conditions from a Text column.</p> <p>My attempt example:</p> <pre><code>def fill_nulls(string, val): if df['TextColumn'].str.contains(string) == True: df['NumericColumn'] = df['NumericColumn'].fillna(value=val) </cod...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code...
python|pandas|dataframe|fillna
1
8,416
70,061,018
'loss nan' in time-series classification
<p>I have a transformer model almost exactly the same as in the Keras example code for time series data. I'll take for stock info process for practice a classification via transformer, targeting a simple {0,1} separation as result. The problem here is all I get is always loss <code>nan</code> without any accuracy impro...
<p>without having your data it is just a guess. You say that you want to make a <strong>binary prediction</strong> but you use &quot;categorical_crossentropy&quot; as your loss function which is normaly used for multiple classes. You can have a look here how and when to use diffrent loss and activation functions <a hre...
tensorflow|machine-learning|keras
0
8,417
56,130,164
How to incorporate elevation into euclidean distance matrix in pandas?
<p>I have the following <code>dataframe</code> in pandas:</p> <pre><code>import pandas as pd df = pd.DataFrame({ "CityId": { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4 }, "X": { "0": 316.83673906150904, "1": 4377.40597216624, "2": 3454.158...
<p>You can try <code>scipy.spatial.distance_matrix</code>:</p> <pre><code>xx = df[['X','elevation_meters', 'Y']] pd.DataFrame(distance_matrix(xx,xx), columns= df['CityId'], index=df['CityId']) </code></pre> <p>Output:</p> <pre><code>CityId 0 1 2 3 ...
python|pandas|matrix|euclidean-distance|altitude
1
8,418
56,184,013
Tensorflow Lite GPU support for python
<p>Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If <code>tensorflow-gpu</code> is installed and <code>tensorflow.lite.python.interpreter</code> is imported, will GPU be used automatically?</p>
<p>According to <a href="https://github.com/tensorflow/tensorflow/issues/31377" rel="nofollow noreferrer">this</a> thread, it is not.</p>
tensorflow|machine-learning|tensorflow-lite
3
8,419
56,012,137
Trying to optimize parameters in the Lugre Dynamic Friction model
<p>I have data collected in CSV of every output of the friction model. the model imagines the contact between to surfaces as one dimensional bristles that react to being bent like springs this deflection. the force of friction is model as: </p> <pre><code>FL(V,Z) = sig0*Z +sig1*DZ/Dt +sig2*V </code></pre> <p>where ...
<p>As I mentioned in my comment, <code>Velocity()</code> ist the cause of the error that is most probably due to the fact that it uses a time value, whereas you pass a whole list/ array (with multiple values) to <code>Velocity()</code> when you call it in <code>friction()</code>.</p> <p>Using some chosen values and af...
python|numpy|scipy|physics|ode
0
8,420
55,623,798
Syntax Error In Python When Trying To Refer To Range Of Columns
<p>I am trying to remove the last several columns from a data frame. However I get a syntax error when I do this:</p> <p><code>db = db.drop(db.columns[[12:22]], axis = 1)</code></p> <p>This works but it seems clumsy...</p> <p><code>db = db.drop(db.columns[[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]], axis = 1)</co...
<p>The first example uses <code>[12:22]</code> is a "slice" of nothing. It's not a meaningful statement, so as you say, it gives a syntax error. It seems that what you want is a list containing the numbers 12 through 22. You need to either write it out fully as you did, or use some generator function to create it.</...
python|pandas
1
8,421
55,912,900
How can I implement this type of search in Pandas?
<p>assuming I have a dataframe with a lot of names like:</p> <pre><code>[[jack,rose,mike], [mike,jack,lee], [jeff,jack,alex]] </code></pre> <p>what I need is like a function that when I input "jack", the return dataframe is like:</p> <pre><code>[[1,0,0], [0,1,0], [0,1,0]] </code></pre> <p>Is there any method in P...
<p>You can directly compare DataFrame items to a scalar:</p> <pre><code>(df == 'jack').astype(int) </code></pre>
python|pandas
0
8,422
55,845,445
Pandas add increment to timestamp to break ties, preserving original order
<p>I have a dataframe of the format </p> <pre><code> df = pandas.DataFrame([{'tstamp':'2019-03-06 06:42:13.582500', 'value' : 1}, {'tstamp':'2019-03-06 06:43:28.937400', 'value': 2}, {'tstamp':'2019-03-06 06:43:28.937400', 'value' : -1}, {'tstamp':'2019-03-06 06:43:28.937400', 'value' : 2}, {'t...
<p>If a conversion of <code>'tstamp'</code> to <code>np.datetime</code> format is ok, then this should work:</p> <pre><code>df['tstamp2'] = pandas.to_datetime(df.tstamp) df['tstamp2'] += pandas.to_timedelta(df.groupby(df.tstamp2).cumcount(), unit='ns') # Condition 1: # Out: True # Condition 2: # Out: False # Condition...
pandas|timedelta
1
8,423
39,668,665
Format a table that was added to a plot using pandas.DataFrame.plot
<p>I'm producing a bar graph with a table using pandas.DataFrame.plot.</p> <p>Is there a way to format the table size and/or font size in the table to make it more readable?</p> <p>My DataFrame (dfexe):</p> <pre><code>City State Waterfalls Lakes Rivers LA CA 2 3 1 SF CA 4 9 0 Dallas TX 5 6 ...
<p>Here is an answer.</p> <pre><code># Test data dfex = DataFrame({'City': ['LA', 'SF', 'Dallas'], 'Lakes': [3, 9, 6], 'Rivers': [1, 0, 0], 'State': ['CA', 'CA', 'TX'], 'Waterfalls': [2, 4, 5]}) myplot = dfex.plot(x=['City','State'],kind='bar',stacked='True',table=True) myplot.axes.get_xaxis().set_visible(False) ...
python|pandas|matplotlib
5
8,424
39,483,546
get_dummies split character
<p>I have data labelled which I need to apply one-hot-encoding: <code>'786.2'</code>, <code>'ICD-9-CM|786.2'</code>, <code>'ICD-9-CM'</code>, <code>'786.2b|V13.02'</code>, <code>'V13.02'</code>, <code>'279.12'</code>, <code>'ICD-9-CM|V42.81'</code> is labels. The <code>|</code> mean that the document have 2 labels at t...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> and then select first item...
python|pandas|one-hot-encoding
4
8,425
44,053,388
Fast splitting of array on column indices from each row of sparse array
<p>Let's say I have a sparse array and a dense array that has the same number of columns but fewer rows:</p> <pre><code>from scipy.sparse import csr_matrix import numpy as np sp_arr = csr_matrix(np.array([[1,0,0,0,1],[0,0,1,0,0],[0,1,0,0,1],[0,0,0,1,1],[0,0,0,1,0]])) arr = np.random.rand(10).reshape(2,5) print(arr) [...
<p>Well, there are two options - <code>np.split</code> or <code>loop comprehension</code>. In my experience, I have found out the latter to be faster. But, the priority must be to do minimal work inside the loop comprehension by doing as much of pre-processing as possible.</p> <p><strong>Approach #1 :</strong> First a...
python|numpy|scipy|sparse-matrix
1
8,426
69,374,842
Can't install tensorflow-macos on MacM1 (errors while installing grpcio)
<p>This has been a long fight trying to install tensorflow in Mac Mini M1... I'm using macOS Monterey(12.0 Beta) According to the last instructions from tensorflow/apple (<a href="https://developer.apple.com/metal/tensorflow-plugin/" rel="nofollow noreferrer">https://developer.apple.com/metal/tensorflow-plugin/</a>), I...
<p>Try running the following code line</p> <pre><code>SYSTEM_VERSION_COMPAT=0 python -m pip install tensorflow-macos </code></pre> <p>For a short tutorial on installation <a href="https://medium.com/@aaparikh_/setting-up-apple-silicon-devices-to-allow-tensorflow-use-native-gpu-for-data-science-60a355c7d008" rel="nofoll...
macos|tensorflow|apple-m1
0
8,427
69,384,357
Pandas dataframe on python
<p>I feel like this may be a really easy question but I can't figure it out I have a data frame that looks like this</p> <pre><code>one two three 1 2 3 2 3 3 3 4 4 </code></pre> <p>The third column has duplicates if I want to keep the first row but drop the second row because there is a duplicate on row two...
<p>Pandas DataFrame objects have a method for this; assuming <code>df</code> is your dataframe, <code>df.drop_duplicates(subset='name_of_third_column')</code> returns the dataframe with any rows containing duplicate values in the third column removed.</p>
python|pandas
1
8,428
69,557,333
Initializing a differentiable param in pytorch
<p>I'm trying to define a set of new parameters <code>B</code> in a pytorch model. I would like to initialize the new params with current weights of the model <code>W</code>.</p> <p><strong>Question:</strong> I want these params <code>B</code> to be differentiable, but autograd should not track their history to <code>W...
<p>There are several ways to do it and one of them is</p> <pre><code>B = W.clone().detach() </code></pre> <p>Another elegant one comes to my mind is</p> <pre><code>B = torch.new_tensor(x, requires_grad=True) </code></pre> <p>which is much more readable and <a href="https://pytorch.org/docs/stable/generated/torch.Tensor...
pytorch
0
8,429
40,781,795
Complex function for getting combinations of one column with other
<p>I have a table in pandas df</p> <pre><code>id_x id_y a b b c a c d a x a m b c z a k b q d w a w q v </code></pre> <p>How to read this table is :</p> <p>the combinations for a is, a-b,a-c,a-k,a-w, similarly for b(b-c,b-q) and so on.. I want to write a f...
<p><strong>Edited:</strong> solution redesign according to comments</p> <pre><code>import pandas as pd def direct_related(df, values, column_names=('x', 'y')): rels = set() for value in values: for i, v in df[df[column_names[0]]==value][column_names[1]].iteritems(): rels.add(v) return ...
python|python-2.7|python-3.x|pandas
0
8,430
40,813,733
formatting a .txt file in pandas
<p>I would like to take a .txt file that is in the following format: </p> <pre><code>StateOne[edit] RegionOne (UniversityOne)[1] RegionTwo (UniversityTwo) RegionThree (UniversityThree)[2] </code></pre> <p>and have this data be cleaned up and returned in a DataFrame of this format: </p> <pre><code>State RegionNa...
<p>This is assuming that the state always have the "edit" with <code>[]</code> and the regions <code>()</code>.</p> <p>The trick is to do a <a href="https://docs.python.org/3.3/library/stdtypes.html#str.split" rel="nofollow noreferrer">split</a> in "[" and "(" (as appropriate) and staying with the first part of the st...
python|csv|pandas|file-io|data-science
0
8,431
54,191,262
eig(a,b) in Python giving error "takes 1 positional argument but 2 were given"
<p>According to <a href="https://docs.scipy.org/doc/numpy-1.15.0/user/numpy-for-matlab-users.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.15.0/user/numpy-for-matlab-users.html</a>, the equivalent numpy expression for the MATLAB <code>[V,D]=eig(a,b)</code> is <code>V,D = np.linalg.eig(a,b)</code>. ...
<p>As you saw in the docs of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html#numpy.linalg.eig" rel="nofollow noreferrer"><code>numpy.linalg.eig</code></a>, it only accepts a single array argument and correspondingly it doesn't compute generalized eigenvalue problems.</p> <p>Fortunat...
python|matlab|numpy|eigenvalue|eigenvector
2
8,432
38,183,565
Remapping a pandas dataframe column using a dict
<p>I'm quite new to python so bear with me if this is obvious. </p> <p>I've got a column, 'age', in a dataframe, dff, containing the values 1 to 66. Each value corresponds to a key in the dictionary, di, and I'm trying to replace the values in the column with the corresponding values from the dictionary. </p> <p>I c...
<p>I think <code>.replace()</code> will do a better job. <code>.map()</code> fills <code>nans</code> if a particular match is not found. Purely depends on which is the desired output</p> <pre><code>dff['age'] = dff['age'].replace(di) </code></pre> <p>For example</p> <pre><code>dff = pd.DataFrame(['a', 'b', 'c', 'd',...
python|pandas|dataframe
0
8,433
66,235,484
pandas dataframe interpolate for Nans with groupby using window of discrete days of the year
<p>The small reproducible example below sets up a dataframe that is 100 yrs in length containing some randomly generated values. It then inserts 3 100-day stretches of missing values. Using this small example, I am attempting to sort out the pandas commands that will fill in the missing days using average values for t...
<p>This answers both parts</p> <ul> <li>build a DF <code>dfr</code> that is the calculation you want</li> <li><code>lambda</code> function returns a dict <code>{year:val, ...}</code></li> <li>make sure indexes are named in reasonable way</li> <li>expand out <code>dict</code> with <code>apply(pd.Series)</code></li> <li>...
python|pandas
1
8,434
66,140,256
How do I create a new column based on matching values in two different dataframes?
<p>I have two dataframes:</p> <p>df1 (a row for every event that happens in the game)</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Game</th> <th>Event Type</th> <th>Player</th> <th>Time</th> </tr> </thead> <tbody> <tr> <td>02/28/10</td> <td>USA vs Canada</td> <td>Faceoff</t...
<p>You can filter the <code>df1</code> for <code>shot</code>, then do a value count:</p> <pre><code>shots = df1.loc[df1['Event Type']=='shot', 'Player'].value_counts() df2['shots'] = df2['Player'].map(shots) # or using reindex with `fill_value` option # shots.reindex(df2['Player'], fill_value=0).values </code></pre> <...
python|pandas|dataframe|numpy
1
8,435
46,288,854
Determine change in values in a grouped dataframe
<p>Assume a dataset like this (which originally is read in from a .csv):</p> <pre><code>data = pd.DataFrame({'id': [1,2,3,1,2,3], 'time':['2017-01-01 12:00:00','2017-01-01 12:00:00','2017-01-01 12:00:00', '2017-01-01 12:10:00','2017-01-01 12:10:00','2017-01-01 12:10:00'],...
<p>I think you're looking for a <code>groupby</code> and comparison by <code>shift</code>;</p> <pre><code>data.groupby('id')['value'].agg(lambda x: (x != x.shift(-1)).sum() - 1) id 1 0 2 1 3 1 Name: value, dtype: int64 </code></pre>
python|pandas|dataframe|group-by|pandas-groupby
4
8,436
58,254,949
How to search all the values in a dataframe with a particular string
<p>I am actually stuck and want to search a Dataframe to find all the cells which includes a url link into a different dataframe i.e.</p> <p><strong>Input:</strong></p> <pre><code> A B C 0 1 2 https://123 1 https://432 333 qq 2 https://567 rt q4 </code...
<p>Try:</p> <pre><code>output_df = pd.dataframe(columns=['R']) for col in df.columns.tolist(): output_df = pd.concat([ouput_df, df.loc[df[col].str.contains('https'), col].rename({col: 'R'}, axis=1)]) </code></pre>
python|pandas|dataframe
0
8,437
58,244,542
Tensorflow LSTM stateful option not maintaining state between batches
<p>I am new to Tensorflow and wanted to understand the <a href="https://www.tensorflow.org/versions/r1.14/api_docs/python/tf/keras/layers/LSTM" rel="nofollow noreferrer">keras LSTM layer</a> so I wrote this test program to discern the behavior of the <code>stateful</code> option.</p> <pre class="lang-py prettyprint-ov...
<p>Everything appears to be working as intended - but the code's in need of much revision:</p> <ul> <li><code>Batch: 0</code> should be <code>Sample: 0</code>; your <code>batch_shape=(4, 5, 1)</code>, contains 4 <em>samples</em>, 5 <em>timesteps</em>, and 1 <em>feature</em> / <em>channel</em>. <code>I</code> in your c...
python|tensorflow|keras|lstm
3
8,438
58,309,845
Pandas re-arange flat hierarchy from bottom up to top down
<p>I am stuck with a challenge to re-arange a flat unbalanced hierarchy that is build bottom up, i.e. mapping a child element to parent and the parent's parent and so on, to a top down structure, i.e. starting from root and populating the structure downwards. Because the tree is unbalanced some end with a lower hierarc...
<p><code>set_index</code> and flip the values. Then make use of the <a href="https://stackoverflow.com/a/47898659/4333359"><code>justify</code></a> function that cs95 modified from Divakar.</p> <pre><code>df = df.set_index('Child').loc[:, ::-1] pd.DataFrame(justify(df.to_numpy(), invalid_val=np.NaN), in...
pandas
0
8,439
58,381,379
Looping over a dataframe and referencing a series
<p>I'm trying to iterate over a data frame in python and in my if statement I reference a couple of columns that happen to be a Series. When i run my code I get the following error:</p> <pre><code>The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p><strong>...
<p>You could try setting the value of <code>s['Swipe']</code> using <code>np.where</code> instead:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np s['Swipe'] = np.where((s['Template'] == 'detail page') &amp; (s['Template'] == s['Prev']), 1, 0) </code></pre>
python|pandas|loops|numpy|dataframe
2
8,440
58,267,188
Dataframe filter rows based on comparison with another dataframe
<p>I want to filter the one dataframe based on dates which falls in between dates of another dataframe.</p> <p>I've tried the following code:</p> <pre><code>df1 = pd.DataFrame({ 'Start':['1/1/2016', '1/1/2016', '1/1/2016', '1/1/2016', '1/1/2016'], 'end':['1/12/2016', '1/12/2016...
<p>You should have equal number of rows in both data frames for comparison.Here You have 5 rows in <code>df1</code> and 3 rows in <code>df2</code>.</p>
python|pandas|dataframe|filter
0
8,441
69,225,294
NumPy + PyTorch Tensor assignment
<p>lets assume we have a <code>tensor</code> representing an image of the shape <code>(910, 270, 1)</code> which assigned a number (some index) to each pixel with width=910 and height=270.</p> <p>We also have a <code>numpy</code> array of size <code>(N, 3)</code> which maps a 3-tuple to an index.</p> <p>I now want to c...
<p>Assuming you have <code>_colors</code>, and <code>indexed_image</code>. Something that ressembles to:</p> <pre><code>&gt;&gt;&gt; indexed_image = torch.randint(0, 10, (920, 270, 1)) &gt;&gt;&gt; _colors = np.random.randint(0, 255, (N, 3)) </code></pre> <p>A common way of converting a dense map to a RGB map is to lo...
python|arrays|numpy|pytorch|tensor
1
8,442
69,124,087
How to add a Column named Key into a dictionary of multiple dataframes
<p>Given a dictionary with multiple dataframes in it. How I can add a column to each dataframe with all the rows in that df filled with the key name'?</p> <p><a href="https://i.stack.imgur.com/tDSxA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tDSxA.png" alt="Dictionary Structure" /></a></p> <p>I ...
<p>I could do it with the method assign() in the DataFrames and then replacing the hole value in the dictionary, but I don't know in fact if it's this that you want...</p> <pre><code> for key, df in myDictDf.items(): myDictDf[key] = df.assign(sheet_name=[key for w in range(len(df.index))]) </code></pre> <p>To so...
python|pandas|dataframe|dictionary
0
8,443
44,424,836
Filtering a Pandas Dataframe with a boolean mask
<p>How do I drop all dataframe rows that don't match a pair of conditions.</p> <p>I did this:</p> <pre><code>df = df[ ! ((df['FVID'] == 0) &amp; (df['vstDelta'] == 0)) ] </code></pre> <p>but that was a syntax error. Hopefully it illustrates what I want to do, which is to drop all records containing these 2 conditi...
<p>You should use '~' instead of ! to get the negation of the condition.</p> <pre><code>df = df[~((df['FVID'] == 0) &amp; (df['vstDelta'] == 0))] </code></pre>
python|pandas|dataframe
5
8,444
44,643,137
How do you use PyTorch PackedSequence in code?
<p>Can someone give a full working code (not a snippet, but something that runs on a variable-length recurrent neural network) on how would you use the PackedSequence method in PyTorch?</p> <p>There do not seem to be any examples of this in the documentation, github, or the internet.</p> <p><a href="https://github.co...
<p>Not the most beautiful piece of code, but this is what I gathered for my personal use after going through PyTorch forums and docs. There can be certainly better ways to handle the sorting - restoring part, but I chose it to be in the network itself</p> <p>EDIT: See answer from @tusonggao which makes torch utils take...
machine-learning|torch|recurrent-neural-network|pytorch
7
8,445
44,413,793
How to do nested iterrows in Pandas
<p>I am trying to take the data from the endResult dataframe'issues' column and put it into the 'Sprint' column in df. When I run this bit of code, it returns a dataframe that has the third entry from the 'issues' column inserted into each row of the 'Sprint' column in df. </p> <pre><code>for i, r in endResult.iterrow...
<p>Because you are assigning everything to <code>j</code> in the first loop, you overwrite this value on each loop. Then you assign each value in sprint to the value of <code>j</code>, which is going to be the last value in <code>issues</code>.</p> <p>One simple change that fixes this is to change j to a list and appe...
python|pandas
0
8,446
60,873,683
Python - Filtering dataframe based on 3 columns potentially containing a sought after value
<p>I'm trying to take a query of recent customer transactions and match potential primary phone, cellphone and work phone matches against a particular list of customers I have.</p> <p>Essentially, I am taking one dataframe column (the list of customers I am trying to see if they had transactions recently) against the ...
<p>The thing here is that applying the <code>.isin()</code> method of a Series to another Series will return a boolean Series. </p> <p>In your example <code>transaction_data['phone']</code> is a Series, and also <code>df['phone']</code>. The return of this method will be a boolean Series containing the value <code>Tru...
python|pandas
0
8,447
60,880,095
Appending elements to a numpy nd array
<p>I have initialized a numpy nd array like the following</p> <pre><code>arr = np.zeros((6, 6)) </code></pre> <p>This empty array is passed as an input argument to a function,</p> <pre><code>def fun(arr): arr.append(1) # this works for arr = [] initialization return arr for i in range(0,12): fun(arr)...
<pre><code>In [523]: arr = np.zeros((6,6),int) In [524]: arr Out[524]: array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]...
python|arrays|numpy|append
0
8,448
71,788,845
Remove duplicate data based on the same unix time
<p>multiple data on the same date. I am trying to remove the multiple data and have the data aligned based on the unix time given, I tried using remove duplicate but its not working</p> <pre><code> time x y 0 1648598400000 233 6758 1 1648598400000 234 6758 2 1648598403000 553 8678 3 16485984...
<p><code>df[ ~df['time'].duplicated() ]</code> (with <code>~</code>) works for me.</p> <p>I use <code>io</code> only to simulate file - so everyone can copy it.</p> <pre><code>data = ''' time x y 0 1648598400000 233 6758 1 1648598400000 234 6758 2 1648598403000 553 8678 3 1648598404000 987 ...
python|pandas|dataframe
1
8,449
42,249,852
fetch values from csv with different number of columns in csv, numpy
<p>I am reading a csv with </p> <pre><code>numpy.genfromtxt(csv_name, delimiter=',') </code></pre> <p>but I am unable to do so because my csv contains different no of columns for each row.</p> <p>o/p:</p> <pre><code>ValueError: Some errors were detected Line #2 (got 8 columns instead of 7) Line #3 (got 8 columns...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html</a>, you can do it using the <code>filling_values</code> argument of <code>genfromtxt</code>.</p> <p>Otherwise, you could use this...
python|numpy
1
8,450
42,326,748
tensorflow on GPU: no known devices, despite cuda's deviceQuery returning a "PASS" result
<blockquote> <p>Note : this question was initially <a href="https://github.com/tensorflow/tensorflow/issues/7648#issuecomment-280866214" rel="noreferrer">asked on github</a>, but it was asked to be here instead</p> </blockquote> <p>I'm having trouble running tensorflow on gpu, and it does not seems to be the usual c...
<p>From the log output, it looks like you are running the CPU version of TensorFlow (PyPI: <a href="https://pypi.python.org/pypi/tensorflow" rel="noreferrer"><code>tensorflow</code></a>), and not the GPU version (PyPI: <a href="https://pypi.python.org/pypi/tensorflow-gpu" rel="noreferrer"><code>tensorflow-gpu</code></a...
tensorflow
78
8,451
69,750,333
How to show sliding windows of a numpy array with matplotlib FuncAnimation
<p>I am developing a simple algorithm for the detection of peaks in a signal. To troubleshoot my algorithm (and to showcase it), I would like to observe the signal and the detected peaks all along the signal duration (i.e. <code>20</code> minutes at <code>100Hz</code> = <code>20000</code> time-points).</p> <p>I thought...
<p>I've created an animation using the data you presented; I've extracted the data in 500 increments for 5000 data and updated the graph. To make it easy to extract the data, I have created an index of 500 rows, where id[0] is the start row, id<a href="https://i.stack.imgur.com/ofeJx.gif" rel="nofollow noreferrer">1</a...
python|numpy|matplotlib|visualization
2
8,452
69,812,787
How can I use weighted labels in the knn algorithm?
<p>I am working on my own implementation of the weighted knn algorithm.</p> <p>To simplify the logic, let's represent this as a predict method, which takes three parameters:</p> <p>indices - matrix of nearest j neighbors from the training sample for object i (i=1...n, n objects in total). [i, j] - index of object from...
<p>This should work:</p> <pre><code># compute inverses of distances # suppress division by 0 warning, # replace np.inf with a very large number with np.errstate(divide='ignore'): dinv = np.nan_to_num(1 / distances) # an array with distinct class labels distinct_labels = np.array(list(set(labels))) # an array ...
python|numpy|knn
1
8,453
69,694,093
GPU is not available for Pytorch
<p>I installed Anaconda, CUDA, and PyTorch today, and I can't access my GPU (RTX 2070) in torch. I followed all of installation steps and PyTorch works fine otherwise, but when I try to access the GPU either in shell or in script I get</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import torch &gt;&g...
<p>Downgrading CUDA to 10.2 and using PyTorch LTS 1.8.2 lets PyTorch use the GPU now. Per the comment from @talonmies it seems like PyTorch 1.10 doesn't support CUDA</p>
python|pytorch|anaconda|conda
1
8,454
70,019,359
Code completion problems using numpy with collections
<p>The code completion e.g. in Visual Studio shows me like in the screenshot below, what possibilities I have to code completion my code.</p> <p>In Python I started to use Linux and the software PyCharm to code now. My problem here is, that the code completion by far doesn't show me the possibilities I have to code com...
<p>1.Go to code menu 2. Go to completion sub menu of Code menu 3. The following code completion options are available A. Basic B SmartType C Cyclic Expand word D Cyclic Expand word Backward</p> <p>Pick each of one, then test to see if it gives you what you want e.g pick basic, then test, if not satisfied pick SmartType...
python|numpy|pycharm|code-completion
0
8,455
72,400,813
How to create a ranking variable/function for different periods in a panel data?
<p>I have a dataset, <code>df</code>, that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Code</th> <th>City</th> <th>State</th> <th>Population</th> <th>Quantity</th> <th>QTDPERCAPITA</th> </tr> </thead> <tbody> <tr> <td>2020-01</td> <td>11001</td> <td>Los An...
<p>You can use:</p> <pre><code># MinMax scaler: (rank - min) / (max - min) ranking = lambda x: (x.rank() - 1) / (len(x) - 1) # Rank between [0, 1] -&gt; 0 the lowest, 1 the highest df['RANKING'] = df.groupby('Date')['QTDPERCAPITA'].apply(ranking) # Rank between [1, 4149] -&gt; 1 the lowest, 4149 the highest # df['RAN...
python|pandas|ranking-functions
3
8,456
72,379,260
How to Read Huge and Valid JSON File Line by Line in Python
<p>I've been trying to use this code to read a huge JSON file (It contains 80+ million records) line by line:</p> <pre><code>import json import pandas as pd lines = [] with open('file_path','r') as f: for line in f: lines.append(json.loads(line)) df = pd.DataFrame(lines) </code></pr...
<p>Maybe are you searching this?</p> <pre><code>from pandas as pd df = pd.read_json('data/simple.json') </code></pre>
python|json|pandas
0
8,457
50,261,076
Using pandas to add list elements together
<p>I have the following array of dicts:</p> <pre><code>items = [ { 'FirstName': 'David', 'Language': ['en',] }, { 'FirstName': 'David', 'Language': ['fr',] }, { 'FirstName': 'David', 'Language': ['en',] }, { 'FirstName': 'Bob', 'Language': ['en',] } ] </code></pre> <p>Which I want to...
<p>Aggregate all with sum, <code>transform</code> values to set and then <code>to_dict()</code></p> <pre><code>&gt;&gt;&gt; df.groupby('FirstName').sum()["Language"].transform(set).reset_index().to_dict(orient='records') [{'FirstName': 'Bob', 'Language': {'en'}}, {'FirstName': 'David', 'Language': {'en', 'fr'}}] </c...
python|pandas
6
8,458
50,500,415
pandas new column from values in others
<p>I have a <code>df</code> that is populated with XY coordinates from different subjects. I want to create a new column that takes specified XY coordinates from those subjects. </p> <p>This is achieved when the name of any subject is highlighted in the <code>'Person'</code> column. This returns the XY coordinates of ...
<p>If you want to iterate through rows you can try:</p> <pre><code># iterate through rows for index, row in df.iterrows(): # check Event value for the row if row['Event'] == 'AA' : # update dataframe df.loc[index,('X', 'Y')] = AA print(df) </code></pre> <p>Result:</p> <pre><code> Event Joh...
python|pandas|indexing|apply
1
8,459
45,705,474
Transform with group by in Pandas
<p>I am creating a Dataframe </p> <pre><code>import pandas as pd df1 = pd.DataFrame( { "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } ) df1.groupby( ["City"] )['Name'].transform(l...
<p><strong>1. column aggregation</strong></p> <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>apply</code></a> with <code>,.join</code>, then for change order use double <code>[[]]</code>:</p> <pre><code>df = df...
python|python-3.x|pandas|pandas-groupby
3
8,460
45,312,698
RuntimeError: Attempted to use a closed Session in tflearn
<p>I want to train my model with tflearn, but i get the error showed above. Here is my training loop: BTW I splitted my training inputs in seperate numpy files</p> <pre><code>for i in range(EPOCHS): for file in filess: file = np.load(file) x = [] y = [] for a, b in file: ...
<p>I replaced <code>try/except</code> with <code>if os.path.exists(...)</code></p> <p>But <code>save(MODEL_NAME)</code> doesn't create one file with name <code>MODEL_NAME</code> but few files with names <code>"MODEL_NAME.meta"</code>, <code>"MODEL_NAME.index"</code>, <code>"MODEL_NAME.data-00000-of-00001"</code> so <c...
python|numpy|tflearn
2
8,461
62,741,474
Is there a way of summing specific columns if they exist in a list?
<p>I'm trying to lookup a column in df2 and only sum the columns in df1 that exist in the df2 column</p> <pre class="lang-py prettyprint-override"><code>df1 = London, New York, Paris, LA, Chicago 1000, 2000, 5000, 10000, 3000 df2 = US Cities New York Miami LA Chicago Seattle </code></pre> <p>result:</p> <pre class="l...
<p>Here you go:</p> <pre class="lang-py prettyprint-override"><code>df1['Sum of US Cities'] = df1.loc[:, df1.columns.isin(df2['US Cities'])].sum(axis=1) </code></pre> <p>Output</p> <pre><code> London New York Paris LA Chicago Sum of US Cities 0 1000 2000 5000 10000 3000 15000 </code...
python|pandas|list|sum|lookup
2
8,462
62,574,971
Convert horizontal values of a pandas dataframe into vertical values
<p>I created a pandas dataframe from a dictionary like this:</p> <pre><code> dictionary={'cat': [B1, B2,B3,B4,B5,B6,B7,B8,B9,B10], 'Dog': [c1, c2,c3], 'Bird': [d1,d2,d3,d4,d5]} </code></pre> <p><code>df = pd.DataFrame(dictionary.items(), columns=['ID_1','ID_match'])</code></p> <p>But I get a table looking like this:</p...
<p>This solution should work. The first .iloc is taking every other starting with the first column, and the second is taking every other starting with the second column.</p> <pre><code>df1 = df.iloc[:,::2].melt() df1 = df1['variable'] df2 = df.iloc[:,1::2].melt() df2 = df2['value'] df3 = pd.DataFrame({'col1':df1, 'col2...
python|pandas
0
8,463
62,532,042
Finding the Unique Arrays in an List of Arrays
<p>I have a list of arrays, say</p> <pre><code>List = [A,B,C,D,E,...] </code></pre> <p>where each A,B,C etc. is an nxn array.</p> <p>I wish to have the most efficient algorithm to find the unique nxn arrays in the list. That is, say if all entries of A and B are equal, then we discard one of them and generate the list<...
<p>Not sure if there is a faster way, but I think this should be pretty fast (using the built-in unique function of numpy and choosing axis=0 to look for nxn unique arrays. More detail in the <a href="https://numpy.org/devdocs/reference/generated/numpy.unique.html" rel="nofollow noreferrer">numpy doc</a>):</p> <pre><co...
python|arrays|list|numpy
1
8,464
54,349,604
Export Web Scraped Table to Excel
<p>I am having trouble getting pandas to export some web scraped data in the format I want.</p> <p>I want to visit each URL in <code>URLs</code> and get the various elements from that page and put them into an Excel spreadsheet with the column names specified. I then want to visit the next URL in <code>URLs</code> and...
<pre><code>masterlist = [] i = 0 for plant in URLs: sublist = [] soup = BeautifulSoup(urlopen(plant),'lxml') table = soup.find_all('td') for td in table: sublist.append(td.text) heading2 = soup.find_all('h2') for h2 in heading2: sublist.append(h2.text) para = soup.find_al...
python|excel|pandas
1
8,465
73,724,397
How to get the most repated elements in a dataframe/array
<p>I compiled a list of the top artists for every year across 14 years and I want to gather the top 7 for the 14 years combined so my idea was to gather them all in a dataframe then gather the most repeated artists for these years, but it didn't work out.</p> <pre><code>#Collecting the top 7 artists across the 14 years...
<p>You're very close - you just need to flatten your list of lists into a single list, then call value_counts:</p> <pre><code>artists_flat = [a for lst in artists for a in lst] pd.Series(artists_flat).value_counts().head(n) </code></pre> <p>Your current code is counting the occurrences of entire lists (as strings), rat...
python|python-3.x|pandas|dataframe|data-science
0
8,466
73,732,393
Combine excel files
<p>Can someone help how to get output in excel readable format? I am getting output as dataframe but #data is embedded a string in row number 2 and 3</p> <pre><code>import pandas as pd import os input_path = 'C:/Users/Admin/Downloads/Test/' output_path = 'C:/Users/Admin/Downloads/Test/' [enter image description here][...
<p>Your issue may be in using <code>sheet_name=None</code>. If any of the files have multiple sheets, a dictionary will be returned by pd.read_excel() with {'sheet_name':dataframe} format.</p> <p>To .append() with this, you can try something like this, using python's Dictionary.items() method:</p> <pre class="lang-py p...
python|excel|pandas|export-to-excel
0
8,467
73,626,874
How to search for substring in a pandas column from a given list efficiently?
<p>How can I search for substring in a column efficiently? If I use str.contains() method, it takes forever to search through the df.</p> <pre><code>frame = pd.DataFrame({'a' : ['111,222,333,444', '11,44', '222,333,444','666,777','555']}) mylist = ['111', '222', '444','555'] pattern = '|'.join(mylist) frame.loc[frame....
<p>I think this is better:</p> <pre><code>import pandas as pd import re pattern = '|'.join(mylist) def regex_filter(val): if val: mo = re.search(pattern,val) if mo: return True else: return False else: return re.search(pattern,val) frame = pd.Data...
python|python-3.x|pandas
0
8,468
71,215,627
geopandas shape files coordinates
<p>I'm currently trying to create geojson files from a set of shape files.</p> <pre><code>for shape_file in shape_files[1:]: print(fileName(shape_file)) shp = geopandas.read_file(shape_file) shp.to_crs(epsg = '4326') file_name = shape_file[0:len(shape_file) - len('.shp')] + '.geojson' print(file...
<p>The dtype to put the epsg in is incorrect. If you declare epsg it must be int. So your code should look like this:</p> <pre><code>shp.to_crs(epsg = 4326) </code></pre> <p>or</p> <pre><code>shp.to_crs('epsg:4326') </code></pre>
geopandas|shapefile|coordinate-systems
0
8,469
71,347,542
ValueError for sklearn, problem maybe caused by float32/float64 dtypes?
<p>So I want to check the feature importance in a dataset, but I get this error:</p> <pre><code>ValueError: Input contains NaN, infinity or a value too large for dtype('float32'). </code></pre> <p>I checked the dataset and fair enough there were nan values. So I added a line to drop all nan rows. Now there are no nan v...
<p>You are in the third case (large value) then in the second case (infinity) after the downcast:</p> <p>Demo:</p> <pre><code>import numpy as np a = np.array(np.finfo(numpy.float64).max) # array(1.79769313e+308) b = a.astype('float32') # array(inf, dtype=float32) </code></pre> <p>How to debug? Suppose the following a...
pandas|scikit-learn|sklearn-pandas
1
8,470
71,111,735
Python Pandas: Get number of NaN before first non NaN value
<p>I have the following DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>y</th> </tr> </thead> <tbody> <tr> <td>NaN</td> </tr> <tr> <td>NaN</td> </tr> <tr> <td>5</td> </tr> <tr> <td>NaN</td> </tr> <tr> <td>7</td> </tr> </tbody> </table> </div> <p>I would like to write a function t...
<p>You could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isna.html" rel="nofollow noreferrer"><code>isna</code></a> to get True/1 on the NaN values and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.cumprod.html" rel="nofollow noreferrer"><code>cumprod</code></a> to get ...
python|pandas|dataframe
3
8,471
71,139,210
Implementation of stack using numpy in python
<p>Like there are implementation of stack using array in c++ I was wondering if the same can be done in python using numpy stack? This was my take on it</p> <pre class="lang-py prettyprint-override"><code>from turtle import shape import numpy as np class stack: def __init__(self): self.stack = np.empty(sh...
<p>I messed around with the code for a while and I found a way to do it, and here it is:</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot; Time: 15:08 Date: 16-02-2022 &quot;&quot;&quot; from turtle import shape import numpy as np class stack: def __init__(self): self.stack = np.array...
python|arrays|numpy|stack
0
8,472
71,363,689
converting pandas dataframe to xarray dataset
<pre><code> Unnamed: 0 index datetime ... cVI Reg average_temp 0 0 2000-01-01 2000-01-01 ... NaN Central -5.883996 1 1 2000-01-02 2000-01-02 ... NaN Central -6.715087 2 2 2000-01-03 2000-01-03 ... NaN Central -6.074254...
<p>xarray will treat the index in a dataframe as the dimensions of the resulting dataset. A MultiIndex will be unstacked such that each level will form a new orthogonal dimension in the result.</p> <p>To convert your data to xarray, first set the datetime as index in pandas, with <code>df.set_index('datetime')</code>.<...
python|pandas|dataframe|python-xarray
1
8,473
71,300,132
Count of active items on day given start and stop date
<p>I have a dataframe with 2 columns similar to below.</p> <pre><code>+------+-------------+------------+ | id | start_date | stop_date | +------+-------------+------------+ | Foo | 2019-06-01 | 2019-06-03 | | Bar | 2019-06-07 | 2019-06-10 | | Pop | 2019-06-09 | 2019-06-11 | | Bob | 2019-06-13 |...
<p>You can do this:</p> <pre><code>df[[&quot;start_date&quot;, &quot;stop_date&quot;]] = df[[&quot;start_date&quot;, &quot;stop_date&quot;]].apply(pd.to_datetime) df = df.ffill(axis=1) df[&quot;days&quot;] = [ pd.date_range(s, e, freq=&quot;D&quot;) for s, e in zip(df[&quot;start_date&quot;], df[&quot;stop_date&qu...
python|pandas|datetime|date-range
2
8,474
52,240,476
Delete array from 2D array
<p>I have a 2D array like this:</p> <pre><code> [array([71, 35, 44, 0]) array([56, 55, 0]) array([32, 90, 11]) array([ 0, 3, 81, 9, 20]) array([0, 0]) array([0, 0]) array([0, 0]) array([ 5, 89])] </code></pre> <p>and I want to remove <code>[0, 0]</code></p> <p>I try to </p> <p><code>myarray = np.delete(myar...
<p>Use a list comprehension with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_equal.html" rel="nofollow noreferrer"><code>np.array_equal</code></a>:</p> <pre><code>&gt;&gt;&gt; [i for i in arr if not np.array_equal(i, [0,0])] </code></pre> <p></p> <pre><code>[array([71, 35, 44, 0]), ar...
python|python-3.x|numpy
3
8,475
52,166,594
How to use Padding in conv2d layer of specific size
<p>My input size image is : <code>256 * 256</code></p> <p>Conv2d Kernal Size : <code>4*4</code> and strides at <code>2*2</code>.</p> <p>The output will be <code>127*127</code>. I want to pass to Max Pool for this i want to apply padding to make it <code>128*128</code> so that pooling works well and pooling output wil...
<p><code>tf.layers.conv2d</code> has a <code>padding</code> parameter that you can use to do this. The default is <code>"valid"</code> which means no padding is done, so each convolution will slightly shrink the input. You can pass <code>padding="same"</code> instead. This will apply padding such that the output of the...
python|tensorflow|image-processing|padding|conv-neural-network
0
8,476
52,387,191
Reading large CSV file with Pandas freezes computer
<p>I am working with a relatively large CSV file in Python. I am using the pandas <code>read_csv</code> function to import it. The data is on a shared folder at work and around 25 GB.</p> <p>I have 2x8 GB RAM and an Intel Core i5 processor and using the juypter notebook. While loading the file the RAM Monitoring goes u...
<p>For large files, pandas can read them in chunks.</p> <pre><code>chunksize = 10 ** 6 for chunk in pd.read_csv(filename, chunksize=chunksize): process(chunk) </code></pre>
python|pandas|csv
4
8,477
52,129,486
Python: Find the nearest neighbor pairs in a list of point coordinates
<p>I have a list of coordinates. The first element of tuple is the slice number. The 2nd and 3rd are the xy coordinate. Now I want to find the set of points which are nearest. So If I have 6 slices, there must be a return list with pairs of 6 coordinates which belong to each other.</p> <p>Example dataset:</p> <pre><c...
<p>Here is some code, looking for the nearest point from one slice to the next:</p> <pre><code>import numpy as np from scipy.spatial import KDTree import matplotlib.pylab as plt def get_points_on_slice(i): return slices[ slices[:, 0] == i ][:, (1, 2)] # Look for the nearest point slice by slice: n_last_slice = i...
python|numpy|scipy
1
8,478
60,357,116
Command to print top 10 rows of python pandas dataframe without index?
<p><code>head()</code> prints the indexes. <code>dataframe.to_string(index=False,max_rows=10)</code> prints the first 5 and last 5 rows.</p>
<p>You should try this : </p> <pre><code>print(df.head(n=10).to_string(index=False)) </code></pre> <p>This will work because <code>df.head</code> return a <code>Dataframe</code> object so you can apply the <code>to_string</code> method to it and get rid of that index ^^.</p>
python|pandas|dataframe
5
8,479
60,585,948
Convert model.fit_generator to model.fit
<p>I have codes in the following, </p> <pre><code>train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( 'data/train', ...
<p>You just have to change <code>model.fit_generator()</code> to <code>model.fit()</code>.</p> <p>As of TensorFlow 2.1, <code>model.fit()</code> also accepts generators as input. As simple as that.</p> <p>From TensorFlow's official documentation: </p> <blockquote> <p>Warning: THIS FUNCTION IS DEPRECATED. It will b...
keras|tensorflow2.0|tensorflow2.x
6
8,480
32,333,179
Remove seconds from date Pandas
<p>I have a dataframe that contains a column with a date (StartTime) in the following format: <strong>28-7-2015 0:09:00</strong> the same dataframe contains also a column that contains the number of seconds (SetupDuration1). </p> <p>I would like to create a new column that subtracts the number of seconds from the dat...
<p><code>apply</code> a lambda to convert to timedelta and then subtract:</p> <pre><code>In [88]: df = pd.DataFrame({'StartTime':pd.date_range(start=dt.datetime(2015,1,1), end = dt.datetime(2015,2,1)), 'SetupDuration1':np.random.randint(0, 59, size=32)}) df Out[88]: SetupDuration1 StartTime 0 14 20...
python|pandas
1
8,481
40,706,338
Adding extra entry in a multi-indexed pandas dataframe from another multi-indexed pandas dataframe
<p>I have a multi-indexed pandas dataframe that I have used the <code>groupby</code> method followed by the <code>describe</code> method on to give me the following:</p> <pre><code> grouped= self.HK_data.groupby(level=[0,1]) summary= grouped.describe() </code></pre> <p>which gives: </p> <pre><code>Antibody ...
<p>I think you first add third level of <code>MultiIndex</code> , assign new index by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_tuples.html" rel="nofollow noreferrer"><code>MultiIndex.from_tuples</code></a> and last use <a href="http://pandas.pydata.org/pandas-docs/stable/gen...
python|pandas|multi-index
2
8,482
40,372,026
Importing TensorFlow graph fails for uninitialized variables
<p>I'm trying to export the multi layer perceptron example as a .pb graph. In order to do it, I have named the input variables and output operation and added the following line:</p> <pre><code>tf.train.write_graph(sess.graph_def, "./", "graph.pb", False) </code></pre> <p>To import, I did the following:</p> <pre><cod...
<p>TensorFlow splits saving the Graph definition and the Variable values in different files (graph and checkpoint respectively).</p> <p>You want to use the TF Saver. </p> <p>See this answer for details: <a href="https://stackoverflow.com/a/33762168/4120005">https://stackoverflow.com/a/33762168/4120005</a></p> <p>Or ...
python|tensorflow
2
8,483
62,009,696
How to get the row position based on column value if dataframe has been resorted?
<p>My dataframe has been resorted so the index values have lost their sequence.</p> <p>In this example below, when I select for df_ranking.Ticker == 'WRB ', I want to get 0 instead of 478.</p> <pre><code>In [113]: df_ranking.head() Out[113]: Ticker TrendScoreStr TrendScoreNum 478 WRB GCAGA 200010000...
<p>Do this:</p> <pre><code>In [1788]: df_ranking.reset_index(drop=True, inplace=True) In [1789]: df_ranking Out[1789]: Ticker TrendScoreStr TrendScoreNum 0 WRB GCAGA 2000100000200 1 ISRG CMAMA 2000100000000 2 ALGN DGAGA 2000001000200 3 CI...
python|pandas|dataframe
1
8,484
61,850,718
How to fill multiple values into One Column in pandas dataframe? (without using strings) Python
<p>so far I managed to do this by using a string and splitting it up later.</p> <pre><code>print(df) a b c z 0 0 0 0 "23,8,100" 1 1 1 1 "23,2,100" 2 2 2 2 "1,8,100" 3 3 3 3 "23,5,300" 4 4 4 4 "23,8,7" # converting column to list x_lis...
<p>IIUC you want to convert string to list<br> First, remove extra <code>"</code> quotes using <code>strip</code> then split string into list </p> <pre class="lang-py prettyprint-override"><code>df.z.str.strip('"').str.split(',') 0 [23, 8, 100] 1 [23, 2, 100] 2 [1, 8, 100] 3 [23, 5, 300] 4 [23, 8, 7]...
python|arrays|pandas|list|multiple-columns
0
8,485
57,846,434
Difference between sample step and time step in LSTM (Keras)
<p>I'm trying to understand how the state progresses in an LSTM-layer. If I have the following code</p> <pre class="lang-py prettyprint-override"><code>model = Sequential() model.add(LSTM(2, return_sequences=True,input_shape=(4,2),stateful=False,batch_size=4)) yp=model.predict(np.array([ [[0,0],[0,1],[0,0],[1,1]], ...
<p>Your input is an array of <code>shape=(4,4,2)</code>, where the first 4 is batch size (4 samples), second 4 is time_step, and the last 2 is the input_dim of each time_step. </p> <h2>Difference between sample step and time step in LSTM</h2> <p>Each sample can have multiple time steps, or even different time steps ...
tensorflow|keras|lstm
0
8,486
57,828,028
How can I add a column of one data frame to another based on the nearest identifier?
<p>Problem:</p> <ol> <li><p>I have a data frame <code>foo</code> that contains measurements and a <code>common_step</code> column, which contains integers indicating when each row was measured.</p></li> <li><p>I have a second data frame that also contains a <code>common_step</code> column and a <code>bar_step</code> c...
<p>As @QuangHoang suggested in the comment, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer">merge_asof</a> does this. Moreover, the second data frame should contain no other columns to not interfere with existing columns in the first one:</p> <pre c...
python|pandas
0
8,487
58,049,454
Is this TF training curve overfitting or underfitting?
<p>In the case of overfitting, to my knowledge the <code>val_loss</code> has to soar as opposed to the <code>train_loss</code>. But how about the case below (<code>val_loss</code> remains low)? Is this model underfitting horribly? Or is it some completely different case? Previously my models would overfit badly so I ad...
<p>This is neither overfitting nor underfitting. Some people refer to it as <em><a href="https://stats.stackexchange.com/questions/187335/validation-error-less-than-training-error">Unknown fit</a></em>. Validation &lt;&lt; training loss happens when you apply regularization (L1, L2, Dropout, ...) in keras because they ...
python|tensorflow|keras|deep-learning
2
8,488
58,082,903
python Panda float number get rounded while converting to string
<p>I have this CSV file</p> <pre><code>id,adset_id,source 1,,google 2,23843814084680281,facebook 3,,google 4,23843814088700279,facebook 5,23843704830370464,facebook </code></pre> <p>My problem is when I am trying to read it with panda since I can not pass the schema panda infer the schema for <code>adset_id</code> co...
<p>Within <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>pd.read_csv</code></a>. Look at the <code>dtype</code> argument. You can set a dictionary of dtypes to ensure it is read as a string.</p> <pre><code>df = pd.read_csv('PATH_TO_CSV.csv', dt...
python|pandas|csv|scientific-notation
1
8,489
57,777,003
Column <x> has dtype object, cannot use method 'nsmallest' with this dtype
<p>Any query I try on my table complains that</p> <pre><code>Column 'time' has dtype object, cannot use method 'nsmallest' with this dtype </code></pre> <p>However, when I look at the table source that I queried, the schema reports types of long. In this case, I am querying Treasure Data.</p> <p>How then do I sort m...
<p>You sort it by:</p> <pre><code>df.sort_values(['time'], inplace=True) </code></pre> <p>If you use:</p> <pre><code>df['time'].sort_values(ascending=True).head(n) </code></pre> <p>You should get the first n smallest values as well.</p>
pandas|dataframe
1
8,490
57,786,652
pandas merge two dataframe to form a multiindex
<p>I'm playing around with Pandas to see if I can do some stock calculation better/faster than with other tools. If I have a single stock it's easy to create daily calculation L</p> <pre><code>df['mystuff'] = df['Close']+1 </code></pre> <p>If I download more than a ticker it gets complicated: </p> <pre><code>df = df...
<p>This is not exactly the same but it returns Multiindex you can use as in the <code>a_g</code> case</p> <pre class="lang-py prettyprint-override"><code>import pandas_datareader.data as web import pandas as pd from datetime import datetime start = datetime(2019, 7, 1) end = datetime(2019, 8, 31) out = [] for tick in...
pandas|pandas-datareader
1
8,491
36,715,067
Scipy's leastsq with complex numbers
<p>I'm trying to use scipy.optimize.leastsq with complex numbers. I know there are some questions about this already but I still can't get my simple example working, which is complaining about casting from complex to real numbers.</p> <p>If I did it right the solution to the below should be <code>x=[1+1j,2j]</code>:</...
<p>Since <code>leastsq()</code> can only accept real numbers, you need to use <code>.view()</code> method to convert between real array and complex array.</p> <pre><code>import numpy as np from scipy.optimize import leastsq def cost_cpl(x, A, b): return (np.dot(A, x.view(np.complex128)) - b).view(np.double) A = ...
python|numpy|scipy|complex-numbers|least-squares
3
8,492
54,816,225
Multi-hot labels encoding
<p>I'm new to Tensorflow. I have a image dataset with several labels for one image. As far as I understand, I need to use <code>tf.losses.sigmoid_cross_entropy()</code>. I tried to apply <code>tf.one_hot</code> to labels but when I try to pass them into loss function I get error, shapes incompatible. How can I fix this...
<p>You're right about <code>tf.losses.sigmoid_cross_entropy</code>. All you need to do is wrap <code>tf.one_hot</code> with <code>tf.reduce_max</code> to reduce dimensionality like this. </p> <pre><code>tf.reduce_max(tf.one_hot(labels, num_classes, dtype=tf.int32), axis=0) </code></pre> <p>That should return tensor o...
python|tensorflow
3
8,493
54,915,755
ANSI codes not working in a ndarray of strings
<p>I think the best way to explain my problem is to just show it:</p> <pre><code>import numpy as np coloured_letters = np.ndarray(shape=(2, 2), dtype="&lt;U100") print("\033[1;32;40m A test \033[30m") def fill(ndarray): y = 0 x = 0 while y &lt; 2: while x &lt; 2: ndarray[y][x] = "\033...
<p>Numpy is storing exactly the values you want. However, when you print the variable <code>coloured_letters</code> numpy calls the <code>__repr__</code> or <code>__str__</code> function to convert the string into a printable representation. This means that it will translate each string into something the terminal can ...
python|numpy
1
8,494
54,732,675
Python Keras Prediction returning nan
<p>I am having problems with understanding how Keras works with data and why my model is not working accordingly. I am trying to build small model that could predict cities based on input of longitude and latitude.</p> <p>What i would like to see is when i make a prediction, for example, the first index of cities arra...
<p>Not clear what is <code>train_labels</code>. If it's the same as <code>labels</code> then you'll need to have output of the last layer to be <code>21</code> and not <code>20</code>, since in keras labels start from <code>0</code>. Or you can redefine your labels to be from <code>0</code> to <code>19</code>. Otherwis...
python|tensorflow|keras|neural-network
4
8,495
49,523,140
Spectral norm 2x2 matrix in tensorflow
<p>I've got a 2x2 matrix defined by the variables <code>J00, J01, J10, J11</code> coming in from other inputs. Since the matrix is small, I was able to compute the spectral norm by first computing the trace and determinant</p> <pre><code>J_T = tf.reduce_sum([J00, J11]) J_ad = tf.reduce_prod([J00, J11]) J_cb = tf.reduc...
<p>The spectral norm of a matrix <code>J</code> equals the largest <a href="https://en.wikipedia.org/wiki/Singular-value_decomposition" rel="nofollow noreferrer">singular value</a> of the matrix.</p> <p>Therefore you can use <a href="https://www.tensorflow.org/api_docs/python/tf/svd" rel="nofollow noreferrer"><code>t...
python|matrix|tensorflow
4
8,496
27,955,727
How to display just the mesh of meshgrid
<p>The following four lines will create a rectangular meshgrid with bottom-left corner as (-5,-5) and top-right corner as (5,5). The width of each cell in the meshgrid will be 0.55 and height will 0.5. Is it possible to just display this created mesh in python? That is, without superimposing on it any other plot of a f...
<p>You can use <code>matplotlib</code>'s <code>plot</code> to put a point at each point of the grid. <img src="https://i.stack.imgur.com/dJoX0.png" alt="enter image description here"></p> <pre><code>plt.plot(xx, yy, ".k") plt.show() </code></pre> <p>Here, this is actually plotting each column as a separate plot, and ...
numpy|matplotlib
7
8,497
28,199,056
Pandas: Conver all strings in column to 1
<p>I have a df with a column df.open. I want to check this column for strings. If there's a string, I'd like to convert it to a 1. There are already a lot of 1s and 0s in the column. </p> <p>So, suppose the values in the column are as follows: &lt;0,0,1,0,text,1,open,0,0,xyz,1>. I'd like to go through the column and t...
<p>Convert all to boolean then to int:</p> <pre><code>df.open = df.open.astype(bool).astype(int) </code></pre> <p><code>1</code> and any non-empty text is <code>True</code>, <code>0</code> is <code>False</code>.</p> <p><code>True</code> is <code>1</code>, <code>False</code> is <code>0</code>.</p>
python|pandas
2
8,498
28,174,580
Sort csv-data while reading, using pandas
<p>I have a csv-file with entries like this:</p> <pre><code>1,2014 1 1 0 1,5 2,2014 1 1 0 1,5 3,2014 1 1 0 1,5 4,2014 1 1 0 1,6 5,2014 1 1 0 1,6 6,2014 1 1 0 1,12 7,2014 1 1 0 1,17 8,2014 5 7 1 5,4 </code></pre> <p>The first column is the ID, the second the arrival-date (example of last entry: may 07, 1:05 a.m.) and ...
<p>OK, the following shows you can convert the date times and then shows how to add the minutes:</p> <pre><code>In [79]: df['Arrival_Date'] = pd.to_datetime(df['Arrival_Date'], format='%Y %m %d %H %M') df Out[79]: ID Arrival_Date Duration 0 1 2014-01-01 00:01:00 5 1 2 2014-01-01 00:01:00 ...
python|sorting|csv|pandas
0
8,499
73,387,241
Automatically extracting data from csv file into specific matrix position
<p>I have a rather large csv file that I need the program to read, then input the data into the correct position of a zero matrix. Sample of csv block (also attached file):</p> <pre><code> Sector,Service,Data_Point Bio,Electricity NonEmitting,0 NEElectricity,Electricity NonEmitting,0.5 RE,Electricity NonEmitting,0 Elec...
<p><a href="https://i.stack.imgur.com/XrRzb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XrRzb.png" alt="Matrix" /></a></p> <p>Is that the kind of matrix u wanted to create?</p> <p>I created this matrix without pandas with the following source code:</p> <pre><code>import csv import numpy as np ro...
python|python-3.x|pandas|numpy|csv
2