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
356,500
58,295,207
Why not apply one hot encoder , knowing that there is no error during running file?
<p>I want to apply one hot encoding to one column which is "drive_wheels" However, on running there is no error and no change to the dataset! Is there any error in the code?</p> <pre><code>import pandas as pd import numpy as np df = pd.read_csv('onehotencoding.csv') df.head() obj_df = df.select_dtypes(include=['o...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html#pandas-get-dummies" rel="nofollow noreferrer">pd.get_dummies()</a> doesn't have an <code>inplace</code> switch. Therefore, you need to join the resulting DataFrame to your original:</p> <pre><code>dummies = pd.get_dummies(ob...
python|pandas
1
356,501
58,252,742
Re-Assign Maximum Values in a Pandas DataFrame
<p>I have a DataFrame that looks like this:</p> <pre><code>id OUTCOME A 0 A 1 A 0 B 0 B 0 B 0 C 0 C 1 C 1 </code></pre> <p>How can I re-assign the outcome values so that they are equal to the maximum value for each group? In other words, the outcome should look like this:</p> <pre><code>id...
<p>You can first group by the <code>'id</code>' column, and then perform a <code>.transform(..)</code> on the <code>OUTCOME</code> column:</p> <pre><code>df['OUTCOME'] = df.groupby('id')['OUTCOME'].transform('max') </code></pre> <p>We then obtain:</p> <pre><code>&gt;&gt;&gt; df id OUTCOME 0 A 1 1 A ...
python|pandas|pandas-groupby
0
356,502
58,326,360
Split a column in pandas dataframe based on dot
<p>I went through similar questions but could not solve my problem. A part of my dataframe looks like this:</p> <pre><code> Index Character Top 10 by edits Top 10 by added text 780 NaN Viradha David G Brault · 8 (40%) David G Brault · 1,915 (81.4%) 781 NaN Viradha Wiki-uk ·...
<p>The dot in the 'Top 10 by added text' column is not a period but is rather a dot character whereas you are trying to split by a period in your code. Try changing one or the other to match. </p>
python|pandas|split
2
356,503
58,434,832
Aggregate pandas Series/DataFrame with MultiLevel Index And Insert Result
<p>Given a pandas <code>Series</code> (or <code>DataFrame</code>) with a multi-level index:</p> <pre><code>name month A 2019-05 8 2019-06 8 2019-07 3 2019-08 4 2019-09 7 B 2019-06 ...
<p>Here is one way use <code>unstack</code> </p> <pre><code>s=df['count'].unstack() s['sum']=s.sum(1) s=s.stack() name month A 2019-05 8.0 2019-06 8.0 2019-07 3.0 2019-08 4.0 2019-09 7.0 sum 30.0 B 2019-06 10.0 2019-07 5.0 2019-08 ...
python|pandas|dataframe
1
356,504
58,190,542
Can someone help me understand what .index is doing in this code?
<p>I have the following code:</p> <pre><code>print(df.drop(df[df['Quantity'] == 0].index).rename(columns={'Weight': 'Weight (oz.)'})) </code></pre> <p>I understand what query is trying to do, but I'm lost at why you need to add the " .index " portion?</p> <p>What is .index doing in this particular code? </p> <p>For...
<p>The <code>DataFrame.index</code> is the index of each record in your dataframe. It is unique to each row even if two rows have the same data in each column. <code>DataFrame.drop</code> takes the <code>index : single label or list-like</code> and drops those rows that match the index.</p> <p>So from the code above, ...
python|pandas|indexing
0
356,505
58,298,981
Most efficient way to generate a large array of (x,y,z) coordinates
<p>I'm generating coordinates of a bi-cone model in spherical coordinates. I'm using a series of nested for loops, as show here:</p> <pre><code>theta_in = 30.0 * np.pi/180.0 theta_out = 60.0 * np.pi/180.0 phi = 2*np.pi # rotation R = 1.0 sampling = 100 theta = np.linspace(theta_in,theta_out,sampling) phi = ...
<p>Create open grids off those inputs and then perform the same operations -</p> <pre><code>RI,PI,TI = np.ix_(r,phi,theta) # get open grids X = RI*np.cos(PI)*np.sin(TI) Y = RI*np.sin(PI)*np.sin(TI) Z = np.repeat(RI*np.cos(TI),sampling,axis=1) </code></pre> <p>Alternative #1 : Those open grids could also be...
python|arrays|numpy
3
356,506
58,288,465
The equivalent of tf.contrib.image.transform in tensorflow 2.0?
<p>What is the equivalent of <code>tf.contrib.image.transform</code> in <code>tensorflow 2.0</code>? When I use the <code>tf_upgrade_v2</code> conversion script, I get the error:</p> <pre><code>ERROR: Using member tf.contrib.image.transform in deprecated module tf.contrib. tf.contrib.image.transform cannot be converte...
<p>There is no equivalent. Some of the ops are implemented in the tensorflow addons though which is only available in Linux not Windows for now.</p> <p>Here is the link to tensorflow addones: <a href="https://github.com/tensorflow/addons" rel="nofollow noreferrer">https://github.com/tensorflow/addons</a></p> <p>Here ...
python|tensorflow|tensorflow2.0
0
356,507
58,326,771
How to sum the time-differenced values in a dataframe without compromissing the format HH:MM:SS?
<p><a href="https://stackoverflow.com/questions/2780897/python-summing-up-time">Python summing up time</a> - In this link, the answers are long coded and also using a small list of time values. However, I would like to learn a pythonic way to sum the time values in a data-frame but i can't seem to figure out yet. Can s...
<p>I don't see why your solution wouldn't work. Maybe you haven't converted the datetime to the proper type:</p> <pre><code>df['in'] = pd.to_datetime(df['in'], format="%Y/%m/%d %H:%M") # format needs adjustment </code></pre> <p>If it still doesnt work, please provide the rest of the code or some raw data.</p>
python|python-3.x|pandas|datetime|pandas-groupby
0
356,508
58,441,694
Most efficient way to split and perform function on pandas data frame
<p>I have been given a data frame that contains two measurements of a value (A and B) in rows and each column represents the measurements for sample.</p> <p>Example below: </p> <pre><code>ID S1 S2 S3 M1_A 1 2 3 M1_B 3 2 1 M2_A 1 2 3 M2_B 3 2 1 </code></pre> <p>I need to calculate the ratio of B to A+B [i.e. (B/...
<p>This sounds like a classic groupby-aggregate problem. Pandas can handle the underscore in the ID column easily as well.</p> <pre><code>df['ID'] = df['ID'].str.split('_').str[0] df = df.groupby('ID').agg(lambda x: x.values[-1]/x.sum()) print(df) S1 S2 S3 ID M1 0.75 0.5 0.25 M2 0.75 ...
python|pandas|dataframe
2
356,509
58,404,293
Python DBSCAN clustering with periodic boundary conditions
<p>Im a noob, probably im doing things too big for me, but i need this for my tesis, please forgive my ignorance. My goal is to do clustering on 3D points, using sklearn.cluster.DBSCAN, and implement periodic boundary condition only on x,y. The easiest way that I have found is to use the scipy function <em>pdist</em> o...
<p>Squreform produces a condensed distance matrix in a one-dimensional array. That is a more memory efficient representation - but only if you use it from the beginning, not convert to it later.</p> <p>Anyway, this form is only used by scipy, not by sklearn. But because python does not have a strong type system, it ca...
python|numpy|scikit-learn|cluster-analysis|dbscan
0
356,510
58,219,683
How to recognize two different objects with the similar shape, but different size
<p>I am using Mask-RCNN neural network. I retrained my network to detect and mask wheels of die-cast toy cars. I am using images, which present the side of the car (left or right).</p> <p>Sometimes the cars have different sizes of the wheels like presented on the image below. The front wheels are much smaller than rea...
<p>Mask-RCNN can segment each instance of object separately irrespective of size of object. It does not classify object based on perspective, it will classify both wheels as wheels.</p> <p>If you train model with two classes like front and rear wheel it will work fine when the condition is true, but when the wheels wi...
tensorflow|machine-learning|keras|neural-network|computer-vision
0
356,511
58,399,766
Python/Pandas - Rearrange string from column value
<p>I would need to rearrange the column value on column: "Quarter" . Expected output should be as in column:"new_Quarter"</p> <p><a href="https://i.stack.imgur.com/Dok9i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dok9i.png" alt="enter image description here"></a></p> <p>I got the column:"Quart...
<p>You may use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>strftime</code></a></p> <pre><code>df['new_Quarter'] = df.Quarter.dt.strftime('Q%q %y') </code></pre> <p>As a side note, the column <code>Quarter</code> can also be simply...
python|pandas|date
3
356,512
58,253,003
Deriving the structure of a pytorch network
<p>For my use case, I require to be able to take a pytorch module and interpret the sequence of layers in the module so that I can create a “connection” between the layers in some file format. Now let’s say I have a simple module as below</p> <pre><code>class mymodel(nn.Module): def __init__(self, input_channels):...
<p>The information you are looking for is not stored in the <code>nn.Module</code>, but rather in the <code>grad_fn</code> attribute of the output tensor:</p> <pre class="lang-py prettyprint-override"><code>model = mymodel(channels) pred = model(torch.rand((1, channels)) pred.grad_fn # all the information is in the c...
python|neural-network|pytorch|tensor
2
356,513
58,387,271
Is numpy.array() equivalent to numpy.stack(..., axis=0)?
<p>I made my self an example:</p> <pre><code>import numpy as np arrays = [np.random.rand(3,4) for _ in range(10)] arr1 = np.array(arrays) print(arr1.shape) arr2 = np.stack(arrays, axis=0) print(arr2.shape) </code></pre> <p>I found that arr1 and arr2 have the same shape and content. So are these two methods (np.array(...
<p>In general, you should get something similar from the two, but there will be some edge cases. For example, passing ragged lists to <code>np.array</code> will give an <code>np.array</code> of lists, but <code>np.stack</code> will raise an exception:</p> <pre><code>In [119]: np.stack([[1,2], [4,5,6]], axis=0) -------...
python|arrays|numpy
3
356,514
58,567,446
get_weights is slow with every iteration
<p>I'm computing gradients from a private network and applying them to another master network. Then I'm copying the weights for the master to the private (it sounds redundant but bear with me). The problem is that with every iteration get_weights becomes slower and I even run out of memory. </p> <pre><code> def wo...
<p>This would typically happen when you dynamically add new nodes to the graph. Example situation:</p> <pre><code>while True: grad_op = optimizer.get_gradients() session.run([gradients]) </code></pre> <p>Where get_gradients will add new operations to the graph. Operations returned by get_gradients would not c...
tensorflow|keras|python-3.7|tensorflow2.0
2
356,515
58,567,884
How to handle pandas KeyError in a for loop?
<p>I wrote the following code in a for loop to handle the pandas KeyError I met, but it seemed that I couldn't use a continue statement and except keyword in this block. How could I fix it? </p> <p>Originally, I would like to raise an exception to show those keys that are not in the table and let the for loop continue...
<p>If you raise an error, execution will stop. You can put your continue statement in the except block. That will allow you to continue going through the loop. Just make sure to print out/log out whatever information you need before hitting the continue statement.</p> <pre><code>for i in range(1000): # do somethin...
python|pandas|dataframe
1
356,516
58,471,669
SUMIFS formula in Pandas Python
<p>I work in a logistics company and we do B2C deliveries for our client. So we have a rate card in a form of a table and list of deliveries/ transaction, the weight of the package and the location where it was delivered. </p> <p>I have seen a lot of SUMIFS question being answered here but is very different from the o...
<p>This is <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> on <code>category</code> and <code>island</code> and then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nof...
python|pandas|data-analysis
2
356,517
58,357,486
tflearn with tensorflow 2.0
<p>I can't import tflearn with TensorFlow 2.0</p> <pre><code>Python 3.7.4 (v3.7.4:e09359112e, Jul 8 2019, 14:54:52) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; import tflearn Traceback (most recent call last): File "/Library/Framework...
<p>As of today, <a href="https://pypi.org/project/tflearn/" rel="nofollow noreferrer"><code>tflearn</code></a> (v0.3.2) is not TensorFlow 2.0 ready, and specifically requires TF 1.x. I'm sure it will get updated at some point but for now, if you need tflearn, use TF 1.</p> <hr /> <p>I get a different error: <code>Modul...
python|python-3.x|tensorflow|tflearn
6
356,518
58,438,243
Python Pandas : Return column header/name where values equal the other in the dataframe
<p>I am trying to get the column header location(s) where the value in the last column equals a value in any of the other columns. This should be appended as a new column. Assuming I have the dataframe:</p> <pre><code> category color size max_value a [2, 1] [1,1,1] [1,1,1] ...
<p>You can do the comparison after dropping down to <code>numpy</code></p> <pre><code>m = df.iloc[:, :-1].to_numpy() == df.max_value.to_numpy()[:, None] #array([[False, True, True], # [ True, False, False], # [False, True, False]]) df['matched_cols'] = [', '.join(df.columns[:-1][x]) for x in m] # cate...
python|pandas
2
356,519
58,538,831
1D CNN in Keras: Flattening from pooled features to dense layer raises ValueError
<p>I have the following CNN model defined. it is expecting a 1D vector input of length 501.</p> <pre><code>model = ml.models.Sequential() model.add(ml.layers.Conv1D(filters=NUMBER_OF_FILTERS, kernel_size=KERNEL_SIZE, activation=ACTIVATION, input_shape=(None, 501))) model.add(ml.layers.MaxPooling1D(pool_size=POOL_SIZE,...
<p>I have figured out the solution. I was not correctly defining the input_shape of the Conv1D Layer, it should instead be:</p> <pre><code>model.add(ml.layers.Conv1D(filters=NUMBER_OF_FILTERS, kernel_size=KERNEL_SIZE, activation=ACTIVATION, input_shape=(501, 1))) </code></pre>
python|tensorflow|keras
0
356,520
58,305,598
Using tensorflow_transform with tensorflow 2.0
<p>After installing tensorflow 2 and tensorflow_transform, when importing tensorflow_transform I get the error: <code>from tensorflow.contrib.boosted_trees.python.ops import gen_quantile_ops ModuleNotFoundError: No module named 'tensorflow.contrib'</code></p> <p>So it seems that tensorflow_transform is not yet on...
<p>All currently released versions of tensorflow-transform don't support TF 2.0. See this table here: <a href="https://github.com/tensorflow/transform/blob/master/README.md#compatible-versions" rel="nofollow noreferrer">https://github.com/tensorflow/transform/blob/master/README.md#compatible-versions</a></p> <p>The la...
tensorflow2.0|tensorflow-transform
0
356,521
58,578,641
panda: csv to dictionary
<p>I have a csv file in following format:</p> <blockquote> <p>id, category</p> <p>1, apple</p> <p>2, orange</p> <p>3, banana</p> </blockquote> <p>I need to read this file and populate a dictionary which has ids as key and categories as value.</p> <p>I am trying to use panda, but its to_dict function us returning a dict...
<p>You can create index by first column and then convert Series <code>df['category']</code> to dictionary:</p> <pre><code>df = pd.read_csv('file.csv', index_col=0) d = df['category'].to_dict() </code></pre> <p>Or if only 2 columns csv is possible create Series by <code>index_col=0</code> and <code>squeeze=True</code...
python|pandas
2
356,522
58,311,944
Python: Locate the max value of a column and pick up the value of other column in the same row
<p>I have next data frame with two columns:</p> <pre><code>Idx =[1,2,3,4,5] Values =[7,-2,-1,10,5] lists = list(zip(Idx, Values)) dfsr = pd.DataFrame(lists, columns = ['Idx', 'Values']) dfsr </code></pre> <p>This generates the next DataFrame </p> <pre><code> Idx Values 0 1 7 1 2 -2 2 3 -1 3 4 10...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; MVI = dfsr.loc[dfsr.Values == dfsr.Values.max(), 'Idx'] &gt;&gt;&gt; MVI 3 4 Name: Idx, dtype: int64 </code></pre> <p>Alternatively, if you just want the object itself (not <code>pandas.Series</code> object):</p> <pre class="lang-py prettypr...
python-3.x|pandas
3
356,523
58,308,175
I want to create a pandas DF based on 2 np.ranges tied together
<p>I want to create a pandas DF with 2 columns based on 2 np.arrays.</p> <p>in the end it it should look like a dissolved x-y-matrix, since i have to test all X and Y combinations</p> <p>example should be a DF with columns "X" and "Y"</p> <pre><code> X Y ---------- -5 -3 0 -3 5 -3 -5 0 0 ...
<p>Can you use <code>itertools.product</code> and <code>from_records</code>:</p> <pre><code>from itertools import product </code></pre> <p><strike> df = pd.DataFrame.from_records([i for i in product(a,b)])</strike><br> Actually, you don't need the list comprehension </p> <pre><code>df = pd.DataFrame.from_rec...
python|pandas|numpy
1
356,524
58,546,991
Set Field in Column to 0 Based on Two Column Values Being Equal Pandas
<p>I have a df using pandas with a list of permits and then a list of subpermits. I need to compare the Parent and Sub Permit columns, and if the Parent Permit is equal to the sub permit, set the Value total field to 0. The BLD-00045 row needs to retain the 70000 value essentially, but the ELE and PM need to be set to ...
<p>Reading between the lines of your data, I am guessing that in reality, there is some kind of hierarchical, tree-like structure of permits, and you are interested in assigning costs to only certain levels.</p> <p>Based on your example, it sounds like you want to identify rows where the Sub Permit is equal to <em>any...
python|pandas
3
356,525
58,560,271
How to sum values in a column dataframe base on values in another column
<p>I have a data set which has video games, their sales, and the year the game was released. I am only looking for the game sales per year, not the game sales per title per year.</p> <p>I am using a pandas Dataframe. I have tried a groupby method. I have tried a loop with .unique() values. </p> <pre><code>df = df[["Y...
<p>You can use</p> <pre><code>df.groupby('Year', as_index=False)['NA_Sales'].sum() </code></pre>
python|pandas|dataframe
1
356,526
58,565,037
Date formatting to month
<p>I want to change the format of "Date" column from 10/15/2019 to m/d/y format.</p> <pre><code>tax['AsOfdate']= pd.to_datetime(tax['date']) </code></pre> <p>How do I do it?</p>
<p>like this, and here is the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer">documentation</a>. </p> <pre class="lang-py prettyprint-override"><code>tax['AsOfdate']= pd.to_datetime(tax['date'], format="%m/%d/%Y" ) </code></pre>
python|pandas|datetime
1
356,527
58,486,475
How to put tag my duplicate values in particular way
<p>I have below .csv. I am trying to make a dataframe where I can find the duplicates and I need to find one more column where first value will be always </p> <pre><code>Name = [('Hello'), ('Spider'), ('Captain'), ('Superman'), ('Hello'), ('Superman')] dfName = pd.DataFrame(Name, column...
<p>Remove <code>keep=False</code> for default <code>keep='first'</code> parameter:</p> <pre><code>dfName['un_dup_hel'] = np.where(dfName['Name'].duplicated(),'duplicate', 'unique') print (dfName) Name un_dup_hel 0 Hello unique 1 Spider unique 2 Captain unique 3 Superman unique 4 H...
python|pandas
2
356,528
58,533,080
Solving Shrodinger's equation for a particle in a harmonic potential well
<p>Hello (this is my first time posting in stack overflow), I am trying the calculate the first 3 energy levels of a particle in a harmonic potential using the shooter method</p> <p>The code is adapted from a script in Computational Physics by Mark Newman, this script calculated the ground state for a particle in a bo...
<p>Yep! You are right about the values being too close to each other. Your code returns a <code>nan</code>. It is because of the division by zero. </p> <p>I would suggest using a correction factor. Something like <code>max(delta, (psi2-psi1))</code> in the denominator where <code>delta</code> can still be a very small...
python|numpy
2
356,529
58,454,612
Binning a column in a DataFrame into 10 percentiles
<p>I am looking to qcut or cut my "Amount" column into bins of 10 percentiles. Basically the describe() feature but with 0-10%, 11-20%, 21-30%, 31-40%, 41-50%, 51-60%, 61-70%, 71-80%, 81-90%, 91-100% instead.</p> <p>After the binning i'd like to create a column that shows 1-10 indicating the bin that particular amount...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.qcut.html" rel="nofollow noreferrer"><code>pd.qcut</code></a>:</p> <pre><code># Sample data size = 100 df = pd.DataFrame({ 'Amount': np.random.randint(5000, 20000, size), 'CustomerType': np.random.choice(['New', 'Repeat'], size) ...
python|pandas|numpy
1
356,530
58,510,980
add left and right portions of the array symmetrically - python
<pre><code>a = np.array([[[ 1, 11], [ 3, 13], [ 5, 15], [ 7, 17], [ 9, 19]], [[ 2, 12], [ 4, 14], [ 6, 16], [ 8, 18], [10, 20]]]) </code></pre> <p>I'm trying to add the left portion to...
<p>Looks like you may invert the array, add and cut to the <code>a.shape[1]//2</code> middle</p> <pre><code>(a + a[:,::-1,:])[:, :a.shape[1]//2, :] </code></pre> <hr> <pre><code>array([[[10, 30], [10, 30]], [[12, 32], [12, 32]]]) </code></pre>
python|arrays|numpy
2
356,531
58,223,402
Pandas Rolling: Return Min and Max Dates, Sum of Exposure
<p>I am trying to implement a rolling window and am struggling with the very last part. As you can see below, the code returns the sum of exposure, attached to the last date in the rolling window. I also want a column that has the first date in the window as well. (they are ordered by date but I am ultimately after ...
<p>Operations on rolling windows are actually limited to aggregation functions and must be performed on <strong>numbers</strong>, not on <strong>dates</strong>.</p> <p>To circumvent this limitation, notice that the Date from the beginning of your rolling window of size 12 is actually the Date from 11-th row before.</p...
python|pandas|rolling-computation
0
356,532
58,513,084
Subtract values for all columns in df1 by values in one column in df2
<p>Assuming I have the following dataframe <code>df1</code>:</p> <pre><code> a b c d 10 15 20 25 8 18 28 38 20 25 30 35 </code></pre> <p>And for simplicity, assuming I have a dataset <code>df2</code>:</p> <pre><code> y 1 2 3 </code></pre> <p>I want to subtract, row-wise, values in ...
<p>Use <code>sub</code> and <code>axis=0</code> for a vectorized solution</p> <pre><code>df.sub(df2.values, axis=0) </code></pre> <hr /> <pre><code> a b c d 0 9 14 19 24 1 6 16 26 36 2 17 22 27 32 </code></pre> <hr /> <h3><code>Timings</code></h3> <p>For a small number of columns:</p> <pre><code>...
python|pandas
5
356,533
58,599,623
merging arrays from n file into a new file in python
<p>I have three files each containing columns that are a mixture of ints and floats for example the first line from each of the files is:</p> <pre><code>file1 1.0000,0,0,1,1,0,0,0,0,0,0.0000,0.0000,0.0000,0,0,0,8.7129,-102.3384,142.2611,0 </code></pre> <pre><code>file2 1640 3110 1780 </code></pre> <pre><code>file3 ...
<p>Hi I was able to solve this, the problem was with the way the square brackets were positioned. The right way to write the code was</p> <pre><code>tbl_out=rfn.merge_arrays([tbl1[['CCC']],tbl3[['Bin','NA8']],\ tbl1[['pIndex']],\ tbl3[['NA9','NA10','NA11','NA12','NA13'...
python|python-3.x|numpy|array-merge
0
356,534
58,397,340
Plotting by Index with different labels
<p>I am using pandas and matplotlib to generate some charts.</p> <p>My DataFrame:</p> <pre><code> Journal Papers per year in journal 0 Information and Software Technology 4 1 2012 International Conference on Cyber Securit... 4 2 Journal of Net...
<p>I found a solution, based on this question <a href="https://stackoverflow.com/questions/11927715/how-to-give-a-pandas-matplotlib-bar-graph-custom-colors">here</a>. SO, the dataframe needs to be transformed into a matrix, were the values exist only on the main diagonal. First, I save the column <code>journals</code>...
python|python-3.x|pandas|matplotlib
0
356,535
58,268,840
Hyperparameter tuning with ml-engine returns State: failed
<p>I'm trying to get my models hyperparameters tuned with the ml-engine but i'm not quite sure if its working or not.</p> <p>I'm not specifying the <code>algorithm</code> tag in <code>HyperparameterSpec</code>, which should default to Bayesian optimization method according to the documentation. Im also not setting <co...
<p>The problem could be solved by using the python package <code>cloudml-hypertune</code> with the following code:</p> <pre><code>self.hpt.report_hyperparameter_tuning_metric( hyperparameter_metric_tag=hypeparam_metric_name, metric_value=value, global_step=step) </code></pre> <p>An...
tensorflow|google-cloud-ml|hyperparameters
1
356,536
58,586,007
Selecting random windows from numpy arrays greater than 2 dimensions
<p>How can I select a random window from a numpy array greater than 2 dimensions wherein the window is random with respect to 2 different dimensions? </p> <p>I'd like to do something similar to the answer in this post but in 3 dimensions, not 2: <a href="https://stackoverflow.com/questions/47982894/selecting-random-wi...
<p>We can leverage <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/#indexing-scheme-strides" rel="nofollow noreferrer"><code>np.lib.stride_tricks.as_strided</code></a> based <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows" rel="nofollow noreferrer"><code>sciki...
python|arrays|numpy|vectorization
0
356,537
58,226,184
How to assign each row in a numpy array into keys in dictionary python
<p>I have a rather large numpy array. I'd like to take each row in my array and assign it to be a key in a dictionary I created. For example, I have a short 2-dimensional array:</p> <pre><code>my_array = [[5.8 2.7 3.9 1.2] [5.6 3. 4.5 1.5] [5.6 3. 4.1 1.3]] </code></pre> <p>and I'd like to c...
<p>If a tuple will do, then:</p> <pre><code>import numpy as np my_array = np.array([[5.8, 2.7, 3.9, 1.2], [5.6, 3., 4.5, 1.5], [5.6, 3., 4.1, 1.3]]) d = { k : None for k in map(tuple, my_array)} print(d) </code></pre> <p><strong>Output</strong></p> <pre><code>{(5.8, 2.7,...
python|numpy|dictionary
2
356,538
58,602,442
How to save data in .csv file in row and column form using numpy
<p>I am trying to read and image using OpenCV and after reading that image I have got some data which I have to save in a CSV file using numpy. Here is the program:-</p> <pre><code>import cv2 as cv import numpy as np import os img1 = cv.imread('C:/Users/sbans/Pictures/bird.jpg') dataA1 = os.path.basename('C:/Users/sb...
<p>You could simplify the code a bit by defining a function </p> <pre><code>def get_array(file): img = cv.imread(file) basename = os.path.basename(file) height, width, channels = img.shape h = int(height/2) w = int(width/2) px = img[h,w] return np.array([basename, height, width, channels, ...
python|numpy|csv
1
356,539
58,477,696
Plotly Choroplethmapbox not showing all polygons
<p>I'm having an odd issue with Plotly, the image below will give some context:</p> <p><a href="https://i.stack.imgur.com/L5PKR.png" rel="nofollow noreferrer">This is the map made with Bokeh</a></p> <p><a href="https://i.stack.imgur.com/l82ql.png" rel="nofollow noreferrer">This is the map made with Plotly</a></p> <p...
<p>I had a similar issue. That is a slice of my geopandas dataframe looked like -</p> <pre><code> province_id geometry 0 1 POLYGON (x1, y1) 1 1 POLYGON (x2, y2) 2 1 POLYGON (x3, y3) </code></pre> <p>I used <code>province_id_data.dissolve(by='province_id', aggfunc='first')</code> t...
python|plotly|mapbox|geopandas|choropleth
1
356,540
58,368,601
RuntimeError: size mismatch, m1: [32 x 1], m2: [32 x 9]
<p>I'm building a CNN and training it on hand sign gesture classification for letters A through I (9 classes), each image is RGB with 224x224 size.</p> <p>Not sure which matrix I need to transpose and how. I have managed to match the inputs and outputs of layers, but that matrix multiplication thing, not really sure h...
<p>You don't need <code>x=x.view(-1,1)</code> and <code>x = x.squeeze(1)</code> in your <code>forward</code> function. Remove these two lines. Your output shape would be <code>(batch_size, 9)</code>.</p> <p>Also, you need to convert <code>labels</code> to one-hot encoding, which is in shape of <code>(batch_size, 9)</c...
python|neural-network|deep-learning|conv-neural-network|pytorch
2
356,541
58,587,685
Protection against "index 0 is out of bounds for axis 0 with size 0" error in Python
<p>I have a code in which I get a specific distribution of points on the graph of the function <code>tan()</code> limited from the bottom and top by straight lines:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import sys import itertools import multiprocessing import tqdm ic = range(1,10) jc = r...
<p>Where does this error occur? That's a fundamental piece of information - for us, but especially for you!</p> <p>@edison says it's in the <code>argwhere</code> expression. I'll try to recreate that step, starting with a guess as to what <code>diffs</code> looks like:</p> <pre><code>In [8]: x = np.ones(5)*.1 ...
python|python-3.x|numpy|matplotlib
2
356,542
58,413,499
Create a list of random numbers and filter the list to only have numbers larger than 50
<p>I am using list comprehension to create a list of random numbers with numpy. Is there a way to check if random number generated is larger than 50 and only then append it to the list.</p> <p>I know I can simply use:</p> <pre><code>numbers = [np.random.randint(50,100) for x in range(100)] </code></pre> <p>and that ...
<p>You use numpy, so we can leverage indexing method.</p> <pre class="lang-py prettyprint-override"><code>my_array = np.random.randint(1, 100, size=100) mask = my_array &gt; 50 print(my_array[mask]) # Contain only value greater than 50 </code></pre> <p>But of course, the best way to do what you want is that. </p> <p...
python|numpy|random
4
356,543
69,061,733
Counting selected dataframe columns according to condition
<p>Although this question seems somewhat similar to previous ones, I could not have it solved with previous answers and I need help from experts.</p> <p>I am trying to create a column (e.g. 'Result') with the count of other columns with labels that start with 'X_', given a condition (eg. column element &gt;1).</p> <pre...
<p>We can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</code></a> the DataFrame for columns that start with <code>X_</code> test which values are <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ge.html" rel="nofollow no...
python|pandas|dataframe
2
356,544
68,900,171
Counting occurrence of string value in df1 if other column date value in df1 is between two dates in df2
<pre><code> df1 = pandas.DataFrame( { &quot;ID&quot; : [&quot;11&quot;, &quot;11&quot;, &quot;11&quot;, &quot;11&quot;] , &quot;updated_date&quot; : [&quot;2019/04/03&quot;, &quot;2019/05/02&quot;, &quot;2019/05/20&quot;, &quot;2019/03/03&quot;], &quot;other_date&quot; : [&quot;2019/04/09&q...
<ol> <li><p><strong>merge</strong>:</p> <p><strong>df3=pd.merge(df1,df2,how='left',on='ID')</strong></p> </li> </ol> <p>then you got a new table:</p> <pre><code>ID updated_date other_date new_date characteristic 0 11 2019/04/03 2019/04/09 2019/04/02 T 1 11 2019/04/03 2019/04/09 2019/05/03 T 2 11 ...
python|pandas|dataframe|count|conditional-statements
0
356,545
68,989,800
Parsing XML and converting to CSV python
<p>I'm having some trouble with parsing an XML. After having a search on here I've got close to getting what I need but I'm having issues with unnesting some deeper data.</p> <p>this is my xml data.</p> <pre><code>xml = &quot;&quot;&quot; &lt;instance&gt; &lt;ID&gt;1&lt;/ID&gt; &lt;start&gt;0&lt;/start&gt; ...
<p>You're almost there, just a few hiccups. Try chainging your <code>for</code> loop to</p> <pre><code>for i in root: #no change in the first 4 items: ID = i.find(&quot;ID&quot;).text Start = i.find(&quot;start&quot;).text End = i.find(&quot;end&quot;).text Player= i.find(&quot;code&quot;).text ...
python|pandas|xml|csv
2
356,546
69,014,545
formatting row output from python pandas dataframe iterrows()
<p>I've got a python pandas dataframe (<code>my_df</code>). I'd like to extract the rows using <code>iterrows()</code>, then turn the rows into lists, and finally append the rows-turned-lists to a list of lists (<code>my_list</code>).</p> <pre><code>import pandas as pd # DATA data = {'a': [8, 8, 8, 7], 'b': [7, 8...
<p>Just use <code>tolist</code>:</p> <pre><code>my_list = [] for index, row in my_df.iterrows(): my_list.append(row.tolist()) print(my_list) </code></pre> <p>Output:</p> <pre><code>[[8, 7, 7, 7], [8, 8, 7, 7], [8, 8, 8, 7], [7, 8, 8, 7]] </code></pre>
python|pandas|data-science
1
356,547
69,285,931
Adding multiple new columns to an existing dataframe base on a given condition
<p>I have a Dataframe with the below column names, and I want to create new columns(<strong>n_1, n_2, n_3 n_4, n_5, n_6, n_7, n_8</strong>) off the original Dataframe based on a given condition. The condition is to create new columns for each unique <strong>EVENT_ID</strong> in the Dataframe. check for rows in the ...
<p>You can use a pivot table and add prefixes once that's done.</p> <pre><code>df.pivot_table(index='EVENT_ID',columns='SELECTION_TRAP',values='BSP').add_prefix('n_') </code></pre> <p>Output</p> <pre><code>SELECTION_TRAP n_1 n_2 n_3 n_4 n_5 n_6 n_7 n_8 EVENT_ID ...
python|pandas|dataframe
2
356,548
69,280,640
Unstack columns in pandas-python
<p>I would like to Unpivot/unstack my dataframe. My df is like:</p> <pre><code>a=pd.DataFrame(columns=['Name','Title','Status'],data=[['John','Course1','Finished'],['Mike','Course2','Accepted'],['Jim','Course1','Accepted'],['Jhonny','Course3','Rejected'],['Jhonny','Course3','Accepted']]) </code></pre> <p>And I need it ...
<p>You could use <code>pivot_table()</code></p> <pre><code>a.pivot_table(index='Name', columns=['Title'], values='Status', aggfunc='first') </code></pre> <p>prints:</p> <pre><code> Course1 Course2 Course3 Name Jhonny Accepted NaN Rejected Jim Accepted NaN ...
python|pandas
0
356,549
68,995,072
Plotting data grouped by labels
<p>I am training a neural network with different hyper-parameters and would like to plot the different results in order to compare which ones perform better.</p> <p>I currently have a plugging to do this but would like to do it myself with <code>matplotlib</code>. I would like to replicate the following image.</p> <p><...
<ul> <li><p><a href="https://seaborn.pydata.org/generated/seaborn.stripplot.html" rel="nofollow noreferrer"><strong><code>seaborn.stripplot</code></strong></a> with <code>jitter</code> disabled</p> <pre class="lang-py prettyprint-override"><code>import seaborn as sns sns.stripplot(data=df, x='Activation', y='Accuracy',...
python|pandas|matplotlib
1
356,550
69,052,249
Text Detection using tensorflowjs
<p>I want to do text detection in an image using only tensorfow.js or opencv.js, i have already build a EAST model on keras and converted to tensorflowjs model</p> <p>can anyone help me with this, any resource will be great</p> <p>Thanks.</p>
<p>So, initially you need to download the East frozen model and then conver it to tensorflow.js model by using the below command</p> <pre><code>tensorflowjs_converter --input_format=tf_frozen_model --output_node_names='feature_fusion/Conv_7/Sigmoid,feature_fusion/concat_3' /path_to_model /path_to_where_you_want_save_c...
tensorflow.js|tensorflowjs-converter
2
356,551
68,902,688
Nested Json in Pandas Column
<p>I have a dataframe with nested json as column.</p> <pre><code>df.depth 0 {'buy': [{'quantity': 51, 'price': 2275.85, 'o... 1 {'buy': [{'quantity': 1, 'price': 2275.85, 'or... 2 {'buy': [{'quantity': 1, 'price': 2275.85, 'or.. </code></pre> <p>inside each row have 5 depths of buy sell</p> <pre><code>df.de...
<p>You could try <code>concat</code>:</p> <pre><code>df = pd.concat([pd.concat([pd.DataFrame(x, index=[0]) for x in i], axis=1) for i in pd.json_normalize(df['depth'])['buy'].tolist()], ignore_index=True) print(df) </code></pre> <p>Output:</p> <pre><code> quantity price orders quantity price orders ... quan...
python|json|pandas
1
356,552
68,930,282
Create a column with time elapsed (in seconds) since first date based on two conditions
<p>I have 3 cols:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>User_id</th> <th>Country</th> <th>Datetime</th> </tr> </thead> </table> </div> <p><strong>Objective:</strong> I need to create a fourth column that is time elapsed in seconds based on user and country's first datetime</p> <p>...
<p>I can't test the code right now, but I would do something like:</p> <pre><code># ensure datetime type (optional if already right type) df['Datetime'] = pd.to_datetime(df['Datetime']) # get the first value per group: df['first'] = df.groupby(['User_id', 'Country']).transform.min() # or first() if you want the first ...
python|pandas|datetime
2
356,553
69,031,189
How to use lambda functions with cross-index computation when iterating dataframes columns
<p>I have a pandas data frame, <code>df</code>, with one of the columns called <code>val</code> to which I apply a cross index computation:</p> <pre><code>import pandas as pd sensor_data = {'Sensor': ['A', 'B', 'C', 'D', 'E'], 'val': [20, 2 , 2, 19, 18]} df = pd.DataFrame(sensor_data) # Cross index computation: cross_...
<p>What about <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer">shift</a> ?</p> <pre><code>print((df['val'] * df['val'].shift(-1)).dropna().astype(int).to_list()) [40, 4, 38, 342] </code></pre>
python|pandas|dataframe|lambda
0
356,554
69,132,933
Count unique values of a series based on condition - Pandas
<p>I have a dataframe like this.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>booking_id</th> <th>booking_category</th> <th>vehicle_number</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>x</td> <td>abc</td> </tr> <tr> <td>2</td> <td>x</td> <td>def</td> </tr> <tr> <td>3</td> <td>y</td> <t...
<p>Create a frequency table with <code>crosstab</code>, then check for the counts to make sure only <code>x</code> category has count greater than <code>0</code></p> <pre><code>s = pd.crosstab(df['vehicle_number'], df['booking_category']) m = s.pop('x').ge(1) &amp; s.eq(0).all(1) </code></pre> <p>Details</p> <pre><code...
python|pandas|dataframe
0
356,555
68,881,498
converting columns to rows in paython
<p>I have a dataframe like this,</p> <pre><code>df1= time asset_id sensor_01 sensor_02 0 2019-08-01 120 23 54 1 2019-08-02 125 45 38 2 2019-08-03 120 25 49 </code></pre> <p>since number of sensors are variable, I decided to write them in rows like,</p> <...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>pandas.melt</code></a>:</p> <pre><code>pd.melt(df1, id_vars=['time', 'asset_id'], # variables to keep as columns var_name='sensor_ID', # column name for the variable value_name=...
python|pandas|dataframe
1
356,556
68,890,495
Merge two dataframes on DateTimeIndex ignoring the year
<p>I have two dataframes, one is a series of measurements,</p> <pre><code>A = ID Value 2020-01-01 00:00:00 0.2 2020-01-01 01:00:00 0.2 ... 2020-12-31 22:00:00 0.6 2020-12-31 23:00:00 0.5 2021-01-01 00:00:00 0.4 2021-01-01 01:00:00 0.3 ... 202...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with left join and helper column defined by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.strftime.html" rel="nofoll...
python|pandas|dataframe|merge
3
356,557
68,933,462
Calculate set of multilevel columns mean based on a lookup table in Pandas
<p>Given a two level columns as below. The first level can be group into <code>tech_one</code>, <code>tech_two</code>, <code>tech_three</code>, <code>tech_four</code>, <code>etc</code> and <code>mnt</code>. On the second level, the <code>ch</code> and <code>b</code> is separated by <code>_</code>, and <code>ch</code> c...
<p>Any reason in particular you need to deal with the MultiIndex? They are usually more of a headache than being helpful. Is your data structured in a way, that you can tranpose the table and make the index levels simple columns instead? Like this:</p> <pre><code>df = df_cal.T.reset_index().rename(columns={&quot;level_...
python|pandas
1
356,558
68,893,910
Create a "stacked" bar chart according to one boolean column
<p>I would like to create a single bar which is composed of multiple layers stacked on top of each other, where each layer is colored according to a boolean flag (contained for example in a dataframe).</p> <p>The final effect should be something like the picture below, but I would be using a large set (40'000 entries)....
<p>You could convert the dataframe column to a 2D numpy array and use <code>sns.heatmap()</code>:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd df = pd.DataFrame({'bool_val': np.random.randn(40000).cumsum() &gt; 0}) ax =...
python|pandas|dataframe|matplotlib|seaborn
1
356,559
69,168,432
How to remove string None from a single string with commas and count the most common words in a row?
<p>I have rows in a df formed by a string that contains several elements separated by commas.</p> <p>Among the rows, there are words of interest (eg. Car, Bus) and the word None. Also, there are rows that only have the word None.</p> <p>Here is an example of df:</p> <div class="s-table-container"> <table class="s-table...
<p>You can split the &quot;Col&quot; column with <code>.str.split(&quot;, &quot;)</code>, filter out the <code>None</code> values, empty lists and count unique items with <code>.value_counts()</code>:</p> <pre class="lang-py prettyprint-override"><code>df.Col = df.Col.str.split(&quot;, &quot;).apply(lambda x: [v for v ...
python|pandas|dataframe|python-re
1
356,560
68,921,691
pyreadstat read and write spss without data loss
<p>To read an spss .sav file using pandas/pyreadstat, you use:</p> <pre><code>df, meta = pyreadstat.read_sav() </code></pre> <p>to write a dataframe, you use:</p> <pre><code>pyreadstat.write_sav(df) </code></pre> <p>How can I read, edit and write a .sav file without losing any meta data, like labels and other things th...
<p>Talk is cheap, here's the code. :-)</p> <pre class="lang-py prettyprint-override"><code># using pyreadstat from pyreadstat import write_sav class TempFile(type(pathlib.Path())): # type: ignore def __exit__(self, exc_type, exc_val, exc_tb): filepath = str(self.absolute()) try: os.rem...
python|pandas|dataframe|spss
1
356,561
69,263,823
How to put together all corelated values from different column
<p>I have 5 set (at max) of values:</p> <pre><code>ID1 ID2 ID3 ID4 ID5 1 2 3 5 7 1 2 1 8 3 9 4 11 15 4 17 11 15 17 4 18 </code></pre> <p>IF IDs are on the same row then they belong to a common group:</p> <p>SO, I want to generate the groups:</p> <p>In this example, I w...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> for <code>DataFrame</code> for <code>level_0</code> form indices and <code>val</code> column first:</p> <pre><code>df = df.rename(index=str).stack().astype(in...
python|pandas
3
356,562
68,897,195
How to read csv data from kaggle in pycharm
<p>Hi there if anyone can answer this. I am trying to read csv data from kaggle <a href="https://www.kaggle.com/stackoverflow/stack-overflow-2018-developer-survey" rel="nofollow noreferrer">https://www.kaggle.com/stackoverflow/stack-overflow-2018-developer-survey</a> in pycharm and online jupyter notebook but I can not...
<p>From the page you linked to, you have a couple of options.</p> <ol> <li>Create a notebook and the input files will be automatically included. Run the first cell that's generated for you and it will print out the paths to the input files. You can use Pandas <code>read_csv</code> in the notebook to load the data using...
python|pandas|csv|pycharm
0
356,563
69,137,208
How to interpolate only over a specific window?
<p>I have a dataset that follows a weekly indexation, and a list of dates that I need to get interpolated data for. For example, I have the following df with weekly aggregation:</p> <pre><code>data value 1/01/2021 10 7/01/2021 10 14/01/2021 10 28/01/2021 10 </code></pre> <p>and a list of...
<p>Use <code>interpolate</code> to get expected outcome but before you have to prepare your dataframe like below.</p> <p>I slightly modify your input data to show you interpolation with datetimeindex (<code>method='time'</code>):</p> <pre><code># Input data df = pd.DataFrame({'data': ['1/01/2021', '7/01/2021', '14/01/2...
python|pandas
0
356,564
69,233,353
TypeError: 'Series' object cannot be interpreted as an integer
<p>Is there a way to use values from a dataframe in functions like <code>range</code> or compare the values to non-dataframe values? My code is:</p> <pre><code>import pandas as pd cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'], 'Qty': [20,34,12,43] } df = pd.DataFrame(cars, c...
<p>Not for sure what's your point. But if you want to get a DataFrame where 'Qty' &gt; 15, you can do it like this:</p> <pre><code>df[df['Qty'] &gt; 15] </code></pre> <p>Or you may want this:</p> <pre><code>[item for item in df['Qty'] if item &gt; 15] </code></pre> <p>It returns a list with elements which great than 15...
python|pandas|dataframe
0
356,565
69,249,220
Passing Dataframes in classes and functions
<p>I know this has probably be done to death, but im really struggling with the use of variables (dataframes) in classes and functions. I have a created a small code example. basically I want to</p> <ol> <li>read a csv to a Dataframe via a button</li> <li>show a label when a dataframe is read</li> <li>ignore the label ...
<p>Nevermind</p> <p>it seems I didnt address the variable correctly as I had to include the classname before it.</p> <p>in this case it was UI.df_data I also didnt need to use different names as this name is valid throughout the class</p>
python|pandas|dataframe
0
356,566
69,177,945
Split a column by separating numbers and letters
<p>I have a dataframe with a column looking like this:</p> <pre><code> X 1.6 aaa_2345 1.6 aaa_2345 Bbb 1.4t_2890 Bbb 1.4t_2891 1.2 ccc_4570 </code></pre> <p>I would like to create a new column with only the float part i.e:</p> <pre><code> X 1.6 1.6 1.4 1.4 1.2 </code></pre>
<p>You can use <code>extract</code>:</p> <pre><code>df['X'].str.extract('([\d.]+)').astype(float) </code></pre> <p>output:</p> <pre><code> 0 0 1.6 1 1.6 2 1.4 3 1.4 4 1.2 </code></pre>
python|pandas
2
356,567
69,127,427
How to merge matching indices with two pandas dataframes
<p>While this seemed like something that had been asked before, I have not found any information on best practices on how to perform this function.</p> <p>Overview: I have two dataframes; the first is what I would call a FULL dataframe. It is the original source, so to speak. Then I have a dataframe that includes parts...
<p>You may use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>pandas.DataFrame.update</code></a> method.</p> <pre><code>geoid = geoid.set_index('ID') original = original.set_index('ID') original.update(geoid) </code></pre>
python|pandas
4
356,568
69,201,063
Can we use VGG19 with transferlearning and another image size?
<p>I've followed this really good example of how to use transfer learning with VGG19 and rock,paper,scissors image classification: <a href="https://github.com/Nithyashree-2022/VGG-19-for-Rock-Paper-and-Scissors-classification" rel="nofollow noreferrer">https://github.com/Nithyashree-2022/VGG-19-for-Rock-Paper-and-Sciss...
<p>Vgg will work with an image size other than 224 X22 X 3. Make sure you call tf.keras.applications.vgg19.preprocess_input on your inputs before passing them to the model. vgg19.preprocess_input will convert the input images from RGB to BGR, then will zero-center each color channel with respect to the ImageNet dataset...
tensorflow|keras|transfer-learning|vgg-net|image-classification
0
356,569
69,133,967
Pandas map --- ValueError: Length mismatch
<p>I have two CSVs in memory stored as dataframes: df1 and df2</p> <p>df1 has a column 'OOSCUSTID' df2 has a column 'FORCUSTID'</p> <p>For each row in df1:</p> <p>Where the OOSCUSTID value in df1 == FORCUSTID value in df2, take the value from df2['KKLM'], and store it in df1['FOREIGN-KKLM'']</p> <pre><code>df1: NO. ...
<h2><strong><code>merge()</code></strong> method:</h2> <pre><code>df1['FOREIGN-KKLM'] = df1.merge(df2, left_on='OOSCUSTID', right_on='FORCUSTID', how='left')['KKLM'] Print(df1) NO. OOSCUSTID FOREIGN-KKLM 0 648500 -17 3....
python|pandas
1
356,570
68,936,835
How to specify input sequence length for BERT tokenizer in Tensorflow?
<p>I am following this <a href="https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4" rel="nofollow noreferrer">example</a> to use BERT for sentiment classification.</p> <pre><code>text_input = tf.keras.layers.Input(shape=(), dtype=tf.string) preprocessor = hub.KerasLayer( &quot;https://tfhub.dev/tensorfl...
<p>Just going off the docs here (haven't tested this), but you might do :</p> <pre><code>preprocessor = hub.load( &quot;https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3&quot;) text_inputs = [tf.keras.layers.Input(shape=(), dtype=tf.string)] </code></pre> <p>Doesn't look like you've tokenized your data ab...
tensorflow|keras|nlp|tokenize|bert-language-model
0
356,571
68,940,201
How to create list of coordinates for each row in pandas dataframe?
<p>I have a dataframe that contains coordinates of several 2d points in the sequence of frames. It looks like</p> <pre><code>frame point_1_x point_2_x point_3_x point_1_y point_2_y point_3_y 1 0 1 1 2 3 1 2 2 3 5 1 2 3 3 ...
<p>rename the columns and then groupby</p> <pre><code>df.columns = df.columns.str[:-2] arr = df.stack().groupby(level=[1,0]).agg(tuple).values array([(0, 2), (2, 1), (8, 4), (1, 3), (3, 2), (2, 5), (1, 1), (5, 3), (3, 6)], dtype=object) </code></pre>
python|pandas
-1
356,572
69,252,549
Using Python Great Expectations to remove invalid data
<p>I just started with Great Expectations library and I want to know if it is possible to use it to remove invalidated data from Pandas DataFrame. And how I can do that if is possible ? Also I want to insert invalid data to PostgreSQL database.</p> <p>I didn't find anything about this in the documentation and on search...
<p><code>Great Expectations</code> is a powerful tool to validate data.<br /> Like all powerful tools, it's not that straightforward.</p> <p>You can start from here:</p> <pre><code>import great_expectations as ge import numpy as np import pandas as pd # get some random numbers and create a pandas df df_raw = pd.Da...
python|pandas|postgresql|great-expectations
1
356,573
69,257,090
python pandas is giving a keyerror for a column I group by, even though a boolean expression shows that the column is part of the dataframe
<p>I cannot seem to print the following line: <code>summarydata[&quot;Name&quot;].groupby([&quot;Tag&quot;]).size()</code></p> <p>without getting the error:</p> <pre><code> File &quot;C:\Users\rspatel\untitled0.py&quot;, line 76, in &lt;module&gt; print(summarydata[&quot;Name&quot;].groupby([&quot;Tag&quot;]).size...
<p>You are trying to group by a key on the column itself. Instead you want:</p> <pre class="lang-py prettyprint-override"><code>summarydata[&quot;name&quot;].groupby(summarydata[&quot;Tag&quot;]) </code></pre> <p>from the docs:</p> <blockquote> <p>by: (mapping, function, label, or list of labels)</p> </blockquote> <bl...
python|pandas|dataframe|pandas-groupby|keyerror
2
356,574
68,944,416
'numpy.ndarray' object has no attribute 'reset_index'
<p>I have installed pandas but I still have trouble using reset_drop...any idea what the problem is?! recently I've been using and dataframing and I have trouble using reset_drop code the result is</p> <pre><code>'numpy.ndarray' object has no attribute 'reset_index' </code></pre>
<p>I don't think there is <code>reset_drop</code> in pandas, but if you want to reset the index you can use <code>df.reset_index(drop=True)</code>.</p>
python|pandas|machine-learning
1
356,575
69,220,930
How to delete common index values with Pandas?
<p>I have a pandas df sourced from a csv file. There is a common value within the index column for all entries. How can I remove this common value? The common value is '00:00:00'</p> <pre><code> Date/Time 2021-01-04 00:00:00 Compost Maker 2021-01-05 00:00:00 Green Up Feed ...
<p>Try:</p> <pre><code>df.index = pd.to_datetime(df.index).normalize() </code></pre> <p>Result:</p> <pre><code>print(df) Product Date/Time 2021-01-04 Compost Maker 2021-01-05 Green Up Feed &amp; Weed 2021-01-05 Nippon Mouse Trap in a Box...
python|pandas|jupyter-lab
0
356,576
68,886,676
why the output of model is different in pytorch
<p>I have a simple model, just only one linear layer.</p> <pre><code>model = torch.nn.Linear(1,1).to(device) x_train1 = torch.FloatTensor([[1], [2], [3]]) out = model(x_train1) print(out) </code></pre> <p>But whenever I tried to run this code, the printed output is diffrent.</p> <p>Also I set these random seeds.</p> <p...
<p>You must set the seed every time you run the code if want to get the same result.</p> <pre class="lang-py prettyprint-override"><code>import torch def my_func(device: str, seed: int): torch.manual_seed(seed) model = torch.nn.Linear(1,1).to(device) x_train1 = torch.FloatTensor([[1], [2], [3]]) out = ...
pytorch
1
356,577
69,091,019
How to print rows and columns of missing values using NaN
<pre><code>for i in range(19): for j in range(5): if df.iloc[i,j] == 'NaN': print('Missing Value at (row,col): ({}, {}) '.format(i,j)) </code></pre>
<pre><code>You can try this, hope it helps:) # importing pandas as pd import pandas as pd # importing numpy import numpy as np # dictionary of lists dict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe using dict...
python|pandas|nan|locate
1
356,578
68,938,545
Is there a mean-variance normalization layer in PyTorch?
<p>I am new to PyTorch and I would like to add a mean-variance normalization layer to my network that will normalize features to zero mean and unit standard deviation. I got a bit confused reading the documentation, could anyone give me some leads?</p>
<p>As @Ivan commented, the normalization can be done on many levels. However, as You say</p> <blockquote> <p>normalize features to zero mean and unit standard deviation</p> </blockquote> <p>I suppose You just want to input unbiased data to the network. If that's the case, You should treat it as data preprocessing step ...
pytorch|conv-neural-network|normalization
1
356,579
69,130,083
How to move the first 2 rows of a file to the end with pandas
<p>I have a file with 2 columns and 10 rows:</p> <pre><code>01/12/2019 234.75 02/12/2019 303.6666666666667 03/12/2019 213.29166666666663 04/12/2019 187.91666666666663 05/12/2019 191.875 06/12/2019 188.25 07/12/2019 208.5833333333333 08/12/2019 184.125 09/12/2019 210.16666666666663 10/12/2019 315.4166666666667...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with selecting rows by positions:</p> <pre><code>df1 = pd.concat([df.iloc[2:], df.iloc[:2]]) </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/...
python|pandas|row
4
356,580
68,994,870
Pandas tz.convert GMT and local time does not match
<p>I am trying to convert UTC data to local time Mozambique. For Mozambique the local time follows GMT+2 or Africa/Maputo. However, when using <code>.tz_localize('UTC').tz_convert(X)</code> where X can either be <code>= 'GMT+2'</code> or <code>= 'Africa/Maputo'</code> I get separate answers. As an example:</p> <pre><co...
<p>The time zone conversion using etcetera works in reverse, and perhaps it should be deprecated altogether, considering the following observation on its <a href="https://opensource.apple.com/source/system_cmds/system_cmds-230/zic.tproj/datfiles/etcetera" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p...
python|pandas|numpy|time-series
0
356,581
69,083,832
Filter and replace substring in Pandas
<p>How can I filter <code>df</code> rows where <code>name</code> contains <code>Al</code>, and replace <code>large</code> with <code>L</code> in <code>sport</code>?</p> <p>Reproducible example:</p> <pre><code>df = pd.DataFrame({'name': ['Bob', 'Jane', 'Alice'], 'sport': ['tennis small', 'football me...
<p>Try with <code>loc</code> and <code>str.contains</code> with <code>str.replace</code>:</p> <pre><code>df.loc[df.name.str.contains('Al'), 'sport'] = df.sport.str.replace('large', 'L') </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; df.loc[df.name.str.contains('Al'), 'sport'] = df.sport.str.replace('large', 'L')...
python|pandas
1
356,582
68,880,433
How to read 24:00 hour?
<p>I have a csv file with 24:00 hour instead of 00:00 and try to read it with pandas. I found solution and try to adopt it. The problem is, I get an error and don't know how to fix it. Can someone help me?</p> <p>My csv:</p> <pre><code> Datetime Value 45 01.01.2021 23:00 2.7 46 01.01.2021 23:30 ...
<p>You can use <code>str.split()</code>+<code>pd.to_datetime()</code>+<code>pd.to_timedelta()</code>:</p> <pre><code>s=df['Datetime'].str.replace('.','-').str.split(expand=True) df['Datetime']=pd.to_datetime(s[0])+pd.to_timedelta(s[1]+':00') </code></pre> <p>OR</p> <pre><code>df['Datetime']=pd.to_datetime(df['Datetime'...
python|pandas|dataframe|datetime
2
356,583
69,057,220
Is there a better way to group by a category, and then select values based on different column values in Pandas?
<p>I have an issue where I want to group by a date column, sort by a time column, and grab the resulting values in the values column.</p> <p>The data that looks something like this</p> <pre><code> time value date 0 12.850000 19.195359 08-22-2019 1 9.733333 13.519543 09-19-2019 2 14.08333...
<p>You can sort the data frame before calling <code>groupby</code>:</p> <pre class="lang-py prettyprint-override"><code>first_of_day = df.sort_values('time').groupby('date').head(1) </code></pre>
python|pandas|data-science|grouping|data-preprocessing
0
356,584
69,289,726
Lookup Values and sum values in cell pandas
<p>I have two dataframes:</p> <pre><code>df1 = pd.DataFrame({'Code' : ['10', '100', '1010'], 'Value' : [25, 50, 75]}) df2 = pd.DataFrame({'ID' : ['A', 'B', 'C'], 'Codes' : ['10', '100;1010', '100'], 'Value' : [25, 125, 50]}) </code></pre> <p>Column &quot;C...
<ul> <li><code>explode()</code> the list of <strong>Codes</strong></li> <li><code>merge()</code> with <strong>df1</strong> and calculate total, grouping on the index of <strong>df2</strong></li> <li>have created a new column with this calculated</li> </ul> <pre><code>df1 = pd.DataFrame({&quot;Code&quot;: [&quot;10&quot...
python|pandas|dataframe|vlookup
0
356,585
69,019,207
NumPy TypeError: only integer scalar arrays can be converted to a scalar index
<p>I want to create <code>linnerud_df</code> dataframe by appending the <code>physiological</code> class to the <code>linnerud</code> data.</p> <pre><code>import numpy as np import seaborn as sns; sns.set(style=&quot;ticks&quot;, color_codes=True) import sklearn.datasets import pandas as pd linnerud = sklearn.datasets...
<pre><code>In [2]: import sklearn.datasets In [3]: linnerud = sklearn.datasets.load_linnerud() In [5]: linnerud.target_names Out[5]: ['Weight', 'Waist', 'Pulse'] In [6]: linnerud.target Out[6]: array([[191., 36., 50.], [189., 37., 52.], [193., 38., 58.], [162., 35., 62.], [189., 3...
python|pandas|numpy|scikit-learn
0
356,586
69,008,617
How to extract value from dictionary into new colum?
<p>I have a dataframe that contains one column with format like {&quot;orderNum&quot;:123456} Here is the example:</p> <pre><code>ActionTime Details OrderNumber 0 1/2/2021 17:21 {&quot;orderNum&quot;:123456} 1 1/2/2021 20:16 {&quot;orderNum&quot;:467899} 2 1/3/2021 8:38 {&quot;orderNum&...
<p>If the <code>Details</code> column is a string representation of a dictionary, you could use regular expressions to extract the number:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({&quot;Action&quot;: [0, 1, 2], &quot;Details&quot;: ['{&quot;orderNum&quot;:123456}', '{&quot;orderNum&quot;:4...
python-3.x|pandas|dataframe
1
356,587
69,122,523
Removing values in two columns of a Pandas dataframe if row above have the same values
<p>With this sample pandas df:</p> <pre><code>ColA ColB ColC Apple Fruit Food Apple Fruit Pie Apple Arrow Story </code></pre> <p>I am attempting to roll through the dataframe and if the values in ColA and ColB are the same in the current row as in the previous row, delete the current rows values for those two...
<p>Try:</p> <pre><code>df[[&quot;ColA&quot;, &quot;ColB&quot;]] = df[[&quot;ColA&quot;, &quot;ColB&quot;]].where(~df.duplicated([&quot;ColA&quot;, &quot;ColB&quot;]), &quot;&quot;) &gt;&gt;&gt; df ColA ColB ColC 0 Apple Fruit Food 1 Pie 2 Apple Arrow Story </code></pre> <p>If your data ...
python|pandas
1
356,588
69,032,087
Combining the Same Column in Python
<p>I want to combine the same columns. Here is an example:</p> <pre><code> Name X Name Y Name Z 0 Jack 5 Maria 8 John 12 1 Celine 14 Andrew 14 Jonathan 21 </code></pre> <p>In the above example, I want to combine &quot;<em><strong>Name</strong></em>&quot; columns. It wil...
<p>Not the prettiest solution probably, but does the job. Open to improvements.</p> <pre><code>&gt;&gt;&gt; df Name X Name Y Name Z 0 Jack 5 Maria 8 John 12 1 Celine 14 Andrew 14 Jonathan 21 &gt;&gt;&gt; pd.concat([df.iloc[:, i:i+2] for i in range(0, df.shape[1], 2)]) Nam...
python|pandas|list|dataframe|datatable
0
356,589
68,974,288
Group rows in Pandas dataframe, apply custom function and store results in a new dataframe as rows
<p>I have a pandas dataframe <strong>df_org</strong> with three columns - Index (integer), Titles (string) and Dates (date).</p> <p><a href="https://i.stack.imgur.com/L0Eqd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L0Eqd.png" alt="enter image description here" /></a></p> <p>I have a method <str...
<p>You can use the <code>DataFrame.explode</code> method, followed by <code>groupby</code> and <code>size</code>:</p> <p>I am going to just use a simple <code>.str.split</code> instead of your function, as I don't know where <code>word_tokenize</code> comes from.</p> <pre class="lang-py prettyprint-override"><code>In [...
python|pandas|dataframe|nltk|data-analysis
1
356,590
69,271,491
Pandas replace values with dictionary values using python built in map() function
<p>I have a dictionary like this <code>{'Note1':'Desc1','Note2':'Desc2','Note3':'Desc3'}</code> and a dataframe with values like this:</p> <pre><code>{0: 'Note1', 1: 'Note1', 2: 'Note1', 3: 'Note2', 4: 'Note2', 5: 'Note2;Note3', 6: 'Note2;Note3', 7: 'Note3', </code></pre> <p>I want to have a new column where the...
<p>Figured it out thanks to <a href="https://stackoverflow.com/questions/33078554/mapping-dictionary-value-to-list">this</a> post.</p> <pre><code>def swap(x): x = x.split(';') x = [*map(notelist.get, x)] x = &quot;,&quot;.join(x) return x df['noteText'] = df['NoteRef'].apply(swap) </code></pre>
python|pandas|dictionary
0
356,591
68,947,262
Errror when trying to find index of list variables: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
<p>The following is my code where I get the value error stated above.</p> <pre><code>citiesR = [melbourneR, perthR, brisbaneR] print(citiesR.index(melbourneR)) print(citiesR.index(perthR)) ValueError Traceback (most recent call last) &lt;ipython-input-43-517b86a5b2b0&gt; in &lt;mo...
<blockquote> <p>Printing melbourneR, the first element of the list gives me the index value correctly</p> </blockquote> <p>That's because it is identified by object identity.</p> <blockquote> <p>but trying to print PerthR gives me this error and I can't work out why.</p> </blockquote> <p>Because it's a different object...
python|numpy
1
356,592
69,170,921
Adding a list as a column to a Data Frame on python
<p>I have a data frame and lists I generated from some for loops using the values on the data frame. However I would like this lists to become columns of the data frame.</p> <pre><code>archivo=pd.read_csv('winequalityN.csv') #this is my file Y=archivo['quality'] #a column from the data frame y1=[] for y in Y: i...
<p>to simplify the data, say data is the 3 lists of numbers</p> <pre><code>data = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] </code></pre> <p>would be same as saying <code>data = [y1,y2,y3]</code>. To pivot that is fast with this method.</p> <pre><code>&gt;&gt;&gt; data = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] &gt;&gt;&gt; [list(x...
python|pandas|dataframe|for-loop
0
356,593
68,956,247
Plotting geopandas changes figure size in matplotlib
<p>So I create a matplotlib figure, and then add 3 (germany, slovakia, czech) countries via shape files.</p> <p>I explictly set the figsize as <code>(15, 15)</code>. <code>germany</code>, <code>czech</code>, <code>slovakia</code> are the read shape files, and finally <code>germany_pipe</code> is a <code>GeoDataFrame</c...
<p>Plotting several <code>geodataframes</code> on a common <code>ax</code> axis correctly requires all of them to have CRS (coordinate reference system) set properly. Preferably, all of them should have the same CRS for easy operation without (unnecessary) specifying coordinate transformation in the plotting instructio...
python|matplotlib|size|geopandas|figure
0
356,594
69,042,540
Split data frame in python based on one parameter shape
<p>I have a data frame which is like the following :</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import csv import matplotlib.pyplot as plt import seaborn as sns import warnings df_input = pd.read_csv('combine_input.csv', delimite...
<p><strong>Note: InPlace of target you have to write time as your column name Is time,or change column name to target</strong></p> <pre><code>def calRows(df,x,y): #df For consideration df1 = pd.DataFrame(df.target[df.target&lt;=x]) minCount = len(df1) targets = df1.target.unique() for i in targets: count = int(df1[...
python|pandas|dataframe|csv|split
0
356,595
69,046,534
docker stops when importing tensorflow
<p>I have a problem when building a docker container using tensorflow. Container gets build fine but when it runs the script 'ai_app.py' and reaches the <code>import tensorflow as tf</code> line the container immediately stops. It does not show me any error or something, it is like if i were using ctrl + c inside the d...
<p>I figured it out, the container stops because AVX support is not enabled</p>
python|docker|tensorflow
0
356,596
68,875,227
How to subtract two dataframes with duplicate first column?
<p>So, I have the following two dataframes and my ideal output is to get open_orders reduced by cancel_orders so I know how many open_orders I have.</p> <p>Desired Output:</p> <pre><code>df_total_orders order_id business_symbol open_orders 0 a1b2c3111111 AA 0.0 1 4kl3l2242244...
<pre><code>df_total_orders =df_add_orders.merge(df_cancel_orders, how = 'left', on = 'order_id) </code></pre> <p>will get you a dataframe with the data from the two original dataframes. You can then do</p> <pre><code>df_total_orders['open_orders'] = df_total_orders['open_orders']- df_total_orders['ca...
python|pandas|dataframe
1
356,597
68,906,112
How to get an exact representation of floats during `DataFrame.to_json`?
<p>I observed the following behavior with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html" rel="noreferrer"><code>DataFrame.to_json</code></a>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df = pd.DataFrame([[eval(f'1.12345e-{i}') for i in range(8, 20)]]) &gt;&gt;...
<p>I'm not sure on achieving this with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html" rel="nofollow noreferrer">pd.DataFrame.to_json</a>, but we can use <a href="https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">pd.Data...
python|json|pandas|floating-point
1
356,598
69,010,397
Concatenate n number of numpy arrays columnwise in python
<p>I know that we concatenate two 2-D numpy arrays named <code>arr1</code> and <code>arr2</code> with same number of rows with the help of following command:</p> <pre><code>np.concatenate((arr1,arr2),axis=1) </code></pre> <p>But I have n number of numpy arrays (I haven't done global variable name assignment to these a...
<p>Just a side note,</p> <p>Concatenating with <a href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>np.concatenate</code></a> on <code>axis=1</code> is equivalent to a horizontal stack: <a href="https://numpy.org/doc/stable/reference/generated/numpy.hstack.ht...
python|arrays|numpy|arraylist
1
356,599
69,024,042
seasonal WindRose subplots
<p>I'm trying to make WindRoses for the four seasons of the year on the same plot. I tried to follow the method from <a href="https://stackoverflow.com/questions/42733194/subplot-of-windrose-in-matplotlib">Subplot of Windrose in matplotlib</a> but the method did not work for me.</p> <p>I also tried the following from <...
<p>I managed to reproduce your question. Please keep in mind @mozway suggestion about <a href="/help/mcve">mcve</a> for your next questions.</p> <h1>Prepare data</h1> <p>I downloaded locally your data in my working direction.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np fro...
python|pandas|matplotlib|subplot|windrose
1