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
374,800
49,202,426
Adding tuple elements, parsed into pandas DataFrame
<p>I have several Python lists of tuples:</p> <pre><code>[(0, 61), (1, 30), (5, 198), (4, 61), (0, 30), (5, 200)] [(1, 72), (2, 19), (3, 31), (4, 192), (6, 72), (5, 75)] [(3, 12), (0, 51)] ... </code></pre> <p>Each of these tuples are created such that these are in the format <code>(key, value)</code>:</p> <p>There ...
<p>Consider your data in a name <code>tups</code></p> <pre><code>tups = [ [(0, 61), (1, 30), (5, 198), (4, 61), (0, 30), (5, 200)], [(1, 72), (2, 19), (3, 31), (4, 192), (6, 72), (5, 75)], [(3, 12), (0, 51)] ] </code></pre> <hr> <p><strong>Option 0</strong><br> Using <code>np.bincount</code> and crazy ma...
python|pandas
4
374,801
49,296,114
Convert list of strings to columns with custom rules pandas
<p>I have list of string within my dataframe columns:</p> <pre><code>data = [{'column A': '3 item X; 4 item Y; item E of size 7', 'column B': 'item I of size 10; item X has 5 specificities; characteristic W'}, {'column A': '13 item X; item F of size 0; 9 item Y', 'column B': 'item J of size 11; item Y has 8 sp...
<p>Don't go for complex functions pandas has great string manipulation functions. Check this code to get the desired output.</p> <pre><code>data = [{'column A': '3 item X; 4 item Y; item E of size 7', 'column B': 'item I of size 10; item X has 5 specificities; characteristic W'}, {'column A': '13 item X; item F...
python|pandas
0
374,802
49,098,712
States in the tensorflow static rnn
<p>I'm trying to work with RNN using Tensorflow. I use the following function from this <a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/recurrent_network.py" rel="nofollow noreferrer">repos</a>:</p> <pre><code>def RNN(x, weights, biases): # Prepare data shape to...
<p>To confirm the discussion in the comments: when constructing a static RNN using <code>BasicLSTMCell</code>, <code>state</code> is a two-tuple of <code>(c, h)</code>, where <code>c</code> is the final cell state and <code>h</code> is the final hidden state. The final cell hidden state is in fact equal to the final o...
tensorflow|recurrent-neural-network
1
374,803
48,999,887
tensorflow next_batch vs custom next_batch?
<p>I'm trying to write a function that can get batches of data, similar to tensorflow's next_batch.</p> <p>next_batch can be seen here: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorfl...
<p>Direct cp from my comment but...</p> <p>As far as I can tell, your code does almost exactly the same thing as the next_batch function from the mnist example. The only differences being that the DataSet class in the example flattens input data from (x,y,z,1) into (x,y*z) and then also normalizes all the data from [0...
python|tensorflow|tensorflow-datasets
0
374,804
49,068,574
Sklearn, Gaussian Process: XA and XB must have the same number of columns
<p>I am quite new to python and interesting in doing Gaussian regression. I am under py3.6 and SKlearn 0.19.</p> <p>I have simple code and I get an error about the dimension of the vectors in cdist called by predict. I understand there's something bad in my input. But I do not see why...</p> <p>I looked for example o...
<p>I hav simply copy paste a code and did something stupid:</p> <pre><code>X_train, v1 = make_regression() </code></pre> <p>Just had to remove it. </p>
python|pandas|numpy|machine-learning|scikit-learn
1
374,805
48,898,406
compress list of numbers into unique non overlapping time ranges using python
<p>I'm from biology and very new to python and ML, the lab has a blackbox ML model which outputs a sequence like this : </p> <pre><code>Predictions = [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,1,0] </code></pre> <p>each value represents a predicted time frame of...
<p>You can iterate through the list and create a range when you detect a change. You'll also need to account for the final range when using this method. Might not be super clean but should be effective.</p> <pre><code>current_time = 0 range_start = 0 current_value = predictions[0] ranges = [] for p in predictions: i...
python|algorithm|python-2.7|numpy
4
374,806
49,120,232
Add a datetime column to multiple dataframes in Pandas
<p>I'm trying to loop through a list of dataframes and append a datetime column to each. I've tried the following to no avail:</p> <pre><code>dfs = ['nov22_2017', 'nov29_2017', 'dec06_2017','dec13_2017', 'dec20_2017', 'dec27_2017', 'jan03_2018', 'jan10_2018'] sheets = ['11.22.17', '11.29.17', '12.6.17', '12.13...
<p>You could make this part of your list comprehension:</p> <pre><code># assign each df to a variable dfs = [nrc_xl.parse(sheet, usecols = 10).assign(date=datetimes[i]) \ for i, sheet in enumerate(sheets)] </code></pre>
python|pandas|dataframe
0
374,807
49,337,960
SKLearn NMF Vs Custom NMF
<p>I am trying to build a recommendation system using Non-negative matrix factorization. Using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.NMF.html" rel="noreferrer">scikit-learn NMF</a> as the model, I fit my data, resulting in a certain loss(i.e., reconstruction error). Then I gene...
<p>The choice of the optimizer has a big impact on the quality of the training. Some very simple models (I'm thinking of GloVe for example) do work with some optimizer and not at all with some others. Then, to answer your questions:</p> <ol> <li><blockquote> <p>how can I determine which are the right ones ?</p> </bl...
python|tensorflow|scikit-learn|recommendation-engine|nmf
2
374,808
48,929,508
numpy pad a sequence instead of constant values
<p>I am trying to pad a numpy array with a sequence <code>[0, 1]</code> along each row. So for example if I have an array as:</p> <pre><code>x = np.random.rand(2, 4) array([[0.51352468, 0.4274193 , 0.11244252, 0.56787658], [0.37855923, 0.80976327, 0.0290558 , 0.87585656]]) </code></pre> <p>After the padding o...
<p>Perhaps it would be simpler (to read) if you simply allocate a 2D array of zeros, assign ones to the last row, and copy <code>x</code> into the padded array:</p> <pre><code>import numpy as np def pad(x): nrows, ncols = x.shape padded = np.zeros((4, ncols)) padded[-1, :] = 1 padded[:nrows, :] = x ...
python|numpy
2
374,809
49,090,643
How can I use numpy create list out of another list with modified elements
<p>I am not new at all to Python programming, but I am completely new to the Numpy module. I need to use this module for it's very fast and efficient.</p> <p>Say I have an array called <code>noise</code> which is defined as follows:</p> <pre><code>noise = [[uniform(0, 1) for i in range(size)] for j in range(size)] </...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html" rel="nofollow noreferrer"><code>np.fromfunction</code></a> for this:</p> <pre><code>modified_noise = np.fromfunction(lambda i, j: function(i, j), (size, size), dtype=float) </code></pre> <p>This constructs an array b...
python|arrays|performance|numpy|list-comprehension
2
374,810
49,054,126
Creating a 3D numpy array of from a prexisting iterable that has the appropriate shape
<p>I have an array of M samples and each sample has a shape of: (11, 64) So theoretically my main array should have a shape of (M, 11, 64) but all I get is (m,) as the shape</p> <p>I tried np.array(main_array) but that doesn't do anything. I was wondering if there was anyway to make numpy realize the dimensionality o...
<p><code>np.array</code> won't 'flatten' an object dtype array. You have to use some sort of concatenate.</p> <p>Make an array of arrays. Notice that I have play some games to get around <code>np.array's</code> preference to create a 3d array:</p> <pre><code>In [5]: arr = np.empty((3,), dtype=object) In [6]: arr Ou...
python|arrays|pandas|numpy|multidimensional-array
1
374,811
58,692,359
Training a model with single output on multiple losses keras
<p>I am building an image segmentation model using keras and I want to train my model on multiple loss functions. I have seen <a href="https://gaborvecsei.wordpress.com/2018/10/15/implement-loss-functions-inside-keras-models/" rel="nofollow noreferrer">this</a> link but I am looking for a simpler and straight-forward s...
<p>This is just an example from <a href="https://keras.io/api/losses/#creating-custom-losses" rel="nofollow noreferrer">here</a>. You could play around with it.</p> <pre><code>def custom_losses(y_true, y_pred): alpha = 0.6 squared_difference = tf.square(y_true - y_pred) Huber = tf.keras.losses.huber(y_true,...
python|tensorflow|keras|deep-learning|loss-function
0
374,812
58,789,924
Cant assign value to cell in multiindex dataframe (assigning to copy / slice of df?)
<p>I am trying to assign a value (mean of values in another column) to a cell in a multi-index Pandas dataframe over which I iterate to calculate means over a moving window in a different column. But, when I try to assign the value it doesn't change. </p> <p>I am not used to working with multi-indexes and have solved ...
<p>I think it is a easy as setting last line to:</p> <pre><code>df.loc[(country, t), new_indicator] = mean </code></pre>
python-3.x|pandas|multi-index
2
374,813
58,702,476
Tensorflow saved_model.load issue
<p>I'm trying to just be able to load a tensorflow model from a checkpoint, but for some reason I'm getting the error: "The passed save_path is not a valid checkpoint: /path/variables/variables"</p> <p>I noticed that it adds an extra "variables" string to the path, for some reason. Is that correct? My directory file ...
<blockquote> <p>I noticed that it adds an extra "variables" string to the path, for some reason. Is that correct?</p> </blockquote> <p>Yes, it correct. Please refer below code, here model saved at <code>./savedmodel/</code>, where as it loaded from <code>./savedmodel/variables/variables</code>.</p> <p>I am able t...
python|tensorflow
0
374,814
58,864,468
Python pandas modify dataframe according to date and column adding hours
<p>I have the following dataframe:</p> <pre><code>;h0;h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15;h16;h17;h18;h19;h20;h21;h22;h23 2017-01-01;52.72248155184351;49.2949899678983;46.57492391198069;44.087373768731766;44.14801243124734;42.17606224526609;43.18529986793594;39.58391124876044;41.63499969987035;41.405944...
<p>Turn columns names into a new column, turn to hours and use pd.to_datetime</p> <pre><code>s = df.stack() pd.concat([ pd.to_datetime(s.reset_index() \ .replace({'level_1': r'h(\d+)'}, {'level_1': '\\1:00'}, regex=True) \ [['level_0','level_1']].apply(' '.join, axis=1)...
python|pandas|sorting|date|dataframe
0
374,815
58,923,848
TensorFlow Root being imported and many methods not registering
<p>I've spent the last few hours trying to install TensorFlow (non-GPU) and it still not working. I'm using Visual Studio 2019. I have used an admin CMD to <code>pip install tensorflow</code>, and it was successful (or seems so). I can see in <code>%appdata%\..\Local\Programs\Python\Python37\Lib\site-packages\</code> t...
<p>I deleted and remade the VS solution. It seems Visual Studio was not updating its packages or something. </p>
python|python-3.x|visual-studio|tensorflow|visual-studio-2019
0
374,816
59,016,748
Append a dataframe with a column of another dataframe and a constant with Python
<p>Let's take these two dataframes :</p> <pre><code>df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB')) df1 A B 0 1 2 1 3 4 df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('CD')) df2 C D 0 5 6 1 7 8 </code></pre> <p>I would like to add column C of df2 to column A of df1, and to put 9 in column...
<pre><code>df1.append(df2.rename(columns={'C':'A'}).drop(columns='D'), ignore_index=True) \ .fillna(9).astype(int) A B 0 1 2 1 3 4 2 5 9 3 7 9 </code></pre>
python|pandas|dataframe|append
1
374,817
58,615,611
How do I use my own Hand-Drawn Image in TensorFlow Number Recognition
<p>I have some basic Python code to create a very basic neural network that classifies hand-drawn numbers from the MNIST dataset.</p> <p>The network is working and I would like to make a prediction against a hand drawn image that is not part of the MNIST dataset.</p> <p><strong>Here is my code:</strong></p> <pre><co...
<p>Since your model is trained on black and white images, you only have one channel and you need to convert your image to greyscale:</p> <pre><code>import numpy as np import cv2 img = cv2.imread('test_image.jpg') img = cv2.resize(img, (28,28)) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = np.reshape(img, [1,28,28...
python|tensorflow|machine-learning|keras|deep-learning
1
374,818
58,847,405
Drop nan rows unless string value in separate column - Pandas
<p>I want to drop rows containing <code>NaN</code> values except if a separate column contains a specific string. Using the <code>df</code> below, I want to drop rows if <code>NaN</code> in <code>Code2, Code3</code> unless the string A is in <code>Code1</code>.</p> <pre><code>df = pd.DataFrame({ 'Code1' : [...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.notna.html" rel="nofollow noreferrer"><code>DataFrame.notna</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>DataFrame.all</code></a> to ...
python|pandas
3
374,819
58,644,850
How to sum multiple values in a dataframe column, if they are corresponding to 1 value in an other column
<p>I have a data frame like this:</p> <pre><code>Code Group Name Number ABC Group_1_ABC Mike 40 Amber 60 Group_2_ABC Rachel 90 XYZ Group_1_XYZ Bob 30 Peter 75 Nikki 55 Group_2_XYZ Julia 23 Ross 80 LMN ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> by first level or by level name <code>Code</code>:</p> <pre><code>df['Percentage']= (df['Number']/df.groupby(level=0)['Number'].transform('s...
python|pandas|sum|multiple-columns
1
374,820
58,905,628
heatmap hashtag and location in python pandas dataframe
<p>I have Pandas Dataframe as below</p> <p><a href="https://i.stack.imgur.com/VE9yx.png" rel="nofollow noreferrer">newdf[['name_left','text']]</a></p> <p>from each text column I would like to extract every hashtag and create heatmap with name_left on X axis and extracted hashtag on Y axis</p> <p>I can perform count ...
<p>I think what you want is this</p> <pre><code> import pandas as pd df = pd.DataFrame({'name_left': ['Canada', 'Peru'], 'text': ['asdf #broccoli sadfsd #milk', 'sdfsd #king bbas #toast']}) df = df.groupby(['name_left']).apply(lambda x: x.text.str.extractall(r'(#\w+)').reset_index(level=0).drop_du...
python|pandas|heatmap
0
374,821
58,763,795
Setting subset of a pandas DataFrame by a DataFrame
<p>I feel like this question has been asked a millions times before, but I just can't seem to get it to work or find a SO-post answering my question.</p> <p>So I am selecting a subset of a pandas DataFrame and want to change these values individually.</p> <p>I am subselecting my DataFrame like this:</p> <pre class="...
<p>Just add <code>.values</code> or <code>.to_numpy()</code> if using pandas v 0.24 +</p> <pre><code>df1.loc[df1['cars_per_year'].isnull(),['cars_per_year','some_other_value']] = df2.values Name Age Amount_of_cars cars_per_year some_other_value 0 Alex 10 0 0.000000 ...
python|pandas|dataframe
2
374,822
58,837,565
Pandas: Remove Column Based on Threshold Criteria
<p>I have to solve this problem: Objective: Drops columns most of whose rows missing <strong>Inputs</strong>: 1. Dataframe df: Pandas dataframe 2. threshold: Determines which columns will be dropped. If threshold is .9, the columns with 90% missing value will be dropped <strong>Outputs</strong>: 1. Dataframe df with dr...
<p>I think you need to change from </p> <p><code>df = df.drop(i)</code></p> <p>to </p> <p><code>df = df.drop(i, axis=1)</code></p> <p>So you account for columns instead of rows, which is the default option. See here for the same error <a href="https://stackoverflow.com/a/44931865/5184851">https://stackoverflow.com/...
python|excel|pandas|numpy|dataframe
0
374,823
58,740,076
Plot a table from selected rows in DataFrame
<p>I have a dataframe that looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Institution':['Uni1', 'Uni2', 'Uni3', 'Uni1', 'Uni2', 'Uni3'], 'Year': [2018, 2018, 2018, 2019, 2019, 2019], 'Value': [1000000, 2000000, 250000, 2300000, 3000000, 90000], ...
<p>To plot Values column:</p> <pre><code>plt.table(cellText = df[['Value']].values.T) </code></pre> <p>keep in mind that <code>df[['Value']]</code> return a DataFrame but <code>df['Value']</code> return a Series.</p> <p>creating rows for each year using <a href="https://pandas.pydata.org/pandas-docs/stable/reference...
python-3.x|pandas|matplotlib
1
374,824
58,876,412
Tree structured input in keras/tensorflow
<p>For some school project I am trying to implement a tree convolution as described in <em>"Convolutional Neural Networks over Tree Structures for Programming Language Processing" Lili Mou, et al.</em></p> <p><strong>Goal</strong></p> <p>Basically, the outcome should be a neural network. The samples to this network a...
<p>Tensorflow used to have a decision tree implementation. You can see the data structures (variables) it used here: <a href="https://github.com/tensorflow/tensorflow/blob/v0.10.0rc0/tensorflow/contrib/tensor_forest/python/tensor_forest.py#L155" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/v0...
python|tensorflow|keras|deep-learning|tree
1
374,825
58,891,834
Passing random seed to numpy random.choice function
<p>Let's say I have an function that takes a <code>random_state</code> argument to ensure replicability</p> <pre><code>def replicable_function(random_seed): choice = np.random.choice(X, 10) #do more stuff here with choice return f(choice) </code></pre> <p>These are my two requirements:</p> <ol> <li>Passi...
<p>I figured this answer right after asking it here. I'm not sure it's the best solution though, so I'm happy to receive other suggestions.</p> <p>I ended up using a utility function from <code>sklearn</code> that, if needed, turns an integer input into a <code>RandomState</code> instance.</p> <pre><code>def check_ra...
numpy|random-seed
0
374,826
59,003,985
Why is the Pytorch Dropout layer affecting all values, not only the ones set to zero?
<p>The dropout layer from Pytorch changes the values that are not set to zero. Using Pytorch's documentation example: (<a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Dropout" rel="nofollow noreferrer">source</a>):</p> <pre class="lang-py prettyprint-override"><code>import torch import torch.nn as nn m = n...
<p>It is how the dropout regularization works. After a dropout the values are divided by the keeping probability (in this case 0.5). </p> <p>Since PyTorch Dropout function receives the probability of zeroing a neuron as input, if you use <code>nn.Dropout(p=0.2)</code> that means it has 0.8 chance of keeping. so the va...
python|pytorch|tensor|dropout
6
374,827
58,618,885
Unable to use resample.ohlc() method - DataError: No numeric types to aggregate
<p>I am receiving stock ticks second-wise and I am storing them in a dataframe. I need to resample them to get the ohlc value for a minute. Here is my code:</p> <pre><code> def on_ticks(ws, ticks): global time_second, df_cols, tick_cols, data_frame for company_data in ticks: ltp = company_data['last...
<p>Problem is there is no numeric column, only datetimes in <code>Timestamp</code>. </p> <hr> <p>I think you can create <code>DatetimeIndex</code> and then convert all columns to <code>float</code>s, also is necessary remove parameter <code>on</code> in <code>resample</code>:</p> <pre><code>resamp_df = data_frame.se...
python|pandas|dataframe|resampling|ohlc
1
374,828
59,022,664
Combining two dataframes based on specific column
<p>I'm attempting to combine different dataframes for NBA data. My first dataframe is from a <a href="https://www.basketball-reference.com/leagues/NBA_2019_per_poss.html" rel="nofollow noreferrer">basketball-reference</a> page and my second dataframe is from a <a href="https://projects.fivethirtyeight.com/2020-nba-play...
<p>I think you probably want to use pandas .merge().</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'player': ['foo', 'bar', 'baz', 'foo', 'bar', 'foo'], 'value': [1, 2, 3, 5, 7, 9]}) df2 = pd.DataFrame({'player': ['foo', 'bar', 'baz', 'foo'], 'value': [5, 6, 7, 8]}) merged_df...
python|pandas|dataframe
0
374,829
59,006,554
Webscraping and decoding string into pandas DF
<p>I'm webscraping and would like to have a Pandas dataframe as a result of my content scraping. I'm able to get an <code>UTF-8</code> string that I'd like to read as a Pandas dataframe, but I'm not sure how to do it and I'd like to avoid outputting to CSV and reading it back. How would I do it?</p> <p>E.g.</p> <pre>...
<p>You can use pythons csv module to read and spit your csv. It will take care of things like commas being inside quoted strings and know not to split those. below is a small example using your input string. As you will see in the example below the field <code>protein stabilization, positive</code> doesn't get split in...
python|python-3.x|pandas|web-scraping|robobrowser
1
374,830
58,909,918
Can't Install Python Pandas in 3.6.6
<p>I am Mac user and trying to install Pandas in Python 3.6.6. to use in IDLE / VS Code to do my work.</p> <pre><code>Hasans-MacBook-Pro:~ hasan-macbookpro$ python3 --version Python 3.6.6 Hasans-MacBook-Pro:~ hasan-macbookpro$ </code></pre> <p>But when i run the <code>pip install pandas</code> it download it in Pytho...
<p>try <code>pip3 install pandas</code> to specify it for python3.</p>
python-3.x|pandas
0
374,831
58,981,134
Creating a variable conditional to the value of another variable in Python
<p>I'm trying to generate variable which is value depend on the value of another variable. My dataset is <code>urban_classification</code> and I am trying to create the variable <code>URBRUR</code> based on the value of the variable <code>prc_urbain</code>. This is my code:</p> <pre><code>if urban_classification.prc_u...
<p>The error message:</p> <blockquote> <p>The truth value of a Series is ambiguous.</p> </blockquote> <p>comes from </p> <pre><code>if urban_classification.prc_urbain&gt;0.5 : </code></pre> <p>because <code>urban_classification.prc_urbain</code> is a pd.Series, hence <code>urban_classification.prc_urbain&gt;0.5<...
python|pandas
0
374,832
58,629,183
How can I take an input 'n' to define a matrix of order n in python?
<pre><code> num_array = list() num = input("Enter how many elements you want:") print('Enter numbers in array: ') for i in range(int(num)): n=input("num :") num_array.append(int(n)) print('ARRAY: ',num_array) </code></pre> <p>this one was there but it's not gonna give me matrix of or...
<p>I think if you want a matrix representation, you should go with a list of lists. You only input n numbers, but for a matrix you need n*n numbers. Do that with a second for loop like so:</p> <pre><code># matrix is gonna be a list of lists num_array = list() num = input("Enter how many elements you want:") print('E...
python|arrays|numpy|matrix|input
0
374,833
58,914,513
Error while converting a frozen.pb file to tflite format
<pre><code>tflite_convert --output_file=./graph.tflite --graph_def_file=output_graph_frozen.pb --input_arrays=IteratorV2 --output_arrays=linear/head/predictions/probabilities </code></pre> <p>Traceback (most recent call last): File "/usr/local/bin/tflite_convert", line 11, in sys.exit(main()) File "/usr...
<p>what is the purpose for setting the "input_arrays" and "output_arrays"?</p> <p>In the most simple case, you can just do </p> <pre><code>converter = tf.lite.TFLiteConverter.from_saved_model(export_dir) tflite_model = converter.convert() </code></pre> <p>as documented at <a href="https://www.tensorflow.org/lite/con...
tensorflow|tensorflow-lite
0
374,834
58,705,410
how to set session property when executing pd.to_sql? {error:"Required field 'numDVs' is unset! }
<p>there is issue when insert dataframe data to presto db.</p> <p>error message is</p> <pre><code>{'message': "Required field 'numDVs' is unset! Struct:LongColumnStatsData(lowValue:0, highValue:2, numNulls:0, numDVs:0), 'errorCode': 16777216, 'errorName': 'HIVE_METASTORE_ERROR', 'errorType': 'EXTERNAL' ..." </code>...
<p>We can set session properties by <code>session_props</code> as below.</p> <pre class="lang-py prettyprint-override"><code>from pyhive import presto cursor = presto.connect('localhost', session_props={'hive.collect_column_statistics_on_write': 'false'}).cursor() </code></pre>
python|pandas|sqlalchemy|presto
2
374,835
58,659,212
Specifying a merge function in pandas?
<p>Can a merge criteria function be specified in pandas?</p> <p>So instead of just matching two fields, specifying a function that will return true or false to determine if _merge is ‘both’ or the alternatives?</p>
<p>If I understand your question correctly, you can do this:</p> <pre><code>pd.merge(df1,df2, on = 'your_var' how = 'outer', indicator = True) </code></pre> <p>You can then just look at _merge variable and it will show.</p>
python-3.x|pandas|merge
0
374,836
58,637,390
Withou onnx, how to convert a pytorch model into a tensorflow model manually?
<p>Since ONNX supports limited models, I tried to do this conversion by assigning parameters directly, but the gained tensorflow model failed to show the desired accuracy. Details are described as follows:</p> <ol> <li>The source model is Lenet trained on MNIST dataset.</li> <li>I firstly extracted each module and its...
<p>As the comment by jodag mentioned, there are many differences between operator representations in Tensorflow and PyTorch that might cause discrepancies in your workflow.</p> <p>We would recommend using the following method:</p> <ol> <li>Use the <a href="https://pytorch.org/tutorials/advanced/super_resolution_with_...
tensorflow|pytorch|exchange-server|onnx
2
374,837
58,620,552
tf.reshape is not giving ?(None) for first element
<p>I am new to tensorflow, I have tensor like below,</p> <pre><code>a = tf.constant([[1, 2, 3], [4, 5, 6]]) </code></pre> <p>Output of <code>a.shape</code> is </p> <blockquote> <p>TensorShape([Dimension(2), Dimension(3)])</p> </blockquote> <p>For my computational process I want to reshape the tensor to <code>(?, ...
<p>The "problem" is TensorFlow does as much shape inference as it can, which is generally something good, but it makes it more complicated if you explicitly want to have a <code>None</code> dimension. Not an ideal solution, but one possible workaround is to use a <a href="https://www.tensorflow.org/versions/r1.15/api_d...
python|python-3.x|tensorflow
1
374,838
58,811,263
How to update the Index of df with a new Index?
<p>I am currently having one df which has an incomplete Index. like this:</p> <pre><code>Idx bar baz zoo 001 A 1 x 003 B 2 y 005 C 3 z 007 A 4 q 008 B 5 w 009 C 6 t </code></pre> <p>I have the complete <code>Index([001, 002, ...... 010])</code>. Would like to how t...
<p>You can try with <code>reindex</code></p> <pre><code>df=df.reindex(completeIndex) </code></pre>
python|pandas|dataframe
2
374,839
58,761,791
Python ingestion of csv files
<p>I am trying to ingest daily csv data into Python. I have different files such as follows for each day.I need help in appending two columns where the values from the columns are from the file name, for eg first column should take the value before '_' and the second column takes the date part from the file name.</p> ...
<p>Try this</p> <pre><code>path = "C:\xyz\Files\ETL\Dashboard" files = list(filter(lambda x: '.csv' in x, os.listdir('path'))) for file in files: pre,post = file.split("_") post = post.split(".")[0] dfn = pd.read_csv(f"{path}/{file}", skiprows = 17) # assume your inital values for column 0 and 1 i...
python-3.x|pandas|automation
0
374,840
58,655,860
Creating a loop of 12 hours in dataframe with timestamp index
<pre><code>df['index_day'] = df.index.floor('d') </code></pre> <p>my dataframe is <code>df.head</code></p> <pre><code> index_day P2_Qa ... P2_Qcon P2_m 2019-01-10 17:00:00 2019-01-10 93.599342 ... 107.673342 14.962424 2019-01-10 17:01:00 2019-01-10 90.833884 ... 104.658384 ...
<p>I think you can filter first by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.between_time.html" rel="nofollow noreferrer"><code>DataFrame.between_time</code></a> only for nights and then loop by <code>12H</code> with <code>base=6</code>:</p> <pre><code>rng = pd.date_range('201...
python-3.x|pandas|loops|datetime|timestamp
0
374,841
58,976,313
How to fix: AttributeError: module 'tensorflow' has no attribute 'contrib'
<p>I'm training a LSTM and I'm defining parameters and regression layer. I get the error in the title with this code:</p> <pre><code> lstm_cells = [ tf.contrib.rnn.LSTMCell(num_units=num_nodes[li], state_is_tuple=True, initializer= tf.contrib.layers.xavier_in...
<p>This error occurs because the <code>contrib</code> module has been removed from version 2 of tensorflow. There are two solutions to this problem:</p> <ol> <li><p>You can delete the current package and install one of the Series 1 versions.</p> </li> <li><p>You can use this command, which is also compatible with the v...
python-3.x|tensorflow|tensorflow2.0
3
374,842
58,718,365
Fast way to convert upper triangular matrix into symmetric matrix
<p>I have an upper-triangular matrix of <code>np.float64</code> values, like this:</p> <pre class="lang-py prettyprint-override"><code>array([[ 1., 2., 3., 4.], [ 0., 5., 6., 7.], [ 0., 0., 8., 9.], [ 0., 0., 0., 10.]]) </code></pre> <p>I would like to convert this into the correspondi...
<p><code>np.where</code> seems quite fast in the out-of-place, no-cache scenario:</p> <pre><code>np.where(ut,ut,ut.T) </code></pre> <p>On my laptop:</p> <pre><code>timeit(lambda:np.where(ut,ut,ut.T)) # 1.909718865994364 </code></pre> <p>If you have pythran installed you can speed this up 3 times with near zero effo...
python|numpy|optimization
5
374,843
58,937,277
Pandas.ExcelWriter KeyError when using writer.sheets method
<p>Please help, I don't know why this error is happening. I have used this code previously with no issues. I hope it's not something stupid. Always appreciate the help. </p> <p>Versions:</p> <p>python 3.6</p> <p>pd 0.23.0</p> <p>xlsxwriter 1.0.4</p> <pre><code>writer = pd.ExcelWriter('Output.xlsx', engine='xlsxwri...
<p>You didn't create a Sheet 1. </p> <p>from <a href="https://xlsxwriter.readthedocs.io/working_with_pandas.html" rel="noreferrer">here</a> there's an example:</p> <pre><code>import pandas as pd # Create a Pandas dataframe from the data. df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) # Create a Pandas Ex...
python|pandas|xlsxwriter
7
374,844
58,708,732
Loop through the columns and avoid IndexError
<p>Given sample data set (real data has <code>(931, 674)</code>):</p> <pre><code>12_longitude_1 12_latitude_1 14_longitude_2 14_latitude_2 15_longitude_3 15_latitude_3 16 11 12 13 14 15 16 11 12 ...
<p>Python starts indexing at 0. So if your axis is of size 3, then you can only access it with indices 0, 1, and 2.</p> <p><code>len(border.columns)</code> is (I presume) 3. And so <code>col_num</code> will take values 0 and 2 in your for loop.</p> <p>When it takes value 2, and then you do <code>border.columns[col_nu...
python|pandas|geopandas
0
374,845
58,792,897
Creating a random matrix with 7 rows by 21 column vectors with A,C,T G
<p>I am new to coding and need to create a random matrix with 7 rows by 21 column vectors with A,C,T G as values.</p>
<pre><code>In [412]: np.random.choice(list('ACTG'),(3,4),replace=True) Out[412]: array([['C', 'C', 'C', 'G'], ['A', 'A', 'G', 'T'], ['G', 'A', 'T', 'T']], dtype='&lt;U1') </code></pre>
python|numpy
1
374,846
58,649,009
Write pandas dataframe to_csv in columns with trailing zeros
<p>I have a pandas dataframe of floats and wish to write out to_csv, setting whitespace as the delimeter, and with trailing zeros to pad so it is still readable (i.e with equally spaced columns).</p> <p>The complicating factor is I also want each column to be rounded to different number of decimals (some need much hig...
<p>You can get the string representation of the dataframe using <code>df.to_string()</code> (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_string.html" rel="nofollow noreferrer">docs</a>). Then simply write this string to a text file.</p> <p>This method also has <code>col_spac...
python|pandas|csv|dataframe
1
374,847
58,758,390
I want to get a specific value from a data frame and see what another value is a few rows down , but in a different column
<p>I have the following data frame now3: </p> <pre><code> size date unix price 0 4.0 2019-11-03 02:42:00 1.570000e+12 9288.5 1 4.0 2019-11-03 02:42:00 1.570000e+12 9288.5 2 4.0 2019-11-03 02:42:00 1.570000e+12 9288.5 3 4.0 2019-11-03 02:...
<p>In the below code, it uses timedelta to modify the original time to get the desired ones, then store it in a separate dataframe. Inner join the desired (time, size) pairs with all the data, you will get the data you want. </p> <pre><code>from datetime import datetime, timedelta time_interval = timedelta(minutes = ...
python|pandas|dataframe
1
374,848
58,791,635
Python How to sliding for sum data in dataframe?
<p>If I have data frame like this.</p> <pre><code>df = [3, 2, 4, 1, 0, 3] </code></pre> <p>I want to slice to sum 3 value like this.</p> <pre><code>3+2+4 = 9 2+4+1 = 7 4+1+0 = 5 1+0+3 = 4 </code></pre> <p>So, the result will be.</p> <pre><code>9, 7, 5, 4 </code></pre> <p>How to for sum dataframe with python ?</p>
<p>You can do this with a sliding slice in a list comprehension</p> <pre><code>df = [3, 2, 4, 1, 0, 3] print([sum(df[i:i+3]) for i in range(len(df)-2)]) </code></pre> <pre><code>[9, 7, 5, 4] </code></pre>
python|python-3.x|pandas
2
374,849
58,823,497
Any way to speedup itertool.product
<p>I am using itertools.product to find the possible weights an asset can take given that the sum of all weights adds up to 100. </p> <pre><code>min_wt = 10 max_wt = 50 step = 10 nb_Assets = 5 weight_mat = [] for i in itertools.product(range(min_wt, (max_wt+1), step), repeat = nb_Assets): if sum(i) == 100: ...
<p>Many improvements are possible.</p> <p>For starters, the search space can be reduced using <em>itertools.combinations_with_replacement()</em> because summation is commutative.</p> <p>Also, the last addend should be computed rather than tested. For example if <code>t[:4]</code> was <code>(10, 20, 30, 35)</code>, y...
python|numpy|nested-loops|itertools
4
374,850
58,745,819
Splitting list of nested json to multiple columns
<p>This is sort of an extension on a previous question I asked, but different scope and approach.</p> <p>I have a dataframe with a column populated by lists of dictionaries in each row</p> <pre><code>0 [{"date":"0 1 0" firstBoxerRating:[null null] ... 1 [{"date":"2 2 1" firstBoxerRating:[null null] ... 2 [{"...
<p>Managed to resolve this issue with using regex and str.extract. </p> <p>I extract the text between two strings and append said text to its relevant column</p> <p>Example:</p> <pre><code>df[0].str.extract('date(?P&lt;date&gt;.*?)firstBoxerRating(?P&lt;firstBoxerRating&gt;.*?)firstBoxerWeight(?P&lt;firstBoxerWeight...
python|json|pandas
0
374,851
58,871,889
How to plot a numpy array with matplotlib?
<p>I generate a circle numpy array like this:</p> <pre><code># -*- coding: utf-8 -*- import numpy as np a, b = 3, 3 n = 7 r = 3 arr = np.ones((n, n)) y, x = np.ogrid[-a:n-a, -b:n-b] mask = x ** 2 + y ** 2 &lt;= r**2 arr = 255 * mask.astype(int) print(arr) </code></pre> <p>it print result like this:</p> <pre><code...
<p>This can be done using <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.colors.ListedColormap.html" rel="nofollow noreferrer">matplotlib's color map feature.</a></p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import colors a, b = 3, 3 n = 7 r = 3 arr = np.ones((n, n)...
python|numpy|matplotlib
0
374,852
58,698,611
Removing rows until a metric point is reached and extracting the minimum value
<p>I'am classifying some text using a Machine learning model. Essentially I am fitting 80% of the data to the model and predicting the remaining 20%. On top of this, for each classification, I am outputting a confidence level as given by the ML model and and a <code>check</code> variable, which is set to <code>TRUE</co...
<p>Here is the solution:</p> <ol> <li>read your dataframe in (code below), treating <code>Check</code> column as int (rather than boolean), and sort in order of increasing <code>confidence</code>.</li> <li>now look at the values as you sweep your confidence threshold over rows: <code>[ round(df.iloc[n:].Check.mean(), ...
python|pandas
1
374,853
58,991,545
Sum the values of specific rows if the rows have same values in specific column
<p>I have a data frame like this:</p> <pre><code> a b c 12456 11 123.1 12678 19 345.67 13278 19 1235.345 </code></pre> <p>or in another format </p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;12456&lt;/td&gt; &lt;td&gt;11&lt;/td&gt;&lt;td&gt;123.1&lt;/td&gt; &lt;/tr&gt; ...
<p>Use <strong>pandas</strong>:</p> <pre><code>import pandas as pd df = pd.read_csv("data.csv", delim_whitespace=True) df a b c 0 12456 11 123.100 1 12678 19 345.670 2 13278 19 1235.345 df.groupby('b')['c'].sum() </code></pre> <p>Output:</p> <pre><code>b 11 123.100 19 1581.015...
python|pandas|dataframe
0
374,854
58,831,422
How to delete row data from a CSV file using pandas?
<p>I am new to Pandas and was wondering how to delete a specific row using the row id. Currently, I have a CSV file that contains data about different students. I do not have any headers in my CSV file. </p> <p><strong>data.csv:</strong></p> <pre><code>John 21 34 87 ........ #more than 100 columns of data Abigail ...
<p>You can just use a filter to filter out the ids you don't want. </p> <p>Example:</p> <pre><code>import pandas as pd from io import StringIO data = """ 1,John 2,Beckey 3,Timothy """ df = pd.read_csv(StringIO(data), sep=',', header=None, names=['id', 'name']) unwanted_ids = [3] new_df = df[~df.id.isin(unwanted_...
python-3.x|pandas
0
374,855
58,842,298
What is the fastest and the best way to get a specific number of group after applying groupby?
<p>I have more than <strong>1000</strong> groups with different <code>id</code> and I only need to select a <strong>specific number</strong> of groups and read the <code>nth</code> number of every group. <a href="http://tpcg.io/XyNS8UNP" rel="nofollow noreferrer">Here</a> an example of what I need:</p> <pre><code> #Th...
<p>To the best of my understanding of your problem:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = \ pd.DataFrame( { 'id': [i for i in range (1000)]*10, 'col1': ['col1 occurence {} for id {}'.format(j, i) for j in range(10) for i in range (1000)], 'col2': ['col2 occurence...
python|python-3.x|pandas
1
374,856
58,807,858
Update multiple rows of SQL table from Python script
<p>I have a massive table (over 100B records), that I added an empty column to. I parse strings from another field (string) if the required string is available, extract an integer from that field, and want to update it in the new column for all rows that have that string.</p> <p>At the moment, after data has been pars...
<p>As mentioned, consider pure SQL and avoid iterating through billions of rows by pushing the Pandas data frame to Postgres as a staging table and then run one single <code>UPDATE</code> across both tables. With SQLAlchemy you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame...
python|sql|database|pandas|amazon-redshift
4
374,857
70,201,921
BERT Domain Adaptation
<p>I am using <code>transformers.BertForMaskedLM</code> to further pre-train the BERT model on my custom dataset. I first serialize all the text to a <code>.txt</code> file by separating the words by a whitespace. Then, I am using <code>transformers.TextDataset</code> to load the serialized data with a BERT tokenizer g...
<p>You saved a <code>BERT</code> model with LM head attached. Now you are going to load the serialized file into a standalone <code>BERT</code> structure without any extra element and the warning is issued. This is pretty normal and there is no Fatal error to do so! You can check the list of unloaded params like below:...
python|nlp|pytorch|huggingface-transformers|bert-language-model
1
374,858
70,250,296
How to interpret a 4 dimensional contigiency table in pandas
<p>I am trying to understand this contingency table and I have no luck looking in the documentation of pandas or any other related questions. This is for a personal machine learning project.</p> <p>I have the following example data:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({&quot;la&quot;:[...
<p>I figured it out, basically, the columns whose elements are all NaN are dropped so truncate the output due to <code>dropna</code>, which is set to <code>True</code> by default:</p> <blockquote> <p><strong>dropna</strong>: <em><strong>bool</strong></em>, <em><strong>default</strong></em> <em><strong>True</strong></em...
python|pandas|dataframe
0
374,859
70,118,623
ValueError after attempting to use OneHotEncoder and then normalize values with make_column_transformer
<p>So I was trying to convert my data's timestamps from Unix timestamps to a more readable date format. I created a simple Java program to do so and write to a .csv file, and that went smoothly. I tried using it for my model by one-hot encoding it into numbers and then turning everything into normalized data. However, ...
<p>using <strong>OneHotEncoder</strong> is not the way to go here, it's better to extract the features from the column <strong>time</strong> as separate features like year, month, day, hour, minutes etc... and give these columns as input to your model.</p> <pre><code>btc_data['Year'] = btc_data['Date'].astype('datetime...
python|pandas|tensorflow|deep-learning|one-hot-encoding
3
374,860
70,212,748
How to make an order column when grouping by another column
<p>I have a dataframe in a format:</p> <pre><code>d = {'hour': [1, 1,2,2], 'value': [10, 50,200,100]} df = pd.DataFrame(data=d) </code></pre> <p>How can I create a column order, where order will be an order of values when grouped by the hour column.</p> <p>The result should be:</p> <pre><code>index hour value order ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.rank.html" rel="nofollow noreferrer"><code>GroupBy.rank</code></a>:</p> <pre><code>df['order'] = df.groupby('hour')['value'].rank(method='dense').astype(int) print (df) hour value order 0 1 10 1 1 ...
python|pandas
4
374,861
70,214,493
the inplace parameter in pandas how it works?
<p>in pandas the <strong>inplace</strong> parameter make modification on the reference but I know in python data are sent by value not by reference i want to know how this is implemented or how this work</p>
<blockquote> <p>Python’s argument passing model is neither “Pass by Value” nor “Pass by Reference” but it is “Pass by Object Reference”</p> </blockquote> <p>When you pass a dictionary to a function and modify that dictionary inside the function, the changes will reflect on the dictionary <em>everywhere</em>.</p> <p>How...
python|python-3.x|pandas|mutability|call-by-value
1
374,862
70,374,119
What is making my model predicting the wrong value when running on my laptop and colab?
<p>I've exported a TF model to <code>.h5</code> format to use it for my project. When running and testing on Colab, it predicts perfectly but when I tried to predict the <code>.h5</code> format model in my machine(laptop), it did not predict the correct one therefore it did not work like it used to in Colab. I've tried...
<p>I'd check the outputs of each step of your model prediction code.</p> <p>Are you able to verify your model gets the same results when you call <code>model.evaluate()</code> on a test split of the dataset?</p> <p>That's one of the first things I'd try to do.</p> <p>Otherwise, you might want to check out the part of t...
python|tensorflow|machine-learning|keras|deep-learning
0
374,863
70,277,501
Exception Report from pandas DataFrame
<p><strong>Background:<br></strong> The following function takes a pandas DataFrame and renames it <code>exceptions_df</code> whilst applying 2x conditions to it.</p> <p><strong>Function:</strong></p> <pre><code>def ownership_exception_report(): df = ownership_qc() exceptions_df = df[df['Entity ID %'] != 100.00...
<pre><code>def ownership_exception_report(): df = ownership_qc() return df[(df['Entity ID %'] != 100.00) &amp; (df['Account # %'] != 100.00)] </code></pre> <p>Or:</p> <pre><code>def ownership_exception_report(): df = ownership_qc() return df[df['Entity ID %'].ne(100.00) &amp; df['Account # %'].ne(100.00...
python|pandas|exception
3
374,864
70,138,600
Is there any way to check the repetition of the value in a B field, taking into account a sorted A field, for each ID group? (See example below)
<p>Suppose we have a table of thousands of users with an <em>ID</em>, a <em>year-month</em> and a <em>balance($)</em>. Let's simplify it in the following table with 3 users:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">user ID (numeric)</th> <th style="text-alig...
<p>For each <code>ID</code>, perform run length encoding on <code>balance</code> and check if only the last value for that encoding is <code>0</code>.</p> <pre class="lang-py prettyprint-override"><code>import pdrle def foo(x): rle = pdrle.encode(x.eq(0)) if rle.vals.sum() == 0: return True if rle....
python|sql|pandas|group-by|sas
1
374,865
70,087,537
How to prevent overflow in MLE method for large data
<p>I am trying to do a manual MLE estimation using scipy. My dataset is not that large so it surprises me that my values get very large very fast and scipy.optimize.minimize seems to get into NaNs for my density extremely quickly. I've tried to use the sum of logarithms instead of the product of the densities but that ...
<p>You need to avoid the giant exponentiations. One way to do this is to actually simplify your function:</p> <pre><code>log_pareto_pdf = lambda alpha, x: np.log(alpha) + alpha*np.log(5e5) - (alpha + 1)*np.log(x) </code></pre> <p>Without simplifying, your program still needs to try to calculate the <code>5e5**alpha</co...
python|numpy|scipy|statistics|scipy-optimize
3
374,866
70,258,123
I want to count the number of lines for each different groups
<p>Let say that we have this dataframe:</p> <pre><code>d = {'col1': [1, 2,0,55,12], 'col2': [3, 4,44,34,46], 'col3': [A,A,B,B,A] } df = pd.DataFrame(data=d) df col1 col2 col3 0 1 3 A 1 2 4 A 2 0 44 B 3 55 34 B 4 12 46 A </code></pre> <p>I want anoth...
<p>You can create consecutive groups by compare shifted values for not eqaual with cumulative sum and pass to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas....
python|pandas|dataframe
2
374,867
70,183,494
Is my configuration for Densenet in tensorflow wrong?
<p>When I am running the code pasted below, the model is just training for “multiplier” =1 or =4. Running the same code in google colab → just training for multiplier=1</p> <p>Is there any mistake in how I am using DenseNet here?</p> <p>Thanks in advance, appreciate your help!</p> <pre><code>import numpy as np import t...
<p>apparently, it is necessary to add a custom GlobalAveragePooling and Dense Layer if a custom <code>input_shape</code> (not the standard 224x224x3 of ImageNet) and <code>include_top = False</code> is used:</p> <pre><code>base_model = DenseNet201( include_top=False, weights='imagenet', input_tensor=None, input...
python|tensorflow|keras|densenet
0
374,868
70,293,437
Writing pandas dataframe to CSV with decimal places
<p><strong>Background</strong> - I am trying to round the values of 2x columns (<code>Entity ID %</code> and <code>Account # %</code>) to 7 decimal places in a pandas Dataframe, before writing to a <code>.csv</code></p> <p><strong>Function</strong> - this function takes a dataframe (<code>df</code>) strips out any rows...
<p>Your problem is probably because you don't set the output of <code>round</code> to <code>df</code>:</p> <pre><code># Replace df.round({'Entity ID %': 7, 'Account # %': 7}) # By df = df.round({'Entity ID %': 7, 'Account # %': 7}) </code></pre>
python|pandas|csv
1
374,869
70,194,131
Using np.where with multiple conditions
<p>Why does the first line work but not the second?</p> <p>ok:</p> <pre><code>data_frame['C'] = np.where(np.logical_and(np.greater_equal(data_frame['A'],1), np.not_equal(data_frame['B'],0)), 'OK', '-' ) </code></pre> <p>not ok:</p> <pre><code>data_frame['C'] = np.where(data_frame['A']== 1 &amp; data_frame['B']!=0, 'OK...
<p>It's just the order of operations not being correct if you don't have parens/brackets in the appropriate places. This should work in place of your 2nd variant:</p> <pre><code>np.where((data_frame['A'] == 1) &amp; (data_frame['B'] != 0), 'OK', '-') </code></pre> <p>So the comparison operations -- <code>==</...
python|pandas|numpy
2
374,870
70,080,360
Remove top-N layers from a pretrained model and Save as new model
<p>How can I remove certain layers AND be able to save it as a new model in tensorflow?</p> <p>I have the following code for removing top-N layers in tensorflow and it works:</p> <pre><code>reconstructed_model = tf.keras.models.load_model(model_path) embedding = Model(reconstructed_model.input, reconstruc...
<p>I tried using <code>EfficientNetB0</code> and constructed a model truncating the last four layers, just as you did.</p> <pre><code>from tensorflow.keras.applications import EfficientNetB0 import tensorflow as tf efficientnet = EfficientNetB0( include_top=False ) embedding = tf.keras.models.Model( efficientnet....
tensorflow|keras
0
374,871
70,177,432
how to find numbers of row above mean in pandas.dataframe?
<p>and here i am stuck at a question about finding how many number of rows above average/mean score.</p> <p>my df like this:</p> <pre><code> Subject Name Score 0 s1 Amy 100 1 s1 Bob 90 2 s1 Cathy 92 3 s1 David 88 4 s2 Emma 95 5 s2 Frank 80 6 s2 ...
<p>You can try using <code>groupby</code> and <code>apply</code>:</p> <pre class="lang-py prettyprint-override"><code>def count_above_avg(g): avg = g.Score.mean() return (g.Score &gt; avg).sum() df.groupby('Subject').apply(count_above_avg) </code></pre>
python|pandas|dataframe
0
374,872
70,281,357
Monthly climatology across several years, repeated for each day in that month over all years
<p>I need to find the monthly climatology of some data that has daily values across several years. The code below sufficiently summarizes what I am trying to do. <code>monthly_mean</code> holds the averages over all years for specific months. I then need to assign that average in a new column for each day in a specific...
<p>Your code is setting the column == to the group, so every iteration of your loop you're setting the df's values only for that group---which is why your df ends on December, the last month in the list.</p> <pre><code>monthly_mean = df['A'].groupby(df.index.month).mean() for month, group in df.groupby(df.index.month):...
python|pandas|dataframe
1
374,873
70,155,614
How to create a new dataframe from input dataframe based on certain condition
<p>I have pandas dataframe like this.</p> <pre><code>api region base_path https://apis.us/image/ us /image https://apis.emea/video/ emea /video https://apis.asia/docs/ asia /docs https://apis.emea/image/ emea /image https://apis....
<p>Try this:</p> <pre><code>import itertools import functools, operator def find_coomon_elements(p): return list(set.intersection(*[set(li) for li in p])) def find_unique_elements(p, l): merged_p = functools.reduce(operator.iconcat, p, []) return [x for x in l if merged_p.count(x)==1] strings_array = df[...
python-3.x|pandas
2
374,874
70,123,409
pandas dataframe create new columns and fill with an external API response as calculated using concertinaed values from same df
<pre><code>df= User id 0 u1 id1 1 u2 id2 2 u3 id3 user_limit1=api('u1:id1') new_df= User id user_limit 0 u1 id1 user_limit1 1 u2 id2 user_limit2 2 u3 id3 user_limit3 </code></pre> <p>how can i update df as above for about 9800 rows of DF ?</p>
<p>Create a column and use <code>apply</code> on rows</p> <pre><code>df['user_limit'] = df.apply(lambda x: api_call(f'{x.User}:{x.id}'), axis=1) </code></pre> <p>OR</p> <pre><code>df['user_limit'] = df.User + ':' + df.id df['user_limit'] = df.user_limit.map(api_call) </code></pre> <p>Note: Ensure that the <code>api_cal...
python|pandas|dataframe|for-loop|rows
0
374,875
70,202,374
How to change histogram color based on x-axis in matplotlib
<p>I have this histogram computed from a pandas dataframe.</p> <p><a href="https://i.stack.imgur.com/BnznK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BnznK.png" alt="enter image description here" /></a></p> <p>I want to change the colors based on the x-axis values.<br /> For example:</p> <pre><c...
<p>Just plot them one by one:</p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as plt x = np.linspace(-1,1,10) y = np.random.uniform(0,1,10) width = 0.2 plt.figure(figsize = (12, 6)) cmap = mpl.cm.RdYlGn.reversed() norm = mpl.colors.Normalize(vmin=0, vmax=10) for x0, y0 in zip(x,y): plt.bar(x0, y0,...
python|pandas|matplotlib|histogram
0
374,876
70,065,974
InvalidArgumentError: ConcatOp : Dimensions of inputs should match when predicting on X_test with Conv2D - why?
<p>I'm learning Tensorflow and am trying to build a classifier on the Fashion MNIST dataset. I can fit the model, but when I try to predict on my test set I get the following error:</p> <pre><code>y_pred = model.predict(X_test).argmax(axis=1) InvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0]...
<p>With <code>model.predict</code> you are making predictions on batches as stated <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model?version=nightly#predict" rel="nofollow noreferrer">here</a>:</p> <blockquote> <p>Computation is done in batches. This method is designed for batch processing of large num...
python|tensorflow|keras|deep-learning|conv-neural-network
1
374,877
70,350,573
merge two pyspark dataframe based on one column containing list and other as values
<p>I have two tables</p> <pre><code>+-----+-----+ |store|sales| +-----+-----+ | F| 4000| | M| 3000| | A| 4000| +-----+-----+` +-----+------+ | upc| store| +-----+------+ |40288|[F, M]| |42114| [M]| |39192|[F, A]| +-----+------+` </code></pre> <p>I wish to have the final table as</p> <pre><code>+-----+-----...
<p>You can <code>join</code> based on <a href="https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.array_contains.html?highlight=array_contains" rel="nofollow noreferrer"><code>array_contains</code></a>. After join, group by <code>upc</code> and <code>store</code> in df22 and <code>sum</...
python|pandas|dataframe|pyspark
3
374,878
70,185,922
Input random dates into the column pandas
<p>I have a data frame called df_planned and would like to insert into column &quot;order_date&quot; some random dates from Oct-2021. Is there a way to that in the loop? There are 300 rows of the data so obviously the dates can repeat.</p> <p>I wrote this function to generate the dates:</p> <pre><code>import datetime d...
<p>You can use <code>np.random.choice</code> and <code>pd.date_range</code>:</p> <pre><code>import pandas as pd import numpy as np df['order_date'] = np.random.choice(pd.date_range('2021-10-01', '2021-10-31'), 300) print(df) # Output: order_date 0 2021-10-08 1 2021-10-27 2 2021-10-21 3 2021-10-11 4 2021...
python|pandas|dataframe|datetime
3
374,879
70,239,115
Sensibly merging two dataframes
<p>If one of my dataframes gives me some info about items:</p> <pre><code> itemId property_1 property_2 property_n Decision 0 i1 88.90 NaN 0 1 1 i2 87.09 7.653800e+06 0 0 2 i3 78.90 7...
<p>You can <code>pivot</code> the second table like:</p> <pre><code>df.pivot(index='itemId', columns='userId', values='Decision').reset_index() </code></pre> <p>Then you can do the <code>merge</code> on <code>itemId</code>.</p>
python|pandas|dataframe|merge
1
374,880
70,191,573
it there any way to convert 3D numpy array to 2D
<p>I got a 3d NumPy array:</p> <pre><code>array([[[ 12., 0., 0.], [ 15., 0., 0.], [ 13., 0., 0.]], [[ 12., 0., 0.], [ 11., 0., 0.], [ 13., 0., 0.]]]) </code></pre> <p>Is there any way to convert to a 2d and only get</p> <pre><code>[12., 15., 13.] [12., 11., 13.] </code></pre>
<pre><code>x = np.array( [[[ 12., 0., 0.], [ 15., 0., 0.], [ 13., 0., 0.]], [[ 12., 0., 0.], [ 11., 0., 0.], [ 13., 0., 0.]]] ) x_2d = x[:, :, 0] &gt;&gt; x_2d &gt;&gt; array([[12., 15., 13.], [12., 11., 13.]]) </code></pre>
python|pandas|numpy
0
374,881
70,089,884
Extract data and sort them by date
<p>I am trying to figure out an exercise on string manipulation and sorting. The exercise asks to extract words that have time reference (e.g., hours, days) from the text, and sort rows based on the time extracted in an ascendent order. An example of data is:</p> <pre><code>Customer Text 1 12 hours ago —...
<p>Given the DataFrame sample, I will assume that for this exercise the first two words of the text are what you are after. I am unclear on how the sorting works, but for the third point, a more suitable time would be the <code>current time - timedelta</code> from by the Text column</p> <p>You can apply an if-else lamb...
python|pandas|data-manipulation
1
374,882
70,025,995
Using isna() as a condition in a if else statement
<p>I have a df that looks like the following with many more rows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LastTravelDate</th> <th>TripStartDate</th> <th>TripEndDate</th> </tr> </thead> <tbody> <tr> <td>2021-07-10</td> <td>2021-08-16</td> <td>NaT</td> </tr> <tr> <td>2021-08-28</td> <...
<p>For a vectorized approach you can use <code>np.where()</code>:</p> <pre><code>df['LastTravelDate'] = np.where(df['TripEndDate'].isna(),df['TripStartDate'],df['TripEndDate']) </code></pre>
python|pandas|numpy|if-statement
3
374,883
70,086,114
Snowflake- How to ignore the row number (first column) in the result set
<p>Whenever i run any select query in snowflake the result set is having auto generated row number column (as a first column).. how to ignore this column from the code...</p> <p>Like : select * from emp ignore row;</p>
<p>If you're referring to the unnamed column just before TABLE_CATALOG in the below picture.</p> <p>I'm pretty sure that's not something we can not change -&gt; maybe if you wrote some custom JS to fiddle with the page you might be able to hide it by perhaps changing the TEXT color to white or something. But that seems...
python|pandas|dataframe|snowflake-cloud-data-platform|series
0
374,884
70,348,437
What is the difference between x.view(x.size(0), -1) and torch.nn.Flatten() layer and torch.flatten(x)? pytorch question
<p>I'm quite curious on what's the difference between using view(,-1) and flatten like the simple code here:</p> <p>Since I found that the size and data all flatten to one dimension.</p> <pre class="lang-py prettyprint-override"><code>import torch from torch import nn from torch.utils.data import DataLoader from torchv...
<p>A view is a way to modify the way you look at your data without modifying the data itself:</p> <ul> <li><a href="https://pytorch.org/docs/stable/generated/torch.Tensor.view.html?highlight=view#torch.Tensor.view" rel="nofollow noreferrer"><code>torch.view</code></a> returns a view on the data: the data is not copied,...
python|pytorch
0
374,885
70,058,128
How to discretize a datetime column?
<p>I have a dataset that contains a column of datetime of a month, and I need to divide it into two blocks (day and night or am\pm) and then discretize the time in each block into 10mins bins. I could add another column of 0 and 1 to show it is am or pm, but I cannot discretize it! Can you please help me with it?</p> <...
<p>If I understood correctly you are trying to add a column for every interval of ten minutes to indicate if an observation is from that interval of time.</p> <p>You can use <code>lambda expressions</code> to loop through each observation from the series.</p> <p>Dividing by 10 and making this an integer gives the first...
python|pandas|dataframe|datetime|discretization
0
374,886
70,233,279
tensorflow lite program crashing with kivy on buildozer
<p>I tried running this github program <a href="https://github.com/tito/experiment-tensorflow-lite" rel="nofollow noreferrer">https://github.com/tito/experiment-tensorflow-lite</a> It is basically about running tensorflow lite using kivy on android.</p> <p>I tried running the program on my pc but I got this error``</p>...
<p>Just use command:</p> <pre><code>buildozer android clean </code></pre> <p>before:</p> <pre><code>buildozer android debug </code></pre>
ubuntu|kivy|tensorflow-lite|buildozer
0
374,887
70,043,838
Pandas Data Frame, reading from a file or setting a new Data Frame inside a function
<p>I am trying to read 3 CSV files into 3 pandas DataFrame. But after executing the function the variable seems not available. Tries to create a blank data frame outside the function and read and set the frame in the function. But the frame is blank.</p> <pre><code># Load data from the csv file def LoadFiles(): x =...
<p>try following code</p> <pre><code># Load data from the csv file def LoadFiles(): x = pd.read_csv('columns_description.csv', index_col=None) print(&quot;Columns Description&quot;) print(f&quot;Number of rows/records: {x.shape[0]}&quot;) print(f&quot;Number of columns/variables: {x.shape[1]}&quot;) ...
python|pandas|jupyter-notebook|vscode-python|exploratory-data-analysis
0
374,888
70,274,443
Parse CSV to Extract Filenames and Rename Files (Python)
<p>I'm looking to try and extract filenames from a comma CSV, rename the files they refer to by sequential numbering, then going back to the CSV in the process.</p> <p>I am able to extract all the first column:</p> <pre><code>import pandas as pd my_data = pd.read_csv('test.csv', sep=',', header=0, usecols=[0]) </code><...
<p>You can directly modify the <code>dataframe</code> and the file by iterating trough the dataframe itself. Once you have edited the desired rows, you persist the dataframe by rewriting it to a csv file (the same if you want to overwrite it). I assume here that <code>file_path</code> is the name of the column containi...
pandas|csv
0
374,889
70,089,168
Python Selenium Table Body Data Extraction
<p>I am trying to get the data elements of class <code>td</code> from my table, but my code consistently is only capable of pulling the rows from the <code>thead</code>. If I add <code>find_element_by_tag_name(&quot;tbody&quot;)</code>, then I get the classic <em>Message: no such element: Unable to locate element...</e...
<p>There are two table elements - one for the <strong>Header</strong> (without <code>id</code> attribute) and other for the <strong>Data</strong> (with <code>id</code> attribute).</p> <p>Try like below and confirm.</p> <pre><code>driver.get(&quot;https://shinyapps.asee.org/apps/Profiles/&quot;) # Code to select &quot;...
python|pandas|selenium|datatables
0
374,890
70,081,419
How to take transpose of one particular DataFrame column in Python? Also how to get certain values from second iteration onwards from 'for' loop?
<p>I am running a 'for' loop whose output is a data frame with two columns, column 1 with columns names and column 2 with data. It can be seen below:</p> <p><a href="https://i.stack.imgur.com/kaUK9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kaUK9.png" alt="enter image description here" /></a></p...
<p>For your first question first set your index to you desired column names column, then transpose using <code>T</code>:</p> <p><code>df2=df.set_index('1').T</code></p> <pre><code>1 Column1 Column2 Column3 Column4 Column5 2 data_1_1 data_1_2 data_1_3 data_1_4 data_1_5 </code></pre>
python|pandas|dataframe|for-loop
-1
374,891
70,281,636
Two Pandas dataframes, how to interpolate row-wise using scipy
<p>How can I use scipy interpolate on two dataframes, interpolating row-rise?</p> <p>For example, if I have:</p> <pre><code>dfx = pd.DataFrame({&quot;a&quot;: [0.1, 0.2, 0.5, 0.6], &quot;b&quot;: [3.2, 4.1, 1.1, 2.8]}) dfy = pd.DataFrame({&quot;a&quot;: [0.8, 0.2, 1.1, 0.1], &quot;b&quot;: [0.5, 1.3, 1.3, 2.8]}) displa...
<p>Since you are looking for linear interpolation, you can do:</p> <pre><code>def interpolate(val, dfx, dfy): t = (dfx['b'] - val) / (dfx['b'] - dfx['a']) return dfy['a'] * t + dfy['b'] * (1-t) interpolate(0.5, dfx, dfy) </code></pre> <p>Output:</p> <pre><code>0 0.885714 1 0.284615 2 1.100000 3 -0.0...
pandas|scipy|interpolation
0
374,892
70,175,266
How to take a subset of the columns of a pandas data frame?
<p>I have got a pandas data frame with multiple columns and a list with column indices (0, 1, ..., n) that index a subset of the columns of the data frame. How can I create a new data frame with exactly this subset of columns?</p>
<p>The answer to your question can be found in the pandas documentation:</p> <p><a href="https://pandas.pydata.org/docs/getting_started/intro_tutorials/03_subset_data.html" rel="nofollow noreferrer">How do I select a subset of DataFrame</a></p> <p>The article displays many different ways to do it.</p>
python|pandas|dataframe
1
374,893
70,202,728
More Efficient Way To Insert Dataframe into SQL Server
<p>I am trying to update a SQL table with updated information which is in a dataframe in pandas.</p> <p>I have about 100,000 rows to iterate through and it's taking a long time. Any way I can make this code more efficient. Do I even need to truncate the data? Most rows will probably be the same.</p> <pre><code> conn = ...
<p>Don't use <code>for</code> or <code>cursors</code> just <code>SQL</code></p> <pre><code>insert into TABLENAMEA (A,B,C,D) select A,B,C,D from TABLENAMEB </code></pre> <p>Take a look to this link to see another demo: <a href="https://www.sqlservertutorial.net/sql-server-basics/sql-server-insert-into-select/" rel="nof...
python|sql|sql-server|pandas
0
374,894
70,086,045
Grouping by ID choosing highest values in columns from same ID
<p>I have a problem trying to calculate some final tests marks. I need to group by Students, getting only the highest value in each column for each student.</p> <p>Being DF the dataframe:</p> <pre><code>data = {'Students': ['Student1', 'Student1', 'Student1', 'Student2','Student2','Studen3'], 'Result1': [2, 4,...
<p>The dataframe can be generated using simply iterations over groups:</p> <pre><code>df2 = pd.DataFrame(columns=('Student', 'res1', 'res2', 'res3')) for s in df.Students.unique(): stdf = df[df[&quot;Students&quot;]==s] df2 = df2.append({'Student':s,'res1':max(stdf.Result1),'res2':max(stdf.Result2), ...
python|pandas|pandas-groupby
2
374,895
70,143,435
Creating labels and updating a column based on multiple conditions
<p>I have a data frame which looks like this:</p> <pre><code>data = { 'user_id': [ '9EPWZVMNP6D6KWX', '9EPWZVMNP6D6KWX', '9EPWZVMNP6D6KWX', '9EPWZVMNP6D6KWX', '9EPWZVMNP6D6KWX', '9EPWZVMNP6D6KWX' ], 'timestamp': [ 1612139269, 1612139665, 1612139579, 1612141096, 1612143046, 16...
<p>edit: my original post had the first loop on <code>n</code> in reverse, I don't think we need that or it helps... i also updated it so that we don't count previous occurrences of checkout:confirmation but instead just add 1 to the last checkout:confirmation count, so we are able to skip running through as many lines...
python|pandas|dataframe|conditional-statements|data-analysis
1
374,896
70,083,221
Rename pandas column of type datetime pandas
<p>i have dataframe like this:</p> <pre><code>df=pd.DataFrame(data={'2021-11-21':['10','20'],'2021-11-14':['39','21']}) df 2021-11-21 2021-11-14 10 39 20 21 </code></pre> <p>i want rename columns like this:</p> <pre><code>curr_week_2021-11-21 prev_week_2021-11-14 10 39 ...
<p>One way to do it programmatically with an arbitrary list of prefixes would be to use <code>map</code>/<code>zip</code>/<code>join</code>:</p> <pre><code>prefixes = ['curr_week', 'prev_week'] df.columns = map('_'.join, zip(prefixes, df.columns)) </code></pre> <p>output:</p> <pre><code> curr_week_2021-11-21 prev_week...
python|pandas
1
374,897
70,103,620
How to create different dataframes from dictionaries
<p>I have a dataframe with dictionaries saved under two columns:</p> <pre><code>Name Trust_Value Affordability_Value 0 J. {'J.': 0.25, 'M.': 0.23} {'Z.': 0.024, 'M.': 0.34} 1 M. {'M.': 0.12, 'S.': 0.14} {'S.': 0.017, 'B.': 0.21} 1 C. {'S.': 0.21, 'N.': 0.13} {'D.': 0.015, 'B.': 0.22...
<p>You first need to <code>explode</code> your dictionaries:</p> <pre><code>df2 = (df.assign(Trust_Key=df['Trust_Value'].apply(lambda d: d.values()), Affordability_Key=df['Affordability_Value'].apply(lambda d: d.values()) ) .set_index('Name') .apply(pd.Series.explode) ...
python|pandas|dataframe
3
374,898
70,264,645
How to read parquet file partitioned by date folder to dataframe from s3 using python?
<p>Using python, I should go till cwp folder and get into the date folder and read the parquet file. I have this folder structure inside s3.</p> <p><strong>Sample s3 path:</strong></p> <p><strong>bucket name = lla.analytics.dev</strong></p> <p><strong>path = bigdata/dna/fixed/cwp/dt=YYYY-MM-DD/file.parquet</strong></p>...
<p>I see you have pyarrow tagged. If you would like to use pyarrow (disclaimer, I work with pyarrow), you should be able to do:</p> <pre><code>import pyarrow.fs as fs import pyarrow.dataset as ds s3, path = fs.FileSystem.from_uri(&quot;s3://lla.analytics.dev/bigdata/dna/fixed/cwp&quot;) dataset = ds.dataset(path, par...
python|pandas|dataframe|pyarrow|fastparquet
2
374,899
70,343,845
pandas/JupyterLab hiding first half of string between $$
<pre><code> one two three 0 $97500_$9500 $9000_$7500 nan 1 $97500_$9500 $9000_$7500 7000 2 $97500_$9500 $9000_$7500 7000 3 $97500_$9500 $9000_$7500 7000 4 $97500_$9500 $9000_$9900 $7500_$7000 5 97500 77500 7000 6 7700...
<p>Pandas has a <a href="https://pandas.pydata.org/pandas-docs/dev/user_guide/options.html" rel="nofollow noreferrer">display option</a> <code>display.html.use_mathjax</code> which is <code>True</code> by default:</p> <blockquote> <p>When True, Jupyter notebook will process table contents using MathJax, rendering mathe...
python|pandas|numpy|jupyter-notebook|jupyter-lab
1