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
369,000
63,850,702
Pandas - Reset CUMSUM after every cycle
<p>I am planning to move to another position in my company and I asked for a typical assignment to train myself. To some point, I did it and I really understood things, but now I am stuck. I was searching, but nothing works for me yet as I also can't understand it, but I guess it should be some kind of a loop and I am ...
<p>So the easiest way is to change how you calculate your balance column to do it how to you want to do it the first time.</p> <pre><code>df['balance'] = df.groupby((df['Correct'].shift() == '0').cumsum()).apply(lambda x: (x['Correct'] - x['Incorrect']).cumsum()).reset_index()[0] </code></pre> <p>So we are using cumsum...
python|pandas|dataframe|rows|cumsum
1
369,001
64,070,336
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) with array size exceeding 4000
<p>my code seems to produce this error when the &quot;input_data&quot; is over 4000 long. But I'd like to train it on 180,000 long array. I just finished a text generation class and trying to make my model generate some Eminem lyrics, and it's actually not doing too bad only using about 5% of all Eminem's words (4k out...
<p>I found that after about 4000 words, for some reason, tokenizer starts producing different lengths of tensors (not 10 as specified), so it needed one more line of code for padding:</p> <pre><code>padded = pad_sequences(input_data, maxlen=10, padding=&quot;pre&quot;) </code></pre>
python|numpy|tensorflow|deep-learning|neural-network
0
369,002
63,870,871
Column available in data frame but not getting while slicing the data frame
<p>While slicing the pivotted data frame unable to get the column names and throwing error below.Unable to find out what is happening as though columns available it is not extracted during slicing the dataframe. Data set is 'MovieLens 100K Dataset'</p> <p>Data set is</p> <pre><code>movieRatings=ratings.pivot_table(inde...
<p>Edited - Original answer wasn't what the OP wanted.</p> <p>The problem is with the way you created it. An array/list <code>values</code> argument is interpreted differently than a simple string. In this case, you need to just use the string one. If you use the array, you'll need to index with [<code>ratings</code>, ...
python|pandas|dataframe|sparse-matrix|keyerror
0
369,003
64,046,556
Nested loop results in table, Python
<p>I need to loop a computation over two lists of elements and save the results in a table. So, say that</p> <pre class="lang-py prettyprint-override"><code>months = [1,2,3,4,5] Region = ['Region1', 'Region2'] </code></pre> <p>and that my code is of the type</p> <pre class="lang-py prettyprint-override"><code>df=[] for...
<p>Assuming that there is the right numbers of items in <code>result</code></p> <pre><code>result = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] months = [1, 2, 3, 4, 5] Region = ['Region1', 'Region2'] df = pd.DataFrame([[Region[i]] + result[i*len(months): ((i+1)*len(months))] for i in range(len(Region))], column...
python|pandas
2
369,004
64,117,712
compare value in every row of other pandas dataframe
<p>I have a simple pandas dataframe which has a range column.</p> <pre><code>map_dict = { 'range' : [50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 40000, 80000, 120000], 'sample' : [1000, 1000, 1000, 1000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000] } pd.DataFrame.from_dict(map_dict) </code...
<p>I believe you need subtract values, compare by greater like <code>0</code> and get first matched value of <code>sample</code> column:</p> <pre><code>x = 4000 y = next(iter(df.loc[df['range'].sub(x) &gt; 0, 'sample'])) #alternative for first matched value #y = df.loc[ y &gt; 0, 'sample'].to_numpy()[0] print (y) 2000...
python|pandas|numpy
2
369,005
63,833,089
append data frame without a for loop in python
<p>im working with a large set of data and need a more efficient way of doing the following:</p> <pre><code>rate = [0.03,0.02,0.01] d = {'portfolio':['abc','de','xyz'], 'A':[0,1,2],'B':[3,4,5]} df = pd.DataFrame(data=d) +---+-----------+---+---+ | | portfolio | A | B | +---+-----------+---+---+ | 0 | abc | 0...
<p>Assign it then <code>explode</code></p> <pre><code>df['rate']=[rate]*len(df) df=df.explode('rate') df[['A','B']] = df[['A','B']].add(df['rate'],axis=0) df Out[62]: portfolio A B rate 0 abc 0.03 3.03 0.03 0 abc 0.02 3.02 0.02 0 abc 0.01 3.01 0.01 1 de 1.03 4.03 0.03 1...
python|pandas|dataframe|loops|append
1
369,006
63,775,198
How do I delete all pandas dataframe created by my python code
<p>I'm using python 3.x.I would like to delete all pandas dataframe created by my python code. I know there is an option</p> <pre><code>del df </code></pre> <p>to delete dataFrame df. But I'm looking something similar to R command</p> <pre><code>rm(list=ls()) </code></pre> <p>to remove all available dataframe created b...
<p>It's not as straightforward in Python as it is in R. The best and safest option is to manually <code>del</code> each dataframe by name (as well as any other references to the object, e.g. if they are also in a list). However, if this isn't an option, you can iterate through all available variables, check if they are...
python|r|pandas
1
369,007
64,151,679
Deep Neural Network Not Learning Anything
<p>I am training a simple Neural network with some Dense and Dropout Layers. But on running the fit function, there is no training taking place. My Model is:</p> <pre><code>import tensorflow as tf from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.models import Sequential Model = Sequential() Mo...
<p>Use a sigmoid activation function if you only have 1 output neuron with 2 posibilities. If you want to use softmax, use 2 output neurons and one hot encode your answers like: [0,1] or [1,0]</p> <p>This issue is explained here: <a href="https://mc.ai/softmax-output-neurons-number-for-binary-classification/" rel="nofo...
python|tensorflow|keras|neural-network
1
369,008
63,851,431
How to Augment the Training Set using the tf.keras.utils.Sequence API?
<p>TensorFlow documentation have the following example that can illustrate how to create a batch generator to feed a training set in batches to a model when the training set is too large to fit in memory:</p> <pre class="lang-py prettyprint-override"><code>from skimage.io import imread from skimage.transform import res...
<p>Use custom <code>Callback</code> and hook into <code>on_epoch_end</code>. After each epoch end change the angle of the data iterator object.</p> <h3>Sample (documented inline)</h3> <pre><code>from skimage.io import imread from skimage.transform import resize, rotate import numpy as np import tensorflow as tf from ...
python|tensorflow|keras
0
369,009
64,130,691
Error on value column in group by value counts
<p>I have code below as:</p> <pre><code>df[('name')]['cash_amount'].valuecounts(normalize=True).sum() </code></pre> <p>I want to use valuecounts normalize true, because I want to calculate the % of each names cash over the total amount of cash in the column.</p> <p>Where I am trying to calculate the total number each ...
<p>Please use <code>df.replace</code>, <code>groupby()</code> and apply lambda grouped sum divided by total sum</p> <pre><code> df['cash_amount']=df.replace(regex=r'\$', value='')['cash_amount'].astype(int) (df.groupby('name').cash_amount.apply(lambda x: x.sum())/df.cash_amount.sum()).rename('%').reset_index() name ...
python|python-3.x|pandas|pandas-groupby
1
369,010
46,739,603
returning multiple columns after comparing dataframes
<p>I have two dataframe as listed below. It was generated using pandas. </p> <p>df1</p> <pre><code> 0 0 reallocations 1 four 2 payoff </code></pre> <p>df2</p> <pre><code>word frequency whether 1 House 1 Sniderman 1 payoff ...
<p>You need an <em>outer</em> join:</p> <pre><code>df1.rename(columns={'0': 'word'}).merge(df2, how='outer').fillna(0) # or df1.rename(columns={0: 'word'}).merge(df2, how='outer').fillna(0) if column names in df1 # is a number # word frequency #0 reallocations 0.0 #1 four 0.0 #2 payoff ...
python|pandas
0
369,011
46,948,385
pandas generates a new column based on values from another column considering duplicates
<p>I am working on a <code>dataframe</code> which has a column that each value is a list, now I want to derive a new column which only considers list whose size is greater than 1, assigns a unique integer to the corresponding row as id. If elements in two lists are the same but with a different order, the two lists sho...
<p>First, you need to assign a column with the list lengths, and another column with the lists <s>as set objects</s> sorted:</p> <pre><code>df['list_len'] = df.document_no_list.apply(len) df['list_sorted'] = df.document_no_list.apply(sorted) </code></pre> <p>Then you need to assign the <code>cluster_id</code> for eac...
python-3.x|pandas|dataframe
1
369,012
46,899,186
How to filter on the Groupby Criterion in Pandas?
<p>Suppose the following contrived setup:</p> <pre><code>import pandas as pd d = {'fname': ['bob', 'Bob', 'larry', 'LARRY', 'Larry', 'Dick'], 'lname': ['harris', 'Larson', 'Douglas', 'REDMOND', 'Beal', 'Dyke']} df = pd.DataFrame(d) g = df.groupby(df.fname.str.lower()) query = ['bob', 'dick', 'chris'] </code></p...
<p>I don't know if I am missing something here but simple boolean indexing using isin looks enough. </p> <pre><code>df[df.fname.str.lower().isin(query)] fname lname 0 bob harris 1 Bob Larson 5 Dick Dyke </code></pre>
python|pandas|pandas-groupby
1
369,013
47,040,797
Pandas timespan and groups: Need to groupby/pivot with index as group id with columns that correspond to most recent period values
<p>I have a table that looks like this:</p> <pre><code> Index Group_Id Period Start Period End Value Value_Count 42 1016833 2012-01-01 2013-01-01 127491.00 17.0 43 1016833 2013-01-01 2014-01-01 48289.00 9.0 44 1016833 2014-01-01 2015-01-01 2048.00 2...
<p>Still using <code>pivot</code> </p> <pre><code>df['ID']=df.groupby('Group_Id').cumcount() d1=df.pivot('Group_Id','ID','Value').add_prefix('Value_P') d2=df.pivot('Group_Id','ID','Value_Count').add_prefix('Count_P') pd.concat([d1,d2],axis=1).fillna(0) Out[347]: ID Value_P0 Value_P1 Value_P2 Count_P0 Coun...
python|pandas|time-series|timespan|data-munging
0
369,014
46,868,993
TensorFlow: bazel error when building pip package
<p>Was following <a href="https://stackoverflow.com/questions/41293077/how-to-compile-tensorflow-with-sse4-2-and-avx-instructions">this link</a> to compile TensorFlow library.</p> <p>Using this code <code>bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.2 --config=cuda -k /...
<p>You have to run <code>./configure</code>. That will create a <code>.bazelrc</code> and <code>.tf_configure.bazel</code> file in your Tensorflow workspace.</p> <p>The <code>--config=cuda</code> Bazel flag refers to entries in those two files (they are both text files). The entries typically look like this: <code>bui...
tensorflow|bazel
1
369,015
46,752,321
Plotting Candle Stick in Python
<p>I am trying to plot a candle stick chart in python. Here is my code</p> <pre><code>from pandas_datareader import data as pdr import plotly.plotly as py import plotly.graph_objs as go import fix_yahoo_finance as yf yf.pdr_override() mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31") mcd_candle = ...
<p>The problem must be because you didn't provide the <code>username</code> and <code>api key</code> which you will get from the <code>https://plot.ly/settings/api</code> link. If you want to use <code>plotly online</code> to create this graph. First create an account, then get the <code>username</code> and <code>api k...
python|pandas|plotly|candlestick-chart
4
369,016
47,020,901
TensorFlow Mean Squared Error metric always returns 0
<p>I am encountering a problem where no matter what labels/predictions I pass TF.Metrics.Mean_Squared_Error it always returns a 0 value. </p> <p>Here is code that duplicates the problem:</p> <pre><code>a = tf.constant([0,0,0,0]) b = tf.constant([1,1,1,1]) mse, update = tf.metrics.mean_squared_error(a,b) sess = tf.Se...
<p>I don't really know why it works that way, but you actually need to run <code>update</code> before the inner state of the mse takes your data into account:</p> <pre><code>a = tf.constant([0,0,0,0]) b = tf.constant([1,1,1,1]) mse, update = tf.metrics.mean_squared_error(a,b) sess = tf.Session() sess.run(tf.global_var...
machine-learning|tensorflow|statistics
1
369,017
46,767,001
What is cuDNN implementation of rnn cells in Tensorflow
<p>To create <code>RNN</code> cells, there are classes like <code>GRUCell</code> and <code>LSTMCell</code> which can be used later to create <code>RNN</code> layers.<br> And also there are 2 other classes as <code>CudnnGRU</code> and <code>CudnnLSTM</code> which can be directly used to create <code>RNN</code> layers.</...
<p>In short: cudnnGRU and cudnnLSTM can/ must be used on GPU, normal rnn implementations not. So if you have tensorflow-gpu, cudnn implementation of RNN cells would run faster.</p>
python-3.x|tensorflow|cudnn
0
369,018
47,064,899
Re-indexing a DataFrame with a composite index
<p>I had to load my DataFrame from a text file using the 'index_col=False' option to avoid an offset between the headers and the records.</p> <p>Now that the DataFrame has been properly loaded and cleaned,I need to reindex according to a key that is composed of the first 4 columns. </p> <p>Q1: recommended option: sho...
<p>YOu can simply put the 4 columns in your index with <code>set_index([col1,col2,col3,col4],inplace=True)</code>. You can refer to the documentation: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/g...
pandas|dataframe|python-3.6
1
369,019
46,725,178
how to have two y scales in matplotlib while having a date on x axis
<p>I have the following dataframe :</p> <pre><code> date us_dollar active_user_count 2016-01-01 4.76 1083 2016-01-02 46.78 1558 2016-01-03 60.47 1872 2016-01-04 218.72 1884 2016-01-05 78.90 2068 </code></pre> <p>need to visualize them in a way that m...
<p>Not every datapoint in your plot has its own ticklabel. Here you have 13 ticklabels, but 366 datapoints, hence the error.</p> <p>If you have a dataframe <code>df</code> with three columns <code>x</code>,<code>y</code>,<code>z</code>, you can plot it two twin axes via</p> <pre><code>ax=df[['x','y']].set_index('x')....
python|pandas|matplotlib
0
369,020
46,783,303
Non conformable array error when using rpart with rpy2
<p>I'm using <code>rpart</code> with <code>rpy2</code> (version 2.8.6) on python 3.5, and want to train a decision tree for classification. My code snippet looks like this:</p> <pre><code>import rpy2.robjects.packages as rpackages from rpy2.robjects.packages import importr from rpy2.robjects import numpy2ri from rpy2....
<p>I got around this by creating the dataframe using pandas and passing the panadas dataframe to rpart using rpy2's pandas2ri to convert it to R's dataframe.</p> <pre><code>from rpy2.robjects.packages import importr from rpy2.robjects import pandas2ri from rpy2.robjects import Formula rpart = importr('rpart') pandas2r...
arrays|numpy|python-3.5|decision-tree|rpy2
0
369,021
47,046,218
Format causing issues when converting to datetime (data_string[found.end():]))
<p>I am loading lots of csv files, which I want to plot, that have column titles representing date and time. </p> <p>For example:</p> <pre class="lang-none prettyprint-override"><code>14/01/2015 14:27 14/01/2015 14:27 29.97299 30.05902 30.00391 30.09555 </code></pre> <p>For some reason, different files get ...
<p>That error message means <code>strptime</code> is converting a string that has more information in it than specified in the format, such as seconds or microseconds. For example I get the same error if I try to push '14/01/2015 14:27:00.000' through <code>strptime</code> with the format <code>%d/%m/%Y %H:%M</code>. T...
python|pandas|datetime|dataframe|strptime
1
369,022
47,025,306
Pandas : Add new unnamed columns to existing dataframe
<p>I have an existing dataframe and an np array like so:</p> <pre><code>[[ 0.3397825 0.6602175 ] [ 0.3397825 0.6602175 ] ..., [ 0.89700502 0.10299498]] </code></pre> <p>The number of rows in this array matches my dataframe row count. I just want to add two new columns to my dataframe with column headers like ...
<p>By using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a></p> <pre><code>pd.concat([df,pd.DataFrame(ary,columns=['prob0', 'prob1'])],axis=1) </code></pre> <p>Data Input </p> <pre><code>ary=[[ 0.3397825 , 0.6602175 ], [ 0.3397825...
python|pandas
2
369,023
46,781,143
How to apply mask from array to another matrix in numpy
<p>How you I apply a mask in numpy to get this output?</p> <pre><code>ar2 = np.arange(1,26)[::-1].reshape([5,5]).T ar3 = np.array([1,1,-1,-1,1]) print ar2, '\n\n', ar3 [[25 20 15 10 5] [24 19 14 9 4] [23 18 13 8 3] [22 17 12 7 2] [21 16 11 6 1]] [ 1 1 -1 -1 1] </code></pre> <p>--apply where ar3 = 1...
<p>I don't see why <code>np.where</code> shouldn't work here:</p> <pre><code>&gt;&gt;&gt; np.where((ar3==1)[:, None], ... ar2 // ar2[:, [0]], # where condition is True, divide by first column ... ar2 // ar2[:, [4]]) # where condition is False, divide by last column array([[ 1, 0, 0, 0, 0], ...
python|arrays|pandas|numpy
3
369,024
46,759,741
Spyder appends Tensorboard summary files
<p>When I run my python code from a console, everything works fine: I get one new tensorboard file (626 bytes) every time and I can look it up using the Tensorboard service.</p> <p>But, when I run this code from Spyder IDE, after every run there is a new file that contains data from <strong>all</strong> the runs made ...
<p>Ok, I've found an answer to my own question. There is a setting in Spyder: Tools -> Preferences -> Run -> 'Clear all variables before execution' </p> <p>(also in Run -> Configuration per file... -> 'Clear all variables before execution')</p> <p>Details: <a href="https://github.com/spyder-ide/spyder/issues/2563" re...
python|machine-learning|tensorflow|spyder|tensorboard
1
369,025
46,992,208
Continuing training (image_retraining/retrain.py) by loading an intermediate_output_graphs(.pb)
<p>I'm using the retrain script provided in the image_retraining folder from the tensorflow repository. </p> <p>One of the parser arguments/flags let you store intermediate graphs every X steps</p> <pre><code>parser.add_argument( '--intermediate_output_graphs_dir', type=str, default='tf_files2/tmp/i...
<p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/import_graph_def" rel="nofollow noreferrer">tf.import_graph_def</a> to import your frozen .pb file:</p> <pre><code># Read the .pb file into graph_def. with tf.gfile.GFile(FLAGS.graph, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFrom...
python|tensorflow|deep-learning
1
369,026
46,794,146
Keras models in tensorflow
<p>I'm building image processing network in tensorflow and I want to make use of texture loss. Texture loss seems simple to implement if you have pretrained model loaded. </p> <p>I'm using TF to build the computational graph for my model and I want to incorporate Keras.application.VGG19 model to get output from layer ...
<p>It seems following code does the trick</p> <pre><code>with tf.variable_scope("") as scope: phi_func = VGG19(include_top=False, weights=None, input_shape=(128, 128, 3)) text_1 = phi_func(predicted) scope.reuse_variables() text_2 = phi_func(x) text_loss = tf.reduce_mean((text_1 - text_2)**2) </c...
tensorflow|deep-learning|keras
0
369,027
46,810,642
Python/pandas - Using DataFrame.apply with function returning dictionary
<p>I am aware of how the apply function can be used on a dataframe to calculate new columns and append them to the dataframe. My question is if I have a function which takes as parameters several values (corresponding to the columns currently in the dataframe) and returns a dictionary (corresponding to the columns I wa...
<p>Since you want to retain the previous columns, you can make a Series out of the new columns, and then append that new Series object to the original Series. Keep in mind that the input to <code>get_cols</code> is an individual <strong>row</strong> (and is thus a Series) from the original DataFrame.</p> <pre><code>im...
python|pandas
5
369,028
46,665,233
Python - Sorting Pandas dataframe
<p>if I have a data frame as such:</p> <pre><code>[[19 a, 27 b, 32 c], [21 b, 1 a, 100 c], [], [81 c, 70 a]] </code></pre> <p>how can I sort it to be:</p> <pre><code>[[19 a, 27 b, 32 c], [1 a, 21 b, 100 c], [null, null, null], [70 a, null, 81 c]] </code></pre> <p>Where all a's are in column 1, b's in column 2 a...
<p>I am a little bit confused about your "integer-text" values, but something like this can solve your problem:</p> <pre><code>li = [['19 a', '27 b', '32 c'], ['21 b', '1 a', '100 c'], [], ['81 c', '70 a']] def parse(item): parsed = [] for letter in ['a', 'b', 'c']: match = ''.joi...
python|pandas|sorting|fill
0
369,029
47,047,183
Could someone explain what is happening in this code to save a numpy array as a binary file?
<p>I've been using the pickle library to read and write numpy arrays but they tend to be very large. In my quest for finding out if there was a better way, I found Mark's answer on <a href="https://stackoverflow.com/questions/9619199/best-way-to-preserve-numpy-arrays-on-disk/41425878#41425878">this</a> page (the one wi...
<p>I have (from another question) </p> <pre><code>In [509]: arr Out[509]: array([[-1.0856306 , 0.99734545], [ 0.2829785 , -1.50629471], [-0.57860025, 1.65143654]]) </code></pre> <p>I can format a string with its attributes:</p> <pre><code>In [510]: '%s %d %d'%(arr.dtype, *arr.shape) Out[510]: 'float...
arrays|numpy|format|pickle|binaryfiles
0
369,030
47,018,220
Shifting all columns through a loop in Pandas
<p>I would like to shift my Dataframe through a loop. I have the following dataframe;</p> <pre><code> A B 0 0.0 101 1 0.0 101.996163 2 0.0 209.987279 3 0.0 168.605494 4 0.0 138.245242 </code></pre> <p>I can shift each column by u...
<p>Use another <code>for</code>:</p> <pre><code>for col in df.columns: for i in range(1,5): df["%s_%s_%s"%(col,i,-1)] = df[col].shift(i) print (df) A B A_1_-1 A_2_-1 A_3_-1 A_4_-1 B_1_-1 B_2_-1 \ 0 0.0 101.000000 NaN NaN NaN NaN NaN NaN 1 ...
python|pandas|dataframe
0
369,031
47,079,393
pandas - change value in column based on another column
<p>Say I have a dataframe <code>all_data</code> such as this: </p> <pre><code>Id Zone Neighb 1 NaN IDOTRR 2 RL Veenker 3 NaN IDOTRR 4 RM Crawfor 5 NaN Mitchel </code></pre> <p>I want to input the missing values in 'Zone' column, such that where 'Neighb' is '...
<p>Use np.select i.e </p> <pre><code>df['Zone'] = np.select([df['Neighb'] == 'IDOTRR',df['Neighb'] == 'Mitchel'],['RM','RL'],df['Zone']) </code></pre> <pre> Id Zone Neighb 0 1 RM IDOTRR 1 2 RL Veenker 2 3 RM IDOTRR 3 4 RM Crawfor 4 5 RL Mitchel </pre> <p>In your case of condtions you ...
python|pandas|dataframe
3
369,032
46,792,484
Leap years in pandas.DatetimeIndex.dayofyear
<p>I want to calculate the mean depending of the day of the year from a time series with data over many years. Thereby I encountered a problem when dealing with leap years which is shown in the example below.</p> <pre><code>ind=pd.DatetimeIndex(start='2016-01-01', end='2016-12-31', freq='d') dat=np.arange(1,367,1) ser...
<p>I am not following your complete logic here, but you can use this as a starting point.</p> <pre><code>ind=pd.DatetimeIndex(start='2016-01-01', end='2016-12-31', freq='d') dat=np.arange(1,367,1) ser=pd.Series(dat, index=ind) ser=ser[~((ser.index.month==2)&amp;(ser.index.day==29))] ser = ser.ne(0).cumsum() ser.grou...
python|pandas
0
369,033
46,734,116
numpy how to slice index an array using arrays?
<p>Perhaps this has been raised and addressed somewhere else but I haven't found it. Suppose we have a numpy array: </p> <pre><code>a = np.arange(100).reshape(10,10) b = np.zeros(a.shape) start = np.array([1,4,7]) # can be arbitrary but valid values end = np.array([3,6,9]) # can be arbitrary but valid values </...
<p>We can use <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="noreferrer"><code>broadcasting</code></a> to create a mask of places to be edited with two sets of comparisons against <code>start</code> and <code>end</code> arrays and then simply assign with <code>boolean-indexing</cod...
python|numpy
6
369,034
46,900,364
Select columns with name matching str with wildcard for t-test (Python)
<p>I have</p> <pre><code> Apple f2 m Apple f2 t Apple f3 m Apple f3 t 0 3 4 5 3 1 12 7 4 7 2 5 9 7 5 3 3 3 4 8 4 ...
<p>For future reference. The <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="noreferrer">pandas.Series.str.contains</a> has the param regex set to True by default which means we can use Regex expressions.</p> <p>To find 0 or more of any character we can simply use ...
python|pandas
15
369,035
46,735,745
How to control scientific notation in matplotlib?
<p>This is my data frame I'm trying to plot:</p> <pre><code>my_dic = {'stats': {'apr': 23083904, 'may': 16786816, 'june': 26197936, }} my_df = pd.DataFrame(my_dic) my_df.head() </code></pre> <p>This is how I plot it:</p> <pre><code>ax = my_df['stats'...
<p>Adding this line helps to get numbers in a plain format but with ',' which looks much nicer:</p> <pre><code>ax.get_yaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) </code></pre> <p><a href="https://i.stack.imgur.com/WxM1I.png" rel="noreferrer"><img src="https://i.st...
python-2.7|pandas|matplotlib
16
369,036
46,644,603
What is a very general way to read-in .csv in Python and pandas?
<p>I have a .csv file with rows with multiple columns lengths. </p> <pre><code>import pandas as pd df = pd.read_csv(infile, header=None) </code></pre> <p>returns the </p> <pre><code>ParserError: Error tokenizing data. C error: Expected 6 fields in line 8, saw 8 </code></pre> <p>error. I know I can use the </p> <pr...
<p>OK, somewhat inspired by this related question: <a href="https://stackoverflow.com/questions/31493880/pandas-variable-numbers-of-columns-to-binary-matrix">Pandas variable numbers of columns to binary matrix</a></p> <p>So read in the csv but override the separator to a tab so it doesn't try to split the names:</p> ...
python|pandas|csv|input
4
369,037
32,744,997
Apply Formatting to Each Column in Dataframe Using a Dict Mapping
<p><strong>Problem Setup</strong></p> <pre><code>import pandas as pd df = pd.DataFrame(data={'Currency': {0: 111.23, 1: 321.23}, 'Int': {0: 23, 1: 3}, 'Rate': {0: 0.03030, 1: 0.09840}} ) </code></pre> <p>Produces the following DataFrame</p> <pre><code> Currency In...
<p>The easiest way would be to iterate through the <code>format_mapping</code> dictionary and then apply on the column (denoted by the key) the formatting denoted by the <code>value</code>. Example -</p> <pre><code>for key, value in format_mapping.items(): df[key] = df[key].apply(value.format) </code></pre> <p>De...
python|dictionary|pandas|formatting|dataframe
13
369,038
32,914,447
Pandas idiomatic way to do a dictionary lookup
<p>I have a pandas series of integers (they are restricted to some smallish finite subset) and a dictionary of those possible integers to doubles. I'd like to create a new series that looks like <code>dictionary[series]</code>. What's the pandas idiomatic way to do so?</p>
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> to do this.</p> <p>For example, here's a dictionary mapping a few integers <code>n</code> to <code>n + 0.5</code>, and a Series of integers:</p> <pre><code>&gt;&gt;&gt; d = {1: 1.5...
python|dictionary|pandas|series
1
369,039
32,612,273
py2exe setup.py not working
<p>I have an small code that uses pandas and sqlalchemy and is declared in my main.py as:</p> <pre><code>import pandas as pd from sqlalchemy import create_engine </code></pre> <p>this is my complete setup.py: </p> <pre><code>from distutils.core import setup import py2exe from glob import glob data_files = [("Micros...
<p>without know what your program does I would try the following 1st open a command window and run your .exe from there The window will not close and any error messages (if any) will be displayed</p>
pandas|sqlalchemy|python-3.4|py2exe
0
369,040
33,025,855
ValueError from simple Numpy comparison
<p>I encountered a python issue, I tried various ways but I could not fix it. Would you offer me some hint?</p> <pre><code>sp_step = np.linspace(0.0,2.0,41) #### bin size is 50 Kpc for jj in range(len(sp_step) -1): if sp &gt; sp_step[jj] and sp &lt;= sp_step[jj+1]: stack_num[jj] += 1 stack[jj] = ...
<p>This is one of the more common SO numpy questions. It's the result of some <code>numpy</code> test producing multiple values, and then trying to use that in a Python context that expects only one value.</p> <p>Take a look at this expression (print its result)</p> <pre><code>sp &gt; sp_step[jj] and sp &lt;= sp_ste...
python|numpy
3
369,041
32,744,205
Getting a Basemap projection as a numpy array
<p>This must be possible but I am unsure as to how to approach it. </p> <p>I have a geographical domain, with a set number of lat and lons. Using these, I am able to plot a simple Basemap of the domain:</p> <pre><code>fp_mhd = name.footprints('path/to/file') domain_lon = fp_mhd.lon domain_lat = fp_mhd.lat ### Const...
<p>Have a look at the following function. You should be able to extract the mask as it returns a numpy masked array.</p> <p>.mask returns a Boolean array.</p> <blockquote> <p>mpl_toolkits.basemap.maskoceans(lonsin, latsin, datain, inlands=True, resolution='l', grid=5)</p> <p>returns a masked array the same s...
python|numpy|matplotlib-basemap
1
369,042
32,617,812
How to put 'flat' json data into python data frame?
<p>I'm making an API request and getting data that I'm not sure how to deal with. I would like to have all the data within a pandas dataframe with the 'channel_id' as rows (or index I suppose) and all of the other info as columns. </p> <p>This is the call I make:</p> <pre><code>with requests.Session() as s: r1 = ...
<pre><code>df = pd.DataFrame.from_dict(data['value']['data']) df.set_index(['channel_id'], inplace=True) </code></pre>
python|json|pandas
1
369,043
32,801,806
pandas concat ignore_index doesn't work
<p>I am trying to column-bind dataframes and having issue with pandas <code>concat</code>, as <code>ignore_index=True</code> doesn't seem to work:</p> <pre><code>df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'D': ['D0', 'D1', 'D2', 'D3']}, ...
<p>If I understood you correctly, this is what you would like to do.</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index=[0, 2, 3,4]) df2 = pd.DataFrame({...
python|pandas|append|concat
132
369,044
38,873,345
Replace regions in a raster image with values from another image in python
<p>I have two raster images of the same area and x,y dimensions as numpy arrays. Image 1 is a land-use classification (e.g. with classes 0 to 5) and image 2 is a cloud-shadow mask (with the values: 0 = cloudfree, 255 = cloud/ shadow areas). <br> I want to combine those images. Either take/clip all the 255 values from ...
<p>You can do this with numpy's boolean indexing feature. </p> <pre><code>img1 = np.array([[0, 1, 0, 1],[1, 0, 1, 0]]) img2 = np.array([[1, 2, 3, 4],[5, 6, 7, 8]]) bool_arr = img1 == 0 img1[bool_arr] = img2[bool_arr] print(img1) # outputs: [[1 1 3 1] # [1 6 1 8]] </code></pre>
python|numpy|open-source|gdal
0
369,045
38,927,294
numpy.column_stack with numeric and string arrays
<p>I have several arrays, some of them have float numbers and others have string characters, all the arrays have the same length. When I try to use numpy.column_stack in these arrays, this function convert to string the float numbers, for example:</p> <pre><code>a = np.array([3.4,3.4,6.4]) b = np.array(['holi','xlo','...
<p>The easiest structured array approach is with the <code>rec.fromarrays</code> function:</p> <pre><code>In [1411]: a=np.array([3.4,3.4,6.4]); b=np.array(['holi','xlo','xlo']) In [1412]: B = np.rec.fromarrays([a,b],names=['a','b']) In [1413]: B Out[1413]: rec.array([(3.4, 'holi'), (3.4, 'xlo'), (6.4, 'xlo')], ...
python|numpy
4
369,046
38,892,314
Run random_ops in TensorFlow, TypeError happens
<p>In RMSProp Optimizer <code>tensorflow\python\training\rmsprop.py</code>, I tried to introduce random noise to the algorithm.</p> <p>So I invoked <code>rnd = random_ops.random_normal()</code> to return random values. But, when I run <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/trai...
<p><code>random_ops.random_normal()</code> returns an tensor, instead a <code>Variable object</code> the <code>training_ops.apply_rms_prop(...., rnd, ...).op</code> needs. So I import variables ops, by</p> <blockquote> <p><code>from tensorflow.python.ops import variables</code></p> </blockquote> <p>and construct <c...
tensorflow
0
369,047
38,743,981
What is the theano counterpart of numpy apply_along_axis?
<p>I want to apply some function to a tensor with Theano. Here's my numpy version script. But, I'm lost when converting this to a Theano version.</p> <p>For example, I want to convert </p> <pre><code>array([[[0, 0, 1, 2, 3], [0, 1, 2, 3, 4]]]) </code></pre> <p>to </p> <pre><code>array([[[0, 0, 3, 2, 1], ...
<p>Try it on arrays of different dimensions:</p> <p>For a 1d array, it doesn't add any functionality:</p> <pre><code>In [36]: A=np.arange(10) In [38]: np.apply_along_axis(reverse_and_shift,-1,A) Out[38]: array([0, 9, 8, 7, 6, 5, 4, 3, 2, 1]) In [39]: reverse_and_shift(A) Out[39]: array([0, 9, 8, 7, 6, 5, 4, 3, 2, 1])...
numpy|theano
0
369,048
38,731,491
Add custom legend to bokeh Bar
<p>I have pandas series as:</p> <pre><code>&gt;&gt;&gt; etypes 0 6271 1 6379 2 399 3 110 4 4184 5 1987 </code></pre> <p>And I want to draw Bar chart in Bokeh: <code>p = Bar(etypes)</code>. However for legend I get just <code>etypes</code> index number, which I tried to decrypt with this dictionary...
<p><strong>*Note from Bokeh project maintainers:</strong> This answer refers to an obsolete and deprecated API. For information about creating bar charts with modern and fully supported Bokeh APIs, see the other response.</p> <hr> <p>Convert the series to a DataFrame, add the legend as a new column and then reference...
python|pandas|bokeh
2
369,049
38,572,812
Unexpected behavior from python's relativedelta
<p>I'm getting a confusing result when using Python's timestamps and </p> <blockquote> <p>my_timestamp </p> </blockquote> <p><code>Timestamp('2015-06-01 00:00:00')</code></p> <blockquote> <p>my_timestamp + relativedelta(month = +4)</p> </blockquote> <p><code>Timestamp('2015-04-01 00:00:00')</code></p> <p>Natu...
<p>The issue is that you are using the wrong keyword argument. You want <code>months</code> instead of <code>month</code>. </p> <p>Per <a href="http://dateutil.readthedocs.io/en/stable/relativedelta.html" rel="nofollow">the documentation</a>, <code>month</code> denotes absolute information (not relative) and simply ...
python|datetime|pandas|timestamp|relativedelta
4
369,050
38,575,443
Pandas resample to return just one column after an apply as been made
<pre><code>def wk(args): return args['Open'].mean() - args['Close'].mean() df = pd.DataFrame() df = data.resample("2B").apply(wk) </code></pre> <p>I run the following code on the below dataframe:</p> <pre><code> Open High Low Close Volume Date 201...
<h1>Row-wise Apply and Resampler <em>Dispatch</em></h1> <p>Use a row-wise <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html#pandas-dataframe-apply" rel="nofollow"><code>.apply(func, axis=1)</code></a> and turn your <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries...
python|pandas
3
369,051
38,863,033
how to read the first chunk in a large data frame?
<p>I have a 3GB file and <code>pd.read_csv(...)</code> crashes my iPython notebook so instead I have written (in bad style)</p> <pre><code>df = pd.read_csv("train.csv", chunksize=10**6) for chunk in df: print chunk break </code></pre> <p>What is more correct? I just want to see the first million rows.</p>
<p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking" rel="nofollow"><code>iterator</code></a> parameter to <code>read_csv</code>:</p> <pre><code>reader = pd.read_csv("train.csv", iterator=True) df = reader.get_chunk(10**6) </code></pre> <p>If it's still to big, you can read (and po...
csv|pandas|dataframe
2
369,052
38,861,686
Numpy .shuffle gives the same results each time
<p>I am attempting to take a pandas DataFrame, take out 1 column, shuffle the contents of that column, then place it back into the DataFrame and return it. This is the code used:</p> <pre><code>def randomize(self, data, column): '''Takes in a pandas database and randomizes the values in column. data is the pa...
<p><strong><em>Your code</em></strong></p> <pre><code>def randomize(data, column): df1 = data.copy() newcol = list(data[column]) np.random.shuffle(newcol) df1[column] = newcol return df1 </code></pre> <p><strong><em>My <code>df</code></em></strong></p> <pre><code>df = pd.DataFrame(np.arange(25).r...
python|pandas|numpy|random
1
369,053
38,641,235
Upsample data and interpolate
<p>I have the following dataframe:</p> <pre><code>Month Col_1 Col_2 1 0,121 0,123 2 0,231 0,356 3 0,150 0,156 4 0,264 0,426 ... </code></pre> <p>I need to resample this to weekly resolution and to interpolate between the points. The latter part, the interpolation is straight-...
<p>I have to assume a start date, I chose <code>2009-12-31</code>.</p> <p>To get <code>resample</code> to work, you need a <code>pd.DateTimeIndex</code>.</p> <pre><code>start_date = pd.to_datetime('2009-12-31') df.Month = df.Month.apply(lambda x: start_date + pd.offsets.MonthEnd(x)) df = df.set_index('Month') df.res...
python|pandas|interpolation
1
369,054
38,797,494
un-slicing numpy arrays
<p>Given a sliced numpy array as follows:</p> <pre><code>b = [a[..., i] for i in a.shape[-1]] </code></pre> <p>What is the most simple way I can recreate <code>a</code> from <code>b</code>?</p> <p>Something like:</p> <pre><code>for i in range(a.shape[-1]): c[..., i] = b[i] </code></pre>
<p>Instead of that list comprehension, your original operation should have been</p> <pre><code>b = numpy.rollaxis(a, axis=-1) </code></pre> <p>which produces a view of <code>a</code> as a new array instead of a list of arrays.</p> <p>The reverse operation is</p> <pre><code>c = numpy.rollaxis(b, axis=0, start=b.ndim...
python|numpy
1
369,055
38,905,396
Can I change the number of hidden nodes in my Deep Learning model instead of remaking the entire model?
<p>I'm trying a brute force grid search to find the optimal number of hidden nodes to have in my TensorFlow DeepLearning model. I'm not too concerned about how long the program will take but I've found that my program runs out of memory because of all the tf.variables it has to make. The code to build my model is as fo...
<p>Even though this isn't a perfect answer, I managed to find a workaround. I wrote a shell script that gets a range of numbers based on my interval using the <em>seq starting_number increment ending_number</em> and fed each value into my python code as a command line parameter. This avoids the memory problem since eac...
python|machine-learning|out-of-memory|tensorflow|deep-learning
0
369,056
38,891,974
Creating a Cumulative Frequency Column in a Dataframe Python
<p>I am trying to create a new column named 'Cumulative Frequency' in a data frame where it consists of all the previous frequencies to the frequency for the current row as shown here.</p> <p><a href="https://i.stack.imgur.com/jQ39A.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jQ39A.jpg" alt="ent...
<p>You want <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="noreferrer"><code>cumsum</code></a>:</p> <pre><code>df['Cumulative Frequency'] = df['Frequency'].cumsum() </code></pre> <p>Example:</p> <pre><code>In [23]: df = pd.DataFrame({'Frequency':np.arange(10)}) df Out...
python|pandas|dataframe
9
369,057
38,658,811
Remapping `numpy.array` with missing values
<p>I'm dealing with some large data sets - observations as a function of time - which are not continuous in time (i.e., there is a lot of missing data, where the complete record is absent). To make things fun, there are a lot of data sets, all with missing records, all at random places... </p> <p>I somehow need to get...
<p>If you do <code>d2 = np.intersect1d(dc, d2)</code> before calling <code>dc.searchsorted(d2)</code> it will remove all elements in d2 that are not in dc.</p>
python|numpy
1
369,058
38,716,584
Unable to run TensorFlow on Spark
<p>I am trying to make TensorFlow work on my Spark cluster in order to make it run in parallel. As a start, I tried to use this <a href="https://gist.github.com/tnachen/e004539cdd38e5941d0cb712d0ad3b91" rel="nofollow noreferrer">demo</a> as-is.</p> <p>The demo works great without Spark, but when using Spark, I get the ...
<p>I finally realised that the root-cause is the six module itself - it has some compatibility issues with spark, and whenever it is loaded there are problems.</p> <p>Therefore, to solve the issue I searched for all the usages of the <strong><em>six</em></strong> package in the demo, and replaced them with an equivale...
python|apache-spark|tensorflow|pyspark
4
369,059
38,753,774
running replace method multiple times over a column in Pandas
<p>I am in a situation where I am having to run <code>np.replace</code> multiple times. The goal is to check for strings, such as <code>CASE 1</code>, and if I find it, replace it with some other text. For example, </p> <pre><code>list_1 = [ 'CASE 1', 'CASE 1B' ] list_2 = [ 'CASE 2', 'CASE 2B' ] df.col1 = df.col1.r...
<p>Can you just make a list of lists and iterate over it?</p> <pre><code>list_of_lists = [list_1, list_2] list_replace = ['found_list_1', 'found_list_2'] for i in range(0, len(list_of_lists)): df.col1 = df.col1.replace(list_of_lists[i], list_replace[i]) </code></pre>
pandas|replace
1
369,060
38,668,376
Memory Usage, Filling Pandas DataFrame using Dict vs using key and value Lists
<p>I am making a package that reads a binary file and returns data that can be used to initialize a <code>DataFrame</code>, I am now wondering if it is best to return a <code>dict</code> or two lists (one that holds the keys and one that holds the values). </p> <p>The package I am making is not supposed to be entirely...
<p>I made memory profiling of 1M rows. The winning structure is to use array.array for every numerical index and a list for strings (147MB data and 310MB conversion to pandas).</p> <p>According to Python manual </p> <blockquote> <p>Arrays are sequence types and behave very much like lists, except that the type of...
python|performance|list|pandas|dictionary
4
369,061
38,727,375
Why do jobs in slurm freeze indefinitely when they are TensorFlow scripts?
<p>I am having this error when I use the slurm (<a href="http://slurm.schedmd.com/">http://slurm.schedmd.com/</a>) workload manager. When I run some tensorflow python scripts, sometimes it results in an error (attached). It seems that it can't find cuda library installed but I am running scripts that do not require GPU...
<p>There is some bug in tensorflow operating with slurm submitting via a batch job.</p> <p>Currently I get around it by running srun on slurm.</p> <p>It also appears in your case that you installed the GPU version of tensorflow and are running it on a machine that does not have a GPU. Which is causing another error i...
linux|tensorflow|slurm
1
369,062
63,000,289
How do I convert ANTsR to ANTsPy image querying command?
<p>I am trying to convert the following ANTsR line to ANTsPy:</p> <p><code>seggm[seggm &lt; 0.5 &amp; tmp &gt; 0.5] &lt;- 2</code> (seggm and tmp are both 'ANTsImage's)</p> <p>I have tried:</p> <p><code>seggm[seggm.numpy() &lt; 0.5 &amp; tmp.numpy() &gt; 0.5] = 2</code> but this is too slow.. Is there a faster way to ...
<p>Whoops typed it differently in my code.. This works now!</p>
python|numpy|numpy-ndarray
0
369,063
63,303,109
Finding all files associated with an id within a folder of images?
<p>I'm trying to populate a dataframe based on a class label and images in a folder.</p> <p>I have a folder have over 10,000 images with the following name structure: <code>['leaflet_10000_1.jpg', 'leaflet_10000_2.jpg', 'leaflet_10001_1.jpg', 'leaflet_10001_2.jpg', 'leaflet_10002_1.jpg', 'leaflet_10002_2.jpg', 'leaflet...
<p>You're on the right track!</p> <p>If all IDs are unique and you want an output dataframe with <em>just</em> the party and image number, you can do something like:</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path import numpy as np import pandas as pd partySer = df.loc[:, ['ID', 'Party']]...
python|python-3.x|pandas
2
369,064
63,301,893
Create two new Dataframes from existing one based on unique and repeated values of a column
<pre><code>colA colB A 125 B 546 C 4586 D 547 A 869 B 789 A 258 E 123 </code></pre> <p>I want to create two new dataframe and the first one should be based on the unique values in 'colA' and the second one should be the repeated values of 'colB'. The colB has no repeated values. The firs...
<p>For the first group, use <code>drop_duplicates</code>. For second group, use <code>duplicated</code>:</p> <pre><code>print (df.drop_duplicates(&quot;colA&quot;)) colA colB 0 A 125 1 B 546 2 C 4586 3 D 547 7 E 123 print (df[df.duplicated(&quot;colA&quot;)]) colA colB 4 A 869 5 ...
python-3.x|pandas|dataframe
1
369,065
62,928,147
Pivot pandas dataframe to get resultant dataframe in correct order
<p>I have an excel data in below format:</p> <pre><code> Original Data Frame Package FISCAL_YR SCENARIO PERIOD USD_AMT LY_USD_AMT CY_NetSales LY_NetSales Canada 2021 Plan Per01 1.00 2.00 3.00 4.00 Africa 2021 Actual Per...
<p>Maybe this is what you are looking for: 1- Make your pivot table:</p> <pre><code>import pandas as pd import numpy as np data={&quot;package&quot;:[&quot;Canada&quot;,&quot;Africa&quot;,&quot;Africa&quot;,&quot;Brazil&quot;,&quot;Brazil&quot;,&quot;Africa&quot;,&quot;Mexico&quot;,&quot;Canada&quot;], &quot;scenario&...
python|pandas|pivot-table
1
369,066
63,130,662
How not to use loop in a df when access previous lines
<p>I use pandas to process transport data. I study attendance of bus lines. I have 2 columns to count people getting on and off the bus at each stop of the bus. I want to create one which count the people currently on board. At the moment, i use a loop through the df and for the line n, it does : current[n]=on[n]-off[n...
<p>If I've understood the problem properly, you could calculate the difference between people getting on and off, then have a running total using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>Series.cumsum()</code></a>:</p> <pre><code>impo...
python|pandas
0
369,067
63,191,469
defining a higher dimensional array without using extra memory
<p>I'd like to define a higher dimensional array in terms of a lower dimensional array, without taking up extra storage space. I was wondering if this is possible. I think I have a solution using broadcasting (see below), but I think it will take up extra storage space.</p> <pre><code>aa=np.arange(2).reshape(2,1) bb=np...
<p>You can use <code>np.broadcast_to</code></p> <pre><code>import numpy as np import sys aa=np.arange(2).reshape(2,1) bb=np.zeros((50,2,1)) bb+=aa cc = np.broadcast_to(aa[None]...
python|arrays|numpy|array-broadcasting
1
369,068
62,918,980
Using keras neural network in function
<p>I am trying to implement an algorithm from a paper, using keras, where they train a neural network to approximate a mathematical function f(x) with limited amount of data points. I want the input of the neural network to be x and the output in the form of f(x) = 1 + xN(x), where N(x) is the value from the final dens...
<p>The Add layer is working between two layers and between a layer and a number/ndarray.</p> <p>you can just use it like this:</p> <pre><code>init=np.ones(shape=(10, 1)) inp = Input(shape=(1,)) hidden = Dense(8, activation='relu')(inp) out = Dense(1, activation='linear')(hidden) mul=Multiply()([out, inp]) out = Add()(...
python|tensorflow|keras|neural-network
0
369,069
63,059,606
ValueError when creating a Series
<p>When I run:</p> <pre><code>ser = pd.Series ( data =[ 100, 'Ninguno', 300, 'Texto', 5.3], index =[ 'pablo', 'juan', 'pedro', 'enrique']) ser </code></pre> <p>the result gives me error:</p> <blockquote> <p>ValueError: Length of passed values is 5, index implies 4.</p> </blockquote>
<p>A pandas Series is just a list or array that has an index. You are passing in the index and the data in your call above, but your index is not the same length as the data, so that is the problem. Below, I have added another element to the index to show a successful creation.</p> <p>From the look of your data, it i...
python|pandas
0
369,070
63,080,457
How do I change all the headers in 34 dataframes with a loop?
<p>I have successfully pulled in 31 '*.csv' files and created 31 dataframes with JupyterLab. I was able to adjust the headers in one data frame as needed, but I dread having to apply individually. As my database grows it will be entirely too tedious to adjust each header.</p> <pre><code>filenames = glob.glob('*.csv')...
<p>Since it looks like all dataframes have the same columns... do a loop as you suggested:</p> <pre><code>colnames = {0:'Date', 1:'Open', 2:'High', 3:'Low', 4:'Close'} for i, df in enumerate(dataframes): dataframes[i] = df.drop(0, axis=0).rename(columns=colnames) </code></pre>
python|pandas|dataframe
0
369,071
63,318,411
Pandas - mapping values between DataFrames
<p>I have this <code>df_players</code>:</p> <pre><code> rank player_id posicao 0 39 82730 Goleiro 1 136 100651 Atacante 2 140 87863 Meio-Campista 3 66 83257 Atacante 4 139 101290 Atacante </code></pre> <hr /> <p><code>df_players.info()</code>:</p> <...
<p>You can use pd.merge to bring rank from df_games.</p> <pre><code>df_games.merge(df_players[['rank','player_id']],on='player_id',how='left') </code></pre> <p>You can also see more details from documentation of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofoll...
python|pandas
1
369,072
63,235,370
How to plot histogram of mean of one column while bins are defined by another column in Pandas
<p>I want to plot a histogram for the two columns of my Pandas DataFrame. While the bins are defined by the value of column <code>ratio</code>, e.g. [0-0.1, 0.1-0.2,...,0.9-1.0], instead of the counts like regular histogram, I need to plot the mean value of the other column <code>feet</code> for each bin. I can probabl...
<p>You don't need to create a new column, just pass a function to groupby:</p> <p>Example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'ratio':np.random.rand(100), 'feet': np.random.rand(100)*10}) df.groupby(pd.cut(df.ratio, np.linspace(0,1,11))).feet.mean().plot.bar() </code></pre> <p><a h...
python|pandas|matplotlib|histogram
3
369,073
63,301,529
Dataframe to Sankey Diagram
<p>I want to generate a Sankey Diagram from product data looking like this.</p> <pre><code> id begin_date status 1 01.02.2020 a 1 10.02.2020 b 1 17.02.2020 c 2 02.02.2020 d 2 06.03.2020 b 2 17.04.2020 c </code></pre> <p>For your exp...
<p>Found the answer!</p> <pre><code># assuming df is sorted by begin_date import pandas as pd df = pd.read_csv(r&quot;path&quot;) dfs = [] unique_ids = df[&quot;id&quot;].unique() for uid in unique_ids: df_t = df[df[&quot;id&quot;] == uid].copy() df_t[&quot;status_next&quot;] = df_t[&quot;status&quot;].shift(-1...
python|pandas|sankey-diagram
0
369,074
63,275,672
Eigen and Numpy -> Passing Matrices from Python to C++
<p>I'm working on a simulation project, and I'm trying to figure out the best way to pass matrices between Python and C++. I'm using Python's NumPy and C++'s Eigen library, and I'm using <a href="https://github.com/pybind/pybind11" rel="nofollow noreferrer">PyBind11</a> to get them to communicate with eachother.</p> <p...
<p>Figured out a compromise! I'm going to copy the values from Python to C++ once, and then just past references to the data from C++ to Python.</p>
python|c++|numpy|eigen|pybind11
3
369,075
63,252,485
Keras model in Tensorflow.js: good predictions on images but awful on video?
<p>I have converted a custom Keras model to layersModel for Tensorflow.js. I tested the model by uploading an image and calling the prediction after upload was done. Snippet for prediction:</p> <pre><code>let img = document.getElementById('image') let offset = tf.scalar(255) let tensorImg = tf.browser.fromPixels(img).r...
<p>Even though video is technically made of individual frames it has one important thing which is that those frames exist as a sequence of frames. Your model is not performing well because you trained it to do well on a single frame at a time. When dealing with video data you should be using a CONV(for spatial features...
tensorflow|keras|tensorflow.js
0
369,076
63,275,123
Pandas populate column 'a' using average of cells directly before and after in column 'b'
<p>I have a time series dataset where GPS is missing for every second time interval.</p> <p>I'm hoping to use Pandas to fill these missing values using the average of the GPS directly before and after a data gap.</p> <p>In the example below, it would result in populating columns 'AV_latitude' and 'AV_longitude' at 'tim...
<p>Pandas has a method to deal with <code>NaN</code> values, <code>.fillna</code>. Among other methods, it supports &quot;forward fill&quot; and &quot;backward fill&quot;, a combination of which will give the desired result.</p> <pre><code>df[['lat', 'long']] = ( df[['lat', 'long']].fillna(method='ffill') + df...
python|pandas|cell|average
1
369,077
63,086,169
Selenium only prints one output
<p>I am trying to scrape an ecommerce page... when I try and use selenium to scrape the titles, I only get one output (you can also provide alternative ways to scrape it with BS4)</p> <p>my code..</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys import pandas as pd from bs...
<p>You can do it like this:</p> <pre><code>from bs4 import BeautifulSoup import requests response = requests.get(URL) response = respnose.text soup = BeautifulSoup(response, &quot;lxml&quot;) all_titles = soup.findAll(&quot;span&quot;, class_ = &quot;itemTitle&quot;) for title in all_titles: title = title.find(&q...
python|pandas|selenium|beautifulsoup|python-requests
1
369,078
63,199,318
How to groupby two columns of a dataframe and convert other columns into dict with column header as key
<p><strong>Dataframe:</strong></p> <pre><code>id id_2 salary title allowance name 0420 13.28 100000 director No Tom 0420 13.28 70000 developer Yes Sam 0110 13.12 120000 director No Dave 0110 13.12 75000 developer Yes shaun </code></pre> <p>Groupby id a...
<ul> <li>There is not a one-liner pandas argument that will provide a <code>list</code> of <code>dicts</code> in the shape you're requesting.</li> <li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby</code></a> to select the ...
python|pandas|json-normalize
1
369,079
63,025,829
splitting list and keeping unique identifier for both values - python
<p>I am trying to figure out a way to best map these values to the course name. The results of the data scraped do not have the same values every time. Every time the &quot;Carts&quot; element appears in the list indicates a new course was scraped. After splitting, I am trying to tie the course name to these labels and...
<pre><code>import pandas as pd # initial data cx = ['Course_1', 'Course_1', 'Course_1', 'Course_1', 'Course_2', 'Course_2', 'Course_2', 'Course_2'] ax = ['Carts\nYes - $18', 'Clubs\nYes', 'GPS\nNo', 'Pull-carts\nYes', 'Carts\nYes', 'Clubs\nYes', 'GPS\nNo', 'Pull-carts\nYes'] dicCs = {} # dictionary of courses, each c...
python|pandas|dictionary|split
0
369,080
62,973,539
Split a pipe-delimited series, groupby a separate series, and return the counts of each split value in new columns
<p>Given a dataframe with a pipe-delimited series:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'year': [1960, 1960, 1961, 1961, 1961], 'genre': ['Drama|Romance|Thriller', 'Spy|Mystery|Bio', 'Drama|Rom...
<p>We can get to your desired result using some simple reshaping and aggregation:</p> <pre><code>(df.assign(genre=df['genre'].str.split('|')) .explode('genre') .groupby('year')['genre'] .value_counts(normalize=True) .unstack(fill_value=0)) genre Bio Drama Mystery Romance Spy Thri...
python|pandas|matplotlib
3
369,081
63,004,713
Pandas Oracle query gives "ORA-00911: invalid character"
<p>Hello I am trying to execute the following Oracle Query. I confirmed i can successfully connect to the database using cx_Oracle but my query is not executing. This is a large table and i am trying to limit the number of rows to 10</p> <pre><code>query1 = &quot;&quot;&quot; select * from (select * from some_tabl...
<p>Remove the semi-colon from the SQL statement. Semi-colons are not part of SQL.</p> <pre><code>query1 = &quot;&quot;&quot; select * from (select * from some_table ) where rownum &lt; 10 &quot;&quot;&quot; </code></pre>
python-3.x|pandas|oracle|cx-oracle
1
369,082
62,912,239
tensorflow's Timedistributed equivalent in pyTorch
<p>Is there any equivalent implementation of tensorflow.keras.layers.Timedistributed for pytorch?</p> <p>I am trying to build something like Timedistributed(Resnet50()).</p>
<p><em><strong>Credit to miguelvr on <a href="https://discuss.pytorch.org/t/any-pytorch-function-can-work-as-keras-timedistributed/1346/4" rel="noreferrer">this topic</a>.</strong></em></p> <p>You can use this code which is a PyTorch module developed to mimic the Timeditributed wrapper.</p> <pre><code>import torch.nn a...
tensorflow|pytorch
7
369,083
63,063,875
Pandas Lambda Function Format Month and Day
<p>I have a DF &quot;ltyc&quot; that looks like this:</p> <pre><code>month day wind_speed 0 1 1 11.263604 1 1 2 11.971495 2 1 3 11.989080 3 1 4 12.558736 4 1 5 11.850899 </code></pre> <p>And, i apply a lambda function:</p> <pre><code>ltyc['date'] = pd.to_datetime(ltyc...
<p>create a series with value <code>2020</code> and name <code>year</code>. Concat it to <code>['month', 'day']</code> and passing to <code>pd.to_datetime</code>. As long as, you passing a dataframe with columns names in this order <code>year, month, date</code>, pd.to_datetime will convert it to the appropriate dateti...
pandas|date|lambda
3
369,084
63,104,794
Preprocessing for TensorFlow Dataset 'cats_vs_dogs'
<p>I am trying to create a preprocessing function so that the training_dataset can be directly fed into a keras sequential neural network. The preprocess function should return features and labels.</p> <pre><code>def preprocessing_function(data): features = ... labels = ... return features, labe...
<p>Here are two functions for preprocessing. FIrst one will be applied to both train and validation data to normalize the data and resize to the expected size of network. The second function, augmentation, will be applied to training set only. The type of augmentation you want to do depends on your dataset and applicat...
tensorflow|tensorflow-datasets|feature-selection
1
369,085
62,994,059
A resource failed to call close -flutter/tflite error
<p>I want to do image processing in flutter. I load the ml model(tflite) in flutter. Here I successfully take the image from gallery/camera . I stuck in processing part of the image .I didnt get the required ouput. please help me</p> <pre class="lang-dart prettyprint-override"><code> import 'dart:io'; import '...
<p>The tflite seems to be throwing a BufferOverflowException due to lack of grayscale support on onFrame methods. The issue should have been fixed as mentioned on this <a href="https://github.com/shaqian/flutter_tflite/issues/105#ref-pullrequest-677182611" rel="nofollow noreferrer">GitHub issue ticket</a>.</p>
tensorflow|flutter|dart|flutter-layout|tensorflow-lite
0
369,086
62,986,429
How to remove ending 00:00:00 in timestamp in a series
<p>I am trying to graph coronavirus cases over time, but my timestamps are being weird. I want to remove the 00:00:00 at the end of the timestamp. How can I do this?</p> <p>the index of the series I am plotting:</p> <pre><code>DatetimeIndex(['2020-03-01', '2020-03-02', '2020-03-03', '2020-03-04', '2020-0...
<p>This works to remove 00:00:00 from the dates (<code>df.index.format()</code>) Also, you can create your DatetimeIndex using pandas in a more simplified way.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates #Create the DatetieIndex auto df = pd.DataFrame( index= p...
python|pandas|matplotlib
3
369,087
63,212,247
Precision is lost while reading a column from excel using openpyxl
<p>I'm reading the contents stored in an excel workbook using <code>load_workbook</code> of <code>openpyxl</code>. The following is the code,</p> <pre><code>wb = load_workbook(filename=xlsx_file, read_only=True, data_only=True ) ws = wb.get_sheet_by_name(name=sheet) data = ws.values columns = next(data)[0:] df = pd.Dat...
<p>You just need to set the number of digits after the decimal point:</p> <pre><code>df['t'] = df['t'].map('{:,.1f}'.format) </code></pre>
python-3.x|excel|pandas|precision|openpyxl
1
369,088
63,317,201
Most efficient way of multi groupby count activities on large datasets
<p>I am trying to find subsets (of any lengths) of attribute (column) values, which are unique in a given dataset. The most efficient way to the best of my knowledge to find those is by computing multiple (many) groupby activities counting the corresponding group sizes in pandas. As the loop can become pretty large, wh...
<p>You can use RAPIDS cudf for fast processing of groupbys in large dataset. I'm working on a more nuanced answer for your real question on <strong>efficiency</strong>, but I am spending more time trying to scale out your example than solving for it. Wouldn't mind your help on that by sending me a larger sample. BTW, ...
pandas|group-by|pandas-groupby|cudf
0
369,089
63,170,144
Create DataFrame from subarrays of existing Series object
<p>Could you suggest the method to create DataFrame from Series like I have described below: Input Series</p> <pre><code>s = pd.Series([1,2,3,4,5,6]) </code></pre> <p>Wanted DataFrame:</p> <pre><code> x y z 0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6 </code></pre> <p>Of course I could do it by using ...
<p>I'm not certain that's what you're looking for, but here's a pretty trivial way to do that:</p> <pre><code>df = pd.DataFrame({&quot;x&quot;: s[:-2].values, &quot;y&quot;: s[1:-1].values, &quot;z&quot;: s[2:].values} ) </code></pre> <p>Output:</p> <pre><code> x y z 0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6 </co...
python|pandas
1
369,090
63,221,794
Parse into list by row data frame pandas or nltk
<p>I have a text file which I'm reading with pandas and nltk which is just the alphabet with three colums and an &amp; in the last position for a total of 27 characters. I want to be able to parse the rows into a list. How could I go about doing that?</p>
<p>I'm assuming you have a dataframe and you just want to change each row to a list. This can be done with the following:</p> <pre><code># Create an empty list rowlist =[] # Iterate over each row for index, rows in df.iterrows(): # Create list for the current row my_list =[rows.col1, rows.col2, rows.col...
python|pandas|nltk
0
369,091
63,201,417
How to convert 2 columns into target indicies
<p>I have a mock pandas dataframe consisting of 4 columns (x, y, color, marker). I want to combine the color, marker columns into one column which has a number corresponding to every different color marker pair. I have tried searching online but couldn't find a problem like this one. I have tried bringing in the get_du...
<p>This code seems to work:</p> <pre><code>import pandas as pd dd = { 'Color': ['r','r','r','b'], 'Marker': ['^','*','^','*'] } df = pd.DataFrame(dd) # create lookup table dflkup = df[['Color','Marker']]; dflkup = dflkup.drop_duplicates() # distinct combinations dflkup.insert(0, 'Combined', range(1, len(dflkup)+1...
python|pandas
1
369,092
62,967,509
NoneType object is not subscriptable when extracting instagram comments
<p>The following code tries to extract 10 instagram comments from 10 instagram posts using an Instagram scraper (<a href="https://github.com/realsirjoe/instagram-scraper" rel="nofollow noreferrer">https://github.com/realsirjoe/instagram-scraper</a>). The error encountered is a TypeError (NoneType object is not subscrip...
<p>Try printing 'df' before accessing df['link'] to see if 'link' has any information inside.</p>
python|python-3.x|pandas|web-scraping|python-requests
0
369,093
63,197,794
Error while creating netcdf file using lat long time variable in Python
<p>I have written this code to write the NETCDF file utilizing lat long time variable (e.g. precip). I am reading all datasets from csv files. Therefore, I have made two csv files: (1) containing precipitation time series data (rows 11, columns 9) and (2) containing lat &amp; Longitude (e.g. X, Y). When I am running th...
<p>Well, you can't have time,lat,lon as dimensions on your data because...they're not the dimensionality of your data. The precip data is dimensioned on (think function of) station and time, so those are your dimensions. This is because you don't have a grid where lat and lon are independently varying; instead, they bo...
python|python-3.x|python-2.7|numpy-ndarray|netcdf4
1
369,094
63,184,901
"AttributeError: 'numpy.ndarray' object has no attribute 'values'
<p>Here's a snippet of my code:</p> <pre><code>#code sample for i in range(1, number_of_segments + 1): I1 = (dcm_pixel_array[&quot;array&quot; + str(3 + (i - 1))]) * 2 I8 = (dcm_pixel_array[&quot;array&quot; + str(3 + (7*int((number_of_segments+2)/8)) + (i-1) + 2)]) * 2 for j in range(I1.ndim): for ...
<p>Since the given dataset is already an array, values won't work. Call the array using <code>I8[j][k]</code></p>
python|numpy|matrix|numpy-ndarray|medical-imaging
2
369,095
62,946,716
getting 'list object not callable" in keras Sequential Model
<p>I am trying to build a sequential model as follows, but on running, it is showing list object not callable on tf.keras.layers.Dense(26, activation='softmax')</p> <pre><code> model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(64,(3, 3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooli...
<p>There doesn't seems to be problem with the list that you're passing, neither with the model.</p> <p>This error often occurs when you set the name of a variable as an existing module name, in your case you probably wrote <code>list = [...]</code> or something like that before building this model</p>
python|list|tensorflow|machine-learning|keras
0
369,096
63,045,562
Linear regression plot not giving me meaningful visualization
<p>I am using some time-series power consumption data and trying to do a linear regression analysis on it.</p> <p>The data has the following columns:</p> <p>Date, Denmark_consumption, Germany_consumption, Czech_consumption, Austria_consumption.</p> <p>It is time-series data with a frequency of hours.</p> <p>There are, ...
<p>Your methodology is complicated, but doable. Personally I think it's probably easier to create a linear mapping between Germany's dates and Germany's consumption, then try to make predictions for Denmark's consumption from their dates that way.</p> <p>However, sticking with your method, you should keep in mind that ...
python|pandas|linear-regression|sklearn-pandas
2
369,097
63,118,138
Calculate Mean Values in 2D Array Using Numpy
<p>I have two 2D arrays with similar size of 67x30831. I was wondering how do I average the rows in order to have only one 2D array with size 67x30831 using numpy. Thank you for the help.</p>
<p>If you want to average the 2 arrays, @Quang Hoang's answer would be right:</p> <pre><code>mean = (arr1 + arr2) / 2. </code></pre> <p>If you want to average across rows, use <code>np.mean(arr1, axis=1)</code>, <code>axis=1</code> to compute across columns, so you have 67 means.</p>
python|numpy|multidimensional-array
0
369,098
62,913,828
how to append the last row of one pandas datafram to another
<p>So basically i am iteratively generating a dataframe and after each iteration i want to take the final row of the dataframe and store it in a separate dataframe to be used for future calculations. i have tried the following:</p> <p><code>Storage_Df = Storage_Df.append(Iterating_Df.iloc[-1], ignore_index = True)</cod...
<p>you can use the following.To get the last row you can use dataframe.tail()</p> <pre><code>storage_df=pd.DataFrame() last_row=Iterating_df.tail(1) storage_df=storage_df.append(last_row,ignore_index=True) </code></pre>
pandas|dataframe|append|row|stock
0
369,099
63,075,215
Read html where required table needs user's input
<p>I want to read the table from 'https://coinmarketcap.com/exchanges/bitfinex/', however I need 'pair' to be set to 'USD'. By default it is set to 'All'. Changing 'USD' to 'All' doesnt change the url or anything so when I give the link to pandas_datareader it finds only default table.</p> <p>Is there any way I can re...
<p>It seems this page has all data in HTML and it uses JavaScript to filter data in table when you select <code>USD</code>. So it doesn't use other <code>URL</code> to get data and it doesn't use <code>AJAX</code> to load them from other <code>URL</code> - so you can't get it by changing <code>URL</code></p> <p>You can...
python|pandas|datareader
1