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
10,100
61,907,616
(pandas)I want add to count,percent at groupby
<blockquote> <p>i do road csv file's and grouping 2 headers in csv file so i want to each other count about 1 headers value and percent count/total and add dataframe</p> <p>have a lot of data in test.csv</p> </blockquote> <pre><code>==example== country city name KOREA busan Kim KOREA busan choi KORE...
<p>I believe you need counts per <code>country</code> and <code>name</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a> and then percentage divide by length of <code>DataFrame</code>:</p> <pre><code...
python|pandas|pandas-groupby
1
10,101
61,667,735
How to select 5% of total values from a tensor randomly?
<p><code>a = torch.rand(2,5,10)</code> I want to select at most 5% of values from tensor <code>a</code> randomly and then multiply those values with <code>-1</code>? How to do that? kindly, give a generic solution as the shape of the tensor is not fixed</p>
<p>This worked for me</p> <pre><code>out = (torch.rand_like(a) - 0.05).sign().type_as(a) * a </code></pre>
pytorch|tensor
0
10,102
61,900,003
Simple way to convert tensor to numpy array without eager mode in TF 2.2
<p>I can't find a simple way to convert a tensor to a NumPy array without enabling eager mode, which gives a nice .numpy() method, but also slows down my model training. </p> <p>I'd be super grateful for your suggestions. For context, I'm writing a custom metric for my TensorFlow model that relies on a scikit learn fu...
<p>Wrapping my NumPy metric with tf.numpy_function() solved it. <a href="https://www.tensorflow.org/api_docs/python/tf/numpy_function" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/numpy_function</a></p>
numpy|tensorflow|keras
0
10,103
61,821,685
In Tensorflow, is there a built in function to compute states over time given a transition matrix?
<p>I have a system given by this recursive relationship: x<sub>t</sub> = A<sub>t</sub> x<sub>t-1</sub> + b<sub>t</sub>. I wish to compute x<sub>t</sub> for all t, with A<sub>t</sub>, b<sub>t</sub> and x<sub>0</sub> given. Is there are built-in function for that? If I use a loop it would be extremely slow. Thanks! </p>
<p>There is sort of a way. Let's say you have your <code>A</code> matrices in a 3D tensor with shape <code>(T, N, N)</code>, where <code>T</code> is the total number of time steps and <code>N</code> is the size of your vector. Similarly, <code>B</code> values are in a 2D tensor <code>(T, N)</code>. The first step in th...
tensorflow
0
10,104
57,834,295
Pandas select values from each hour for each ID
<p>I have a dataframe in which I have some IDs, and for each ID I have some values and timestamps (around one value each 5 minutes for 5 to 7 days in a row). I would like to select, for each hour and for each ID, the mean, median and variance of the values in that hour and store them in different columns like in the fo...
<p>Try this:</p> <pre><code># Extract the hour from the Date column h = df['Date'].dt.hour.rename('Hour') # Group by ID and Hour df.groupby(['ID', h]).agg({ 'Value': ['mean', 'var', 'median'] }) </code></pre> <p>You can replace the <code>h</code> series by <code>pd.Grouper</code>. By default <code>pd.Grouper</co...
python|pandas|hour
1
10,105
34,224,954
Why my VAE for toy dateset doesn't learn?
<p>I played with VAE (Variational Auto-encoder) for a couple of days. It works pretty well on the demo dataset like mnist or frayface. However, when I apply it to my own dataset, it doesn't work at all.</p> <p>I cannot find any reference regarding the potential difficulties in training VAE, so I made a tiny test case....
<p>One very common problem that occur in VAEs is 'Posterior Collapse' (see here: <a href="https://datascience.stackexchange.com/questions/48962/what-is-posterior-collapse-phenomenon">https://datascience.stackexchange.com/questions/48962/what-is-posterior-collapse-phenomenon</a>).</p> <p>If this is indeed the case, I s...
neural-network|tensorflow
0
10,106
36,876,798
Pandas read csv with multiple whitespaces and parse dates
<p>I have a csv file that looks like</p> <pre><code>Year Mo Da (01,52) 1950 1 1 0.00 1950 1 2 0.00 1950 1 3 0.05 1950 1 4 0.00 1950 1 5 0.07 1950 1 6 0.07 </code></pre> <p>and I would like transform it into a dataframe with 2 columns: a datetime column of...
<p>If you pass params <code>delim_whitespace=True</code> and pass the 3 columns in a list to <code>parse_dates</code> the last step is just to overwrite the column names:</p> <pre><code>In [96]: import pandas as pd import io t="""Year Mo Da (01,52) 1950 1 1 0.00 1950 1 2 0.00 1950 1 3 0.0...
python|csv|datetime|pandas
1
10,107
36,736,793
Tensorflow convolutional net error: Invalid argument: logits and labels must be same size: logits_size=[512,4] labels_size=[128,4]
<p>I made a convnet based on the 5_convolutional_net.py example found here: <a href="https://github.com/nlintz/TensorFlow-Tutorials" rel="nofollow noreferrer">https://github.com/nlintz/TensorFlow-Tutorials</a>. I try to classify chess pieces. I loaded my pictures : I ve got 1136 60x60 grayscale images for each piece. I...
<p>Since you feed 60x60x1 image, your tensor shapes will be these:</p> <pre><code>Tensor("Relu:0", shape=(?, 60, 60, 32), dtype=float32) Tensor("MaxPool:0", shape=(?, 30, 30, 32), dtype=float32) Tensor("Relu_1:0", shape=(?, 30, 30, 64), dtype=float32) Tensor("MaxPool_1:0", shape=(?, 15, 15, 64), dtype=float32) Tensor(...
python|machine-learning|classification|tensorflow|conv-neural-network
3
10,108
55,102,108
Pandas group and join
<p>I am new to pandas. I want to analysis the following case. Let say, A fruit market is giving the prices of the fruits daily the time from 18:00 to 22:00. For every half an hour they are updating the price of the fruits between the time lab. Consider the market giving the prices of the fruits at 18:00 as follows,</p>...
<p>You dont need to pivot in this case, we can simply use <code>merge</code> and use <code>suffixes</code> argument to get the desired results:</p> <pre><code>df_update = pd.merge(df, df2, on='Fruit', how='outer', suffixes=['_1800h', '_1830h']) Fruit Price_1800h Price_1830h 0 Apple 10.0 10.0 ...
python|pandas
2
10,109
54,951,663
Calculate time difference, if difference greater than an hour, mark as 'missing', plot gap in line graph in that area
<p>I have a basic pandas dataframe in python, that takes in data and plots a line graph. Each data point involves a time. If everything runs well with the data file, ideally each time stamp is roughly 30 min different from each other. In some cases, no data comes through for more than in hour. During these times, I wan...
<p>Not exactly what you want, but a quick and elegant solution is to resample your data.</p> <pre><code>df = df.set_index('datetime') df </code></pre> <pre class="lang-none prettyprint-override"><code> l1 l2 l3 datetime 2019-02-03 01:52:16 0.1 0.2 0.4 2019-02-03 0...
python|pandas|plot|time|linegraph
2
10,110
49,757,721
Insert a column into a Dataframe without modifying the original frame
<p>I have a DataFrame named <code>df_orig</code> as follows:</p> <pre><code>import pandas as pd import numpy as np exam_data = {'name': ['X1', 'X2', 'X3'], 'score': [12.5, 9, 16.5], 'attempts': [1, 3, 2], 'qualify': ['yes', 'no', 'yes']} labels = ['a', 'b', 'c'] df_orig = pd.DataFrame(exam_dat...
<p>To avoid changing the original <code>DataFrame</code> use:</p> <pre><code>df1 = df_orig.copy() </code></pre> <p>By default, Python passes by reference. An explicit copy is required to keep unchanged the original object.</p>
python|python-3.x|pandas|dataframe
3
10,111
73,502,635
CNN-LSTM model for sentiment analysis has low validation accuracy
<p>I am working on a project to implement CNN-LSTM sentiment analysis. Below is the code</p> <pre><code>from keras.models import Sequential from keras import regularizers from keras import backend as K from keras.callbacks import ModelCheckpoint from keras.layers import Dense, Conv1D , MaxPool1D , Flatten , Dropout fr...
<p>Since your code works, I believe that your network is failing silently by 'not learning' a lot from the data. Here's a list of some of the things you can generally check:</p> <ul> <li><p>Is your textual data well transformed into numerical data? Is it well reprented using TF-IDF or bag of words or any other method t...
python|tensorflow|machine-learning|keras|deep-learning
0
10,112
35,241,673
pandas df.apply TypeError data type not understood
<p>I'm trying to apply an operation to every value in a datetime series. I've reduced this to a lambda print to illustrate the problem. This works in another similar dataframe but not on this one? Python is version 3.5.1, pandas version 0.17.1. </p> <p>Some more padding to satisfy the SO question verbosity requirement...
<p>I don't really known what's going on, but as a workaround you can get the expected output calling <code>apply()</code>on the column:</p> <pre><code>dfY['predicted_time'].apply(lambda rr: print(rr)) </code></pre> <p><strong>EDIT</strong> Looks like you hit a bug in pandas. The issue is triggered by using time zone ...
python|numpy|pandas
2
10,113
31,151,913
How to specify depth of iterator in numpy?
<p>I have a multidimensional array in numpy (e.g. 4D) and I want to specify the depth of the numpy iterator and I am not sure how to do this please?</p> <p>For example, let's say I have a 4D numpy array, and I want to get elements form the iterator only for the 2D level (so then each item would be also 2D). Is there a...
<p><code>np.ndindex</code> does a nice job of iterating over specified dimensions.</p> <p>Your <code>x</code> is a 4d <code>object</code> array <code>dtype=ndarray</code> becomes <code>dtype=object</code>. Though with tuples all the same size the elements are really just scalars, not arrays.</p> <pre><code>In [385]:...
python|arrays|numpy|iterator
2
10,114
67,596,326
SageMath: Getting the imaginary part of a matrix
<p>Suppose you have a matrix with complex entries, and you would like to extract the imaginary component of each entry and make a new matrix in Sage. For instance, suppose</p> <pre class="lang-py prettyprint-override"><code>M = [[1 + 2i, 5 + 3*i], [5, 3*i]] </code></pre> <p>I would like to get</p> <pre class="lang-py p...
<p>Beware that this really defines a list of lists, not a matrix:</p> <pre class="lang-py prettyprint-override"><code>sage: M = [[1 + 2*i, 5 + 3*i], [5, 3*i]] </code></pre> <p>so that it displays like a list of lists:</p> <pre class="lang-py prettyprint-override"><code>sage: M [[2*I + 1, 3*I + 5], [5, 3*I]] </code></pr...
python|numpy|matrix|sage
1
10,115
67,307,130
Dynamically build tensor from 1s and 0s in TensorFlow
<p>Given an integer tensor like <code>x = [2 0 1 0]</code> and a constant <code>C = 3</code> I would like to build a tensor</p> <pre><code>[[1 1 0], [0 0 0], [1 0 0], [0 0 0]] </code></pre> <p>So <code>C</code> is the number of columns, <code>len(x)</code> is the number of rows. Each entry of <code>x</code> specifie...
<p><code>tf.sequence_mask()</code> produces the desired result:</p> <pre><code>In [8]: s = tf.sequence_mask(x, maxlen=C, dtype=tf.int32) In [9]: print(s) tf.Tensor( [[1 1 0] [0 0 0] [1 0 0] [0 0 0]], shape=(4, 3), dtype=int32) </code></pre>
python|tensorflow
0
10,116
67,575,581
How to append array in python using Numpy
<p>I am new to python, Can you please tell me how to append an array with an empty array.</p> <p>I want output like this <code>[[2,6] [5, 4]]</code>. can you please suggest?</p> <p>I do not want output like below</p> <p><a href="https://i.stack.imgur.com/KXC1z.png" rel="nofollow noreferrer"><img src="https://i.stack.im...
<p>The <code>np.append</code> function flattens the inputs if the <code>axis</code> parameter is not supplied (as stated <a href="https://numpy.org/doc/stable/reference/generated/numpy.append.html" rel="nofollow noreferrer">here</a>). Therefore to achieve what you want you should specify <code>axis=0</code></p> <pre cl...
numpy
0
10,117
34,548,681
Vectorize integration of pandas.DataFrame
<p>I have a <code>DataFrame</code> of force-displacement data. The displacement array has been set to the <code>DataFrame</code> index, and the columns are my various force curves for different tests.</p> <p>How do I calculate the work done (which is "the area under the curve")?</p> <p>I looked at <a href="http://doc...
<p>You could vectorize this by passing the whole <code>DataFrame</code> to <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.trapz.html" rel="noreferrer"><code>np.trapz</code></a> and specifying the <code>axis=</code> argument, e.g.:</p> <pre><code>import numpy as np import pandas as pd # some...
python|numpy|pandas|vectorization|numerical-integration
7
10,118
34,600,056
Using Pandas to fill NaN entries based on values in a different column, using a dictionary as a guide
<p>I have a large dataframe where I'm trying to populate the NaN entries of column B based on the values in column A, using a dictionary as a guide. For example:</p> <pre><code>df = A B 0 Red 628 1 Red 149 2 Red NaN 3 Green 575 4 Green 687 5 Green NaN 6 Blue 159 7 Blue NaN </code></pre>...
<p>I think your index looks iffy, the following does what you want:</p> <pre><code>In [19]: df['B'] = df.set_index('A')['B'].fillna(d).reset_index()['B'] df Out[19]: A B 0 Red 628 1 Red 149 2 Red 123 3 Green 575 4 Green 687 5 Green 456 6 Blue 159 7 Blue 789 </code></pre> <p>Here we ...
python|dictionary|pandas
2
10,119
34,463,613
Convert NumPy arrays to Pandas Dataframe with columns
<p>I want to normalize my both categorical and numeric values. </p> <pre><code>cols = df.columns.values.tolist() df_num = df.drop(CAT_COLUMNS, axis=1) df_num = df_num.as_matrix() df_num = preprocessing.StandardScaler().fit_transform(df_num) df.fillna('NA', inplace=True) df_cat = df.T.to_dict().values() vec_cat = D...
<p>What you are looking for is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>pandas.get_dummies()</code></a>. It will perform one hot encoding on categorical columns, and produce a dataframe as the result. From there you can use <code>pandas.concat([existi...
python|python-2.7|numpy|pandas|scikit-learn
2
10,120
60,017,998
How to get the counts of False in pandas
<p>I have a dataframe like below</p> <pre><code>no out 20 True 3 False 3 False </code></pre> <p>How to get the counts of True and False</p> <pre><code>df.groupby(['out']).agg({'out':sum}) out out False 0.0 True 26.0 </code></pre> <p>I am getting False count as 0</p>
<p>Try:</p> <pre><code>df.groupby(['out'])['out'].count() </code></pre>
python|pandas
0
10,121
65,229,918
Multiple groupings and groupby aggregations using Python Pandas
<p>I have a dataset that looks very similar to the data below.</p> <ol> <li><p>I would like to create two groups using values in the sku column.</p> <p>group1 - new &amp;</p> <p>group2 - old</p> </li> <li><p>Within the group1 - new, I would like to then groupby rack and take the average of each grouped rack and sum ...
<p>You can filter by conditions with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> for match multiple <code>sku</code> and for old all not match values by <code>~</code> for invert mask:</p> <pre><code>mask = df.sku.isi...
python|pandas|numpy
2
10,122
65,223,566
Pandas: reformatting CSV data from single column into multiple new columns
<p>I'm relatively new to python and have been using Pandas to manipulate scientific data. I have 79 datasets in CSV format of inconsistent satellite imagery of pixel values (lots of NaNs) that have been averaged to bi-monthly values (two months averaged together). The data is formatted similar to the the example data f...
<p>I think all you need to do is use a list for the <code>values</code> parameter:</p> <pre><code>bimonths = ['F-M', 'A-M', 'J-J', 'A-S', 'O-N', 'D-J'] df.pivot(index='year', columns = 'grouping', values = ['region_1','region_2']).reindex(bimonths, axis=1, level=1) </code></pre> <p>Output (column alignment messed up by...
python|python-3.x|pandas|dataframe|reformatting
2
10,123
65,264,231
Is CUDA installation necessary to use GPU while running NLP models eg. BERT at local machine
<p>Does someone need a CUDA toolkit to use local GPU while executing NLP models like BERT or Tensorflow library has the capability to trigger the local machine GPU on its own without extra code to be written(for GPU processing instead of CPU)?</p>
<h2>TLDR :</h2> <p>if You are asking is it necessary to have Cuda installation in order to utilize your NVIDIA-GPU in a Deep Learning framework, it depends. Pytorch ships the necessary Cuda libs and you do not need to have it installed. Tensorflow on the other hand seems to require it.<br /> However, also note that you...
tensorflow|deep-learning|gpu|nvidia|bert-language-model
1
10,124
65,470,463
numpy indexing doesn't keep shape
<p>Running</p> <pre><code>import numpy as np a1 = np.arange(1, 5) a2 = np.arange(2, 6) a = np.array([a1, a2]) a[a &lt;= 3] </code></pre> <p>results in</p> <pre><code>array([1, 2, 3, 2, 3]) </code></pre> <p>Instead I would like to get</p> <pre><code>np.array([[1, 2, 3], [2, 3]]) </code></pre> <p>How should I updated th...
<p>You could use numpy's <a href="https://numpy.org/doc/stable/reference/maskedarray.html" rel="nofollow noreferrer">masked arrays</a> for this purpose.</p> <pre><code>import numpy as np import numpy.ma as ma a1 = np.arange(1, 5) a2 = np.arange(2, 6) a = np.array([a1, a2]) a_masked = ma.masked_greater(a, 3) </code></p...
python|numpy|numpy-ndarray|numpy-slicing
2
10,125
63,856,355
OpenCv imread error while trying it in real-time
<p><strong>code:</strong></p> <pre><code>import face_recognition as fr import os import cv2 import face_recognition import numpy as np from time import sleep def get_encoded_faces(): encoded = {} for dirpath, dnames, fname in os.walk(&quot;./faces&quot;): for f in fname: if f.endswit...
<p>The code and the error message don't agree. Are you running an older version of the code?</p> <p>Error message:</p> <blockquote> <p>File &quot;face.py&quot;, line 37, in classify_face</p> <p>img = cv2.imread(im, 1)</p> </blockquote> <p>Code:</p> <blockquote> <p>img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)</p> </blockq...
python|numpy|computer-vision|opencv3.0|face-recognition
1
10,126
64,119,205
Different frequencies data
<p>I have data for firms that look as follows and data for inflation. However, I have may companies while inflation is the same for all companies. I am wondering how I can put the same value for inflation for each company. <a href="https://i.stack.imgur.com/p896s.png" rel="nofollow noreferrer"><img src="https://i.stack...
<p>I solved the problem by using the concat function pd.concat.</p>
python|pandas|merge
0
10,127
63,931,085
Python : import csv ignoring single comma
<p>i have a csv file below which works fine:</p> <pre><code>Test Case ID,summary TC-16610,“verify that user is able to u_pdate 'active' attribute 'false ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'true'” TC-16609,“verify that user is able to u_pdat...
<p>When you read the file with the comma, first row has <code>NAN</code> values. You need to drop <code>NAN</code> values before you try to apply <code>transform()</code> use</p> <p><code>data = data.dropna()</code></p>
python|python-3.x|django|pandas|csv
1
10,128
47,062,741
Pandas dataframe to nested dictionary
<p>Let's say my dataframe looks like this.</p> <pre><code>date app_id country val1 val2 val3 val4 2016-01-01 123 US 50 70 80 90 2016-01-02 123 US 60 80 90 100 2016-01-03 123 US 70 88 99 11 </code></pre> <p>I want to dump this into a nested dictionary or even a JSON object as...
<p>1st create the dataframe you need. then using <a href="https://stackoverflow.com/questions/19798112/convert-pandas-dataframe-to-a-nested-dict">recur_dictify</a> from DSM.</p> <pre><code>dd=df.groupby(['country','app_id','date'],as_index=False)['val1', 'val2', 'val3', 'val4'].apply(lambda x : x.values.tolist()[0]).t...
python|pandas
2
10,129
46,669,045
Exception doesn't make exception for DataFrame python
<p>I tried to load some data from an excel file and check if some values are integers. However, I am unsuccessful and the <code>IsInt</code> method does not trigger any exceptions. Why?</p> <p>In the Excel file, an integer can be saved as 5.00 as well.</p> <pre><code>class Load; def __init__(self, path="data.xls"...
<p>In Python, <code>num = int(1.6)</code> does not cause an error. It just sets <code>num</code> to <code>1</code> by truncating the fractional part.</p> <p>To check if a number is really an integer, do something like <code>if x == int(x): ...</code>. You should still catch the <code>TypeError</code> in case <code>x</...
python|pandas|exception
0
10,130
32,854,386
python pandas: trying to reference data from another column's previous month end
<p>I am trying to create a column in a dataframe that references the value in another column from the previous month end. Like this...</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Date SD SD.prevmo 0...
<p>After you set the values for <code>is_month_end==True</code> with <code>df['SD']</code>, you can full <code>NAs</code> with <code>ffill</code> methiod - which forward fills the values.</p> <pre><code>In [10]: df.ix[df.index.is_month_end==True, 'SD.prevmo'] = df['SD'] In [11]: df['SD.prevmo'].fillna(method='ffill') ...
python|datetime|pandas|indexing|offset
1
10,131
38,625,102
Change some, but not all, pandas multiindex column names
<p>Suppose I have a data frame with multiindex column names that looks like this:</p> <pre><code> A B '1.5' '2.3' '8.4' b1 r1 1 2 3 a r2 4 5 6 b r3 7 8 9 10 </code></pre> <p>How would I change the just the column names under 'A' from strings to floats...
<pre><code># build the DataFrame (sideways at first, then transposed) arrays = [['A','A','A','B'],['1.5', '2.3', '8.4', 'b1']] tuples = list( zip(*arrays) ) data1 = np.array([[1,2,3,'a'], [4,5,6,'b'], [7,8,9,10]]) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df = pd.DataFrame(data1.T, index=in...
python|pandas
1
10,132
38,622,163
TensorFlow: Does it only have SGD algorithms? or does it also have others like LBFGS
<p>Question about TensorFlow:</p> <p>I was looking at the video and model on the site, and it appeared to only have SGD as an algorithm for machine learning. I was wondering if other algorithms are also included in tensorflow, such as L-BFGS.</p> <p>Thank you for your responses.</p>
<p>TensorFlow's jargon for the algorithms such as Stochastic Gradient Descent (SGD) is optimizer. Following are the optimizers supported by TensorFlow:</p> <ul> <li><a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/train.html#GradientDescentOptimizer" rel="nofollow noreferrer">GradientDescentOptimizer<...
algorithm|machine-learning|neural-network|tensorflow|data-science
10
10,133
63,087,096
Sub dataframe based on the dtype
<p>My dataframe consists of both numerical and categorical data. I want to get the sub dataframe which consists of categorical data(dtype=object) only. I don't know how to get the sub dataset based on dtype. Please suggest me how to do it?</p>
<p>Elaborating on the comment,</p> <pre><code>import pandas as pd import numpy as np A = np.random.rand(3) B = np.random.rand(3) df = pd.DataFrame(data=[A, A, B, B, B], columns = ['1st', '2nd', '3rd']) df['1st'] = df['1st'].apply(lambda x: str(x)) print(df.select_dtypes([object])) </code></pre>
python|pandas|data-science
0
10,134
62,969,722
How to count the number of string words in a column of lists?
<p>I have a dataframe like:</p> <pre><code>Artist Genre A ['Pop','Rock'] B ['Pop'] C ['Rock', 'Electro'] </code></pre> <p>I want to find the frequency of each genre in the dataframe , ie:</p> <pre><code>Genre Count 'Pop' 2 'Rock' 2 'Electro' 1 ...
<p>try this, Convert string to list using <code>literal_eval</code> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>Series.explode</code></a> Transform each element of a list-like to a row, followed by <a href="https://pandas.pydata.org/p...
python|pandas|list|dataframe|count
0
10,135
63,122,338
How to print a dataframe without the name of the columns and the index
<p>I have a dataframe without columns names and when I print it I get a row with numbers, how can I print without this row? I have the same problem with the index, how can I print without index and columns?</p>
<p>See <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_string.html" rel="nofollow noreferrer">the docs</a> for some more info on using the <code>to_string()</code> function in pandas.</p> <pre><code>print(df.to_string(index=False)) </code></pre> <p>To hide the index and the colum...
python|pandas|dataframe
2
10,136
63,132,726
comparing numpy arrays element-wise setting an element-wise result
<p>possibly this has been asked before, but I have a hard time finding a corresponding solution, since I can't find the right keywords to search for it.</p> <p>One huge advantage of numpy arrays that I like is that they are transparent for many operations. However in my code I have a function that has a conditional sta...
<p><code>arr1 &gt; arr2</code> does exactly what you'd hope it does: compare each element of the two arrays and build an array with the result. The result can be used to index in any of the two arrays, should you need to. The equivalent of your function, however, can be done with <a href="https://numpy.org/doc/stable/r...
python|arrays|numpy
1
10,137
67,886,588
Extract words from two lists from sentences in a dataframe
<p>I have text in a panda dataframe</p> <p>I also have two lists of words. I want to see if elements of these lists exist in one sentence and extract all pairings separated by a colon (also if not paired)</p> <p>Eg</p> <pre><code> patternAnatomy=&quot;oesophagus|stomach|duodenum&quot; patternEvent=&quot;clip|RFA|...
<pre><code>k=patternAnatomy+'|'+patternEvent df['extract']=df['text'].str.findall(k) </code></pre>
python|pandas|dataframe
0
10,138
67,878,557
Python: How to generate a random number not part of dataframe?
<p>I have a dataframe containing 15K+ strings in the format of <code>xxxx-yyyyy-zzz</code>. The <code>yyyyy</code> is a random 5 digit number generated. Given that I have <code>xxxx</code> as 1000 and <code>zzz</code> as 200, how can I generate the random <code>yyyyy</code> and add it to the dataframe so that the strin...
<p>I tried to come up with a generic approach, you can use this for lists:</p> <pre><code>import random number_series = [&quot;1000-12345-100&quot;, &quot;1000-82045-200&quot;, &quot;1000-93035-200&quot;] def rnd_nums(n_numbers: int, number_series: list, max_length: int=5, prefix: int=1000, suffix: int=100): # ig...
python|pandas|numpy
1
10,139
67,853,409
How to train machine learning with strings?
<p>I have made input data for machine learning as csv file . The data are 2D arrays input and label Example</p> <p>[[55:32:1:23:41:243:255:11:182:192:231:201],&quot;play&quot;]</p> <p>[[23:222:225],&quot;talk&quot;]</p> <p>[[23:132:215:111:29:192],&quot;talk&quot;]</p> <div class="s-table-container"> <table class="s-ta...
<p>You need a way that the model can predict the output. If you have a fixed amount of strings that you want to predict, you have to map each unique string to a binary variable.</p> <p>An example is a 2-dimensional vector where the first dimension represents &quot;play&quot; and the second dimension represents &quot;ta...
python|pandas|tensorflow|machine-learning|keras
1
10,140
67,951,975
Assistance needed scraping a site with Selenium in Python
<p>I am trying to scrape the NBA player names and projected fantasy score (not single stat DFS) using selenium. I've gotten as far as using selenium to automate clicking NBA, and selecting the fantasy score tab.</p> <p>From there, I see the players in a grid where I will like to scrape the points and names for each pla...
<p>You could do this more easily without <code>Selenium</code> since the data is dynamically loaded from an api:</p> <pre><code>import pandas as pd import requests params = ( ('league_id', '7'), ('per_page', '250'), ('projection_type_id', '1'), ('single_stat', 'true'), ) session = requests.Session() ...
python|pandas|selenium|selenium-webdriver
3
10,141
67,632,190
AttributeError: 'float' object has no attribute 'dtype'
<p>When I try to use a custom activation function in keras (2.2.5), I create a new activation function gelu. add it in activations.py :</p> <pre><code>from . import backend as K import numpy as np def gelu(x): return 0.5 * x * (1 + K.tanh(K.sqrt(2 / np.pi) * (x + 0.044715 * K.pow(x, 3)))) </code></pre> <p>use i...
<p>Replace <code>K.sqrt()</code> with <code>tf.math.sqrt()</code></p>
python|numpy|keras
0
10,142
67,947,409
Want to scrape all the specific href from the a tag
<p>I have search the specific brand Samsung , for this number of products are search ,I just wanted to scrape all the href from the of the search products with the product name .</p> <pre><code>enter code here import urllib.request from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.su...
<p>Couple of things. You are trying to mix bs4 syntax with selenium which is causing your current error. Additionally, you are targeting potentially dynamic values. Finally, there are anti-scraping measures which may later impact on your work.</p> <p>Ignoring the last, a more robust, syntax appropriate version, might b...
python|pandas|selenium|beautifulsoup
0
10,143
31,721,404
Evaluating Python lambda function with numpys np.fromfunction
<p>Let A1 and A2 be numpy arrays of the same shape, say ((d1,d2)). I want to build ((d1,d1)) array from it such that its [i,j]th entry is defined by applying a function to the tuple A1[i],A2[j]. I use np.fromfunction in the form</p> <pre><code>f=lambda i,j: np.inner(A1[i],A2[j]) A=np.fromfunction(f, shape=(d1, d1)) <...
<p>To debug the situation, make <code>f</code> a proper function and add a print statement to see the value of <code>i</code> and <code>j</code>:</p> <pre><code>import numpy as np np.random.seed(2015) d1, d2 = 5, 3 A1 = np.random.random((d1,d2)) A2 = np.random.random((d1,d2)) def f(i, j): print(i, j) return np...
python|numpy|matrix|multidimensional-array
7
10,144
41,298,239
one-hot encoding single sample pandas
<p><strong>Problem statement:</strong> I want to one-hot encode this single sample:</p> <pre><code>In [2]: single_sample = pd.DataFrame({"Color":['Green']}) Color 0 'Green' </code></pre> <p>with the same one-hot encoding used for this dataframe:</p> <pre><code>In [3]: df = pd.DataFrame({...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> of columns by columns of <code>df1</code>:</p> <pre><code>df1 = pd.get_dummies(df) print (df1) Color_Blue Color_Green Color_Orange Color_Red 0 ...
python|pandas|encoding
3
10,145
41,534,717
Conditional selection before certain time of day - Pandas dataframe
<p><a href="https://i.stack.imgur.com/3uJA1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3uJA1.png" alt="enter image description here"></a></p> <p>I have the above dataframe (snippet) and want create a new dataframe which is a conditional selection where I keep only the rows that are timestamped ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow noreferrer"><code>DataFrame.between_time</code></a>:</p> <pre><code>start = pd.to_datetime('2015-02-24 11:00') rng = pd.date_range(start, periods=10, freq='14h') df = pd.DataFrame({'Date': r...
python|pandas
3
10,146
41,432,568
show multiple image in matplotlib from numpy array
<p>I have an array with the shape (1, 64, 224, 224). 64 Single channel images of size 224*224. When I do this:</p> <pre><code>plt.imshow(output_image[0,1,:,:], interpolation='nearest') </code></pre> <p>The image is displayed properly.</p> <p>But when I do:</p> <pre><code>for i in range(64): plt.imshow(output_im...
<p>You can create a new subplot for each image:</p> <pre><code>fig = plt.figure(figsize=(50, 50)) # width, height in inches for i in range(64): sub = fig.add_subplot(64, 1, i + 1) sub.imshow(output_image[0,i,:,:], interpolation='nearest') </code></pre> <p>This will put all 64 images in one column. Change to...
python|numpy|matplotlib
9
10,147
41,645,571
changing number of outputs/classes in tensorflow
<p>Here is my simple logistic regression with two features and two classes:</p> <pre><code>tf.reset_default_graph() x = tf.placeholder(tf.float32, (None, 2)) y = tf.placeholder(tf.int32, (None,)) w = tf.Variable(tf.truncated_normal(shape=(2, 2))) p = tf.matmul(x, w) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_ent...
<p>You should not change the number of classes while training. If that happens, you have to create a new model for the given classes and re-train from it.</p>
tensorflow
0
10,148
61,435,564
Finding whether there's any differences in rows grouped by two columns
<p>Suppose I have a dataframe like below</p> <pre><code>id date email phone country john 2020-01-02 10:09:00.11 john@email 123 USA john 2020-01-02 10:09:00.11 john@email 456 USA john 2020-01-02 10:09:00.11 john@email 1...
<p>let us use <code>df.duplicated</code> with <code>keep=False</code> to mark all duplicates.</p> <pre><code>df['diff'] = df.duplicated(subset=['id','date','email'],keep=False) print(df) id date email phone country diff 0 john 2020-01-02 10:09:00.110 john@email 123 USA Tr...
python|pandas|dataframe|pandas-groupby
1
10,149
61,430,159
Not able to load a csv file using pandas pd.read_csv, multiple errors
<p>I am quite new into the python programing / data scientist world. I use Pycharm and MacOs. For learning purposes I have downloaded some CSV files from Kaggle and I am always able to load them OK into Pycharm. But actually I not able to load a csv file from my work environment, surprisingly, I can load the file using...
<p>I am not very sure but try removing spaces from your folders like 'SNOW raw data' and run again. Also is 'SNOW PTP last year tickets_csv' your file name or just 'tickets_csv'? Always try avoiding spaces in folders and files. </p>
pandas|csv|pycharm
0
10,150
61,244,876
Adding row shifting in pandas dataframe
<p>I have a pandas <code>df</code>, which I created by using <code>shift()</code> function iterating through the original <code>df</code>:</p> <pre><code>for i in range(2, 4): df["lag_{}".format(i)] = df.x.shift(i) </code></pre> <p>So there will be actual <code>x</code> column and <code>lag2-lag10</code> columns ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>DataFrame.append</code></a> with dictionary with key <code>x</code>:</p> <pre><code>df = pd.DataFrame({'x':range(10)}) df1 = df.append({'x':np.nan}, ignore_index=True) #alternative #...
python|pandas|time-series
1
10,151
68,489,441
How to build key drivers analysis of Nps in python?
<p>I have a dataframe like this(columns are a 10 point scale)</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>NPS product</th> <th>time</th> <th>quality</th> <th>comfort</th> </tr> </thead> <tbody> <tr> <td>8</td> <td>6</td> <td>7</td> <td>8</td> </tr> <tr> <td>6</td> <td>4</td> <td>3</td> ...
<p>for regression your feature set or independent variables has to be at least interval scaled which means the differences in the data points has to be meaningful. In your case all the data points are in ordinal scale i.e. order is meaningful but differences are not. You can try Spearman’s Rank Correlation for ordinal ...
python|pandas|scikit-learn|statistics|regression
1
10,152
68,686,075
networkX.draw() not producing edges
<p>I'm not sure why my network graph doesn't include edges.</p> <p>I'm creating a network from a pandas dataframe that looks like the following:</p> <p><a href="https://i.stack.imgur.com/vojQx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vojQx.png" alt="enter image description here" /></a></p> <p>...
<p>That central &quot;blob&quot; in your plot is a lot of nodes connected together which probably do have edges, but they are obscured by the dense mass of nodes. On the periphery there are a few nodes joined together by edges, but due to the plotting algorithm they pairs (or somewhat larger cluster) are again so clos...
python|pandas|networkx
3
10,153
68,734,050
seaborn: 'rows' and 'x_vars' at the same time
<p>I want a seaborn multiplot that varies the x-axis variable by column, but varies the subset of data shown by row. I can use PairGrid to vary the variables graphed, and I can use FacetGrid to vary the subsets graphed, but I don't see any facility to do both at once, even though it seems like a natural extension.</p> ...
<p>This is not a feature that directly exists in seaborn (though it is likely to become one at some point).</p> <p>That said, FacetGrid and PairGrid just instantiate different mappings between a dataframe and a figure (modulo the diagonal plots in PairGrid and a few features here and there). So a plot that is naturally...
python|pandas|dataframe|matplotlib|seaborn
3
10,154
36,441,345
2nd Iteration adding extra character in Pandas/Numpy
<p>I am running the code below and it is running fine for the first iteration and when the second iteration starts it gives me a key error. I notice that the there is a string "L" added to the key automatically when the second iteration starts. Link to my code below:</p> <p><a href="https://github.com/amandeepsharma8...
<p>Now, I looked only at your <code>get_numpy_data</code> definition and think that it doesn't work as you'd expect. For example, the line</p> <pre><code>features_train, output_train = get_numpy_data(df_housePrice_train, feature_list, 'price') </code></pre> <p>seems to modify <code>df_housePrice_train</code>. And <co...
python|numpy|pandas
0
10,155
65,539,305
Mnist dataset splitting
<p>can anyone help me out in splitting mnist dataset into training , testing and validation as per our wish of ratios.</p> <pre><code>(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() </code></pre> <p>Use 70-20-10 split for training, validation and testing.</p>
<p>This approach should do it. It basically uses iteratively the <code>train_test_split</code> function from tensorflow to split dataset into validation-test-train:</p> <pre><code>train_ratio = 0.70 validation_ratio = 0.20 test_ratio = 0.10 # train is now 70% of the entire data set # the _junk suffix means that we dro...
tensorflow|machine-learning|keras|training-data|mnist
1
10,156
65,879,536
how to replace a word in a column with NaN in pandas
<p>Supposed I have a column called &quot;quantity&quot;;</p> <pre><code>Quantity 1 2 3 Plan 3 2 </code></pre> <p>and I want to replace the string <code>Plan</code> as NaN, how can I do that in pandas?</p> <p>thankyou</p>
<p>If need replace all non numeric values to NaNs and also if necessary convert values to numeric use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> with <code>errors='coerce'</code>:</p> <pre><code>df['Quantity'] = pd.to_...
python|pandas
1
10,157
65,762,538
How can we group by and sum based on headers? So Horizontal, not Vertical, Group By and Sum
<p>I have this data frame.</p> <pre><code> 2001Q1 2001Q2 2001Q3 2001Q4 2002Q1 2002Q2 ... 2011Q2 \ RCFD3531 0 1 2 3 4 5 ... 14481 RCFD3532 0 0 0 0 0 0 ... 0 RCFD3533 0 0 0 ...
<pre><code>df.stack().reset_index().groupby('level_1')[0].agg('sum') </code></pre> <p>Something like this.</p>
python|python-3.x|pandas|pandas-groupby
1
10,158
65,587,811
How to apply CountVectorizer to a column of a dataset?
<p>I have been able to use the CountVectorizer in single text strings and all but I have a dataset that has 80.000 length. How can I apply CountVectorizer to everything in a single column? I have tried the following:</p> <pre><code>count_vect = CountVectorizer(lowercase=False) cv = count_vect.fit_transform(df['Tokenize...
<p>Thank you, everyone, for your time. Turns out this will do the trick:</p> <pre><code>df['Vectorized'] = 'default value' vectorizer = CountVectorizer() for i in range(0,len(df): vectorizer.fit_transform(df['Tokenized_Review'][i]) df['Vectorized'][i] = vectorizer.vocabulary_ </code></pre>
pandas|sklearn-pandas
0
10,159
63,605,242
Filter df by list of allowable combinations of column values
<p>Say I have a dataframe with like this:</p> <pre><code> Animal Color 0 Dog White 1 Cat Black 2 Dog Black 3 Dog Brown 4 Rabbit Brown </code></pre> <p>And I want to get all indices which match these tuples: <code>[('Cat', 'Black'), ('Dog', 'Brown')]</code>. So that would be <code>[1,3]</code> i...
<p>Here is a way with the pandas MultiIndex. I changed the example to have a red dog:</p> <pre><code>from io import StringIO import pandas as pd data = ''' Animal Color 0 Dog White 1 Cat Black 2 Dog Red 3 Dog Brown 4 Rabbit Brown ''' df = pd.read_csv(StringIO(data), sep='\s+', engine='python'...
python|pandas
2
10,160
63,348,110
<tensorflow.python.keras.callbacks.History at 0x279ceba2288>
<p>I build the following DL model based on Tensorflow/Keras but it raises the following error</p> <pre class="lang-py prettyprint-override"><code> model = keras.Sequential() model.add(layers.Dense(263, input_dim=263, activation='relu')) model.add(layers.Dense(256, activation='relu',kernel_regularizer=regular...
<p>I can be mistaken, but afaik keras.callbacks.history is just an output object from your fitting, so you can somehow use one specific 'fit' if you initialize your model multiple time</p>
python|python-3.x|python-2.7|tensorflow|keras
0
10,161
63,601,881
Select the maximum value after eliminating a selected value
<p>I have a large data set (300 millions rows) and I need an efficient (or fast) algorithm that will do the job. So here are few rows of dataset.</p> <pre><code>db = pd.DataFrame({'A': [2,3,4,5], 'T': [1,2,6,7], 'G': [8, 1, 4, 6], 'C': [1,1 , 3, 4], 'basecall' : ['G', 'A', 'G', 'T']}) </code></pre> <p...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.lookup.html" rel="nofollow noreferrer"><code>DataFrame.lookup</code></a> to lookup the values based on columns in <code>db['basecall']</code>, then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.D...
python|pandas|dataframe
4
10,162
21,531,759
Plot with python
<p>Hello i know that this way to plot in matlab works:</p> <pre><code>subplot(2,2,[1, 2]) plot(Tabsauv(:, 2:2:2*Ntracks), Tabsauv(:, 3:2:(2*Ntracks+1)),couleur,'LineWidth',2, 'MarkerSize', 2) grid('on') hold on </code></pre> <p>When Tabasauv is a table of values.</p> <p>I'm a new beginner in python, I tried to plot ...
<p>In matlab, you can generate arrays with ":". In python, you can create arrays using range() function or using arange (in numpy) </p> <p>so, </p> <pre><code> a = 3:5 </code></pre> <p>in matlab is just the same as </p> <pre><code>a = np.arange(3,5) #or a = np.array(range(3,5)) </code></pre> <p>in Python. </p> ...
python|matlab|numpy|matplotlib
2
10,163
20,339,934
Python_How to write data in new columns for every file read by numpy?
<p>I have several text files with such a construction. Same number of columns but different rows:</p> <pre><code>1.txt 2013-08-29T15:11:18.55912 0.019494552 0.110042184 0.164076427 0.587849877 2013-08-29T15:11:18.65912 0.036270974 0.097213155 0.122628797 0.556928624 2013-08-29T15:11:18.75912 0.055350041 0.104121...
<p>Will this work for you?</p> <pre><code>import pandas as pd df = pd.DataFrame() mad = lambda x: x[0] + x.mean() A = [] for f in ['1.txt', '2.txt']: tmp = pd.read_csv(f, header=None, delim_whitespace=True) tmp = tmp.ix[:,1:5] df = pd.concat([df, pd.rolling_apply(tmp, 3, mad)], axis=1) df.to_csv('test....
python|csv|numpy|multiple-columns
0
10,164
20,010,539
Array slicing with data that contains multiple types
<p>I read in the following object with <code>numpy.genfromtxt</code>:</p> <pre><code>A = [(4, 'A', 3750.5), (4, 'B', 3252.6), (8, 'A', 3350.5), (8, 'B', 3152.6)] </code></pre> <p>I would like to do numpy fancy indexing on it, but I can't because this is not an numpy array. It's an array of a list.</p...
<pre><code>In [24]: A_array = numpy.asarray(A, dtype=object) In [25]: A_array[A_array[:,0] == 4] Out[25]: array([[4, A, 3750.5], [4, B, 3252.6]], dtype=object) </code></pre> <p>If the columns of data have semantic meaning that you'd like to keep track of, consider loading the list of tuples directly into a <a ...
python|arrays|numpy
4
10,165
71,802,673
Merge column values as a list in DataFrames based on a condition
<p>I have a DataFrame like</p> <pre><code>| Item | Match | Score | | ---- | ----- | ----- | | A | B | 0.9 | | A | C | 0.8 | | A | D | 0.7 | | A | E | 0.6 | | B | A | 0.9 | | B | X | 0.7 | | C | Y | 0.45 | | C | Z | 0.4 | </code></pre> <p>I want to c...
<p>We can do two <code>groupby</code> , 1st get the top 3 line , 2nd get the <code>agg</code> format</p> <pre><code>out = df.sort_values('Score',ascending=False).\ groupby('Item').head(3).\ groupby('Item').\ agg(MatchList = ('Match', list), ScoreLis...
python|pandas|dataframe|merge
3
10,166
71,920,732
How do i convert 3D list in python to csv file?
<p>I have a 3D list like</p> <pre><code>final_arr = [[[1,2,3,4],2],[[1,1,2,2],3],[[1,2,2],4]] </code></pre> <p>Now I want to convert each row into csv column, like for first list item the columns should be <code>1 2 3 4 2</code> in csv single row and multiple columns.</p> <p>Right now I am doing this but the whole list...
<p>Is objective something like this:</p> <pre class="lang-py prettyprint-override"><code>final_arr = [[[1,2,3,4],2],[[1,1,2,2],3],[[1,2,2],4]] with open('out1.csv', 'w') as f: for (i, j) in final_arr: print(*i, j, file=f) # out1.csv 1 2 3 4 2 1 1 2 2 3 1 2 2 4 </code></pre> <p>EDIT: as suggested by @jua...
python|pandas|csv
2
10,167
71,992,045
pandas : appending columns to df that is prat of another df
<p>I have 2 pandas DataFrames:</p> <p>df1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>c1</th> <th>c2</th> <th>x</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>2</td> <td>1</td> <td>4</td> </tr> <tr> <td>1</td> <td>2</td> <td>1</td> </tr> <tr> <td>2</td...
<p>Perhaps the simplest way to do what your question asks is this:</p> <pre class="lang-py prettyprint-override"><code>df2 = pd.merge(df2, df1, on=['c1', 'c2']) </code></pre> <p>We have done an 'inner' join (the default for pandas.merge()) on columns <code>c1</code> and <code>c2</code> of dataframes df1 and df2.</p> <p...
python|pandas|dataframe|join
0
10,168
4,286,544
Write lines longer than 80 chars in output file [Python]
<p>I've got a pretty basic question. I'm using Python to calculate an n×12 vector</p> <pre><code>y = numpy.array([V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12]) </code></pre> <p>which I append after each loop calculation.</p> <p>My problem is that when I try to save it to a file or print it Python automatically breaks the...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="noreferrer"><code>numpy.savetxt()</code></a> to save an array to a text file while controlling the formatting. To print it to the screen, you have different options to control the linewidth. One would be to call</p> ...
python|file-io|numpy
24
10,169
8,376,609
Prevent anti-aliasing for imshow in matplotlib
<p>When I use matplotlib's imshow() method to represent a small numpy matrix, it ends up doing some smoothing between pixels. Is there any way to disables this? It makes my figure's misleading in presentations.<img src="https://i.stack.imgur.com/fg5ay.png" alt="A 28x28 matrix plotted with imshow()"></p> <p>The figur...
<p>There is an interpolation option for <code>imshow</code> which controls how and if interpolation will be applied to the rendering of the matrix. If you try</p> <pre><code>imshow(array, interpolation="nearest") </code></pre> <p>you might get something more like you want. As an example</p> <pre><code>A=10*np.eye(1...
python|numpy|matplotlib|scipy|blurry
55
10,170
8,475,498
looping through the rows of a matrix in sage
<p>I am trying to program a Graham-Schmidt process in sage and cannot figure out how to loop through the rows of an array.</p> <pre><code>def graham_schmidt(W): a=0 U=W for i in W.dims()[0]:# this is the not working part print w a=a+1 for j in xrange(0,-2): a=a+1 ...
<p>You're making things far too complicated. If <code>W</code> is not a sparse matrix, you can just do</p> <pre><code>for row in W: </code></pre> <p>Since you also need the row index, you can use Python's built-in <code>enumerate</code>:</p> <pre><code>for i, row in enumerate(W): </code></pre> <p>or (uglier)</p> <...
python|matrix|numpy|sage
5
10,171
55,310,328
Truth Value of a Series Ambiguous when using While loop
<p>This question has certainly been asked in many forms before, however, I haven't been able to find one that incorporates multiple series inputs as well as a while loop. Hence my question: </p> <p><strong>Without the need for a for-loop ahead of the while loop, is it possible to output a series from this function:</s...
<p>You are comparing a series with scalar value. combine is a series while 100 is a numeric value. </p> <p>You can convert series into dataframe and pass into the function.</p> <pre><code>def modify_to_100(df): df['new'] = df['first'] + df['second'] # df['new'] = np.where(df['new']!=100, 100, df['new']) ...
python|pandas|dataframe
2
10,172
55,238,367
One Hot Encoding Single Categorical Numerical Column
<p>I´m looking to encode a categorical numerical column. I´m seeing a lot of encoding from string-type categorical columns, but not when already transform in numerical.</p> <p>My goal is to convert this pandas dataframe:</p> <pre><code>+---------+ |year|hour| |2018|1| |2018|3| |2019|4| |2019|4| +------+ </code></pre>...
<p>You need <code>pd.get_dummies</code></p> <pre><code>df = pd.DataFrame({'year':[2018,2018,2019,2019], 'hour':[1,3,4,4]}) print(pd.get_dummies(df, columns=['year','hour'], drop_first=False)) </code></pre> <p>Output:</p> <pre><code> year_2018 year_2019 hour_1 hour_3 hour_4 ...
python|pandas|vectorization|one-hot-encoding
0
10,173
56,714,623
zip list elements in different dataframe columns
<pre><code>a=[['1','2'],['3','4']] b=[['5','6'],['7','8']] df14=pd.DataFrame({'key':a,'hi':b}) </code></pre> <p>i want to add a 3rd column with tuples, where each list element from 'key' is matched with its list index in 'hi' -> e.g. that it looks like this.</p> <pre><code> key hi tup 0 [1, 2] [5, 6]...
<p>Here <code>iterrows</code> is not necessary, second row is modify for apply lambda function per row by <code>axis=1</code> and changed <code>d14.hi</code> for <code>x.hi</code> for return values per row of <code>hi</code> column:</p> <pre><code>df14['tup'] = df14.apply(lambda x: list(zip(x.key,x.hi)), axis=1) print...
python|pandas|list|zip|tuples
9
10,174
26,103,729
Pandas plot subplots of a 'group by' result
<p>I struggle with my (poor) Pandas knowledge, as I try to get a bar plot on a hierachial index by a group by operation.</p> <p>My data look like this</p> <pre><code>id, val, cat1, cat2 </code></pre> <p>Then I create a hierachical index:</p> <pre><code>df_group = df_len.groupby(['cat1','cat2']) </code></pre> <p>I ...
<p>Ok guys, so here it's how I solved it finally:</p> <pre><code>dfc = df_len.groupby(['cat1','cat2']).count().reset_index() dfp=dfc.pivot(index="cat1",columns="cat2") dfp.columns = dfp.columns.get_level_values(1) dfp.plot(kind='bar', figsize=(15, 5), stacked=True); </code></pre> <p>In short: I used a pivot table to ...
python|numpy|matplotlib|pandas
2
10,175
26,169,335
numpy efficient array multiplication
<p>I have a three dimensional array img of shape [1200,1600,3] and a two dimensional array labels of shape [1200,1600]. The first array is from an image, the second one is from labels in the image. Location [i,j] in the img array corresponds to an image pixel. I want to create a new array of the same dimension as the ...
<p>Generally speaking, you'd do something similar to:</p> <pre><code>newimg = img.copy() newimg[labels != 0, :] = 255 </code></pre> <p>or alternatively:</p> <pre><code>newimg = np.where(labels[..., None] != 0, img, 255) </code></pre>
python|arrays|image-processing|numpy
3
10,176
26,379,631
Numpy Type (In)consistency?
<p>In Numpy I tried the following. I suspect that this is not a bug. In case it is a feature, I do not understand it. Can somebody explain this? Thanks.</p> <pre><code>&gt;&gt;&gt; np.array([173], dtype = np.uint8) * [360] array([62280]) &gt;&gt;&gt; np.array([173], dtype = np.uint8) * 360 array([-3256], dtype=int16) ...
<p>The difference between these outputs is probably is caused by a bug in your numpy version. </p> <p>The code</p> <pre><code>np.array([173], dtype = np.uint8) * [360] </code></pre> <p>is shorthand for:</p> <pre><code>np.array([173], dtype = np.uint8) * np.array([360]) # output array([62280]) </code></pre> <p>And ...
python|numpy
1
10,177
66,920,458
How merge 2 dataframe
<p>I have a 2 pandas dataframe which looks like this:</p> <pre><code> A0 B0 C0 A1 B1 C1 A2 B2 C2 A3 B3 C3 </code></pre> <p>and</p> <pre><code> A2 D0 E0 A0 D1 E1 A3 D2 E2 A1 D3 E3 </code></pre> <p>How make this:</p> <pre><code>A0 B0 C0 D1 E1 A1 B1 C1 D3 E3 A2 B2 C2 D0 E0 A3 B3 C3 D2 E2 </code></pre>
<p>You are looking for <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a></p> <pre><code>df1 = pd.DataFrame( [['A0', 'B0', 'C0'], ['A1', 'B1', 'C1'], ['A2', 'B2', 'C2'], ['A3', 'B3', 'C3']]) df1.columns = ['c1', 'c2',...
python|pandas|dataframe|merge
1
10,178
66,936,330
I have a list of df resulting by groupby and I need to add a new column with the frequency of kmers
<p>I have a list of pandas data frames that I got applying the groupby function and I want to add to them a new column with the frequency of each kmer. I did that with a loop but I got a message warning that I need to use df.loc[index, col_names]. Here it is a link to one example of the csv file: <a href="https://drive...
<p>It's an error related SettingWithCopyWarning. It's important — read up on it <a href="https://www.dataquest.io/blog/settingwithcopywarning/" rel="nofollow noreferrer">here</a>. Usually you can avoid it with <code>.loc</code> and by avoiding repeat-slicing, but in some cases where you have to slice repeatedly you can...
pandas|pandas-groupby
1
10,179
66,984,387
How to reshape the specific columns of data table using pandas?
<p>I was working on reshaping the table, found out it's more complicated than I thought.</p> <p>The original data is</p> <pre><code> |----- Category 1----------------|----- Category 2-----------------| Date ID Cycle Type 1 Type 2 Type 3 Type 4 Type 1 Type 2 Typ...
<p>As you have more columns than just <code>Cycle</code> and <code>Type</code> you can not simply use transpose but need to stack <code>Type</code> and pivot <code>Cycle</code>. Additionally it gets more complicated because you have a hierarchical index with <code>Category</code> (two lines with indices are hierarchic...
python|pandas|dataframe|pivot-table
0
10,180
47,315,659
Using numba for cosine similarity between a vector and rows in a matix
<p>Found this <a href="https://gist.github.com/FedericoV/0e7d6d8c8794a99a7a42" rel="nofollow noreferrer">gist</a> using numba for fast computation of cosine similarity.</p> <pre><code>import numba @numba.jit(target='cpu', nopython=True) def fast_cosine(u, v): m = u.shape[0] udotv = 0 u_norm = 0 v_norm...
<p>Solution rewriting it a bit:</p> <pre><code>import numpy as np import numba @numba.jit(target='cpu', nopython=True, parallel=True) def fast_cosine_matrix(u, M): scores = np.zeros(M.shape[0]) for i in numba.prange(M.shape[0]): v = M[i] m = u.shape[0] udotv = 0 u_norm = 0 ...
python|numpy|vector|numba|numba-pro
3
10,181
59,433,274
Pandas DataFrame: Substract one row to another taking into account index(name and date)
<p>Hi I have a python pandas Dataframe where I would like to see the changes between the latest 2 dates (when available) for a 3 indexed columns (phonetype, memory and brand). The dataframe looks like this:</p> <p>"""</p> <p><a href="https://i.stack.imgur.com/2F1W0.png" rel="nofollow noreferrer"><img src="https://i.s...
<p>you can try this: </p> <p><strong>First</strong>, change the date columns to type of <code>datetime</code> for to find the latest date. </p> <pre class="lang-py prettyprint-override"><code>df['position_date'] = pd.to_datetime(df['position_date'], format='%d/%m/%Y') print(df.head(10)) </code></pre> <pre><code> ...
python-3.x|pandas|dataframe
0
10,182
59,329,902
How can I fill a numpy array with empty builtin lists?
<p>I'm filling a numpy grid with lists of unknown size because <code>list.append</code> is better to use than <code>np.concatenate</code> (perhaps I'm optimizing prematurely, though).</p> <p>These don't work:</p> <pre><code>foo = np.full((3, 4), []) bar = np.full((3, 4), [], dtype=object) </code></pre> <p>Numpy ju...
<p><code>full</code> with a mutable object, even when it works has problems:</p> <pre><code>In [10]: A = np.full(3,{}) In [11]: A Out[11]: array([{}, {}, {}], dtype=object) In [12]: A[0]['k']=2 ...
python|numpy
2
10,183
45,266,224
Apply on non-grouped dataframe?
<p>Trying to implement a simple func that marks one group as <code>True</code>, at random</p> <p><strong>Dataframe:</strong></p> <pre><code>In [145]: df = pd.DataFrame({'a': [1,1,1,2,2], 'b': [3,3,3,3,3]}) In [146]: df Out[146]: a b 0 1 3 1 1 3 2 1 3 3 2 3 4 2 3 </code></pre> <p><strong>Function:</str...
<p><code>df</code> is a DataFrame, while <code>df.groupby(...)</code> is a <code>DataFrameGroupBy</code> object. <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stab...
python|pandas
2
10,184
45,099,375
tensorflow multi-gpu mnist example, loss does not decrease
<p>I'm trying to write my own mnist example which could use all the two gpu of one machine.</p> <p>It is a simple multi-layer perceptron.</p> <p>Here is my code. You can run it directly.</p> <pre><code>from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=...
<p>The problem is that,</p> <p>I should use <code>tf.constant_initializer(0.1)</code> for the <code>weights</code> instead of <code>tf.constant_initializer(0)</code> </p>
python|machine-learning|tensorflow|deep-learning|mnist
0
10,185
45,255,422
How to find the next Max Value in an array
<p>I want to find the next max value after getting the first Max value in the same array for the following:</p> <pre><code> Open High Low Close Volume Date 2017-07-03 370.24 371.35 351.50 352.62 6305401 2017-07-05 347.20 347.24 326.33 32...
<p>You can write a code like this:</p> <pre><code>a = np.array([10, 18, 20, 8, 15]) arg_max = a.argsort()[-2:][::-1] highest_1 = a[arg_max[0]] #20 highest_2 = a[arg_max[1]] #18 </code></pre>
python|pandas|numpy|dataframe|quantitative-finance
1
10,186
56,878,707
how would I calculate the L2 or euclidean distance between rows of different 2D vectors
<p>I've been given 2 different 2D arrays and I'm asked to calculate the L2 distance between the rows of array x and the rows in array y. The shape of array x is (M, D) and the shape of array y is (N, D). The final answer array should have the shape (M, N).</p> <p>I'm not very good at python. I'm really just doing rand...
<p>I like this one since it works for 1, 2 and 3D arrays</p> <pre><code>def e_dist(a, b, metric='euclidean'): """Distance calculation for 1D, 2D and 3D points using einsum preprocessing : use `_view_`, `_new_view_` or `_reshape_` with structured/recarrays Parameters ---------- a, b : arra...
python|arrays|numpy|machine-learning
1
10,187
57,077,024
How do you create rows for every categories in a column?
<p>Say that I have the following data. Like how many times my kids opened the fridge for each hour from 1 PM to 3 PM.</p> <pre><code>| ----- | ----- | ----- | | Name | Hour | Open | | ----- | ----- | ----- | | Bob | 1 | 4 | | ----- | ----- | ----- | | Bob | 3 | 2 | | ----- | ----- | ----- | | J...
<p>Idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> by all possible combinations created by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.from_product.html" re...
python|pandas|dataframe
4
10,188
57,046,100
Pandas match with a dict between two columns and create a new column
<p>I have a df1/dic like below:</p> <pre><code>Station_to Station_from Distance_km A AA 1.1 A BB 2.2 A CC 3.3 B AA 4.4 ... </code></pre> <p>a df2 like below:</p> <pre><code>Origin Destinatio...
<p>One way to do this would be to use pd.merge operation but it would create a new dataframe so you might want to delete the previous one. If df1 and df2 are two dataframes then:</p> <pre class="lang-py prettyprint-override"><code>df3 = df2.merge(df1, how='right',left_on=['Stationto','Stationfrom'],right_on=['origin',...
python|pandas
0
10,189
45,955,186
Convert numpy array type and values from Float64 to Float32
<p>I am trying to convert threshold array(pickle file of isolation forest from scikit learn) of type from Float64 to Float32 </p> <pre><code>for i in range(len(tree.tree_.threshold)): tree.tree_.threshold[i] = tree.tree_.threshold[i].astype(np.float32) </code></pre> <p>​ Then Printing it</p> <pre><code>for value...
<p>The problem is that you do not do any type conversion of the numpy array. You calculate a float32 variable and put it as an entry into a float64 numpy array. numpy then converts it properly back to float64</p> <p>Try someting like this:</p> <pre><code>a = np.zeros(4,dtype="float64") print a.dtype print type(a[0])...
python|numpy|scikit-learn|pickle
40
10,190
35,463,348
Summing values of a pandas data frame given a list of columns
<p>Given a dataframe as follows:</p> <pre><code>x1 x2 x3 x4 x5 x6 1 2 3 4 5 6 3 4 5 6 3 3 1 2 3 6 1 2 </code></pre> <p>How could i create a new columns of 'sum' that just adds x1 + x3 + x4</p> <pre><code>x1 x2 x3 x4 x5 x6 1 2 3 4 5 6 3 4 5 6 3 3 1 2 3 6 1 2 </code></pre> <p>In my act...
<p>You can use subset of <code>df</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a>:</p> <pre><code>print df x1 x2 x3 x4 x5 x6 0 1 2 3 4 5 6 1 3 4 5 6 3 3 2 1 2 3 6 1 2 print df[['x1', 'x...
python|pandas|data-analysis
3
10,191
28,837,123
pyplot Reverse x axis and reverse table subplot
<p>When I reverse the x axis in pyplot the accompanying table does not get effected. How can i reverse the display of the table elements?</p> <pre><code>ax=ep.plot(kind='bar',table=True).invert_xaxis() </code></pre> <p><img src="https://i.stack.imgur.com/qAIRj.png" alt="enter image description here"></p>
<p>This is how I would do it ...</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt # get the data ... note the order ... data = [4.77, 5.52, 5.93, 6.29, 6.0, 6.95, 7.7, 9.44, 10.94, 12.35, 13.45] df = pd.DataFrame({'data':data}) # referse the dataframe df = df[::-1] # ... and plot ... ax = df.plot...
pandas|matplotlib|reverse
3
10,192
20,818,117
Specifying Elements In A Numpy Array
<p>I would like to create the numpy array which takes on the values in the range [0,10], with divisions between each element 0.1. How might I go about doing this? Hopefully my request is clear enough.</p>
<p>In addition to @agconti answer, you can use what is called a <strong>linspace</strong>:</p> <p><strong>Code:</strong></p> <pre><code>import numpy a = numpy.linspace(0, 10, num = 101) # num -&gt; number of elements print a </code></pre> <p><strong>Output:</strong></p> <pre><code>[ 0. 0.1 0.2 0.3 0.4 ...
python-2.7|numpy|spyder
3
10,193
20,439,460
issue using r function with rpy2
<p>When I do </p> <pre><code>from rpy2.robjects import IntVector, Formula from rpy2 import robjects rr = Formula('gr_bmr~nationalite_france') myparams = {'family': 'binomial'} formula=robjects.r('gr_bmr~nationalite_simple') robjects.r['glm'](rr,data=bdd1,**myparams) </code></pre> <p>I have this error: Erre...
<p>In you R code, <code>binomial</code> is a function while in your Python code it is a string. Try:</p> <pre><code>from rpy2.robjects import Formula from rpy2.robjects.packages import importr rr = Formula('gr_bmr~nationalite_france') stats = importr('stats') myparams = {'family': stats.binomial} stats.glm(rr,data=bdd...
python-2.7|pandas|rpy2
0
10,194
33,244,276
Retrieving data by a MultiIndex
<p>I have a dataframe that contains a multiindex. I need to work with various subsets of the data based on schema and/or script (the indexes are <code>schema</code> and <code>script</code>). The dataframe looks like this: </p> <pre><code> tx_id step step_id start_time ...
<p>Your second statement <code>df.index.levels</code> gets all levels in your index. You then subset it by saying, give me all the levels in the second multiindex (called 'script').</p> <p>What I think you want is something like this, where you say, for the index named 'script', give me a <em>particular</em> value.</p...
pandas
0
10,195
33,087,678
Reordering numpy array indices
<p>I have a 2D array that I want to create an image from. I want to transform the <code>image</code> array of dimensions 140x120 to an array of 140x120x3 by stacking the same array 3 times (to get a grayscale image to use with skimage).</p> <p>I tried the following:</p> <pre><code>image = np.uint8([image, image, imag...
<p><code>np.dstack([image, image, image])</code> (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html" rel="nofollow">docs</a>) will return an array of the desired shape, but whether this has the right semantics for your application depends on your image generation library.</p>
python|arrays|image|numpy
1
10,196
33,067,012
How to merge two tables in pandas, KeyError: 'timestamp,city'
<p>I cant join 2 data frames:</p> <pre><code>df = pandas.merge(df_a,df_b, on=['timestamp,city'], how='right') cola city impression timestamp 0 San Francisco 6 2015-10-11T08:00:00.000Z 1 San Francisco 14 2015-10-11T09:00:00.000Z 2 None 2 2015-10-...
<p>You are not separating the columns correctly, the <code>on</code> argument should be like this:</p> <pre><code>on = ['timestamp', 'city'] </code></pre> <p>The way you are executing this, results in it searching for a column named: <code>timestamp,city</code>, which, since it obviously doesn't exist, results in a ...
python|pandas
1
10,197
66,608,283
Change google sheets API call to batch
<p>Working with google(and all) api calls for the first time, I'm continually hitting a rate limit threshold despite having limited my rate. How would I go about changing the following code to a batch format to avoid this?</p> <pre><code>#API Call Function from ratelimit import limits, sleep_and_retry import requests f...
<p>Thanks to Tanaike's suggestion, I settled on the following solution. There's still remaining issues that I haven't resolved. Namely, the resultant API calls occured at a rate of .5/second, well below the published limit, but any faster would still result in rate limiting issues. Additionally, the code completed afte...
python|pandas|google-sheets|google-api
0
10,198
57,348,091
predict exponential weighted average using a simple rnn
<p>In an attempt to further explore the keras-tf RNN capabilities and different parameters, i decided to solve a toy problem as described - </p> <ol> <li>build a source data set composed of a sequence of random numbers</li> <li>build a "labels" data set comprised of the <a href="https://en.wikipedia.org/wiki/Moving_av...
<p>The code for replicating the behavior of the toy neural network in keras is shown below:</p> <pre><code>from tensorflow import keras import numpy as np from tensorflow.keras.models import Sequential as Sequential np.random.seed(1337) # for reproducibility def run_avg(signal, alpha=0.2): avg_signal = [] a...
tensorflow|keras|deep-learning|recurrent-neural-network
1
10,199
57,528,989
How to include first/last dates in matplotlib plot
<p>I have a time series plot I am drawing using matplotlib in a jupyter notebook. </p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt from numpy.polynomial import polynomial as P from datetime import date </code></pre> <p>First, I create the initial plot and describ...
<p>When I checked the value of <code>ax.get_xticks()</code> I noticed that the min/max values of <code>x</code> were <strong>not included</strong>. So it is no wonder they were not showing up. To get this working I just had to recreate an array of ordinals that include the min/max values of <code>x</code> using <code>n...
python-3.x|numpy|matplotlib|plot
-1