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
360,800
73,794,766
what is the meaning of axis=-1 in tf.keras.layers.Normalization?
<p>I'm trying to learn deep learning using keras and tensorflow and I came across a code explaining linear regression at <a href="https://www.tensorflow.org/tutorials/keras/regression" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/keras/regression</a> wherein they have created a normalization layer usi...
<p>Per the <a href="https://keras.io/api/layers/preprocessing_layers/numerical/normalization/" rel="nofollow noreferrer">documentation</a> this layer is:</p> <blockquote> <p>A preprocessing layer which normalizes continuous <strong>features</strong>.</p> </blockquote> <p>Then, under the description of <code>axis</code>...
python|tensorflow|keras|normalization
0
360,801
73,721,878
how to plot columns by column group in time series data
<pre><code>df= speed status timestamp 20 TRUE 9/10/2022.. 30 TRUE 9/10/2022.. 10 FALSE 9/08/2022.. ... </code></pre> <p>I want to plot the speeds by status through time, however the start-end times are not the same for TRUE and FALSE. I want them the start at the...
<p><code>Seaborn</code> or <code>Plotly</code> packages do this out-of-the box better than matplotlib. you used matplotlib tag but didn't mention it in your question, so here's an answer using <code>Seaborn</code>:</p> <pre class="lang-py prettyprint-override"><code>import seaborn as sns df = your_data_loading sns.li...
python|pandas|matplotlib
1
360,802
73,664,062
How many rides completed on average in a 4 hour span
<p>I have a dataset:</p> <pre><code>ride_completion_time ride_id 0 2022-08-27 11:42:02 1 1 2022-08-24 05:59:26 2 2 2022-08-23 17:40:05 3 3 2022-08-28 23:06:01 4 4 2022-08-27 03:21:29 5 </code></pre> <p>I would like to find out in a 4 hour time span, on average, how many rides are actually completed? I run ...
<p><code>ride_id</code> is object type (probably string) so <code>sum</code> and <code>mean</code> would exclude this column. You want to know number of rides, you can do <code>size</code>:</p> <pre><code>df3.groupby(df3.index.floor('4H').time).size() </code></pre> <p>As to why 2) works but not 1), probably somewhere y...
python|pandas
0
360,803
73,659,685
How can I put two NumPy arrays into a matrix with two columns?
<p>I am trying to put two NumPy arrays into a matrix or horizontally stack them. Each array is 76 elements long, and I want the ending matrix to have 76 rows and 2 columns. I basically have a velocity/frequency model and want to have two columns with corresponding frequency/velocity values in each row.</p> <p>Here is m...
<p>Your problem is that your vectors are one-dimensional, like in this example:</p> <pre class="lang-py prettyprint-override"><code>f_1d = np.array([1,2,3,4]) print(f_1d.shape) &gt; (4,) </code></pre> <p>As you can see, only the first dimension is given. So instead you could create your vectors like this:</p> <pre cla...
python|arrays|numpy|matrix
0
360,804
73,551,953
Pandas, convert datetime format mm/dd/yyyy to dd/mm/yyyy in 2 different columns CSV
<p>I'm a beginner in python and i'm trying to convert date from YYYY-mm-dd to dd/mm/YYYY in two different dataframes/columns (StartDate and EndDate) but i'm getting the below error when converting the second column df['StartDate'] even though it works on the first column df['EndDate'].</p> <p>The Current date on the fi...
<p>Error means not all values in column <code>EndDate</code> are in format <code>YYYYMMDD</code>:</p> <pre><code>df['EndDate'] = pd.to_datetime(df['EndDate'], format='%d/%m/%Y') </code></pre> <p>If all values are in <code>YYYYMMDD</code> and some not match format try:</p> <pre><code>df['EndDate'] = pd.to_datetime(df['E...
python|pandas|date|datetime
1
360,805
73,711,508
How to change all values of a dataframe according to values of another dataframe in Pandas?
<p>IDs needs to be replaced by Canonical Names. First data frame (please use code):</p> <p><a href="https://i.stack.imgur.com/4Iykv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Iykv.png" alt="enter image description here" /></a></p> <pre><code> df = pd.DataFrame({'LopCityCriteriaId': {0: 10077...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a>:</p> <pre><code>df1 = df.replace(df_IDs.set_index('Criteria ID')['Canonical Name']) print (df1) LopCityCriteriaId LopCountryCrite...
python|pandas|dataframe|numpy
3
360,806
73,707,019
No gradients provided for any variable error
<p>I'm creating a model using the Keras functional API.</p> <p>The layer architecture is as follows:</p> <pre><code>n = tf.keras.layers.Dense(1)(input) for i in tf.range(n): output = tf.keras.layers.Dense(4)(input) </code></pre> <p>I then concat the outputs and return for a tensor with shape [1, None, 4] where [1]...
<p>Shape is not differentiable, you cannot do things like this with gradient based learning. Problems like this need to be tackled with more powerful tools, e.g. reinforcement learning where one considers n as an action, and get policy gradient for that.</p> <p>A rule of thumb to remember is that you cannot really back...
python|tensorflow|machine-learning|keras|tensorflow2.0
0
360,807
73,536,536
How to generate a "triangular" data frame with as many columns as the row indicates?
<p>I have this input dataframe</p> <pre><code> number 1 2 3 4 6 </code></pre> <p>And I want this resulting dataframe</p> <pre><code> number C1 C2 C3 C4 C5 C6 1 1 nan nan nan nan nan 2 1 2 nan nan nan nan 3 1 2 3 nan nan nan 4 1 2 ...
<p>Try this:</p> <pre><code>(df.join(pd.DataFrame( df['number'] .map(lambda x: range(1,x+1)).tolist()) .rename(lambda x: 'C{}'.format(x+1),axis=1))) </code></pre> <p>Output:</p> <pre><code> number C1 C2 C3 C4 C5 C6 0 1 1 NaN NaN NaN NaN NaN 1 2 1 2.0 NaN NaN NaN NaN 2 ...
python|pandas|dataframe
0
360,808
73,689,383
change data in data frame pandas
<p>I have a data frame in python as below</p> <pre><code>columnA columnB 10 15 22 34 44 77 </code></pre> <p>i want to change columnA to read 1 less than the data it has example as below.</p> <pre><code>columnA columnB 9 15 21 34 43 77 </code></pre> <p>That is 10 became 9, ...
<p>To reduce values by 1 in a pandas dataframe, here's one simple solution:</p> <pre><code>df['columnA'] = df['columnA'].apply(lambda x: x-1) </code></pre>
python|pandas
0
360,809
73,583,820
python pandas reshape data from long to wide
<p>I have a dataframe in the following format that I am trying to reshape into wide format in pandas.</p> <p>But I am getting the error Index contains duplicate entries, cannot reshape.</p> <p><code>df</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>status</th> <th>value...
<p>Group the dataframe by <code>id</code> and <code>status</code> columns, then take the first values for <code>value</code> column, finally <code>unstack</code> the resulting series:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df.groupby(['id', 'status']).value.first().unstack().reset_index() sta...
python|pandas|analytics|reshape|data-transform
1
360,810
73,676,184
Find the distance between 2 series of points in Pandas, Fastest Iteration
<p>Have 2 sets of data, 1 which contains coordinates of fixed location called locations</p> <p><a href="https://i.stack.imgur.com/QHPU9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QHPU9.png" alt="Table of fixed locations" /></a></p> <p>And a secondary table of vehicle movements called movements <...
<p>You can export the pandas data directly to numpy for example like this:</p> <pre><code>loc_lat=locations['Latitude' ].to_numpy() loc_lon=locations['Longitude'].to_numpy() mov_lat=movements['Lat' ].to_numpy() mov_lon=movements['Lon' ].to_numpy() </code></pre> <p>From now on there is no need to use loops to ...
python|pandas|performance|iteration|cartesian
0
360,811
73,530,104
How to delete rows from a df (negative values)
<p>I would like to delete all rows with negative values (from an especific column). I´m trying this using the code below:</p> <pre><code>df = df.drop(columns = ['column_name'] &lt; int(0) </code></pre> <p>And it´s showing the error 'SyntaxError: unexpected EOF while parsing'</p> <p>What am I doing wrong?</p>
<p>Try this out</p> <pre><code>df = df.drop(df.index[df['col1'] &lt; 0]) </code></pre> <p>Also, instead of int(0) you can use 0.</p>
python|pandas|dataframe
1
360,812
73,608,245
How to iterate the loop if the condition is not met
<p>I am trying to get the id of respective movie name in that i need to check whether the url is working or not . If not then i need to append the movie name in the empty list</p> <pre><code>data = {'id': [nan, nan, nan,nan], 'movie_name': ['captain-fantastic', 'passengers', 'transformers','guardians-of-the...
<p>As dominik-air said, you're getting a 404 response when the file doesn't exist. However Python's built-in <code>urllib</code> raises an error when it gets this (unlike, for example, the justly popular <code>requests</code> library).</p> <p>In Python generally we use try/catch flow to deal with this (<a href="https:/...
python|pandas|dataframe
2
360,813
73,679,002
how can i add two rows number For example
<pre><code>Adi 70 math's Bangalore 2022 vira 80 math's Bangalore 2022 Adi 30 English Bangalore 2022 </code></pre> <p>Result</p> <pre><code>Adi 100 maths bangalore 2022 </code></pre>
<p>Assuming <code>maths</code> in the result is a typo and you want to sum up all marks for a given name/city/year combination,</p> <pre><code>import io import pandas as pd df = pd.read_csv(io.StringIO(&quot;&quot;&quot; Adi;70;math's;Bangalore;2022 vira;80;math's;Bangalore;2022 Adi;30;English;Bangalore;2022 &quot;&q...
python|pandas
0
360,814
73,775,734
Applying function to all pixels of an image (width, height, 3) with np.vectorize
<p>I want to apply a function to every pixel of an image of shape <code>(width, height, 3)</code> and receive a new matrix of shape <code>(width, height, 2)</code> (XYZ -&gt; u'v'). How can this be accomplished with <code>np.vectorize()</code>?</p> <p>Is <code>np.vectorize()</code> the fastest solution here or are ther...
<p>As you have realized, <code>np.vectorize</code> is a glorified python-for loop and quite slow. A better way to achieve that is writing your function in a vectorized way.</p> <pre><code>def xyz2uv(xyz): # untested as we have no example x, y, z = xyz[ ..., 0], xyz[..., 1], xyz[..., 3] denom = x + 15*y + 3*z ...
python|numpy|image-processing
0
360,815
73,621,264
Comparing two numpy arrays
<p>Initializing the empty numpy array</p> <pre><code>y=np.empty((2,2),dtype=np.matrix) b=np.empty((2,2),dtype=np.matrix) </code></pre> <p>Assigning values to above arrays</p> <pre><code>b[0][0]=np.mat([ [67,57], [19,56]]) b[0][1]=np.mat([ [7,58], [9,46]]) b[1][0]=np.mat([ [77,47], [34,34]]) b[1][1]=np.mat([ [2,66]...
<p>Firstly, as Michael Szczesny mentioned, <code>np.mat</code> is deprecated and you should avoid it. Object arrays are also kinda iffy but can serve a purpose sometimes. Although to answer the actual question:</p> <p>To check for equality between these arrays of arrays you need to check that the inner arrays are equal...
python|arrays|numpy|matrix|numpy-slicing
0
360,816
73,724,994
Can we do predictions for sub-classes i.e. class within class?
<p>I need to classify an object into multiple classes. Normally we are familiar with multi-class classification with a single hierarchy, but in my case I have two levels of hierarchy. See the below images to get a clear picture of what I am talking about. so that if I want to classify an image, it should give me all th...
<p>If you know your hierarchy tree, wouldn't it be ok for you to do multi-class classification on the leaves (the final classes), then check what are the parent classes in the tree, for a given prediction ?</p>
tensorflow|machine-learning|pytorch|conv-neural-network|image-classification
0
360,817
73,734,534
AttributeError: 'str' object has no attribute 'contains' when applying a function to a df column using Lambda
<p>I am trying to create a new column based on the following logic by using the function below. When I apply this function to a df using lambda, I am seeing the following error. I tried to remove the &quot;str&quot; in front of &quot;contains&quot; but it did not work. Could anyone assist or advise? Thanks.</p> <pre><c...
<p><code>str.contains</code> is a function applicable to a series as a whole. In your case, instead of using Pandas functions, you can use a simple for loop to do the trick.</p> <pre><code>result = [] for i in df['product']: if pd.isna(i): result.append('') elif 'watch' in i.lower(): result.app...
python|pandas
1
360,818
73,623,406
How to write a function to find clients that are gone, boomeranging, new, etc?
<p>I am trying to come up with a dynamic way to check for the existence of a string and report back a few different results: gone_client, boomerang, new_client.</p> <ol> <li><p>If I groupby address_id and my_date, and the pattern is Verizon, Verizon, Comcast, Comcast, the client left Verizon and went to another company...
<p>Here's a solution with some verbose logic that you can play around with. It doesn't sound like you're quite certain of your final logic but hopefully this gives you enough to play around with.</p> <p>This solution groups the dataframe based on the <code>address_id</code>. Then, for each individual group, we can exam...
python|pandas|dataframe
1
360,819
73,777,647
Pytorch custom dataset is super slow
<p>During training it takes ages to load one batch of data. What can cause this problem? I am new to Pytorch, i had been working with tensorflow for a while, this my first attempt to create something like this. I wrote a custom dataset which gets its images from folders, it gets stored in a dataframe which will be spli...
<p>Putting the solution of the comments in a cleaner way:</p> <p>The creation of several workers was taking large amount of time. It seems that on windows the creation of processes can have weird behaviours in terms of time.</p> <p>As <code>__getitem__()</code> is not called, the problem is not in data loading per se, ...
python|pytorch|dataset
0
360,820
71,192,884
PyTorch calculate gradient of output with respect to "output"
<p>I was playing around with the backward method of PyTorch tensor to find the gradient of a multidimensional output of the model with respect to intermediate activation layers.</p> <p>When I try to calculate the gradients of the output with respect to the last activation layer (the output), I get the gradients as 1. S...
<p>Since it is a variable, the derivative of the output with respect to output will be equal to 1.</p>
tensorflow|math|deep-learning|pytorch|gradient-descent
0
360,821
71,258,084
only convert to date cells with data
<p>I have a data frame with dates and missing dates:</p> <pre><code>date 2022-02-02 2022-02-03 - - </code></pre> <p>I need to convert to date only the ones different from '-', I'm using .loc for this but is not working:</p> <pre><code>df.loc[oppty['date'] != '-', 'date'] = pd.to_datetime(df['date']) </code></pre> <bloc...
<p>Will this work?</p> <pre><code>df1 = pd.DataFrame({'date':['2022-02-02', '2022-02-03', '-','-']}) df1 pd.to_datetime(df1['date'], errors='coerce') </code></pre> <p><a href="https://i.stack.imgur.com/wZ5mU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wZ5mU.png" alt="enter image description here"...
python|datetime|pandas-loc
1
360,822
71,272,362
Use previous cell value from the same column if an event is not present in different column Pandas
<p>I am going through a time series data base in pandas. When an event happens I want the column I am calculating to store the date from another column. If the event is not present I want it to use whatever was in the cell above in the same column. I have tried the following but I cannot get it to work</p> <pre><code>D...
<p>How about using ffill()?</p> <pre><code>import pandas as pd import numpy as np DB = pd.DataFrame({'Time':['12:00', '12:01','12:02','12:03', '12:04', '12:05'], 'Event': [1, 0, 0, 0, 1, 0]}) DB['TimeFlag'] = np.where(DB['Event'] == 1, DB['Time'], np.nan) DB['TimeFlag'] = DB['TimeFlag'].ffill() </c...
python|pandas|dataframe|numpy
0
360,823
71,353,627
Check if one of elements in list is in dataframe column
<p>I have DF that looks like below:</p> <pre><code>columna_1 column_2 1 I am Thomas 2 Are you Thomas 3 How are you? 4 I am fine... 5 Jack, what's up? </code></pre> <p>and I have a list like this:</p> <pre><code>names = [&quot;Thomas&quot;, &quot;Jack&quot;] </code></p...
<p>Use a regex:</p> <pre><code>import re regex = fr'\b({&quot;|&quot;.join(map(re.escape, names))})\b' df['column_3'] = df['column_2'].str.extract(regex, expand=False) </code></pre> <p>To also drop the non matches:</p> <pre><code>import re regex = fr'\b({&quot;|&quot;.join(map(re.escape,names))})\b' (df.assign(column_3...
python|pandas|dataframe|for-loop|substring
1
360,824
71,178,650
How do I make my dataframe single index from multindex?
<p>I would like to make my data frame more aesthetically appealing and drop what I believe are the unnecessary first row and column from the multi-index. I would like the column headers to be: 'Rk', 'Team','Conf','G','Rec','ADJOE',.....,'WAB'</p> <p>Any help is such appreciated.</p> <pre><code>import pandas as pd url =...
<p>You only have to iterate over the existing columns and select the second value. Then you can set the list of values as new columns:</p> <pre><code>import pandas as pd url = 'https://www.barttorvik.com/#' df = pd.read_html(url) df.columns = [x[1] for x in df.columns] df.head() </code></pre> <p>Output:</p> <pre><code...
python|pandas|dataframe|indexing
1
360,825
71,252,052
Find users most frequent recommandations based on input queries
<p>I have a <code>input query</code> table in the following:</p> <pre><code> query 0 orange 1 apple 2 meat </code></pre> <p>which I want to make against the <code>user query</code> table as following</p> <pre><code> user query 0 a1 orange 1 a1 strawberry 2 a1 pear 3 a2 ora...
<p>Unless there is a particular reason to favor pears over bananas (since they both count for one), I would suggest a more idiomatic way to do it:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df_input = pd.DataFrame(...) df_user = pd.DataFrame(...) df_input = ( df_input .assign( ...
python-3.x|pandas|numpy|jupyter-notebook|jupyter-lab
1
360,826
71,221,388
Numpy comparing vectors of length m and n resulting in boolean matrix of size m,n
<p>I am wondering if there is a more efficient way to run the comparison (or really many other functions) using numpy.</p> <pre><code>a = np.array([1,2,5,7]) b = np.array([0,4,6]) np.repeat(a, len(b)).reshape(-1, len(b)) &gt; b &gt; array([[ True, False, False], [ True, False, False], [ True, True, Fal...
<p>You can use <strong>broadcasting</strong> to make this operation more efficient. Indeed, <code>repeat</code> creates a new temporary array. Here is the resulting code:</p> <pre class="lang-py prettyprint-override"><code>a.reshape(-1, 1) &gt; b </code></pre>
python|numpy
3
360,827
71,437,003
Unrecognized type error (pyshark capfile ) numba?
<pre><code>import pyshark import pandas as pd import numpy as np from multiprocessing import Pool import re import sys from numba import jit temp_array = [] cap = np.array(pyshark.FileCapture(sys.argv[1])) #print(cap._extract_packet_json_from_data(cap[0])) def parse(capture): packet_raw = [i.strip('\r').strip('\...
<p><strong>Numba does not support Pandas</strong>. This is explicitly states in the <a href="https://numba.readthedocs.io/en/stable/user/5minguide.html" rel="nofollow noreferrer">first page</a> of the documentation. Additionally, it cannot directly call pure-Python function in <code>nopython</code> mode. Thus, you shou...
python|numpy|numba
0
360,828
71,425,301
reset_index() not working for multiindex dataframe - 'cannot insert an item into a CategoricalIndex that is not already an existing category'
<p>I'm using this code to get to this dataframe:</p> <pre><code>df=df[['rank','Grade','search']].groupby(['Grade','rank']).count() df2=df.div(df.groupby(['Grade']).transform('sum')) df3=df2.unstack() | search | | rank | 1 | 2 | 3 | 4 | 5 | 5-10 | 10-20 | 20+ | | Grade ---|-----|-----|-----|-----|-----...
<p>You can convert categorical to strings:</p> <pre><code>df3 = df_grade2.unstack().rename(columns=str).reset_index() </code></pre>
python|pandas|plot
1
360,829
71,179,828
Tensorflow compatible version for gfile
<p>I have a Python code which uses Tensorflow module as</p> <pre><code>from tensorflow import gfile </code></pre> <p>However, with the following tf module versions</p> <pre><code>tb-nightly 2.9.0a20220218 tensorboard-data-server 0.6.1 tensorboard-plugin-wit 1.8.1 tensorflow-io-gcs-fil...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/io" rel="nofollow noreferrer">gfile</a> api is available inside <code>tensorFlow.io</code> module. So you need to use below namespace to import this api:</p> <pre><code>from tensorflow.io import gfile </code></pre>
python|tensorflow
0
360,830
71,264,213
Pandas, data monotonic behavior
<p>I have a <code>pd.DataFrame</code> similar to the one below:</p> <pre><code> C1 C2 A B C A B C 0 -10 -9 -8 -8 -7 -9 1 -9 -9 -9 -9 -9 -9 2 -8 0 -1 -8 0 0 3 0 1 1 2 3 1 </code></pre> <p>In this dataframe I need to know the monotonicity for each condition (C1, C2) in each row. Basical...
<p>If test monotonic values per rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.is_monotonic_increasing.html" rel="nofollow noreferrer"><code>Series.is_monotonic_increasing</code></a>, need <code>apply</code>. Your solution should be simplify:</p> <pre><code>mask = (df.groupby(a...
python-3.x|pandas|dataframe
2
360,831
71,435,997
Sum up all Columns by specific rows in Pandas
<p>I have a Dataframe where that mix String, Date and float data. Now I would like to be able to sum all columns in my dataframe but only for specific rows where only floats are available. Like the following <a href="https://i.stack.imgur.com/vcjSy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vcjS...
<p>You can use:</p> <pre><code>df1['sum'] = df1.T.apply(pd.to_numeric, errors='coerce').dropna(how='all', axis=1) \ .sum().reindex(df1.index, fill_value='-') print(df1) # Output Col1 Col2 Col3 sum row1 test test test - row2 2 3 5 10 row3 4 5 6 15 </code></pre>
python|pandas|dataframe
0
360,832
71,230,788
Python Pandas - read_html No tables Found
<p>I am very new to python and trying to do my own data analysis.</p> <p>I am trying to parse data from this website: <a href="https://www.tsn.ca/nhl/statistics" rel="nofollow noreferrer">https://www.tsn.ca/nhl/statistics</a></p> <p>I wanted to get the table in a data frame format.</p> <p>I tried this:</p> <p><code>imp...
<p>If you right click the table and choose inspect, you will see that the &quot;table&quot; on that page is not actually using the html table element.</p> <p>From the Pandas documentation:</p> <blockquote> <p>This function searches for &lt;table&gt; elements and only for &lt;tr&gt; and &lt;th&gt; rows and &lt;td&gt; el...
python|pandas|selenium
1
360,833
71,315,477
Getting nested cells when using dictionaries in pandas (lasio for .LAS files)
<p>I am using lasio (<a href="https://lasio.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">https://lasio.readthedocs.io/en/latest/index.html</a>) to call out data within a .LAS file. It's an oil and gas drilling type file with data in the heading and in the body (called the curve). TL;DR on the lasio do...
<p><strong>Problem</strong></p> <p>You are appending dictionaries to an already-existing DataFrame. Each dictionary contains a variety of types (an integer under the key <code>UWI</code>, and pandas Series under other keys). This is a very general operation, and pandas reacts by converting the Series contained within t...
python|pandas|dictionary
0
360,834
71,352,987
Diff two CSVs by specific columns, output matching rows
<p>I am comparing two CSV files. I need to know which rows match by comparing specific columns. The output needs to be the rows that match.</p> <p><strong>Data:</strong></p> <p>CSV 1:</p> <pre><code>name, age, occupation Alice,51,accountant John,23,driver Peter,32,plumber Jose,50,doctor </code></pre> <p>CSV 2:</p> <pre...
<p>I'd suggest the following:</p> <pre><code>import pandas as pd # load csv df1 = pd.read_csv('test.csv', sep=',', encoding='UTF-8') df2 = pd.read_csv('test2.csv', sep=',', encoding='UTF-8') # look for matching rows filter = ['name', 'age'] filter = df1[filter].eq(df2[filter]).all(axis=1) df1 = df1[filter].append(df2...
python-3.x|pandas|csv
2
360,835
71,397,660
Keras Flatten layer returns output shape (None, None)
<p>So, I noticed this strange behavior of Flatten layer of Keras. I'm using TF1.15 and Keras 2.3.0.</p> <p>Basically the output of the Flatten layer has an unknown shape. It's hard to troubleshoot the model when you can't keep track of the shape. Why is this happening with Flatten layer, and can I do something so it re...
<p>Try using <code>tf.keras</code> instead of just <code>keras</code>:</p> <pre><code>import tensorflow as tf print(tf.__version__) inputs = tf.keras.layers.Input(shape=(3,2,4)) prediction = tf.keras.layers.Flatten()(inputs) print(inputs.shape, prediction.shape) </code></pre> <pre><code>1.15.2 (?, 3, 2, 4) (?, 24) </co...
python|tensorflow|keras
1
360,836
71,389,266
pandas groupby cummax just assigning original values instead of updating the max-so-far
<p>I have this dataframe:</p> <pre><code> type run corrected_episode Reward 0 notsweet 0 0 35.0 1 notsweet 0 100 20.0 2 notsweet 0 200 20.0 3 notsweet 0 300 22.0 4 notsweet 0 400 20.0 </code>...
<p>You can try remove <code>corrected_episode</code></p> <pre><code>foo['best_so_far'] = foo.groupby(['type','run']).Reward.cummax() </code></pre>
python|pandas|pandas-groupby
0
360,837
71,207,541
How to group a pandas DataFrame by month? Trying its output to have a index with actual last days
<p>I have the following DataFrame, and like to group by month.</p> <pre><code>import pandas as pd import numpy as np idx = pd.date_range(start='2001-01-01', end='2002-01-01', periods = 80) df = pd.DataFrame(np.random.rand(160).reshape(80,2), index=idx.normalize(), columns=['a','b']) </code></pre> <p>With the following...
<p>Let us try with <code>duplicated</code> after trim the index</p> <pre><code>df = df.sort_index() out = df[~df.index.strftime('%Y-%m').duplicated(keep='last')] Out[242]: a b 2001-01-28 0.984408 0.923390 2001-02-25 0.108587 0.797240 2001-03-29 0.058016 0.025948 2001-04-26 0.095034 0...
python|pandas|group
1
360,838
71,139,608
Plotting Windrose from csv
<p>I would like to plot a windrose from data in .csv file. From the Windrose documentation, it looks like I need the wind speed, wind direction, and date as index column (csv <a href="https://drive.google.com/file/d/1kTa_oKgCMfw-QTTkWCINhF16cd8Uo6cp/view?usp=sharing" rel="nofollow noreferrer">here</a>).</p> <p>I tried ...
<p>You have missing data - for instance, in line 182970, you're missing speed data.</p> <p>Try manually filtering or filling in the data, or try using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer">pandas' filter function</a> to remove the offending lines.<...
python|pandas|csv|windrose
1
360,839
71,143,027
Python for Loop for summation with function
<p>I want to fit an x^n-t curve to some points.</p> <p>I have an array <code>x=np.array([-5,-4,-3,-2,-1,0,1,2,3,4,5])</code>. I have my <code>a=np.array([a_1,a_2,...,a_n])</code> so that<code>a.shape=n</code>. And what i want to do is fit a curve for the x points such:</p> <p>a[0]+a[1]*x+a[2]*x^2+...+a[n]*x^n</p> <p>So...
<p>If you want to plot the curve, you must solve the polynomial equation using the coefficient for every point on <code>x</code> and add it to a list. This way you can plot it against <code>x</code>. You can do this as follows:</p> <pre class="lang-python prettyprint-override"><code>import numpy as np x = np.array([-5,...
python|numpy|for-loop|curve-fitting|curve
1
360,840
71,096,703
Join two 2D numpy array with one row over another
<p>Two numpy arrays, lets say</p> <pre><code>a = np.array([[1,2], [3,4]]) b = np.array([[5,6], [7,8]]) </code></pre> <p>I would like to combine two arrays into one single array such that the results looks like below array</p> <pre><code>np.array([[1,2], [5,6], [3,4], [7,8]]) </code></pre> ...
<p>IIUC, you could <code>stack</code> on the first axis, and <code>reshape</code>:</p> <pre><code>np.stack((a,b), axis=1).reshape(-1,2) </code></pre> <p>Or use <code>np.c_</code> and <code>reshape</code>:</p> <pre><code>np.c_[a,b].reshape((-1,2)) </code></pre> <p>Output:</p> <pre><code>array([[1, 2], [5, 6], ...
python|numpy
2
360,841
71,174,953
Capture all the string before the 2nd and 3rd whitespace in Pandas
<p>I understand how to split the string from the first occurrence of a whitespace. My question is how to split on the second third occurrence of the whitespace and capture all the string before that.</p> <pre><code>df = pd.DataFrame({&quot;cid&quot; : {0 : &quot;cd1&quot;, 1 : &quot;cd2&quot;, 2 : &quot;cd3&quot;}, ...
<p>Use indexing with <code>str</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.join.html" rel="nofollow noreferrer"><code>Series.str.join</code></a>:</p> <pre><code>s = df.Name.str.split() df['split_one'] = s.str[0] df['split_two'] = s.str[:2].str.join(' ') df['split...
python|pandas
1
360,842
71,095,957
Can a snakemake rule depend on data in the file instead of its change state
<p>I have data in a CSV file that frequently changes. The CSV file is a source for a snakefile rule. My issue is that I want this rule to run only when a certain value appears in the data of the CSV file and not every time when the file changes. Is it possible to let rule execution depend on specific patterns in the fi...
<p>The specific check that Snakemake does to determine if a rule should be re-executed is based on timestamps (not file content), so first thing to do is to wrap relevant files in <a href="https://snakemake.readthedocs.io/en/stable/snakefiles/rules.html" rel="nofollow noreferrer"><code>ancient</code></a>.</p> <p>Next, ...
python|pandas|workflow|snakemake|directed-acyclic-graphs
2
360,843
71,215,523
Pandas group by date with subcategories and sums
<p>I have a dataframe such as this one:</p> <pre><code> Date Category1 Cat2 Cat3 Cat4 Value 0 2021-02-02 4310 0 1 0 1082.00 1 2021-02-03 5121 2 0 0 -210.82 2 2021-02-03 4310 0 0 0 238.41 3 2021-02-12 5121 2 2 ...
<p>You can try this.</p> <ol> <li><p>To group by month, you can use this example</p> <p><code>df.groupby(df['Date'].dt.strftime('%B'))['Value'].sum()</code></p> <p><a href="https://stackoverflow.com/questions/44908383/how-can-i-group-by-month-from-a-date-field-using-python-pandas">How can I Group By Month from a Date f...
python|pandas
1
360,844
71,305,804
Is there a way to load sheets with a specific regex with pandas.read_excel()
<p>Is there a way to load sheets with a specific regex with <code>pandas.read_excel()</code> ?</p> <p>Maybe with the parameter <code>sheet_name</code> But can't figure how...</p> <p>Example of regex :</p> <pre><code>regex_sheet = &quot;\s*[d^D][A^a][y^Y]\D*\s*[1-9]\s*&quot; </code></pre>
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.ExcelFile.parse.html" rel="nofollow noreferrer"><code>pandas.ExcelFile</code></a> to have a peek at the sheet names, then select the sheets to keep with any method (here your regex), finally load with <a href="https://pandas.pydata.org/pandas-d...
python|excel|pandas
3
360,845
71,423,474
pandas multiindex DataFrame from list of nested dictionaries
<p>I have a list of nested dictionaries</p> <pre><code>lst = [{'a':{'aa':1,'ab':2},'b':{'ba':3,'bb':4}}]*2 </code></pre> <p>I am struggling to get a pandas DataFrame with mutltiindex columns.</p> <p>Currently I am doing:</p> <pre><code>pd.concat([pd.DataFrame.from_dict(dct,orient='index').stack().to_frame().T for dct i...
<p>Use nested list with dict comprehension and then recreate <code>MultiIndex</code>:</p> <pre><code>df = pd.DataFrame([{(k,k1): v1 for k, v in x.items() for k1, v1 in v.items()} for x in lst]) df.columns = pd.MultiIndex.from_tuples(df.columns) print (df) a b aa ab ba bb 0 1 2 3 4 1 1 2 3 4 </code><...
python|pandas|dictionary|nested|multi-index
0
360,846
71,360,177
Splitting invoices to different data frame and extracting CVSs
<p>I have a data frame having a huge list of all invoices. I need to split the data frame based on the column &quot;invoice numbers&quot;. Total invoices list is up to 230,000 however the unique list of invoice are 138 (i.e for eg invoice &quot;A&quot;, there might be 30 products for an invoice) and each such invoices ...
<p>There are a few syntax errors in the code. You have to pass the <code>i</code> in loop instead of string <code>'i'</code>. Also for the filename, you have to pass the invoice number in the string to prevent overwriting the file with the same name. The full code would be as followed</p> <pre><code>#List of invoice da...
python|python-3.x|pandas|dataframe
3
360,847
71,222,925
How do I convert a dataframe with time-periods into a particular format?
<p>My initial dataframe looks as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>User</th> <th>License</th> <th>Status</th> <th>Start-Date</th> <th>End-Date</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>xy</td> <td>access</td> <td>10.01.2022</td> <td>13.01.2022</td> </tr> <tr> <t...
<p>From the graph it seems like you only care about the total number of active licenses per day. So, I'm providing an answer in that context. If you need the breakup at user level then it has to be changed a bit.</p> <p>First, let's import the packages and create a sample dataframe. I've added one extra row for User A ...
python|pandas|dataframe
1
360,848
71,315,426
Using TFDS datasets with Keras Functional API
<p>I'm trying to train a neural network made with the Keras Functional API with one of the default TFDS Datasets, but I keep getting dataset related errors.</p> <p>The idea is doing a model for object detection, but for the first draft I was trying to do just plain image classification (img, label). The input would be ...
<p>I think the problem is that each image can belong to multiple classes, so I would recommend one-hot encoding the labels. It should then work. Here is an example:</p> <pre><code>import tensorflow as tf import tensorflow_datasets as tfds def resize_and_normalize_img(example): &quot;&quot;&quot;Normalizes images: `...
tensorflow|keras|deep-learning|tensorflow-datasets|data-processing
1
360,849
71,392,343
Compare two dataframes and find rows based on a value with condition
<p>I have two DataFrames. column &quot;video_path&quot; is common in both the dataframes. I need to extract details from df1 if it matches with df2 and also with the value of yes/no.</p> <p>df1</p> <p><a href="https://i.stack.imgur.com/TvOFx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TvOFx.png" ...
<p>Swap <code>df1</code> and <code>df2</code> with left join and <code>indicator</code> parameter, last set column <code>isPresent</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a>:</p> <pre><code>newdf= df2.merge(d...
python|pandas|dataframe
1
360,850
71,186,366
installing box2d gym ai
<p>I want to train DQN on CarRacing environmnet but when I want to import it using bellow command there is an error.</p> <pre><code>env = gym.make('CarRacing-v0').unwrapped AttributeError Traceback (most recent call last) </code></pre> <p>~\AppData\Local\Temp/ipykernel_4868/4193301300.py in ...
<p>I think you are using windows for using OpenAI gym which is not officially supported.<br /> Gym installation for windows is not stable. Linux and Mac are officially supported. I recommend this video <a href="https://youtu.be/e3DyCg0fgx0" rel="nofollow noreferrer">Installing OpenAI Gym (gym[all]) on Linux, Windows an...
python|pytorch|reinforcement-learning|openai-gym
0
360,851
71,109,587
Merge dataclasses in python
<p>I have a dataclass like:</p> <pre><code>import dataclasses import jax.numpy as jnp @dataclasses.dataclass class Metric: score1: jnp.ndarray score2: jnp.ndarray score3: jnp.ndarray </code></pre> <p>In my code, I create multiple instances of it, is there an easy way to merge two of them attribute per attr...
<p>It is possible to do so in a &quot;jax-centric&quot; manner by registering the class <code>Metric</code> as a <a href="https://jax.readthedocs.io/en/latest/_autosummary/jax.tree_util.register_pytree_node.html#jax.tree_util.register_pytree_node" rel="nofollow noreferrer"><code>pytree_node</code></a>. <a href="https:/...
python|numpy|merge|python-dataclasses|jax
2
360,852
71,151,823
Area between two curves
<p>I was able to plot the lines and fill the area in between, however, I'm trying to calculate the area between the two curves. I cant use the integral since I don't have the equation, I only have a bunch of points. How can I calculate the area in between?</p> <pre><code>fig,ax1= plt.subplots(figsize=(8,5)) plt.plot(La...
<p>Since all of the points are connected by lines, integrating using the trapezoid rule will give you the exact area.</p> <p>The <code>numpy</code> library has a trapezoidal integration function so you can take the difference between the area under the estimated variogram and the area under the sampled variogram:</p> <...
python|pandas|dataframe|numpy|area
2
360,853
71,344,070
Cleaning text in pandas
<p>I have a data frame that has a text column that needs to be cleaned.</p> <p>here is the column info</p> <p><a href="https://i.stack.imgur.com/HmBF7.png" rel="nofollow noreferrer">data frame info</a></p> <p>def process is meant to remove punctuation, convert to lower case, remove stop-word, and word stemming.</p> <pr...
<p>You probably have some empty values on df['Cat_Frames'] represented by <code>np.nan</code> (<code>NaN</code>). <code>NaN</code> datatype is <code>float</code>, so when you attempt to use a string method it throws an error.</p> <p>Check if you have NaN and, if that's the case, use <code>df.fillna</code> to change i...
python|pandas|string|text|data-cleaning
0
360,854
71,116,437
expand.grid equivalent to get pandas data frame for prediction in Python
<p>In R can quite easily do:</p> <pre><code>expand.grid(a = c(1,2,3), b = c(4,5)) </code></pre> <p>to get a data frame:</p> <p><a href="https://i.stack.imgur.com/RiKGn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RiKGn.png" alt="enter image description here" /></a></p> <p>I think something like th...
<p>In pandas we have <code>MultiIndex</code></p> <pre><code>d = {'a': [1, 2, 3], 'b': [4, 5]} out = pd.MultiIndex.from_product(d.values(),names=d.keys()).to_frame().reset_index(drop=True) Out[58]: a b 0 1 4 1 1 5 2 2 4 3 2 5 4 3 4 5 3 5 </code></pre> <p>or simple with <code>itertools</code></p> <pre><...
python|r|pandas
2
360,855
71,385,932
PythonRegEx in Excel can i use module re, or another?
<p>Good afternoon, how to use the PythonRegEx module re in Excel data to get data from the example: <code>#0000002947 _ _ 0 _ PK2/6700094735</code> only the last <code>PK2/6700094735</code>, this means that it writes out/searches for the first PK and then writes out all the data that is on the right side.</p> <p>My cod...
<p>I assume that in general, your text will have the same format as the example you give:</p> <blockquote> <p>#0000002947 _ _ 0 _ PK2/6700094735</p> </blockquote> <p>The code sample that will extract the last part: PKX/XXXXXXXXXX, with X being some digit is following:</p> <pre><code>import re your_text = &quot;#0000002...
python|pandas
0
360,856
71,346,380
Converted a Json file to pd dataframe but would like to pair my column data based on a specific column
<p>This is a snippet of my original JSON file:</p> <pre><code>{ &quot;intents&quot;: [ {&quot;tag&quot;: &quot;greeting&quot;, &quot;patterns&quot;: [&quot;Hi&quot;, &quot;Hey&quot;, &quot;How are you&quot;, &quot;Is anyone there?&quot;, &quot;Hello&quot;, &quot;Good day&quot;], &quot;responses&quot;: [...
<p>You need to explode the dataframe, which is the reverse of groupby.</p> <pre><code>df2 = df2.explode(['patterns']).reset_index(drop=True) df2 tag patterns 0 greeting Hi 1 greeting Hey 2 greeting How are you 3 greeting Is anyone there? 4 greeting ...
python|json|pandas|dataframe
0
360,857
71,416,060
Return a numpy array with third dimension representing multiple feature to only have the feature I want
<p>I have a numpy array of shape <code>(samples, sequence_length, number_of_features)</code> e.g. <code>(10000, 1024, 2)</code></p> <p>I want to break this down into <code>(10000, 1024, 1)</code> where I am only taking the first feature - what is the most efficient way of doing this with numpy without unravelling the a...
<p>Try this:</p> <pre><code>np.take(arr, indices=[0], axis=2) </code></pre>
python|arrays|numpy
3
360,858
71,317,879
adding 2 more dimensions to tensor
<p>I am getting the following error message:</p> <p><strong>RuntimeError: w groups=3, expected weight to be at least 3 at dimension 0, but got weight of size [1, 1, 2, 2] instead</strong></p> <p>when i try to convolve a image with a filter using the &quot;functional version of conv2d&quot;</p> <p>i know why i am receiv...
<p>changing the group of the first layer to 1 fixed the problem for me like this</p> <pre><code>def wave_haar(in_t): hh = nnf.conv2d(in_t, hh_k,stride=2,groups=1) ll = nnf.conv2d(in_t, ll_k,stride=2) hl = nnf.conv2d(in_t, hl_k,stride=2) lh = nnf.conv2d(in_t, lh_k,stride=2) return [ll,hl,lh,hh] </co...
pytorch
0
360,859
71,284,728
For each country/location, find which year had the highest mortality in Python
<p>My data is formatted as shown in the picture what i want is for each location the highest mortality year in python pandas and the data shown in the image is a python pandas dataframe...</p> <p><a href="https://i.stack.imgur.com/gaehS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gaehS.png" alt="...
<p>Just use the following:</p> <pre><code>df.loc[:, df.columns[1:]].idxmax(axis=1) </code></pre> <p>Example:</p> <p>input df:</p> <p><a href="https://i.stack.imgur.com/ymoZk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ymoZk.png" alt="enter image description here" /></a></p> <p>output:</p> <p><a h...
python|pandas|dataframe
1
360,860
71,230,159
Fill the empty cells with their neighbours if they are not empty based on another column Pandas
<p>Good afternoon,</p> <p>What is the simplest way to replace empty values to another value in one column if the text in the another column is equal?</p> <p>For example, we have the dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Name</th> <th style="tex...
<p>You can do it like this:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({ 'Name': ['Joe', 'Joe', 'Nick', 'Nick', 'Alice', 'Alice', 'Kate', 'Kate'], 'Life': [789.0, np.nan, np.nan, 45.0, 188.0, np.nan, np.nan, np.nan], 'Score': [45, 13, 24, 155, 34, 43, 43543, 232] }) print(df) ...
python|python-3.x|pandas|dataframe
0
360,861
71,106,263
How to insert sequence at specific position?
<p>I would like to insert a specific sequence at a defined position in a FASTA formatted file for multiple sequences, where the modified sequences would be output in a single file.</p> <p>I have tried the following commands:</p> <p>I can print the records using the code below, but I cannot insert seq at the position. I...
<p>I do not have your entire code, so tried to figure out an example answering your question: &quot;How to insert sequence at specific position?&quot;</p> <p>My position its specific being half the sequence lenght (not at a given index, but the problem was not there).</p> <p>input fasta <code>fasta2.fa</code> :</p> <pr...
python|pandas|dataframe|text-processing|biopython
0
360,862
71,215,060
Extract matrix from a dataframe by value from columns
<p>I am trying something that could be a little hard to understand but i will try to be very specific.</p> <p>I have a dataframe of python like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Locality</th> <th>Count</th> <th>Lat.</th> <th>Long.</th> </tr> </thead> <tbody> <tr> <td>Kras...
<p>I am not sure what you exactly want as minimum. In this solution, the minimum is 0 if there is only 1 city, but otherwise the shortest distance between 2 cities within the country. Also, the filename <code>cities.txt</code> seems just a filter. I didn't do this but seems straightforward.</p> <pre><code>import numpy ...
python|pandas|dataframe|matrix
1
360,863
71,230,891
How do i find the rolling correlation over last 10 periods for different countries within a dataframe?
<p>I'm trying to find the rolling correlation between Mean BMI and Purchasing power parity so for every country I get the correlation printed in a separate column in 2016</p> <p><a href="https://i.stack.imgur.com/H1Ebf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H1Ebf.png" alt="Data Frame head" /...
<p>You can use the Pandas built in rolling correlation function... For each function, you can basically do a simple group by and iterate through each group and get the result.</p> <p>For each country you can have something like this...</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd...
python|pandas|dataframe
0
360,864
71,178,704
replace value in one column without using replace() function
<p>I want to replace string without using <code>replace()</code> function.<br /> Only want to use <code>pandas</code> and <code>numpy</code>.</p> <p>sample data:</p> <pre><code># df Col1 ab1 de4 </code></pre> <p>The logic of replace is:</p> <ol> <li><code>a</code> will be <code>i</code></li> <li><code>b</code> will be ...
<p>You can use <code>translate</code>.</p> <pre class="lang-py prettyprint-override"><code>mapping = 'abde14'.maketrans({ 'a': 'i', 'b': 'g', 'd': 'm', 'e': 't', '1': '2', '4': '3' }) df['Col2'] = df.Col1.str.translate(mapping) </code></pre> <p>If it is always mapping to 1 character, this synta...
python|pandas|data-manipulation
2
360,865
71,393,079
Merge two dataframes and add a new column
<p>Having a couple of dataframes like that (df, df2),</p> <pre><code>df D R1 R2 R3 0 D1 1 1 1 1 D1 1 1 1 2 D2 1 2 1 3 D2 1 2 1 4 D3 1 0 1 df2 D R1 R2 R3 0 D1 1 1 1 1 D1 1 1 1 2 D2 1 3 1 3 D2 1 3 1 4 D3 1 1 1 5 D3 2 2 2 6 D3 2...
<p>You could try:</p> <pre><code>df3 = (df.assign(new_values=~df.index.isin(df2.index)) .merge(df2.assign(new_values=~df2.index.isin(df.index)), how='outer', indicator=True) ) </code></pre> <p>output:</p> <pre><code> D R1 R2 R3 new_values _merge 0 D1 1 1 1 Fals...
python|pandas|dataframe|merge
0
360,866
71,122,648
applying multiple conditions in pandas dataframe
<p>I want to fill an column with true or false, depending on whether a condition is met. I know to use any() method, but I need to compare values of two columns. I tried and have not succeeded- using &amp; gives type error.</p> <p>my data looks something like</p> <pre><code>A B condition_met 1 2 3 3 5 9 7 ...
<p>You can assign mask with parantheses, because priority of operators:</p> <pre><code>df['condition_met'] = (df.A&gt;3) &amp; (df.B&gt;4) </code></pre> <p>Or:</p> <pre><code>df['condition_met'] = df.A.gt(3) &amp; df.B.gt(4) </code></pre> <p>Your solution - <code>'True'</code> if match else <code>NaN</code>s:</p> <pre>...
python|pandas
0
360,867
71,257,503
Read very huge csv file in chunks using generators and pandas in python
<p>I have a very huge CSVs of 40ishGB , how I can read it chunk by chunk and add a column with value &quot;today's date&quot;.</p> <p>Approaches I tried is directly reading and my system crashed. Then I used <code>chunks in pd.read_csv</code> which is well one solution to it.</p> <p>I was wondering if someone suggests ...
<p>I think using <code>pd.read_csv</code> with <code>chunksize</code> is already quite like using a <code>generator</code>.</p> <p>This will add a new column to the end, and assign a value of <code>1</code> to each row for the column.</p> <pre><code>with open('test.csv', 'r') as fin, open('test_output.csv', 'w') as fou...
python|pandas|dataframe|csv|generator
2
360,868
71,348,739
Prevent pandas from changing int to float/date?
<p>I'm trying to merge a series of xlsx files into one, which works fine. However, when I read a file, columns containing ints are transformed into floats (or dates?) when I merge and output them to csv. I have tried to visualize this in the picture. I have seen some solutions to this where dtype is used to &quot;force...
<p>Try to use <code>dtype='object'</code> as parameter of <code>pd.read_csv</code> or (<code>ExcelFile.parse</code>) to prevent Pandas to infer the data type of each column. You can also simplify your code using <code>pathlib</code>:</p> <pre><code>import pandas as pd import pathlib directory = pathlib.Path('your_path...
python|excel|pandas|dataframe|csv
1
360,869
71,154,846
Match dataframe rows one by one and return corresponding row values
<p>I have two data frames <code>dfA</code>, <code>dfB</code>. <code>dfA</code> has two columns <code>value</code> and <code>action</code>, and <code>dfB</code> has one column <code>action</code>. I want to match the B with A on 'Value' column and return the 'Action' item, if not it will return the string &quot;NOT MATC...
<p>Using pandas merge functionality and left join desired output can be achieved. While using merge() first two arguments are the dataframes that we want to merge, 3rd argument is to merge on which column so there &quot;value&quot; is specified, as 4th argument &quot;left&quot; is passed which denotes that both the dat...
python|pandas|dataframe|string-matching
0
360,870
71,124,939
Multi-label classification shape issue
<p>Dataset:</p> <pre><code>def set_labels(data): labels = list(dict(filter(lambda x: x[0] != 'text', data.items())).values()) return data['text'], labels train_dataset.data = tf.data.experimental.make_csv_dataset( self.path + '1', batch_size=1, num_epochs=1, shuf...
<p>Maybe try using the implementation from <a href="https://stackoverflow.com/questions/45287169/tensorflow-precision-recall-f1-multi-label-classification">here</a>. As the author mentions you can choose between micro, macro, and weighted f1 scores:</p> <pre><code>def tf_f1_score(y_true, y_pred): &quot;&quot;&quot;...
python|tensorflow|machine-learning|keras
1
360,871
71,162,121
How to add + in front of positive integers before string concatenation?
<p>I have this code:</p> <pre><code>import pandas as pd zed = pd.DataFrame(data = {'a': [3, -5], 'b': [-4, 7]}) zed['c'] = zed['a'].astype(str) + ' ' + zed['b'].astype(str) </code></pre> <p>Which gives:</p> <pre class="lang-none prettyprint-override"><code> a b c 0 3 -4 3 -4 1 -5 7 -5 7 </code></pre> ...
<p>You can use the <code>apply()</code> method to apply a function onto a DataFrame (<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">see documentation</a>):</p> <pre><code>zed['c'] = zed['a'].apply(plus_prefix) + ' ' + zed['b'].apply(plus_prefix) </code></pre...
python|pandas|dataframe
2
360,872
71,251,983
CFD simulation (with multiple for loops and matrix operations) is very slow to run. Looking to replace with faster numpy functions (or alternative)
<p>As mentioned above, the function below works, however its very slow. I am very interested in using faster/optimised numpy (or other) vectorized alternatives. I have not posted the entire script here due to it being too large.</p> <p>My specific question is - are there suitable numpy (or other) functions that I can u...
<p>For improving the speed, you can see <a href="https://numba.pydata.org/" rel="nofollow noreferrer">Numba</a>, which is useable if you use NumPy a lot but not every code can be used with Numba. Apart from that, the formulation of the equation system is confusing. You are solving 3 equations and adding the result to a...
python|arrays|numpy|vectorization
0
360,873
71,399,847
RuntimeError: 0D or 1D target tensor expected, multi-target not supported I was training a deep learning model but i am getting this issue
<pre><code>*My Training Model* def train(model,criterion,optimizer,iters): epoch = iters train_loss = [] validaion_loss = [] train_acc = [] validation_acc = [] states = ['Train','Valid'] for epoch in range(epochs): print(&quot;epoch : {}/{}&quot;.format(epoch+1,epochs)) for p...
<p>Your problem is that labels have the correct shape to calculate the loss. When you add <code>.unsqueeze(1)</code> to labels you made your labels with this shape [32,1] which is not consistent to the requirment to calcualte the loss.</p> <p><strong>To fix the problem, you only need to remove <code>.unsqueeze(1)</code...
python|deep-learning|pytorch|conv-neural-network|cross-entropy
2
360,874
71,415,857
Populating multiple variables in each iteration with pandas
<p>I have a number of variables and my intention is to populate each of them in a number of iterations while each need a different expression in order to extract their values. A rough equivalent of what I am trying to do is the following for loop.</p> <pre><code>pairs = {('Ams', 'Rot') : 10, ('Del', 'Utr') : 12, ('Ams'...
<p>You could just use <code>dict-comprehension</code> to setup that easily</p> <pre><code>names = ['var_1', 'var_2', 'var_3', 'var_4'] values = {n: range(3) for n in names} df = pd.DataFrame(values) </code></pre> <pre><code> var_1 var_2 var_3 var_4 0 0 0 0 0 1 1 1 1 1 2 ...
python|python-3.x|pandas|dataframe|for-loop
1
360,875
52,433,424
p -value adjustment Mann-Whitney U test in python
<p>I have a two-dimensional list file(name - 'hcl_file'). A shortened version of the file for clarity. Vertical-observations, horizontal-experiment number:</p> <p><code>ID type First Second Third</code></p> <pre><code>gerg I 0.02695 0 0.00135 0.31312 11P I 0.02695 0 0.00135 ...
<p>If you're gonna use pandas, use pandas to load the data too.</p> <pre><code>import pandas from scipy.stats import mannwhitneyu hcl_data = pandas.read_table(hcl_file, sep="\t") print(mannwhitneyu(hcl_data.loc[hcl_data['type'] == "II"], hcl_data.loc[hcl_data['type'] == "III"])) </code></pre> <p>I'm not entirely sur...
python|pandas|scipy|statistics|adjustment
0
360,876
52,023,464
Optimizing parameter in odeint with the output of a neural network in TensorFlow
<p>I would like to optimize the coefficients of an ODE using tensorflow. </p> <pre><code>def odeModel(state, t): x, y, z = tf.unstack(state) dx = y # Here I want to define dy and dz as follows: # [dy, dz] = tf.nn.relu(tf.matmul([y, z], W) + b) return tf.stack([dx, dy, dz]) </code></pre> <p>Basical...
<p>This can be done in exactly the way your describe:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np RS = np.random.RandomState(42) # Defining model parameters as TF variables W1 = tf.Variable(RS.randn(2, 1)) b1 = tf.Variable(RS.randn(1,)) W2 = tf.Variable(RS.randn(2...
python|tensorflow
0
360,877
52,339,031
Extracting multiple new tab delimited files from an existing one
<p>Hi I am trying to split up a a large metadate file in Python. I started using pandas and wasn't able to figure it out. Right now it's a tab delimited file that looks something like:</p> <pre><code>id count MD1_G1 k123 MD1_G2 k34 MD2_G3 k5678 MD2_G4 k50633 MD4_G5 k100 </code></pre> <p>First I wanted...
<p>use <code>pd.concat</code></p> <pre><code>df2 = pd.concat([pd.DataFrame(df.id.str.split('_').tolist()), df['count']], axis=1) for a,b in df2.groupby(0): b.to_excel(f'{a}.xlsx') </code></pre>
python|pandas
4
360,878
52,253,839
How to change input of a tensorflow.layers.dense() layer?
<p>In tensorflow layers.dense(inputs, units, activation) implements a Multi-Layer Perceptron layer with arbitrary activation function. Say i defined my dense layer like this: </p> <pre><code>inputx = tf.placeholder(float, shape=[batch_size, input_size]) dense_layer = tf.layers.dense(inputx, 128, tf.nn.relu) </code></...
<p>You can use the 'name' and 'reuse' argument to achieve this behaviour: </p> <pre><code>inputx = tf.placeholder(float, shape=[batch_size, input_size]) inputx_2 = tf.some_operation(whatever_thisdoes, shape = [batch_size_2, input_size]) dense_layer = tf.layers.dense(inputx, 128, tf.nn.relu, name='dense_layer') dense_...
tensorflow|neural-network
0
360,879
52,208,668
tensorflow serving Error: Invalid argument: JSON object: does not have named input
<p>I am trying to train a model with Amazon Sagemaker and I want serve it using with Tensorflow serving. To achieve that, I am downloading the model to a Tensorflow serving docker and I am trying to serve it from there.</p> <p>The Sagemaker's training and evaluating stages are completed without errors, but when I load ...
<p>This error occurs when there is mismatch between input of the model and the input you feed.</p> <p>The best way is to check the input of the serving model by making a get request like: </p> <pre><code>http://&lt;ip&gt;:8501/v1/models/bilstm/metadata </code></pre> <p>It would return output like</p> <pre><code>{ ...
python-2.7|tensorflow|tensorflow-serving|amazon-sagemaker
3
360,880
52,186,812
Loading Tensorflow Graph in other file not giving the same accuracy
<p>I trained a CNN in Tensorflow and it tested with 92% accuracy. I saved it as a typical ckpt file. </p> <pre><code>session = tf.Session(config=tf.ConfigProto(log_device_placement=True)) session.run(tf.global_variables_initializer()) &lt;TRAINING ETC&gt; saver.save(session, save_path_name) </code></pre> <p>In a diff...
<p>You are assigning the wrong method to <code>saver</code>. From the <a href="https://www.tensorflow.org/guide/saved_model" rel="nofollow noreferrer">TF Guide</a> you can see that you want to init session and then upload through <code>tensorflow.train.Saver()</code>.</p> <pre><code>tf.reset_default_graph() # Create ...
session|tensorflow|inference
2
360,881
52,371,329
Fast spearman correlation between two pandas dataframes
<p>I want to apply spearman correlation to two pandas dataframes with the same number of columns (correlation of each pair of rows).</p> <p>My objective is to compute the distribution of spearman correlations between each pair of rows (r, s) where r is a row from the first dataframe and s is a row from the second data...
<h1>NEW ANSWER</h1> <pre><code>from numba import njit import pandas as pd import numpy as np @njit def mean1(a): n = len(a) b = np.empty(n) for i in range(n): b[i] = a[i].mean() return b @njit def std1(a): n = len(a) b = np.empty(n) for i in range(n): b[i] = a[i].std() return b </code></pre> ...
python|pandas|dataframe|parallel-processing|scipy
5
360,882
52,401,088
How does a 2x2 deconv kernel with stride=2 work?
<p>For example, if the feature map is 8x8, than I use such a deconv and the feature map becomes 16x16, I'm confused that what the difference between:</p> <pre><code>deconv(kernel_size=2, stride=2, padding='valid') </code></pre> <p>and </p> <pre><code>deconv(kernel_size=3, stride=2, padding='same') </code></pre> <p>...
<p>I think you'll find the explanations and interactive demo on <a href="https://distill.pub/2016/deconv-checkerboard/" rel="nofollow noreferrer">this web page</a> very helpful. </p> <p>Specifically, setting <code>stride=2</code> will double your output shape regardless of kernel size.<br> <code>kernel_size</code> de...
tensorflow|deep-learning|computer-vision|caffe|pytorch
2
360,883
52,303,696
How to find last occurence index matching a certain value in a Pandas Series?
<p>How do I find the <em>last</em> occurrence index for a certain value in a Pandas Series?</p> <p>For example, let's say I have a Series that looks like follows:</p> <pre><code>s = pd.Series([False, False, True, True, False, False]) </code></pre> <p>And I want to find the last index for a <code>True</code> value (i...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.last_valid_index.html#pandas-dataframe-last-valid-index" rel="nofollow noreferrer"><code>last_valid_index</code></a>:</p> <pre><code>s = pd.Series([False, False, True, True, False, False]) s.where(s).last_valid_index() </code></pre>...
python|pandas
12
360,884
52,248,178
Update a two dimensional variable by row in Tensorflow
<p>Is there any way to update a row from a two dimensional tf.variable with tf.scatter_update. The idea is that the variable is inside a tf.while_loop and in each iteration the selected row is updated with something else. The idea is:</p> <pre><code>a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] </code></pre> <p>and...
<p>This code updates one tensor, row by row, from another tensor. Please note that I haven't considered any performance implications.</p> <p>The key lines are these where I am using a variable( which I think becomes a tensor inside the loop ) and incrementing it.</p> <pre><code>a = tf.scatter_update(a,v,b[i]) v = i ...
tensorflow
0
360,885
52,183,856
Tensorflow Feature Columns: AttributeError: 'tuple' object has no attribute 'name'
<p>I'm attempting to train a simple dataset using 8 feature columns, 3 numeric, and 5 categorical. My basic training script currently looks like so:</p> <pre><code>import tensorflow as tf feature_names = [ 'col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8' ] def input_fn(file_path, perform_shuff...
<p>Im sure you figured it out yourself by now, but for anyone who has the same error and probably just copied it out from the list with the comma at the end.</p> <p>The trailing comma makes 'col4' a tuple </p> <pre><code>col4 = tf.feature_column.categorical_column_with_identity(key='col4', num_buckets=3), </code></p...
python|tensorflow
1
360,886
52,225,216
Pretty print a pandas dataframe in VS Code
<p>I'd like to know if it's possible to display a pandas dataframe in VS Code while debugging (first picture) as it is displayed in PyCharm (second picture) ?</p> <p>Thanks for any help.</p> <hr> <p><em><code>df</code> print in vs code:</em></p> <p><a href="https://i.stack.imgur.com/6TeZL.jpg" rel="noreferrer"><img...
<p>As of the <a href="https://devblogs.microsoft.com/python/python-in-visual-studio-code-january-2021-release/#data-viewer-when-debugging" rel="noreferrer">January 2021 release</a> of the python extension, you can now view pandas dataframes with the built-in data viewer when debugging native python programs. When the p...
python|pandas|debugging|dataframe|visual-studio-code
32
360,887
52,266,756
Replacing Periods in DF's Columns
<hr> <h2>Replacing Periods in DF's Columns</h2> <p>I was wondering if there was an efficient way to replace periods in pandas dataframes without having to iterate through each row and call.replace() on the row. </p> <pre><code>import pandas as pd df = pd.DataFrame.from_dict({'column':['Sam M.']}) df.column = df.col...
<pre><code>df['column'].str.replace('.', '', regex=False) 0 Sam M Name: column, dtype: object </code></pre>
python|pandas|replace
2
360,888
52,098,512
Converting particular columns in dataframe to a numpy array and merging with original data frame
<p>I have a dataframe like this</p> <pre><code>Company_id year dummy_1 dummy_2 dummy_3 dummy_4 dummy_5 1 1990 1 0 1 1 1 1 1991 0 0 1 1 0 1 1992 0 0 1 1 0 1 1993 1 0 1 1 ...
<p>I believe need select last columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>assign</cod...
python|pandas|numpy
2
360,889
52,346,957
cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version
<p>I get the following error when l run tensorflow in GPU.</p> <pre><code>2018-09-15 18:56:51.011724: E tensorflow/core/common_runtime/direct_session.cc:158] Internal: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version Traceback (most recent call last): File "evaluate_sample...
<p>Updating nvidia driver solved this issue. </p> <p>You can check your cuda toolkit compatiblity <a href="https://docs.nvidia.com/deploy/cuda-compatibility/index.html#binary-compatibility__table-toolkit-driver" rel="noreferrer">here</a>. Then update your nvidia driver by downloading it from <a href="https://www.nvidi...
python-2.7|tensorflow|cuda
8
360,890
52,219,586
Returning 3 images from data generator
<p>I am trying to pass to my triplet network 3 images using my data generator. I am loading the different pairs and stacking them into batches. I don't know how can I return it back as 3 different arrays. I tried appending into a list, but that also didn't work. How can I use a data generator to return them back?</p> ...
<p>There might be other solutions, but what I do is to name my input layers and then use as inputs an dictionary with the same names.</p> <p>So in your model you should name your inputs:</p> <pre><code>input_a = Input(shape=(224,224,3), name = "input_a") input_b = Input(shape=(224,224,3), name = "input_b") input_c = ...
python|tensorflow|keras
1
360,891
52,067,432
Cross entropy giving different values
<p>I want to see the result of how cross entropy is calculated, but the following code gives different results.<br> In one case I used cross entropy formula and in second case I only used <code>tf.nn.softmax_cross_entropy_with_logits</code>.</p> <pre><code>labels=tf.constant([[1,0],[1,0],[0,1]],tf.float32) s = tf.Vari...
<p><code>tf.nn.softmax_cross_entropy_with_logits</code> performs softmax internally. You need to pass the unscaled value (before softmax) to it. In fact, that's what <code>with_logits</code> means.</p> <p>It is explicitly documented here: <a href="https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_...
python|tensorflow
0
360,892
52,210,472
Error when checking input: expected dense_input to have shape (21,) but got array with shape (1,)
<p>How to fix the input array to meet the input shape?</p> <p>I tried to transpose the input array, as described <a href="https://stackoverflow.com/questions/50336110/valueerror-error-when-checking-expected-dense-1-input-to-have-shape-3-but">here</a>, but an error is the same.</p> <p>ValueError: Error when checking i...
<p>Your test array, <code>arrTest1</code>, is a 1d vector of 21:</p> <pre><code>&gt;&gt;&gt; arrTest1.ndim 1 </code></pre> <p>What you are trying to feed your model is a row of 21 features. You simply need one more set of brackets:</p> <pre><code>arrTest1 = np.array([[0.1, 0.1, 0.1, 0.1, 0.1, 0.5, 0.1, 0., 0.1, 0.6,...
python|tensorflow|machine-learning|neural-network|keras
8
360,893
52,391,438
Pandas Group by before outer Join
<p>I have two tables with the following formats: </p> <p>Table1: key = Date, Index </p> <pre><code> Date Index Value1 0 2015-01-01 A -1.292040 1 2015-04-01 A 0.535893 2 2015-02-01 B -1.779029 3 2015-06-01 B 1.129317 </code></pre> <p>Table2: Key = Date </p> <pre><code> Date ...
<p>It seems you want to merge <code>'Value1'</code> of <code>df1</code> with <code>df2</code> on <code>'Date'</code>, while assigning the Index to every date. You can use <code>pd.concat</code> with a list comprehension</p> <pre><code>import pandas as pd pd.concat([df2.assign(Index=i).merge(gp, how='left') for i, gp ...
pandas|join|group-by
0
360,894
52,280,524
Pandas Dataframes - new dataframe with reorganized data
<p>I'm new to Pandas and trying to create a new dataframe from an existing one. </p> <p>My current dataframe has a format: </p> <pre><code>ID Country Status ABC USA Go ABC Columbia Stop ABC Japan Pause ABC Egypt Go DEF Canada Go DEF Peru Stop </code></pre> <p>I'm trying to ...
<p>If you absolutely must do this then this is how you do it.</p> <pre><code>In [48]: df.groupby(['ID', 'Status'])['Country'].apply(','.join).unstack() Out[48]: Status Go Pause Stop ID ABC USA,Egypt Japan Columbia DEF Canada NaN Peru </code></pre>
python|pandas|dataframe|pandas-groupby
2
360,895
52,176,573
pandas.DataFrame slicing accoring to another DataFrame
<p>How can I create df3 according to df1 and df2?</p> <pre><code>df1 = pd.DataFrame([[1,2,3],[10,20,30],[100,200,300]], index=['a','b','c'],columns=['A','B','C']) df2 = pd.DataFrame([['A','C'],['B','A'],['C','B']],index=['a','b','c'],columns=[0,1]) df3 = pd.DataFrame([[1,3],[20,10],[300,200]], index=['a','b','c'],colu...
<p>Seems like you can do with <code>lookup</code> after <code>stack</code> with df2</p> <pre><code>s=df2.stack() s Out[321]: a 0 A 1 C b 0 B 1 A c 0 C 1 B dtype: object pd.Series(df1.lookup(s.index.get_level_values(0),s),index=s.index).unstack() Out[322]: 0 1 a 1 3 b 20 ...
python|pandas
4
360,896
52,135,477
Tf.where doesn't evaluate
<pre><code>sess = tf.InteractiveSession() t = tf.expand_dims(tf.constant(list(range(9))), axis=1) tf.where(t == 5).eval() InvalidArgumentError (see above for traceback): WhereOp : Unhandled input dimensions: 0 [[Node: Where_16 = Where[T=DT_BOOL, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Where_16/con...
<p>In your example, you are evaluating <code>tf.where(False)</code> since the <code>==</code> operator is not overloaded for tensors. (More info e.g. here: <a href="https://stackoverflow.com/questions/35094899/tensorflow-operator-overloading">TensorFlow operator overloading</a>)</p> <p>Try:</p> <pre><code>sess = tf.I...
numpy|tensorflow
0
360,897
52,272,393
Why are my plots in matplotlib not showing the axes
<p>I am having trouble with my plots as the axes labels seem to show in Jupyter Notebooks when I was working on it. </p> <p>However, when I exported the file to a .py file and ran it in terminal, the charts given do not have the axes labels..</p> <pre><code>fig = plt.figure(figsize = (15,5)) ax = fig.add_axes([0,0,1...
<p>The line</p> <pre><code>ax = fig.add_axes([0,0,1,1]) </code></pre> <p>causes the problem. Here you tell <code>matplotlib</code> to use all the figure space for the actual plot and leave none for the axes and labels. <code>tight_layout()</code> appears to have no effect if an <code>Axes</code> instance is created i...
python|pandas|matplotlib
12
360,898
60,438,983
Torchscript incompatible with torch.cat for tensor lists
<p>Torch.cat throws error for tensor lists when used within torchscript</p> <p>Here is a minimum reproducable example to reproduce the error</p> <pre><code>import torch import torch.nn as nn """ Smallest working bug for torch.cat torchscript """ class Model(nn.Module): """dummy model for showing error""" ...
<p>changing <code>axis</code> to <code>dim</code> fixes the error, Original solution was posted <a href="https://discuss.pytorch.org/t/torch-cat-throws-error-for-tensor-list-when-compiling-with-torchscript/71317/2?u=particularlypythonic" rel="nofollow noreferrer">here</a></p>
python|deep-learning|pytorch|jit|torchscript
2
360,899
60,491,666
Unpack a row with similar values as index in a pandas dataframe?
<p>I have a df with rows appended to next to other row.</p> <p>I want columns of the df to be <code>alpha</code>,<code>beta</code>,<code>gamma</code></p> <pre><code> 0 1 2 3 4 5 0 alpha beta gamma alpha beta...
<p>You can try <code>pivot</code>:</p> <pre><code>(df.T.assign(col=df.iloc[0].eq('alpha').cumsum()) .pivot(index='col', columns=0, values=1) .rename_axis(index=None, columns=None) ) </code></pre> <p>Output:</p> <pre><code> alpha beta gamma 1 a b c 2 1 2 3 </code></pre>
python|pandas
0