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
376,300
55,081,741
Tensorflow, Horovod, and NVLINK NotFoundError
<p>I'm trying to run a tensorflow neural network that runs on GPUs using <strong>uber's horovod library</strong>. At the same time I am trying to run a measurement script that measurements the <strong>nvlinks</strong> between the multiple gpus. Alas, whenever I run the file I get the following error: </p> <blockquote>...
<p>Please take a look at this issue raised on the repo:</p> <p><a href="https://github.com/horovod/horovod/issues/656" rel="nofollow noreferrer">https://github.com/horovod/horovod/issues/656</a></p>
python|tensorflow|horovod
-1
376,301
54,749,818
How to turn tabular and horizontal data into tabular data in Pandas/Python
<p>Quick question regarding reshaping data in python/pandas</p> <p>The reports that I have to work with in excel are sometimes organised like figure 1. below (horizontal &amp; vertical)</p> <pre><code>Make Model Volume Yr. 1 Volume Yr. 2 Gadget 1 Model 1 1254 1549 Gadget 2 Model 2 897 ...
<p>Considering the data looks like:</p> <pre><code> Make Model Volume Yr. 1 Volume Yr. 2 0 Gadget 1 Model 1 1254 1549 1 Gadget 2 Model 2 897 1108 2 Gadget 3 Model 3 1598 1974 3 Gadget 4 Model 4 5897 7283 4 Gadget 5 Model...
python|pandas
1
376,302
54,881,627
in tensorflow, how do I convert a list of indices to an indicator vector?
<p>My input are lists of indices like </p> <pre><code>[1,3], [0,1,2] </code></pre> <p>how can I convert them into fixed length indicator vectors?</p> <pre><code>[0, 1, 0, 1], [1, 1, 1, 0] </code></pre>
<pre><code>import tensorflow as tf indices = [[1, 3, 0], [0, 1, 2]] many_hot = tf.one_hot(indices, depth=4) many_hot = tf.reduce_sum(many_hot, axis=1) with tf.Session() as sess: print(sess.run(many_hot)) </code></pre> <p>This prints</p> <pre><code>[[1. 1. 0. 1.] [1. 1. 1. 0.]] </code></pre> <p>Note that this ...
python|tensorflow
5
376,303
54,840,036
Connecting S3 - Lambda - EC2 - Elasticsearch
<p>In my project users upload images into a S3 bucket. I have created a tensor flow resnet model to interpret the contents of the image. Based on the tensor flow interpretation, the data is to be stored in an elasticsearch instance. </p> <p>For this, I have created a S3 Bucket, a lambda function that gets triggered...
<p>I can think of two approaches here:</p> <ol> <li><p>You side load the app. The lambda can be a small bootstrap script that downloads your app from s3 and unzips it. This is a popular pattern in server less frameworks. You pay for this during a cold start of the lambda so you will need to keep it warm in a productio...
amazon-web-services|tensorflow|elasticsearch|amazon-s3
0
376,304
54,809,825
How do I reproduce results from webgraphviz with python graphviz using 2 column pandas dataframe
<p>I have a two column pandas dataframe with parent and child process id's that looks like the following:</p> <pre><code> ChildID ParentID 0 460 580 1 580 716 2 460 724 3 716 840 4 716 812 5 724 884 6 716 800 7 1424 2028 8 2280 2368 9 2368 2480 10 2948 29...
<p>Here is my solution:</p> <pre><code>from graphviz import Graph g = Graph('processs', filename='process.gv', engin='sfdp') # run over all the rows and for each row add a new edge to the graph for index, row in df.iterrows(): g.edge(str(row['ChildID']), str(row['ParentID'])) g.view() </code></pre> <p>If you have...
python|pandas|graphviz|pygraphviz
2
376,305
55,123,657
Combine duplicate rows on specific column
<p>I am trying to combine rows of a dataframe in the event that there is a duplicate in one column. The dataframe looks like the following.</p> <pre><code>Name Code X Y A 123 10 11 B 456 12 13 C 123 15 16 </code></pre> <p>I want to combine on Code. So if the Code is the same, combine ...
<p>Create index from <code>Code</code> column fo avoid casting to strings, then cast all columns and aggregate by index function <code>join</code>:</p> <pre><code>df = df.set_index('Code').astype(str).groupby(level=0).agg(', '.join).reset_index() #pandas 0.24+ #df = df.set_index('Code').astype(str).groupby('Code').agg...
python|pandas
5
376,306
54,808,153
use tf.nn.dynamic_rnn but final state don't have c and h
<p>I'm working with tensorflow, I want run a program with RNN, but I got the followed error:</p> <pre><code>a=self._encoder_final_state[0].c AttributeError: 'Tensor' object has no attribute 'c' </code></pre> <p>the program is like this:</p> <pre><code>self._encoder_cells = build_rnn_layers( cell_type=self._hpara...
<p>From the <a href="https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn" rel="nofollow noreferrer">docs</a> of <code>dynamic_rnn</code>:</p> <blockquote> <p>If cells are <code>LSTMCells</code> <code>state</code> will be a tuple containing a <code>LSTMStateTuple</code> for each cell.</p> </blockquote> <p...
tensorflow|recurrent-neural-network|tensor
1
376,307
54,930,722
to_sql not updating table in ms server
<p>Hey so I have the below code I'm running where I'm pulling a table from a MS Sql Server table, running a bit of code and then trying to reimport it into another table within the same database. Running this in spyder</p> <p>It runs all the way through, but when I</p> <pre><code>select * from pythontest </code></pr...
<p>Try with <code>pymysql</code> :</p> <pre><code>conn = pymysql.connect( host='', port= user='', passwd='', db='', charset='utf8mb4') df = pd.read_sql_query("SELECT * FROM table ", conn) df.head(2) </code></pre>
sql-server|python-3.x|pandas|spyder
1
376,308
55,037,285
How do I use tensoflow frozen graph for visualizing its feature maps?
<p><strong>I am having tensoflow frozen graph (.pb). I want to visualize the hidden layer output (feature maps) given by that graph from an image. Is there any way to do it?</strong></p>
<p>Yes. Probably the best place to start is tensorflow's native way to visualize network infromation, <code>tensorboard</code>.</p>
tensorflow|deep-learning|conv-neural-network
0
376,309
54,761,314
Pandas Dataframe show Count with Group by and Aggregate
<p>I have this data</p> <pre><code>ID Value1 Value2 Type Type2 1 3 1 A X 2 2 2 A X 3 5 3 B Y 4 2 4 B Z 5 6 8 C Z 6 7 9 C Z 7 8 0 C L 8 3 2 D M 9 4 ...
<p>Add new value to dictionary with <code>size</code> function, remove <code>as_index=False</code> for prevent:</p> <blockquote> <p>ValueError: cannot insert Type, already exists</p> </blockquote> <p>and last <code>rename</code> with <code>reset_index</code>:</p> <pre><code>df = pandabook.groupby(['Type','Type2'])...
python-3.x|pandas|dataframe
1
376,310
55,015,329
Add In Plot Labels to Seaborn Lineplot
<p>I have a dataframe that shows monthly revenue. There is an additional column that shows the number of locations opened in that month. </p> <pre><code>&gt; Date Order Amount Locations Opened 16 2016-05-31 126443.17 2.0 &gt; 17 2016-06-30 178144.27 0.0 18 2016-07-31 23033...
<p>IIUC, use <code>text</code>:</p> <pre class="lang-py prettyprint-override"><code>plt.figure(figsize=(12, 5)) sns.lineplot(x="Date", y="Order Amount", data=total_monthly_rev).set_title("Total Monthly Revenue") # Using a variable to manage how above/below text should appear slider = 1000 for i in range(total_monthly...
python|pandas|matplotlib|seaborn
5
376,311
55,000,316
Include file name to be part of xml to csv conversion in Python
<p>I am trying to convert an XML file into csv. I have got this below code working to do just that. I however am also trying to include the file name to be part of the extract but I am not able to have that included in this code.</p> <pre><code>df = pd.DataFrame() for file in allFiles: def iter_docs(cis): ...
<p>Try</p> <pre><code>df = df.append(pd.DataFrame([file] + list(iter_docs(etree.getroot())))) </code></pre> <p>to get a column with the filename added</p> <p>By the way, this approach will give you bad performance.</p> <p>A better approach is to collect the df in a list and convert that to a big one at the end.</p>...
python|xml|pandas
0
376,312
55,120,395
keras kernel initializers are called incorrectly when using load_model
<p>Keras version 2.2.4, tensorflow version 1.13.1, I'm using colab notebooks</p> <p>I'm trying to make a custom initializer and save the model using model.save() but when I load the model again I get the following error:</p> <blockquote> <p>TypeError: myInit() missing 1 required positional argument: 'input_shape'</...
<p>After viewing the source code I got the following working code, which should be the proper way to define an initializer (especially when loading a model with load_model):</p> <pre><code>import numpy as np import tensorflow as tf import keras from google.colab import drive from keras.models import Sequential, loa...
tensorflow|keras|google-colaboratory
4
376,313
54,892,806
Pandas - DataFrame aggregate behaving oddly
<p>Related to <a href="https://stackoverflow.com/questions/54892437/dataframe-aggregate-method-passing-list-problem">Dataframe aggregate method passing list problem</a> and <a href="https://stackoverflow.com/questions/54890646/pandas-fails-to-aggregate-with-a-list-of-aggregation-functions">Pandas fails to aggregate wit...
<p>The issue has to do with applying <code>np.mean</code> to a series. Let's look at a few examples:</p> <pre><code>def nok_mean(x): return x.mean() df.agg({'a': nok_mean}) a 13.5 dtype: float64 </code></pre> <p>this works as expected because you are using pandas version of mean, which can be applied to a se...
pandas|numpy|dataframe|aggregate|series
3
376,314
54,790,000
Calculate segment ids needed in tf.math.segment_sum by length of segments in Tensorflow
<p>I'm working with sequential data of variable-size. Lets consider data like</p> <pre><code>Y = [ [.01,.02], [.03,.04], [.05,.06], [.07,.08], [.09,.1] ] l = [ 3, 2 ] </code></pre> <p>where <code>Y</code> is the result of some auxiliary calculation performed on my data and <code>l</code> stores the length of the orig...
<p>This is one way to do that:</p> <pre><code>import tensorflow as tf def make_seq_ids(lens): # Get accumulated sums (e.g. [2, 3, 1] -&gt; [2, 5, 6]) c = tf.cumsum(lens) # Take all but the last accumulated sum value as indices idx = c[:-1] # Put ones on every index s = tf.scatter_nd(tf.expand_...
python|python-3.x|tensorflow|tensorflow-datasets
2
376,315
55,031,850
Multiple parameters in MySQL "IN" query
<p>I'm clearly doing something wrong in the parameterization, but not sure what the proper syntax is. </p> <p><strong>Desired, but doesn't work: multiple conditions in where IN</strong></p> <pre><code>data = ['lol', 'hi'] query = """ select word, count(1) from table where word in (%(ids)s) group by 1""" pandas.read_s...
<p>Remove the brackets around the placeholder. As it is the query is comparing <code>word</code> against <code>(('lol', 'hi'))</code> after parameter substitution done by pymysql, or in other words a scalar against a tuple. A list of length 1 is fine because the result is <code>(('hi'))</code> and SQL actually treats t...
python|mysql|pandas|sqlalchemy|pymysql
1
376,316
55,131,799
How to preserve datatype in DataFrame from an sklearn Transform (Imputer)
<p>I have the following data below. </p> <pre><code>+----+-------------+----------+--------+------+-------+-------+---------+ | ID | PassengerId | Survived | Pclass | Age | SibSp | Parch | Fare | +----+-------------+----------+--------+------+-------+-------+---------+ | 0 | 1 | 0 | 3 | 22.0...
<p>The dtypes cannot be preserved, because <code>sklearn</code> extracts the underlying data from <code>data2</code> before transforming and homogenises the dtypes to float for performance reasons.</p> <p>You can always reinstate the initial dtypes using <code>astype</code>:</p> <pre><code>v = fill_NaN.fit_transform(...
python|pandas|numpy|scikit-learn
1
376,317
54,800,236
correct use of lambda function with pandas
<p>I want to apply a function to a DataFrame for creating a new dataframe with mean values using lambda, and I'm getting this error: </p> <p>TypeError: ("Argument 'real' has incorrect type (expected numpy.ndarray, got Series)", u'occurred at index 2018-01-02 00:00:00')</p> <p>here is my data:</p> <pre><code> AA ...
<p>In more recent versions of pandas, you can supply a <code>raw=True</code> argument if you want <code>apply</code> to pass an <code>ndarray</code> to your function.</p> <pre><code># data.apply(lambda x: ta.SMA(x, 20), axis=0, raw=True) # Same as, data.apply(ta.SMA, axis=0, raw=True, args=(20, )) </code></pre> <p>PS...
python|pandas|lambda|ta-lib
2
376,318
54,910,321
Allow overflow for numpy types
<p>I'm trying to get the "normal" overflow/underflow behavior of C-type languages in Python. To my surprise, a <code>RuntimeWarning</code> is raised when I'm trying to get this behavior. Example:</p> <pre class="lang-py prettyprint-override"><code>np.uint8(255) + np.uint8(1) &gt;&gt;&gt; RuntimeWarning: overflow encou...
<p>I believe numpy does give you the correct behavior.</p> <pre><code>In [1]: np.uint8(255) + np.uint8(1) /usr/bin/ipython:1: RuntimeWarning: overflow encountered in ubyte_scalars #!/usr/bin/python2 Out[1]: 0 </code></pre> <p>You can suppress the warning by running:</p> <pre><code>In [1]: np.seterr(over='ignore') ...
python|numpy|overflow
2
376,319
55,093,574
Fill NaN's within 1 column of a df via lookup to another df via pandas
<p>I seen various versions of this question but none of them seem to fit with what I am attempting to do: here's my data: </p> <p>Here's the df with the <code>NaN</code>s: </p> <pre><code>df = pd.DataFrame({"A": ["10023", "10040", np.nan, "12345", np.nan, np.nan, "10033", np.nan, np.nan], "B": [",", "1...
<p>The <code>map</code> method from Wen-Ben will be faster in terms of speed, but here's another way you can solve this problem, just for your convenience and knowledge</p> <p>You can use <code>pd.merge</code>, because this is basically a <code>join</code> problem. After the merge, we fillna and drop the columns we do...
pandas|numpy|dataframe|missing-data|fillna
1
376,320
54,904,954
Best method to identify and replace outlier for Salary column in python
<p>What is best method to identify and replace outlier for ApplicantIncome, CoapplicantIncome,LoanAmount,Loan_Amount_Term column in pandas python.</p> <p>I tried IQR with seaborne boxplot, and tried to identified the outlet and fill with NAN record after that take mean of ApplicantIncome and filled with NAN records....
<h2>Outliers</h2> <p>Just like missing values, your data might also contain values that diverge heavily from the big majority of your other data. These data points are called “outliers”. To find them, you can check the distribution of your single variables by means of a box plot or you can make a scatter plot of your ...
sklearn-pandas|data-science-experience
1
376,321
54,993,183
Does a random seed set via numpy.random.seed maintain across submodules?
<p>If I set a seed for my RNG e.g. <code>numpy.random.seed(0)</code> and I call a submodule, will the RNG's state be maintained?</p> <p>e.g.</p> <pre><code># some_lib.py def do_thing(): return numpy.random.rand() </code></pre> <pre><code># parent module import some_lib numpy.seed(0) ... some_lib.do_thing() </code>...
<p>The seed is a global value for all uses of <code>numpy</code>. So as long as the child module doesn't reseed it, or pull values from it non-deterministically (effectively adjusting it to a new seed based on advancing the old), then the seed will be preserved.</p> <p>Most PRNG libraries behave this way, because the ...
python|numpy|random
5
376,322
55,134,142
How to Fix a Column Using a For Loop and Placing into Another Column Using python pandas?
<p>Pasted the code below. Need to fix the accountant name and making each variation them same (doesn't matter which variation, as long each are the same). I figured there were 2 options,1) using a dictionary or 2) trying to fix the name based upon matching the first 3 letters of the Accountant Name.</p> <pre><code>imp...
<p>Not sure what you're asking, so please post expected output.</p> <p>Maybe this?:</p> <pre><code>df['Fixed Accountant Name'] = [x[:3] for x in df['Accountant Name']] df.groupby('Fixed Accountant Name')['Cost'].mean() Fixed Accountant Name Lee 38.666667 McC 8.500000 Sin 19.500000 </code></pre>
python|pandas|dataframe
0
376,323
54,950,980
Problem with removing redundancy from a file
<p>I've got a DataSet with two columns, one with categorical value (<code>State2</code>), and another (<code>State</code>) that contains the same values only in binary.<br> I used <code>OneHotEncoding</code>.</p> <pre><code>import pandas as pd mydataset = pd.read_csv('fieldprotobackup.binetflow') mydataset.drop_dupl...
<p>You either need to add the <code>inplace=True</code> parameter, or you need to capture the returned dataframe:</p> <pre><code>mydataset.drop_duplicates(['Proto2','Proto'], keep='first', inplace=True) </code></pre> <p>or</p> <pre><code>no_duplicates = mydataset.drop_duplicates(['Proto2','Proto'], keep='first') </c...
python|pandas|file|duplicates
2
376,324
55,010,146
Dealing with large sum of distinct values in dataframe columns
<p>Newbie to python, to the world of data analytics with python. I am working on practice data where one of the columns has 87 distinct values and other column has 888 distinct values where I am thinking to delete the latter column. I just don't understand how do I deal with these columns. Do I group these columns or d...
<p>What exactly is your question?</p> <p><strong>Update</strong>: After some clarification/guessing, I am going to assume that the question is about two issues:</p> <ol> <li>How to limit a <code>groupby</code> to only the top <code>k</code> groups (by some aggregate of choice).</li> <li>How to summarize columns, incl...
python|pandas
1
376,325
54,748,330
Changing variable in Lambda layer in pretrained model?
<p>I have imported and pytorch model to keras using pytorch2keras and have made the input flexible from [None,3,224,224] to [None,3,224,224]. Unfortunately, in the original model there is a Lambda layer reducing the output of a convolutional layer by 1, e.g. [None,3,111,111] -> [None,3,110, 110].</p> <p>How can I spec...
<p>You could try to replace the function with <code>lambda x: x[:,:,:-1,:-1]</code>. (If you decide later to use channels_last, then <code>lambda x: x[:,:-1, :-1]</code>.</p> <p>No sure what to do with the argument <code>(3,0,110)</code>, but it seems unnecessary.</p>
python|tensorflow|keras
0
376,326
55,110,049
Creating a '0-1' column based on a list
<p>Let's say that this is head of my df:</p> <pre><code> Team Win_pct_1 Win_pct_2 0 Memphis 0.6 0.5 1 Miami 0.4 0.6 2 Phoenix 0.7 0.4 3 Dallas 0.6 0.3 4 Boston 0.4 0.1 </code></pre> <p>I have created a list of teams for example: </p> <pre><code>...
<p>For your first question, you can use a ternary with <code>np.where</code> and <code>isin</code>:</p> <pre><code>df['New_column'] = np.where(df['Team'].isin(my_list), 1, 0) </code></pre> <p>Another alternative:</p> <pre><code>df['New_column'] = df['Team'].isin(my_list).astype(int) </code></pre>
python|pandas|matplotlib|seaborn
0
376,327
54,987,518
Trying to join two pandas dataframes but get "ValueError: You are trying to merge on object and int64 columns."?
<p>I have two pandas dataframes: <code>seren1</code> and <code>bbox</code>. And I want to perform an inner join of them on column named <code>filepath</code>.</p> <pre><code>seren1[["filepath", "label"]].join(bbox[["filepath", "label"]], on="filepath", how="inner", lsuffix='_caller', rsuffix='_other') </code></pre> <...
<p>I was able to get away with this error as follow: </p> <p>Let suppose you are trying to join df2 to df1. For join function to work correctly, you will have to same column name 'Column' in both data frames and also have to set_index on that column 'Column' in the data frame to be joined. To get df2 joined to df1 at...
python|pandas
0
376,328
55,064,890
How to print a plain text constant in tensorflow eager execution mode
<p>I have initialized a constant in tensorflow:</p> <pre><code>hello = tf.constant('hello') </code></pre> <p>In normal mode, <code>print(sess.run(hello).decode())</code> outputs the plain text in a constant Tensor.</p> <p>In eager execution mode however, the code above does not work.</p> <p>How can I print the plai...
<p>convert tensor to numpy array and then decode</p> <pre><code>print(hello.numpy().decode()) </code></pre>
python|tensorflow
1
376,329
54,965,049
Create array of index values from list with another list python
<p>I have an array of values as well as another array which I would like to create an index to. For example:</p> <pre><code>value_list = np.array([[2,2,3],[255,243,198],[2,2,3],[50,35,3]]) key_list = np.array([[2,2,3],[255,243,198],[50,35,3]]) MagicFunction(value_list,key_list) #result = [[0,1,0,2]] which has the same...
<p>The issue is how to get this to be not terribly inefficient. I see two approaches</p> <ol> <li><p>use a dictionary so that the lookups will be fast. <code>numpy</code> arrays are mutable, and thus not hashable, so you'll have to convert them into, e.g., tuples to use with the dictionary.</p></li> <li><p>Use broadca...
python|image|numpy|indexing
3
376,330
55,138,797
Expand pandas column based on the cell type
<p>I have the following dataframe:</p> <pre><code> field value 0 longitude 100 1 altitude 200 2 location China 3 date 20180303 ...... </code></pre> <p>I want to convert this dataframe into the following format:</p> <pre><code> field string_value int_value datetime_value bo...
<p>Idea is get <code>type</code>s of values, convert to string and <code>map</code> to better readable form, then for new columns use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with <a href="http://pa...
python|pandas|dataframe
3
376,331
54,924,265
Pandas try to append a row to a dataframe but keeps overwriting the existing row
<p>My dataframe (df_UP) looks like this:</p> <pre><code> Total_trends #up #down #flat 0.05 811 326 310 175 </code></pre> <p>I am using a jupyter notebook, when I try to append a row with the following code: </p> <pre><code>`d = {'Total_trends': [total.time], '#up': [good_trigger.time]...
<p>You can convert dictionary to <code>DataFrame</code> and assign back:</p> <pre><code>d = {'Total_trends': [10], '#up': [20], '#down': [3], '#flat': [0]} df_UP = df_UP.append(pd.DataFrame(d), ignore_index=True) print (df_UP) Total_trends #up #down #flat 0 811 326 310 175 1 10 20 ...
python|pandas
1
376,332
55,095,316
How can I make a generator which iterates over 2D numpy array?
<p>I have a huge 2D numpy array which I want to retrieve in batches. Array shape is=<code>60000,3072</code> I want to make a generator that gives me chunks out of this array like : <code>1000,3072</code> , then next <code>1000,3072</code> and so on. How can I make a generator to iterate over this array and pass me a ...
<p>consider array <code>a</code></p> <pre><code>a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) </code></pre> <p><strong><em>Option 1</em></strong><br> Use a generator</p> <pre><code>def get_every_n(a, n=2): for i in range(a.shape[0] // n): yield a[...
python|numpy
3
376,333
55,002,918
Why does the size of tensorflow model files depend on the size of the dataset?
<p>The sizes of .index, .meta, and .data files of my saved model after training on a dataset of 10K sentences are 3KB, 58MB and 375MB respectively</p> <p>Keeping the architecture of the network same and training it on a dataset of 100K sentences, the sizes of the files are 3KB, 139MB and 860MB</p> <p>I think it sugge...
<pre><code>import tensorflow as tf from tensorflow.python.training import checkpoint_utils as cp cp.list_variables('./model.ckpt-12520') </code></pre> <p>Running the above snippet gives the following output</p> <pre><code>[('Variable', []), ('decoder/attention_wrapper/attention_layer/kernel', [600, 300]), ('decoder/a...
tensorflow
1
376,334
54,938,429
Reading multiple excel files and writting it to multiple excel files in python
<p>I have written code where it is reading excel file and then after processing required function I want to write it to Excel file . Now I have done this for one excel file . and now my question is when I want to do it for multiple excel file that is reading multiple excel file and then output should be also in multip...
<p>I tried to stick to your example and just expand it as I would do it. The below example is untested and does not mean that it is the best way to do it!</p> <pre><code>from ParallelP import * import time,json import pandas as pd import os from pathlib import Path # Handles directory paths -&gt; less error prone tha...
python|excel|pandas
0
376,335
55,096,595
How to plot normal distribution curve along with Central Limit theorem
<p>I am trying to get a normal distribution curve along my Central limit data distribution.</p> <p>Below is the implementation I have tried.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats import math # 1000 simulations of die roll n = 10000 avg = []...
<p>You almost had it! First, see that you're plotting two histograms on the same axes:</p> <pre><code>plt.hist(avg[0:]) </code></pre> <p>and</p> <pre><code>plt.hist(s, 20, normed=True) </code></pre> <p>So that you can plot the normal density over the histogram you rightly normalised the second plot with the <code>n...
python|numpy|matplotlib|statistics
2
376,336
54,797,538
How to write values of dictionary in numpy array to csv file instead of the full dictionary?
<p>I'm trying to write a multidimensional <code>numpy</code> array to a <code>.csv</code> file. This array includes words, numbers, and a dictionary. When writing the file, my code prints the keys and values to the array. However, I need only the values to be written.</p> <p>My code can be seen as follows:</p> <pr...
<p>Assume, for lack of further information, that your <code>array</code> is really a <code>list</code> like:</p> <pre><code>In [338]: alist = ['Abjure','abjure',{'a': 1, 'b': 1, 'c': 0, 'd': 0, 'e': 1, 'f ...: ': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 1, 'k': 0, 'l': 0, 'm': 0, 'n': 0, ...: 'o': 0, 'p': 0, 'q': 0,...
python|file|csv|numpy|dictionary
0
376,337
54,765,953
How to replace Swedish characters ä, å, ö in columns names in python?
<p>I have a dataframe with some columns names having Swedish characters (ö,ä,å). I would like to replace these characters with simple o,a,a instead. </p> <p>I tried to convert the columns names to str and replace the characters, it works but then it gets complicated if I want to assign back the str as columns names, i...
<p>For me working first normalize, then encode to ascii and last decode to <code>utf-8</code>:</p> <pre><code>df = pd.DataFrame(columns=['aä','åa','oö']) df.columns = (df.columns.str.normalize('NFKD') .str.encode('ascii', errors='ignore') .to_series() ...
pandas|python-2.7|python-unicode
3
376,338
55,121,828
Negative examples for image classification?
<p>I have 1000 images of dogs and 1000 images of cats. </p> <p>I've trained a small CNN to do classification on this dataset and the accuracy on both the validation/test set is 99% +. </p> <p>But, I've noticed that when I give an input that isn't a cat or a dog, for example a car, the classifier (sometimes) gives a h...
<p>If the network is trained only on dog/cat images, it makes sense that it confuses an image that belongs to none of the two categories. You should add negative examples in the training set (as you mentioned) and convert your final classification layer to predict confidence over 3 catetegories (dog, cat, none). This s...
tensorflow|machine-learning|deep-learning|classification
1
376,339
54,799,199
I cannot fully uninstall numpy
<p>I wrote "pip uninstall numpy", and it appears uninstalled. For example when I put import pandas, it returns </p> <pre><code>module 'numpy' has no attribute '__version__' </code></pre> <p>But when I run "import numpy" it lets me import it. However, it does when i ask it </p> <pre><code>print numpy.__file__ </code>...
<p>I installed the 2018-12 version of Anaconda, and it appears like the problem has been solved. </p>
python|numpy
1
376,340
55,044,538
How to search by using different columns
<p>Gender and city are two different columns. I want to search in such a way that how many males and Females from Gender column in particular city in Pandas</p>
<pre><code>df = pd.DataFrame({ 'city': ['NY', 'NY', 'NY', 'LA'], 'gender': ['m', 'f', 'f', 'm']}) z = df.groupby(['city', 'gender']).size() z </code></pre> <p>Output:</p> <pre><code>city gender LA m 1 NY f 2 m 1 </code></pre> <p>To check distribution in one city, e.g. NY...
pandas
1
376,341
54,951,448
How to subtract neighbouring vectors in a numpy array from each other
<p>My expected results are as follows:</p> <pre><code>array = [[2,3,4], [1,2,4]] </code></pre> <p>Output:</p> <pre><code>[1, 1, 0] # [2-1, 3-2, 4-4] </code></pre> <p>I tried doing this by enumerating and getting the indexes to subtract with no luck as:</p> <pre><code>for i, k in enumerate(array): for j in k: ...
<p>This works:</p> <pre><code>result = [(i-j) for (i,j) in zip(*array)] </code></pre> <p><strong>Output:</strong></p> <pre><code>print (result) [1, 1, 0] </code></pre> <p><strong>Explanation:</strong></p> <p><code>zip(*array)</code> is equivalent to the list of tuples <code>[(2,1), (3,2), (4,4)]</code></p>
python|numpy
0
376,342
54,808,927
How to get two columns Values based on Where function in python
<p>The Question is: Based on the <code>user_id</code> column, I want to get the values of <code>rating</code> and <code>product_id</code> columns. There can be multiple entries with the same user_id. I want to get all users records with the <code>rating</code> and <code>product_id</code> columns value But for the movie...
<p>try </p> <pre><code> print(df[df.user_id==y][['rating','product_id']]) </code></pre>
python|python-3.x|pandas|csv
1
376,343
55,128,156
Importing CSV file into Google Colab using numpy loadtxt
<p>I'm trying to migrate a JupyterLab notebook to Google Colab. In JupyterLab, when I have the notebook file and the associated csv files in the same directory, it is easy to import the data using numpy's loadtxt function as follows:</p> <pre><code>import numpy as np filein = "testfile.csv" data = np.loadtxt(open(file...
<p>Colab doesn't automatically mount Google Drive. By default, the working directory is <code>/content</code> on an ephemeral backend virtual machine.</p> <p>To access your file in Drive, you'll need to mount it first using the following snippet:</p> <pre><code>from google.colab import drive drive.mount('/content/gdr...
python|numpy|import|google-colaboratory
11
376,344
54,821,206
I want all numpy arrays to be forced to be 2 dimensional
<p>I am coming over from Matlab, and while everything was mostly ported over really well (the community has to be thanked for this, a Matlab license costs way over $1000). There is one thing that I cannot for the life of me find out.</p> <p>In Matlab, all arrays are 2D (until recently, where they gave you other option...
<p>As noted above, the np.matrix class has semantics quite similar to a matlab array.</p> <p>However, if you goal is to learn numpy as a marketable skill, I would strongly recommend you fully embrace the concept of an ndarray; while there is some historical truth to calling numpy a port of matlab, it is a bit of an in...
python|arrays|numpy
2
376,345
55,088,656
Most efficient way to calculate frequency of pairs of numbers in a 2D Numpy array
<p>Let's say I have the following 2D array:</p> <pre><code>import numpy as np np.random.seed(123) a = np.random.randint(1, 6, size=(5, 3)) </code></pre> <p>which produces:</p> <pre><code>In [371]: a Out[371]: array([[3, 5, 3], [2, 4, 3], [4, 2, 2], [1, 2, 2], [1, 1, 2]]) </code></pre> <...
<p>If your elements are not too large nonnegative integers <code>bincount</code> is fast:</p> <pre><code>from collections import Counter from itertools import combinations import numpy as np def pairs(a): M = a.max() + 1 a = a.T return sum(np.bincount((M * a[j] + a[j+1:]).ravel(), None, M*M) ...
python|performance|numpy|processing-efficiency
2
376,346
49,483,025
Adding Tensorboard summaries from graph ops generated inside Dataset map() function calls
<p>I've found the Dataset.map() functionality pretty nice for setting up pipelines to preprocess image/audio data before feeding into the network for training, but one issue I have is accessing the raw data before the preprocessing to send to tensorboard as a summary. </p> <p>For example, say I have a function that lo...
<p>I think your use of Dataset API doesn't make much sense. In fact you have 2 disconnected subgraphs. One for reading data and the other for running your training step.</p> <pre class="lang-py prettyprint-override"><code>batch_ys, batch_xs, path = sess.run(next_element) summary, train_acc, _ = sess.run([summaries, ac...
python|tensorflow|tensorboard|tensorflow-serving|tensorflow-datasets
5
376,347
49,466,894
How to correctly give inputs to Embedding, LSTM and Linear layers in PyTorch?
<p>I need some clarity on how to correctly prepare inputs for batch-training using different components of the <code>torch.nn</code> module. Specifically, I'm looking to create an encoder-decoder network for a seq2seq model.</p> <p>Suppose I have a module with these three layers, in order:</p> <ol> <li><code>nn.Embed...
<p>Your understanding of most of the concepts is accurate, but, there are some missing points here and there.</p> <h3>Interfacing embedding to LSTM (Or any other recurrent unit)</h3> <p>You have embedding output in the shape of <code>(batch_size, seq_len, embedding_size)</code>. Now, there are various ways through wh...
lstm|pytorch
58
376,348
49,682,724
Tensorflow Index File Utility
<p>I've been looking for a clear answer, but couldn't find until now.</p> <p>In Tensorflow, after the training executing, 4 files are generated:</p> <p>.meta, .data, .index and checkpoint</p> <p>What is the utility of the .index file?</p> <p>Thanks! </p>
<p>The .index file holds an immutable key-value table linking a serialized tensor name and where to find data in its .data files</p>
tensorflow|machine-learning|deep-learning
1
376,349
49,729,404
Produce equal length of rows for each value in another column (using Python or SQL)
<p>My original data in the table is organised as below format:</p> <pre><code> routes demand days Paris-New York 1 Paris-New York 3 Paris-New York 5 London-Berlin 2 London-Berlin 3 London-Berlin 4 London-Berlin 5 Tokyo-Shanghai 2 Tokyo-Shanghai 4 </code></pre> <p>The desired forma...
<p><strong>pandas</strong> solution working if for each <code>routes</code> are unique <code>demand days</code>:</p> <pre><code>df = df.set_index(['routes']).set_index('demand days', drop=False, append=True) df = (df.reindex(pd.MultiIndex.from_product(df.index.levels,names=('routes','calendar days'))) .reset_i...
python|sql|pandas
2
376,350
49,789,700
Extracting just Month and Year from Pandas Datetime column in a .csv file(Python)
<pre><code>OrderDate 2/1/2018 3/1/2018 3/1/2018 3/1/2018 2/1/2018 3/1/2018 3/1/2018 3/1/2018 3/1/2018 3/1/2018 3/1/2018 3/1/2018 3/1/2018 3/1/2018 2/1/2018 </code></pre> <p>The format of the date is <code>%d/%M/%Y</code>. When i changed the string <code>Orderdate</code> to <code>Datetime</code>, the day becomes the mo...
<pre><code>import pandas as pd import os df = pd.read_csv("sample.csv") df['OrderDate'] = pd.to_datetime(df['OrderDate'], format='%Y%m%d', errors='ignore') print df </code></pre> <h1>output:</h1> <pre><code> OrderDate 0 2/1/2018 1 3/1/2018 2 3/1/2018 3 3/1/2018 4 2/1/2018 5 3/1/2018 6 3/1/2018 7 3/1/...
python|pandas|datetime
0
376,351
49,632,200
Replace numpy cell with values from second array based on a condition
<p>I have two images, <code>img1</code> and <code>img2</code>. I'm trying to find everywhere in <code>img1</code> that the color <code>[0,204,204]</code> occurs and replace it with whatever is in <code>img2</code> in the same place. I can use <code>np.where()</code> to find the places where that color occurs and repla...
<p>If I understand correctly, you can use the following:</p> <pre><code>img1[np.where((img1==[0,204,204]).all(axis=2))] = img2[np.where((img1==[0,204,204]).all(axis=2))] </code></pre> <p>This works because the syntax you had originally (<code>np.where((img1==[0,204,204]).all(axis=2))</code>) already returns the indic...
python|arrays|image|numpy
1
376,352
49,480,591
Group and rename pandas dataframe
<p>In Pythons Pandas, I have a dataframe where one column holds a group called "code" and another column holds notes for that group. Each occurrence of those groups may have different notes.<br> How to rename the groups by selecting the first occurrence of the note in that group? <br><br> Example: <br> IN:</p> <pre><c...
<p>Call <code>drop_duplicates</code> and then <code>map</code> <code>NOTE</code> to <code>CODE</code>:</p> <pre><code>df['CODE'] = df.CODE.map(df.drop_duplicates('CODE').set_index('CODE').NOTE) </code></pre> <p>Or,</p> <pre><code>df['CODE'] = df.CODE.replace(df.drop_duplicates('CODE').set_index('CODE').NOTE) </code>...
python|pandas|dataframe
2
376,353
49,645,155
Filtering out Non English sentences in a list in Python Pandas
<p>So there is a excel file which i have read through pandas and stored it in a dataframe 'df'. Now that excel file contains 24 columns as 'questions' and 631 rows as 'responses/answers'.</p> <p>So i converted one such question into a list so that i can tokenize it and apply further nlp related tasks on it.</p> <pre>...
<p>There is another library (closely related to nltk), TextBlob, Initially bound to Sentiment analysis, But you can still use it for translation, see the doc here: <a href="https://textblob.readthedocs.io/en/dev/quickstart.html" rel="nofollow noreferrer">https://textblob.readthedocs.io/en/dev/quickstart.html</a></p> <...
python|pandas|filtering|non-english|pyenchant
1
376,354
49,604,224
Pulling stock information using pandas datareader
<p>I am using pandas datareader to pull stock information for a given range of dates. For example:</p> <pre><code>import pandas_datareader.data as web import datetime as dt start = dt.datetime(2018,3,26) end = dt.datetime(2018,3,29) web.DataReader('IBM','yahoo', start, end).reset_index() </code></pre> <p>This retur...
<p>Here is another way, creating your dataframe directly:</p> <pre><code>tickers = ['IBM','AAPL'] df = pd.concat([web.DataReader(ticker,'morningstar', start, end) for ticker in tickers]).reset_index() </code></pre> <p>Which returns:</p> <pre><code> Symbol Date Close High Low Open Volume 0 ...
python|pandas|stock|datareader
6
376,355
49,399,198
Sort a tensor based on two columns in tensorflow
<p>Is it possible to sort a tensor based on values in two columns in Tensorflow?</p> <p>For example, let's say I have the following tensor.</p> <pre><code>[[1,2,3] [2,3,5] [1,4,6] [2,2,1] [0,4,2]] </code></pre> <p>I would lik it to be sorted first based on the first column and then the second column. After sorting i...
<p>A very naive approach, </p> <pre><code>import tensorflow as tf a = tf.constant([[1, 2, 3], [2, 3, 5], [1, 4, 6], [2, 2, 1], [0, 4, 2]]) # b = a[:0]*10 + a[:1]*1 -- &gt; (e.g 1*10+2*1 =12) b = tf.add(tf.slice(a, [0, 0], [-1, 1]) * 10, tf.slice(a, ...
python|tensorflow
1
376,356
49,424,084
Loop on pandas dataframe over unique values only
<p>I have the following pandas dataframe:</p> <pre><code>DB Table Column Format Retail Orders ID INTEGER Retail Orders Place STRING Dept Sales ID INTEGER Dept Sales Name STRING </code></pre> <p>I want to loop on the Tables, while generating a SQL for creating the tables. e.g. </p...
<p>This is the way I would do it. First create a dictionary via <code>df.itertuples</code> [more efficient than <code>df.iterrows</code>], then use <code>str.format</code> to include the values seamlessly.</p> <p>Uniqueness is guaranteed in dictionary construction by using <code>set</code>.</p> <p>I also convert to a...
python|pandas
2
376,357
49,543,158
How to use weights in tf.metrics.auc?
<p>The docs for the <a href="https://www.tensorflow.org/api_docs/python/tf/metrics/auc" rel="nofollow noreferrer">tf.metrics.auc function in tensorflow</a> say</p> <blockquote> <p>weights: Optional Tensor whose rank is either 0, or the same rank as labels, and must be broadcastable to labels (i.e., all dimensions mu...
<p>Assuming your labels are a vector, setting the weights to be a vector with 1 for rows where data points belong to a class and 0 for rows where data points do not belong to that class will let you compute AUC for members of that class.</p>
tensorflow|auc
0
376,358
49,514,655
r - Dplyr 'ungroup' function in pandas
<p>Imagine you have in R this 'dplyr' code:</p> <pre><code>test &lt;- data %&gt;% group_by(PrimaryAccountReference) %&gt;% mutate(Counter_PrimaryAccountReference = n()) %&gt;% ungroup() </code></pre> <p>how can I exactly convert this to pandas equivalent code ? Shortly, I need to group by to...
<p>Now you are able to do it with <a href="https://github.com/pwwang/datar" rel="nofollow noreferrer"><code>datar</code></a>:</p> <pre class="lang-py prettyprint-override"><code>from datar import f from datar.dplyr import group_by, mutate, ungroup, n test = data &gt;&gt; \ group_by(f.PrimaryAccountReference) &g...
python|r|pandas|group-by|dplyr
0
376,359
49,755,610
in keras, how can apply filter ( where ) funtion?
<p>like filter funtion in functools package, i want to find element over 0.5 in tensor. </p> <p>this is code for that, but not work . </p> <pre><code>def pred_overhalf(y_true, y_pred): return K.count_params( filter( lambda x : x &gt; 0.5 , y_pred ) ) model.compile(optimizer = "adam" , loss = "mse", metrics = [ p...
<pre><code>def pred_overhalf(y_true,y_pred): out = K.greater(y_pred,0.5) out = K.cast(out,K.floatx()) #option 1 return K.mean(out) #fraction of items greater than 0.5 #option 2 return K.sum(out) #total count (beware: this will consider all samples) </code></pre>
python|tensorflow|deep-learning|keras
0
376,360
49,371,943
Error in data type in python?
<p>I have a text file which has 4 attributes like this:</p> <pre><code> taxi id date time longitude latitude 0 1 2008-02-02 15:36:08 116.51172 39.92123 1 1 2008-02-02 15:46:08 116.51135 39.93883 2 1 2008-02-02 15:46:08 116.51135 39.93883 3 1 2008-02-02 15:56:08 116.5162...
<p>Your data ingestion is incorrect. You have a table with <em>one</em> column named <code>taxi id date time longitude latitude</code>. You need to insert or specify the proper data separator when your read the file.</p>
python|pandas
0
376,361
49,775,476
Python Pandas: reduce dataframe to contain with duplicate states
<p>this is my first question I ask here, I couldn't find an easy solution to my problem.</p> <p>I want to reduce a dataframe which contains state changes. Similar to ".drop_duplicates()" i want to reduce the dataframe with duplicate states, but instead it should only drop the row when the state didn't change.</p> <p>...
<p>One way is to compare your series to a series shifted by one value:</p> <pre><code>df = pd.DataFrame(data={'Date':('Day1', 'Day2', 'Day3', 'Day4', 'Day5'), 'State':(1,0,0,2,0)}) df = df.set_index('Date') res = df.loc[df['State'] != df['State'].shift()] print(res) # State # Date ...
python|pandas|dataframe
1
376,362
49,734,582
Summing in a list of Counters
<p>I have a following list of counters </p> <pre><code>[Counter({'A': 2, 'B': 2, 'C': 1}), Counter({'A': 3, 'B': 3, 'C': 2}), Counter({'A': 4, 'B': 4, 'C': 4}), Counter({'A': 5, 'B': 4, 'C': 5}), Counter({'A': 6, 'B': 6, 'C': 6}), Counter({'A': 7, 'B': 8, 'C': 8}), Counter({'A': 8, 'B': 9, 'C': 9}), Counter({'A': 9, '...
<p>Since <code>pd.DataFrame()</code> knows how to handle a list of dictionaries, this can be done fairly easily:</p> <pre><code>counter_list = [Counter({'A': 2, 'B': 2, 'C': 1}), Counter({'A': 3, 'B': 3, 'C': 2}), Counter({'A': 4, 'B': 4, 'C': 4}), Counter({'A': 5, 'B': 4, 'C': 5}), ...
python|python-3.x|list|pandas|counter
1
376,363
49,673,876
Assign new values in pandas
<p>I am trying to change the value in one row in pandas dataframe for certain columns with other values:</p> <pre><code>sub_data.loc[[0],20:71] = sub_data.loc[1,20:71] or sub_data.loc[0,20:71] = sub_data.loc[1,20:71] </code></pre> <p>both did not work. any suggestion? </p> <p>Update</p> <p>It was solved when I used...
<p>Most probable reason is that you are using <code>20:71</code> in <code>loc</code>. That looks like you need <code>iloc</code></p> <pre><code>sub_data.iloc[0, 20:71] = sub_data.iloc[1, 20:71] </code></pre>
python|pandas|row
1
376,364
49,432,508
Multiple input/output arguments for function in python
<p>I wrote the following function to convert a value (col) with unit (ufrom) into another unit (uto):</p> <pre><code>def convert(row, col , ufrom, uto): convRow = convDF[(convDF.from == row[ufrom]) &amp; (convDF.to == uto)] val = row[col] / convRow.factor return(val, uto) </code></pre> <p>convDF is a data...
<p>You can have your function take a list of columns as an argument then return a list based on what is in the column list. For example, </p> <pre><code>def convert(row, cols , ufrom, uto): values=[] for col in cols: convRow = convDF[(convDF.from == row[ufrom]) &amp; (convDF.to == uto)] values....
python|pandas|function|multiple-columns
1
376,365
49,576,858
Adding LSTM to conv2D layers in keras
<p>I have an input shape of 64x60x4 for reinforcement learning an agent to play Mario. The problem is, it seems very "if screen looks like this then do that", which isn't very good for this problem.</p> <p>I want to add an LSTM layer after 3 conv2D layers in Keras (TensorFlow) but it complains that it expects 5 dimens...
<p>I would suggest something like this, after your MaxPooling Layer)</p> <pre><code>out = Reshape((64, -1))(out) out = LSTM(...)(out) out = Flatten... </code></pre> <p>Also I don't recommend starting with 32 filters then going up, I suggest starting with 64 then going down, but hey, you do you. Also I would suggest s...
python|tensorflow|keras
1
376,366
49,533,818
Not able to import numpy in JyNi alpha 4
<p>I am new to python and jython i want to import numpy in my jython program but whenever i import it shows following error:</p> <pre><code>Traceback (most recent call last): File "/home/phpdev/workspace/FirstProgram/testone.py", line 16, in &lt;module&gt; import numpy File "/usr/lib/python2.7/dist-packages/numpy/__in...
<p>What you are trying to do should be workable as NumPy 12 and 13 are supported in JyNI alpha 4, 5 and newer.</p> <p>Most likely, Jython/JyNI locates the wrong NumPy installation. I suspect that you have multiple numpy installations in parallel and JyNI takes the wrong one.</p> <p>Further information on your platfor...
python|numpy|jyni
0
376,367
49,534,162
File with sequence of numbers to two column array/list and then plot
<p>I have a text file (test.txt) which just has some sequence of numbers e.g. 2, 5, 6, 9, 3, 1, 3, 5, 5, 6, 7, 8, etc. My main goal is to plot odd placed numbers on the X-axis and even placed numbers on the Y-axis. To do that i thought, perhaps i can first store them in a list/array with two columns and then just ...
<p>I am assuming your <code>data</code> to be saved in <code>myFile.csv</code> like this:</p> <pre><code>2, 5, 6, 9, 3, 1, 3, 5, 5, 6, 7, 8 5, 6, 9, 3, 1, 3, 5, 5, 6, 7, 8, 8 </code></pre> <p>you can load it into a numpy array with <code>np.loadtxt</code>. If you don't want your dataset to be divided into multiple li...
python|numpy|matplotlib|number-sequence
0
376,368
49,464,047
pandas groupby events across different days
<pre><code>import pandas as pd df = pd.DataFrame(data=[[1,1,10],[1,2,50],[1,3,20],[1,4,24], [2,1,20],[2,2,10],[2,3,20],[2,4,34],[3,1,10],[3,2,50], [3,3,20],[3,4,24],[3,5,24],[4,1,24]],columns=['day','hour','event']) df Out[4]: day hour event 0 1 1 10 1 1 2 50 2 1 3 20 &lt;- ...
<pre><code>#convert columns to datetimes, for same day of next day subtract 2 hours: a = pd.to_datetime(df['day'].astype(str) + ':' + df['hour'].astype(str), format='%d:%H')- pd.Timedelta(2, unit='h') #get hours between 1 and 23 only -&gt;in real 3,4...23,1 hours = a.dt.hour.between(1,23) #create consecutives groups by...
python|pandas|dataframe
1
376,369
49,455,620
Find rows in pandas dataframe, where diffrent rows have common values in lists in columns storing lists
<p>I can solve my task by writing a for loop, but I wonder, how to do this in a more pandorable way.</p> <p>So I have this dataframe storing some lists and want to find all the rows that have any common values in these lists, </p> <p>(This code just to obtaine a df with lists:</p> <pre><code>&gt;&gt;&gt; df = pd.Dat...
<p>Using a <code>merge</code> on <code>df</code>:</p> <pre><code>v = df.merge(df, on='b') common_cols = set( np.sort(v.iloc[:, [0, -1]].query('a_x != a_y'), axis=1).ravel() ) common_cols {'A', 'B'} </code></pre> <p>Now, pre-filter and call <code>groupby</code>:</p> <pre><code>df[df.a.isin(common_cols)].groupby(...
python|pandas|dataframe|pandas-groupby
2
376,370
49,677,060
Pandas: count empty strings in a column
<p>I tried to find the number of cells in a column that only contain empty string <code>''</code>. The <code>df</code> looks like:</p> <pre><code>currency USD EUR ILS HKD </code></pre> <p>The code is:</p> <pre><code>df['currency'].str.contains(r'\s*') </code></pre> <p>but the code also recognizes cells with actual ...
<p>Several ways. Using <code>numpy</code> is usually more efficient.</p> <pre><code>import pandas as pd, numpy as np df = pd.DataFrame({'currency':['USD','','EUR','']}) (df['currency'].values == '').sum() # 2 len(df[df['currency'] == '']) # 2 df.loc[df['currency'] == ''].count().iloc[0] ...
python|string|pandas|dataframe|series
25
376,371
49,539,203
Pandas - Combine Excel Rows on ID
<p>I have a dataframe that currently looks like this. I need to combine the two rows on the id.</p> <pre><code> id post date 0 10-1 Lorem ipsum dolor sit amet, consectetur adipiscing... 2012-01-28 1 10-1 Ut enim ad minim veniam, quis nostrud ...
<p>You can can past a dict to agg, <code>key</code> of the dict is the <code>column</code> and <code>value</code> is the function you will implement to that column. </p> <pre><code>df.groupby('id').agg({'post':'sum','date':'first'}) </code></pre>
python|excel|pandas
2
376,372
49,502,617
How can I multiply unaligned numpy matrices in python?
<p>I've got two numpy matrices: the first, <code>indata</code> has a shape of <code>(2, 0)</code>. The second (<code>self.Ws[0]</code> in my code) has a shape of <code>(100, 0)</code>.</p> <p>Is it possible to multiply these matrices by each other? </p> <pre><code>def Evaluate(self, indata): sum = np.dot(self.Ws[...
<p>There is no such thing as shape <code>(N, 0)</code> for an array unless the array is empty. What you have is probably of shape <code>(2,)</code> and <code>(100,)</code>. One way of multiplying these objects is:</p> <pre><code>np.dot(self.Ws[0].reshape((-1, 1)), indata.reshape((1, -1))) </code></pre> <p>This is goi...
python|numpy|sum
1
376,373
28,140,771
Select only one index of multiindex DataFrame
<p>I am trying to create a new DataFrame using only one index from a multi-indexed DataFrame. </p> <pre><code> A B C first second bar one 0.895717 0.410835 -1.413681 two 0.805244 0.813850 1.607920 baz one -1.206412 0.132003 1.02...
<p>One way could be to simply rebind <code>df.index</code> to the desired level of the MultiIndex. You can do this by specifying the label name you want to keep:</p> <pre><code>df.index = df.index.get_level_values('first') </code></pre> <p>or use the level's integer value:</p> <pre><code>df.index = df.index.get_leve...
python|pandas|select|dataframe|indexing
106
376,374
28,331,948
Numpy getting in the way of int -> float type casting
<p>Apologies in advance - I seem to be having a very fundamental misunderstanding that I can't clear up. I have a fourvector class with variables for ct and the position vector. I'm writing code to perform an x-direction lorentz boost. The problem I'm running in to is that I, as it's written below, ct returns with a pr...
<p>All your problems are indeed related.</p> <p>A numpy array is an array that holds objects efficiently. It does this by having these objects be of the same <em>type</em>, like strings (of equal length) or integers or floats. It can then easily calculate just how much space each element needs and how many bytes it mu...
python|numpy
12
376,375
28,314,337
TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0] while using RF classifier?
<p>I am learning about random forests in scikit learn and as an example I would like to use Random forest classifier for text classification, with my own dataset. So first I vectorized the text with tfidf and for classification:</p> <pre><code>from sklearn.ensemble import RandomForestClassifier classifier=RandomForest...
<p>I don't know much about <code>sklearn</code>, though I vaguely recall some earlier issue triggered by a switch to using sparse matricies. Internally some of the matrices had to replaced by <code>m.toarray()</code> or <code>m.todense()</code>.</p> <p>But to give you an idea of what the error message was about, cons...
python|numpy|machine-learning|nlp|scikit-learn
13
376,376
28,238,275
python pandas yahoo data ETF
<p>I would like to fetch some ETF data from yahoo finance using pandas. </p> <p>If I go onto the yahoo finance website, I can find the single ETFs (e.g. C001).</p> <p>However, if I try to pull the data using python pandas, I get nothing.</p> <pre><code>df = pd.io.data.DataReader('C001','yahoo',start=datetime(2010,1,...
<p>i noticed that on yahoo finance there are several tickers for C001 (C001.f,c001.de and so on).</p> <p>i used some of my code(that include the ticker simbol too) and with C001F (or everything else) it worked fine.</p> <pre><code> import datetime import pandas as pd from pandas import DataFrame from pandas.io.dat...
python|pandas|yahoo-finance
1
376,377
28,207,077
Why does inserting a dimension of size 1 into a numpy array invalidate its 'contiguous' flag?
<p>Consider this array:</p> <pre><code>In [1]: a = numpy.array([[1,2],[3,4]], dtype=numpy.uint8) In [2]: a.strides Out[2]: (2, 1) In [3]: a.flat[:] Out[3]: array([1, 2, 3, 4], dtype=uint8) In [4]: a.flags['C_CONTIGUOUS'] Out[4]: True In [5]: numpy.getbuffer(a)[:] Out[5]: '\x01\x02\x03\x04' </code></pre> <p>So far...
<p>This is a bit mysterious, and I even dug into the source code a bit before I saw <a href="https://stackoverflow.com/questions/28207077/why-does-inserting-a-dimension-of-size-1-into-a-numpy-array-invalidate-its-cont#comment44782376_28207077">hpaulj</a>'s comment. His observation that <code>reshape</code> and slicing ...
python|numpy
0
376,378
28,196,476
Pandas Boolean indexing with two dataframes
<p>I have two pandas dataframes:</p> <pre><code>df1 'A' 'B' 0 0 0 2 1 1 1 1 1 3 df2 'ID' 'value' 0 62 1 70 2 76 3 4674 4 3746 </code></pre> <p>I want to assign <code>df.value</code> as a new column <code>D</code> to df1, but just when <code>df.A == 0</code>. <code>df1.B</code> and <code...
<p>Slightly tricky this one, there are 2 steps here, first is to select only the rows in df where 'A' is 0, then merge to this the other df where 'B' and 'ID' match but perform a 'left' merge, then select the 'value' column from this and assign to the df:</p> <pre><code>In [142]: df['D'] = df[df.A == 0].merge(df1, le...
python|python-3.x|pandas
3
376,379
73,468,198
Shuffling of time series data in pytorch-forecasting
<p>I am using pytorch-forecasting for count time series. I have some date information such as hour of day, day of week, day of month etc...</p> <p>when I assign these as categorical variables in <strong>TimeSeriesDataSet</strong> using <strong>time_varying_known_categoricals</strong> the training.data['categoricals'] v...
<p>Actually, the <strong>time_varying_known_categoricals</strong> are NOT shuffled. The categories assigned to them are not in order like 1 for 1st hour, 2 for 2nd hour etc.. that's why it feels like it has shuffled the time series. I tried to align &quot;hour_of_day&quot; categorical variable for 3 days. I noticed th...
time-series|pytorch-forecasting
0
376,380
73,461,557
How to reward for two parameters in reinforcement learning?
<p>I have a two box that should touch each other in straight line, so I have done two approach to reward:</p> <p>Approach 1: Reward when distance is decreasing this approach works well in 50% event after 100 million steps of training. The problem is that two box do not touch each other completely straight and it fails ...
<p>May be you can try to use only the first way and improve it.</p> <p>You can add more conditions to help your agent to reach the goal.</p> <p>for example :</p> <pre><code>reward = 0 if(distance &lt; lastDistance) reward += 1 lastDistance = distance if(distance &lt; 5) reward += 5 if(distance &lt; 3) reward...
tensorflow|machine-learning|pytorch
0
376,381
73,258,315
deleting pandas dataframe rows not working
<pre><code>import numpy as np import pandas as pd randArr = np.random.randint(0,100,20).reshape(5,4) df =pd.DataFrame(randArr,np.arange(101,106,1),['PDS', 'Algo','SE','INS']) df.drop('103',inplace=True) </code></pre> <p>this code not working</p> <pre><code>Traceback (most recent call last): File &quot;D:\Education\4t...
<p>The string '103' isnt in the index, but the integer 103 is:</p> <p>Replace <code>df.drop('103',inplace=True)</code> with <code>df.drop(103,inplace=True)</code></p>
python-3.x|pandas|dataframe|numpy
0
376,382
73,332,481
How to use grouped rows in pandas
<p>Hello I have table with MultiIndex:</p> <pre><code>Lang C++ java python All Corp Name ASW ASW 0.0 0.0 5.0 5 Facebook Facebook 8.0 1.0 5.0 14 Google Google 2.0 24.0 1.0 27 ASW Cristiano NaN NaN 5.0 5 Facebook...
<p>Add <code>group_keys=False</code> parameter in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a>:</p> <pre><code>out = (df.groupby(level=0, group_keys=False) .apply(lambda g: g.sort_values('All', asc...
python|pandas|group
0
376,383
73,364,110
unable to change date format while loading excel file with pandas
<p>I'm loading an Excel file with pandas using the parse_dates=True parameter. However, the date format can not change. When I open the file in Excel on my local computer, the date format is accurate, but when the file is loaded in Python, the format is incorrect. The issue is that &quot;dmY acts like mdY for half of t...
<p>Using pd.to_datetime() allows for the use of the <code>infer_datetime_format</code> argument which eases working with datetime values. In this particular case, if you'd like to parse all columns except for ID you can try:</p> <pre><code>df['RT_Date'],df['DateCreated'] = [pd.to_datetime(df[x],infer_datetime_format=T...
python|python-3.x|pandas|dataframe|datetime
2
376,384
73,418,894
How to obtain counts and sums for pairs of values in each row of Pandas DataFrame
<p><strong>Problem:</strong></p> <p>I have a <code>DataFrame</code> like so:</p> <pre><code>import pandas as pd df = pd.DataFrame({ &quot;name&quot;:[&quot;john&quot;,&quot;jim&quot;,&quot;eric&quot;,&quot;jim&quot;,&quot;john&quot;,&quot;jim&quot;,&quot;jim&quot;,&quot;eric&quot;,&quot;eric&quot;,&quot;john&quot;]...
<p>You need two <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>groupby.transform</code></a>:</p> <pre><code>g = df.groupby(['name', 'category'])['amount'] df['sum_for_category'] = g.transform('sum') df['count_or_category'] = g.t...
python|pandas|dataframe
2
376,385
73,455,571
two intervals color df panda red <-3 and green >3
<p>I would like to know how to generate two intervals for my highlight. I want all the value of my df &lt;-3 in red and all the value &gt;3 in green, else don't change, in black.</p> <p>I try with highlight_between and other, but never work :</p> <pre><code>cm = sns.light_palette(&quot;blue&quot;, as_cmap = True) df = ...
<pre><code>import pandas as pd import numpy as np np.random.seed(0) df = pd.DataFrame((np.random.rand(5,10) - 0.5) * 20) df.style.applymap(lambda x: f&quot;background-color: {'lime' if x &gt; 3 else 'tomato' if x &lt; -3 else 'white'}&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/winXU.png" rel="nofollow...
python|pandas|styles|highlight|intervals
1
376,386
73,211,773
How to fill nans with multiple if-else conditions?
<p>I have a dataset:</p> <pre><code> value score 0 0.0 8 1 0.0 7 2 NaN 4 3 1.0 11 4 2.0 22 5 NaN 12 6 0.0 4 7 NaN 15 8 0.0 5 9 2.0 24 10 1.0 12 11 1.0 15 12 0.0 5 13 2.0 26 14 NaN 28 </code></pre> <p>There are some NaNs in it. I w...
<p>You could use <code>numpy.select</code> with conditions on <code>&lt;10</code>, <code>10≤score&lt;20</code>, etc. but a more efficient version could be to use a floor division to have values below 10 become 0, below 20 -&gt; 1, etc.</p> <pre><code>df['value'] = df['value'].fillna(df['score'].floordiv(10)) </code></p...
pandas
3
376,387
73,264,482
what is the difference between Sequential and Model([input],[output]) in TensorFlow?
<p>It seems <code>Sequential</code> and <code>Model([input],[output])</code> have the same results when I just build a model layer by layer. However, when I use the following two models with the same input, they give me different results.By the way,the input shape is <code>(None, 15, 2)</code> ande the output shape is...
<p>The <code>Sequence</code> version uses the <a href="https://keras.io/guides/sequential_model/" rel="nofollow noreferrer">Sequencial model</a> while the <code>Model([inputs], [outputs])</code> uses the <a href="https://keras.io/guides/functional_api/" rel="nofollow noreferrer">Functional API</a>.</p> <p>The first is ...
python|tensorflow|keras|deep-learning|lstm
1
376,388
73,328,284
filtering "events" in awkward-array
<p>I am reading data from a file of &quot;events&quot;. For each event, there is some number of &quot;tracks&quot;. For each track there are a series of &quot;variables&quot;. A stripped down version of the code (using awkward0 as awkward) looks like</p> <pre><code>f = h5py.File('dataAA/pv_HLT1CPU_MinBiasMagDown_14No...
<p>It looks to me, from the fact that you're able to call <code>np.asarray</code> on these arrays without error, that they are one-dimensional arrays of numbers. If so, then Awkward Array isn't doing anything for you here; you should be able to find the one-dimensional NumPy arrays inside</p> <pre class="lang-py pretty...
numpy|hdf5|awkward-array
0
376,389
73,308,149
Meaning of output shapes of ResNet9 model layers
<p>I have a ResNet9 model, implemented in Pytorch which I am using for multi-class image classification. My total number of classes is 6. Using the following code, from torchsummary library, I am able to show the summary of the model, seen in the attached image:</p> <p><code>INPUT_SHAPE = (3, 256, 256) #input shape of ...
<p>Yes<br /> your <code>INPUT_SHAPE</code> is <code>torch.Size([3, 256, 256])</code> if it's channel first format AND <code>(256, 256, 3)</code> if it's channel last format.<br /> As Pytorch model accepts it in channel first format , for you it shows torch.Size([3, 256, 256])</p> <p>and talking about our <code>output ...
python|pytorch|resnet|modelsummary
1
376,390
73,366,608
How can I import resnet_rs module from keras?
<p>I was trying to import resnet_rs module from keras. But counldn't find a way to do it via keras.applications. Using tensorflow 2.8</p> <p>I tried the following:</p> <pre><code>from tensorflow.keras.applications.resnet_rs import ResNetRS50 </code></pre> <p>Got no module error.</p> <p>Then I tried to use it via api, a...
<p>What version of Tensorflow are you on? I was on Tensorflow 2.8.2 and it wasn't working for me either. I switched to 2.9.1, and it fixed the import. I think those modules were added only recently. That's why previous versions won't work.</p> <p>To upgrade to the latest version:</p> <pre><code>pip install tensorflow -...
python|tensorflow|keras
1
376,391
73,209,775
Time Series data to fit for ConvLSTM
<p>I used stock data with 4057 samples, made it into 28 time steps, with 25 features.</p> <pre><code>TrainX shape: (4057, 28, 25) </code></pre> <p>The Target consists of 5 categories of interger</p> <pre><code>[0,1,2,3,4] </code></pre> <p>and reshape into:</p> <pre><code>trainX_reshape= trainX.reshape(4057,1, 28,25,1) ...
<p>Your model's output does not make any sense, if you are working with sparse integer labels. It is 5D and your labels are 2D (including batch size). Try:</p> <pre><code>seq =Sequential([ ConvLSTM2D(filters=40, kernel_size=(3, 3),input_shape=(1, 28, 25, 1),padding='same', return_sequences=True), BatchNormaliza...
python|tensorflow|keras
2
376,392
73,494,634
Converting dataframe column from Pandas Timestamp to datetime (or datetime.date)
<p><em>The bjillion python time formats cause more lost time than anything I do.</em></p> <p>Reading a file or a sql query into a dataframe gives me a column of Pandas Timestamp (i.e. type = pandas._libs.tslibs.timestamps.Timestamp). Not the 'normal' timestamps. Answers I find do not address the combination of both thi...
<p>My assumption without a sample df is you can use:</p> <pre><code>df['date'] = df['pdTimeStamp'].apply(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d')) </code></pre>
python|pandas|dataframe|datetime|timestamp
0
376,393
73,328,310
Concatenate values in a dataframe with value in preceding column on same row - Python
<p>I am trying to concatenate the values in a cell with values in its preceding cell on the same row i.e. one column before it throughout my dataframe. For sure, the first column values wont have anything to concatenate with. Also, my df has NaN values - which I have changed to None.</p> <p><a href="https://i.stack.img...
<p>Try with <code>add</code> then <code>cumsum</code></p> <pre><code>out = df.add('_').apply(lambda x : x[x.notna()].cumsum().str[:-1],axis=1) Out[871]: 1 2 3 4 5 0 a a_b a_b_c a_b_c_d a_b_c_d_e 1 a a_e a_e_f NaN NaN </code></pre>
python|pandas|dataframe|concatenation
2
376,394
73,444,928
Combining CSVs with Python issue
<p>I'm trying to combine a bunch of CSVs in a folder into one using Python. Each CSV has 9 columns but no headers. When they combine, some 'sheets' are spread far to the right in the sheet. So it seems they are not combining properly.</p> <p>Please see code below</p> <pre><code>## Merge Multiple 1M Rows CSV files impor...
<p>First, please check if separator and delimiter are fine in pandas.read_csv, default are ',' and None. You can pass them like that for example:</p> <pre><code>pandas.read_csv(&quot;my_file_path&quot;, sep=';', delimiter=',') </code></pre> <p>If they are already ok regarding to your csv files, try cleaning the datafra...
python|pandas|csv
0
376,395
73,505,129
Concatenate strings in dataframe rows (Python - pandas)
<p>Let's say I have the following dataframe d1:</p> <pre><code>d1 = pd.DataFrame(data = {'col1': [&quot;A&quot;, &quot;C&quot;], 'col2': [&quot;B&quot;, &quot;D&quot;]}) </code></pre> <p><a href="https://i.stack.imgur.com/wKYbQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wKYbQ.png" alt="enter ima...
<p>You can also use <code>agg</code> to operate <code>join</code>. However, it will return a <code>pd.Series</code>, so convert it to a dataframe with <code>pd.Series.to_frame</code>:</p> <pre><code>d2 = d1.agg(' '.join).to_frame().T </code></pre>
python|pandas
3
376,396
73,246,897
IndexError: single positional indexer is out-of-bounds (iloc[1: , :])
<p>This will be tricky, but I need your help. To sum up, my coworker in charge of data left, and there is an unsolved bug in his Python requests. I have close to 0 knowledge of this language, and I didn't write these Python requests, so I can't figure out the issue. Here is the code:</p> <pre class="lang-py prettyprint...
<p>Problem is in your <code>churn_calculation</code> method</p> <pre class="lang-py prettyprint-override"><code>----&gt; 6 df.loc[:,'Cumulative_Churn_perc']=round((df.loc[:,'Cumulative Churn']/df.iloc[0,3])*100,2) </code></pre> <p>Here you use <code>df.iloc[0,3]</code>, <code>iloc</code> indexing starts from 0, the p...
python|pandas|indexoutofboundsexception
0
376,397
73,337,400
Why the error information "unrecognized arguments" return?
<p>When I tried to use ArgumentParser() class to define the argument &quot;epochs&quot; as the training epoch of my CNN model with PyTorch, the system informed me this error. This is my code block:</p> <pre><code># 2.1 define super arguments (training epochs for example) import argparse parser = argparse.ArgumentParse...
<p>From your error message, I guess you are running the code in the jupyter notebook environment. In jupyter notebook, if you want to use argparse, please modify the code to the following form: args = vars(parser.parse_args(args=[]))</p>
python|pytorch|arguments
0
376,398
73,425,535
I'm using this Spleeter library for vocal seperation but it is not working
<p>I'm using this Spleeter library for vocal seperation <a href="https://github.com/FaceOnLive/Spleeter-Android-iOS" rel="nofollow noreferrer">Spleeter-Android-iOS</a></p> <p>But it gives me 1 instead of 0 when I call the func spleeterSDK.process(wavPath!, outPath: path). I don't know what is the problem.</p> <p>Any he...
<p>Generally, if a function works, it has requirements on its inputs. We would need to see your inputs to have any chance to know why it doesn't work</p> <pre><code>spleeterSDK.process(wavPath!, outPath: path) </code></pre> <ol> <li>What is wavPath?</li> <li>Is there actually a file there on your device in a place you...
python|ios|swift|tensorflow|spleeter
1
376,399
73,280,226
pandas remove equal rows by comparing columns in two dataframes
<pre><code>df1 = [['tom', 10, 1.2], ['nick', 15, 1.3], ['juli', 14, 1.4]] </code></pre> <p><a href="https://i.stack.imgur.com/8SGSR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8SGSR.png" alt="enter image description here" /></a></p> <pre><code>df1 = [['tom', 10, 1.2], ['nick', 15, 1.3], ['juli', ...
<p>Assuming you want everything from df1 that does not matches df2</p> <pre><code>n_columns = len(df1.columns) df1[(df1 == df2).apply(sum, axis=1).apply(lambda x: x != n_columns)] </code></pre>
python|pandas|dataframe
0