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
19,100
71,002,708
Change y-axis range in Pandas.boxplot()
<p>I use the following <code>boxplot</code> function from <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.boxplot.html" rel="nofollow noreferrer">Pandas</a>,</p> <pre><code>df.boxplot(column=['D1', 'D2']) </code></pre> <p>and I would like to change the y-axis range. However, I didn't see such an ...
<p>You can do so editing the axis-object - you can either do</p> <pre><code>ax = df.boxplot(column=['D1', 'D2']) ax.set_ylim(0, 10) </code></pre> <p>or</p> <pre><code>import matplotlib.pyplot as plt fix, ax = plt.subplots(1, 1) df.boxplot(column=['D1', 'D2'], ax=ax) ax.set_ylim(0, 10) </code></pre> <p>figure is the who...
python|pandas|plot
1
19,101
70,858,397
PyTorch Inference High CPU Usage on Kubernetes
<p><strong>Problem</strong></p> <p>We are trying to create an inference API that load PyTorch ResNet-101 model on AWS EKS. Apparently, it always killed OOM due to high CPU and Memory usage. Our log shows we need around 900m CPU resources limit. Note that we only tested it using <strong>one</strong> 1.8Mb image. Our Dev...
<p>Have you tried limiting the CPU available to the pods?</p> <pre class="lang-yaml prettyprint-override"><code> - name: pytorch-ml-model image: pytorch-cpu-hog-model-haha resources: limits: memory: &quot;128Mi&quot; cpu: &quot;1000m&quot; # Replace this with CPU amount your devops guys w...
kubernetes|pytorch|computer-vision|amazon-eks
1
19,102
51,899,112
Panda dataframe: draw bar plot by year
<p>I'm creating some new plots, and I'd like to see my data based on the year. I have data like this given below:</p> <pre><code> creation_time physical_device_type --------------- -------------------- 7/25/2018 14:53 email 7/26/2018 14:53 printer 7/26/2017 14:53 email 7/24/2017 14:53 printer 7/23/2017 1...
<p>Using <code>pivot_table</code>:</p> <pre><code>(df.pivot_table( index=df.creation_time.dt.year, columns='physical_device_type', aggfunc='size').plot(kind='bar', stacked=True, colormap='dark2', width=0.2) ) </code></pre> <p></p> <pre><code>plt.tight_layout() plt.show() </code></pre> <p>Output:</p> <p...
python|pandas|matplotlib
1
19,103
35,829,364
Fixing inflexion point estimate using python
<p>I am trying to find the inflexion points on a curve using python. The data for the curve is here: <a href="https://www.dropbox.com/s/rig8frgewde8i5n/fitted.txt?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/rig8frgewde8i5n/fitted.txt?dl=0</a>. Please note that the curve has been fitted to the raw data. Ra...
<p>Any reason not to use uni-variate spline directly on the gradient?</p> <pre><code>from scipy.interpolate import UnivariateSpline #raw data data = np.genfromtxt('ww.txt') plt.plot(np.gradient(data), '+') spl = UnivariateSpline(np.arange(len(data)), np.gradient(data), k=5) spl.set_smoothing_factor(1000) plt.plot(s...
python|numpy|scipy
7
19,104
37,209,908
Is there a pandas equivalent of dplyr::summarise?
<p>In R/dplyr, I can do</p> <pre><code>summarise(iris, max_width=max(Sepal.Width), min_width=min(Sepal.Width)) </code></pre> <p>and get:</p> <pre><code> max_width min_width 1 4.4 2 </code></pre> <p>Is there something similar to <code>summarise</code> in pandas? I know <code>describe()</code>, but I w...
<p>To your question: Yes, there is.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from datar.all import f, summarise, max, min &gt;&gt;&gt; from datar.datasets import iris &gt;&gt;&gt; &gt;&gt;&gt; summarise(iris, max_width=max(f.Sepal_Width), min_width=min(f.Sepal_Width)) max_width min_width ...
python|r|pandas|dplyr
1
19,105
41,715,814
python pandas rolling function with two arguments in a grouped DataFrame
<p>This is a somewhat extension to my previous problem <a href="https://stackoverflow.com/questions/41445415/python-pandas-rolling-function-with-two-arguments">python pandas rolling function with two arguments</a> .</p> <p>How do I perform the same by group? Let's say that the 'C' column below is used for grouping.</p...
<p>One way to achieve would be to iterate through every group and use <code>pd.rolling_apply</code> on every such groups.</p> <pre><code>import scipy.stats as ss def my_tau_indx(indx): x = dff.iloc[indx, 0] y = dff.iloc[indx, 1] tau = ss.mstats.kendalltau(x, y)[0] return tau grp = dff.sort_values(['A...
python|pandas
1
19,106
37,761,238
How do I select and store columns greater than a number in pandas?
<p>I have a pandas DataFrame with a column of integers. I want the rows containing numbers greater than 10. I am able to evaluate True or False but not the actual value, by doing:</p> <pre><code>df['ints'] = df['ints'] &gt; 10 </code></pre> <p>I don't use Python very often so I'm going round in circles with this. </p...
<p>Sample DF:</p> <pre><code>In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc')) In [80]: df Out[80]: a b c 0 6 11 11 1 14 7 8 2 13 5 11 3 13 7 11 4 13 5 9 5 5 11 9 6 9 8 6 7 5 11 10 8 8 10 14 9 7 14 13 </code></pre> <p>present only ...
python|pandas
72
19,107
37,979,037
TensorFlow MLP unhashable type 'list'
<p>I'm trying to feed a MLP with an array. The input array contains 120 floats and the output contains 2.</p> <pre><code>sess.run(init) # Training cycle train = True if train is True: for i in range(50): for letter in d1: #print(letter[0][0][0:5]) letter[0][0][0:5] = sorted(letter[0...
<p>I suppose you had at the beginning of your code two placeholder <code>x</code> and <code>y</code>:</p> <pre class="lang-py prettyprint-override"><code>x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) </code></pre> <hr> <p>The issue is that in your code, you use again the same name <code>x</code> and ...
python|list|tensorflow
0
19,108
37,914,795
Normalising rows in numpy matrix
<p>I am trying to normalize rows of a numpy matrix using L2 norm (unity length). </p> <p>I am seeing a problem when I do that. </p> <p>Assuming my matrix 'b' is as follows: </p> <p><a href="https://i.stack.imgur.com/VwPUm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VwPUm.png" alt="enter image ...
<p>The problem comes from the fact that <code>b</code> has type <code>int</code> so when you fill in row by row, <code>numpy</code> automatically converts the results of you computation (<code>float</code>) to <code>int</code>, hence the zeros. One way to avoid that is to define <code>b</code> with type <code>float</co...
python|numpy|matrix
3
19,109
31,229,499
Pandas: Splitting a Graph into many sub graphs while maintaining scale
<p>I have a bar graph of 150 values.<br>The code is : <br> rcParams.update({'figure.autolayout': True}) plt.figure(figsize=(14,9), dpi=600)</p> <pre><code>reso_names = [x[0] for x in resolution3] reso_values = [x[1] for x in resolution3] plt.bar(range(len(reso_values[0:20])), reso_values[0:20], align='center'...
<p>You can specify <code>sharey=True</code> to keep the y-scale same in all subplots.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.random.randint(1, 10, 10) y = np.random.randint(1, 100, 10) fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True) # do simple plot here, replace barplot your...
python|pandas|matplotlib|graph
3
19,110
64,269,232
Hi, I want to create a second column in my dataframe with only specific values of the first column
<p>I have a dataframe with names of regions and their states:</p> <pre><code> 0 1 0 Alabama[edit] Alabama[edit] 1 Auburn Auburn 2 Florence Florence 3 Jacksonville Jacksonville 4 Livingston Livingston 5 Montevallo Montevallo 6 Troy Troy 7 Tuscaloosa Tuscaloosa 8 Tuskegee Tuskegee...
<p>Find the locations that do NOT have <code>&quot;[edit]&quot;</code> in them, and replace them with <code>nan</code>s:</p> <pre><code>df.loc[df[1].str.find('[edit]') == -1, 1] = np.nan </code></pre> <p>Forward-fill the <code>nan</code>s:</p> <pre><code>df[1].ffill(inplace=True) </code></pre>
python-3.x|pandas|dataframe
1
19,111
64,378,321
List comprehension to get rows from a dataframe that contains matching column values of another dataframe
<p>So I have 2 wildly different dataframes- different column names, different data. Both have a column that contain some matching numbers. Ive attempted to use list comp with any() statements without success, and merge/join is a mess without renaming everything. heres a small example of what im working on:</p> <pre><co...
<p>I guess what you actually meant to write was</p> <pre><code>df1 = pd.DataFrame(np.random.randint(0,2,size=(10, 5)), columns=list('ABCDE')) df2 = pd.DataFrame(np.random.randint(0,2,size=(10, 5)), columns=list('EFGHI')) </code></pre> <p>Since my dfs have a shared column we know what we are looking for to agree and sin...
python|pandas|dataframe|list-comprehension|any
0
19,112
47,928,967
4D array from 2D arrays
<p>I have certain number of Numpy arrays with the shape</p> <pre><code>print(x.shape) &gt;&gt;&gt;(256,256) </code></pre> <p>How can I stack them so that the shape is</p> <pre><code>print(y.shape) &gt;&gt;&gt;(certainnumber,256,256,1) </code></pre> <p>I've been trying with np.stack and np.concatenate but I only get...
<p><strong>Method #1</strong></p> <p>Here's one with <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.stack.html" rel="nofollow noreferrer"><code>np.stack</code></a> -</p> <pre><code>np.stack(list_of_arrays)[...,None] </code></pre> <p><strong>Method #2</strong></p> <p>You can prepend a new...
python|arrays|numpy
3
19,113
47,683,255
CoreMLtools and Keras ValueError: need more than 1 value to unpack
<p>I'm fine-tuning the Inception V3 model with Keras, in order to convert it with coremltools into a .mlmodel file.</p> <p>However, when converting the model coremltools throws an error saying the following when the converter reaches the last layer of the model:</p> <pre><code>coremltools/models/neural_network.py", l...
<p>I'm writing here in response to @SwimBikeRun's request (as I need a bit more space) I was converting YOLO to Keras and then Keras to CoreML. For conversion I was using this script <a href="https://github.com/qqwweee/keras-yolo3/blob/master/convert.py" rel="nofollow noreferrer">https://github.com/qqwweee/keras-yolo3/...
tensorflow|keras|coreml
2
19,114
47,917,906
Trace an image in python
<p>I Wrote this python script to trace the image. But it is throwing an error. It is showing <strong>"IndexError: index 181 is out of bounds for axis 0 with size 181"</strong> where my image size is <strong>181x158</strong>. I decreased the range in order to rectify this error but, no use.</p> <pre class="lang-py pret...
<p>Note that your code is recursive (startTrace calls itself) and you don't know how many times it will call itself. In fact, can you assure that a single call to startTrace() will ever exit? Could startTrace() call startTrace() forever? This would cause a stack overflow eventually. But this is not your problem (yet).<...
python|numpy|opencv|image-processing
1
19,115
48,894,930
Concatenate two 1 column DataFrames doesn't return both columns
<p>I'm using Python 3.6 and I'm a newbie so thanks in advance for your patience. </p> <p>I have a function that sums the difference between 3 points. It should then take the 'differences' and concatenate them with another DataFrame called labels. k and length are integers. I expected the resulting DataFrame to have tw...
<p>Given two <code>DataFrame</code>s, <code>df1-df2</code> will perform the subtraction element-wise. Use <code>abs()</code> to take the absolute value of that difference, and finally sum each row. That's the explanation to the first command in the following function. The other lines are similar to your code.</p> <pre...
python-3.x|pandas|concat
0
19,116
49,303,679
Intersection between two multi-dimensional arrays with tolerance - NumPy / Python
<p>i am stuck at a problem. I have two 2-D numpy arrays, filled with x and y coordinates. Those arrays might look like:</p> <pre><code>array1([[(1.22, 5.64)], [(2.31, 7.63)], [(4.94, 4.15)]], array2([[(1.23, 5.63)], [(6.31, 10.63)], [(2.32, 7.65)]], </code></pre> <p>Now I have to find "duplicate nodes". ...
<p>In order to compare to nodes with a giving tolerance I recommend to use <code>numpy.isclose()</code>, where you can set a relative and absolute tolerance.</p> <pre><code>numpy.isclose(1.24, 1.25, atol=1e-1) # [True] numpy.isclose([1.24, 2.31], [1.25, 2.32], atol=1e-1) # [True, True] </code></pre> <p>Instead of usi...
python|numpy
4
19,117
58,791,373
Is there a way of displaying a 16-bit image in Tkinter?
<p>I got a single-layer uint16 tiff image, i.e 2d array each value ranges between 0-65355. When I read and display the image with cv2 it works corrrectly.</p> <pre><code>im = cv2.imread(path, -1) cv2.imshow('im', im) </code></pre> <p>Now I'm trying to make a GUI with Tkinter and incorporate the image into the GUI, bu...
<p>I have had the same issue as of late without a solution. This is what I believe is causing the issue.</p> <p>Your image <a href="https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes" rel="nofollow noreferrer"><code>mode</code></a> is type <code>I;16L</code>, but when you call <a href="https:/...
python|numpy|tkinter|python-imaging-library|cv2
1
19,118
70,135,992
How to minimize wrt one set of parameters and maximize wrt other set of parameters simultaneously in a training loop in pytorch?
<p>I have a loss function that includes two sets of parameters to learn. One is a matrix, wrt which I want to maximize the loss, other is the set of parameters for logistic regression, wrt which I want to minimize the loss. In pytorch whenever I use loss.backward(), the loss is minimized wrt both sets of parameters and...
<p>You can refer to the gradient reversal idea from <a href="https://arxiv.org/abs/1409.7495" rel="nofollow noreferrer">https://arxiv.org/abs/1409.7495</a>.</p> <p>But the crux of the idea is this: you have some loss function l(X,Y) where X and Y are parameters. Now you want to update X to minimize loss and update Y to...
optimization|pytorch|minimax
0
19,119
70,318,982
Vectorizing a custom parsing function gives a ValueError
<p>I've written a custom number parsing function. Basically, I want to convert app size information as it is given in the Google Play store (5.6M, 3M, 112K) to a standard float number.</p> <p>To apply this function to a column of data in my data frame, I want to vectorize it using numpy.vectorize. However, when I'm tes...
<p><code>np.vectorize</code> creates <code>numpy.array</code> which can't mix different type of data - <code>string</code> and <code>float</code> - and it tries to convert all to <code>float</code>. You would have to return <code>np.NaN</code> instead of all strings.</p> <pre><code>import numpy as np import re import p...
python|numpy|vectorization
1
19,120
56,370,964
Can torchtext's BucketIterator pad all batches to the same length?
<p>I recently started using torchtext to replace my glue code and I'm running into an issue where I'd like to use an attention layer in my architecture. In order to do this, I need to know the maximum sequence length of my training data. </p> <p>The problem is that <code>torchtext.data.BucketIterator</code> does paddi...
<p>When instantiating a <code>torchtext.data.Field</code>, there's an optional keyword argument called <code>fix_length</code> which, when set, defines the length to which all samples will be padded; by default it is not set which implies flexible padding.</p>
python-3.x|pytorch|preprocessor|torchtext
0
19,121
56,158,706
How to group HTTP requests log using pandas
<p>I have a HTTP requests log. The included features are: capture_time, ip, method, url, content, user_agent</p> <p>All this information is in a csv file.</p> <p>i want to group all requests from the same IP between a 10 minutes interval.</p> <p>how can i do that using pandas?</p> <p><strong>example dataset:</stron...
<pre><code>df.set_index('date', inplace = True) unnesting(df.resample('10T')['ip'].unique().reset_index(), ['ip']).reset_index(drop = True) </code></pre> <p>First you need to set your date to your index. Next you need to resample the time in 10 min increments, look at your IP column and get the unique ones for each t...
python|pandas|dataframe
1
19,122
55,629,119
How to filter unwanted values in arrays for plotting? ValueError in matplotlib using numpy arrays
<p>I am working on a new routine inside some codes based on OOP, and encountered a problem while modifying the array of the data (short example of the code is below).</p> <p>Basically, this routine is about taking the array <strong>R</strong>, transposing it and then sorting it, and then filter out the data below the ...
<p>With the help of a techie friend, the problem is simply resolved by keeping this part</p> <pre><code>R = R[R[:, 0] &gt;= thres] </code></pre> <p>because removing unwanted elements is more preferable than changing them to NaN or zero. And then the problem with plotting is fixed by adding a slight modification in th...
python-3.x|matplotlib|numpy-ndarray|valueerror
0
19,123
55,852,534
Unable to plot pandas dataframe data with plotly in pycharm
<p>I am trying to plot a pandas dataframe data using plotly in pycharm but it is not working. The following is the code snippet.</p> <pre><code>import plotly.plotly as py import pandas as pd import numpy as np import cufflinks as cf cf.go_offline() df = pd.DataFrame(np.random.randn(100,4),columns='A B C D'.split()) ...
<p>Your code, <em>exactly</em> as it is, runs just fine in a Jupyter Notebook and produces this plot:</p> <p><a href="https://i.stack.imgur.com/TjKBD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TjKBD.png" alt="enter image description here"></a></p> <p>So the question boils down to how <em>you</...
python|pandas|dataframe|pycharm|plotly
0
19,124
55,984,021
Pandas failing to seperate columns of csv-File
<p>I am currently trying to extract data from a .csv-File using panda's read_csv-function. My .csv-File has the following format:</p> <p>[Link to first image as I am not allowed to include images][1]</p> <p>It seems to me like a reasonable format only the # in the header line troubles me a bit, but does not influenc...
<p>You could also try passing <code>quotechar</code> and <code>sep</code> arguments in Pandas.read_csv():</p> <pre><code>data_frame = pd.read_csv(csv_path, sep=',', quotechar ='"') </code></pre> <p>Running that, I got the following output when calling <code>data.head()</code>:</p> <pre><code> fi...
python|pandas|csv
0
19,125
55,655,102
Feed Multiple Images in a batch item to an Conv2d Layer, reshaping issue
<p>I have an input of:</p> <pre class="lang-py prettyprint-override"><code>[batch_size, number_of_images, img_size_x, img_size_y] </code></pre> <p>e.g. <code>[24, 51, 28,28]</code></p> <p>Now I want to process each image of an item of the batch through a Conv2d-Layer and collect the outputs.</p> <p>I would like to ...
<p>This is more about working with dimensions. Suppose you have an input and labels arrays. First dimension is 10 time the batch size just for the sake of example.</p> <pre><code>input_data = np.ones((240, 51, 28, 28)) output_data = np.ones((240, 10)) </code></pre> <p>First you need to change the order of dimensions....
python|numpy|tensorflow|keras|deep-learning
0
19,126
64,654,166
Add a specific character between specific numbers in a string column in pandas datafrane?
<p>I have a column of strings and I need to insert a character at a specific index. For example, this is my column in a pandas DataFrame:</p> <pre><code>16923ABCD 16928ABCD 16917ABCD 16934ABCD 16912ABCD </code></pre> <p>The expected output is as follows (I have inserted character 'A' at index 2, after '16'):</p> <pre><...
<p>If you have these strings in list use a <code>for</code> loop and for each use the followings:</p> <p><code>A = A[:2] + 'A' + A[2:]</code></p> <p>If you have them in a column of a pandas dataframe, the following will help. Assume df is your dataframe:</p> <pre><code>df = pd.DataFrame({'column1': ['16923ABCD' ,'16928...
python|pandas|string|dataframe
2
19,127
40,018,755
how do you map a pandas dataframe column to a function which requires more than one parameter
<p>I have a function which has two arguments, the first argument is some text the second a regex pattern. </p> <p>I want to pass each row of a certain column from my dataframe to a function using .map however I am not sure how to direct the data from the dataframe to be the first argument and the regex (which will be ...
<p>I think you need <code>lambda</code> function with parameters <code>pattern</code> and <code>x</code>:</p> <pre><code>df['new_column'] = df['source_code'].map(lambda x: some_function(pattern, x)) df['new_column'] = df['source_code'].apply(lambda x: some_function(pattern, x)) </code></pre> <p>Thank you <a href="ht...
python|regex|pandas
1
19,128
40,046,619
Keras + tensorflow gives the error "no attribute 'control_flow_ops'"
<p>I am trying to run keras for the first time. I installed the modules with:</p> <pre><code>pip install keras --user pip install tensorflow --user </code></pre> <p>and then tried to run <a href="https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py">https://github.com/fchollet/keras/blob/master/exampl...
<p>There is an issue between Keras and TF, Probably tf.python.control_flow_ops does not exist or not visible anymore. using below import statements you can resolve this issue</p> <pre><code>import tensorflow as tf tf.python.control_flow_ops = tf </code></pre> <p>For Details check: <a href="https://github.com/fcholle...
python|ubuntu|machine-learning|tensorflow|keras
24
19,129
69,544,256
How padding works in PyTorch
<p>Normally if I understood well PyTorch implementation of the Conv2D layer, the padding parameter will expand the shape of the convolved image with zeros to all four sides of the input. So, if we have an image of shape (6,6) and set <code>padding = 2</code> and <code>strides = 2</code> and <code>kernel = (5,5)</code>,...
<p>The input is padded, not the output. In your case, the conv2d layer will apply a two-pixel padding on all sides just before computing the convolution operation.</p> <p>For illustration purposes,</p> <pre><code>&gt;&gt;&gt; weight = torch.rand(1, 1, 5, 5) </code></pre> <ul> <li><p>Here we apply a convolution with <c...
pytorch|conv-neural-network
3
19,130
69,651,254
Replace unknown character � in BigQuery query using Airflow
<p>I am trying to read a BigQuery table and turn it into a pandas dataframe using Python on Airflow. This is the code I'm using to execute the queries:</p> <pre><code>bq_hook = BigQueryHook(bigquery_conn_id=SRC_CONN, use_legacy_sql=False) bq_client = bigquery.Client(project = bq_hook._get_field(&quot;project&quot;), cr...
<p><code>BigQueryHook</code> has <a href="https://github.com/apache/airflow/blob/25a50bb1fbf0e228706c7927cb36570921881adb/airflow/providers/google/cloud/hooks/bigquery.py#L204" rel="nofollow noreferrer">get_pandas_df</a> function.</p> <p>You can do:</p> <pre><code>bq_hook = BigQueryHook(bigquery_conn_id=SRC_CONN, use_l...
python|pandas|google-bigquery|airflow|non-ascii-characters
0
19,131
69,425,982
Question on how to add strings using Python if conditional statements
<p>I have a question. <br>I'd appreciate it if you could help me. <br>I want to add a specific character in the middle of a string using a python ‘if’ statement. <br>For example, <br>When I change <strong>January 1, 2021</strong> to a string, I want to convert 2020011 (7 letters) to 20200101 (8 letters). <br>This is my...
<p>Check function from module <code>datetime</code> - <a href="https://docs.python.org/3/library/datetime.html#datetime.date.isoformat" rel="nofollow noreferrer">isoformat</a> or more general <a href="https://docs.python.org/3/library/datetime.html#datetime.date.strftime" rel="nofollow noreferrer">strftime</a> function...
python|pandas|if-statement
0
19,132
69,329,152
How to choose encoding type for the read_csv of pandas
<p>I have difficulties in finding the encoding type of the xlsx file. When I use pd.read_csv(file), it display an error(&quot;UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 15-16: invalid continuation byte&quot;). Then I try to create a list of many encoding types to loop through, but still doesn't wo...
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> function expects data in <strong>comma-separated values</strong>, or CSV, format. Excel saves files to <code>.xlsx</code> files, which are binary files containing Excel-sp...
python|pandas
2
19,133
38,110,921
How does tf.nn.conv2d behave with an even-sized filter?
<p>I've read <a href="https://stackoverflow.com/questions/34619177/what-does-tf-nn-conv2d-do-in-tensorflow">this question</a> for which the accepted answer only mentions square odd-sized filters (1x1, 3x3), and I am intrigued about how <code>tf.nn.conv2d()</code> behaves when using a square even-sized filter (e.g. 2x2)...
<p>See the description here: <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#convolution" rel="nofollow">https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#convolution</a></p> <p>For VALID padding, you're exactly right. You simply walk the filter over the input without any paddi...
tensorflow|conv-neural-network
1
19,134
38,269,483
Numpy setup error : extra formal argument
<p>I have some Fortran files I would like to use in Python files. I have used the command C:\Python27\python.exe setup.py build_ext --inplace --fcompiler=g95. My setup.py file contains the following code: </p> <pre><code>import sys, os extra_link_args = [] extra_link_args = ['-framework', 'accelerate'] from numpy.dis...
<p>Sorry, it appears the f2py wrapper support is broken, as it declares a function twice with conflicting signatures: first 2 then 3 formal arguments. It's not clear this version will work for you as desired, though you might find it useful to work through the examples of the first few <a href="https://web.archive.org...
python|python-2.7|numpy|fortran|setup.py
1
19,135
66,180,649
Pandas generate multiple CSV files on a loop
<p>I'm trying to recreate what I achieved manually using a for loop What I did was to manually written 10 CSV files. the code is like this</p> <pre><code> df_1.to_csv('eblist1.csv', encoding='latin-1', index=False) df_2.to_csv('eblist2.csv', encoding='latin-1', index=False) df_3.to_csv('eblist3.csv', enco...
<p>Based on the error message &quot;'str' object has no attribute 'to_csv'&quot;, it appears you attempted to access the to_csv() method from a string and not the class itself. You are on the right track. Assuming you have a list of your dataframes (the actual dataframes and not strings of the dataframes), then you sho...
python|pandas
1
19,136
66,234,132
Display sample size with xlabels in a stacked bar chart
<p>I have a pandas dataframe <code>table</code></p> <pre><code>table Out[12]: Highly unlikely Slightly unlikely Neutral Slightly likely Highly likely age_bin 18-24 ...
<p>I found an ugly way to do this, you can format your <code>x-axis ticks</code>. <code>plt.xticks</code> receives a string as it's argument, and you passed in a tuple <code>(sum[0], sum[1], sum[2])</code>. Since it expects a string it tried to transform it to string using the tuple's <code>__str__</code> method which ...
python|pandas|matplotlib|bar-chart
1
19,137
65,987,362
what is the difference between notna() and dropna()?
<p>I'm working on titanic data right now, using pandas. Funny thing is, when dealing with missing values, drorpna() does not work but notna() does.</p> <pre><code>temp.Embarked.dropna(inplace = True) temp.isnull().sum() </code></pre> <p>Embarked 2</p> <pre><code>temp = temp[temp['Embarked'].notna()] temp.isnull()....
<p>I think both done same process, but when we are using <code>dropna()</code> we have to mention how the way we have to drop Nan means, by axis....</p> <p>you have to mention row wise or column wise</p> <p>Eg:<code>temp.Embarked.dropna(inplace = True,axis=1)</code></p> <p>it will drop the nan values with entire row</p...
python|pandas
1
19,138
46,551,899
Count the number of day if time pass a certain checkpoint in a given range of dates, e.g. number of stay in hotel
<p>I would like to count the number of day if time pass a certain checkpoint in a given range of dates. For example, the checkpoint is every midnight. I have the check-in and check-out timestamp as follows:</p> <pre><code>chkin = ['2015-01-01 23:00:00', '2015-01-01 22:30:30', '2015-01-01 01:30:...
<p>You can subtract datetime objects like this:</p> <pre><code>import datetime format = '%Y-%m-%d %H:%M:%S' difference = abs((datetime.datetime.strptime(df['chkout'], format) - datetime.datetime.strptime(df['chkin'], format)).days) print(difference) </code></pre> <p>Although, you will get more accurate answers if you...
python|pandas
0
19,139
58,569,157
Filling a 2D Numpy array based on given coordinates
<p>I want to fill a 2D numpy array created by this:</p> <pre><code>import numpy as np arr = np.full((10,10),0) </code></pre> <p>Example coordinates:</p> <p><a href="https://i.stack.imgur.com/9y3FA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9y3FA.png" alt="enter image description here"></a></...
<p>Here's one way of doing it:</p> <pre><code>import numpy as np coords = ['2,1:2,5', '8,6:4,6', '5,1:8,1'] arr = np.full((10, 10), 0) for coord in coords: start, stop = map(lambda x: x.split(','), coord.split(':')) (x0, y0), (x1, y1) = sorted([start, stop]) arr[int(y0):int(y1)+1, int(x0):int(x1)+1] = 1 ...
python|arrays|numpy
1
19,140
58,198,126
Replace, convert, change, a bool False and True to 0 and 1
<p>I have tried just about every combination on the web, and even though I do not get an error, the bool false does not change to 0</p> <pre><code>df['loan_status_is_great'].replace({'False': 0}) df['loan_status_is_great'].replace('False',0,inplace=True) </code></pre>
<p>I am not sure this is fine enough, But will convert True to 1 and any other value would be converted to 0</p> <pre><code>import pandas as pd ser = pd.Series(['True', 'False','Nan'], dtype='object') ser = (ser == 'True').astype('int') print(ser) </code></pre> <p>Output :</p> <pre><code>0 1 1 0 2 0 </...
python|pandas
0
19,141
58,484,868
Convert a CSV column to nested field in json
<p>I have a csv file with some as the columns in the format x;y;z. I am using pandas to read this data, do some pre-processing and convert to a list of json objects using to_json/to_dict methods of pandas. While converting these special columns, the json object for that column should be of the format {x: {y: {z: value}...
<p>I found it easier to use pandas to dump the data as a dict then use a recursive function to iterate through the keys and where I encounter a key which contains a <code>;</code> then i split the key by this deliminator and recursively create the nested dicts. When i reach the last element in the split key i update th...
python|json|pandas|csv
1
19,142
58,561,104
How do I access array elements if the dimension can vary?
<p>I have data stored in an array as for example</p> <pre><code>myList = array([('A', 3, 2, 5),('B', 3, 7, 0),dtype=[('f0', '&lt;U128'), ('f1', '&lt;f8'), ('f2', '&lt;f8'), ('f3', '&lt;f8')]) </code></pre> <p>It has a constant number of columns >2 and an arbitrary number of rows. I would like to read the 2nd column i...
<p>Provided <code>myList</code> is an actual <code>numpy</code> array,</p> <pre><code>def func(arr): if len(arr.shape) == 1: return arr[1] else: return arr[:, 1] result = func(myList) </code></pre> <p>If <code>myList</code> is a type <code>list</code> instead:</p> <pre><code>def func(lst): ...
python|list|numpy|indexing
0
19,143
69,182,110
Pandas not adding time when converting string to datetime
<p>I'm trying to convert a string to date using pandas, but can't figure out how to also get time (00:00:00) added.</p> <p>I have a column named &quot;Date&quot; with the following string formatting: YYYY-MM-DD</p> <p>python code:</p> <pre><code>import pandas as pd datetime = pd.to_datetime(data_frame[DATE]) </code></p...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>strftime</code></a> to convert as a string of your choice:</p> <pre><code>df['DATE'] = pd.to_datetime(df['DATE']) df['DATE'] = df['DATE'].dt.strftime('%Y-%m-%d %H:%M:%S') df.to_csv('filen...
python|pandas|datetime
1
19,144
61,038,112
Restructure dataframe (maybe pivot or unpivot) to have each column display the label of data based on 0's and 1's
<p>I have survey data. The survey asks a question and the respondents pick one or more given categories for each question. The survey then asks demographic questions such as gender. The output is a dataframe with demographic information as columns and a matrix of 0's and 1's for each category in each question (0 = not ...
<p>Use:</p> <pre><code>#convert to MultiIndex all not Q topic columns df2 = df.set_index(['Survey ID','Gender']) #split columns names to MultiIndex in columns df2.columns = df2.columns.str.split(expand=True) #reshape df2 = df2.stack() #filter only rows with at least one 1 per row and reshape for remove NaNs #also repl...
python|pandas|dataframe|pivot|transform
3
19,145
71,542,758
LSTM difference between output and hidden state output
<p>I am trying to build a wakeword model for my AI Assistant, but i dont know which output i should give it to my Linear Layer. What is the difference between them and why should i use the recommendatioin of yours?</p>
<p>You should give the output to the linear layer instead of hidden state output. Like this (time series prediction):</p> <pre class="lang-py prettyprint-override"><code>def forward(self, input_seq): h_0 = torch.randn(self.num_directions * self.num_layers, self.batch_size, self.hidden_size).to(device) c_0 = tor...
pytorch|lstm|recurrent-neural-network
0
19,146
71,581,762
Pandas - Concat rows based on group of values in columns
<p>I have a dataframe like this (summarized version), with 14 cols:</p> <pre><code>df = pd.DataFrame({'Date':[01/10/2020,02/10/2020], 'Ticker': [AAPL,APPL], 'Transaction':[Dividend,Tax], 'Value':[10,1]}) </code></pre> <p>Table Format:</p> <div class="s-table-container"> <table class="s-table"> <thea...
<p>If I understand correctly, you are looking for <code>pivot_table()</code>:</p> <pre><code>pd.pivot_table( df, index = ['Date', 'Ticker'], values = 'Value' columns = 'Transaction' ) </code></pre>
python|pandas|dataframe|concatenation
0
19,147
71,736,527
`generator` yielded an element of shape (8, 0) where an element of shape (None,) was expected. Traceback (most recent call last):
<p>I was training a network and I decided to add more data for training. my data set is selected from another data but both have (460,620,3) and Uint8 type. but when I train my net with this data, I got this error:</p> <pre><code>Epoch 1/40 1/100 [..............................] - ETA: 8:10 - loss: 10312.7480 - X_coo...
<p>But you didn't show the generator &amp; the signature in caller - so nobody could see... I had the same problem (for the topic's name), therefore (if somebody wiil need) I show the simplified example:</p> <pre><code># Importing the tensorflow library import tensorflow as tf import numpy as np def fn_t(): for x ...
python|tensorflow|keras|batchsize
0
19,148
71,457,185
Is there a more optimal way of filtering Pandas dataframe by a column value, when that column is ordered?
<p>In Pandas, I have a large DF with millions of rows. There are typically thousands of rows per a particular <code>date</code>, all of them relevant to a particular event.</p> <p>I want to iterate through, processing in groups the rows with a shared date. For example, this is my current approach:</p> <pre><code># Gets...
<p>I haven't so big data to test it but it has <code>.groupby()</code> and later you can works with every group separatelly or run some functions on all groups at once - i.e. <code>.sum()</code>, <code>.min()</code>, <code>.max()</code> or even <code>.apply()</code>.</p> <pre><code>df.groupby('date').sum() df.groupby(...
python|pandas|dataframe|filter
0
19,149
71,569,260
Leading zeros removed by pandas import
<p>Why is my leading zeros not staying in column_item and line_item?</p> <pre><code>#format columns dtype_dic= {'line_item': str, 'column_item' : str} # loop over the list of csv files for f in csv_files: # read the csv file df = pd.read_csv(f, sep=&quot;;&quot;, dtype = dtype_dic) df_l...
<p>Your code behaves as expected, here using <code>io.StringIO</code> as a file proxy:</p> <pre><code>data='''entity;business_line_group;conso_level_entity;report_name;line_item;column_item;z_axis;value_text;amount;approval_text 456;test;456;C_72_00_a;0070;0010;UNDEFINED;Value 1;05198630.14;28-feb-22 456;test;456;C_72_...
python|pandas|dataframe
1
19,150
42,529,598
Estimator with Coordinator as an input function for reading input data in distributed fashion in tensorflow
<p>The CNN cifar10 tutorial (tensor flow tutorials) gives an example of low-level API use for reading data as an independent job to train model (with multiple GPU). Is it possible to use high-level API Estimator with low-level threading support and multi/single GPUs training?</p> <p>I am looking for a way to combine b...
<p>I push a code to <a href="https://github.com/BobLiu20/Classification_Nets/blob/master/tensorflow/training/train_estimator.py" rel="nofollow noreferrer">here</a>.<br> It is support input_fn as a queue when using estimator. High-level API Estimator with low-level threading support and multi/single GPUs training. And e...
tensorflow|tensorflow-serving
1
19,151
69,932,553
Equivalent of SUMPRODUCT in dataframe with strings
<p>What would be the equivalent in Pandas of the PRODUCTSUM in Excel? I have this formula in Excel with PRODUCTSUM inside a conditional IF.</p> <pre><code>IF(PRODUCTSUM((A$2:A2=A2)*(C$2:C2=C2)*(B$2:B2=B2))&gt;1;0;1) </code></pre> <p>I have found some examples in other posts like these:</p> <p><a href="https://stackover...
<p>you can use <code>groupy</code></p> <pre><code>df['Output']=df.groupby(['A','B','C']).cumcount() df.Output = df.Output + 1 df.loc[(df.Output &gt; 1),&quot;Output&quot;] = 0 </code></pre>
python|pandas
1
19,152
69,820,462
Keras weighted_metrics does not include sample weights in calculation
<p>I am training a CNN model with a 2D tensor of shape (400,22) as both input and output. I am using categorical_crossentropy both as loss and metric. However the loss/metrics values are very different.</p> <p>My model is somewhat like this:</p> <p><strong>1. Using sample weights, and passing metrics with <code>metrics...
<p>Keras does not automatically include sample weights in the evaluation of metrics. That's why there is a huge difference between the loss and the metrics.</p> <p>If you'll like to include sample weights when evaluating metrics, pass them as <code>weighted_metrics</code> rather than metrics.</p> <pre class="lang-py pr...
python|tensorflow|keras|deep-learning|loss-function
3
19,153
43,395,964
Optimize Setting Pandas column with Function
<p>I have a task to create a column in my DataFrame based on the file that was used to create said DataFrame. I can tackle this task with an example of the code below, but I'm thinking there is a better way of doing so. I'm pretty sure I can skip the steps of creating the column and setting it to zero: <code>dfp['F'] =...
<p>Doing this for every row is not necessary. You can do it once and fill that into an entire column.</p> <p>Use the <code>re</code> module</p> <pre><code>import re fnames = re.findall('(foo|bar)', file2) fname = fnames[0] if fnames else None dfp['F'] = fname dfp A B C D E...
python|pandas|dataframe
2
19,154
50,626,810
Why does tensorflow doubles the one_hot on values?
<p>I have the following test program in Python:</p> <pre><code>import tensorflow as tf sess = tf.InteractiveSession() # Some tensor we want to print the value of a = tf.one_hot(1,5) # Add print operation a = tf.Print(a, [a], message = "This is a: ") # Add more elements of the graph using a b = tf.add(a, a) b.eval()...
<p>You are adding <code>a</code> to itself, and then printing the addition. So essentially... <code>a= 1; print (a+a)</code> Obviously, that's not how it's written, but I sure hope that 1+1 is 2.</p>
python|tensorflow|one-hot-encoding
2
19,155
50,655,906
Get the frequencies of values from one numpy array in another array
<p>I have two numpy arrays, for example:</p> <pre><code>import numpy as np a1 = np.linspace(0,2*np.pi,101) a2 = np.random.choice(a1, 60) </code></pre> <p>I need to count how many times each value from <code>a1</code> appears in <code>a2</code>. I can do it with a loop but I was hoping for a better solution.</p> <p>S...
<p>Another <code>np.unique</code> approach:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a1 = np.linspace(0,2*np.pi,101) &gt;&gt;&gt; a2 = np.random.choice(a1, 60) &gt;&gt;&gt; &gt;&gt;&gt; unq, idx, cnts = np.unique(np.concatenate([a1, a2]), return_inverse=True, return_counts=True) &gt;&gt;&gt; assert...
python|numpy
2
19,156
45,529,865
Changing Column Heading CSV File
<p>I am currently trying to change the headings of the file I am creating. The code I am using is as follows;</p> <pre><code>import pandas as pd import os, sys import glob path = "C:\\Users\\cam19\\Desktop\\Test1\\*.csv" list_=[] for fname in glob.glob(path): df = pd.read_csv(fname, dtype=None, low_memory=False) ...
<p>Instead of appending the values try to append values by creating the dataframe and setting the column i.e </p> <pre><code>output = pd.DataFrame(df['value'].value_counts()) output.columns = [os.path.basename(fname).split('.')[0]] list_.append(output) </code></pre> <p>Changes in the code in the question </p> <pre><...
python|pandas|csv
2
19,157
45,703,529
Why does complex floating-point division underflow weirdly with NumPy?
<p>Consider this code:</p> <pre><code>import numpy numpy.seterr(under='warn') x1 = 1 + 1j / (1 &lt;&lt; 533) x2 = 1 - 1j / (1 &lt;&lt; 533) y1 = x1 * 1.1 y2 = x2 * 1.1 z1 = x1 / 1.1 z2 = x2 / 1.1 print(numpy.divide(1, x1)) # 1-3.55641399918e-161j # OK print(numpy.divide(1, x2)) # 1+3.55641...
<p>To do this math, you need to first &quot;scale&quot;, so-to-speak, the 3.23310363561e-161. That is what triggers the underflow</p> <pre><code> 0.909090909091 - 3.23310363561e-161 = -------------------- 0.909090909091 x 10^0 - 3.23310363561 x 10^-161 = ------------------------- 0.909090909091 x 10^0 - 0.000.....
python|numpy|floating-point|underflow
0
19,158
62,507,943
remove duplicate pairs from the list in column in pandas
<p>I would like to remove duplicate pairs from the list in column while mainting the order:</p> <p>for example the input is :</p> <pre><code> cola. colb 1. [sitea,siteb,sitea,siteb;sitec,sited,sitec,sited] </code></pre> <p>the expected output is the unique elements before each ';' symbol</p> <pre><code> cola...
<p>eventually I did it by converting the list into series, dropped the duplicates and joined the series again as following :</p> <pre><code> df['e2etrails']=df['e2etrails'].str.split(';') df['e2etrails']=df['e2etrails'].apply(lambda row :';'.join(pd.Series(row).str.split(',').map(lambda x : ','.join(sort...
python|pandas|duplicates
0
19,159
62,634,685
How to trigger python script automatically in a specific date?
<p>I have a file which looks like: df: Month Product Start_Date End_Date Updated_on 0 January Beverage 01/01/2020 01/31/2020 02/06/2020 1 February Beverage 02/01/2020 02/29/2020 03/06/2020 2 March Beverage 03/01/2020 03/31/2020 04/06/2020 3 April Beverage 04/01/2020 04/30/2020 05/06/202...
<p>I'm pretty sure the easiest solution is daemons. Depending on your operating system you would need to use daemons like cron on Linux or Task scheduler on windows, there might be some analogies but those I'm familiar with. Those are tools which schedule certain tasks depending on time criteria and not only.</p> <p><a...
python|python-3.x|pandas
1
19,160
62,893,665
How To get value in [[ ]]
<p>example</p> <pre><code>import pandas as pd b = [[300, 200, 100, 10]] #(data which pass from upper side so cant edit) data_dict = {'value': pd.Series(b)} dframe = pd.DataFrame(data_dict) dframe value 0 [300, 200, 100,10] </code></pre> <p>How to make the number show on each row? like below</p> <pre><code> ...
<p>You can try:</p> <pre><code>dframe.explode('value').reset_index(drop=True) </code></pre> <p>Result:</p> <pre><code> value 0 300 1 200 2 100 3 10 </code></pre>
python|pandas|dataframe
1
19,161
62,511,066
Pivot table in Pandas
<p>I would like to create a pivot table for <strong>Count_Orders</strong> as well as <strong>Count_Sessions</strong>. However, with the current code I can only do the calculation for <strong>Count_Orders</strong> once I am trying to add **Count_Sessions&quot; I get the following error:</p> <p><code>SyntaxError: positio...
<p>Here's a solution:</p> <pre><code>res = pd.pivot_table(df, index=&quot;Month&quot;, columns=[&quot;Country&quot;]) res.columns = [c[0] + &quot;_&quot; + c[1] for c in res.columns] res[[&quot;orders_ratio&quot;, &quot;sessions_ratio&quot;]] = res.iloc[:, [0,2]].divide(res.iloc[:, [1,3]].values) </code></pre> <p>The...
python|pandas
1
19,162
62,525,583
Working with data from CSV with Python without using Pandas
<p>I am very new to using python to process data on CSV files. I have a CSV file with the data below. I want to take the <strong>averages of the time stamps</strong> for each Sprint, Jog, and Walk column <strong>by session</strong>. The below example has the subject <strong>John Doe</strong> and <strong>Session2</stron...
<p>As you want the average grouped by subject and session, just compose unique keys out of that information:</p> <pre><code>import csv times = {} with open('yourfile.csv', 'r') as csvfile[1:]: for row in csv.reader(csvfile, delimiter=','): key = row[0]+row[1] if key not in times.keys(): ...
python|numpy|csv|dictionary|average
0
19,163
54,351,196
Compare dataframe column with strings and numbers
<p>I have a dataframe with two columns that have strings and numbers. When I compare the two columns, they don't match even though they appear to be the same. </p> <p>example data:</p> <pre><code>old_code new_code 100000 100000 </code></pre> <p>When I compare, the result is false:</p> <pre><code>df['old_c...
<h3><code>object</code> dtype series can hold anything</h3> <p>The issue is <code>object</code> dtype series contain <strong>arbitrary</strong> Python objects. Here your series have a string in one and an integer in another:</p> <pre><code>df = pd.DataFrame({'old_code': ['100000'], 'new_code': [100000]}, dtype=object...
python|pandas
11
19,164
71,321,591
How to load images from URL using Pytorch
<p>I want to load the images using Pytorch</p> <p>I have a dataset of <code>image_urls</code> with its corresponding labels(<strong><code>offer_id</code> are labels.</strong>) <a href="https://i.stack.imgur.com/cxSdo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cxSdo.png" alt="enter image descri...
<p>You may convert your image URLs to files first by downloading them to specific folder representing the label. You will certainly find a way to do so. Then you may do like this to check what you have:</p> <pre><code>%%time import glob f=glob.glob('/content/imgs/**/*.png') print(len(f), f) </code></pre> <p>There is a ...
deep-learning|pytorch|pytorch-dataloader
0
19,165
71,388,287
How to groupby column of release year by decade
<p>I'm working on a dataframe of Netflix's movies. I have a column which has the release year of each one and I would like to group this column by decade.</p> <p>The column data type is int64 and when I group my df by release year it looks like this:</p> <pre><code>dates = df.groupby(&quot;release_year&quot;, as_index=...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>out = df.groupby(df[&quot;release_year&quot;] // 10).count() out.index.name = &quot;decade&quot; out = out.reset_index().assign(decade=out.index * 10) print(out) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> decade release_...
python|pandas|function|group-by
0
19,166
71,168,805
Python Pandas Column Formation
<p>Is there an easy way to reformat the columns from</p> <pre><code>2000-01-03 Location1 A1 B1 C1 A2 B2 C2 A3 B3 C3 2000-01-04 Location2 A1 B1 C1 A2 B2 C2 A3 B3 C3 2000-01-05 Location3 A1 B1 C1 A2 B2 C2 A3 B3 C3 </code></pre> <p>to</p> <pre><code>2000-01-03 Location1 A1 A2 A3 B1 B2 B3 C1 C2 C3 2000-01-04 Location...
<p>One of the easiest ways to reorder the columns of Pandas DataFrame is to use indexing</p> <pre><code>reordered_col_list = ['Date', 'Location', 'A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'] df = df[reordered_col_list] </code></pre>
python|pandas
0
19,167
71,246,442
Compare 2 Data frames for partial similarities
<p>How do I compare 2 data frames and remove the rows that have similar values?</p> <pre><code>df = pd.read_csv('trace_id.csv') df1 = pd.read_csv('people.csv') combinedf = pd.concat([df, df1], axis=1) </code></pre> <p><a href="https://i.stack.imgur.com/6UU2y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgu...
<p>Hard to be sure without example data, but you can:</p> <ol> <li>delete <code>TRACE_</code> from the <code>trace_id</code> column of <code>df</code></li> <li>merge on the trimmed <code>trace_id</code> and <code>index</code>, passing <code>indicator=True</code> to get a merge indicator column named <code>_merge</code>...
python|pandas|dataframe
0
19,168
52,405,971
data handling in order to plot seasonal pattern over a time series data
<p>I have a time series data with date range starting from 2007-04-06 until 2018-09-14</p> <pre><code>df.index DatetimeIndex(['2007-04-06', '2007-04-13', '2007-04-20', '2007-04-27', '2007-05-04', '2007-05-11', '2007-05-18', '2007-05-25', '2007-06-01', '2007-06-08', ... ...
<p>Plotting separate lines for each year. More efforts needed to have proper x axis tick marks. Unfortunately, have to run now, will look later</p> <h3>Dummy data</h3> <pre><code>df = pd.DataFrame({'Date': pd.date_range('2003-1-1', periods=4000, freq='B'), 'Pre1': np.random.randint(4500, 5000, 4000)}, columns=['Date'...
python|pandas|matplotlib
0
19,169
60,398,943
Converting string date to a date and dropping the time in a dataframe
<p>I am trying to convert a string date and time (ex: "6/30/2015 0:00") to just a date in this format: %Y/%m/%d. I am trying to do this for all values in a dataframe column. I almost have it but can't seem to get rid of the time part. I also need to apply this method to another column that might have null/blank values....
<p>Try:</p> <pre><code>cnms_df['STATUS_DATE'] = pd.to_datetime(cnms_df['STATUS_DATE'][:cnms_df['STATUS_DATE'].index(' ')[0]], format="%Y/%m/%d") </code></pre> <p>Assuming your dates are consistent, it's just a matter of chopping off the time segment using <code>split</code>. Hope that helps.</p>
python|pandas|datetime|date-conversion
2
19,170
60,434,020
Average over dataframes
<p>Is there a direct way to take the average over multiple dataframes (multiple runs of a simulation for example)? One way that I am using, with 3 dataframmes (df1, df2, df3), but is not the most efficient when having a large number of dataframes is:</p> <pre class="lang-py prettyprint-override"><code>(df1+df2+df3)/3...
<p>To avoid <code>concat</code> it is possible to convert all data to numpy arrays and use <code>mean</code> by <code>axis=0</code>, last convert output to <code>DataFrame</code> constructor:</p> <pre><code>df1 = pd.DataFrame({ 'A':[4,5,4], 'B':[7,8,90], }) df2 = pd.DataFrame({ 'A':[4,50,4]...
python|pandas|dataframe
5
19,171
60,644,978
Keras Tensorflow Custom loss function debug
<p>I'm having trouble debugging my custom loss function in keras. </p> <pre><code>def custom_loss_wrapper(input_tensor): def custom_loss(y_true, y_pred): diff = y_pred - y_true diff = kb.print_tensor(diff) print(input_tensor) return kb.square(diff) return custom_loss model.compile(optimizer='a...
<p>You can define your model.fit as a loop displaying all the required fields like below - </p> <pre><code>for epoch in range(1,5): model.fit(x, y, batch_size=64, epochs= epoch, initial_epoch = (epoch-1), verbose=1, validation_split=0.2, shuffle=True) inputs = model.model._feed_inputs + model.model._fe...
python|tensorflow|keras
1
19,172
60,472,986
Why is my Python returning a random invalid syntax error?
<p><a href="https://i.stack.imgur.com/SyIth.png" rel="nofollow noreferrer">Error in Cmd Prompt</a></p> <pre><code> Traceback (most recent call last): File "Training.py", line 2, in &lt;module&gt; import tensorflow as tf File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tensorf...
<p>according to @khelwood comment, the word 'async' is one of the reserved words.go to your .py document and change all of 'async' to something else.</p>
python|python-3.x|tensorflow|syntax-error
0
19,173
59,513,077
Stacked bar plotting dataframe groups
<p>I'm trying to plot stacked bar chart from a dataframe for several hours. I'm sorry if this is a bare question, but I just can't make it work, I need help.</p> <p>My dataframe looks like this:</p> <pre><code> _id date news_source 0 2715eeada67260...
<p>How about this? I added counts for your data:</p> <pre><code>df1 = df.groupby(['date', 'news_source']).size().reset_index().rename(columns={0:'count'}) </code></pre> <p>Then, I used <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer">pd.crosstab</a>,...
python|pandas|matplotlib
1
19,174
59,504,365
write and read lists from/to file in python
<p>How to write, then read, (conserving all specifics) of the following list, in python?</p> <p>Using various methods, I could not read the data back with the exact same formatting, datatypes, etc. I'm using python 3.6.7. Here is a toy-sample to play with</p> <pre><code>sample_list = [[np.ones(shape = (3,4), dtype=...
<p>Import Pickle:</p> <pre><code>import pickle </code></pre> <p>Save Variable:</p> <pre><code>f = open('store.pckl', 'wb') pickle.dump(sample_list, f) f.close() </code></pre> <p>Load Variable:</p> <pre><code>f = open('store.pckl', 'rb') obj = pickle.load(f) f.close() </code></pre> <p>Reference: <a href="https://s...
python|numpy|file|format|dtype
1
19,175
59,779,428
Python showing timespan
<p>I created a chart where you can see the visualized data and the trend of the data. Is it possible to cut the chart on a timespan?</p> <p>This is my code for the chart</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.dates as mdates fig, ax = plt.subplots() ax.grid(True) year = mdates.YearLocator...
<p>You can use <code>plt.xlim</code> to adjust the date range, </p> <pre class="lang-py prettyprint-override"><code>plt.xlim([datetime(2004, 1, 1), datetime(2008, 1, 1)]) </code></pre> <p>Which will give you an x-axis that looks like </p> <p><a href="https://i.stack.imgur.com/aZXAS.png" rel="nofollow noreferrer"><im...
python|pandas|matplotlib|charts
1
19,176
40,363,292
Python pandas select rows by list of dates
<p>How to select multiple rows of a dataframe by list of dates</p> <pre><code>dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) In[1]: df Out[1]: A B C D 2013-01-01 0.084393 -2.460860 -0.118468 0.54361...
<p>You can use <code>index.isin()</code> method to create a logical index for subsetting:</p> <pre><code>df[df.index.isin(myDates)] </code></pre> <p><a href="https://i.stack.imgur.com/YVahK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YVahK.png" alt="enter image description here"></a></p>
python|pandas|select|time-series
9
19,177
40,558,083
Counting with pandas (two different numbers at the same row)
<p>I have a csv file concerning fines for wrong parking and it contains month , year , and the reason for the fine. I want to find the top 10 reasons (Error section / main cause) for getting the fines.</p> <p>Notice that some rows in the <code>Error section / main cause</code> column some rows have two different reas...
<p>First of all, your file is a bit corrupted: the following two lines should be merged:</p> <pre><code>255121 October;; 255122 ;2014;0701 Parking without p-recognized / p-unit / p-ticket </code></pre> <p>Then your file seem to be Latin-1 encoded. Python 3 assumes by default that all files are UTF-8 and Python 2 assu...
python|pandas
1
19,178
40,336,100
different size of element in numpy array and list
<p>I am using Python 3.4 32 bits on win 7. </p> <p>I found that an integer in an numpy array has 4 bytes, but in a list it has 10 bytes.</p> <pre><code>import numpy as np s = 10; lt = [None] * s; cnt = 0 ; for i in range(0, s): lt[cnt] = i; cnt += 1; lt = [x for x in lt if x is not None]; a = np.array(lt);...
<p>The element size in arrays is easy - it's determined by the <code>dtype</code>, and as your code shows can be found with <code>.itemsize</code>. 4bytes is common, such as for <code>np.int32</code>, <code>np.float64</code>. Unicode strings are also allocated 4 bytes per character - though the real unicode uses a va...
python|arrays|list|numpy
0
19,179
61,888,166
np.savetxt - add one header to csv file
<p>I want to add 1 header to the csv file but the header will be added to each row. <a href="https://i.stack.imgur.com/Mxl8O.png" rel="nofollow noreferrer">this is what i got</a></p> <p><a href="https://i.stack.imgur.com/usQ0v.png" rel="nofollow noreferrer">this is what I want</a></p> <pre><code>IMG_DIR = 'path to th...
<p>Do not repeatedly open the file inside the loop. Open it outside the loop and add header prior to loop once:</p> <pre><code>IMG_DIR = 'path to the images' with open('Data.csv', 'ab') as c: c.write(b'\n') for img in os.listdir(IMG_DIR): img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_COLOR) ...
python|numpy|file
0
19,180
61,732,045
Pandas Resample does not work with mean() method
<p>I am resampling a 12-days frequency time-series. I would like to resample it into a month frequency one by grouping the values by months. It works fine when I resample it by sum and count, but not by mean.</p> <p>This is the code I'm using:</p> <pre><code>date = ['09/03/2015','02/04/2015','26/04/2015','08/05/2015'...
<ul> <li>When the dataframe is created with <code>pd.DataFrame([date,values]).T</code>, the columns are both recognized as objects. The <code>Values</code> type is never set to <code>float</code>.</li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd # data date = ['09/03/2015','02/04/2015','...
python|pandas|mean
0
19,181
62,003,827
denoise image segmentation (mode filtering?) - or how to vectorize this operation in numpy?
<p><em>UPDATE: In my initial post I stupidly applied <code>stats.mode</code> patch-wise rather than along the axis of the patches. Fixing this increased my speed by a factor of 4. however its still slow and my original questions still exist: (1) can i increase the speed? (2) are there different/better/standard approac...
<p>Below I present 2 answers to question my question: </p> <ol> <li>by expanding out my initial attempt into a function that numba can handle</li> <li>using the above suggestion by <a href="https://stackoverflow.com/users/13226440/alex-alex">Alex Alex</a>, which i'll call "categorical-smoothing" (is there a standard n...
numpy|image-processing|computer-vision|image-segmentation|numba
0
19,182
57,966,420
why the tensorflow split function report error when X is a tensor
<p>The tensorflow function split report error and I cannot figure it out</p> <pre class="lang-r prettyprint-override"><code>X = tf$random_uniform(minval=0, maxval=10, shape(256, 32), name = "X"); Y = tf$split(X, num_or_size_splits = 2, axis = 0) </code>...
<p>it works fine in tensorflow 1.14 with eager enabled:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf tf.enable_eager_execution() X = tf.random_uniform(shape=(256, 32),minval=0,maxval=10,name = "X"); Y = tf.split(X, num_or_size_splits = 2, axis = 0) </code></pre> <p>if you are trying to...
r|tensorflow|split
0
19,183
57,942,507
How to save GPU memory usage in PyTorch
<p>In PyTorch I wrote a very simple CNN discriminator and trained it. Now I need to deploy it to make predictions. But the target machine has a small GPU memory and got out of memory error. So I think that I can set <code>requires_grad = False</code> to prevent PyTorch from storing the gradient values. However I didn't...
<p>You can use <a href="https://pypi.org/project/pynvml/" rel="nofollow noreferrer">pynvml</a>.</p> <p>This python tool made Nvidia so you can Python query like this:</p> <pre><code>from pynvml.smi import nvidia_smi nvsmi = nvidia_smi.getInstance() nvsmi.DeviceQuery('memory.free, memory.total') </code></pre> <p>You ...
out-of-memory|pytorch
3
19,184
34,058,054
Extracting X coordinate from numpy array
<p>I am extracting the x positions of 2 blobs via a live two camera stream. I can get the first x position no problem because it is given as a tuple, (ex = ...object at (455, 69)). The problem is I need the x position of the bottom left corner of the second blob but it returns as a numpy array and 'blob.x' does not wor...
<p><code>y2</code> will not be defined if <code>blobs0 is None</code>, in which case you probably don't want to do anything anyway.</p> <p>I suggest you put everything in a single <code>if</code> block:</p> <pre><code>blobs0 = segmentedImage0.findBlobs() blobs1 = segmentedImage1.findBlobs() if blobs0 is not None and ...
python|linux|numpy|raspberry-pi2|simplecv
1
19,185
55,104,496
fillna on DataFrame with a simple function
<p>I am looking for a way of filling NAs values of a DatFrame with a simple function : [row-1].value +1. The particularity of the dataframe is that it has multiple NAs one after another.</p> <p>Here is an example a the kind of DataFrame I am dealing with :</p> <pre><code>import pandas as pd import numpy as np df = pd...
<p>You can try something like this:</p> <pre><code>import pandas as pd import numpy as np df=pd.DataFrame({'a':[1, 2, np.nan, np.nan, 5, np.nan, 7]}) df a 0 1.0 1 2.0 2 NaN 3 NaN 4 5.0 5 NaN 6 7.0 df['a'] = df.groupby(df['a'].notnull().cumsum()).cumcount() + df['a'].ffill() df a 0 1.0 1 2.0 2 3...
python|pandas|dataframe|fillna
2
19,186
54,874,982
Python - Constructing a column of a pandas data frame on conditions and queries
<p>I have to build a column of a dataframe based on some conditions. I usually use the np.where() function but in my case, as expected, it does not work. I need to add a column to the df2 based on the values ​​of another column, in our case 'Let'. When it is equal to 'a' it is necessary to search for a value in another...
<p>Not sure if this helps.</p> <pre><code>new = df2.merge(df1, how = 'left', left_on = ['Animal','Mesure'], right_on = ['Species','Age']) new = new.drop(['Species','Age'], axis = 1) new.loc[new['Let'] == 'b','Dates'] = np.nan new </code></pre>
python|pandas|calculated-columns
0
19,187
28,023,384
Python Pandas: check if items from list is in df index
<p>I have a dataframe: </p> <pre><code>data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012], 'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'], 'wins': ['11102', '8425', '12%', '15%', '11%', '6%', '20%', '4%'], 'losses': ['5222', '8888', '6%', '1%', '5%', '30%...
<p>The reason you saw <code>['b','c']</code> in your first attempt is that what is returned from the inner <code>isin</code> is a boolean index of <code>[False, True, True]</code> which you're applying to the df from the beginning, you need to reapply it again to the last 3 rows:</p> <pre><code>In [21]: fixed_cats = ...
python|pandas|dataframe
4
19,188
28,152,696
Grouping data in Python with pandas yields a blank first row
<p>I have this nice pandas dataframe:</p> <p><img src="https://i.stack.imgur.com/qmce2.png" alt="enter image description here"></p> <p>And I want to group it by the column "0" (which represents the year) and calculate the mean of the other columns for each year. I do such thing with this code:</p> <pre><code>df.grou...
<p>That's just a display thing, the grouped column now becomes the index and this is just the way that it is displayed, you will notice here that even when you set <code>pd.set_option('display.notebook_repr_html', False)</code> you still get this line, it has no effect on operations on the goruped df:</p> <pre><code>I...
python|pandas|group-by|mean
1
19,189
73,252,622
Fix the data frame: for one date one value in Pandas
<p>I just started learning the Pandas package in Python and I need help.</p> <p>I have got this data frame:</p> <pre><code> dataStream rowCount probingTimestamp 0 BCL_TaskCreation 315349655 2020-01-13 09:33:00.497 1 BCL_TaskCreation 315349655 2020-01-13 09:34:00.157 2 BCL_TaskCreation 31453377...
<p>try:</p> <pre class="lang-py prettyprint-override"><code># only if the column probingTimestamp is not of type datetime64 else skip this line df.probingTimestamp = df.probingTimestamp.astype('datetime64') df['rowCount'] = df.probingTimestamp.dt.date\ # Get date without time .map( ...
python|pandas|dataframe
2
19,190
73,199,393
How to create dynamic dataframe using python loop?
<p>I have a 4 dataframes that I generate for 2 products each, totaling 8 dataframes.</p> <p>Currently, I create each dataframe manually such as (very clunky):</p> <pre><code>productA = productA.withColumn('col1', productA['col2'] / productA['col3']) productA = productA.withColumn('col4', productA['col5'] / productA['co...
<pre><code>def cal_new_column(df): for i in range (1, 11, 3): numerator = i+1 denominator = i+2 df = df.withColumn(f'col{i}', col(f'col{numerator}') / col(f'col{denominator}')) return df df = spark.createDataFrame( [ (2, 4, 8, 16, 10, 20, 33, 66), (1, 2, 3, 6, 2, 8, 11, 22), ],...
python|pandas|pyspark
0
19,191
73,192,365
Creating custom function in python
<p>I'm trying to create a custom function that will return the percentage of a column consisting of 0 in this dataframe (refer to the image).</p> <p>The interested columns are &quot;Scholarship&quot;, &quot;Hipertension&quot;, &quot;Diabetes&quot;, &quot;Alcoholism&quot;, &quot;Handcap&quot; and &quot;SMS_received&quot...
<p>Your syntax is wrong at for loop. You need to correct that first.</p> <p>within your function you can try getting first total count of 0's and 1's with;</p> <pre><code>values = df[&quot;column_name&quot;].value_counts() </code></pre> <p>Then using this variable you can make your calculation and return percent. So ex...
python|pandas|function
1
19,192
73,352,629
Reading large csv with variable chunks sizes - pandas
<p>I have a csv file with an id column. I want to read it but I need to process all consecutive entries of an id at the same time. For example, if the &quot;chunk size&quot; was 2, <code>df = pd.read_csv(&quot;data.csv&quot;, chunksize=2)</code>, I would only read these two first values of A whereas I need to process ...
<p>Based on the comments suggesting this <a href="https://stackoverflow.com/questions/42228770/load-pandas-dataframe-with-chunksize-determined-by-column-variable/42229904#42229904">accepted answer</a>, I slightly changed the code to fit any chunk size as it was incredibly slow on large files, especially when manipulati...
python|pandas|dataframe
0
19,193
73,322,462
How to add all standard special tokens to my hugging face tokenizer and model?
<p>I want all special tokens to always be available. How do I do this?</p> <p>My first attempt to give it to my tokenizer:</p> <pre><code>def does_t5_have_sep_token(): tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained('t5-small') assert isinstance(tokenizer, PreTrainedTokenizerFast) print(t...
<p>I think this is correct. Please correct me if I'm wrong:</p> <pre><code>def add_special_all_special_tokens(tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast]): &quot;&quot;&quot; special_tokens_dict = {&quot;cls_token&quot;: &quot;&lt;CLS&gt;&quot;} num_added_toks = tokenizer.add_spe...
python|machine-learning|deep-learning|huggingface-transformers
0
19,194
67,395,128
Pandas Pivot table and Rank
<p>I have below dataframe</p> <pre><code>df = pd.DataFrame() df['SubjectArea'] = [&quot;a&quot;,&quot;b&quot;,&quot;a&quot;,&quot;c&quot;,&quot;a&quot;,&quot;s&quot;,&quot;d&quot;,&quot;b&quot;,&quot;s&quot;,&quot;a&quot;,&quot;s&quot;,&quot;c&quot;,&quot;s&quot;,&quot;z&quot;,&quot;a&quot;] df['Articles'] = [10, 20,5,...
<p>You can assign rank without separating the subjects with <code>groupby</code>:</p> <pre><code>df[&quot;weightedAverage&quot;] = df[&quot;Articles&quot;]*0.35 + df[&quot;NoOfReading&quot;]*0.65 df['Rank'] = df.groupby('SubjectArea')['weightedAverage'].rank() df = df.sort_values(['SubjectArea', 'Rank']) </code></pre...
python|pandas|dataframe|pivot-table
2
19,195
67,244,650
Why does Pandas Series slicing behave differently when slicing using index numbers versus index values?
<p>Came across this problem and was curious why the values for slicing using the index numbers is exclusive at the end but using the index values was inclusive. Here's a short reproducible example. I apologize if I'm using improper terminology.</p> <pre><code># start with a pandas series series = pd.Series(np.arange(5)...
<p>Not sure if this has been answered before hence a community wiki.</p> <p>According to the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-slicing-with-labels" rel="nofollow noreferrer">Slicing with Labels</a> documentation:</p> <blockquote> <p>When using .loc with slices, if b...
python|python-3.x|pandas|series
0
19,196
67,570,696
TypeError: Parameter to MergeFrom() must be instance of same class: expected TensorShapeProto got TensorShapeProto. in tf.keras.layers.Embedding
<p>I'm Trying to do text Classification with <code>tensorflow.keras.layers.Embedding</code> and Glove. when I run the code:</p> <pre><code>model.add(Embedding(len(word_index) + 1, 100, weights=[embedding_matrix], input_length=MAX_LENGTH, trainable=False)) </code></pre> <p>I get the error :</p> <pre><code>TypeError:...
<p>I was able to reproduce this issue. Thanks to the <a href="https://github.com/tensorflow/tensorflow/issues/50545" rel="nofollow noreferrer">@sclarkson answer</a> the bug went away when I did the following:</p> <p>I. Find file <code>lib/python3.7/site-packages/tensorflow/python/__init__.py</code> in my environment di...
python|tensorflow|keras|nlp
3
19,197
67,562,512
How do I convert Coin Market Cap API data from JSON to Pandas Dataframe?
<pre><code>import requests import pandas as pd import APIKEY url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' parameters = { 'start': '1', 'limit': '10', 'convert': 'USD' } headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': APIKEY.KeyAPI, } jsondata = reque...
<p>There's good documentation here: <a href="https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest" rel="nofollow noreferrer">https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest</a></p> <p>try something like this (because I'm not exactly seei...
python|json|pandas|coinmarketcap
1
19,198
34,634,606
pandas plot x-axis label
<p>I bumped into a problem when plotting a pandas series. When plotting the series with a datetime x-axis, x-axis is accordingly relabeled when zooming, i.e. it works fine:</p> <pre><code>from matplotlib import pyplot as plt from numpy.random import randn from pandas import Series,date_range import numpy as np, pandas...
<p>When you format your date labels as strings before plotting, you lose all the actual date information; they're just strings now. This means that pandas / matplotlib can't reformat the tick labels when you zoom. See the first paragraph after the plot <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/visual...
python|pandas|plot|axis-labels
0
19,199
34,616,067
Use string.capwords with Pandas column
<p>Given this data frame:</p> <pre><code>df = pd.DataFrame( {'A' : ['''And's one''', 'And two', 'and Three'], 'B' : ['A', 'B', 'A']}) df A B 0 And's one A 1 And two B 2 and Three A </code></pre> <p>I am attempting to capitalize the first letter only (without capitalizing the ...
<p>You can use the vectorised <code>str.split</code> and then <code>apply</code> a lambda and join:</p> <pre><code>In [132]: df['A'].str.split().apply(lambda x: [el.capitalize() for el in x]).str.join(' ') Out[132]: 0 And's One 1 And Two 2 And Three dtype: object </code></pre> <p>or call <code>apply</code...
python-3.x|pandas|capitalize
3