Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
10,300
71,327,256
pandas dataframe style numbers to currency
<p>I have a simple dataframe that contains Dates as columns and numbers as row values. I am attempting to add formatting to the numbers so that they display in currency format of $x.xx. I can't figure out what I am doing wrong as no error is produced and all the other formats I have are being applied except for the cu...
<p>after looking through the official documentation I stumbled upon &quot;number-format&quot; which allowed me to add the currency format I was looking for.</p> <p><a href="https://i.stack.imgur.com/vvVND.png" rel="nofollow noreferrer">here's an image from the docs showing what is acceptable when writing to excel</a></...
python|pandas|dataframe|formatting
2
10,301
71,350,027
Efficient way to "broadcast" the sum of elements of two 1D arrays to a 2D array
<p>Is there a more efficient way (without loops) to do this with Numpy ?:</p> <pre class="lang-py prettyprint-override"><code>for i, x in enumerate(array1): for j, y in enumerate(array2): result[i, j] = x + y </code></pre> <p>I was trying to use einsum without success yet.</p> <p>Thank you !</p>
<p>Simply use broadcasting with an extra dimension:</p> <pre><code>result = array1[:,None]+array2 </code></pre>
python|numpy|optimization|array-broadcasting|numpy-einsum
2
10,302
71,182,988
Pandas Dataframe: Dropping Selected rows with 0.0 float type values
<p>Please I have a dataset that contains amount as float type. Some of the rows contain values of 0.00 and because they skew the dataset, I need to drop them. I have temporarily set the &quot;Amount&quot; to index and sorted the value as well. Afterwards, I attempted to drop the rows after subsetting with <strong>iloc<...
<p>You could make a boolean frame and then use any</p> <pre><code>df = df[~(df == 0).any(axis=1)] </code></pre> <p>in this code, all rows that have at least one zero in their data has been removed</p>
python-3.x|pandas|dataframe|subset|delete-row
0
10,303
52,255,307
Reshape Dataframe pandas with merge cell
<p>I have </p> <pre><code>df = pd.DataFrame({ 'key': ['value1','value2','value1','value2'], 'domain': ['domain1.com','domain1.com','domain2.com','domain2.com'], 'url' :['urlB','urlA','url1','url2'], 'score' : [12,14,200,2001]}) </code></pre> <p>I'd like to get result <a href="https://i.stack.imgur.com/jQt1W.jpg" rel...
<p>Use:</p> <pre><code>df = df.set_index(['key','domain']).unstack().swaplevel(0,1, axis=1).sort_index(axis=1) print (df) domain domain1.com domain2.com score url score url key value1 12 urlB 200 url1 value2 14 urlA...
python|pandas
3
10,304
52,134,130
How to restrict the absolut value of each dimention of a sparse gradient from being too large?
<p>Consider the code below:</p> <pre><code>import tensorflow as tf inputs=tf.placeholder(tf.int32, [None]) labels=tf.placeholder(tf.int32, [None]) with tf.variable_scope('embedding'): embedding=tf.get_variable('embedding', shape=[2000000, 300], dtype=tf.float32) layer1=tf.nn.embedding_lookup(embedding, inputs) ...
<p>Now I use this, it works well.</p> <pre><code>grads=[tf.IndexedSlices(tf.clip_by_value(g.values, -max_grad_value, max_grad_value), g.indices, g.dense_shape) if isinstance(g, tf.IndexedSlices) else tf.clip_by_value(g, -max_grad_value, max_grad_value) for g in grads] </code></pre>
python|tensorflow|sparse-matrix|gradient
0
10,305
52,440,927
pandas merging 300 dataframes
<p>The purpose of this code is</p> <ol> <li>Scrape a 300 of tables via Pandas and Beautiful Soup</li> <li>Concatenate this tables into a single data frame The code works fine for the first step. But it is not working in the second.</li> </ol> <p>Here is the code:</p> <pre><code>import pandas as pd from urllib.reques...
<p>The Pandas concat function takes a <em>sequence or mapping of Series, DataFrame, or Panel objects</em> as it's first argument. Your code is currently passing a single DataFrame.</p> <p>I suspect the following will fix your issue:</p> <pre><code>import pandas as pd from urllib.request import urlopen, Request from b...
python|pandas|beautifulsoup
4
10,306
60,593,624
Modify trained model architecture and continue training Keras
<p>I want to train a model in a sequential manner. That is I want to train the model initially with a simple architecture and once it is trained, I want to add a couple of layers and continue training. Is it possible to do this in Keras? If so, how? </p> <p>I tried to modify the model architecture. But until I compile...
<p>Without knowing the details of your model, the following snippet might help:</p> <pre><code>from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Input # Train your initial model def get_initial_model(): ... return model model = get_initial_model() model.fit(...) model.save_...
python|tensorflow|keras|pre-trained-model
4
10,307
72,577,958
Tensorflow layer expects 1 tensor input, but getting two tensor input
<p>I am new to deep learning currently trying to learn neural network.However,I encountered this problem while training the neural network.</p> <p>This is the input .I thought by using the tensor Dataset I am ready to pass the values into the model I build.My train.values is the feature while trainLabel is the label(ou...
<p>This issue is similar to your <a href="https://stackoverflow.com/questions/72568479/typeerror-inputs-to-a-layer-should-be-tensor">other</a> issue in Stackoverflow and please refer to the answer mentioned in the answer section.</p> <p>Please change the <code>input_shape</code> in the model definition here likewise me...
python|tensorflow|keras
0
10,308
72,581,494
How does tensorflow handle training data passed to a neural network?
<p>I am having an issue with my code that I modified from <a href="https://keras.io/examples/generative/wgan_gp/" rel="nofollow noreferrer">https://keras.io/examples/generative/wgan_gp/</a> . Instead of the data being images, my data is a (1001,2) array of sequential data. The first column being the time and the second...
<p>'Why is the 60000 now None?': In defining TensorFlow models, the first dimension (batch_size) is None. Getting under the hood of what goes on with TensorFlow and how it uses graphs for computation can be quite complex. But for your understanding right now, all you need to know is that batch_size does not need to be ...
python|tensorflow|keras|generative-adversarial-network
1
10,309
61,841,560
How to add Keras- Gaussian noise to image data
<p>Importing the modules:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.layers import GaussianNoise from tensorflow.keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() </code></pre> <p>Re-scaling th...
<p>Type casting is costly, and so Tensorflow doesn't do automatic type casting. As a default, Tensorflow's dtype is <code>float32</code>, and the dataset you imported has a dtype <code>float64</code>. You will just have to pass the optional dtype argument to <code>GaussianNoise</code>:</p> <pre><code>sample = GaussianN...
python|tensorflow|keras
4
10,310
61,753,567
Convert cumsum() output to binary array in xarray
<p>I have a 3D x-array that computes the cumulative sum for specific time periods and I'd like to detect which time periods meet a certain condition (and set to 1) and those which do not meet this condition (set to zero). I'll explain using the code below:</p> <pre><code>import pandas as pd import xarray as xr import ...
<p>Solved this using some masking and the backfill functionality:</p> <pre><code># make something to put results in out = xr.full_like(cumulative, fill_value=0.0) # find the points which have met the criteria out.values[cumulative.values &gt; 3] = 1 # fill the other valid sections over 0, with nans so we can fill the...
python|numpy|python-xarray|cumsum
0
10,311
57,807,496
Parse SQL parameter marker with pandas using dynamic tables
<p>I have the following code:</p> <pre><code>query = """ DECLARE @DATABASE VARCHAR(128) = '{}'; DECLARE @SCHEMA VARCHAR(128) = '{}'; DECLARE @TABLE VARCHAR(128) = '{}'; DECLARE @sql VARCHAR(200) = 'SELECT * FROM ' + CONCAT(QUOTENAME(@DATABASE), '.', QUOTENAME(@SCHEMA), '.', QUOTENAME(@TABLE), ' WH...
<p>I have been able to solve it!</p> <p>Instead of trying to execute directly the sql statement in one step, I first construct the sql query, and generate its final form:</p> <pre><code>SELECT * FROM [DB].[SCHEMA].[TABLE] WHERE COD = ? </code></pre> <p>Then, I call <code>read_sql_query</code> passing in the params</...
python|pandas|pyodbc
2
10,312
57,986,730
How to apply the value from specific row within the group in a column python 3.7
<h1>GOAL</h1> <p>Use the value which is No.1 in "Group_Line" column within the group to overwrite "-" of the rest of rows in every group, without influence the group which doesn't have any "Name" value but "-".</p> <pre><code> Name Group Group_Line NEW_Name 0 Paul A-1 1 Paul 1 - A-1 ...
<p>Reason of error is <code>NAME_IND</code> is not column, but index, what is perfect for mapping, so only specify column <code>Name</code> after <code>groupby</code> and then <code>map</code> by <code>Series</code> called <code>y</code>:</p> <pre><code>y= (xx.sort_values(by=['Group','Group_Line'],ascending=True) ...
python-3.x|pandas-groupby
2
10,313
58,151,772
Python Appending DataFrame, weird for loop error
<p>I'm working on some NFL statistics web scraping, honestly the activity doesn't matter much. I spent a ton of time debugging because I couldn't believe what it was doing, either I'm going crazy or there is some sort of bug in a package or python itself. Here's the code I'm working with:</p> <pre><code>import pandas ...
<p>I don't really follow what the overall aim is but I do note two things:</p> <ol> <li><p>You either need the local <code>game_df</code> to be declared as <code>global game_df</code> before <code>game_df = game_df.append(temp_row,ignore_index=True)</code> or better still pass as an arg in the def signature though yo...
python|pandas|loops|for-loop|append
1
10,314
54,933,438
Python Seaborn Pandas Dataframe plot first few groups
<p>I have a need to plot only the first n number of groups, or plot several plots of n items out of a set of groups from a pandas dataframe. The frame contains columns as </p> <pre><code>import pandas as pd import seaborn as sns; sns.set() import numpy as np datain = np.loadtxt("data.txt") df = pd.DataFrame(data = da...
<p>If you specifically need multiple groups (polymers) plotted together on the same chart, you can subset/filter your dataframe to only the polymer (p) values that you need for your plot, e.g.:</p> <pre><code>df[df['p'].isin([0,1])] </code></pre> <p>and pass the output to the scatterplot command.</p>
python|pandas|grouping|seaborn
1
10,315
49,520,906
Changing zero to x in multidimensional array
<p>I have a 3-dimensional array in python, and would like to learn how to find and replace given elements</p> <p>For example, </p> <pre><code>x = np.array([[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]], np.int32) </code></pre> <p>I'd like to replace each 0 with x in the array, which would result in:</p> <pre><code>([[...
<p>Can do something like:</p> <pre><code>x[x==0] = 10 </code></pre>
python|python-3.x|python-2.7|numpy
2
10,316
49,633,220
Serialized data doesn't match deserialized data in tenserflow TFRecordDataset code
<p>I have a large dataset of numpy integers which I want to analyze with a GPU. The dataset is too large to fit into main memory on the GPU so I am trying to serialize them into a TFRecord and then use the API to stream the record for processing. The below code is example code: it wants to create some fake data, serial...
<p>Instead of </p> <pre><code>sess.run(iterator.initializer) while True: try: sess.run(next_element) fil,m,n = (next_element[0],next_element[1],next_element[2]) with sess.as_default(): print("fil.shape: ",fil.eval().shape) print("M: ",m.eval()) print("N: ...
python|tensorflow|tfrecord
0
10,317
49,538,497
How to apply function to slice of columns using .loc?
<p>I have a pd DataFrame with integers displayed as strings:</p> <pre><code>frame = pd.DataFrame(np.random.randn(4, 3), columns=list('ABC'), index=['1', '2', '3', '4']) frame = frame.apply(lambda x: x.astype(str)) </code></pre> <p>This gives me a dataframe:</p> <pre><code> A B C 1 -0.890 0.162 0.477 ...
<p>You can pass kwargs to <code>apply</code></p> <h3>In Line with <code>assign</code></h3> <pre><code>frame.assign(**frame.loc[:, 'B':'C'].apply(pd.to_numeric, errors='coerce')) A B C 1 -1.50629471392 -0.578600 1.651437 2 -2.42667924339 -0.428913 1.265936 3 -0.866740402265 -0....
python|pandas|dataframe|apply
9
10,318
73,336,285
Make a new dataframe from multiple dataframes
<p>Suppose I have 3 dataframes that are wrapped in a list. The dataframes are:</p> <pre><code>df_1 = pd.DataFrame({'text':['a','b','c','d','e'],'num':[2,1,3,4,3]}) df_2 = pd.DataFrame({'text':['f','g','h','i','j'],'num':[1,2,3,4,3]}) df_3 = pd.DataFrame({'text':['k','l','m','n','o'],'num':[6,5,3,1,2]}) </code></pre> <p...
<p>You can extract the wanted columns with a list comprehension and <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> them:</p> <pre><code>pd.concat([d['text'].rename(f'topic_{i}') for i,d in enumerate(df_list, start=1)], axi...
python|pandas
2
10,319
67,328,047
Filtering pandas dataframe on condition over NaN
<p>I have a datetime dataframe in pandas like this:</p> <pre><code> date value1 value2 name 0 2020-08-27 07:30:00 28.0 27.0 A 1 2020-08-27 08:00:00 28.2 27.0 A 2 2020-08-27 09:00:00 NaN 27.5 A 3 2020-08-27 09:30:00 29.0 NaN A 4 2020-08-27 10:30:00 NaN ...
<pre><code>&gt;&gt;&gt; df.set_index(&quot;name&quot;) \ .loc[df[[&quot;value1&quot;, &quot;value2&quot;]] \ .isna() \ .groupby(df[&quot;name&quot;]) \ .sum() \ .max(axis=&quot;columns&quot;) &lt; 3] date value1 value2 name A 2020-08-27...
pandas
0
10,320
67,422,881
How do I count the number of unique values in a csv using Python
<p>Maybe someone can post another question that already has an answer to my question, but I have been unable to find it.</p> <p>My dataset is a 10,000+ row csv that looks like this:</p> <pre><code> col_1 col_2 a, b, c, d 9 a, b, c 3 b, d 5 a, c, e 1 </code></...
<p>Get the dummies, multiply then sum:</p> <pre><code>df['col_1'].str.get_dummies(&quot;,&quot;).mul(df['col_2'],axis=0).sum() </code></pre> <hr /> <pre><code>a 13 b 17 c 13 d 14 e 1 dtype: int64 </code></pre>
python|python-3.x|pandas|for-loop|iteration
2
10,321
60,325,018
read excel cell containing formulas with link to external workbook with numpy/panda
<p>I need to read an excel file with a cell containing a reference to an external excel workbook in the same path as the origin excel file. Is there any function/parameter to get the reference in such cell with numpy/panda?</p>
<p>This seems to work.</p> <pre><code>from openpyxl import load_workbook import pandas as pd wb = load_workbook(filename = 'C:\\your_path\\Book1.xlsx') sheet_names = wb.get_sheet_names() name = sheet_names[0] sheet_ranges = wb[name] df = pd.DataFrame(sheet_ranges.values) df </code></pre> <p>Result:</p> <pre><code> ...
python|numpy|reference|external
0
10,322
65,201,940
Improving accuracy of multinomial logistic regression model built from scratch
<p>I am currently working on creating a multi class classifier using numpy and finally got a working model using softmax as follows:</p> <pre><code>class MultinomialLogReg: def fit(self, X, y, lr=0.00001, epochs=1000): self.X = self.norm_x(np.insert(X, 0, 1, axis=1)) self.y = y self.classes ...
<ol> <li>This looks right, but I think the preprocessing you perform in the fit function should be done outside of the model.</li> <li>It's hard to know whether this is good or bad. While the loss landscape is convex, the time it takes to obtain a minima varies for different problems. One way to ensure you've obtained ...
python|numpy|logistic-regression
1
10,323
65,356,414
How to apply a function to every element in a dataframe?
<p>This is probably a very basic question but I can't find the answer in other questions. I have two lists that I have used to create a 2D dataframe, let's say:</p> <pre class="lang-py prettyprint-override"><code>X= np.arange(0, 2.01, 0.25) Y= np.arange(10, 30, 5.0) df = pd.DataFrame(index = X, columns = Y) print(df)...
<p>Since your problem requires access to both the index and column labels of your <code>df</code> you probably want <code>df.apply()</code>.</p> <p><code>df.apply()</code> has access to a <code>pandas.Series</code> representing each row/column (dependent on <code>axis</code> argument value) and you will have access to ...
python|pandas|dataframe|numpy
3
10,324
65,382,599
difference between detectObjectOnImage and runModelonImage in tflite flutter
<p>I'm trying to make a tflite multiple object detector in flutter I came across two function which takes image path as input that's why this question.</p> <p>the two function are <code>detectObjectOnImage</code> and <code>runModelOnImage</code> and when I use <code>runModelOnImage</code> my code is running and if I sw...
<p>The difference between the two functions are their usages:</p> <p>For object detection you use Tflite.detectObjectOnImage()</p> <p>For image classification (finding objects without printing boxes around them) you use Tflite.runModelOnImage()</p> <p>The two Methods return different sized tensors. When the Tensors can...
flutter|adb|tensorflow-lite
1
10,325
65,185,120
Why does my Keras LSTM model perform horrible compared to RandomForest on timeseries forecasting?
<p>I have a DataFrame predicting the number of vehicles passing a road based on some sensor data.</p> <p>The DataFrame is shaped on the following format, and is indexed based on the timestamp</p> <pre><code> index | t | t - 1 | t - 2 | .... | t - 95 | number of cars 2020-08-01 : 00:00:...
<p>I think the main problem is that your <code>y_train</code> and <code>y_test</code> are not standardized.</p> <p>Also, for <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM" rel="nofollow noreferrer">LSTM</a> layer, you should not change the activation.</p>
python|tensorflow|keras
0
10,326
65,482,453
How to filter pandas dataframe column by multiple conditions
<p>I am trying to find median revenue in 2013 for US, France and Spain. My pandas dataframe looks like <a href="https://i.stack.imgur.com/SaTGx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SaTGx.png" alt="enter image description here" /></a></p> <p>I am using the following code</p> <pre><code> df[...
<p>To filter a value between different possibilities, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a></p> <pre><code>df[(df.year == 2013) &amp; (df.country.isin(['US', 'FR', 'ES']))] </code></pre>
python|pandas
3
10,327
49,823,963
Get index of one series into another in pandas
<p>I have two series, and I want to get the index of each value of one series into the other:</p> <pre><code>import pandas as pd s1 = pd.Series(list('ABCDE'), index=range(1, 6)) s2 = pd.Series(list('BDAACE')) expected_result = pd.Series([2, 4, 1, 1, 3, 5]) assert pd.some_operation(s1, s2).equals(expected_result) </c...
<p>Using <code>Series</code> <code>get</code></p> <pre><code>pd.Series(s1.index,index=s1).get(s2) Out[416]: B 2 D 4 A 1 A 1 C 3 E 5 dtype: int64 </code></pre>
python|pandas
3
10,328
49,865,478
Forward propagation slow - Training time normal
<p>I'm having trouble figuring out why when I perform forward propagation my code is extremely slow. The code in question can be found here: <a href="https://github.com/rekkit/lazy_programmer_ml_course/blob/develop/05_unsupervised_deep_learning/poetry_generator_rnn.py" rel="nofollow noreferrer">https://github.com/rekki...
<p>I've figured it out. Every time I call the predict method I'm rebuilding the graph. Instead, in the fit method I define a variable:</p> <pre><code>preds = self.predict(self.tfX) </code></pre> <p>and then every time I need the predictions, instead of using:</p> <pre><code>predictions = self.session.run(self.predic...
python|python-3.x|performance|tensorflow|tensorboard
3
10,329
63,770,159
How to convert time in days, hours, minutes, and seconds to only seconds
<p>I have the following dataframe column:</p> <p><img src="https://i.stack.imgur.com/kqQfy.png" alt="Columm of Dataset" /></p> <p>I need to convert object string data from the csv column into total seconds.</p> <p>Example: 10m -&gt; 600s</p> <hr /> <p>I tried this code:</p> <pre><code>df.duration = str(datetime.timedel...
<ul> <li>The correct, and vectorized way to convert <code>'duration'</code> to seconds is to: <ol> <li>Convert <code>'duration'</code> to a timedelta</li> <li>Divide by <code>pd.Timedelta(seconds=1)</code></li> </ol> </li> <li>The correct way to get seconds for only the hours, minutes and seconds component is to use <c...
python|pandas|dataframe|csv|data-analysis
3
10,330
63,076,679
Creating an aggregate columns in pandas dataframe
<p>I have a pandas dataframe as below:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'ORDER':[&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;], 'var1':[2, 3, 1, 5],'a1_bal':[1,2,3,4], 'a1c_bal':[10,22,36,41], 'b1_bal':[1,2,33,4], 'b1c_bal':[11,22,3,4], 'm1_bal':[15,2,35,4]}) df ...
<p>You could try something like this. I am not sure if its exactly what you are looking for, but I think it should work.</p> <pre><code>dfforgroup = df.set_index(['ORDER','var1']) #Creates MultiIndex dfforgroup.columns = dfforgroup.columns.str[:2] #Takes first two letters of remaining columns df2 = dfforgroup.groupby(d...
python-3.x|pandas
0
10,331
62,970,806
Expand DatasetV1Adapter shape grey scale image shape to 3 channels to make use of pretrained models
<p>I want to use the pre-trained model MobileNetV2 in order to classify the <a href="https://www.tensorflow.org/datasets/catalog/binary_alpha_digits" rel="nofollow noreferrer">Binary Alpha Data</a>. However, this data comes in shape <code>(20, 16, 1)</code> (greyscale one channel) and not as needed <code>(20, 16, 3)</c...
<p>Just from looking at it, shouldn't</p> <pre><code>def format_example(image, label): image = tf.cast(image, tf.float32) image = image*1/255.0 image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE)) image = tf.image.grayscale_to_rgb(image) return image, label </code></pre> <p>be the easiest solution.</p>
python|tensorflow|image-processing|rgb|tensorflow-datasets
2
10,332
63,248,888
Save preprocessing Tensorflow Transform function
<p>Currently we have a model that we are going to use for our API using Tensorflow Serving. Therefore we need to transform the current API input data into the features. As the creation of the model and the usage of the model are performed in two different repos, and I don't want to have the transformations in two diffe...
<p>Anything running in TensorFlow Serving is just a TensorFlow graph, whether that's the model itself or your preprocessing steps. All you'd need to do to fold the two together is to connect the two graphs by substituting the output of the preprocessing step as the input to the model, assuming that's compatible.</p> <p...
tensorflow|tensorflow-serving|tensorflow-transform
1
10,333
67,800,802
numpy function to reorder along an axis
<p>Is there an easier way (np function) to achieve the following? <code>bb</code> is the output I'm looking for.</p> <pre><code>import numpy as np aa = np.arange(4*4*3).reshape(4,4,3) bb = np.stack((aa[:,:,2],aa[:,:,1],aa[:,:,0]),axis=2) </code></pre> <p>I don't think <code>np.roll</code> is applicable here, because it...
<p>You could just use -1 as the step argument on last axis while indexing to create a reverse array along that axis:</p> <pre><code>In [10]: bb = aa[:,:,::-1] </code></pre>
python|arrays|numpy
2
10,334
67,921,404
What is the difference between the 'set' operation using loc vs iloc?
<p>What is the difference between the 'set' operation using loc vs iloc?</p> <pre><code>df.iloc[2, df.columns.get_loc('ColName')] = 3 #vs# df.loc[2, 'ColName'] = 3 </code></pre> <p>Why does the website of iloc (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow...
<p>There isn't much of a difference to say. It all comes down to your need and requirement.</p> <p>Say you have label of the index and column name (most of the time) you are supposed to use <code>loc</code> (location) operator to assign the values.</p> <p>Whereas like in normal matrix, you usually are going to have on...
pandas
0
10,335
61,566,919
example of doing simple prediction with pytorch-lightning
<p>I have an existing model where I load some pre-trained weights and then do prediction (one image at a time) in pytorch. I am trying to basically convert it to a pytorch lightning module and am confused about a few things.</p> <p>So currently, my <code>__init__</code> method for the model looks like this:</p> <pre><c...
<p><code>LightningModule</code> is a subclass of <code>torch.nn.Module</code> so the same model class will work for both inference and training. For that reason, you should probably call the <code>cuda()</code> and <code>eval()</code> methods outside of <code>__init__</code>.</p> <p>Since it's just a <code>nn.Module</c...
pytorch|pytorch-lightning
9
10,336
61,277,181
Adding R-value (correlation) to scatter chart in Altair
<p>So I am playing around with the Cars dataset and am looking to add the R-value to a scatter chart. So I can use this code to produce a scatter chart using <code>transform_regression</code> to add a regression line which is great.</p> <pre><code>from vega_datasets import data import altair as alt import pandas as pd...
<p>You can do this by adding a text layer:</p> <pre><code>text = alt.Chart({'values':[{}]}).mark_text( align="left", baseline="top" ).encode( x=alt.value(5), # pixels from left y=alt.value(5), # pixels from top text=alt.value(f"r: {corl:.3f}"), ) chart + text + chart.transform_regression('Miles_per_...
python|pandas|numpy|correlation|altair
5
10,337
68,687,299
python pandas change order and column name after merge
<p>I have merged two dataframes with multiple overlapping columns. I would like to put the columns side by side.</p> <pre><code>merge = df1.merge(df2) </code></pre> <p>For example, Current Output:</p> <pre><code>YEAR_x,DATE_x,MAX_x,MIN_x,YEAR_y,DATE_y,MAX_y,MIN_y </code></pre> <p>I want the output to be:</p> <pre><code...
<p>Use <code>pd.merge</code> with <code>suffixes</code> parameter:</p> <pre><code>merge = df1.merge(df2[set(df2) &amp; set(df1)], suffixes=('', '_auto')) </code></pre> <p>To sort your columns as df1:</p> <pre><code>cols = sorted(merge.columns, key=lambda x: df1.columns.get_loc(x.split('_')[0])) </code></pre> <p>Example...
python|pandas|merge
3
10,338
68,839,011
Python/Keras: LeakyRelu using tensorflow
<p>I am having problems installing keras. The following are giving me too much trouble to get around (even when doing updates on the terminal):</p> <pre><code>from keras.layers import Dense, Activation from keras.models import Sequential </code></pre> <p>So instead of initialising a ANN with <code>ann = Sequential()</c...
<p>To use LeakyReLU in a layer you can do this:</p> <pre class="lang-py prettyprint-override"><code>ann.add(tf.keras.layers.Dense( units=32, activation=tf.keras.layers.LeakyReLU(alpha=0.3))) </code></pre>
python|tensorflow|keras|deep-learning|relu
1
10,339
52,940,677
AWS Sagemaker: AttributeError: module 'pandas' has no attribute 'core'
<p>Let me prefix this by saying I'm very new to tensorflow and even newer to AWS Sagemaker.</p> <p>I have some tensorflow/keras code that I wrote and tested on a local dockerized Jupyter notebook and it runs fine. In it, I import a csv file as my input.</p> <p>I use Sagemaker to spin up a jupyter notebook instance wi...
<p>Pull our data from S3 for example:</p> <pre><code>import boto3 import io import pandas as pd # Set below parameters bucket = '&lt;bucket name&gt;' key = 'data/training/iris.csv' endpointName = 'decision-trees' # Pull our data from S3 s3 = boto3.client('s3') f = s3.get_object(Bucket=bucket, Key=key) # Make a dat...
pandas|tensorflow|amazon-sagemaker
1
10,340
53,285,454
Apply scikit-learn murmurhash3_32 on a Pandas dataframe
<p>I try to apply murmurhash on a pandas dataframe. I wanted to use scikit-learn murmurhash3_32 (any other easy proposition would be appreciated). I tried</p> <pre><code>import pandas as pd from sklearn.utils.murmurhash import murmurhash3_32 df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000]}, dtype='int32') df.ap...
<p>Stupid mistake, not sure if I should delete my question:</p> <p>Apply will pass a series to the function.</p> <p>Using applymap works as expected as it pass every element to the function.</p>
python|pandas|scikit-learn|murmurhash
1
10,341
53,154,192
Sum the duplicate rows of particular columns in dataframe
<p>I want to add the particular columns (C, D, E, F, G) based on the duplicate rows of column B. Whereas the remaining non-duplicate rows unchanged. The output of column A must be the first index of duplicate rows.</p> <p>I have a dataframe as follows:</p> <pre><code>A B C D E F G box1 0487 1 1 ...
<p>Create dictionary of columns names with aggregate functions and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="noreferrer"><code>agg</code></a>, also here is necessary <code>min_count=1</code> to <code>sum</code> for avoid <code>0</code> for...
python|pandas|dataframe
7
10,342
53,016,253
Pandas DataFrame parsing for integers
<p>This is how my df looks</p> <pre><code>person_a done 37918 , 37925 to37932 ,37934 to 37939 (17 ) person_b Done 37940 to 37950 (12 ) and 38101 to 38109 ( 9 ) </code></pre> <p>(Couldn't find a good way to show them side by side, person_a and person_b are columns). I need to parse all integers outside the <code>()</...
<p>maybe not so short but i think with some regex and list manipulation it is possible. first i extracted the numbers from the string for each person </p> <pre><code>df1.replace(to_replace=['\(\d+ \)','\( \d+ \)','Done','done'],value='', regex=True, inplace=True) df1.replace(to_replace=['to'],value='-', regex=True, ...
python|pandas
1
10,343
53,230,880
Python: how to replicate the same row of a matrix?
<p>How can I copy each row of an array <em>n</em> times?</p> <p>So if I have a <code>2x3</code> array, and I copy each row 3 times, I will have a <code>6x3</code> array. For example, I need to convert <code>A</code> to <code>B</code> below:</p> <pre><code>A = np.array([[1, 2, 3], [4, 5, 6]]) B = np.arr...
<p>If I read correctly, this is probably what you want assuming you started with <code>mat</code>:</p> <pre><code>transformed = np.concatenate([np.vstack([mat[:, i]] * 3).T for i in range(mat.shape[1])], axis=1) </code></pre> <p>Here's a verifiable example:</p> <pre><code># mocking a starting array import string mat...
python|arrays|numpy|matrix
1
10,344
65,600,720
Computing network properties for subset of nodes
<p><strong>Context:</strong> I have two panda dataframes that characterize a network, <code>df_nodes</code> and <code>df_edges</code>. They can be matched through a shared identfier, <code>id</code>.</p> <p><code>df_nodes</code> looks roughly like this:</p> <pre><code> id: att_1: att_2: att_3: id1 red...
<p>I expect that filtering a Pandas dataframe will be quicker than filtering a Networkx graph. So I would try the following:</p> <p>Create a dictionary of nodes in the attribute table:</p> <pre><code>nodes_with_attributes = {x:0 for x in df_nodes['id'].values} </code></pre> <p>(Look ups in a dictionary are much faster ...
pandas|networkx
0
10,345
65,785,702
Transpose dataframe with respect to a column without duplicate columns
<p>I have a DataFrame which looks like:</p> <pre><code> ftr_1 ftr_2 ftr_3 ftr_4 1 0.1 A 10 2 0.2 A 11 3 0.3 B 12 4 0.4 B 13 5 0.5 C 14 6 0.6 C 15 7 0.7 D 16 8 0.8 D 17 </code></...
<p>You can try:</p> <pre><code>df.set_index([&quot;ftr_3&quot;,df.groupby(&quot;ftr_3&quot;).cumcount()]).unstack().T.droplevel(1) </code></pre> <hr /> <pre><code>ftr_3 A B C D ftr_1 1.0 3.0 5.0 7.0 ftr_1 2.0 4.0 6.0 8.0 ftr_2 0.1 0.3 0.5 0.7 ftr_2 0.2 0.4 0.6 0.8 ftr_4 ...
python|pandas|matrix
4
10,346
63,429,459
Converting VTK image (.vti) data to VTK poly (.vtp) data
<p>I'm trying to take some VTK image data generated from a 3-D <code>numpy</code> array and convert it into poly data so it can be read by a package that only takes .vtp as an input format. I chose to use the marching cubes algorithm to take my point/node data as input and give poly data as an output. The data is segme...
<p>To read a .vtki file you need to use vtk.vtkXMLImageDataReader. You are trying to read an image file with a vtk.vtkPolyDataReader, which is designed for reading surface meshes.</p>
python|numpy|vtk
0
10,347
63,677,157
Check if column value is present in Dictionary Value
<p>i want to check whether the <code>colval</code> item is present in <code>values</code> of -<code>dictionary</code><br /> If it is present than append the corresponding <code>key</code> of that value, else append the <code>colval</code> item.</p> <p><strong>CODE</strong><br /> This is what i did</p> <pre><code>colorm...
<p>The problem is that colormap.append(col) is in the innermost loop. For each colval value, it's iterating through every value in the master_colors dict and every time it doesn't match that particular value, it appends colval. Instead you need to wait until you iterate through the entire dict and confirm that there's ...
python|pandas|for-loop
1
10,348
63,552,224
How to search column elements and corresponding mappings in Python Pandas?
<p>I have a dataframe <strong>df1</strong> such as the following that has a list of tags.</p> <pre><code> tags 0 label 0 document 0 text 0 paper 0 poster ... ...
<p>Merge:</p> <pre><code>new_df = df1.merge(df2, how='left', left_on='tags', right_on='name') </code></pre>
python|pandas|dataframe|search|mapping
1
10,349
63,405,508
Error : module 'tensorflow.python.framework.ops' has no attribute '_TensorLike'
<p>Hi I'm building cycleGan below are the code that makes the as no attribute <code>'_TensorLike'</code> errors.</p> <p>my version of <code>keras is 2.3.1 , tensorflow is 2.3</code>.</p> <p>lots people suggest to replace with &quot;<code>from tensorflow.karas......</code> but this can't work with</p> <pre><code>from ke...
<p>My scipy was deprecated, which apparently was the problem. This solved:<br /> <code>pip install --upgrade scipy</code></p>
tensorflow2.0|normalization|tf.keras|generative-adversarial-network
0
10,350
63,441,712
Error: its rank is undefined, but the layer requires a defined rank
<p>I have my tf.keras model feeding from a <code>tf.data.Dataset.from_generator</code> feature size <code>(224, 224, 1)</code> and label size <code>(1, 265)</code> as I have <code>265 CLASSES</code>. My batch size is <code>64</code>, returned feature size is <code>(64, 244, 244, 1)</code> and label size <code>(64, 265)...
<p>So the issue here is that the <code>Resnet</code> model also contains the <code>Input_layer</code>.</p> <p>If you do the summary of the <code>Resnet</code> model you can see this.</p> <p><code>base_model.summary()</code></p> <pre><code>Model: &quot;resnet50&quot; _____________________________________________________...
python|tensorflow|tf.keras
1
10,351
53,563,225
Pandas display all index labels in jupyter notebook despite repetition
<p>When displaying a DataFrame in jupyter notebook. The index is displayed in a hierarchical way. So that repeated labels are not shown in the following row. E.g. a dataframe with a Multiindex with the following labels</p> <pre><code>[1, 1, 1, 1] [1, 1, 0, 1] </code></pre> <p>will be displayed as </p> <pre><code>1 1...
<p>Use - </p> <pre><code>with pd.option_context('display.multi_sparse', False): print (df) </code></pre> <p><strong>Output</strong></p> <pre><code> 0 1 2 3 4 0 0 8 1 4 0 2 0 1 0 1 7 4 7 1 0 9 6 5 2 0 1 1 2 2 7 2 7 </code></pre> <p>And globally:</p> <pre><code>pd.options.display.mul...
python|pandas|jupyter
3
10,352
71,953,266
Numpy compare with 2 different dimension array
<pre class="lang-py prettyprint-override"><code>a = np.array([[ 0, 100, 0], [ 0, 0, 0], [ 0, 50, 0]]) b = np.array([0, 50, 0]) c = np.array([0, 0, 1]) </code></pre> <p>How can I get array c through a and b, except use <code>for</code>? If b equals the item in a, then the same index item of ...
<p>Here's a possible way. First, <code>b</code> is subtracted from each row of <code>a</code> and the absolute value at each index is found. Then, the sum of each row is taken, and if the sum is not 0, then that value in <code>c</code> becomes 0. If the sum is 0, then that index row in <code>a</code> is equal to <code>...
python|numpy|computer-vision
1
10,353
71,905,244
I don't understand how the second bracket works
<p>This piece of code is for plotting a series of data by coloring by the classes they belong to. <code>X_train</code> is an array <code>(115,2)</code> and <code>Y_train</code> is another array <code>(115,)</code> with their respective scope values. My question is what does <code>[Y_train == i]</code> do exactly?</p> <...
<p>Boolean values in python are just subclasses of integers.</p> <p><code>Y_train == i</code> just evaluates into either <code>False</code> or <code>True</code>, which is then used to access either index <code>0</code> or <code>1</code> respectively.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; a = ...
python|python-3.x|numpy
4
10,354
72,099,336
K-fold cross validation for Keras Neural Network
<p>Hi have already tuned my hyperparameters and would like to perfrom kfold cross validation for my model. I have being looking around for different methods it won't seem to work for me. The code is here below:</p> <pre><code>tf.get_logger().setLevel(logging.ERROR) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Set random...
<p>I haven't tested it, but this should roughly be what you want. You use the sklearn KFold method to split the dataset into different folds, and then you simply fit the model on the current fold.</p> <pre class="lang-py prettyprint-override"><code>tf.get_logger().setLevel(logging.ERROR) os.environ['TF_CPP_MIN_LOG_LEVE...
python|tensorflow|keras
0
10,355
55,383,080
Pandas: Checking for NaN using rolling function
<p>I have a data frame with a variable "A" and I would like to create a rolling Nan checker, such that the new variable "rolling_nan" = 1 if ALL 3 (seconds) cells (current cell and the two previous ones) are NaN, else "rolling_nan" = 0.</p> <p>I am applying a function since the <code>.rolling</code> pandas function do...
<p>You can think in the different way mark all <code>notna</code> , and find the <code>max</code> </p> <pre><code>df.A.notna().rolling(3).max()==0 Out[316]: 2018-01-01 00:00:00 False 2018-01-01 00:00:01 False 2018-01-01 00:00:02 False 2018-01-01 00:00:03 False 2018-01-01 00:00:04 False 2018-01-01 00:0...
pandas|apply|nan|rolling-computation
1
10,356
55,519,386
Vectorised non zero groups in numpy array
<p>Say you have 1d numpy array:</p> <pre class="lang-py prettyprint-override"><code>[0,0,0,0,0,1,2,3,0,0,0,0,4,5,0,0,0] </code></pre> <p>How would you create the following groups <strong>without</strong> using for loop?</p> <pre class="lang-py prettyprint-override"><code>[1,2,3], [4,5] </code></pre>
<p>Here's one way using <code>np.split</code>:</p> <pre><code>a # array([0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 4, 5, 0, 0, 0]) ### find nonzeros z = a!=0 ### find switching points z[1:] ^= z[:-1] ### split at switching points and discard zeros np.split(a, *np.where(z))[1::2] # [array([1, 2, 3]), array([4, 5])] </code></...
python|numpy
2
10,357
55,493,429
Merge one file to other file in groups
<p>In <code>Python</code> and <code>Pandas</code>, I have one dataframe for 2018 which looks like this:</p> <pre><code>Date Stock_id Stock_value 02/01/2018 1 4 03/01/2018 1 2 05/01/2018 1 7 01/01/2018 2 6 02/01/2018 2 9 03/01/2018 2 4 04/01/2018 2 6 </code></pre> <p>and a dataframe with one...
<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow noreferrer"><code>product</code></a> for all combinations of values with <code>Stock_id</code> and merge with <code>left join</code>:</p> <pre><code>df1['Date'] = pd.to_datetime(df1['Date'], dayfirst=True) df2['Date'] = p...
python|pandas
2
10,358
68,093,450
Find first layer with true condition
<p>Using these two example numpy arrays:</p> <pre><code>dis = np.array([[[40,42,44], [41,43,45], [41.5,43.5,45.5]], [[35,37,39], [36,38,40], [36.5,38.5,40.5]], [[30,32,34], ...
<p>You directly use greater than comparator then use <code>ndarray.sum</code> on the boolean values here.</p> <pre><code>(dis &gt; hd_mn).sum(0) array([[1, 1, 2], [1, 1, 2], [2, 3, 3]]) </code></pre> <hr /> <h2>Details</h2> <pre><code>dis &gt; hd_mn array([[[ True, True, True], # --\ [ True, ...
python|numpy
3
10,359
68,083,434
how to get rows satisfying certain condition pandas
<pre><code> name strike INFY 1000 INFY 1020 INFY 1040 INFY 1060 INFY 1080 INFY 1100 INFY 1120 INFY 1140 INFY 1160 INFY 1180 INFY 1200 INFY 1220 </code></pre> <p>I have a dataframe containing columns name and strike,</p...
<p>You need to play with the index.</p> <p>First of, create an empty dataframe: <code>results = pd.Dataframe()</code> Then <code>for index in df.iterrows():</code> And then if condition is reached (x &gt; 1065), ask to append</p> <pre><code>df.loc[:,index-3], df.loc[:,index-2], df.loc[:,index-1],df.loc[:,index],df.loc[...
python|pandas
0
10,360
68,163,679
pandas: detect and print outliers in a dataframe
<p>I am trying to identify and print the rows of a dataframe containing outliers. Just as an experiment, I am considering outliers all values under the column 'xy' between 6 and 10 that correspond to category 'C' under column 'x'. I am not sure why, my code prints an empty output.</p> <pre><code>import numpy as np impo...
<p>You need to take the second condition into <code>()</code> otherwise it is parsed incorrectly. Without it, it tries to compare <code>df['xy'].between(6,10,inclusive=False) &amp; df['x']</code> to <code>C</code></p> <pre><code>&gt;&gt;&gt; outliers= (df['xy'].between(6,10,inclusive=False) &amp; (df['x']=='C')) &gt;...
python|pandas|dataframe|outliers
0
10,361
59,199,872
Do rolling mean in 2 different columns and make one column in Python
<p>I have a DataFrame that looks like this:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'hometeam_id': {0: 1, 1: 3, 2: 5, 3: 2, 4: 4, 5: 6, 6: 1, 7: 3, 8: 2}, 'awayteam_id': {0: 2, 1: 4, 2: 6, 3: 3, 4: 5, 5: 1, 6: 4, 7: 6, 8: 5}, 'home_score': {0: 1, 1: 4, 2: 3, 3: 2, 4: 1, 5: 5, 6: ...
<p>IIUC, you can do:</p> <pre><code>df['total_home'] = (df.groupby('hometeam_id') .home_score .rolling(2, min_periods=0) .mean() .reset_index(level=0, drop=True) ) df['total_away'] = (df.groupby('awayteam_id') ...
python|pandas|moving-average
3
10,362
56,940,893
How to drop the first row number column pandas?
<p>This question may sound similar to other questions posted, but I'm posting this after searching long for this exact solution.</p> <p>So, I've a JSON from which I'm creating a pandas dataframe:</p> <pre><code>col_list = ["allocation","completion_date","has_expanded_access"] final_data = dict((k,d[k]) for k in (col_...
<p>Try</p> <p><code>df.to_csv('df_name.csv', sep = ';', encoding = 'cp1251', index = False)</code></p> <p>to save df without indices.</p> <p>Or change index column with</p> <p><code>df.set_index('col_name')</code></p>
python|pandas
3
10,363
45,881,124
Session object not specified in Tensorflow MNIST tutorial
<p>Why is there no Session object in the Tensorflow Layers tutorial? Is it possible to obtain it in some way?</p> <p>Tutorial: <a href="https://www.tensorflow.org/tutorials/layers" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/layers</a></p> <p>Source code: <a href="https://github.com/tensorflow/tens...
<p>The <a href="https://www.tensorflow.org/tutorials/layers" rel="nofollow noreferrer">TensorFlow <code>tf.layers</code> tutorial</a> uses <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator" rel="nofollow noreferrer"><code>tf.estimator.Estimator</code></a> as a high-level API that hides the deta...
python|tensorflow|mnist
0
10,364
51,069,750
How do I combine/ensemble results of 3 machine learning models stored in 3 dataframes and output 1 dataframe with results agreed by majority?
<p>I am currently participating in an online hackathon. All the top entries are within 1% of each other. So I decided to run 3 different models instead of a single best performing one, i.e. ensemble learning, tuned hyperparameters on each one of them and then combine results of all three to get a better model. I've com...
<p>Simply run conditional logic with <code>.loc</code>:</p> <pre><code>df.loc[df['xg_damage_grade'] == df['lr_damage_grade'], 'damage_grade'] = df['xg_damage_grade'] df.loc[df['xg_damage_grade'] != df['lr_damage_grade'], 'damage_grade'] = df['rf_damage_grade'] </code></pre> <p>Or with numpy's <code>where</code>:</p> ...
python|pandas|machine-learning|scikit-learn|ensemble-learning
1
10,365
66,447,464
Python numpy function for matrix math
<p>I have to np arrays</p> <pre><code>a = np.array[[1,2] [2,3] [3,4] [5,6]] b = np.array [[2,4] [6,8] [10,11] </code></pre> <p>I want to multiple each row of a against each element in array b so that array c is created with dimensions of a-rows x b row...
<p>Does this do what you want?</p> <pre><code>&gt;&gt;&gt; a array([[1, 2], [2, 3], [3, 4], [5, 6]]) &gt;&gt;&gt; b array([[ 2, 4], [ 6, 8], [10, 11]]) &gt;&gt;&gt; a[:,None,:]*b array([[[ 2, 8], [ 6, 16], [10, 22]], [[ 4, 12], [12, 24], [2...
python|arrays|numpy
4
10,366
66,609,882
Find max volume and data count above that volume in a Dataframe
<p>I have a sample dataframe as below. I need to find result as per the below condition.</p> <pre><code>Datetime Volume Price 2020-08-05 09:15:00 1033 504 2020-08-05 09:15:00 1960 516 2020-08-05 09:15:00 0 521 2020-08-05 09:15:00 1724 520 2020-08-05 09:15:00 ...
<p>Try:</p> <pre><code># positive volume pos_vol = df.query('Volume!=0') # rows with max volume by time s = pos_vol.groupby('Datetime').Volume.idxmax() # extract the output out = df.loc[s].set_index(['Datetime']) # map the datetime to the price corresponding to the max volume aligned_prc = pos_vol['Datetime'].map(o...
python|python-3.x|pandas|dataframe|pandas-groupby
2
10,367
66,522,196
wrong input of image in tensorflow for training
<p>I am writing my thesis in machine learning and am trying to build a unet to perform it. The code is as follows:</p> <p>First i create the dataloader to create the datasets for input:</p> <pre><code>def dataloader(filepath, subset): # Initiliaze return arrays - input of shape = HYPERPARAMETER global size ...
<p>I am not sure what this network is supposed to do, so I will list some mistakes that in your code.</p> <p>In your function you already compile the model:</p> <pre><code>model.compile(optimizer=optimizer(lr=lr), loss=loss_metric, metrics=metrics) return model </code></pre> <p>After outside the function you do it agai...
python|image|image-processing|tensorflow2.0
1
10,368
66,626,700
Difference between Tensorflow's tf.keras.layers.Dense and PyTorch's torch.nn.Linear?
<p>I have a quick (and possibly silly) question about how Tensorflow defines its Linear layer. Within PyTorch, a Linear (or Dense) layer is defined as, y = x A^T + b where A and b are the weight matrix and bias vector for a Linear layer (see <a href="https://pytorch.org/docs/stable/generated/torch.nn.Linear.html?highli...
<p>If we set activation to <code>None</code> in the dense layer in <code>keras</code> API, then they are technically equivalent.</p> <p>Tensorflow's</p> <pre><code>tf.keras.layers.Dense(..., activation=None) </code></pre> <p>According to the <a href="https://keras.io/api/layers/core_layers/dense/" rel="noreferrer">doc...
tensorflow|pytorch
14
10,369
66,450,790
How to Show the actual value instead of the percent in a Matplotlib Pie Chart
<p>The following code is for creating a pie chart that shows the number of purchases made by each person from the &quot;Shipping Address Name&quot; column. The 'labels' list contains the name of each person and the 'purchases' list contain the number of purchases each person has made.</p> <pre><code>labels = df['Shippi...
<p>Try re-calculate the actual values by multiplying with the total purchases:</p> <pre><code>purchases = df['Shipping Address Name'].value_counts() purchases.plot.pie(autopct=lambda x: '{:.0f}'.format(x*purchases.sum()/100) ) # also # plt.pie(purchases, autopct=lambda x: '{:.0f}'.format(x*purchases.sum()/100)) </code...
python|pandas|list|dataframe|matplotlib
3
10,370
57,689,620
convert dates to int in pandas
<p>I have a date column of format YYYY-MM-DD and want to convert it to an int type, consecutively, where 1= Jan 1, 2000. So if I have a date 2000-01-31, it will convert to 31. If I have a date 2020-01-31 it will convert to (365*20yrs + 5 leap days), etc.</p> <p>Is this possible to do in pandas?</p> <p>I looked at <a ...
<p>First subtract column by <code>Timestamp</code>, convert timedelts to days by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.days.html" rel="nofollow noreferrer"><code>Series.dt.days</code></a> and last add 1:</p> <pre><code>df = pd.DataFrame({"Date": ["2000-01-29", "2000-01-01"...
pandas|date
2
10,371
72,885,243
Applying lambda function to multiple columns with IF statement to leave blanks as-is
<p>I am working with a dataset where a few interger columns have two extra zeros at the end of each number. As such, I wrote a lambda function to remove them:</p> <pre><code>df[['col_8', 'col_9', 'col_10']] = df[['col_8', 'col_9', 'col_10']].apply(lambda x: x.apply(lambda value: '{:,.2f}'.format(value/100))) </code></p...
<p>Your code is almost correct. However, you need to put the check inside the second lambda function and improve the check for number values. This code should work:</p> <pre class="lang-py prettyprint-override"><code>import numbers df[['col_8', 'col_9', 'col_10']] = df[['col_8', 'col_9', 'col_10']].apply(lambda x: x.ap...
python|pandas|dataframe|lambda
0
10,372
72,905,347
Merging two dataset with partial match
<p>I want to merge two dataframe df1 and df2. Shape of df1 is (115, 16) and Df2 is (624402, 23).</p> <pre><code>df1 = pd.DataFrame({'Invoice': ['20561', '20562', '20563', '20564'], 'Currency': ['EUR', 'EUR', 'EUR', 'USD']}) df2 = pd.DataFrame({'Ref': ['20561', 'INV20562', 'INV20563BG', '20564'], ...
<p>The IndexError occurs when no row matches the invoice. You can check for this and return <code>np.nan</code> (or a different default value) if a matching invoice is not found:</p> <pre><code>df4 = df1.copy() for i, row in df1.iterrows(): tmp = df2[df2['Ref'].str.contains(row['Invoice'], na=False)] df4.loc[i...
pandas|dataframe|merge
0
10,373
72,925,734
How to create list of array combinations lexographically in numpy?
<p>I have this array and I want to return unique array combinations. I tried meshgrid but it creates duplicates and inverse array values</p> <pre><code>&gt;&gt; import numpy as np &gt;&gt; array = np.array([0,1,2,3]) &gt;&gt; combinations = np.array(np.meshgrid(array, array)).T.reshape(-1,2) &gt;&gt; print(combinations...
<p>you could use <code>combinations</code> from itertools</p> <pre><code>import numpy as np from itertools import combinations array = np.array([0,1,2,3]) combs = np.array(list(combinations(arr, 2))) </code></pre>
python|arrays|numpy
2
10,374
70,422,783
is there a way to efficiently fill a pandas df column in python with hourly datetimes between two dates?
<p>So I am looking for a way to fill an empty dataframe column with hourly values between two dates. for example between</p> <blockquote> <p>StartDate = 2019:01:01 00:00:00</p> </blockquote> <p>to</p> <blockquote> <p>EndDate = 2019:02:01 00:00:00</p> </blockquote> <p>I would want a column that has</p> <blockquote> <p>2...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> with <code>DataFrame</code> constructor:</p> <pre><code>StartDate = '2019-01-01 00:00:00' EndDate = '2019-02-01 00:00:00' df = pd.DataFrame({'dates':pd.date_range(Start...
python|pandas|time|time-series
1
10,375
70,538,852
Column sum in pandas groupby
<p>Below is the dataframe</p> <pre><code>Skill Category Location Market Type Count Java Cat1 Europe Tier1 A 2 Java Cat1 Europe Tier1 B 1 Java Cat1 Europe Tier1 C 1 Java Cat2 Asia Tier2 D 1 Java Cat3 ...
<p>Just merge back to original one:</p> <pre class="lang-py prettyprint-override"><code>df.merge( df.groupby(['Skill','Category','Location','Market','Type'])['count'].sum().rename('Sum_Market').reset_index() ) </code></pre>
python|pandas|dataframe|group-by|pivot-table
1
10,376
51,799,843
tensorflow: find larges value in variable and replace it
<p>I have a <code>tf.Variable()</code> came out of softmax, as a sequence of probabilities, e.g., <code>[0.3, 0.5, 0.8, 0.1, 0.2]</code>. What I tried to do is to convert this sequence into [0, 0, 1, 0, 0], i.e. the highest probability replaced with 1 and all other with 0. But since <code>tf.Variable()</code> is not it...
<pre><code>import tensorflow as tf tf.enable_eager_execution() softmax = tf.constant([0.3, 0.5, 0.8, 0.1, 0.2], dtype=tf.float32) index = tf.argmax(softmax, axis=0, output_type=tf.int32) # sparse = tf.SparseTensor(tf.reshape(index, [-1]), tf.constant([[1]], dtype=tf.int32), tf.shape(softmax)) result = tf.scatter_nd(t...
python|tensorflow|softmax
0
10,377
51,728,054
Appending data into pandas dataframe
<p>I'm building a system where raspberry pi receives data via bluetooth and parses it into pandas dataframe for further processing. However, there are a few issues. The bluetooth packets are converted into a pandas Series object which I attempted to append into the empty dataframe unsuccesfully. Splitting below is perf...
<p>You don't want to append to a DataFrame in that way. What you can do instead is create a list of series, and concatenate them together. </p> <p>So, something like this:</p> <pre><code>series_list = [] for packet in p_rows: pkt = pd.Series(packet.split(","),dtype='str') print(pkt) series_list.append(pkt...
python|pandas|dataframe|append
1
10,378
51,596,522
Converting a list into comma separated and add quotes in python
<p>I have :</p> <pre><code>val = '[12 13 14 16 17 18]' </code></pre> <p>I want to have:</p> <pre><code>['12','13','14','16','17','18'] </code></pre> <p>I have done </p> <pre><code>x = val.split(' ') y = (" , ").join(x) </code></pre> <p>The result is </p> <pre><code>'[12 , 13 , 14 , 16 , 17 , 18 ]' </code></pre> ...
<p>You can do it with</p> <pre><code>val.strip('[]').split() </code></pre>
python|list|pandas
3
10,379
35,829,211
Pandas: Counting the proportion of zeros in rows and columns of dataframe
<p>I have this code below. It is surprizing for me that it works for the columns and not for the rows.</p> <pre><code>import pandas as pd def summarizing_data_variables(df): numberRows=size(df['ID']) numberColumns=size(df.columns) summaryVariables=np.empty([numberColumns,2], dtype = np.dtype('a50')) ...
<p>try this instead of the first funtion:</p> <pre><code>print(df[df == 0].count(axis=1)/len(df.columns)) </code></pre> <p>UPDATE (correction):</p> <pre><code>print('rows') print(df[df == 0].count(axis=1)/len(df.columns)) print('cols') print(df[df == 0].count(axis=0)/len(df.index)) </code></pre> <p>Input data (i've...
python-2.7|pandas
8
10,380
37,559,561
Errors when importing files into spyder (Correct directory)
<p>Here is my code</p> <pre><code>import pandas as pd all_ages = pd.read_csv("all-ages.csv") all_ages.head(5) </code></pre> <p>And I have already put the csv file in the working directory, but I still encounter </p> <blockquote> <p>OSError: File b'all-ages.csv' does not exist</p> </blockquote> <p>But if I type ea...
<p>You'd better provide the <strong>absolute file path</strong>. Python uses the current working directory which depends on where you invoke/run your python script. </p> <p>Even you put your python script and csv file "all-ages.csv" under the same directory, the current working directory might be different.</p> <p>Fo...
python|csv|pandas|anaconda|spyder
1
10,381
41,789,469
Set value based on day in month in pandas timeseries
<p>I have a timeseries </p> <pre><code>date 2009-12-23 0.0 2009-12-28 0.0 2009-12-29 0.0 2009-12-30 0.0 2009-12-31 0.0 2010-01-04 0.0 2010-01-05 0.0 2010-01-06 0.0 2010-01-07 0.0 2010-01-08 0.0 2010-01-11 0.0 2010-01-12 0.0 2010-01-13 0.0 2010-01-14 0.0 2010-01-15 0.0 2...
<p>Assume your timeseries is <code>s</code> with a datetimeindex </p> <p>I want to create a <code>groupby</code> object of all index values whose days are greater than or equal to <code>9</code>.</p> <pre><code>g = s.index.to_series().dt.day.ge(9).groupby(pd.TimeGrouper('M')) </code></pre> <p>Then I'll check that t...
python|date|pandas
3
10,382
41,874,452
averaging over subsets of array in numpy
<p>I have a numpy array of the shape (10, 10, 10, 60). The dimensions could be arbitrary but this just an example.</p> <p>I want to reduce this to an array of <code>(10, 10, 10, 20)</code> by taking the mean over some subsets I have two scenarios:</p> <p><strong>1</strong>: Take the mean of every <code>(10, 10, 10, 2...
<p>You could reshape splitting the last axis into two, such that the first one has the length as the number of blocks needed and then get the average/mean along the second last axis -</p> <pre><code>m,n,r = x.shape[:3] out = x.reshape(m,n,r,3,-1).mean(axis=-2) # 3 is no. of blocks </code></pre> <p>Alternatively, we c...
python|numpy
1
10,383
41,778,964
Pandas : using both log and stack on a bar plot
<p>I have some data that comes from amazon that I'd like to work on. One of the plot I'd like to include is a distribution of ratings for each brand, I thought the best way of doing this would be a stacked bar plot.</p> <p>However, some brands are much more reviewed than others, so I have to use the log scale or else ...
<p>In order to have the total bar height living on a logarithmic scale, but the proportions of the categories within the bar being linear, one could recalculate the stacked data such that it appears linear on the logarithmic scale.</p> <p>As a showcase example let's choose 6 datasets with very different totals (<code>...
python|python-3.x|pandas|matplotlib
4
10,384
37,658,776
How can you add external dependencies to bazel
<p>I am a student and currently working on a project where I am trying to connect my game that which I have created with Android Studio. A neural network has also been made with Tensorflow which is going to be used for the android game.</p> <p>The problem is that Android Studio uses a build tool which is called Gradle...
<p>You may want to look at the Makefile support we just added for Android: <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/makefile" rel="nofollow">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/makefile</a></p> <p>It's still very experimental (and fiddly), but...
android|gradle|tensorflow|bazel
0
10,385
37,870,929
How can you find the most common sets using python?
<p>I have a pandas dataframe where one column is a list of all courses taken by a student. The index is the student's ID.</p> <p>I'd like to find the most common set of courses across all students. For instance, if the dataframe looks like this:</p> <pre><code>ID | Courses 1 [A, C] 2 [A, C...
<p>You can first convert <code>list</code> to <code>tuples</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html"><code>value_counts</code></a>. Last use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html"><code>to_dict</cod...
python|pandas|set
5
10,386
64,411,352
min() max() and sum() functions working on pandas group by object but not mean()
<p>So basically, I have grouped month columns into quarters like columns 2000-01,2000-02,2000-03 into a single group 2000q1 where q1 means quarter 1 and so on. I have done is for 16 x 12 months and formed 48 quarters.</p> <p>Now, I wish to get the average value of each row in a group. When I do <code>grouped.max()</cod...
<p>It's easier to groupby the columns with values, and perform the operations.</p> <pre><code>df = pd.DataFrame({'Region':[1,2,3],'City':['a','b','c'],'Country':['A','B','C']}) df = pd.concat([df,pd.DataFrame(np.random.uniform(0,1,(3,12)), columns=['2000-01','2000-02','2000-03','2000-04','2000-05','2000-06','2001-01',...
python|pandas|dataframe|pandas-groupby|mean
2
10,387
47,819,255
Python pandas map CSV file
<p>I want to "merge" two CSV files. I want to map the emails from the File 1 and get their respective userId from File 2 then I want to assign it to the respective emails of File 1</p> <p>Example:</p> <p>File 1</p> <pre><code>name, userId, email john, null, john@a.com alex, null, alex@a.com micheal, null, mike@a.com...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging" rel="nofollow noreferrer">Dataframe.merge</a></p> <pre><code>df1 = pd.read_csv("file1.csv", sep=",") df1.columns = ['name', 'userid', 'email'] df2 = pd.read_csv("file2.csv", sep=",", index_col=0) df1 = df1.dr...
python|pandas|csv|dictionary
1
10,388
47,942,861
Join one dataset and the result of OneHotEncoder in Pandas
<p>Let's consider the dataset of House prices from <a href="https://github.com/ageron/handson-ml/blob/master/02_end_to_end_machine_learning_project.ipynb" rel="nofollow noreferrer">this example</a>.</p> <p>I have the entire dataset stored in the <code>housing</code> variable:</p> <pre><code>housing.shape </code></pre...
<p>Well, depends on how you created the one-hot vector. But if it's sorted the same as your original DataFrame, and itself is a DataFrame, you can add the same index before joining:</p> <pre><code>housing_cat_1hot.index = range(len(housing_cat_1hot)) </code></pre> <p>And if it's not a DataFrame, convert it to one. Th...
python|pandas|join|one-hot-encoding
1
10,389
49,243,870
No module named 'pandas_datareader.mstar'
<p>I am using Python 3.6 (Anaconda) on Windows 10, PyCharm IDE. Please bear with me as I am new to coding. I just started Python for my equity research project. </p> <p>Here is the code: </p> <pre><code>import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import panda...
<p>For some reason I managed to resolve the error by deleting all yahoo related in the data.py (within the pandas-datareader package). Seems like there was an issue with the yahoo API, if I understand it correctly. </p>
python|pandas|dataframe|finance
0
10,390
49,050,243
Why is my output dataframe shape not 1459 x 2 but 1460 x 2
<p>Below is what i have done so far.</p> <pre><code>#importing the necessary modules import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression from sklearn.linear_model import RidgeCV from sklearn.linear_model import LassoCV from skl...
<p>Scikit learn is very sensitive o ordering of columns, so if your train data set and the test data set are misaligned, you may have a problem similar to that above. so you need to first ensure that the test data is encoded same as the train data by using the following align command.</p> <pre><code>train, test = trai...
python|pandas|machine-learning|scikit-learn|kaggle
0
10,391
58,964,096
Creating a pivot table and finding correlations between books with multiple genres
<p>I have a table that is like</p> <pre><code>book_id original_title tag_id tag_name 1 The Hunger Games 11305 fantasy 1 The Hunger Games 26771 scifi 1 The Hunger Games 26138 romance 10000 The First World War 14467 historical 10000 The First World War 21689 nonfiction </code></pre...
<p>Maybe this can help:</p> <pre><code>df.pivot(index='original_title',columns='tag_name',values='tag_id') </code></pre>
python|pandas|machine-learning|statistics|recommendation-system
0
10,392
70,281,203
How to drop rows with string <NA> value and trim strings from pandas data frame
<p>I have the below python code:</p> <pre><code>import streamlit as st import subprocess import pandas as pd git_output = subprocess.run(['git', 'worktree', 'list', '--porcelain'], cwd='F:/myenv/', capture_output=True, text=True).stdout df = pd.DataFrame([ ...
<p>This will work:</p> <pre><code>import ast df = df.dropna().astype(str).apply(lambda col: col.apply(lambda x: ast.literal_eval(x)[-1])) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df worktree branch 1 F:/demo/b refs/heads/dev/demo/b 2 F:/demo/c refs/heads/dev/demo/c </code></pre> <p>I...
python-3.x|pandas|dataframe
1
10,393
55,819,940
Looping through a Pandas Dataframe with multiple conditions
<p>This data contains the last four weeks of data and the idea is average the Total Volume based on Day of Week and Time. for example, if the day = Monday and time = 1 am then average the total volume from the last 4 weeks. </p> <pre><code> Day of Week Time Total Volume 0 Monday 00:00 4 1 Monday ...
<p>Using for loop in pandas tend to be very slow. It is often times faster to implement a simple calculation over the entire dataframe (that can leverage numpy), and then choose the day/time you want afterwards.</p> <p>You can try groupby function to calculate a 4 weeks moving average of volume from the same weekday a...
python|pandas
1
10,394
55,767,020
Parse and expand JSON data that currently embedded within a Dataframe
<p>Essentially I have raw data that has been pulled from a certain Weather API. Through an SQL query, the data is formatted into a data frame with columns: latitudes (lats), longitudes (lngs), date, and "blob."</p> <p>The blob is JSON data that is nested in 2 layers. The data as you will see below starts off with a su...
<pre><code>import json from pandas.io.json import json_normalize #from your data df = pd.DataFrame(data) #make the entire df a json file df_json = df.to_json(orient = 'records', date_format='iso') #use json_normalize to read in your json file, look at the hourly dict, and attach lat, lng and date. df2 = json_normali...
python|json|pandas|dataframe
0
10,395
39,507,417
Identify cells containing specific strings and overwrite content with numbers using Python
<p>I have a dataframe which looks like this:</p> <p><a href="https://i.stack.imgur.com/qe7Y2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qe7Y2.png" alt="enter image description here"></a></p> <p>My goal is to identify for each cell of every column if the following strings are contained: <code>'...
<p>If you create a dict with your lookup and replacement values then you can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html#pandas.Series.map" rel="nofollow"><code>map</code></a> on this column, additionally you need to pass <code>na_action='ignore'</code> to <code>map</code>...
python|pandas|replace|substitution
3
10,396
43,983,757
Python: Is it OK to use "as_matrix" with dataframes as input to scikit models
<p>Hi I have seen some examples of machine learning implementations that uses as_matrix with dataframes as inputs to machine learning algorithms. I wonder if it is OK to use tuples, which are output of .as_matrix as inputs to machine learning algorithms such as below. Thanks</p> <pre><code>trainArr_All = df.as_matrix(...
<p>Pandas <code>as_matrix</code> converts the dataframe to <strong>numpy.array</strong> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.as_matrix.html" rel="nofollow noreferrer">documentation</a>) <strong>NOT tuple</strong>! sklearn assumes that the inputs are in the form of numpy array...
python|pandas|dataframe|scikit-learn
1
10,397
44,339,463
confusing situations when `tf.constant` not displayed in `tensorboard`?
<p>Below is the working code where some <code>tf.constant</code> get displayed in <code>tensorboard</code>, some don't. </p> <p>However, I have no idea why those don't get displayed. </p> <p>Could anyone help me out here? Thanks</p> <pre><code>import tensorflow as tf import numpy as np # tf.constant(value, dtype=Non...
<p>I got it now.</p> <p>To display any nodes in tensorboard, the nodes have to be used in an operation first. Being a <code>tf.constant</code> without involving in <code>add</code> or <code>multiply</code> or any other operations, won't be displayed by tensorboard.</p>
tensorflow|tensorboard
0
10,398
69,636,787
Select rows in pandas where any of six column are not all zero
<p>Here's what the pandas table look like:</p> <p><a href="https://i.stack.imgur.com/1VDKE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1VDKE.jpg" alt="enter image description here" /></a></p> <p>As you can see the red marked rows have any of all six column values set to '0'. I want to select only...
<p>Use a boolean mask as suggested by @Ch3steR and use <code>.iloc</code> or <code>.loc</code> to select a subset of columns:</p> <pre><code># Minimal sample &gt;&gt;&gt; df A B C D E F G H I J 0 4 0 0 0 0 0 0 1 3 2 # Drop 1 4 6 4 0 0 0 0 0 0 0 # Keep # .iloc version: select the first...
python|pandas
1
10,399
69,445,143
Pandas - Averaging entries in specific row and column
<p>I've imported an excel sheet which has a series of tables. The pandas dataframe looks like this:</p> <pre><code> 1 2 3 4 0 3 2 7 2 1 4 2 8 1 2 5 1 4 1 3 6 0 2 3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1 2 3 4 0 3 2 2 1 1 3 3 9 1 2 3 1 5 1 3 ...
<p>If first column is index and same columns names in each subDataFrame simpliest is:</p> <pre><code>print (df) 1 2 3 4 0.0 3.0 2.0 7.0 2.0 1.0 4.0 2.0 8.0 1.0 2.0 5.0 1.0 4.0 1.0 3.0 6.0 0.0 2.0 3.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1.0 2.0 3.0 4.0 0.0 3.0 2.0 2...
python|pandas
3