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
352,200
49,048,537
Python: How can I fix my drawn "random" values s.t. function calls are consistent?
<p>I have:</p> <pre><code>np.random.seed(123) var_v = 0.007 ** 2 T = 100 rho = 0.9 def v_t(var_v, T): v_t_ = np.zeros([T,1]) v_t_[1:T] = (var_v ** 0.5) * np.random.randn(len(v_t_) - 1, 1) return v_t_ def s_t(rho, T): v_t_ = v_t(var_v, T) s_t_ = np.zeros([T,1]) s_t_[0] = 0 for t in range...
<p>You need to set the seed every time that you draw random numbers if you want to ensure consistency. The following small example will illustrate:</p> <pre><code>np.random.seed(123) np.random.randn(4, 1) np.random.randn(4, 1) </code></pre> <p>Outputs are different:</p> <pre><code>array([[-1.0856306 ], [ 0.99...
python|function|numpy|random
1
352,201
49,105,196
Why am i getting the TypeError?
<p>Sorry before hand if this is a silly question, but I tried to figure out and unable to get it through</p> <p>I have a dictionary named data of pandas dataframe, where <strong>data['class_size']</strong> has the following data</p> <pre><code>CSD SCHOOL CODE SCHOOL NAME 1 M015 P.S. 015 Roberto C...
<p>Try</p> <pre><code>data['class_size']['padded_csd'] = data["class_size"]["CSD"].apply(lambda x: str(x).zfill(2) if len(str(x)) == 1 else str(x) ) #Update else str(x) </code></pre>
python|pandas|lambda|typeerror
3
352,202
49,223,937
How to merge multiple pandas series to a dataframe, where series have list of values
<p>I want to make a <code>pandas Dataframe</code> with following columns.</p> <pre><code>my_cols = ['chrom', 'len_of_PIs'] </code></pre> <p>and following values inside specific columns:</p> <pre><code>chrom = pd.Series(['chr1', 'chr2', 'chr3']) len_of_PIs = pd.Series([[np.random.randint(15, 59, 86)], ...
<p>I don't believe you need the inner lists in your <code>len_of_PIs</code> series. You may also find it convenient to instantiate your <code>pd.DataFrame</code> from a dictionary. The below produces your desired output.</p> <p>It's generally not good practice to convert numeric data to strings, unless you absolutely ...
python|pandas|dataframe|join|series
2
352,203
49,221,826
Problems with Matrix Multiple Regression
<p>I wanted to implement a multiple regression model and wrote the following code:</p> <pre><code>import numpy as np from sklearn.preprocessing import StandardScaler class MatrixLinearRegression: def __init__(self): pass def fit(self, X, Y): X_ = np.append(np.ones((X.shape[0],1)), X, axis = 1...
<p>Your custom formula for the coefficient of determination (output of <code>score</code>) is off. </p> <p>From the <a href="https://en.wikipedia.org/wiki/Coefficient_of_determination#As_explained_variance" rel="nofollow noreferrer">notation of the Wikipedia article on coefficient of determination</a>, you are choosin...
python|numpy|machine-learning|regression
1
352,204
49,335,184
Reuse variables and model encapsulated in class
<p>I want to train a model in tensorflow and only define the graph and variables once. So I encapsulated that in a class as follows in this functionally non-sense minimum example:</p> <pre><code>import tensorflow as tf import numpy as np class Model: weights = tf.get_variable("weights", (10, 1)) bias = tf.ge...
<p>In general you should use <code>saver</code> to save the model then load it but a workaround would be to save the tensorflow session as a variable too and use that for both train and prediction.</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np class Model: weights ...
python|oop|tensorflow|dry
1
352,205
49,157,349
Why can't I search for a row in a pandas df using a date as part of a tuple index?
<p>I am trying to search a pandas df I made which has a tuple as an index. The first part of the tuple is a date and the second part is a forex pair. I've tried a few things but I can't seem to search using a date-formatted string as part of a tuple with .loc or .ix</p> <p>My df looks like this:</p> <pre><code> ...
<p>Can you try putting the tuple in a list using brackets?</p> <p>Like this:</p> <pre><code>print(forex_open_close.ix[[('11-01-2018', 'GBPUSD')]]) </code></pre>
python|pandas|datetime|tuples
2
352,206
48,946,335
Formatting datetime in matplot Python
<p>I am having problems to adjust the datetime in a better way to visualize in my graph. Here is my code:</p> <pre><code>fig = plt.figure() new.plot(title='(Graph)',figsize=(10,7), legend=None) plt.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left=...
<p>You can try rotating the labels adding the paramenter <code>labelrotation</code> <a href="https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html" rel="nofollow noreferrer">https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html</a>:</p> <pre><code>plt.tick_params(axis="both", whic...
python|pandas|matplotlib|graph
1
352,207
49,032,296
Interaction between CheckboxButtonGroup and Legend in complex bokeh plot
<p>I have a complex multivariate dataset that is similar in structure to this:</p> <pre><code>import pandas as pd import numpy as np import datetime as dt from itertools import cycle, islice N = 24 start_date = dt.date(2016,1,1) nbdays = int(365 / N) df = pd.DataFrame({'Date': [start_date + dt.timedelta(days=i*nbday...
<p>Here is some ideas:</p> <ul> <li>use <code>CustomJSFilter</code> to wrap a javascript function to do the data filter. </li> <li>use only one call of <code>p.circle()</code> to draw all the circles.</li> <li>use <code>factor_cmap</code> to map Treatment column to colors. </li> <li>use <code>tags</code> property to s...
python|pandas|bokeh
2
352,208
49,264,296
Pandas read_csv with 4GB of csv
<p>My machine was laggy while trying to read a 4GB of csv in jupyter notebook with chunksize option: <code> raw = pd.read_csv(csv_path, chunksize=10**6) data = pd.concat(raw, ignore_index=True) </code> This takes forever to run and also freeze my machine (Ubuntu 16.04 with 16GB of RAM). What is the right way to do this...
<p>The point of using chunk is that you don't need the whole dataset in memory at one time and you can process each chunk when you read the file. Assuming you don't need the whole dataset in memory at one time, you can do</p> <pre><code>chunksize = 10 ** 6 for chunk in pd.read_csv(filename, chunksize=chunksize): do...
python|python-3.x|pandas|csv
2
352,209
49,052,687
How to convert Multilevel Dictionary with Irregular Data to Desired Format
<pre><code>Dict = {'Things' : {'Car':'Lambo', 'Home':'NatureVilla', 'Gadgets':{'Laptop':{'Programs':{'Data':'Excel', 'Officework': 'Word', 'Coding':{'Python':'PyCharm', 'Java':'Eclipse', 'Others': 'SublimeText'}, 'Wearables': 'SamsungGear', 'Smartphone': 'Nexus'}, 'clothes': 'ArmaaniSuit', 'Bags':'TravelBags'}}}} d ...
<p>You information looks a lot like json and that's what the API is returning. If that's the case, and you are turning it into a dictionary, then you might me better off using python's json library or even panda's built it read_json format. </p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas...
python|pandas|dictionary|dataframe|qtableview
0
352,210
49,085,813
pandas groupby with ignore some rows
<p>I have such DataFrame</p> <pre><code> W2 N V1 V2 ba EX 62069 30014 ba ADV 12325 8218 ba X 23 22 b X 164831 39425 b PRT 41543 16708 </code></pre> <p>I need groupby W2 with same va...
<p>I think need first filter out rows by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>query</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</...
python|pandas
0
352,211
49,229,610
Difference between numpy.round and numpy.around
<p>So, I was searching for ways to round off all the numbers in a numpy array. I found 2 similar functions, numpy.round and numpy.around. Both take seemingly same arguments for a beginner like me. </p> <p>So what is the difference between these two in terms of:</p> <ul> <li>General difference</li> <li>Speed</li> <li>...
<p><a href="https://github.com/numpy/numpy/blob/v1.14.0/numpy/core/fromnumeric.py#L2840-L2851" rel="noreferrer">They are the exact same function</a>:</p> <pre><code>def round_(a, decimals=0, out=None): """ Round an array to the given number of decimals. Refer to `around` for full documentation. See Als...
python|arrays|numpy|rounding
11
352,212
49,161,652
How to get around in place operation error if index leaf variable for gradient update?
<p>I am encountering In place operation error when I am trying to index a leaf variable to update gradients with customized Shrink function. I cannot work around it. Any help is highly appreciated!</p> <pre class="lang-python prettyprint-override"><code>import torch.nn as nn import torch import numpy as np from torc...
<p>I just found: In order to update the variable, it needs to be <code>ht.data[idx]</code> instead of <code>ht[idx]</code>. We can use <code>.data</code> to access the tensor directly.</p>
python|neural-network|deep-learning|gradient-descent|pytorch
12
352,213
48,967,121
percentage change in pandas
<p>I have DataFrame that is like the following </p> <pre><code> Date ACH BABA BIDU CEA CHA CTRP EDU HNP 0 2000-06-30 $1.00 $3.00 $1.00 $0.00 $0.00 $0.00 $0.00 $0.00 1 2000-07-03 $3.00 $2.00 $6.20 $1.50 $0.00 $0.00 $0.00 $-0.48 2 2000-07-04 $5.00 $6.00...
<p>You need remove <code>$</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>replace</code></a> and cast to <code>float</code>s first:</p> <pre><code>import pandas as pd s = '''\ Date ACH BABA BIDU CEA CHA CTRP ...
python-3.x|pandas
3
352,214
49,109,190
Cannot manually assign new parameters via layer name
<p>I'm trying to manually assign new weights to my pytorch model. I can assign new weights like this:</p> <pre class="lang-python prettyprint-override"><code>import scipy.io as sio import torch caffe_params = sio.loadmat('export_conv1_1.mat') net.conv1_1.weight = torch.nn.Parameter(torch.from_numpy(caffe_params['w'...
<p>Does the following work?</p> <pre><code>for name in varList: caffe_params = sio.loadmat(rootDir + 'export_' + name + '.mat') getattr(net, name).weight.data.copy_(torch.from_numpy(caffe_params['w'])) getattr(net, name).bias.data.copy_(torch.from_numpy(caffe_params['b'])) </code></pre>
pytorch|setattr
0
352,215
48,922,447
Using a randomly shuffled batch as input to a CNN from a tensor of image data
<p>I am trying to train a network using STL-10 dataset.</p> <p>I have extracted the data from the STL-10 binary files and converted them into numpy arrays. Then i have converted them to tensors using <code>tf.convert_to_tensor</code> function</p> <p>Now I have a tensor of shape (5000,96,96,3)</p> <p>I want to get a ...
<p>From the docs of <code>tf.train.batch</code>:</p> <blockquote> <p>The argument tensors can be a list or a dictionary of tensors. The value returned by the function will be of the same type as tensors.</p> </blockquote> <p>You need to convert your data into a list of 5000 tensors, each of them shaped (96,96,3)....
python|tensorflow
1
352,216
49,289,896
alter for loop to skip record with missing value
<p>When I run the code below, I get the error below. What seems to be happening is that for some _place records in my good_df dataframe there are no hcat with the stf_id and no entries in the goodsellers field. The goodsellers field has a concatenated string of values that are separated by pipe. So since it can't sp...
<pre><code>for stf_id in stf_id: for place in place: print("%s | %s" % (place, stf_id)) try: goodsellers = good_df[(good_df['hcat']==stf_id) &amp; (good_df['_place']==place)]['goodsellers'].squeeze().split("|") except AttributeError: print("skipped to the next _pl...
python-2.7|pandas
1
352,217
49,234,647
Check that a csv file has the correct column names python
<p>I have a csv file that I'm uploading to a database, Id like to compare the headings/columns to a list so that I can make sure its the correct csv file being inserted into the database without having to open the csv file so if I have the following <code>Name Surname Age Height</code> it must be compared to the csv h...
<p>You can use <code>pd.read_csv</code> with <code>nrows=0</code>. Below is an example.</p> <pre><code>from io import StringIO import pandas as pd mystr = StringIO("""col1,col2,col3 val1,val2,val3""") check_list = ['Name', 'Surname', 'Age', 'Height'] df_cols = pd.read_csv(mystr, nrows=0) df_cols_list = df_cols.colu...
python|python-3.x|pandas|csv
5
352,218
49,085,469
Convert structured array to numpy array for use with Scikit-Learn
<p>I'm having difficulty converting a structured array loaded from a CSV using <code>np.genfromtxt</code> into a <code>np.array</code> in order to fit the data to a Scikit-Learn estimator. The problem is that at some point a cast from the structured array to a regular array will occur resulting in a <code>ValueError: c...
<p>Add a <code>.copy()</code> to <code>data[features]</code>: </p> <pre><code>X = data[features].copy() X = X.view((float, len(X.dtype.names))) </code></pre> <p>and the <code>FutureWarning</code> message is gone.</p> <p>This should be more efficient than converting to a list first.</p>
python|arrays|numpy
3
352,219
48,976,028
Random diagonal matrix
<p>I want to create a random diagonal matrix with size n such that each element in the diagonal entries has 50% chance of being -1 and 50% chance of being 1. Is there any advice for this?</p> <pre><code>import numpy as np diagonal_entries = np.random.randint(low = -1, high = 1, size = n) D = np.diag(diagonal_entries) ...
<p>You can use <code>np.random.choice</code> to sample a vector</p> <pre><code>import numpy as np n=100 vec=np.random.choice([-1,1],n) mat=np.diag(vec) </code></pre>
python|numpy
3
352,220
49,321,361
How to align xlabels and ylabels in seaborn?
<p>I am plotting heatmap of features but the feature names on x and y axes conincide with each other. So how can I align x axis feature names vertically and y axis feature names horizontally so that they do not overlap.</p> <p>Code: </p> <pre><code>%matplotlib notebook corr = data.loc[:,'PERID':'PRXRETRY'].corr() s...
<p>This works for me:</p> <pre><code>hm = sns.heatmap(corr, cmap="YlGnBu", annot=True) hm.set_xticklabels(labels=corr.columns.values, rotation=90) hm.set_yticklabels(labels=corr.columns.values, rotation=0) </code></pre>
python|pandas|seaborn
1
352,221
48,982,185
How to create dataframe from Dict
<pre><code> @app.route('/patient') def patientData(): global patientData patientGuid = request.args.to_dict() df1 = pd.DataFrame([patientGuid]) #df1.to_csv("path.csv") return str(df1) if __name__ == "__main__": app.run() </code></pre> <p>But when save file it gi...
<p>I think you need,</p> <pre><code> a=[ { "PatientGuid": "0", "Gender": 1, "YearOfBirth": 1923 } ] df=pd.DataFrame(a) print(df) [out]: Gender PatientGuid YearOfBirth 0 1 0 1923 </code></pre> <p>if you want to change the column names,</p> <pre><code> df.columns=["a","b","c"] print(df) ...
python|pandas|dictionary|flask|request
1
352,222
49,237,757
Calculate multiple composite scores in Pandas DataFrame
<p>I'm a Python and Pandas newbie here and first ever Stackoverflow question.</p> <p>I'm working with some survey data and need to create multiple composite scores. The problem I have is that there are 50 satisfaction scores and 50 importance scores and therefore I need to calculate 50 composite scores using the simpl...
<p>IIUC, I think you do this:</p> <pre><code>data.join(data.groupby(data.columns.str.extract(r'(\d+\b)',expand=False), axis=1) .prod() .add_prefix('Comp')) </code></pre> <p>OR </p> <pre><code>(data.assign(**data.groupby(data.columns.str.extract(r'(\d+\b)',expand=False), axis=1) .prod() .add_prefi...
python|pandas
3
352,223
49,077,702
Joining 2 dataframes in pandas with different column names
<p>I'm trying to join 2 dataframes in a kind of strange way and was wondering if anyone has any advice. </p> <p>My first data frame looks like this, call it <code>df1</code>:</p> <p><a href="https://i.stack.imgur.com/L1qtF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L1qtF.jpg" alt="teamStatsDF"...
<p>You can use <code>left_on</code> and <code>right_on</code> parameters from <code>pd.merge</code>.</p> <pre><code>df1 = pd.DataFrame({'col1' : ['a','b','c','d','e','b'], 'val2': [31,43,23,54,65,23]}) df2 = pd.DataFrame({'col2': ['a','b','c'], 'val1': [11,22,33]}) df3 = pd.merge(df1, df2, left_on='col1', right_on='c...
python|python-3.x|pandas|dataframe|join
2
352,224
49,279,208
How to store a NumPy array as a key in Python
<p>I have a set of length three NumPy arrays. E.g.:</p> <pre><code>[ [0,0,0], [0,0,1], [0,0,2], [0,1,0],[0,1,1],... ] </code></pre> <p>For each of these NumPy arrays, I would like to store a list that is constantly being updated and have it in some way linked to a particular NumPy array. </p> <p>For example, if for ...
<p>As @chepner mentioned, you'll never be able to use numpy arrays as keys since they are mutable. To solve your problem, you can try using a dictionary of dictionaries. The format could be something a long the lines of this:</p> <pre><code>{'000': {state: [0,0,0], rewards: [1,1,1,1,0,-1,-1,1,1,1]}, '001': {state:...
python|arrays|numpy|reinforcement-learning
2
352,225
48,997,836
pandas: merging dataframes with different keys
<p>df1</p> <pre><code> 1 2 3 4 101 1 C 22.6253 101 2 O -32.7148 101 3 N 119.0569 101 4 H 26.8502 101 5 C 126.1352 </code></pre> <p>df2</p> <pre><code> num1 type name num2 first 101 N VAL 101 N 101 H VAL 101 H 101 ...
<p>This is one way. <em>I assume that the first row in your result is incorrect.</em></p> <pre><code>pd.merge(df1, df2[['type', 'name', 'first']]\ .drop_duplicates('first'), how='left', left_on='3', right_on='first')\ .drop('first', 1) </code></pre> <p><strong>Result</strong></p> <pre><code> 1 2 3 ...
python|pandas|merge
0
352,226
48,916,582
Replacing part of Numpy 2D Array using list in both rows and columns
<p>Let's import <code>numpy</code> first,</p> <pre class="lang-py prettyprint-override"><code>import numpy as np </code></pre> <p>For example, I have a matrix A as,</p> <pre class="lang-py prettyprint-override"><code>A = np.identity(10) </code></pre> <p>I have two other matrices as,</p> <pre class="lang-py prettyp...
<pre><code>In [99]: A = np.identity(10).astype(int) In [100]: A Out[100]: array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, ...
python|arrays|python-3.x|numpy|replace
1
352,227
49,211,924
use .assign() method with lambda in python
<p>I run this code in Python:</p> <pre><code> #Declaring these now for later use in the plots TOP_CAP_TITLE = 'Top 10 market capitalization' TOP_CAP_YLABEL = '% of total cap' # Selecting the first 10 rows and setting the index cap10 = cap.loc[:10, :].set_index('id') # Calculating market_cap_perc cap10 = cap10....
<p>I got the answer:</p> <pre><code>import pandas as pd # Reading datasets/coinmarketcap_06122017.csv into pandas dec6 = pd.read_csv('datasets/coinmarketcap_06122017.csv') # Selecting the 'id' and the 'market_cap_usd' columns market_cap_raw = dec6[['id','market_cap_usd']] cap = market_cap_raw.query('market_cap_usd &g...
python|pandas|dataframe|lambda|assign
0
352,228
49,293,053
python : np.where() and broadcasting
<p>Can someone please help me to understand how broadcasting works below in np.where() function ? </p> <pre><code>x = np.arange(9.).reshape(3, 3) np.where(x &lt; 5, x, -1) # Note: broadcasting. array([[ 0., 1., 2.], [ 3., 4., -1.], [-1., -1., -1.]]) </code></pre>
<p>Let's look at the individual pieces</p> <pre><code>x = np.arange(9).reshape(3, 3) &gt;&gt;&gt; x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) </code></pre> <p>Notice that <code>x &lt; 5</code> makes an array of booleans:</p> <pre><code>&gt;&gt;&gt; x &lt; 5 array([[ True, True, True], [ True, ...
python|numpy|array-broadcasting
0
352,229
48,976,923
input_fn optimisation for tf.estimator.train_and_evaluate
<p>I am building a TensorFlow Estimator that I want to train and evaluate using the <code>tf.estimator.train_and_evaluate()</code> function. The <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/train_and_evaluate" rel="nofollow noreferrer">doc</a> for this function gives the following advice:</p> <bloc...
<p>Maybe you can use tf.data.Dataset.range other than tf.data.Dataset.from_generator. Here is the sample code: First, define Python class</p> <pre><code>import tensorflow as tf import time class instance_generator(): def __init__(self): #doing some initialization self.data_index = {n:str(n) for n ...
python|performance|tensorflow|tensorflow-datasets|tensorflow-estimator
0
352,230
48,979,909
Pytorch: TypeError 'torch.LongTensor' object is not reversible
<p>I'm trying to do a NLP task by pytorch and I used following code to pack my batch of sentences.</p> <pre><code>for iter in range(0, n_iters, batch_size): # batch size * max length Variable input_batch = input_data[iter:iter + batch_size] target_batch = target_data[iter:iter + batch_size] # batch si...
<p>PackedInput is coded with the expectation a list of longs. </p> <p>If you want to use a Variable(LongTensor([list])).cuda() for indexes, then you have to bring it back to the cpu, and numpy it, then put it back in.</p> <pre><code>packed_in= pack_padded_sequence(embedded, seqs_len.data.cpu().numpy(), batch_first=T...
pytorch
0
352,231
48,891,382
Stacking matrices to make a matrix with sites of parent matrices map as block diagonals
<p>How stack matrices as follows in python such that elements of parent matrices make a block diagonal at the same block diagonal site of the daughter matrix. example: I have four matrices AA,AB,BA, BB</p> <p>I want to make the matrix out as shown in attached image.<a href="https://i.stack.imgur.com/mEMyO.png" rel="no...
<pre><code>In [35]: arr = np.arange(1,17).reshape(4,4) In [36]: arr2 = arr.reshape(2,2,2,2) In [37]: arr2 Out[37]: array([[[[ 1, 2], [ 3, 4]], [[ 5, 6], [ 7, 8]]], [[[ 9, 10], [11, 12]], [[13, 14], [15, 16]]]]) </code></pre> <p>I did some trial and er...
python|numpy|scipy
1
352,232
49,228,252
Python Pandas condition fails to identify rows accurately
<p>This is a input and output from a jupyter notebook. I need help with identifying the reason why I am unable to accurately select and set the data in the 'went_out' column.</p> <p><a href="https://i.stack.imgur.com/BeXKd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BeXKd.png" alt="enter image d...
<p>As far as i understood you are trying to write the date and time when the door closes. This might be a part of the solution that you want. Instead of looking for the the condition of door opening and then closing you can use just the door close condition to index the 'went_out' column. </p> <pre><code>df.loc[(df[...
python|pandas|jupyter-notebook|jupyter|data-science
1
352,233
49,294,369
Renaming a column in Pandas grouped By dataframe is failing
<p>I have the results of my groupby statements:</p> <pre><code>df_Done_Ccy = df[ df['state'].str.contains('Done') ][['currency_str','state']] d = { ('state',np.size) # apply the count of done trades to the following groupby } df_Done_Ccy_Grp = df_Done_Ccy.group...
<p>Sorting on the rename resolved this: </p> <pre><code>df_Done_Ccy_Grp = df_Done_Ccy_Grp.rename(columns={'state':'Done Trades'}, level=0) display(df_Done_Ccy_Grp.sort_values('Done Trades',ascending=False)) – Peter Lucas </code></pre>
python|pandas|dataframe|group-by|rename
0
352,234
48,935,422
How to start using Numpy
<p>I am trying to use NumPy. Specifically, to run:</p> <pre><code>import numpy as np lst = [[1, 2, 3], [4, 5, 6]] ary1d = np.array(1st) ary1d array([[1, 2, 3,], [4, 5, 6]]) </code></pre> <p>However, I am not sure whether this is code that is meant to be typed into the command terminal or IDLE. I have Co...
<p>First off, install NumPy:</p> <p><code>conda install numpy</code> or <code>pip install numpy</code> should work.</p> <p>Afterwards, you can use it either in an interactive session (using the <code>python</code> command, <code>ipython</code>, or an IDE like Spyder) or by putting it in a standard python file and run...
python|numpy
1
352,235
58,899,895
Cosine similarity loss cause weight values to explode
<p>Suppose my data consists of images of bubbles, and the labels are histograms describing the distribution of sizes, for example:</p> <pre><code>0-10mm 10% 10-20mm 30% 20-30mm 40% 30-40mm 20% </code></pre> <p>It is important to note that -</p> <ul> <li>All size percentages sum to 100% (or 1.0 to be more precise).<...
<p>My guess is cosine distance does an internal normalisation of the logits, removing the magnitude, and thus there is no gradient to propogate that opposes the values increasing. BTW <code>weights</code> is not used in your implementation.</p> <p>What about just plain Euclidian distance using sigmoid instead of softm...
tensorflow|deep-learning|computer-vision
0
352,236
58,689,919
Pandas: Sort a dataframe based on multiple columns
<p>I know that this question has been asked several times. But none of the answers match my case.</p> <p>I've a pandas dataframe with columns,department and employee_count. I need to sort the employee_count column in descending order. But if there is a tie between 2 employee_counts then they should be sorted alphabeti...
<p>You can swap columns in list and also values in <code>ascending</code> parameter:</p> <p><strong>Explanation</strong>:</p> <p>Order of columns names is order of sorting, first sort descending by <code>Employee_Count</code> and if some duplicates in <code>Employee_Count</code> then sorting by <code>Department</code...
python-3.x|pandas|sorting|dataframe|pandas-groupby
12
352,237
58,806,163
How to create a nested list of comprehension for counting number of sheets in a list of excel files?
<p>I created a loop for counting the number of sheets inside each excel file in my directory. </p> <p>I tried to create a nested list of comprehension, but i don't know how to deal with the <code>pd.ExcelFile(file)</code> that actually works inside my loop </p> <p>In order to simplify the code here I created a list c...
<p>This is the list comprehension version, you may always add your <code>for x in i</code> in the <code>[]</code> then on the left compute something, and if needed add a condition at the right</p> <pre><code>counter = [len(pd.ExcelFile(file).sheet_names) for file in file_list] </code></pre>
python|pandas
2
352,238
58,836,695
Concatenate values from two dataframes, based on two sets of indices, in Pandas
<p>I have the following dataframes: </p> <pre><code>test1 = pd.DataFrame({'id_A' : [1,2,3,4,5,6], 'value_A' : 6*['dog']}) test2 = pd.DataFrame({'id_B' : [1,3,5], 'value_B' : 3*['cat']}) </code></pre> <p>and I want to obtain a dataframe in which, where <code>id_A</code> = <co...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> for check membership and then change your <code>map</code> solution with mainly add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.f...
pandas|dataframe|pandas-groupby
2
352,239
58,847,200
matrix multiplication using star operator
<p>I am curious about what the difference is between calling torch.mm(A, B) and A*B?</p> <p>Looks like torch.mm gives us the desirable result, but A*B sometimes doesn't work.</p> <p>It will be better if any documentation is provided. </p> <p>Thank you!</p>
<p><code>torch.mm(A,B)</code> is a regular matrix multiplication and <code>A*B</code> is element-wise multiplication. You can read it on this <a href="https://discuss.pytorch.org/t/the-differences-between-torch-mul-a-b-and-a-b/32153" rel="noreferrer">discussion</a>. For matrix multiplication you can use <code>@</code> ...
pytorch
5
352,240
58,810,335
Create dataframe from loop
<p>I have a loop which runs 3 times, and each time produces 4 values, e.g. below.</p> <pre><code>for i in range(0, 3): val1 = something val2 = something val3 = something val4 = something </code></pre> <p>From this loop, how can I create a dataframe of size (3x4) as follows?</p> <pre><code>val1 val2 ...
<pre><code>data = [] for i in range(0, 3): val1 = something val2 = something val3 = something val4 = something data.append([val1, val2, val3, val4]) df = pd.DataFrame(data, columns=['val1', 'val2', 'val3', 'val4']) </code></pre>
python|pandas
2
352,241
58,961,278
Python/Pandas - long strings trimmed during import of Shapefile to GeoDataFrame
<p>I have observed that during importing of Shapefile format to Pandas DataFrame (using geopandas package) columns with long values (over 256 char) are being trimmed:</p> <pre><code>import geopandas as gpd import pandas as pd shp_file = gpd.read_file(observations.shp) </code></pre> <p>Is there a way to bypass this l...
<p>It is not the fault of import to GeoDataFrame. The Shapefile maximum field width is 254. It is a limitation of the dBase format.</p>
python|pandas|shapefile|geopandas
2
352,242
59,017,146
pandas remove records conditionally based on records count of groups
<p>I have a dataframe like this </p> <pre><code>import pandas as pd import numpy as np raw_data = {'Country':['UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK'], 'Product':['A','A','A','A','B','B','B','B','B','B','B','B','C','C','C','D','D','D','D','D','D'], ...
<p>Define the following function selecting rows from <em>df</em>, for products from the current <em>row</em> in <em>mapping</em>:</p> <pre><code>def selRows(row, df): rows_1 = df[df.Product == row.Product] nr_1 = rows_1.index.size lastWk_1 = rows_1.Week.iat[-1] rows_2 = df[df.Product.eq(row.Product1) &...
python-3.x|pandas|pandas-groupby
1
352,243
59,007,651
How to re order rows, by moving multiple separated rows an X amount of rows below in python with either pandas or numpy
<p>I have a very long dataframe with hundreds of rows. I want to select the rows with one key word in one of the columns, and lower the whole row 18 places below. Since there are too many, using reindex and doing it manually would be too long.</p> <p>As an example, for this df I would like to move the rows with the wo...
<p>First create extra, dummy column, to mock your sorting key. In this case, as far as I understood you:</p> <pre class="lang-py prettyprint-override"><code>ord=["One", "Two", "Three", "Base"] df["sorting_key"]=df.groupby("A").cumcount().map(str)+":"+df["A"].apply(ord.index).map(str) </code></pre> <p>Then just sort ...
python|pandas|rows|reindex
2
352,244
58,894,545
How to store values of selected columns in separate rows?
<p>I have a <code>DataFrame</code> that looks as follows:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'ids': range(4), 'strc': ['some', 'thing', 'abc', 'foo'], 'not_relevant': range(4), 'strc2': list('abcd'), 'strc3': list('lkjh') }) ids strc not_relevant strc2 strc3 0 0 som...
<p>After <code>filter</code>, you need <code>stack</code>, <code>droplevel</code>, <code>rename</code> and <code>join</code> back to <code>df</code></p> <pre><code>df1 = df.join(df.filter(like='strc', axis=1).stack().droplevel(1).rename('strc_list')) Out[135]: ids strc not_relevant strc2 strc3 strc_list 0 0 ...
python|pandas|dataframe
2
352,245
58,618,443
How to Create Pandas DataFrame out of Parsed Code using bs4/selenium on Python?
<p>I have parsed a table and would like to convert two of those variables to a Pandas Dataframe to print to excel. </p> <p><em>FYI:</em> I did ask a similar question, however, it was not answered thoroughly. There was no suggestion on how to create a Pandas DataFrame. This was the whole point of my question.</p> <p><...
<p>Looks like you want to create a DataFrame from a list of tuples, which has been answered <a href="https://stackoverflow.com/questions/28200157/list-of-tuples-to-dataframe-conversion">here</a>. I would change your code like this:</p> <pre><code># Initial empty list data = [] #loop through tr to find_all td for tr in...
python|pandas|selenium|dataframe|parsing
1
352,246
58,953,700
Replacing gradient calculation of loss function in tensorflow 2.0
<p>I would like to replace to gradient function for a loss function in <code>tensorflow 2.0</code>.</p> <p>Say for example I have a loss function which looks like:</p> <pre><code>def loss_function(prediction): # do some standard tensorflow things here return loss </code></pre> <p>I then apply the gradients u...
<p>The answer was actually quite straight forward. First define a <code>@tf.custom_gradient()</code> function which defined the gradient and pass the loss through it i.e.</p> <pre><code>@tf.custom_gradient def custom_grad(x): def grad(dy, **kwargs): # do something with dy here return dy return...
tensorflow|tensorflow2.0|loss-function
0
352,247
58,926,043
Generating Random vectors and matrices for weights and bias
<p>I am trying to know the chance of fire based on sensors x1 and x2.</p> <pre><code>y=1 </code></pre> <p>For this, I am trying to generate random vectors and matrices for weights and bias but I get an error.</p> <pre><code>import numpy as np np.random.seed(seed=123) w1 = np.random.rand(4,2) b1 = 4*1 x = np.array(...
<p>The answer is in the error - you are trying to multiply the matrices <code>w2</code> and <code>x</code>, which have invalid dimensions to be multiplied.</p> <p>Matrix <code>w2</code> has 1 row and 4 columns:</p> <pre><code>&gt;&gt;&gt; w2 = np.random.rand(1,4) &gt;&gt;&gt; w2.shape (1, 4) </code></pre> <p>Matrix ...
python|numpy|sigmoid
0
352,248
58,720,145
Fill a column at missing year/quarter with 0 in pandas dataframe
<p>I have a dataframe like below. <code>value</code> is missing for some <code>year_Quarter</code>.</p> <pre><code>import pandas as pd pd.DataFrame({'Year_Quarter':['2017_Q1', '2017_Q3', '2017_Q4', '2018_Q1', '2018_Q2', '2018_Q4'], 'Value': [12, 14, 2, 44, 5, 33]}) Year_Quar...
<p>Munge <code>df</code> to make <code>Year_Quarter</code> into periods</p> <pre><code>df = df.assign( Year_Quarter= df.Year_Quarter.map(lambda x: pd.Period(x.replace('_', ''), 'Q')) ).set_index('Year_Quarter') </code></pre> <p>Create an index that is a range of periods</p> <pre><code>idx = pd.period_range(d...
python|pandas
3
352,249
58,758,098
How can I remove columns of pandas dataframe conditional on last row values?
<p>Given a data-frame like:</p> <pre><code> A B C 2019-11-02 120 25 11 2019-11-03 119 28 15 2019-11-04 115 23 18 2019-11-05 119 30 20 2019-11-06 121 32 25 2019-11-07 117 24 30 </code></pre> <p>I would like to remove the columns in which the value of the last row is less than (&lt;) a constant X, ...
<h3>Method 1:</h3> <p>Use <code>iloc</code>, <code>lt</code>, and <code>drop</code>:</p> <p>We select the last row with <code>iloc[-1]</code>, then check which column is <code>less than (lt)</code> <code>25</code> and pass that column to <code>DataFrame.drop</code></p> <pre><code>df = df.drop(columns = df.columns[df...
python|pandas|dataframe|subset
1
352,250
58,986,268
Why does pandas.to_csv make a bigger file than xlsx
<p>My code currently grabs some workbooks from the our server and copies them a another location, where I get pandas to read each file (100 workbooks), filter down a certain column then output the filtered data as a .csv. It takes 788 seconds to run over the 100 workbooks (all circa 8mb) and outputs a csv (all 10mb). I...
<p><code>xlsx</code> is a compressed (zipped) format.</p>
python|pandas
1
352,251
58,848,130
Creating autocorrelation plot with irregular time series?
<p>I'm doing a data science project where I'm trying to use previous police stops to predict future ones. I'm trying to make an auto-correlation plot of time vs geo-spatial longitude, but I keep getting an error when I try to make the plot. This is keeping me from finding the correct lags to make the ARIMA model.</p> ...
<p>I believe the issue is coming from the time structure, maybe you should try indexing your time and see how the ACP goes. </p> <p>Maybe something like this:</p> <pre><code>autocorrelation_plot(df.set_index('time')) plt.show() </code></pre> <p>see the docs of pandas <a href="https://pandas.pydata.org/pandas-docs/s...
python|pandas|matplotlib|data-science
0
352,252
58,881,270
adding prefix to pandas column
<p>I'm trying to add a prefix to a DataFrame in pandas. It supposes to be very easy: </p> <pre><code>import pandas as pd a=pd.DataFrame({ 'x':[1,2,3], }) #this one works; "mm"+a['x'].astype(str) 0 mm1 1 mm2 2 mm3 Name: x, dtype: object </code></pre> <p>But surprisingly, if I want to use a prefix of sing...
<p>The problem is that <code>"m"</code> is interpreted as <code>TimeDelta</code>:</p> <pre><code>from pandas.core.dtypes.common import is_timedelta64_dtype print(is_timedelta64_dtype("m")) </code></pre> <p><strong>Output</strong></p> <pre><code>True </code></pre> <p>The function <code>is_timedelta64_dtype</code> i...
python|pandas
3
352,253
58,863,523
Best Practices to apply a function by group on dask
<p>I have a large dataset stored on hdf5 file, and I need to perform some operations.</p> <pre><code> sku cente units 0 103896 1 2.0 1 103896 1 0.0 2 103896 1 5.0 3 103896 1 0.0 4 103896 1 7.0 </code></pre> <p>Using dask, I can perform statistical operations quite fast. This operation ta...
<p>Groupby-apply operations with custom functions are genuinely difficult to do in parallel. You need to move all of the data for each group to a single task to run your custom function. Because Dask does not know what your function does, it can not be clever here.</p> <p>If you can fit all of your data in RAM then ...
python|pandas|dask
1
352,254
58,861,878
Loading and correctly displaying an image dataset using pytorch Dataloader
<p>I'm trying to load a custom dataset for training a neural network, but before I load them in, I would like to verify that they've been loaded correctly. So far it looks like they are not being loaded correctly, but I can't figure out what gives the images the format that they get.</p> <p>This is the code that I'm l...
<p>The <code>.view(128, 128, 3)</code> is messing up with the images.</p> <p>As you can read in the documentation of the transformation <a href="https://pytorch.org/docs/stable/torchvision/transforms.html#torchvision.transforms.ToTensor" rel="nofollow noreferrer"><code>.ToTensor(...)</code></a>:</p> <blockquote> <p>[.....
python|image-processing|pytorch
0
352,255
58,945,362
It is possible to change loss in Tensorflow object detection api?
<p>i want to change loss of object detection for ones of object detection (such as SSD) ,</p> <p>Q1 : i want to know where do i modify the loss function for SSD ,</p> <p>Q2 : is it possible to fine-tune ssd_mobilenet on my dataset with my define loss ? is it good or must be train ssd_mobile from scratch with my loss ...
<p>Q1: If you are using the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">object detection api</a> then a config is used to define the network and the loss, such as these:</p> <p><a href="https://github.com/tensorflow/models/tree/master/research/object_d...
tensorflow|deep-learning|object-detection-api
0
352,256
58,995,187
Transform a function into custom Aggregation using dask
<p>I have a large dataset with 3 columns:</p> <pre><code> sku center units 0 103896 1 2.0 1 103896 1 0.0 2 103896 1 5.0 3 103896 1 0.0 4 103896 1 7.0 5 103896 1 0 </code></pre> <p>And I need to use a <code>groupby-apply</code> function using dask.</p> <pre><code>def function_a(x): ...
<h2>Preface</h2> <p>First, a small primer on what the arguments of <a href="https://docs.dask.org/en/latest/dataframe-api.html#custom-aggregation" rel="nofollow noreferrer">dask.dataframe.groupby.Aggregation</a> do. There is also a good example about custom aggregation on their <a href="https://docs.dask.org/en/latest...
python|pandas|dask
1
352,257
58,814,233
Correlation dataframe into figure in pandas
<p>I calculate the correlation a <code>dataframe</code> with this code:</p> <pre><code>corr = df.corr() corr.style.background_gradient(cmap='coolwarm') </code></pre> <p>I got this result (screenshot):</p> <p><a href="https://i.stack.imgur.com/s7TXn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s...
<p>You can try this,</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import seaborn as sns fig, ax = plt.subplots() sns.heatmap(df.corr(), annot=True, fmt='.4f', cmap=plt.get_cmap('coolwarm'), cbar=False, ax=ax) ax.set_yticklabels(ax.get_yticklabels(), rotation='horizo...
python|pandas
2
352,258
58,642,687
Tensorboard: How to view model summary?
<p><strong>Problem Statement</strong></p> <ul> <li>Run a model with multiple configurations and compare graphs. Based on plot analysis, select a configuration.</li> </ul> <p>In the above statement, I am able to plot multiple runs of the model with their names. Now I need Tensorboard to show configuration/summary of t...
<p>You can use a <a href="https://www.tensorflow.org/api_docs/python/tf/summary/text" rel="nofollow noreferrer"><code>text</code></a> summary with the model summary, something like this:</p> <pre><code>import tensorflow as tf # Get model summary as a string def get_summary_str(model): lines = [] model.summary...
python|tensorflow|keras|deep-learning
2
352,259
58,677,046
what happened there with apply method in python?
<pre><code>In [5]: df1=pd.DataFrame({'Data1':np.random.randint(0,10,5), 'Data2':np.random.randint(10,20,5), 'key1':list('aabba'), 'key2':list('xyyxy')}) In [6]: df1 Out[6]: Data1 Data2 key1 key2 0 8 16 a x 1 9 19 a y 2 9 19 b y 3 6 12 b x 4 2 17 a y ...
<p>I should have googled it before I posted this question. Now I found the answer.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html</a></p> <p>In the ...
python|pandas
1
352,260
58,737,111
Parallelize populating ndarray from pandas series and csr matrix
<p>Currently using a for loop to populate values from pandas series (category/object dtype) and csr matrix (numpy) to an ndarray and I was looking to speed things up</p> <p>Sequential for loop (works), numba (doesn't like series and strings), joblib (slower than the sequential loop), swifter.apply (much slower as I ha...
<p>as <a href="https://stackoverflow.com/users/3293881/divakar">Divarak</a> mentioned, slicing directly works</p> <pre><code>matches_df["left_side"] = name_vector.iloc[sparserows].values matches_df["right_side"] = name_vector.iloc[sparsecols].values matches_df["similarity"] = matches.data </code></pre>
python|pandas|numpy|sparse-matrix
1
352,261
58,976,634
How to create a 2D array with N lots of random numbers?
<p>I am trying to obtain a variance for a value I obtained by processing a 2x150 array into a discrete correlation function. In order to do this I need to randomly sample 80% of the original data N times, which will allow me to calculate a variance over these values. have so far been able to create one randomly sample...
<p>Seeing as you're using numpy already, why not use <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.randint.html" rel="nofollow noreferrer">np.random.randint</a></p> <p>In your case:</p> <pre><code>np.random.randint(len(find_length)-1, size=(N, running_var)) </code></pre> <p>Would ...
python|arrays|numpy|random|statistics
1
352,262
59,012,385
Need to filter dates by month in pandas dataframe
<p>Have data on temperature that spans multiple years in 2010-01-01 format. I want to isolate the temps from June and am unsure how to filter this. Typically the method I use would be <code>df[df['date'] == 2016]</code> but this only parses out by year. </p>
<p>IIUC, you can use a datetime method ontop of your datetime to access the month</p> <pre><code>impot pandas as pd rng = pd.date_range('2010-01-01','2011-01-01',freq='D') df = pd.DataFrame({'dates':rng}) </code></pre> <h3>Print Head of DataFrame.</h3> <pre><code>print(df.head(5)) dates 0 2010-01-01 1 2010-01-0...
python|pandas|date|dataframe|filter
2
352,263
58,686,175
How to display or print all elements of a large python list in the editor
<p>I have a pandas dataframe with 423 variables. </p> <p>I would like to display (print) all of the column (variable) names in the editor so that I can check the exact names for variables. I am using ATOM IDE.</p> <p>To do this, I first use <code>df.columns</code>. This displays a handful of column names followed...
<p>You can just print one by one:</p> <pre><code>for x in df.columns: print(x) </code></pre> <p>Does that help?</p>
python|python-3.x|pandas|atom-editor
1
352,264
59,012,576
pandas backfil and ffill with different values
<p>I want to backfill and fill empty values with different/unique id e.g. if I have following DF</p> <pre><code>+----+------+ | Id | T_Id | +----+------+ | 1 | nan | | 1 | nan | | 1 | nan | | 1 | 4 | | 1 | nan | | 2 | nan | | 2 | 5 | | 2 | 5 | | 2 | nan | | 2 | nan | | 2 | 6 | | 2 | 6 ...
<p>We can do:</p> <pre><code>w1=df['T_Id'].notna() s=w1.cumsum().shift() w2=s.eq(s.max()) df['T_Id']=df['T_Id'].bfill().ffill().astype(str) df['T_Id']=df['T_Id']+np.select([w1,w2,~(w1|w2)],['','b','a']) </code></pre> <hr> <p><strong>Output</strong></p> <pre><code>print(df) Id T_Id 0 1 4a 1 1 4a 2 1...
python|pandas|dataframe|missing-data
2
352,265
58,724,583
export_inference_graph.py vs export_tflite_ssd_graph.py
<p>The output of <code>export_inference_graph.py</code> is</p> <pre><code> - model.ckpt.data-00000-of-00001 - model.ckpt.info - model.ckpt.meta - frozen_inference_graph.pb + saved_model (a directory) </code></pre> <p>while the output of <code>export_tflite_ssd_graph.py</code></p> <pre><code>- tflite_graph.pbtxt...
<p>I assume you are trying to use your object detection model on mobile devices. For which you need to convert your model to tflite version. But, you cannot convert models like fasterRCNN to tflite. You need to go for SSD models to be used for mobile devices.</p> <p>Another way to use model like fasterRCNN in your dep...
tensorflow|neural-network|deep-learning|object-detection|object-detection-api
1
352,266
58,979,299
Convert pandas dataframe of singleton matrices to dataframe of numbers
<p>I have a pandas dataframe of singleton Python matrices that I want to convert to dataframe of values. I can use apply to convert individual columns, but was wondering if I could do this over the entire dataframe. Here is what I have so far:</p> <p>Dataframe df:</p> <pre><code>+-----------+-----------+-----------...
<p>Use <code>applymap</code> instead of <code>apply</code></p> <pre class="lang-py prettyprint-override"><code>df.applymap(lambda x: np.asarray(x).ravel()[0]) </code></pre>
python|pandas|dataframe
5
352,267
58,623,851
Python Pandas: add list to df of different len
<p>I have the following list of len 52:</p> <pre><code>cw = list(range(1,53)) </code></pre> <p>I want to add this list to my df of len 104</p> <p>I use:</p> <pre><code>df.insert(0,"CW",cw, True) </code></pre> <p>This results in: </p> <pre><code>ValueError: Length of values does not match length of index </code></...
<p>You can change your code by adding <code>+cw</code>:</p> <pre><code>df.insert(0,"CW",cw+cw, True) </code></pre> <p>or by adding <code>* 2</code>:</p> <pre><code>df.insert(0,"CW",cw * 2, True) </code></pre>
python|pandas|list|dataframe
0
352,268
58,789,724
Pandas - dataframe containing comments(rows) and words as column headers how to get a frequency count?
<p>I am trying to perform a word frequency count on a relatively large dataframe and don't know what approach would be the best.</p> <p>Currently my dataframe looks like this - </p> <pre><code> Comment 'I' 'it' 'is' 'up' 'I was here' NaN NaN NaN NaN 'I like soup' NaN NaN NaN ...
<p>I do not think there is a better way than:</p> <pre><code>for column in df.columns[1:]: # All but comment column. df[column] = df[column].str.contains(df['Comment']) </code></pre> <p>This will give you a matrix of booleans, which you can map to bits if you really need.</p>
python|pandas|numpy|nlp|nltk
2
352,269
58,629,848
How to fix this error: list indices must be integers or slices, not tuple
<p>Suppose I have a list of tensors called <code>outputs</code></p> <pre><code>&gt;&gt; outputs[2][0][0,:,:] Out[20]: tensor([[ 14.0448, -5.1494, -0.1780, ..., 10.1937, -8.9158, -5.3964], [ 32.0382, -0.5201, 29.9942, ..., -18.8268, -23.1068, 23.9745], [-24.5911, 14.7233, -6.3053, ..., -5...
<p><code>outputs[2][0]</code> and <code>outputs[2][1]</code> both return an object (tensor I suppose).<br/> <code>outputs[2][0:1]</code> returns a list of those objects.<br/> What I think you are looking for is something like <code>outputs[2][0:1][:,0,:,:]</code> or <code>[a[0,:,:] for a in outputs[2][0:1]]</code></p>
python|list|tensorflow|pytorch
3
352,270
59,038,159
Keras time series, how to predict the next time period
<p>I am using Keras on some data. Here are the details: 8,000 customers, each customer has varying time steps ranging from 2 - 41. So I am using zero padding to ensure all customers have 41 time steps. All 8,000 customers have 2 features and the data comes with multiclass labels, 0-4. Each tilmestep has a label.</p> <...
<p>To predict the next timestep for each feature you would want your final <code>Dense</code> layer to be the same width as the number of features:</p> <pre><code>model.add(Dense(n_features)) </code></pre> <p>There's a good example of a similar problem here under <strong>Multiple Parallel Series</strong> <a href="htt...
python|tensorflow|keras|classification|timestep
0
352,271
58,864,228
pandas converting int or string to float
<p>I'm trying to map two dataframes on the name to get the <code>id</code> of a student. The <code>id</code> returned has a decimal in it. For example, if the <code>id</code> in <code>name_to_id</code> is <code>12345</code>, the <code>id</code> in <code>student</code> becomes <code>12345.0</code> Why is this decimal po...
<p>Try doing this for your students['id'] </p> <pre><code>students.astype({'id': 'int32'}).dtypes </code></pre> <p>for your reference I found this on: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stabl...
python|pandas
0
352,272
58,922,494
Statistics in python with missing values
<p>I have a huge dataset with something like 23 columns. I want to do descriptive statistics on the column 18 (and many others), but there are many missing values. I am wondering if there exist a command like in SAS to compute the statistics if the cell is not a missing value. In the picture I provide, i'd like to comp...
<p><code>df.describe()</code> would do the trick. </p> <p>Pandas ignores NaN values by default when calculating descriptive statistics. </p> <p>Example: taken straight from <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html" rel="nofollow noreferrer">https://pandas.pyda...
python|pandas|numpy
0
352,273
58,643,312
Use contains to merge data frame
<p>I have two separates files, one from our service providers and the other is internal (HR).</p> <p>The service providers write the names of our employer in different ways, there are those who write it in firstname lastname format, or first letter of the firstname and the last name or lastname firstname...while the H...
<p>if you are just checking if it exists or no this could be useful: because it is rare to have 2 exactly the same family name, I recommend to just split your Df1 and compare families, then for ensuring you can differ first names too you can easily do it with a for:</p> <pre><code>for i in range('your index'): if df1...
python|pandas
0
352,274
58,958,721
turn an array of (scalar) functions into a function returning an array
<p>I have an array <code>farr</code> of functions, say</p> <pre><code>import numpy as np farr=np.array([(lambda x, y: x+y) for n in range(5)]) </code></pre> <p>(in reality, the functions are all different splines) Now, I would like one function <code>f</code> that returns the result of all the functions in <code>farr...
<p>Another way is to use map:</p> <pre><code>x = 3 y = 3 value = list(map(lambda f: f(x,y), farr)) </code></pre> <p>For more details see <a href="https://book.pythontips.com/en/latest/map_filter.html" rel="nofollow noreferrer">map doc</a>. On my machine this is a tiny bit more efficient (~20% faster)</p>
python|arrays|python-3.x|function|numpy
2
352,275
58,883,903
Matplotlib charts are not lining up correctly over the xaxis
<p>I have the following code:</p> <pre><code>import pandas as pd from pandas import datetime from pandas import DataFrame as df import matplotlib from pandas_datareader import data as web import matplotlib.pyplot as plt import datetime start = datetime.date(2015,1,1) end = datetime.date.today() start1 = datetime.date...
<p>The problem is that you have missing dates that are different in the two datasets. You can solve it by "filling" the missing dates at the beginning. This is done with:</p> <pre class="lang-py prettyprint-override"><code># create index with all dates full_dates = pd.date_range(start, end) # fill missing dates with N...
python-3.x|pandas|matplotlib
1
352,276
58,847,381
Dimension Input Keras
<p>I've amended the code found <a href="https://github.com/sibyjackgrove/CNN-on-Wind-Power-Data/blob/master/CNN_on_power_data_with_Keras_and_Python_generator.ipynb" rel="nofollow noreferrer">here</a>. But i'm getting a dimension error in my in input, like below:</p> <blockquote> <p>ValueError: Error when checking in...
<p>In</p> <pre class="lang-py prettyprint-override"><code>tf.keras.layers.Input(shape=(2,24,1),name='InputLayer') </code></pre> <p>you're specifying that the inputs to your model, i.e. the first argument passed to <code>model.fit</code> should have shape <code>(?, 2, 24, 1)</code>, but that's not what you're passing....
python|tensorflow|keras|artificial-intelligence|dimensions
1
352,277
58,697,495
Pandas 'Int64' type is converted to an 'object' type after merge
<p>I noticed the following behaviour when working with <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html" rel="nofollow noreferrer">Int64</a>. Is there a way to avoid the type conversion and preserve the <code>Int64</code> type post merge?</p> <pre><code>df1 = pd.DataFrame(data={'col1': ...
<p>It comes from needing to reindex df2 (base dataframe) needing to reindex to match df1 (merging dataframe). It probably should behave as you expect but is an edge case from using the pandas Int64Dtype type instead of python int type.</p> <p>When preforming the merge, this reindexing is called:</p> <pre><code>&gt; /ho...
python|pandas|dataframe
0
352,278
58,618,123
Keras Layer Build Error: build() takes 1 Positional Argument but two were given
<p>I have the following error in this simple layer:</p> <pre><code>class MyLayer(Layer): def __init__(self): super(MyLayer, self).__init__() def build(self): # Create a trainable weight variable for this layer. self.kernel = self.add_weight(name='kernel', shape=(1) ...
<p>Each layer in a Keras layer requires a <code>input_shape</code> argument. Add it to your <code>build()</code> method. </p>
python|tensorflow|keras|keras-layer|tf.keras
5
352,279
58,688,407
getting the previous and next value from a dataframe and add a new column
<p>I am new to python and pandas. Here I have a dataframe which is like ,</p> <pre><code> Id Offset feature 0 0 2 0 5 2 0 11 0 0 21 22 0 28 22 1 32 0 1 38 ...
<p>You can use list comprehensions:</p> <pre><code>x = df['feature'].tolist() y = x[::-1] df['previous'] = [y[-i:][:3] for i in range(1, len(x)+1)] df['Next'] = [x[i: i + 3] for i in range(1, len(x) + 1)] df['previous'] = df['previous'].shift(1).where(df['feature'] == 0, '-') df['Next'] = df['Next'].where(df['feature...
python|python-3.x|pandas|numpy
0
352,280
70,256,003
How can I only train the classifier and freeze rest of the parameters in Pytorch?
<p>I have taken the pretrained model of MoviNet, I have changed the last layer.</p> <p>This is last parameters of pretrained model that I have taken;</p> <pre><code>classifier.0.conv_1.conv2d.weight : torch.Size([2048, 640, 1, 1]) classifier.0.conv_1.conv2d.bias : torch.Size([2048]) classifier.3.conv_1.conv2d.weigh...
<p>When creating your optimizer, only pass the parameters that you want to update during training. In your example, it could look something like:</p> <pre><code>optimizer = torch.optim.Adam(clfr.parameters()) </code></pre>
python|pytorch|torch
1
352,281
70,053,288
Loop through dataframe in python to select specific row
<p>I have a <strong>timeseries data</strong> of <strong>5864 ICU Patients</strong> and my dataframe is like this. Each row is the ICU stay of respective patient at a particular hour.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">HR</th> <th style="text-align: c...
<pre><code>for x in df['P_ID'].unique(): print(df.query('P_ID == @x and Sepsis == 1')['ICULOS'][0]) </code></pre>
python|pandas|dataframe|loops|for-loop
0
352,282
70,091,398
Python getting part of string based on condtion
<p>Hi I am pretty new to Python and is currently looking for a way to effectively get a part of a string from a column based on a condition.</p> <p>I currently have a column with the address. It looks something like this.</p> <pre><code>data = {'addr': ['Seoul Gangnam Apgujeong 38-5', 'Seoul Songpa Jamsil 40-1 5-1302',...
<p>You can use list comprehension with <code>split</code>, slicing, and <code>join</code>:</p> <pre class="lang-py prettyprint-override"><code>data = {'addr': ['Seoul Gangnam Apgujeong 38-5', 'Seoul Songpa Jamsil 40-1 5-1302', 'Jeju Jeju Aewol 31-5', 'Busan Haeuondae Centum 70-1 7-141']} output = {'addr': [' '.join(s.s...
python|pandas|string
1
352,283
70,203,067
pandas groupby concatination based on a condition
<p>I have a dataframe like below, and I am trying to join the names, when the class is non empty,</p> <pre><code>Name class score kumar &quot;&quot; &quot;&quot; ram 10 14 ravi &quot;&quot; &quot;&quot; tej &quot;&quot; &quot;&quot; om 12 15 </code></pre> <p>my desired output is,</p> ...
<p>You are correct to find blocks with <code>cumsum</code> on negate condition. Here however, you can reverse the series before cumsum, so blocks are count from bottom up:</p> <pre><code>blocks = df['score'].ne('&quot;&quot;')[::-1].cumsum() df.groupby(blocks).agg({ 'Name':''.join, 'class':'last', 'score':'...
python|pandas|group-by
2
352,284
70,069,207
Weird Discrepencies in Layer Shapes when Calling Model
<p>I am trying to use the output of a variational autoencoder to aid in classifying images. I have pre-trainned the autoencoder and am now trying to load the weights in another script to use the weights of the encoder model for prediction. I am having a weird error when calling the encoder that I cannot make sense of. ...
<p>I solved my issue. Long story short that I'm an idiot. I was passing in a numpy array that was (256,256,1) in size (note that the batch dimension was missing). Reshaping to (1, 256, 256, 1) solved my issue (note that the first 1 is the batch dimension)</p>
python|tensorflow|autoencoder
0
352,285
70,087,249
How to convert boolean pandas dataframe to square matrix dataframe
<p>I have a dataframe like this (boolean values)</p> <pre><code>a b c d count 1 0 1 0 196 0 1 0 1 110 0 1 0 0 17 0 0 1 0 10 0 0 0 0 9 </code></pre> <p>As you can, someone can be <strong>a</strong> and <strong>c</strong> // or <strong>b</strong> an...
<p>I got the answer by simply do a dot product.</p> <pre><code>df_transpose = df.transpose() count = df_transpose.dot(df) &gt; a b c d a 222 5 8 1 b 5 154 14 22 c 8 14 34 6 d 1 22 6 29 </code></pre>
python|pandas
0
352,286
70,173,423
Path column and name column need to be associated how to form such association?
<p>My issue right now is pretty simple i have the following dataset <a href="https://i.stack.imgur.com/RhKvP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RhKvP.png" alt="Dataset" /></a></p> <p>And i want the path column to be aligned to it is specific pokemon, so basically if the path ends up in a...
<p> In this case you should try to do a <a href="https://stackoverflow.com/questions/10383044/fuzzy-string-comparison">fuzzy string search</a>.</p> <pre><code>&gt;&gt;&gt; from fuzzywuzzy import fuzz &gt;&gt;&gt; from fuzzywuzzy import process &gt;&gt;&gt; &gt;&gt;&gt; name = df['Name'].tolist() &gt;&gt;&gt; paths = df...
python|pandas
1
352,287
70,273,453
Deleting rows in Pandas Dataframe, when column values match tuples in a list
<p>I have a data frame</p> <pre><code> index col1 col2 col3 0 1 3 5 1 12 7 21 ... ... ... ... </code></pre> <p>I want to delete some rows, with the criteria being that the values in col1 and col2 show up in a certain list. Let the list be <code>[(12,7),(100,34),...]</code>. In th...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.isin.html" rel="nofollow noreferrer"><code>Index.isin</code></a> for test <code>MultiIndex</code> created by both columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nof...
python|pandas|dataframe
3
352,288
70,166,709
Pandas create a column iteratively - increasing after specific threshold
<p>I have a simple table which the datetime is formatted correctly on.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Datetime</th> <th>Diff</th> </tr> </thead> <tbody> <tr> <td>2021-01-01 12:00:00</td> <td>0</td> </tr> <tr> <td>2021-01-01 12:02:00</td> <td>2</td> </tr> <tr> <td>2021-01-01...
<p>Since True and False values represent 1 and 0 when summed, you can use this to create a cumulative sum on a boolean column made by <code>df.Diff &gt; 7</code>:</p> <p><code>df['Batch'] = (df.Diff &gt; 7).cumsum()</code></p>
python|pandas|dataframe
3
352,289
70,041,841
DataFrame groupby 2 columns und count occurence in third
<p>I'm trying to group a DataFrame by two columns and count the difference occurence in the third column. What I've got so far is:</p> <pre><code>import pandas as pd df = pd.DataFrame({'colA': ['name1', 'name2', 'name2', 'name4', 'name2', 'name5'], 'colB': ['red', 'yellow', 'yellow', 'black', 'yellow', 'green'], 'colC...
<p>If I understand correctly you just need to group by 3 col A,B and C:</p> <pre><code>df_grouped = df.groupby([&quot;colA&quot;, &quot;colB&quot;,&quot;colC&quot;])[&quot;colC&quot;].count().reset_index(name=&quot;count&quot;) </code></pre> <pre><code>Output : &gt; colA colB colC count 0 name1 red val...
python|pandas|dataframe|group-by
2
352,290
70,158,416
Pandas Dataframe Getting a count of semi-unique values from columns in a CSV
<p>I don't think my title accurately conveys my question but I struggled on it for a bit. I have a range of CSV files. These files contain column names and values. My current code works exactly as I want it to, in that it groups the data by time and then gets me a count of uses per hour and revenue per hour. However I ...
<p>you can use regex to replace the common machine number identifier pattern to create a <code>machine_type</code> series which you can then use to aggregate on.</p> <p><code>df['Machine Type'] = df['Machine Name'].str.replace(' #[0-9]', '', regex=True)</code></p> <p>you can then group on the <code>Machine Type</code><...
python|pandas|dataframe
1
352,291
70,204,974
Combining Pandas DataFrame Columns with Alternate Spelling
<p>I have a DataFrame that was imported from a json file. Part of the data in the json file includes alternate spellings for some string/categorical properties resulting in columns with similar names where values are populated in one, the other, or neither. I want to be able to combine the columns with alternate spelli...
<p>I'd use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isna.html" rel="nofollow noreferrer"><code>.isna()</code></a> for boolean access:</p> <pre><code>df_is.loc[df_is.C4.isna(), &quot;C4&quot;] = df_is.c4 </code></pre> <p>or (in case the column names involved contain blanks)</p> <pre><code>df_i...
python|pandas|dataframe|jupyter-notebook
1
352,292
70,338,539
Tensorflow Reducing Batch dimension | timeseries_dataset_from_array
<p>I am trying to get <code>(None,7)</code> shape from <code>tf.keras.utils.timeseries_dataset_from_array</code> but it returns shape <code>(None, None,7)</code>.</p> <p>tensorflow don't allow to set <code>batch_size=None</code> or <code>batch_size=0</code> to reduce the batch_size dimension.</p> <p>So is there any way...
<p>Try to make 1 batch and get the size of it to be 1, then use <a href="https://www.tensorflow.org/api_docs/python/tf/squeeze" rel="nofollow noreferrer">tf.squeeze</a> to remove that size 1 dimension? Make sure you specify the correct axis.</p>
python|tensorflow|keras
0
352,293
70,040,973
Find how many grid cells contain x,y points
<p>So, I have written the code shown below:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.random.randint(-960,960,15) y = np.random.randint(-540,540,15) fig, ax = plt.subplots(figsize=(20, 11)) ax.scatter(x, y, marker='o', color='red', alpha=0.8) img = plt.imread(scene_folder) plt.imshow(img...
<p>It looks like you need to list coordinates of all the pixels:</p> <pre><code>extent = [-960, 960, -540, 540] p1, p2 = 8, 6 x1 = p1*(x-extent[0])//(extent[1]-extent[0]) y1 = p2*(y-extent[2])//(extent[3]-extent[2]) &gt;&gt;&gt; np.transpose([x1, y1]) array([[4, 2], [6, 0], [2, 2], [7, 0], [...
python|arrays|numpy|2d
0
352,294
70,070,972
How to exclude a category from a mask
<pre><code>sns.histplot(data=DS1[(DS1.TuWgt&lt;30000) &amp; (DS1.TuType!=1001)], x=&quot;TuWgt&quot;,hue=&quot;TuType&quot;,multiple=&quot;stack&quot;) </code></pre> <p>So this is the line I'm trying to run. TuType is a category.</p> <p>TypeError: unsupported operand type(s) for &amp;: 'int' and 'Categorical'</p>
<p>The <code>&amp;</code> operator has a higher priority than the <code>&lt;</code> and <code>!=</code> operators, so your code is being executed like this:</p> <pre class="lang-py prettyprint-override"><code>sns.histplot(data=DS1[DS1.TuWgt &lt; (30000 &amp; DS1.TuType) != 1001], x=&quot;TuWgt&quot;,hue=&quot;TuType&qu...
python|pandas|mask
1
352,295
70,159,199
IsIn for python dataframe
<p>3 of the columns of my dataframe involve medical specialties, I am trying to do a isin on if column1 is in column2, its true... if column2 isin column 3 its true. so the expression would be true. I am also factoring out for nulls, and if everything matches. Swapping the Or between the first line to and &amp; either ...
<p>Try with <code>apply</code> and <code>in</code>:</p> <pre><code>dfMaster['SPECIALTY Okay?'] = (np.where(dfMaster.apply(lambda x: (x[&quot;Specialty_BE&quot;] in x[&quot;Specialty_AM&quot;]) and (x[&quot;Specialty_AM&quot;] in x[&quot;Specialty_M&quot;]), ...
python|pandas
0
352,296
70,256,360
Read single column from csv file and rename with the name of the text file
<p>I'm using a for loop to cycle through numerous text files, select a single column from the text files (named ppm), and append these columns to a new data frame. I'd like the columns in the new data frame to have the name of the text file but I'm not sure how to do this..</p> <p>My code is:</p> <pre><code>all_files=g...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> outside loops with append DataFrames to list with rename column <code>ppm</code>:</p> <pre><code>all_files=glob.glob(os.path.join(path,&quot;*.txt&quot;)) dfs = [] for file in...
python|pandas|dataframe
1
352,297
70,073,310
Return the indices of "false" values in a boolean array
<p>I feel like this is a really simple question but I can't find the solution.</p> <p>Given a boolean array of true/false values, I need the output of all the indices with the value &quot;false&quot;. I have a way to do this for true:</p> <p>test = [ True False True True]</p> <pre><code>test1 = np.where(test)[0] </co...
<p>Use <code>np.where(~test)</code> instead of <code>np.where(test)</code>.</p>
python|numpy|boolean
7
352,298
70,047,710
RuntimeError: Sizes of tensors must match except in dimension 2. Expected size 32 but got size 1 for tensor number 3 in the list
<p>I am running EDITNTS: <a href="https://github.com/yuedongP/EditNTS" rel="nofollow noreferrer">https://github.com/yuedongP/EditNTS</a> without teacher forcing on some training data. When I run main.py I get the error:</p> <pre><code> File &quot;/home/jba5337/work/ds440w/EditNTS-Google/editnts.py&quot;, line 252, in ...
<p>You can do something like this to change the channels order</p> <pre><code>X_train = X_train.permute(1,0,2) </code></pre>
python|tensorflow|torch|simplification
0
352,299
70,135,365
Python : How to return most occurrent value on each row depend on fix columns?
<p>I have a dataframe as below:</p> <pre><code>import pandas as pd # intialise data of lists. data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Book1':[20, 21, 19, 18], 'Book2':[20,'', 12, 20], 'Book3':[31, 21, 17, 16], 'Book4':[31, 19, 18, 16]} # Create DataFrame df = pd.DataFrame(data...
<p>Use <code>value_counts</code>:</p> <pre class="lang-py prettyprint-override"><code>max_val = lambda x: x.value_counts().index[0] \ if x.value_counts().iloc[0] &gt; 1 else 'Mix' df['Output'] = df.filter(like='Book').apply(max_val, axis=1) print(df) # Output: Name Book1 Book2 Book3 Boo...
python|pandas|numpy
9