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
16,600
59,097,989
Deep Q Learning - training slows down significantly
<p>I'm trying to build a deep Q network to play snake. I designed the game so that the window is 600 by 600 and the snake's head moves 30 pixels each tick. I implemented the DQN algorithm with memory replay and a target network, but as soon as the policy network starts updating its weights the training slows down signi...
<pre><code>def decay_epsilon(self, episode): self.current_eps = self.eps_end + (self.eps_start - self.eps_end) * np.exp(-self.eps_decay * episode) // part of code from train() epsilon = self.current_eps if epsilon &gt; random.random(): action = np.random.choice(env.action_space) #expl...
python|tensorflow|keras|deep-learning|reinforcement-learning
2
16,601
59,442,361
EnvironmentNotWritableError in Conda
<p>I am trying to run this command <code>conda install pytorch torchvision cuda80 -c soumith </code> from this link <code>https://github.com/kenshohara/video-classification-3d-cnn-pytorch</code> and I am getting error as below. I don't have root privileges. Can anyone tell me what I should do to fix this issue?</p> <p...
<p>If you have a shared Anaconda then you should create your own local environments for your projects. E.g.,</p> <pre><code>conda create --name my_env -c pytorch torchvision </code></pre> <p>Also note that <code>pytorch</code> is the official channel from which to get PyTorch and that <code>torchvision</code> has a P...
python-3.x|pytorch|conda
0
16,602
59,343,462
How to fit a pandas timeseries to a 24h graph?
<p>I have a pandas timeseries of multiple months and want to count occurences of a feature for different times of day. </p> <p>I.e. I want to create a graph (using seaborn or matplotlib) with the time of day on the x axis (0 to 24 hours) and the relative number of occurences of a column on the y axis <a href="https://...
<p>You need to prepare the plot data first:</p> <pre><code>hour = df['Created Date'].dt.hour.rename('Hour') df_plot = df.groupby(hour).apply(lambda x: x['Open Data Channel Type'].value_counts() / x.shape[0]) \ .rename_axis(index=['Hour', 'Channel Type']) \ .to_frame('Frequency') \ ....
python|pandas|matplotlib|seaborn
1
16,603
44,927,945
How to compare 2 fields of same dataframe values and update result in another column
<p>How to compare 2 columns of same dataframe and update result in another column, if its matches update as <code>True</code> else <code>False</code>.</p> <p><code>df</code>:</p> <pre><code>Col1 Col2 Result 1234569 1234569 TRUE 256132 453543 FALSE DSDFDSF DSDFDSF TRUE TRYTR FGFH FALSE </code></pre>
<p>This returns a boolean series: <code>df.col1==df.col2</code></p>
python|pandas|dataframe
0
16,604
44,899,890
How do I perform calculations on a string in pandas?
<p>I have a dataframe like this:</p> <pre><code>Country Sales Assets China 4B 320B China 3B 125B India 112M 100B USA 39M 200B... </code></pre> <p>The <strong>Sales</strong> and <strong>assests</strong> columns have some values in billions and some in millio...
<p>Something like this should work</p> <pre><code>data=df['Sales'] for value in data: char=value[-1] if char=='M' toadd=float(value[:-1]/1000.0) elif char=='B': toadd=float(value[:-1]) totalsales=totalsales+toadd </code></pre>
python|pandas|dataframe
0
16,605
45,168,334
Pandas apply - Re-using apply result to save time
<p>I am trying to make a new column on a subset of my data-frame that is relatively small (~600 rows) using the apply function and it works but it is slow because the apply function is computationally intensive and I cannot make this black-box function faster / less complex. </p> <p>However, a lot of the results retur...
<p>MVCE example:</p> <pre><code>df = pd.DataFrame({'key':np.random.randint(1,10,60000),'result':np.nan}) def factorial(x): #Black box accum = 1 for i in range(1,x+1): accum *= i return accum %timeit df['result'] = df.key.apply(lambda x: factorial(x)) </code></pre> <p><em>10 loops, best of 3: 120...
python|pandas
1
16,606
57,074,580
How to use np.where between dataframes of different sizes? 'operands could not be broadcast together'
<p>I have two dataframes of different sizes.</p> <p><code>df1</code> has addresses and no zipcodes. <code>df2</code> has address and zipcodes.</p> <p>I am trying to match addresses from <code>df1</code> to <code>df2</code> using <code>np.where</code>, and if there's a match, bring the corresponding zipcode over to <c...
<p>You can use a merge:</p> <pre><code>df_new = df1.merge(df2[['address1', 'zipcode']], on='address1', how='left') df_new = df_new.fillna('no_match') </code></pre>
python|pandas|numpy|dataframe
1
16,607
57,073,490
Fastest way to compute a column of a dataframe
<p>I'm getting a pandas issue that I need help with.</p> <p>On the one hand, I have a DataFrame that looks like the following:</p> <pre><code> contributor_id timestamp edits upper_month lower_month 0 8 2018-01-01 1 2018-04-01 2018-02-01 1 26424341 2018-01-01 ...
<p>Use list comprehension with flattening for test membership between zipped columns converted to tuples and values in range, create <code>DataFrame</code> and <code>sum</code> in generator:</p> <pre><code>rng = pd.date_range('2018-01-01', freq='MS', periods=12) vals = list(zip(df['lower_month'], df['upper_month'])) ...
python|pandas|dataframe
3
16,608
56,875,250
Plot line graph Seaborn while iterating across columns
<p>Given: </p> <pre><code> Month = ["Jan","Feb","Mar","Apr","May","Jun"] Apple= [500,180,1141, 1209, 600,1200] Orange= [900,350,198,789,650,500] Cherry = [852,415,874,404, 692,444] list = {'Month': Month, 'Apple': Apple, 'Orange': Orange, 'Cherry': Cherry} </code></pre> <p>I'm trying to plot ...
<p>IIUC, you want <code>hue</code> in <code>seaborn</code>:</p> <pre><code>df = pd.DataFrame(lst) new_df = df.melt(id_vars='Month', value_name='val', var_name='type') sns.lineplot(x='Month', y='val', hue='type', data=new_df) </code></pre> <p>Output:</p> <p><a href="https://i.stac...
python|pandas|dataframe
1
16,609
57,029,867
Making multiple copies of a smaller matrix into a bigger matrix
<p>So suppose I have a 2by2 numpy array. I want to create another 2 by 2 numpy array so that the elements will each be the previous 2by2 array, without using an explicit for loop. How can I achieve this? The shape of the new numpy matrix should be (2,2,2,2)</p>
<p><strong>This helps you copy the numpy matrix.</strong> But I really did not understand your point</p> <pre><code>import numpy as np a = np.matrix('1,2; 3,2; 3,2') b = a.copy() </code></pre>
python|numpy
0
16,610
57,027,615
pandas groupby followed by resample work differently with datetime in index and datetime in different column
<p>// The comments have made me realize that this is actually a far broader question about how the <code>on</code> keyword works in <code>.reshape</code>. I left the old question below for reference, but I think the question is much broader.</p> <p>Here's a reproducible example; I would expect the first two statements...
<p>You need to use "apply" on a custum function and let pandas adapt itself to the output.</p> <pre><code>def my_func(grouped): my_sum = grouped.resample('D', on = 'DATETIME').X.sum() return my_sum </code></pre> <p>Now call this function on your groupby object:</p> <pre><code>df[df.GROUP == 'B'].groupby("GROUP")...
pandas|pandas-groupby
0
16,611
45,915,198
Why is order of data items reversed while creating a pandas series?
<p>I am new to python and pandas so please bear with me. I tried searching the answer everywhere but couldn't find it. Here's my question:</p> <p>This is my input code:</p> <pre><code>list = [1, 2, 3, 1, 2, 3] s = pd.Series([1, 2, 3, 10, 20, 30], list) </code></pre> <p>The output is:</p> <pre><code>1 1 2 2 ...
<p>I think you omit <code>index</code> which specify first column called <code>index</code> - so <code>Series</code> construction now is:</p> <pre><code>#dont use list as variable, because reversed word in python L = [1, 2, 3, 1, 2, 3] s = pd.Series(data=[1, 2, 3, 10, 20, 30], index=L) print (s) 1 1 2 2 3 ...
python-3.x|pandas
1
16,612
45,871,191
groupby same partial string of pandas dataframe
<p>I've been using pandas to export JSON data to a csv file. Now, I've been asked to group this data and get the sum for each date grouped by <code>system</code>. Below is an example of my DataFrame.</p> <p><strong>DataFrame:</strong></p> <pre><code>system,totalCapacity,totalLocatedCapacity,availableCapacity,date aad...
<p>Are you looking for</p> <pre><code>df.groupby([df.system.str[:2], 'date']).sum().reset_index() system date totalCapacity totalLocatedCapacity availableCapacity 0 aa 20170728 281001546 272202901 91479738 1 bb 20170728 78074304 46757718 56387268 </co...
python|pandas
4
16,613
28,506,194
Identify time point in DataFrame based on condition per time series
<p>I have a DataFrame with time series data, as such below:</p> <p>(TP = time point)</p> <pre><code>gene number TP1 TP2 TP3 TP4 TP5 TP6 gene1 0.4 0.2 0.1 0.5 0.8 1.9 gene2 0.3 0.05 0.5 0.8 1.0 1.7 .... </code></pre> <p>For each row (gene), I want to identify the TP at w...
<p>You could first create a mask <code>ma</code> and set all the row values before the minimum to <code>False</code>. Next, use this mask find the values in each row <em>after</em> the minimum to hit 4 times the minimum (indicated by <code>True</code>):</p> <pre><code>&gt;&gt;&gt; ma = df.values.argmin(axis=1)[:,None]...
python|pandas|numpy|dataframe
1
16,614
50,692,239
Pandas Getting each business day of a year by using date range function
<p>I am trying to get all business day of a year by using pandas date_range function.But i am missing some necessary parameters to get my desired result.</p> <pre><code>pd.date_range('2015-01-01', '2015-12-31', freq='D') DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04', '2015-01-05...
<p>Use the <code>freq</code> <code>B</code> for business days</p> <pre><code>pd.date_range('2015-01-01', '2015-12-31', freq='B') DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-05', '2015-01-06', '2015-01-07', '2015-01-08', '2015-01-09', '2015-01-12', '2015-01-13', '2015-01-14', ...
pandas|data-science|pandas-groupby|date-range|data-science-experience
2
16,615
50,698,208
Python - CSV - Calculate average of column values by a column id
<p>I have a very large CSV file that I managed to order by a column id, but I cannot calculate the average column values that have that column id.</p> <pre><code>88741,42.84286022,16.41829224,1 88797,42.78081536,16.40743455,1 88797,42.78081536,16.21153455,1 88823,42.51512511,16.43304948,2 88885,42.88204193,16.12412548...
<p>I believe need convert values to numeric first if necessary:</p> <pre><code>df[['Lat','Long']] = df[['Lat','Long']].apply(pd.to_numeric, errors='coerce') </code></pre> <p>And then aggregate <code>mean</code> per groups:</p> <pre><code>df.groupby('Cluster')['Lat','Long'].mean() </code></pre>
python-3.x|pandas|csv
0
16,616
50,797,803
Changing format of date in pandas dataframe
<p>I have a pandas dataframe, in which a column is a string formatted as</p> <pre><code>yyyymmdd </code></pre> <p>which should be a date. Is there an easy way to convert it to a recognizable form of date?</p> <p>And then what python libraries should I use to handle them? Let's say, for example, that I would like to ...
<p>Ok so you want to select Mon-Friday. Do that by converting your column to datetime and check if the <code>dt.dayofweek</code> is lower than 6 (Mon-Friday --> 0-4) </p> <pre><code>m = pd.to_datetime(df['date']).dt.dayofweek &lt; 5 df2 = df[m] </code></pre> <p>Full example:</p> <pre><code>import pandas as pd df ...
python|python-3.x|pandas|date
2
16,617
50,702,033
What is DataFrame.columns.name?
<p>Could you explain to me, what the purpose of the 'DataFrame.columns.name' attribute is? </p> <p>I unintentionally got it after creating a pivot table and resetting the index. </p> <pre><code>import pandas as pd df = pd.DataFrame(['a', 'b']) print(df.head()) # OUTPUT: # 0 # 0 a 1 b df.columns.name = 'temp...
<p>giving name to column levels could be useful in many ways when you manipulate your data.</p> <p>a simple example would be when you use `stack()'</p> <pre><code>df = pd.DataFrame([['a', 'b'], ['d', 'e']], columns=['hello', 'world']) print(df.stack()) 0 hello a world b 1 hello d world e df.column...
python|pandas|dataframe
2
16,618
50,992,946
Cast KERAS Tensor to K.tf.int32
<p>This is from a Custom Keras Callback casted=K.cast((yPred), K.tf.int32)</p> <p>I absolutely need to cast yPred, which is a Tensor, to the type int32 (The cast is applied to the Tensor content, I know that)</p> <p>Still, K.cast allow only a conversion to float. </p> <p>How can I solve the problem?</p>
<p>This is how you do it:</p> <pre><code>casted = K.cast(yPred,"int32") </code></pre>
python|tensorflow|casting|keras|tensor
6
16,619
33,378,318
For-loop using dictionary key reference not working
<p>I have never used Python before but have decided to start learning it by manipulating some market data. I am having trouble using the dictionary structures. In the code for <em>read_arr_price</em> below the command <strong>dict_price_recalc[price_id][year_to_index(year), Q] = float(line2)/7.5</strong> assigns <stron...
<p>this line <code>price_id[key] = np_array</code> is setting the same array to each key so every key points to the same array. you probably meant <code>price_id[key] = np_array.copy()</code></p>
python|numpy|dictionary
2
16,620
9,074,996
matplotlib: how to annotate point on a scatter automatically placed arrow?
<p>if I make a scatter plot with matplotlib:</p> <pre><code>plt.scatter(randn(100),randn(100)) # set x, y lims plt.xlim([...]) plt.ylim([...]) </code></pre> <p>I'd like to annotate a given point <code>(x, y)</code> with an arrow pointing to it and a label. I know this can be done with <code>annotate</code>, but I'd l...
<p>Basically, no, there isn't. </p> <p>Layout engines that handle placing map labels similar to this are surprisingly complex and beyond the scope of matplotlib. (Bounding box intersections are actually a rather poor way of deciding where to place labels. What's the point in writing a ton of code for something that ...
python|numpy|matplotlib|scipy
44
16,621
9,280,488
How to store numerical lookup table in Python (with labels)
<p>I have a scientific model which I am running in Python which produces a lookup table as output. That is, it produces a many-dimensional 'table' where each dimension is a parameter in the model and the value in each cell is the output of the model.</p> <p>My question is how best to store this lookup table in Python....
<p>Why don't you use a database? I have found <a href="http://www.mongodb.org/" rel="nofollow">MongoDB</a> (and the official Python driver, <a href="http://www.mongodb.org/display/DOCS/Python+Language+Center" rel="nofollow">Pymongo</a>) to be a wonderful tool for scientific computing. Here are some advantages:</p> <ul...
python|numpy
4
16,622
66,748,416
How can I subtract a value from all values in the imported CSV file?
<p>I have read in a CSV file with one column. The column contains almost 300 rows of different values. From these values I want to subtract a certain value <code>b=0.157</code>. These new approx. 300 values should be saved in a new CSV file (array). How can I do this?</p> <p>This is the csv - file: <strong>wearable.csv...
<p>You can use the broacasting property of <code>numpy</code> (<code>pandas</code> is based on <code>numpy</code> arrays) and simply subtract a constant value from the dataframe.</p> <p><strong>Edit</strong>: adding the part to save to file</p> <pre><code>import pandas as pd import numpy as np b = 0.157 df = pd.DataFr...
python|pandas|csv|for-loop|subtraction
1
16,623
66,591,446
How to suppress scientific notation in values in a pandas dataframe?
<p>I have <code>pandas.DataFrame</code> that contains some values with scientific notation and I want to change those values to a normal value without the <code>e+..</code>.</p> <pre><code>import pandas as pd df = pd.DataFrame( [7.70000e+05, 4.5000000e+09, 3.219500e+05, 25000, 476577], columns = ['Price']) </c...
<p>You can try something like this:</p> <pre><code>pd.set_option(&quot;float_format&quot;, lambda x: f&quot;{x:.2f}&quot;) df Price 0 770000.00 1 4500000000.00 2 321950.00 3 25000.00 4 476577.00 </code></pre>
python|pandas
1
16,624
66,414,456
Update visibility of Traces with fig.update_layout Plotly
<p>Following on from this quesiton: <a href="https://stackoverflow.com/questions/66226542/set-sqrt-as-yaxis-scale-from-dropdown-or-button-python-plotly">Set sqrt as yaxis scale from dropdown or button-Python/Plotly</a></p> <p>I want to :</p> <ol> <li>Define a plot with all traces: visible = False</li> </ol> <pre class=...
<p>In this case you can conditionally update the trace as shown <a href="https://plotly.com/python/creating-and-updating-figures/#conditionally-updating-traces" rel="nofollow noreferrer">here</a>.</p> <p>First when you add each trace give it a <code>name</code> (using 'linear' and 'sqrt' in this case):</p> <pre><code>f...
python|pandas|plotly
2
16,625
57,522,176
Perform calculations based on signals in array
<p>I have two columns - a 'close' column and a 'signals' column in an array. I would like to perform calculations on data in the 'close' column based on classified data that is in the 'signals' column. If the same signal appears consecutively (ignoring NANs) then do nothing, only perform a calculation when the 'signals...
<p>One way might be:</p> <ol> <li>Extract rows where "signals" are not null using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>dropna</code></a></li> <li>Remove consecutive duplicates using <a href="https://pandas.pydata.org/pandas-do...
python|pandas|loops|numpy|signals
1
16,626
24,151,207
Concatenating data in different columns into a single column (pandas, python)
<p>I am looking for the logic to concatenate the values in many columns with related data from an .xlsx file into a single column using pandas in python. The logic to combine each different column would be different depending on what information the column contains. For example:</p> <pre><code>input: ID,when_carpool...
<p>Join all the columns into a new one:</p> <pre><code> df["carpool_info"] = df.apply(lambda x: "+".join([str(x[i]) for i in range(len(x))]),axis=1) </code></pre> <p>and then drop the other columns you don't need (see also here: <a href="https://stackoverflow.com/questions/13411544/delete-column-from-pandas-datafr...
python|excel|pandas
2
16,627
43,654,244
Pandas Python Data Frame: Adding a column depending on the rest
<p>I have two data frames and I want to join them using a "key" that I am going to create. My data frames are of the form:</p> <pre><code>Column1 Column2 Column3 1 240 31-02-16 2 350 25-03-16 3 100 31-03-16 4 500 13-02-16 </code></pre> <p>and I want ...
<p>Simpliest is cast to <code>string</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow noreferrer"><code>astype</code></a> each column:</p> <pre><code>df['new'] = df.Column1.astype(str) + "_" + df.Column2.astype(str) + "_" + df.C...
python|pandas|dataframe
0
16,628
43,560,486
How to change the dtype of a numpy array to 'object'?
<p>My goal is to do this:</p> <pre><code>weights[1][0][0] = some_object(1) </code></pre> <p>But it throws this error:</p> <pre><code>TypeError: float() argument must be a string or a number, not 'some_object' </code></pre> <p>Because of this I wawnt to change the dtype to 'object' In my code I have weights. They lo...
<p>Let's make sure we understand what you are starting with:</p> <pre><code>In [7]: weights Out[7]: [array([[-2.66665269, 0. ], [-0.36358187, 0. ], [ 1.55058871, 0. ], [ 3.91364328, 0. ]]), array([[ 0.], [ 0.]])] In [8]: len(weights) Out[8]: 2 In [9]: we...
python|numpy|object
4
16,629
43,727,520
Speed up JSON to dataframe w/ a lot of data manipulation
<p>I have a massive blob of JSON data formatted as follows:</p> <pre><code>[ [{ "created_at": "2017-04-28T16:52:36Z", "as_of": "2017-04-28T17:00:05Z", "trends": [{ "url": "http://twitter.com/search?q=%23ChavezSigueCandanga", "query": "%23ChavezSigueCandanga", ...
<p>You could speed things up by async flattening the data with <a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow noreferrer">concurrent.futures</a>, then loading it all into a DataFrame with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html...
python|json|pandas|dataframe
3
16,630
43,747,102
Indexing a numpy 2D matrix
<p>Suppose, I have this:</p> <pre><code>import numpy as np N = 5 ids = [ 1., 2., 3., 4., 5., ] scores = [ 3.75320381, 4.32400937, 2.43537978, 3.73691774, 2.5163266, ] ids_col = ids.copy() scores_col = scores.copy() students_mat = np.column_stack([ids_col, scores_col])...
<pre><code>#you need to convert Boolean list to an array to be used when selecting elements. print(students_mat[np.asarray([False, True, False, False, False])]) [[ 2. 4.32400937]] </code></pre>
python|numpy
2
16,631
1,987,694
How do I print the full NumPy array, without truncation?
<p>When I print a numpy array, I get a truncated representation, but I want the full array.</p> <pre><code>&gt;&gt;&gt; numpy.arange(10000) array([ 0, 1, 2, ..., 9997, 9998, 9999]) &gt;&gt;&gt; numpy.arange(10000).reshape(250,40) array([[ 0, 1, 2, ..., 37, 38, 39], [ 40, 41, 42, ..., ...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html" rel="noreferrer"><code>numpy.set_printoptions</code></a>:</p> <pre><code>import sys import numpy numpy.set_printoptions(threshold=sys.maxsize) </code></pre>
python|arrays|numpy|output-formatting
883
16,632
72,925,872
split arrays as string in one column of pandas to multiple columns
<p>I have data frame in the below format. The description is in string format.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>file</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>[[array(['MIT', 'MIT', 'MIT', 'MIT', 'MIT'], dtype=object), array([0.71641791, 0.71641791,...
<p><strong>Update,</strong> If elements in the column as string format, you can find array with <code>regex</code> formula. <em>(Note don't use eval, <a href="https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided">Why should exec() and eval() be avoided?</a>)</em></p> <pre><code>import ast new...
python|pandas|string|dataframe
1
16,633
73,123,821
How to find the last line and the diff of each line
<p>I am trying to handle the following dataframe</p> <pre><code>df = pd.DataFrame({'ID':[1,1,2,2,3,3,3,4,4,4,4], 'sum':[1,2,1,2,1,2,3,1,2,3,4,]}) </code></pre> <p>Now I want to find the difference from the last row by each ID.</p> <p>Specifically, I tried this code.</p> <pre><code>df['diff'] = df.gro...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>transform('last')</code></a> to get the last value per group:</p> <pre><code>df['diff'] = df['sum'].sub(df.groupby('ID')['sum'].transform('last')) </code></pre> <p>or...
python|pandas|group-by
1
16,634
73,002,191
Pandas DataFrame (long) to Series ("wide")
<p>I have the following DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: right;">completeness</th> <th style="text-align: right;">homogeneity</th> <th style="text-align: right;">label_f1_score</th> <th style="text-align: right...
<p>IIUC, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> and flatten the index:</p> <pre><code>df2 = df.unstack() df2.index = df2.index.map('_'.join) </code></pre> <p>output:</p> <pre><code>completeness_mean 0.100000 completen...
python|pandas
3
16,635
73,103,019
Creating a new column sequence based on another column within a dataframe
<p>I have a dataframe <code>Outfall</code> which has a sequence in the column <code>['Head']</code>. The goal is to then make another column relative to <code>['Head']</code> called <code>['OHead']</code> which starts a new sequence once a certain value is matched. I dont have any issues applying a lamda function to cr...
<p>IIUC,</p> <pre><code>data = Outfall[Outfall &lt;= To].dropna().tail(1).reset_index(drop=True).at[0,'Head'] Outfall['Head'].apply(lambda x: 0 if x &lt;= data else x - data) </code></pre> <p>or</p> <pre><code>data = Outfall[Outfall &lt;= To].dropna().tail(1).reset_index(drop=True).at[0,'Head'] Outfall['OHead'] = np.wh...
python|pandas|dataframe|lambda|list-comprehension
0
16,636
72,899,320
Subtract time only from two datetime columns in Pandas
<p>I am looking to do something like in <a href="https://stackoverflow.com/questions/54166156/adding-subtracting-datetime-time-columns-pandas">this thread</a>. However, I only want to subtract the <code>time</code> component of the two <code>datetime</code> columns.</p> <p>For eg., given this dataframe:</p> <pre><code>...
<p>Since you only want the <em>time difference</em> and you're not working with timezone-aware datetime, the date does not matter. Therefore you don't have to change any dates or set some arbitrary reference date. Just work with what you have.</p> <p>Subtract ts1's time component from ts2 as a timedelta, then convert t...
python|pandas|datetime|timedelta
1
16,637
70,724,327
Finding the average and the standard deviation of three data sets
<p>I have a laser that is sent through a signal splitter. 90% of the light goes into a diffuser and that is detected by a Photomultiplier tube (PMT). The other 10% of the signal goes to a separate silicon photodiode that is used to monitor the power of the laser during diffuser testing. The diffuser is rotated through ...
<p>You can organize your data in a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer"><strong><code>pandas.DataFrame</code></strong></a>, where you have a column for angle values, then a column for each diode:</p> <pre><code>columns = ['diode1', 'diode2', 'diode3'] di...
python|pandas|dataframe|matplotlib|data-visualization
1
16,638
70,514,408
Pandas: convert two times to datetime, then take the difference and display back as only times
<p>I have the following toy Pandas dataframe named <code>df</code>:</p> <pre><code>df = pd.DataFrame({'begin' : ['08:00', '10:00', '14:00'], 'end' : ['14:00', '17:00', '22:00']}) begin end 08:00 14:00 10:00 17:00 14:00 22:00 </code></pre> <p>I would like to calculate...
<p>Coerce the time to datetime, substract and convert outcome to hours</p> <pre><code> df['diff_hours']=(pd.to_datetime(df['end'], format=&quot;%H:%M&quot;)-pd.to_datetime(df['begin'], format=&quot;%H:%M&quot;)).astype('timedelta64[m]')/60 begin end diff_hours 0 08:00 14:00 6.0 1 10:00 17:00 ...
python|pandas
3
16,639
70,626,231
How to calculate mean/variance/standard deviation per index of array?
<p>I have some data like [[0, 1, 2], [0.5, 1.5, 2.5], [0.3, 1.3, 2.3]].</p> <p>I am using numpy and python and I wish to calculate the mean and standard deviation for my data, per index. So I wish to calculate the mean/std for (0, 0.5, 0.3) (e.g. index 0 of each subarray), (1, 1.5, 1.3) (e.g. index 1 of each subarray),...
<p>The various statistics functions all take an <code>axis</code> argument that will allow you to calculate the statistic over a column:</p> <pre><code>import numpy as np a = np.array([[0, 1, 2], [0.5, 1.5, 2.5], [0.3, 1.3, 2.3]]) np.mean(a, axis=0) # array([0.26666667, 1.26666667, 2.26666667]) np.std(a, axis=0) # a...
python|arrays|numpy|statistics|mean
1
16,640
70,476,585
Why optimize in the einsum can accelerate binary contraction?
<p>In <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.einsum.html</a></p> <blockquote> <p>optimize{False, True, ‘greedy’, ‘optimal’}, optional Controls if intermediate optimization should occur. No optimization...
<p>My timings:</p> <pre><code>In [26]: A = np.random.random((90,80)) In [27]: B = np.random.random((80,81,82)) In [28]: timeit np.einsum('ab,bcd-&gt;acd',A,B,optimize=False) 39.2 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [29]: timeit np.einsum('ab,bcd-&gt;acd',A,B,optimize=True) 9.06 ms ± 70....
python|numpy|numpy-einsum
3
16,641
42,691,991
Python - Pandas: How to add a series to each row in dataframe
<p>I have this dataframe.</p> <pre><code>&gt;&gt;&gt; print(df) a b c d e 0 z z z z z 1 z z z z y 2 z z z x y 3 z z w x y 4 z v w x y </code></pre> <p>I also have a series.</p> <pre><code>&gt;&gt;&gt; print(map_class) class 0 -1 1 0 2 1 3 2 4 3 5 ...
<p>Here's an approach making use of NumPy for creating the output data and specifically in it, using <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer"><code>NumPy's advanced-indexing</code></a> and finally constructing a dataframe from that output data...
python-3.x|pandas|numpy
2
16,642
27,134,330
python/numpy - How to use einsum in the following example?
<p>I have the following:</p> <p>sum_XY C_x I_xk Cy I_yl P_xy</p> <p>currently my code looks like this:</p> <pre><code># initialise dummy values Nk = Nl = 100 NX = Ny = 10 Ix = np.random.rand(Nx, Nk) Iy = np.random.rand(Ny, Nl) C = np.random.rand(Nk) Pin = np.ones(Nx*Ny) # point 1 Fx = (Ix * C[np.newaxis, :Nk]).T # ...
<p>Starting with <code>point2</code>, this matches your calculation.</p> <pre><code>H2 = np.einsum('kx,ly-&gt;klxy', Fx, Fy) out2 = np.einsum('klxy,xy-&gt;kl', H2, np.ones((Nx,Ny))) print np.allclose(out, out2) </code></pre> <p>I tried to choose einsum indexes to match your shape parameters. I tested it with</p> <p...
python|numpy
0
16,643
27,030,424
How can I make a one-dimensional array into a two-dimensional array using numpy?
<p>I have data that looks like this: </p> <pre><code>&gt;&gt;&gt;npfilled[:5] array([('!', 0, 0, 3, 10, 0, 2, 4, 4), ('!"', 0, 0, 0, 5, 0, 0, 0, 0), ('"', 23, 13, 20, 32, 0, 0, 22, 9), ("'", 21, 8, 23, 12, 5, 10, 0, 7), ('(', 3, 2, 2, 3, 0, 0, 0, 0)], dtype=[('token', '&lt;U64'), ('mel_freq1', '&...
<p>In numpy terms, you're asking how to convert a structured array into a "normal" 2D array, where each item in the structure is along a new axis.</p> <p>On a quick side note, for heterogeneous data such as this, <code>pandas</code> is probably more what you're looking for. </p> <p>That having been said, here's a qu...
python|arrays|numpy
2
16,644
27,384,489
AttributeError: 'NoneType' object has no attribute 'ravel'
<p>Can someone please tell me what is wrong with this code? I keep on getting a <code>NoneType</code> error. I am trying to create a histogram. </p> <pre><code>import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('C:\Pictures\naturalScene.bmp',0) plt.hist(img.ravel(),256,[0,256]); plt.s...
<p>From the <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html" rel="nofollow">docs</a>:</p> <blockquote> <p>The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or...
python|opencv|numpy|matplotlib|image-compression
4
16,645
14,751,165
Using MultiIndex on DataFrame
<p>This is follow-up question to the answer for this question:</p> <p><a href="https://stackoverflow.com/questions/14737566/pandas-performance-issue-need-help-to-optimize/14750813#14750813">pandas performance issue - need help to optimize</a></p> <p>The following suggestion works:</p> <pre><code>df = DataFrame(np.a...
<p>To show it works for me (pandas 0.10.1):</p> <pre><code>In [1]: from StringIO import StringIO In [2]: import numpy as np In [3]: import pandas as pd In [4]: s = StringIO("""col1,col2,year,amount ...: 111111,3.5,2012,700 ...: 111112,3.5,2011,600 ...: 222221,4.0,2012,222""") In [5]: sd=pd.read_csv(s) ...
python|pandas
1
16,646
38,970,423
netCDF convert to NaN for conditional
<p>I want to convert values from a netCDF file into NaN called <code>LandMask_NaN</code> when they are greater than zero. However, there seems to be a type mismatch between <code>LandMask</code> and what numpy will convert to NaNs. Any help much appreciated, code and info below:</p> <pre><code> import netCDF4 as nc i...
<p>It'll be helpful if you share the netcdf file, but here are a few ideas of what's going on:</p> <p>Variables are not currently being read-in as numpy arrays. You need to add indexing parameters to cast them to arrays. Without the file, I'm not sure what they are, but surely some are multi-dimensional. For example:...
python|numpy|nan|netcdf4
1
16,647
39,298,783
Using only part of comma delimited files
<p>I know that in Python, if you have a comma-delimited file that reads something like</p> <pre><code>1,5 2,4 3,3 4,2 5,1 </code></pre> <p>you can do something similar to the following:</p> <pre><code>import numpy as np x, y = np.loadtxt('example.txt', delimiter=',', unpack=True) plt.plot(x,y, label='myLine') </cod...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow"><code>np.loadtxt</code></a> with <code>usecols=(1, 2)</code>:</p> <blockquote> <p>usecols : sequence, optional - Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract th...
python|csv|numpy
0
16,648
23,753,476
Fill non-consecutive missings with consecutive numbers
<p>For a given data frame...</p> <pre><code>data = pd.DataFrame([[1., 6.5], [1., np.nan],[5, 3], [6.5, 3.], [2, np.nan]]) </code></pre> <p>that looks like this...</p> <pre><code> 0 1 0 1.0 6.5 1 1.0 NaN 2 5.0 3.0 3 6.5 3.0 4 2.0 NaN </code></pre> <p>...I want to create a third...
<p>You can do it this way, I took the liberty of renaming the columns to avoid the confusion of what I am selecting, you can do the same with your dataframe using:</p> <pre><code>data = data.rename(columns={0:'a',1:'b'}) In [41]: data.merge(pd.DataFrame({'c':range(1,len(data[data.b.isnull()]) + 1)}, index=data[data....
python|pandas
1
16,649
23,917,144
Python Pandas DateOffset using value from another column
<p>I was thinking this would be very easy but the below is not working for what I want. Just trying to compute a new date column by adding days to a pre-existing datetime column using values from another column. My 'offset' column below just has 1 digit numbers.</p> <pre><code>df['new_date'] = df['orig_date'].apply(la...
<pre><code>In [12]: df['C'] = df['A'] + df['B'].apply(pd.offsets.Day) In [13]: df Out[13]: A B C 0 2013-01-01 0 2013-01-01 1 2013-01-02 1 2013-01-03 2 2013-01-03 2 2013-01-05 3 2013-01-04 3 2013-01-07 4 2013-01-05 4 2013-01-09 </code></pre>
python|pandas|time-series
10
16,650
22,833,404
How do I plot hatched bars using pandas?
<p>I am trying to achieve differentiation by hatch pattern instead of by (just) colour. How do I do it using pandas?</p> <p>It's possible in matplotlib, by passing the <code>hatch</code> optional argument as discussed <a href="https://stackoverflow.com/questions/14279344/how-can-i-add-textures-to-my-bars-and-wedges">h...
<p>This is kind of hacky but it works:</p> <pre><code>df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) ax = plt.figure(figsize=(10, 6)).add_subplot(111) df.plot(ax=ax, kind='bar', legend=False) bars = ax.patches hatches = ''.join(h*len(df) for h in 'x/O.') for bar, hatch in zip(bars, hatches): ...
python|matplotlib|plot|pandas
26
16,651
22,840,900
Hard time finding Python-Numpy deg2rad function
<p>Title says it all, I somehow can not find that function. Obviously it's inside the Numpy package (numpy.core.umath.deg2rad) and I've tried importing it but to no avail. Anyone care to chime in?</p> <ul> <li>import numpy as np - np.deg2rad doesn't even show up</li> <li>from numpy import* - umath.deg2rad shows up, bu...
<pre><code>from numpy.core.umath import deg2rad # then deg2rad(...) </code></pre> <p>Or</p> <pre><code>import numpy as np np.core.umath.deg2rad(...) </code></pre>
python|numpy|vector|scipy|degrees
2
16,652
15,125,407
dealing with zero log values in numpy/pandas
<p>I have a dataframe in pandas that stores a column containing ratios. The ratios need to be transformed into a <code>log2</code> scale for plotting but the ratio values are often 0, leading in <code>log2(0)</code> which is recorded as <code>inf</code> or a missing value in pandas. I want to visualize these since in m...
<p>I guess you can use <code>numpy.inf</code> to identify those that are <code>infinity</code> and treat them separately.</p> <p>Ref: <a href="https://github.com/pydata/pandas/issues/2858" rel="nofollow">github.com/pydata/pandas</a></p>
python|numpy|pandas
3
16,653
14,954,354
numpy correlation coefficient
<p>1) How can I find correlation for the following data set using python code?</p> <pre><code>T = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] P = [ 3480. 7080. 10440. 13200. 16800. 20400. 23880. 27480. 30840. 38040. 41520. 44880. 48480. 52080. 55680. 59280. 62520. 66120. 67580. 69620. 69621.] </code></pre> <p>2) **i...
<p>To calculate correlations between two series of data, i use <code>scipy.stats</code>. I would recommend you to investigate this package.</p> <p>From the <a href="http://docs.scipy.org/doc/scipy/reference/stats.html" rel="nofollow">docs</a>:</p> <pre><code>pearsonr(x, y) #Pearson correlation coefficient and the p-v...
python|numpy
3
16,654
29,356,412
Efficiently re-indexing one level with "forward-fill" in a multi-index dataframe
<p>Consider the following DataFrame:</p> <pre><code> value item_uid created_at 0S0099v8iI 2015-03-25 10652.79 0F01ddgkRa 2015-03-25 1414.71 0F02BZeTr6 2015-03-20 51505.22 2015-03-23 51837.97 2015-03-24 51578.63 2015-03-25 NaN ...
<p>You have a couple of options, the easiest IMO is to simply unstack the first level and then ffill. I think this make it much clearer about what's going on than a groupby/resample solution (I suspect it will also be faster, depending on the data):</p> <pre><code>In [11]: df1['value'].unstack(0) Out[11]: item_uid ...
python|pandas
6
16,655
29,777,702
Aggregate all dataframe row pair combinations using pandas
<p>I use python pandas to perform grouping and aggregation across data frames, but I would like to now perform specific pairwise aggregation of rows (n choose 2, statistical combination). Here is the example data, where I would like to look at all pairs of genes in [mygenes]:</p> <pre><code>import pandas import itert...
<p>I can't think of a clever vectorized way to do this, but unless performance is a real bottleneck I tend to use the simplest thing which makes sense. In this case, I might <code>set_index("Gene")</code> and then use <code>loc</code> to pick out the rows:</p> <pre><code>&gt;&gt;&gt; df = df.set_index("Gene") &gt;&gt...
python|pandas|aggregate|combinations|itertools
11
16,656
29,628,410
How do I multiply each element in an array with a large number without getting OverflowError: Python int too large to convert to C long?
<p>I'm writing a program where I want to multiply each number in an array (from numpy) with a big number (<code>1.692287392646066e+41</code>) and I do it like this:</p> <pre><code>x = array([ 16, 18, 19, 15, 27, 26, 13, 34, 38, 36, 43, 42, 48, 50, 55, 57, 70, 67, 65, 85, 99, 94, 90, 112, 126, ...
<p>It makes no sense to make the multiplication in <code>python</code> and not in <code>numpy</code>. Not only is <code>numpy</code> faster, but it also works better.</p> <p>What you are trying to do creates a <code>python list</code>, which it then tries to copy into the <code>numpy array</code> element wise.</p> <p...
python|arrays|for-loop|numpy
3
16,657
29,797,012
pandas: How to Series.sort_index() in-place?
<p>Is it possible to sort_index a pandas' Series in-place?</p> <p>Well, of course, you can do this:</p> <pre><code>ser = ser.sort_index() </code></pre> <p>What I'm actually trying to do is to sort_index a Series-derived class, like this:</p> <pre><code>class SeriesAutoSorted(Series): def append(self, index, va...
<p>There's an undocumented <code>Series._update_inplace()</code> method that you could use. Pandas uses this <a href="https://github.com/pydata/pandas/blob/69087192747ea670e1e781b25371f40ffec31073/pandas/core/series.py#L1784" rel="nofollow">internally</a></p> <p>Here's an example:</p> <pre><code>In [50]: ser = pd.Ser...
python|pandas
2
16,658
62,107,071
How do I show pie graph in 2 row and 2 column in Python
<p>I have a problem about showing pie graphs in 2 row and 2 column. They are listed in one column.</p> <p>How can I fix the issue?</p> <p>Here is my code snippets shown below.</p> <pre><code>plt.figure(figsize = (8,8)) ax1 = plt.subplot(2,2,1) coursera_df_beginner["course_Certificate_type"].value_counts().plot(kind=...
<p>Here is my answer</p> <pre><code>f,a = plt.subplots(2,2,figsize=(8,8)) f.subplots_adjust(wspace = .8) coursera_df_beginner["course_Certificate_type"].value_counts().plot(kind='pie', shadow=True, ...
python|pandas|pie-chart
0
16,659
62,425,222
Return data indices for all bins with counts greater than threshold
<p>I am trying to find the indices all within a certain bin of the data binned liked this: </p> <pre><code>import numpy as np x=np.random.random(1000) y=np.random.random(1000) #The bins are not evenly spaced and not the same number in x and y. xedges=np.array(0.1,0.2, 0.4, 0.5, 0.55, 0.6, 0.8, 0.9) yedges=np.arange(...
<p>If I understand correctly, you want to build a mask on the original points indicating that the point belongs to a bin with more than 5 points.</p> <p>To construct such a mask, <code>np.histogram2d</code> returns the counts for each bin, but does not indicate which point goes into which bin.</p> <p>You can construc...
python|numpy|scipy|histogram|binning
1
16,660
62,063,777
Creating pandas DataFrame through class returns empty DataFrame
<p>The purpose of this script is to produce a data frame that is generated through code written in object oriented style.</p> <p>The problem is the outcome of this script is an empty data frame.</p> <p>There is no error.</p> <p>Here is the code:</p> <pre><code>import pandas as pd class Dataframe: def __init__...
<p>You need to call the methods you have created to populate the DataFrame.</p> <pre><code>import pandas as pd class Dataframe: def __init__(self): self.df = pd.DataFrame() self.name() self.age() self.sex() self.address() def name(self): self.df['name'] = ["Ha...
python|pandas|oop
3
16,661
51,523,380
Python 3.6.5 returns '<' not supported between instances of 'tuple' and 'str' error message
<p>I'm trying to split a data set into a training and testing part. I am struggling at a structural problem as it seems as the hierarchy of the data seems to be wrong to proceed with below code.</p> <p>I tried the following:</p> <pre><code>import pandas as pd data = pd.DataFrame(web.DataReader('SPY', data_source='mor...
<p>As <code>data.head()</code> will reveal, <code>data</code> is not actually a <code>pd.DataFrame</code> but a <code>pd.Series</code> whose index is a <code>pd.MultiIndex</code> (as suggested also by the error which hints that each element is a tuple) rather than a <code>pd.DatetimeIndex</code>.</p> <p>What you could...
python|pandas|time-series|tuples|pandas-datareader
2
16,662
51,537,166
How to plot column from a dataframe
<p>I am trying to plot integer columns of dataframe. I am trying by following way</p> <pre><code>for i in df: if df[i].dtypes == 'int64': df[i].plot.kde() </code></pre> <p>But it is plotting all in the same graph. I am new to it and would like to know how can I do it?</p>
<p>Just try to add plot option in your loop:</p> <pre><code>for i in df: if df[i].dtypes == 'int64': df[i].plot.kde() plt.show() </code></pre>
pandas|dataframe|matplotlib|data-visualization
1
16,663
48,510,555
Pandas: Flag column if value in list exists anywhere in row
<p>Ultimately, I want to flag a new column, 'ExclusionFlag', with 0 or 1 depending on whether a value that is found in a list exists anywhere in the row. </p> <pre><code>df = pd.DataFrame([['cat','b','c','c'],['a','b','c','c'],['a','b','c','dog'],['dog','b','c','c']],columns=['Code1','Code2','Code3','Code4']) excluded...
<p>Something like</p> <pre><code>df['ExclusionFlag'] = df.isin(excluded_codes).any(1).astype(int) Code1 Code2 Code3 Code4 ExclusionFlag 0 cat b c c 1 1 a b c c 0 2 a b c dog 1 3 dog b c c 1 </code></pre>
python|pandas|conditional
10
16,664
48,547,617
Sum for a large dataframe?
<p>I have a large SparseDataFrame, approximately 12000 rows x 16000 columns. I want to calculate sum of rows grouped by a column:</p> <p>Input:</p> <pre><code>+-------+------+------+------+ | | Col1 | Col2 | Col3 | +-------+------+------+------+ | row 1 | Foo | 1 | 0 | | row 2 | Foo | 3 | 1 | | ro...
<p>This should be fast than <code>groupby</code></p> <pre><code>df.set_index('Col1').sum(level=0) Out[294]: Col2 Col3 Col1 Foo 4 1 Bar 5 3 </code></pre>
python|pandas
2
16,665
48,517,405
Chaining multiple combine_first()
<p>What would be a better way to chain multiple combine_first() statements. i.e.</p> <p>I have parsed some data, and have 3 different columns for cc-email. This works, but is there a cleaner way of doing it?</p> <pre><code>df['cc-email2'] = df['cc-email'].combine_first( df['cc-email_cc-email'].combine_first( df['cc-...
<p>I think you can use <code>reduce</code>:</p> <pre><code>from functools import reduce dfs = [df['cc-email'], df['cc-email_cc-email'], df['cc-emails_cc-email']] df['cc-email2'] = reduce(lambda l,r: l.combine_first(r), dfs) </code></pre> <p>But it seems <code>ffill</code> with select last column should working too:...
python|pandas
3
16,666
70,756,617
Keras GradientType: Calculating gradients with respect to the output node
<p>For startes: this question does not ask for help regarding reinforcement learning (RL), RL is only used as an example.</p> <p>The Keras documentation contains an example <a href="https://keras.io/examples/rl/actor_critic_cartpole/" rel="nofollow noreferrer">actor-critic reinforcement learning implementation</a> usin...
<p>Well, after some research I found the answer myself: It is possible to extract the trainable variables of a given layer based on the layer name. Then we can apply <code>tape.gradient</code> and <code>optimizer.apply_gradients</code> to the extracted set of trainable variables. My current solution is pretty slow, but...
python|tensorflow|keras|reinforcement-learning|gradienttape
0
16,667
70,980,642
Python Tensorflow Dataset Filter Set .issubset()
<p>I have a tensorflow dataset:</p> <pre><code>def fake_sequence(): seq = [np.random.choice([&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]) for _ in range(100)] mutate = [np.random.choice([&quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;]) for _ in range(100)] mask = np.random.choice...
<p>You could use a <code>tf.lookup.StaticHashTable</code> and <code>tf.cond</code> to solve what you want:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np def fake_sequence(): seq = [np.random.choice([&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]) for _ ...
python|tensorflow|set|tensorflow-datasets
1
16,668
70,929,624
Pandas - get first occurrence of a given column value
<p>I have a <code>df</code> with repeated <code>names</code> for different rounds of a tournament, like so:</p> <pre><code>name round_id price_open John 1 5.0 Paul 1 4.0 John 2 5.4 Paul 2 3.4 John 3 5.0 Paul 3 4.0 </code></pre> <p>But at round 3, a new playe...
<p>Use <code>drop_duplicates</code> to keep the first instance of each name:</p> <pre><code>&gt;&gt;&gt; df.drop_duplicates('name') name round_id price_open 0 John 1 5.0 1 Paul 1 4.0 6 George 3 6.0 </code></pre>
python|pandas|dataframe
3
16,669
70,785,103
Pandas MultiIndex dataframe to nested json
<p>I have the following pandas multi-index dataframe and I would like it to become a nested json object.</p> <pre><code>import pandas as pd data = {'store_id' : ['1', '1','1','2','2'], 'item_name' : ['apples', 'oranges', 'pears', 'persimmons', 'bananas'], '2022-01-01': [2.33, 1.99, 2.33, 2.33, 4.21], ...
<p>Use nested list comprehension for add custom format of inner dicts:</p> <pre><code>import json d = {level: {k1: [{'date': k, 'price': v} for k, v in v1.items()] for k1, v1 in df.xs(level).T.items()} for level in df.index.levels[0]} j = json.dumps(d) print (j) </code></pre>...
python|pandas|dataframe|multi-index|nested-json
1
16,670
51,970,251
Tensorflow: get predictions
<p>I try to get predictions and learning network.</p> <p>This is parameters of my network</p> <pre><code>X = tf.placeholder(tf.float32, shape=(None, X_train.shape[1]), name="input") y = tf.placeholder(tf.float32, shape=(None, y_train.shape[1]), name="y") y_cls = tf.argmax(y, axis=1) weights = tf.Variable(tf.truncate...
<p>There are multiple issues with your code and I think the error you posted here is one of the least significant.</p> <p>Lets go through your code and let me comment on some things. I hope this will be more helpful than just fixing the single <code>ValueError</code>.</p> <p>You start with the definition of two place...
python|tensorflow
1
16,671
51,842,534
How do I sum unique values per column in Python?
<p>I am working with weblogs and have data containing account_id and session_id. Multiple sessions can be associated with one account. I want to create a new dataframe containing account_id and count the number of unique sessions associated with that account. My df looks like this:</p> <pre><code>account_id session_id...
<pre><code>df = pd.DataFrame({'session': ['de322', 'de322', 'de322', 'de323', 'de323', 'ge012', 'ge012', 'ge013', 'ge333'], 'user_id': [1111, 1111, 1111, 1111, 1111, 210, 210, 210, 211], }) print(df) df = df.drop_duplicates().groupby('user_id').count() print(df) </code></pre> <p...
python|pandas|pandas-groupby
2
16,672
51,966,498
Pandas: Replace values of multiple columns using boolean masks
<p><strong>Question</strong>: Given DataFrame <code>b</code>, how can I replace the values of multiple columns, with one value, through boolean mask column identification?</p> <p><strong>What works, but I don't want:</strong></p> <pre><code>b.iloc[:, 2:6] = "someConstantValue" </code></pre> <p><strong>What doesn't w...
<p>You can use <code>iloc</code> with Boolean indexing, but be careful. It works with Boolean <strong>arrays</strong>, not Boolean series. For example:</p> <pre><code>b.iloc[(b['A'] == 'a').values, 2:6] = 'someConstantValue' </code></pre> <p>As an aside, chained indexing is <a href="https://pandas.pydata.org/pandas-d...
python|pandas|dataframe|indexing
3
16,673
42,126,754
pandas. How to update a new pandas column row by row
<p>I am trying to add a new column in a pandas data frame, then update the value of the column row by row:</p> <pre><code> my_df['col_A'] = 0 for index, row in my_df.iterrows(): my_df.loc[index]['col_A'] = 100 # value here changes in real case print(my_df.loc[index]['col_A']) my_df </code>...
<p>you are assigning to a slice in this line <code>my_df.loc[index]['col_A'] = 100</code></p> <p>Instead do</p> <pre><code>my_df['col_A'] = 0 for index, row in my_df.iterrows(): my_df.loc[index, 'col_A'] = 100 # value here changes in real case print(my_df.loc[index]['col_A']) </code></pre>
python-3.x|pandas
5
16,674
42,070,410
Match value in pandas cell where value is array using np.where (ValueError: Arrays were different lengths)
<p>many thanks for your reading.</p> <p>(Prior consideration: I cannot change the format of the data inside the dataframes; I'm stuck with what I have. The following is a simplified and reduced version of my data and problem)</p> <p>I have a dataframe with the following form:</p> <pre><code>df = pd.DataFrame( {'Mach...
<p>You need <code>apply</code> with <code>==</code> for check values in <code>list</code>:</p> <pre><code>df['TF'] = np.where(df['Machine'].apply(lambda x: ['No Match'] == x),True, False) print (df) Machine TF 0 [red, blue] False 1 [red] False 2 [blue] False 3 [No Match] True </code></p...
python|arrays|pandas|numpy|dataframe
2
16,675
41,766,648
Efficiently sorting and grouping really big arrays
<p>I am sorting an array of data based on the angle each point within the data forms with the other points. For my given <code>data</code> (x,y,z), i calculate the pairwise distance (<code>pwdist</code>), the pairwise value (<code>pwresi</code>) and the angle between pair data point (<code>pwang</code>). Once i get thi...
<p>To be honest, your code messy, and your question is not fully understandable.</p> <p>So my answer is theoretical, and you should apply it to your own case:</p> <p>Given, a list: <code>myList = [element1, element2, element3]</code></p> <p>And known, an evaluation function: <code>def eval(a): return angle(a.x, a.y)...
python|performance|python-3.x|sorting|numpy
0
16,676
41,916,275
Grouping dataframe by each 6 hour and generating a new column
<p>I have this dataframe (type could be 1 or 2):</p> <pre><code>user_id | timestamp | type 1 | 2015-5-5 12:30 | 1 1 | 2015-5-5 14:00 | 2 1 | 2015-5-5 15:00 | 1 </code></pre> <p>I want to group my data by six hours and when doing this I want to keep <code>type</code> as:</p> <ul> <li><code>1</c...
<p>Try this:</p> <pre><code>In [54]: df.groupby(['user_id', pd.Grouper(key='timestamp', freq='6H')]) \ .agg({'type':lambda x: x.unique().sum()}) Out[54]: type user_id timestamp 1 2015-05-05 12:00:00 3 </code></pre> <p>PS it'll work only with given types: (<code>1</cod...
python|pandas|dataframe|group-by
2
16,677
64,606,752
Android: mobilenet_v1_1.0_224.tflite model doesn't return bounding box information
<p>I am using <a href="https://github.com/anupamchugh/AndroidTfLiteCameraX" rel="nofollow noreferrer">https://github.com/anupamchugh/AndroidTfLiteCameraX</a> source code to learn about integrating the TFLite model with Android. I have labels.txt with all the classes in the <code>Assets</code> folder as well.</p> <p>Cur...
<p>The source code and model you linked is for <a href="https://medium.com/analytics-vidhya/image-classification-vs-object-detection-vs-image-segmentation-f36db85fe81" rel="nofollow noreferrer">Image Classification not Object Detection</a>. So there are no bounding boxes coordinatioon / information.</p> <p>Here is my e...
android|kotlin|classification|bounding-box|tensorflow-lite
1
16,678
64,596,968
Time data does not match format '%yyyy-%mm-%dd
<p>I have the column &quot;date of registration&quot; in the below format.</p> <pre><code>array(['01JAN2018:00:00:00.000000000', '01JAN2019:00:00:00.000000000', '01JAN2020:00:00:00.000000000', ..., '09FEB2018:00:00:00.000000000', '09FEB2019:00:00:00.000000000', '09FEB2020:00:00:00.000000000'], dtype=object) </...
<p>You can use <code>format='%d%b%Y:%H:%M:%S.%f'</code>:</p> <pre><code>pd.to_datetime(['01JAN2018:00:00:00.000000000', '01JAN2019:00:00:00.000000000', '01JAN2020:00:00:00.000000000', '09FEB2018:00:00:00.000000000', '09FEB2019:00:00:00.000000000', '09FEB2020:00:00:00.000000000'], format='%d%b%Y:%H:%M:%S.%f') ...
pandas|datetime
1
16,679
64,176,047
How can i apply onehotencoder to one column of an array?
<p>I've been following a tutorial trying to understand machine learning while trying out what he's doing at the same time.</p> <p>My array is:</p> <pre><code>0 44 72000 2 27 48000 1 30 54000 2 38 61000 1 40 ...
<p>Assuming that your data X has a shape (n_rows, features). If you like to apply one-hot encoding to say, the first column. A quick approach would be</p> <pre><code>onehotencoder = OneHotEncoder() one_hot = onehotencoder.fit_transform(X[:,0:1]).toarray() </code></pre> <p>A better approach to apply one-hot encoding onl...
python|numpy|machine-learning|scikit-learn
1
16,680
64,546,542
Cloud SQL - Postgres - Very slow insert
<p>I may be used to Big Data technology, but when I try to insert ~300k rows for a total (as csv) of 30Mb I don't think 15min is an acceptable time to spend on INSERT with Postgres.</p> <p>I first understand that increasing the total disk size on GCP also increase the IOPS, so I up the disk from 20Go to 400Go.</p> <p>T...
<p>According to the Cloud SQL <a href="https://cloud.google.com/sql/docs/postgres/best-practices#import-export" rel="nofollow noreferrer">best practices</a>, to speed up imports (for small instance sizes):</p> <blockquote> <p>you can temporarily <a href="https://cloud.google.com/sql/docs/postgres/edit-instance" rel="no...
python|pandas|postgresql|google-cloud-sql
0
16,681
64,292,702
Pandas convert partial column Index to Datetime
<p>DataFrame below contains housing price dataset from 1996 to 2016.</p> <p>Other than the first 6 columns, other columns need to be converted to <code>Datetime</code> type.</p> <p><a href="https://i.stack.imgur.com/HlTVv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HlTVv.png" alt="DataFrame's col...
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.html" rel="nofollow noreferrer">pandas index</a> is immutable, so you can't do that.</p> <p>However, you can access and modify the column index with <code>array</code>, see doc <a href="https://pandas.pydata.org/pandas-docs/stable/r...
python|pandas|dataframe|indexing
1
16,682
64,247,027
create multiple dataframes from unique values of a cloumn
<p>I have dataframe with columns(issue_id,summary, source_id). The source_id has values ranging from 1 to 3. I want to create multiple dataframes having name df_1, df_2,df_3 as per the values in source_id.</p> <p>I tried groupby and it gave a dict. but converting dict to dataframe is giving only 1 dataframe.</p> <p>da...
<p>The simple way is delete other columns and assign different name. @krishna</p>
python|pandas|dataframe
0
16,683
47,753,003
How to select ndarray data in python?
<p>I have a <code>ndarray</code> type array, for example:</p> <pre><code>1, 2, 0.5 2, 6, 0.9 9, 2, 0.83 </code></pre> <p>I want to keep the rows whose 3rd elements are larger than <code>0.8</code>, and discard the other rows. It means I want this result:</p> <pre><code>2, 6, 0.9 9, 2, 0.83 </code></pre> <p>How can ...
<p>Here is a simple implementation of your problem:</p> <pre><code>import numpy as np data = np.array([[1, 2, 0.5],[2, 6, 0.9],[9, 2, 0.83]]) result =data[data[:,2]&gt;0.8] </code></pre> <p>Output:</p> <pre><code>[[ 2. 6. 0.9 ] [ 9. 2. 0.83]] </code></pre>
python-3.x|numpy
2
16,684
47,746,450
Read date from tab delimited text file
<p>I only recently switched to Python so this question probably has a really simple solution but I can't seem to find it. I have a text file in the following format:</p> <pre><code>08-05-90 0:00:00 1.78 7.1 10 08-05-90 3:00:00 2.01 7.4 11.1 08-05-90 6:00:00 1.74 7 10.5 08-05-90 9:00:...
<p>Hopefully you are OK using <a href="https://stackoverflow.com/questions/11077023/what-are-the-differences-between-pandas-and-numpyscipy-in-python">pandas</a> in addition to numpy. If so, the datetime of the combined columns is as easy as:</p> <h3>Code:</h3> <pre><code>df['datetime'] = pd.to_datetime(df.date + ' '...
python|arrays|numpy|datetime
0
16,685
58,774,526
TensorFlow custom C++ op with resource handle
<p>Python code:</p> <pre><code> import os import sys from subprocess import check_call import tensorflow as tf CC_NAME = "tf-resource-op.cc" SO_NAME = "tf-resource-op.so" def compile_so(): use_cxx11_abi = hasattr(tf, 'CXX11_ABI_FLAG') and tf.CXX11_ABI_FLAG common_opts = ["-shared", "-O2"] common_opts += ["-s...
<p>Adding <code>-DNDEBUG</code> to the build flags fixes the issue. This workaround is explained <a href="https://github.com/tensorflow/tensorflow/issues/17316" rel="nofollow noreferrer">in TF issue 17316</a>.</p>
python|c++|tensorflow
1
16,686
58,925,771
pandas aggregate sum of two columns and make it as one column
<p>I am looking for solution to group by and then find the sum of two columns in pandas dataframe and display as one column.</p> <p>Sum of Net and Gross column for each row and add a new column 'Total' as teh sum of both.</p> <p>Sample dataset as below</p> <pre><code> Name state Net Gross A1 TN ...
<p>In one step we can do <code>melt</code> first </p> <pre><code>df.melt(['Name','state']).groupby(['Name','state']).value.sum().reset_index() Out[56]: Name state value 0 A1 TN 230 1 A2 AP 300 2 A3 KAR 290 </code></pre>
python-3.x|pandas|sum|aggregate|multiple-columns
2
16,687
58,942,697
Feed data into a deployed model in Tensorflow 2.0
<p>I'm checking the new features of Tensorflow 2.0, and I saw that the <code>placeholder</code>s got deprecated. Now is possible to use directly a python object.</p> <pre class="lang-py prettyprint-override"><code># Define the SummatorModule that sum the submitted value with the previously # submitted one class Summat...
<p>The new saved_model contains the signature of the input/output. Actually the Tensorflow 2.0 C API is not yet released but probably will be a way to parse the Metadata and get these information.</p>
tensorflow|tensorflow-serving|tensorflow2.0
0
16,688
59,011,891
How to make column operations between two different data frames based on a condition in pandas python
<p>I have been trying to perform mathematical operation between two data frames Data1 and Data 2 based on a condition.</p>
<p>Note that for some accounts you have <strong>more than one</strong> operation, <strong>both</strong> incoming and outgoing.</p> <p>So to reflect the transfers between accounts in their balances, in the way compliant with the rules of accounting, you should process your data as follows:</p> <ol> <li>Set the index i...
python|pandas|dataframe
0
16,689
58,876,144
python dataframe gropuby using pd.Series.mode throws error when `by` column contains values with same starting value
<p>I have a dataframe as follows.</p> <pre class="lang-py prettyprint-override"><code>df2 = pd.DataFrame({ "Name" : ['Thomas', 'Thomas', 'Thomas John'], "Credit" : [1200, 1300, 900], "Mood" : ['sad', 'happy', 'happy'] }) </code></pre> <p>I am trying to group it as follows.</p> <pre class="lang-py prettyp...
<p>We could use:</p> <pre><code>aggrFDColumnDetails = { 'Mood':lambda x: x.value_counts().idxmax(), 'Credit':'sum' } df=df2.groupby(['Name']).agg(aggrFDColumnDetails) print(df) Mood Credit Name Thomas happy 2500 Thomas John happy 900 </code></pre> <hr> <p>as ...
pandas|dataframe|python-3.6|pandas-groupby|mode
2
16,690
58,793,491
convert 6 digit int into to yyyymm in pandas
<p>I made a file that had three date columns:</p> <pre><code>pd.DataFrame({'yyyymm':[199501],'yyyy':[1995],'mm':[1],'Address':['AL1'],'Number':[12]}) yyyymm yyyy mm Address Number 0 199501 1995 1 AL1 12 </code></pre> <p>and saved it as a file:</p> <pre><code>df.to_csv('complete.csv') </code></pr...
<p>The columns <code>yyyymm</code> and <code>yyyy</code> and <code>mm</code> are <em>integers</em>. By using <code>.astype(str)</code>, you convert these to strings. But a string has no <code>.dt</code>.</p> <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel...
pandas|datetime
1
16,691
70,300,750
Is there a function in Python to show all rows from a particular year from a data frame with a column of Date type?
<p><code>df['Date']</code></p> <p>gives me the data like this</p> <pre><code>2014-08-22 2016-08-27 2014-04-12 2015-05-05 </code></pre> <p>I need a way to filter out so that it returns only the entire rows from the year 2014.</p> <p>the type of df['Date'] is pandas.core.series.Series</p>
<p>Use:</p> <pre><code>df = df[df['Date'].dt.year == 2014] </code></pre> <p>For multiple years:</p> <pre><code>df = df[df['Date'].dt.year.isin([2014, 2015])] </code></pre>
python|pandas
1
16,692
70,230,009
Pandas df.apply()
<p>I have a df:</p> <pre><code>test2= pd.DataFrame({ 'A':[1, 2, 3], 'B':[4, 5, 6], 'C':[7, 8, 9] }) </code></pre> <p>and I have written a simple function as:</p> <pre><code>def add(a,b,c): return a+b+c </code></pre> <p>Now I am using this function in my df using pandas df.apply m...
<p>It is because <code>apply</code> expects a function to apply to a <code>DataFrame</code> or a <code>Series</code>. If you call <code>add</code> on the three <code>Series</code> objects you are passing to it you don't need to call <code>apply</code> anymore at all. This is because addition is already applicable to <c...
python|pandas
0
16,693
70,027,928
Create a set from two datasets with only values from df1 that isnt in df2
<p>I have 2 dataframes.</p> <p>I want to create a series with locations from df1 that arent duplicated in df2.</p> <p>i am confused how to do this, any answers appreciated</p>
<p>From <code>df_1</code> :</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df_1 values 0 a 1 b 2 c 3 d 4 e </code></pre> <p>And <code>df_2</code> :</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df_2 values 0 b 1 e 2 f 3 g </code></pre> <p>We can get the val...
pandas|dataframe|series
0
16,694
56,409,500
Image in image.show isn't showing anything (Python 3 notebook)
<p>My output doesn't show anything and I honestly can't find out why</p> <p>This is the full code, but I think the problem is when I'm passing the argument to <code>aRed, aGreen, aBlue, originalImage = openImage(response.content)</code> When I run that code in collab python notebook, my image isn't showing up for some...
<p>You don't need to specify <code>.show()</code> in interactive modes. Just remove that part, and it will work fine.</p> <pre><code>import numpy from PIL import Image import requests from io import BytesIO # FUNCTION DEFINTIONS: # open the image and return 3 matrices, each corresponding to one channel (R, G and B c...
python|image|numpy|url|python-imaging-library
0
16,695
55,913,667
How to extract segments with the same value?
<p>I have the following dataframe, </p> <pre><code>df = pd.DataFrame({'col1':range(20), 'col2': list(range(3)) + [5] *3 +list(range(3)) + [3]*3 + list(range(4)) + [2]*3 + [4] }, index = pd.date_range('1/1/2000', periods=20, freq='1S')) df Out[115]: col1 col2 2000-01-01 00:00:00 0 ...
<p>Here is one way using <code>diff</code> and <code>cumsum</code> create the different group , then we using <code>transform</code> and <code>count</code> , get the group count , and select count equal to 3 ,finally we just need <code>groupby</code> and split the dataframe by <code>col2</code></p> <pre><code>s=df.col...
python|pandas|dataframe
2
16,696
64,731,339
Merging two pandas dataframes with common data
<p>Consider this data:</p> <pre><code> INF CTR Time A 1 8 3 B 5 1 3 C 3 2 3 </code></pre> <p>And I have another set of data with the same elements, but different column names:</p> <pre><code> INF2 CTR2 Time A 3 1 3 B 6 4 3 C 1 7 3 </code></pre> <p>I need to merge ...
<p>When you want to join on indexes use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer">.join()</a>, otherwise <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">pd.merge()</...
python|pandas|dataframe
1
16,697
64,905,089
How to find row number from content of cell in python?
<p>How do I from a specific ticker in a cell parse out where that specific ticker occurs? For example if I'm looking for 'AAAB' I would get a read back of every row number that has 'AAAB' Is it better to use pandas or CSV to do this?</p> <pre><code> ,ticker 472,AA 473,AA 474,AAAB 475,AAAB 476,AAA...
<p>If you just want the number of the rows that match the desired pattern, you can use <code>pandas</code>. If your data is inside a <code>.csv</code> file, you can just do:</p> <pre><code>import pandas as pd filename = 'my_file.csv' pattern = 'AAAB' df = pd.read_csv(filename, index_col=0) rows = df[df['ticker'] == ...
python|pandas|database|csv
2
16,698
40,281,849
Concatenate the results of two calls to tf.contrib.learn.datasets.base.load_csv_with_header
<p>I'm trying to concatenate the results of two calls to <code>tf.contrib.learn.datasets.base.load_csv_with_header</code>. I have to do this because I can't have files larger than 25MB on the Juypter Notebook server, so I have to split them in two.</p> <p>Currently I'm attempting to do this, but it just gives a <code>...
<p>So I found a different way to do it. Since later on in the script I split up the <code>data</code> and <code>target</code> parts it was as easy as this:</p> <pre><code>my_x = training_set1.data + training_set2.data my_y = training_set1.target + training_set2.target </code></pre>
python|tensorflow
0
16,699
40,029,618
How to update `xarray.DataArray` using `.sel()` indexer?
<p>I found the easiest way to visualize creating a <code>N-dimensional</code> <code>DataArray</code> was to make a <code>np.ndarray</code> and then fill in the values by the coordinates I've created. When I tried to actually do it, I couldn't figure out how to update the <code>xr.DataArray</code>.</p> <p><strong>How ...
<p>This is really awkward, due to the unfortunate limitation of Python syntax that keyword arguments are not supported in inside square bracket.</p> <p>So instead, you need to put the arguments to <code>.sel</code> as a dictionary in <code>.loc</code> instead:</p> <pre><code>DA.loc[dict(axis_A="A_1", axis_B="B_1", ax...
python|database|numpy|dataframe|python-xarray
18