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
366,100
68,281,595
Nested Json file to csv using Python
<p>I am new to python and need help in converting a nested json file to csv. File name: users.json file path: C:/_apps/test</p> <hr /> <p>File Content:</p> <pre><code>{ &quot;count&quot;: 3, &quot;next&quot;: null, &quot;previous&quot;: null, &quot;results&quot;: [ { ...
<p>As the 'user' field is not a valid python dict, we have to parse it manually and extract all values:</p> <pre><code>import pandas as pd import argparse def extract_results(jsonfile): # Extract 'results' field res = pd.read_json('data.json')['results'].apply(pd.Series) # Process 'user' column user =...
python|json|pandas|csv
0
366,101
68,348,298
Counting values by month with python pandas
<p>I'm trying to count the number of values per month in the sample.purpose.label column in this water quality dataset (All of England, 2019, both compliance and monitoring) <a href="https://environment.data.gov.uk/water-quality/view/download/new" rel="nofollow noreferrer">https://environment.data.gov.uk/water-quality/...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer">pandas.Grouper</a> to group by month, <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer">value_counts</a> to count all occurrenc...
python|pandas|dataframe
0
366,102
68,074,028
How to tell Bazel to include numpy as a dependency and have Vscode autocomplete work with it?
<p>The Bazel documentation for Python has not been helpful. I am using Vscode. Lets say that I have the following Python file:</p> <pre><code>package(default_visibility = [&quot;//visibility:public&quot;]) py_binary( name = &quot;LogTest&quot;, srcs = [ &quot;LogTest.py&quot; ], # deps = [ # &quot...
<p>External dependencies are not supported in built-in python rules, but you can a <a href="https://github.com/bazelbuild/rules_python/tree/master/examples/pip_install" rel="nofollow noreferrer">bazelbuild/rules_python</a> to achieve that.</p> <p>About autocompletion: I guess it is not possible, you need to treat you b...
python|numpy|visual-studio-code|bazel
0
366,103
68,109,323
How to import datetools in python?
<p>I am using Jupyter Notebook with python 3.8.</p> <p>I get an error:</p> <pre><code>ImportError: cannot import name 'datetools' from 'pandas' </code></pre> <p>from the code below:</p> <pre><code>import pandas as pd from pandas import datetools </code></pre> <p>I confirm that pandas is installed but I saw that dateto...
<p>Pandas datetools may have been removed from the version you are using now in your system. Try downgrading the pandas if you insist on using datetools, or for better solution, use <code>datetime</code> package that will help you achieve results.</p>
python|pandas|jupyter
0
366,104
68,242,087
How to count unique counts of each string from the pandas list?
<p>I have a data frame that looks as in the below format (2 columns of pandas data frame). Column name has the ID and the column menu has the string inside the list.</p> <pre><code>name | menu A | [cheese, cake, sausage] B | [chicken, cake, water] C | [chicken, sausage, water] D | [water, cheese, sausage] ...
<p>Assuming the column <code>menu</code> contains lists, you can run (as suggested in the comments):</p> <pre><code>df.explode('menu')['menu'].value_counts() </code></pre> <p>Or to wrap it in a new df:</p> <pre><code>pd.DataFrame(df.explode('menu')['menu'].value_counts()).reset_index().rename(columns={'index': 'word', ...
python|pandas
1
366,105
68,255,561
add new column with the summary of all previous values (python)
<p>I am very new to python and trying to complete an appointment for uni. I've already tried googling the issue (and there may already be a solution) but could not find a solution to my problem.</p> <p>I have a dataframe with values and a timestamp. It looks like this:</p> <div class="s-table-container"> <table class="...
<p>Try <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>cumsum()</code></a>:</p> <pre class="lang-py prettyprint-override"><code>df['sum'] = df['delta'].cumsum() </code></pre>
python|pandas|sum
2
366,106
68,403,103
Python: Exp of complex number is not working
<p>I am really new to Python and usually code with MATLAB, so I tried to creat this small code that has exp(complex number) in a for loop. (I need the for loop since I have multidimensional matrix along the code). <br> Every time I add the term (1j*) the code wont work and it show the following error</p> <pre><code> ...
<p>By default, <code>np.zeros</code> creates an array of type <code>np.float64</code>. If you try to assign a complex value to an element of such an array, you'll get the error <code>TypeError: can't convert complex to float</code>.</p> <p>Your code works if you make <code>Zx</code> an array of complex numbers:</p> <p...
python|numpy
3
366,107
68,135,242
Python Dataframe Logical Operations on Multiple Columns using Multiple If statements
<p>I have a big data frame with float values. I want to perform two if logical operations.</p> <p>My code:</p> <pre><code>df = A B 0 78.2 98.2 1 54.0 58.0 2 45.0 49.0 3 20.0 10.0 # I want to compare each column data with predefined limits and assign a rank. # For A col, Give rank 1 if &gt; 70, 2 if ...
<p>It doesn't look like you need to use <code>pd.cut</code> for this. You can simply use <code>np.select</code>:</p> <pre><code>df[&quot;A_op&quot;] = np.select([df[&quot;A&quot;]&gt;70, df[&quot;A&quot;]&lt;40],[1,3], 2) df[&quot;B_op&quot;] = np.select([df[&quot;B&quot;]&gt;80, df[&quot;B&quot;]&lt;45],[1,3], 2) pri...
python|pandas|dataframe|numpy
1
366,108
68,146,776
Plot groupby percentage dataframe
<p>I didn't find a complete answer to what i want to do:</p> <p>I have a dataframe. I want to group by user and their answers to a survey, sum all of their good answers/total of their answers, display it in % and plot the result.</p> <p>I have an answer column which contains : 1,0 or -1. I want to filter it in order t...
<p>Here is a sample solution assuming you want to calculate percentage based on filtered dataframe.</p> <pre><code>import pandas as pd import numpy as np df_sample = pd.DataFrame(np.random.randint(-1,2,size=(10, 1)), columns=['answer']) df_sample['user'] = [i for i in 'a b c d e f a b c d'.split(' ')] df_filtered = ...
python|pandas|dataframe|matplotlib
0
366,109
68,126,473
Concatenating ResNet-50 predictions PyTorch
<p>I am using a pre-trained ResNet-50 model where the last dense is removed and the output from the average pooling layer is flattened. This is done for feature extraction purposes. The images are read from folder after being resized to (300, 300); it's RGB images.</p> <p>torch version: 1.8.1 &amp; torchvision version:...
<p>If you want to stack the results in a Tensor:</p> <pre><code>results = torch.empty((0,2048)) results.to(device) results = torch.cat((results, predictions), 0) </code></pre>
numpy|pytorch|conv-neural-network|python-3.8|resnet
1
366,110
68,439,889
Iterate over 4d and 3d array and return the values in the shape of 4d again
<p>I have a <code>4D</code> array of shape <code>(10, 100, 32, 64)</code> called <code>first_channel</code>. Then, I go over each one of 10 elements in the first dimension, and take the resulting 3D array of shape <code>(100, 32, 64)</code>. I go over each one of the 100 elements of the first dimension, do min-max scal...
<p>You can compute all the quantities directly, without reshaping anything:</p> <pre><code>mn = first_channel.min(axis=(2, 3), keepdims=True) mx = first_channel.max(axis=(2, 3), keepdims=True) first_channel -= mn first_channel /= mx - mn </code></pre> <p>This does the operation in-place, which is probably what you want...
python|arrays|numpy|normalization
2
366,111
68,221,932
How to train transfer-learning model on custom dataset? ValueError: Shape must be rank 4
<p>I am trying to build a transfer learning model to classify images. The images are a gray-scale (2D). previously I used <code>image_dataset_from_directory</code> method to read the images and there was no problem. However, I am trying to use a custom read function to have more control and access on the data such as k...
<p>The problem in the code is that OpenCV reads the image in grayscale format, but the grayscale format of the image returned is not <code>(160,160,1)</code> but <code>(160,160)</code>.</p> <p>Because of this fact, the error is thrown.</p> <p>I managed to replicate your problem by testing it locally.</p> <p>Say we rand...
python|tensorflow|keras|deep-learning
1
366,112
68,220,613
Where can I get official PyTorch documentation in pdf form?
<p>I want to learn <a href="https://pytorch.org" rel="nofollow noreferrer">PyTorch</a> in great detail.</p> <p>I saw all the docs, tutorials in the main site of PyTorch. But, I want to take printout and read. When I take printout from website pages, I am getting very small letters, which are difficult for me to read th...
<p>I don't think there is an official pdf. The pytorch documentation uses <a href="https://www.sphinx-doc.org/en/master/" rel="nofollow noreferrer">sphinx</a> to generate the web version of the documentation. But sphinx can also generate PDFs.</p> <p>So you could download the <a href="https://github.com/pytorch/pytorch...
printing|pytorch|resources
1
366,113
68,271,217
Installing numpy 1.21.0 on EC2 instance
<p>I am trying to install numpy 1.21.0 (which is a dependency for a project I am working on) on an EC2 instance. Using pip, I can only install up to version 1.19.5, which is the highest version provided in that environment.</p> <p>I have also tried the following:</p> <ul> <li>install directly from wheel -&gt; none of t...
<p>Here is how I installed the Numpy 1.21.0 package on the Amazon Linux 2 AMI (HVM):</p> <pre><code>[ec2-user@ip-172-31-25-7 ~]$ pip3 install numpy==1.21.0 Defaulting to user installation because normal site-packages is not writeable Collecting numpy==1.21.0 Downloading numpy-1.21.0-cp37-cp37m-manylinux_2_12_x86_64.m...
python-3.x|amazon-web-services|numpy|amazon-ec2|installation
0
366,114
68,054,551
Using Values from Results of Groupyby in Pandas for naming columns in new data-frame
<p>I have a question: I have a data-frame with columns ('A', 'B', 'C', 'D') which I have grouped by two columns ('A', 'B') and then I used count function. <code> temp_df = df.groupby(['A', 'B']).count()</code></p> <p>the result is like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th st...
<p>You can <code>unstack</code> the <code>B</code> level while filling the missings of either <code>y_1</code> or <code>y_2</code> with 0. Then we select the <code>C</code> column's values as <code>D</code> can be omitted as mentioned in the comments:</p> <pre><code>&gt;&gt;&gt; df.unstack(&quot;B&quot;, fill_value=0)....
python|pandas|dataframe
0
366,115
68,160,208
How to preprocess with categorical data and dataframes
<p>I am preprocessing data for my multiple linear regression model by having a list of genres which I onehotencode</p> <pre><code>genres = [ &quot;Action&quot;, &quot;Adventure&quot;, &quot;Biography&quot;, &quot;Comedy&quot;, &quot;Crime&quot;, &quot;Erotica&quot;, &quot;Fantasy&quot;, ...
<p>Could it be something as simple as:</p> <pre><code>X_new = pd.DataFrame(0, index=np.arange(len(x_user)), columns=genres) X_new['Action'] = x_user.Action X_new['Thriller'] = x_user.Thriller </code></pre> <p>assuming x_user is a pandas dataframe. If it is instead a numpy array or something similar just assign it based...
python|pandas|scikit-learn
0
366,116
68,395,370
How to get a given number of unique combinations of layers variations, while maintaining a given proportion of each layer variant using Python?
<p>I need to write a script in Python to solve this task, but I can't figure out how to do it.</p> <p>I have items (let's name them layers): A, B, C...</p> <p>Each layer can have any number of variations.</p> <p>For each variation, the proportion percent is given that we want to get at the output.</p> <p>At the output,...
<p>For every layer, you can find the distribution list and then recursively merge the results to produce the combinations. Due to the very high number of combinations that could result from <code>get_combos</code>, the latter is a generator, and you can use <code>next</code> to produce the values on-demand:</p> <pre><c...
python|numpy|combinations|combinatorics|cartesian-product
0
366,117
68,186,088
No axis named URL for object type DataFrame
<p>I think my code is almost complete but I keep getting this error &quot;No axis named URL for object type Dataframe&quot; There's a column named URL and I know it works since the table output includes a URL column. Here's two samples of my code</p> <pre><code>rows_processed=[] for item in items.findAll(&quot;div...
<p>You just need to look up the &quot;URL&quot; value differently, see below:</p> <pre><code>rows_processed = [ ['shoes', 'Available', 270.00, 'www.abc.com'], ['jacket', 'Available', 260.00, 'www.bbb.com'] ] df = pd.DataFrame(rows_processed, columns=[&quot;Item Title &quot;, &quot;Status&quot;, &quot;Price&quo...
python|pandas|dataframe
0
366,118
68,064,645
Attribute AttributeError: module 'tensorflow.compat.v2' has no attribute '_internal_'
<p>Following the CARLA tutorials, I created a file to train my model; however, whenever I try to run it using Command prompt, this error shows up:</p> <pre><code>2021-06-20 19:39:30.429984: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart...
<p>From comments</p> <blockquote> <p>Try to revert to an older version of <code>tf</code>, that might help (paraphrased from StarShine)</p> </blockquote> <p>Actually the above issue was due to incompatibility between latest <code>Tensorflow</code> version and standalone <code>Keras</code>. For more information you can ...
python|tensorflow|keras|carla
1
366,119
68,248,733
Convert Twitter engine search to pandas dataframe
<p>I made a loop to capture unique tweets using the following code below.</p> <pre><code>engine = Twitter(language='en') idindex = set() tweets = [] prev = None #create loop to capture 200 unique tweets for 'Winter snow storm' for i in range(5): print(i) for tweet in engine.search('Winter snow storm', start=p...
<p>This should do that job:</p> <pre><code>import pandas as pd engine = Twitter(language='en') idindex = set() tweets = [] df= pd.DataFrame() prev = None #create loop to capture 200 unique tweets for 'Winter snow storm' for i in range(5): print(i) for tweet in engine.search('Winter snow storm', start=prev, c...
python|pandas
0
366,120
68,418,361
How to explode a dict column into a new dataframe
<p>I have the following sample dataframe:</p> <pre><code>df = pd.DataFrame( [[20, 30, [{&quot;ab&quot;:&quot;1&quot;, &quot;we&quot;:&quot;2&quot;, &quot;as&quot;:&quot;3&quot;}, {&quot;ab&quot;:&quot;4&quot;, &quot;we&quot;:&quot;5&quot;, &quot;as&quot;:&quot;6&quot;}],&quot;String&quot;]], columns=['A', '...
<p>Use <code>apply</code> with <code>pd.Series</code></p> <pre><code>df.C.apply(pd.Series) </code></pre> <p>Output</p> <pre><code> ab we as 0 1 2 3 </code></pre> <p>If the column type is <code>object</code>, use this</p> <pre><code>df.C.apply(lambda x: pd.Series(literal_eval(x))) </code></pre> <p>If you have invali...
pandas|dataframe
2
366,121
68,355,457
How to join column to table?
<pre><code>import numpy as np #Collect the compound values for each news source score_table = df.pivot_table(index='User', values=&quot;Compound&quot;, aggfunc = np.mean) score_table from collections import Counter import pandas as pd a = dict(Counter(HT_positive)) t = list(a.items()) compound = score_table[&quot...
<p>I think that you could check if &quot;Compound&quot; or &quot;User&quot; should be the key that you use to query the value from the dictionary.</p>
python|pandas|dataframe
0
366,122
68,215,005
Comparing two spreadsheets, removing the duplicates and exporting the result to a csv in python
<p>I'm trying to compare two excel spreadsheets, remove the names that appear in both spreadsheets from the first spreadsheet and then export it to a csv file using python. I am new, but here's what I have so far:</p> <pre><code>import pandas as pd data_1 = pd.read_excel (r'names1.xlsx') bit_data = pd.DataFrame(data_1,...
<p>Use pandas merge to get all unique names, with no duplicates. If you want to drop any names that are in both files (I'm not sure if that's what you're asking), you can do so. See this toy example:</p> <pre><code>row1list = ['G. Anderson'] row2list = ['Z. Ebra'] df1 = pd.DataFrame([row1list, row2list], columns=['Fu...
python|excel|pandas|dataframe
0
366,123
68,240,463
pandas: row-wise operation to get change over time
<p>I have a large data frame. Sample below</p> <pre><code>| year | sentences | company | |------|-------------------|---------| | 2020 | [list of strings] | A | | 2019 | [list of strings] | A | | 2018 | [list of strings] | A | | ... | .... | ... | | 2020 | [list of strings] |...
<p>TL;DR: see full code on bottom</p> <p>You have to break down your task in simpler subtasks. Basically, you want to apply one or several calculations on your dataframe on successive rows, this grouped by company. This means you will have to use <code>groupby</code> and <code>apply</code>.</p> <p>Let's start with gene...
pandas|bert-language-model|sentence-similarity
0
366,124
68,353,675
How to apply function to all rows in data frame?
<p>I am confused about how to apply a function to a data frame. Generally with creating user-defined-functions, I am familiar with ultimately having a &quot;return&quot; value to produce. Except for this case, I need the &quot;return&quot; value to show up in every cell of a data frame column, and I can't figure this o...
<p>No need to use apply, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer">pd.Series.where</a> instead:</p> <pre><code>df['Production_loss'] = df['Production_potential'].where(df['No_employee?'].eq(1), df['Production_potential'] * df['No_machiner...
python|pandas
1
366,125
68,189,339
How do I load a dataframe in Python sklearn?
<p>I did some computations in an IPython Notebook and ended up with a dataframe <code>df</code> which isn't saved anywhere yet. In the same IPython Notebook, I want to work with this dataframe using sklearn.</p> <p>df is a dataframe with 4 columns: id (string), value(int), rated(bool), score(float). I am trying to dete...
<p>Ok, so some clarifications first: in your example, it is unclear what the load_boston() function does. they just import it. whatever that function returns has an attribute called &quot;data&quot;.</p> <p>They use this line:</p> <pre><code>X = pd.DataFrame(boston.data, columns=boston.feature_names) </code></pre> <p>t...
python|pandas|dataframe|scikit-learn
2
366,126
68,268,086
How to know if a record has been modified or included new in a pandas dataframe
<p>I have a dataframe in which new rows can be included, but I have to know if that new row that enters on the dataframe is a modification of some existing record, or if on the contrary, it is a new record.</p> <p>For example, Input dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th...
<p>So if you sort by timestamp, and use <code>groupby</code> on your columns that define unique rows, you can get all the information you want. Using <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.core.groupby.GroupBy.last.html" rel="nofollow noreferrer"><code>last</code></a> to get t...
python|pandas|dataframe|date|datetime
1
366,127
68,363,979
Matplotlib -3D data visualization
<p><a href="http://www.filedropper.com/d401" rel="nofollow noreferrer">here is example of one txt file</a></p> <p>My experiment measurements are in several txt files (in reality I will have hundreds of files, but to demonstrate the idea of plotting, here I only list out 3 files, they are d_401.txt, d_402.txt, d_403.txt...
<p>The following in the hypotesis that all the files contain the same vector of <em>x</em> …</p> <pre><code>In [146]: import numpy as np ...: import matplotlib.pyplot as plt ...: from matplotlib.cm import ScalarMappable as sm ...: from glob import glob ...: ...: # create fake data and put it i...
python|numpy|matplotlib|plot
0
366,128
68,118,853
Building a Numpy array by appending data (without knowing the full size in advance)
<p>I have many files, and each file is read as a matrix of shape <code>(n, 1000)</code>, where n may be different from file to file.</p> <p>I'd like to concatenate all of them into a single big Numpy array. I currently do this:</p> <pre><code>dataset = np.zeros((100, 1000)) for f in glob.glob('*.png'): x = read_as_...
<p>Use a native <code>list</code> of numpy arrays, then <a href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>np.concatenate</code></a>.</p> <p>The native <code>list</code> will multiply (<a href="https://stackoverflow.com/questions/52195579/what-is-the-resizi...
python|numpy|memory|memory-management|numpy-ndarray
5
366,129
68,352,240
How to smoothly impute values in a Pandas DataFrame?
<p>I am doing a data science project using <strong>Streamlit</strong>, <strong>Pandas</strong> and the <a href="https://www.quandl.com/data/NASDAQOMX/NOMXNEN-NASDAQ-OMX-Nordic-Energy-NOMXNEN" rel="nofollow noreferrer"><strong>Quandl Nasdaq Nordic Dataset</strong></a>.</p> <br/> <p>When I use the Python Quandl module t...
<p>Thanks to <strong>ifly6</strong>, I have found the solution.</p> <p>Simply set your dataset to the interpolated version as below:</p> <pre><code>data = df.interpolate() </code></pre> <h3 id="simple-a574">Simple!</h3>
python|pandas|dataframe|scikit-learn|quandl
0
366,130
68,213,291
How to find the highest value according to specified certain conditions in for loop?
<p>I managed to put the arrays in for loop and, depending on the condition, select the values I need. From these selected values I try to choose the highest value from the matrix a and b. Unfortunately, somehow I miss some syntax.</p> <p>my code</p> <pre><code>a=np.array([0, 0, 0, 1, 1, 1, 2, 4,2, 2]) b=np.array([0, 1,...
<p>We can use <code>numpy</code>'s masking, then <code>.max()</code>.</p> <p>This is a no-for-loops solution, also called <a href="https://stackoverflow.com/questions/47755442/what-is-vectorization">vectorization</a>.</p> <pre><code>import numpy as np a = np.array([0, 0, 0, 1, 1, 1, 2, 4, 2, 2]) b = np.array([0, 1, 2,...
python|numpy|for-loop
1
366,131
573,487
Any way to create a NumPy matrix with C API?
<p>I read the documentation on NumPy C API I could find, but still wasn't able to find out whether there is a possibility to construct a matrix object with C API — not a two-dimensional array. The function is intended for work with math matrices, and I don't want strange results if the user calls matrix multiplication ...
<p>You can call any python callable with the <code>PyObject_Call*</code> functions.</p> <pre><code>PyObject *numpy = PyImport_ImportModule("numpy"); PyObject *numpy_matrix = PyObject_GetAttrString(numpy, "matrix"); PyObject *my_matrix = PyObject_CallFunction(numpy_matrix, "(s)", "0 0; 0 0"); </code></pre> <p>This wil...
python|numpy|python-c-api
6
366,132
59,413,487
How to Successfully Produce Mosaic Plots in Pyviz Panel Apps?
<p>I have created the following dataframe <code>df</code>:</p> <p><strong>Setup:</strong></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import random import copy import feather import matplotlib.pyplot as plt from statsmodels.graphics.mosaicplot import mosaic import plotly...
<p>Statsmodels function <a href="https://www.statsmodels.org/stable/generated/statsmodels.graphics.mosaicplot.mosaic.html" rel="nofollow noreferrer">mosaic()</a> returns a tuple with a figure and rects. <br></p> <p>What you're seeing now via interact is that tuple. This tuple also gets updated in your code when you u...
python-3.x|pandas|pyviz|mosaic-plot|panel-pyviz
1
366,133
59,080,026
How convert multi value row to columns using pandas?
<p>What functions do I use to convert this Dataframe:</p> <pre><code>id name genre 1 Fiml1 action, comedy 2 Fiml2 animation 3 Fiml3 comedy 4 Fiml4 action, animation 5 Fiml5 action 6 Fiml6 animation, comedy </code></pre> <p>To:</p> <pre><code>id name action animation comedy 1 Fiml1 1 0 1 2 Fiml2 0...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>Series.str.dummies</cod...
python|python-3.x|pandas|dataframe|data-science
3
366,134
59,262,242
python pandas dataframe rename a colume to a multiindex column
<p>I have the following <code>dataframe</code></p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.random((4,4))) df Out[5]: 0 1 2 3 0 0.136122 0.948477 0.173869 0.929373 1 0.194699 0.759875 0.723993 0.497966 2 0.323100 0.443267 0.210721 0.6...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.map.html" rel="nofollow noreferrer"><code>Index.map</code></a>, if use pandas 0.23+ is possible omit <code>.get</code>:</p> <pre><code>df.columns = df.columns.map(mapping.get) print (df) 1 2 ...
python|pandas|dataframe
2
366,135
59,365,891
Installing pandas for QPython app on android
<p>I am using the QPython app on my android device to run scripts. I have a script that requires the pandas package but can't seem to download it onto my phone. The app has a section for downloading extra packages under the secion "QPYPI" and then the "AIPY" section. It has numpy and others listed as well as pandas. It...
<p>Can you tell us what phone, android version, QPython version, where did you install it in advance please ?</p>
pandas|qpython
0
366,136
59,121,193
How can I automate my code using openpyxl and Pandas?
<p>I have a couple of issues automating my data regarding openpyxl and pandas which is related to the length of the Dataframe DF.</p> <p>The first one is regarding cells. I want to automate each row in which if it only prints the border in the number of rows equal to the length of the dataframe starting from row 3</p>...
<p>For the second question, you can simply do, IIUC:</p> <pre><code>df['Note'] = None </code></pre>
python|pandas|openpyxl
1
366,137
59,419,648
loop through the batch image loader pytorch
<p>Let say I have batch with </p> <blockquote> <p>imgs = torch.Size([128, 1, 28, 28])</p> </blockquote> <p>if I want to loop through the each image <br/></p> <pre><code>for img in imgs: print(img.shpae) -&gt; torch.Size([1, 28, 28]) </code></pre> <p>if I want to get a torch.Size([1,1, 28, 28]) for each image...
<p>You can resize the tensor initially to a shape of <code>[128, 1, 1, 28, 28]</code></p> <pre class="lang-py prettyprint-override"><code># tensor.resize_((`new_shape`)) imgs.resize_((128, 1, 1, 28, 28)) </code></pre> <p>No when you loop through each image, will be of the desired shape [1, 1, 28, 28].</p> <p>Sec...
numpy|pytorch
1
366,138
59,097,802
Numpy Backprop Cost is Not Decreasing
<p>I'm working on a python script that allows the user to define the number of hidden layers and their number of nodes in fully connected neural network. </p> <p>The problem is, the error is coming up as nan when I try larger datasets. I'm not sure why this is the case but I'm also getting this python error when runni...
<p>I think it is a regression model, and it looks like using <code>tanh</code> activation for all layers. Since <code>tanh</code>'s output range is [-1, +1], you should use relu-like activation for the last layer, because range of the target of sklearn's boston dataset is [0, 50].</p>
python|numpy|machine-learning|backpropagation
1
366,139
59,146,494
Spliting DataFrame into Multiple Frames by Dates Python
<p>I fully understand there are a few versions of this questions out there, but none seem to get at the core of my problem. I have a pandas Dataframe with roughly 72,000 rows from 2015 to now. I am using a calculation that finds the most impactful words for a given set of text (tf_idf). This calculation does not accou...
<p>Let us assume you have a data frame like this:</p> <pre><code>date = pd.date_range(start='1/1/2018', end='31/12/2018', normalize=True) x = np.random.randint(0, 1000, size=365) df = pd.DataFrame(x, columns = ["X"]) df['Date'] = date df.head() </code></pre> <p><strong>Output</strong>:</p> <pre><code> X Date 0...
python|pandas|dataframe
1
366,140
59,069,232
How to convert a list to a Dataframe in Pandas?
<p>I scraped a table from Wikipedia, using Pandas and BeautifulSoup, I obtained a list. I want to convert it into a Dataframe, but when I use the pd.DataFrame() function, the result is not as expected. Please help.</p> <pre><code>import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup res ...
<p>You already have a pandas DataFrame encapsulated in a list. You just have to take the first element:</p> <pre class="lang-py prettyprint-override"><code>neigh = df[0] print(neigh) </code></pre> <pre><code> Postcode Borough Neighbourhood 0 M1A Not assigned Not assigned 1 ...
python|pandas|dataframe|beautifulsoup
2
366,141
59,244,462
How to using pandas to cell merge
<p>I want to combine the cells as follows.</p> <p>Before:</p> <pre><code>| | test1 | test2 | test3 | | -:|:----- |:----- | -----:| | 0 | value | value | value | | 1 | test4 | test5 | | 2 | value | value | | 3 | test6 | test7 | test8 | | 4 | value | value | value | | 5 | test9 | test0 | | 6 | value | value | </code>...
<p>Here is something you can do. </p> <pre><code>import pandas as pd df = pd.DataFrame({'test1 ':['15','test4','79', 'test6', '34', 'test9', '323'], 'test2 ':['78','test5','45', 'test7', '4', 'test10', '34'], 'test3 ':['8','','', 'test8', '56', '', '']}) print("Original Dataframe...
python|excel|pandas
2
366,142
59,072,302
Efficient way to threshold image array and render - Python / NumPy / OpenCV
<p>I have a camera that is sending the image data to my computer. From there my python script puts the 8bit color info (black and white; ranging from 0 - black - to 255 - white) into a numpy array. The array is 2D, first dimension up to 384 and second dimensions up to 288 Displaying this with a openCV window works grea...
<p>Try this:</p> <pre class="lang-py prettyprint-override"><code>frame[frame &gt; 200] = 255 frame[frame &lt;= 200] = 0 cv2.imshow("LiveVideo", frame) </code></pre>
python|arrays|performance|loops|numpy
4
366,143
59,062,718
Save JSON details into Excel file using Python
<p>I am reading below json file and trying to store it in <code>.xlsx</code> format using pandas library of python.</p> <p>JSON:</p> <pre><code>{ "log": [ { "code": "info", "message": {"text": "[info] Activation of plug-in abcd rule processor (xule) successful, version Check version using Tools-&gt;Xule-&gt;V...
<pre><code>data1 = [] for i in range(len(data['log'])): code = data['log'][i]['code'] message = data['log'][i]['message'] refs = data['log'][i]['refs'] level = data['log'][i]['level'] data1.append((i,code, message, refs, level)) df = pd.DataFrame(data1, columns = ['log','code','message','refs','lev...
python|pandas
1
366,144
59,386,739
pandas, How to add rows with average grouped columns
<p>I have a dataframe like below.<br> I want to add 1 row for each fruit, where </p> <ul> <li>the <code>price</code> for the new row should be set to the average price of the pre-existing rows for that fruit. </li> <li>the <code>resource</code> for the new row will always be <code>all</code>. </li> <li>the <code>ftyp...
<p>You can aggregate <code>mean</code> and add new columns with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a>:</p> <pre><code>df1 = df.groupby('fruit', as_index=False)['price'].mean().assign(resource='all',ft...
python|pandas
4
366,145
59,223,095
Pandas explode index
<p>I have a df like below</p> <p><code>a = pd.DataFrame([{'col1': ['a,b,c'], 'col2': 'x'},{'col1': ['d,b'], 'col2': 'y'}])</code></p> <p>When I do an explode using <code>df.explode(‘col1’)</code>, I get below results</p> <pre><code>col1 col2 a x b x c x d y b y </code></pre> <p>However, I w...
<p>You could do the following:</p> <pre><code>result = a.explode('col1').reset_index().rename(columns={'index' : 'col1_index'}) result['col1_index'] = result.groupby('col1_index').cumcount() print(result) </code></pre> <p><strong>Output</strong></p> <pre><code> col1_index col1 col2 0 0 a x 1 ...
python|python-3.x|pandas
2
366,146
59,277,448
How to create a video from numpy array without looping?
<p>I want to make a video from array which shape is (70000, 640, 480, 3). the first axis is the number of photos which I want to collect them into a video without using loops to append each photo .</p>
<p>You can create a 4-dimensional empty numpy array first, and then set the values later on </p> <pre><code>import numpy as np videos = np.zeros(shape=(70000, 640, 480, 3)) videos[60000][300][200][1] = 300 # set values later when needed </code></pre>
python-3.x|numpy|numpy-ndarray|array-broadcasting|numpy-ufunc
0
366,147
59,227,523
sklearn Logistic Regression “ValueError: Found array with dim 3. Estimator expected <= 2.”
<p>I design a CNN autoencoder,and I compress the image into a four dimensions vector(name:flatten), then I when to visualize the result by PCA method.</p> <p>Below is my model:</p> <pre><code>import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import in...
<p>@劉書宏, Thank you very much for the solution. For the benefit of the community am posting your solutions here (Answer Section).</p> <pre><code>import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST...
python|tensorflow|machine-learning|scikit-learn|pca
0
366,148
59,411,984
adding multiple columns to a dataframe using df.apply and a lambda function
<p>I am trying to add multiple columns to an existing dataframe with df.apply and a lambda function. I am able to add columns one by one but not able to do it for all the columns together. My code</p> <pre><code> def get_player_stats(player_name): print(player_name) resp = requests.get(player_id_api + player...
<p>It's tricky, since in pandas the apply method evolve through versions.</p> <p>In my version (0.25.3) and also the other recent versions, if the function returns <code>pd.Series</code> object then it works.</p> <p>In your code, you could try to change the return value in the function:</p> <pre><code>return pd.Seri...
python|pandas|lambda|apply
1
366,149
59,432,795
In Pandas, I want to group by a common element and get a list of the elements between them
<p>I want to group by a common element and get a list of the elements between them. </p> <p>The data set i have is below:</p> <pre><code>pd.DataFrame({'Type': {0: 'S', 1: '1', 2: '3', 3: '3', 4: '2', 5: 'S', 6: '4', 7: 'S', 8: '4', 9: '5', 10: '6', 11: 'S', 12: '2', 13: 'S'}}) Type 0 S 1 1 2 3 3 3...
<p>Make a Series which indicates which rows are in which groups:</p> <pre><code>groupidx = (df.Type == 'S').cumsum() grouped = df.groupby(groupidx) result = grouped.Type.apply(list) </code></pre> <p>The result is:</p> <pre><code>1 [S, 1, 3, 3, 2] 2 [S, 4] 3 [S, 4, 5, 6] 4 [S, 2] 5 ...
python|pandas
1
366,150
59,247,248
How to write recursion in dataframe?
<p>I have the dataframe like this:</p> <pre><code> Price Signal 0 28.68 -1 1 33.36 1 2 44.7 -1 3 43.38 1 ---- smaller than Price[2] # False: Drop row[3,4] 4 41.67 -1 5 42.17 1 ---- smaller than Price[2] # False: Drop row[5,6] 6 44.21 -1 7 46.34 1 ---- greater ...
<p>You can do it without <code>recursion</code>. By the way your approach will be slow because you call <code>.drop()</code> inside a loop. The easiest way is just use a new column to mark a rows for deletion.</p> <pre><code>df = pd.DataFrame({ 'Price': (28.68, 33.36, 44.7, 43.38, 41.67, 42.17, 44.21, 46.34, 45.2,...
python-3.x|pandas|recursion
1
366,151
59,308,026
How to speed up the loop over an OpenCV image in Python using Numpy?
<p>The goal is to overcome the problem of slow execution of nested loops in python by using the built-in functions in <code>numpy</code>.</p> <p>In the code below, I read an image with <code>imread</code> (colors: BGR) into <code>src</code> (a numpy array) and I define thresholds for each color (BGR respectively). The...
<p>You can do this:</p> <pre><code>a = np.array([[[1,2,3], [10,20,30]], [[40,50,60], [10, 30, 20]] ]) [*zip(*np.where((a &gt; (10,20,30)).all(-1)))] </code></pre> <p>Output:</p> <pre><code>[(1, 0)] </code></pre> <p><strong>Note</strong>: <code>np.where((a &gt; (10,20,30)).all(-1))</code> alone would give ...
python|numpy|opencv
2
366,152
59,163,887
How to use Multivariate time-series prediction with Keras, when multiple samples are used
<p>As the title states, I am doing multivariate time-series prediction. I have some experience with this situation and was able to successfully setup and train a working model in TF Keras.</p> <p>However, I did not know the 'proper' way to handle having multiple unrelated time-series samples. I have about 8000 uniqu...
<p>The main challenge is in 800 vs. 30,000 timesteps, but nothing you can't do. </p> <ul> <li><strong>Model design</strong>: <em>group sequences into chunks</em> - for example, 30 sequences of 800-to-900 timesteps, padded, then 60 sequences of 900-to-1000, etc. - don't have to be contiguous (i.e. next can be 1200-to-1...
python|tensorflow|keras|time-series|lstm
5
366,153
59,385,958
Cannot resolve symbol "tensorflow" flutter framework
<p>I get an error while trying to import TensorFlow lite from a maven repository on a flutter framework</p> <p>Error: Cannot resolve symbol "tensorflow"</p> <p>Specifically, I would like to use tflite Interpreter hence the import MainActivity.java file as below</p> <pre><code> package Doesnt.matter; import org.ten...
<h2><strong>Android SDK version</strong></h2> <ol> <li><p>You are required to use min SDK level 24 </p></li> <li><p>Go to File/Project Structure/Modules</p></li> <li><p>Scroll down and find $var[something...]</p></li> <li><p>now replace it with 24 sync and recompile</p></li> </ol>
java|android|flutter|tensorflow-lite
0
366,154
59,098,320
Frequency count in pandas
<p>I want to classify this data into two csv files. If the file name has <code>1</code> frequency it'll save to <code>single_face.csv</code> and the others will be saved to <code>multi_faces.csv</code></p> <p>What I've done is to get the frequencies of my data, this is what it looks like:</p> <pre><code>21_Festival_F...
<p>You can just use the conditions as an index into your <code>Series</code> and use <code>.to_csv()</code> for each of those:</p> <pre><code>In [4]: s = pd.Series(np.random.randint(1, 4, 20), index=list("abcdefghijkilmnopqrs")) In [5]: s[s == 1] Out[5]: a 1 g 1 k 1 s 1 dtype: int32 In [6]: s[s &gt; 1] O...
python|pandas
0
366,155
59,160,042
Python-OpenCV digit segmentation
<p>For my image processing class, I picked the digit recognition project by myself. In this project the aim is to recognize the digits on the analogue water-gas meters. My first aim is to find , where the digits are located and draw a rectangle on them. Later I want to take the rectangle image and apply machine learnin...
<p>First, you need to find key points on meter used to locating digit area. Such as <strong>template match</strong> using SURF feature. Then, crop digit area and using detect method to detect digits.</p>
python|numpy|opencv|image-processing|image-segmentation
0
366,156
59,237,402
How to specify the model version label in a REST API request?
<p>As described in the documentation, using the <code>version_labels</code> field, you can specify a label to a model version in order to handle canary deployments. </p> <p><a href="https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/serving_config.md#assigning-string-labels-to-model-versions-to...
<h3>Update:</h3> <p>Based on comments on <a href="https://github.com/tensorflow/serving/issues/1413" rel="nofollow noreferrer">this</a> GitHub Issue, @misterpeddy states that, as of August 14th 2019:</p> <blockquote> <p>Re: not being able to access the version using labels via HTTP - this is something that's not po...
tensorflow-serving
1
366,157
59,363,689
getting an error message when I run python pd.read_csv code
<p><strong>When I try run this code to read a CSV file that is located in my C drive:</strong></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd fd_inspections = pd.read_csv('c:\food_inspections.csv') </code></pre> <p><strong>I get this error</strong></p> <pre class="lang-py prettyprint-overr...
<ul> <li>just put <code>r''</code> before your path to file. Because <code>\</code> escapes character.</li> <li>Another way is to use <code>\\</code> in your string to escape that <code>\</code>.</li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd fd_inspections = pd.read_csv(r'c:\food_inspe...
python|pandas
2
366,158
59,100,902
How to change one entire row into the column headers? please advise me on this
<pre><code>class Decoder(json.JSONDecoder): def decode(self, s): result = super(Decoder, self).decode(s) return self._decode(result) def _decode(self, o): if isinstance(o, str): try: return int(o) except ValueError: try: ...
<p>You may use:</p> <pre><code>df.columns = df.loc['id',:].values df.drop('id', axis=0, inplace=True) df 1 2 3 4 5 6 7 8 9 value NY 11 D 531293696 5202013 NaN NaN NaN NaN df.columns Index([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='object') </code></pre>
python|pandas|numpy|dataframe
0
366,159
59,423,940
How to find leaves in a tree stored in a DataFrame
<p>Previously I posted this <a href="https://stackoverflow.com/questions/59283760/easier-way-to-find-nodes-in-a-dataframe">link</a>.</p> <p>I'd like to know if someone could help on retrieving only the leaves (in case of unbalanced tree) and not necessarily the nodes of level N.</p> <p>For instance, given the below t...
<p>If I understood correctly, you want the leaves, i.e. the children that aren't parents. You can get them by doing:</p> <pre><code>set(df['child']) - set(df['parent']) </code></pre> <h3>edit:</h3> <p>If you are willing to use <code>networkx</code>, you can use a lot of existing functionality:</p> <pre><code>import...
python-3.x|pandas|algorithm|tree
1
366,160
59,208,377
What should be the ideal validation accuracy of a LSTM based text generator?
<p>I modelled a LSTM based text generator using a data set I have. The purpose of the model is to predict the end of sentences. My training is showing a validation accuracy of around 81%. When reading through a couple of articles, I found that unlike a classification problem I should be worried more about loss rather t...
<p>There is no minimum limit for accuracy in any of the machine learning or Deep Learning problem.It's as many say <em>garbage IN, garbage OUT</em><br> Quality of data and with a decent model will give you good accuracy. </p> <p>Generally, these accuracy benchmark is set for the standard dataset available on an open ...
python|tensorflow|keras|lstm
1
366,161
59,195,915
Generate the initial game board of a Candy-Crush-like game
<p>I need to implement a function, which returns a 6 by 6 matrix that fulfills the following requirements:</p> <ul> <li>The 36 numbers on the board must be 9 ones, 9 twos, 9 threes and 9 fours</li> <li>Any row or column must not contain 3 or more direct neighbours that are the same number </li> <li>The function return...
<p>This should work. Note that this solution just generates a random board, checks if the conditions hold, and if not, generates another, so is not the most elegant solution.</p> <p><strong>Code:</strong></p> <pre><code>from random import shuffle def check_board(board): for row in board: if check_list(ro...
python|algorithm|numpy|matrix|nested-lists
1
366,162
59,081,908
Age group categorization
<p>I have dataframe, in that I have age column.I want to apply user defined function, so it arrange age in bins. I have following function trying to apply over columns but i am getting error. Name of the column is 'age'</p> <pre><code>def ageGroup(x): if (data_drop_row['age'] &gt; 0) &amp; (data_drop_row['age'] &l...
<pre><code>buckets = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] buckets_name = ['1', '2', '3', '4','5','6','7','8','9','10'] data_drop_row['age_cat']=pd.cut(data_drop_row['age'].values, buckets , labels = buckets_name) </code></pre>
python|pandas
1
366,163
59,192,705
How to apply bounds on a variable when performing optimisation in Pytorch?
<p>I am trying to use Pytorch for non-convex optimisation, trying to maximise my objective (so minimise in SGD). I would like to bound my dependent variable x > 0, and also have the sum of my x values be less than 1000. </p> <p>I think I have the penalty implemented correctly in the form of a ramp penalty, but am stru...
<p>I meet the same problem with you. I want to apply bounds on a variable in PyTorch, too. And I solved this problem by the below Way3.</p> <p>Your example is a little compliex but I am still learning English. So I give a simpler example below.</p> <p>For example, there is a trainable variable <code>v</code>, its bound...
optimization|pytorch|clamp|non-convex
3
366,164
59,165,907
Interpreting a “Traceback (most recent call last):” error
<p>I realize this issue has been explained many times before so I understand if this is closed as a duplicate, but I have some more theoretic questions to ask that may justify this as a new question. I'm new to Python (and SO), so bear with me.</p> <p>I'm trying to read in a .csv file that has 16 columns and 30,000ish...
<p>I'll expand on my comment to answer the original question - interpreting the exception.</p> <blockquote> <p>The cause for the error is because your dataframe most likely is not using integers for its column names, so the integers 0 through 15 will cause the KeyError you're seeing, which is the final line of both ...
python|pandas|numpy|dataframe|compiler-errors
1
366,165
59,453,732
Keep the first rows of continuous specific values in a pandas data frame?
<p>I have a data frame like this,</p> <pre><code>df col1 col2 1 A 2 A 3 A 4 A 5 A 6 A 7 B 8 B 9 A 10 A 11 A 12 A 13 B 14 A 15 B 16 A 17 A 18 A </code></pre> <p>Now if there is continuous B or only o...
<p>You can first replace non <code>B</code> values to missing values and then forward filling them by limit <code>1</code> - so last 2 <code>B</code> create one group and last get first values of <code>B</code> groups:</p> <pre><code>m = df['col2'].where(df['col2'].eq('B')).ffill(limit=1).eq('B') df = df[ m.ne(m.shift...
python|pandas|dataframe
3
366,166
59,313,589
Python: How to resample a 3d curve given by points as spline in equal distances?
<p>Allow me to separate this to increasing difficulty questions:</p> <hr> <p><strong>1.</strong></p> <p>I have some 1d curve, given as a <code>(n,)</code> point array.</p> <p>I would like to have it re-sampled <code>k</code> times, and have the results come from a cubic spline that passes through all points.</p> <...
<p>Partial answer; for 1 and 2 I would do this:</p> <pre><code>from scipy.interpolate import interp1d import numpy as np # dummy data x = np.arange(-100,100,10) y = x**2 + np.random.normal(0,1, len(x)) # interpolate: f = interp1d(x,y, kind='cubic') # resample at k intervals, with k = 100: k = 100 # generate x axis:...
python|arrays|numpy|scipy|curve-fitting
0
366,167
59,343,442
vectorize a function that changes values of a column conditionally
<p>I have been wondering how to vectorize the function below for my dataframe. And can anything be vectorized? </p> <p>Here is my dataframe:</p> <pre><code> date AGE 0 28/04/2017 13:08 25 1 28/04/2017 08:58 87 2 03/05/2017 07:59 23 3 03/05/2017 08:05 45 4 ...
<p>use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.gt.html" rel="nofollow noreferrer"><code>Series.gt</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofollow noreferrer"><code>Series.astype</code></a>.</p> <p>This ...
python|pandas|numpy
2
366,168
59,363,420
Value Error converting an object to a float
<p>I'm using a dataset which has a column "price" with values as "$150.00". In order to remove "$" I used:</p> <blockquote> <p><code>df.price = ([x.strip('$') for x in df.price])</code></p> </blockquote> <p>It worked. However, this column still remain as an "object". So my next step was check the highest values to...
<p>Because <code>strip</code> only removes characters from both left and right ends of a string, a <code>,</code> is in the middle, consider using <code>replace</code> instead, something like this should work:</p> <pre><code>df.price = ([x.replace(',', '') for x in df.price]) </code></pre> <p>And then turn them into ...
python|pandas|dataframe
0
366,169
14,084,234
pandas efficient way to get first filtered row for each DatetimeIndex entry
<p>I have a DataFrame with the following structure:</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; DatetimeIndex: 3333 entries, 2000-01-03 00:00:00+00:00 to 2012-11-21 00:00:00+00:00 Data columns: open 3333 non-null values high 3333 non-null values low 3333 non-null values cl...
<p>You may find it faster to extract the index as a column and use <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> and <a href="http://pandas.pydata.org/pandas-docs/dev/basics.html#filling-while-reindexing" rel="nofollow"><code>bfill</code><...
python|numpy|pandas|time-series
2
366,170
14,025,879
Assertion Error in columns in DataFrame with hierarchical indexing
<p>Another pandas question:</p> <p>I have this table with hierarchical indexing:</p> <pre><code>In [51]: from pandas import DataFrame f = DataFrame({'a': ['1','2','3'], 'b': ['2','3','4']}) f.columns = [['level1 item1', 'level1 item2'],['', 'level2 item2'], ['level3 item1', 'level3 item2']] f Out[51]: level1 item...
<p>I pushed a fix for this yesterday. Here's the new behavior on github master:</p> <pre><code>In [1]: paste from pandas import DataFrame f = DataFrame({'a': ['1','2','3'], 'b': ['2','3','4']}) f.columns = [['level1 item1', 'level1 item2'],['', 'level2 item2'], ['level3 item1', 'level3 item2']] f ## -- End pasted tex...
python|pandas|hierarchical
9
366,171
45,222,774
Python matplotlib get data with cursor from plot
<p>, Hi guys, I'm using python>matplotlib and I want to get the data from the plot by using the cursor.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt t = np.arange(0., 2., 0.1) plt.plot(t,t,'g^') ax = plt.gca() line = ax.lines[0] xd = line.get_xdata() yd = line.get_ydata() valx = np.where(xd==xd[0]...
<p>There is a <a href="https://matplotlib.org/users/event_handling.html#simple-picking-example" rel="nofollow noreferrer">Picker example</a> on the matplotlib page. You can adapt it to show the first n point pairs when the nth point is clicked.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt t = np.a...
python|numpy|matplotlib
1
366,172
45,173,451
scikit-learn: How to calculate root-mean-square error (RMSE) in percentage?
<p>I have a dataset (found in this link: <a href="https://drive.google.com/open?id=0B2Iv8dfU4fTUY2ltNGVkMG05V00" rel="nofollow noreferrer">https://drive.google.com/open?id=0B2Iv8dfU4fTUY2ltNGVkMG05V00</a>) of the following format. </p> <pre><code> time X Y 0.000543 0 10 0.000575 0 10 0.041324 1 10 0.041331...
<p>Your implementation of <code>calculate_mape</code> is not working because you are expecting the <code>check_arrays</code> function, which was removed in <code>sklearn 0.16</code>. <code>check_array</code> is not what you want.</p> <p><a href="https://stackoverflow.com/a/42251083/58866">This</a> StackOverflow answer...
python|python-3.x|pandas|scikit-learn|random-forest
6
366,173
44,996,599
Pandas enlargement of multidimensional objects
<p>I want to add row to a multidimensional pd.Series.</p> <pre><code>b = pd.Series([1,1,2,3], index = [["digit", "digit", "digit", "digit"], ["one", "one", "two", "three"]]) b Out[30]: digit one 1 one 1 two 2 three 3 dtype: int64 </code></pre> <p>Now, when I do </p> <pre><co...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_index.html" rel="nofollow noreferrer"><code>sort_index</code></a> because:</p> <blockquote> <p>PerformanceWarning: indexing past lexsort depth may impact performance.</p> </blockquote> <p>and then tuple with <a href="http:...
python|pandas|multidimensional-array
1
366,174
45,271,607
Tensorlfow, Running Error
<p>I want to know why this error occured. The input is image files <code>(24*375*3(width, height, channels)images, *.png)</code> and output is labeled file(.csv) which has Boolean (0 or 1) label.</p> <p>Here is my github <a href="https://github.com/dldudwo0805/DeepLearningPractice" rel="nofollow noreferrer">https://gi...
<pre><code>y_data = tf.reshape(y_data, [50, 1]) </code></pre> <p>y_data is a tensor. Try np.reshape rather than tf.reshape</p>
python|numpy|tensorflow
2
366,175
45,199,342
Train a model in Keras with non-differentiable layer
<p>How can I train a deep neural net in Kera(Tensorflow) with a Quantization layer in middle? i.e. I want to make the representation in a particular layer of the network be quantized (using Vector quantization) and then passed to the next layer. </p>
<p>You can use a <a href="https://keras.io/layers/core/#lambda" rel="nofollow noreferrer">Lambda Layer</a>.</p> <pre><code>def quantize(x): # Your vector quantization code model.add(Lambda(quantize)) </code></pre>
tensorflow|neural-network|deep-learning|keras|quantization
2
366,176
44,937,009
parse string as conditions to filter pandas dataframe
<p>Hi I have a pandas dataframe, I have a column A.</p> <pre><code>data = pandas.DataFrame() data['A']= [numpy.random.choice([1,2,3,4,5,6]) for i in range(10)] </code></pre> <p>I want to add a column B condition on A (when A =1 then B=0, when A>5 then B=1) instead of using:</p> <pre><code>data.loc[data['A']==1,'B']=...
<p>While there may be efficient ways to do it, one possible way might be to use <code>eval</code> function.</p> <p>Creating input <code>df</code>:</p> <pre><code>import pandas as pd import numpy as np data = pd.DataFrame() data['A']= [np.random.choice([1,2,3,4,5,6]) for i in range(10)] print(data) </code></pre> <p>...
python|string|pandas|operators
3
366,177
45,117,295
What is the relation between validation_data and validation_split in Keras' fit function?
<p><code>validation_split</code> says: "<em>hey give me all the input data – I will take care of splitting between test and validation</em>".</p> <pre><code>model.fit(inputX, inputY, validation_split=0.20, epochs=10, batch_size=10) </code></pre> <p><code>validation_data</code> says "<em>please give me explicitly the ...
<p>No, everything is correct. One potential reason behind this separation is that sometimes people have training and validation data separately (in many academic datasets) and sometimes you have all the data and can split it anyway you want.</p>
machine-learning|tensorflow|keras
5
366,178
45,093,955
TensorFlow Object Detection API using image crops as training dataset
<p>I want to train a ssd-inception-v2 model from Tensorflow Object Detection API. The training dataset I want to use is a bunch of cropped images with different sizes without bounding boxes, as the crop itself is the bounding boxes.</p> <p>I followed the create_pascal_tf_record.py example replacing the bounding boxes ...
<p>Object detection algorithms/networks often work by predicting the location of a bounding box as well as the class. For this reason the training data often needs to contain bounding box data. By feeding your model with training data with a bounding box that is always the size of the image then it's likely you'll get ...
image-processing|tensorflow|computer-vision|deep-learning|conv-neural-network
5
366,179
45,259,726
Tensorflow TypeError: 'Series' objects are mutable, thus they cannot be hashed
<p>I'm trying to build a simple logistic regression with Tensor Flow, but I'm getting this error:</p> <pre><code>TypeError: 'Series' objects are mutable, thus they cannot be hashed </code></pre> <p>This is my code:</p> <pre><code>data = pd.read_csv(data_file,sep=";",names=header) ... n = data.shape[0] n_training_set...
<p>Your error lies near:</p> <pre><code>rsi = tf.contrib.layers.real_valued_column(df_train["rsi"]) stochk = tf.contrib.layers.real_valued_column(df_train["stochk"]) stochd = tf.contrib.layers.real_valued_column(df_train["stochd"]) </code></pre> <p>Here you pass as a first parameters a column from the pandas datafram...
python|tensorflow
1
366,180
44,846,574
Python - bin sizes of lowest variance for classification
<p>I would like to change my feature 'Age' from a continuous variable, to a categorical variable of age ranges for binary classification, like this:</p> <pre><code>df['Age'] = pd.cut(df['Age'], [0,6,12,16,65,90] ,labels=['0-6','6-12','12-16','16-65','65-90']) </code></pre> <p>However I want to split it in the optimal...
<p>Maybe you can use <code>sklearn.cluster</code> to do this.</p>
python|pandas|feature-engineering
1
366,181
45,112,484
When training a single batch, is iteration of examples necessary (optimal) in python code?
<p>Say I have one batch that I want to train my model on. Do I simply run tf.Session()'s sess.run(batch) once, or do I have to iterate through all of the batch's examples with a loop in the session? I'm looking for the optimal way to iterate/update the training ops, such as loss. I thought tensorflow would handle it it...
<p>In a regression model, the network calculates the model output based on the randomly initialized values for your model parameters. That's why you're seeing negative values here; you haven't trained your model enough for it to learn that your values are only between 0 and 5. </p> <p>Unless I'm missing something, you...
python-2.7|performance|tensorflow|training-data
1
366,182
44,920,796
Concatenating string and integers in pandas dataframe(based on conditions)
<p>In my dataframe I have 2 columns:</p> <ol> <li>Country index(For example SK)</li> <li>id_number(usually 8 digit,for example:98341852)</li> </ol> <p>I want to concatenate them and it's easy:</p> <pre><code>sk_df['id'] = sk_df['country index'].str.cat(sk_df['id_number'].values.astype(str)) </code></pre> <p>But som...
<p>Use <code>.zfill()</code>:</p> <pre><code>sk_df['id'] = sk_df['country index'] + sk_df['id_number'].astype(str).str.zfill(8) </code></pre>
pandas
4
366,183
45,084,326
pandas - convert column to minutes values
<p>Hi I am trying to 'clean' a dataset which has a column called 'Duration'. It has elements like this:</p> <pre><code>18 mins 34 mins 1 hr 51 mins 1 day 1 hr 1 day 2 hrs 32 mins 3 days 4 hrs 48 mins </code></pre> <p>In other words, most entries are numerical values (minutes) but some have text data that represent d...
<p>Try this:</p> <pre><code>In [99]: pd.to_timedelta(df['Duration'].replace(['mins','hr','hrs'], ['min','hour','hour'], regex=True)) Out[99]: 0 0 days 00:18:00 1 0 days 00:34:00 2 0 days 01:51:00 3 1 days 01:00:00 4...
python|pandas
3
366,184
44,996,062
A custom alternating update rule with keras
<p>I would like to use an alternating update rule with keras. I.e. per-batch I would like to call a regular gradient-based step, and next call a custom step.</p> <p>I thought about implementing it by either inheriting an optimizer or a callback (and use the on-batch calls). However, neither would do, because they both...
<p>try create a custom callback</p> <pre><code>import keras.callbacks as callbacks class JSONMetrics(callbacks.Callback): _model = None _each_epoch = None _metrics = None _epoch = None _file_json = None def __init__(self,model,each_epoch,logger=None): self._file_json = "file_log.json" self._...
optimization|tensorflow|keras|keras-layer|keras-2
-1
366,185
44,979,927
Pandas series case-insensitive matching and partial matching between values
<p>I have the following operation to add a status showing where any string in a column of one dataframe column is present in a specified column of another dataframe. It looks like this:</p> <pre><code>df_one['Status'] = np.where(df_one.A.isin(df_two.A), 'Matched','Unmatched') </code></pre> <p>This won't match if the ...
<p>You can do the first test by converting both strings to lowercase or uppercase (either works) inside the expression (as you aren't reassigning either column back to your DataFrames, the case conversion is only temporary):</p> <pre><code>df_one['Status'] = np.where(df_one.A.str.lower().isin(df_two.A.str.lower()), \ ...
python|pandas|numpy|np
6
366,186
45,200,409
Setting each value to a float, but returning an object in pandas
<pre><code>for x in range(1,17): df.loc[(df[x]=='n'), (x)]=float(0.0) df.loc[(df[x]=='y'), (x)]=float(1.0) df.loc[(df[x]=='?'), (x)]=np.nan df.dtypes </code></pre> <p>returns all objects. Why is that when I'm specifically setting each item to either a float 0 or 1 or a NaN. Basically i'm unable to run col...
<pre><code>url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/voting-records/house-votes-84.data' df = pd.read_csv(url, header=None, index_col=0) df[df.eq('?')] = np.nan df[df.eq('y')] = 1.0 df[df.eq('n')] = 0.0 df = df.reset_index() </code></pre> <p>Result:</p> <pre><code>In [67]: df Out[67]: ...
python|pandas|floating-point|mean
1
366,187
45,217,126
Daily mean of subset of columns in pandas dataframe
<p>I have the following dataframe (with datetime index):</p> <pre><code> col_a col_b col_c col_d col_e col_f col_g col_h fid 7/20/2017 10:00 0 18 45 17 19 2.777778 180 0.92 999000 7/20/2017 11:00 0.03 18 45 17 19 2.2222224 180 0.93 999000 7/20/2017 12:00 0.03 ...
<p>If need resample some values differently (like column <code>fid</code> because text column) is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.resample.Resampler.aggregate.html" rel="nofollow noreferrer"><code>Resampler.agg</code></a> by <code>dict</code>, which can be dynamic...
python|pandas
1
366,188
44,875,397
KeyError: False in pandas dataframe
<pre><code>import pandas as pd businesses = pd.read_json(businesses_filepath, lines=True, encoding='utf_8') restaurantes = businesses['Restaurants' in businesses['categories']] </code></pre> <p>I would like to remove the lines that do not have Restaurants in the categories column, and this column has lists, however g...
<p>The expression <code>'Restaurants' in businesses['categories']</code> returns the boolean value <code>False</code>. This is passed to the brackets indexing operator for the DataFrame businesses which does not contain a column called False and thus raises a KeyError.</p> <p>What you are looking to do is something ca...
python|pandas
26
366,189
45,120,708
Calculating pairwise spatial distances in periodic 2D lattice
<p>I've been searching in vain for a solution to compute spatial distances between discrete, equidistant square sites on a lattice of periodic/wrapped edges. For example, setting adjacent sites to be 2 units apart on 9x9 lattice:</p> <pre><code>m = 9 lattice = np.zeros((m,m)) for i in arange(0,6+1,3): for j in ara...
<p>Since <code>distance.cdist</code> accepts an arbitrary metric, provided as a callable, the problem is just in writing a function for your metric. </p> <p>If it was wrapped distance between points p and q, that would be</p> <pre><code>def wrapped_euclidean_points(p, q): diff = np.abs(p - q) return np.linalg...
python|arrays|numpy|scipy|euclidean-distance
3
366,190
44,825,351
Python DataFrame for Stock data - Drop Function Not working
<pre><code>import quandl import pandas as pd from pandas_datareader import data, wb import sys #df = DataFrame(table, columns=headers) #df = DataFrame(table) #Code to take data from Quandl df=quandl.get("NSE/BHEL",start_date="2017-06-15", end_date="2017-06-29") df.rename(columns = {'Last':'Adj Close'}, inplace = True...
<p>I think you need select data by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> if need select by position or <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code...
python|pandas|dataframe|stock
2
366,191
44,832,615
rescaling axes on pcolor plot from pandas data frame
<p>I'm inputting data from a text file with column structure more or less like this:</p> <pre><code>x y density </code></pre> <p>I need to plot a heat map of density(x,y).</p> <p>I'm just getting started with pyplot and pandas and I'm not sure how to achieve this functionality efficiently.</p> <p>I first tried ...
<p>This code snipped is out of the Python data science handbook from Jake VanderPlas:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt x=np.linspace(0,10,100) y=np.linspace(0,10,100) def density(x,y): return np.sin(x) ** 10 + np.cos(10 + y * x)*np.cos(x) X,Y=np.meshgrid(x,y...
python|pandas|matplotlib|plot
-1
366,192
45,246,903
using numpy.where on multidimensional arrays
<p>I have a 2D array, each row represents an output of a classifier that classifies some input to 3 categories (array size is <code>1000 * 3</code>) : </p> <pre><code>0.3 0.3 0.3 0.3 0.3 1.0 1.0 0.3 0.3 0.3 0.3 0.3 0.3 1.0 0.3 ... </code></pre> <p>I want to get a list of all the inputs that the classifier is "not su...
<p>Alternatively to <code>np.where</code>:</p> <pre><code>res_all_unsure = preds[:,np.amax(preds, axis=(0,2)) &lt;= 0.8,:] res_one_unsure = preds[:,preds.max(-1).min(0) &lt;= 0.8,:] </code></pre>
python|arrays|numpy
3
366,193
45,152,427
multiple rows for row in pandas dataframe python
<p>For a column in a pandas DataFrame with several rows I want to create a new column that has a specified number of rows that form sub-levels of the rows of the previous column. I'm trying this in order to create a large data matrix containing ranges of values as an input for a model later on.</p> <p>As an example I ...
<p>I think you need <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html" rel="nofollow noreferrer"><code>numpy.tile</code></a> with <code>DataFrame</code...
python|pandas|dataframe|numpy
2
366,194
45,036,496
Tensorflow object detection: ImportError: No module named nets
<p>I am currently attempting to install the tensorflow object detection app on Windows 7 (employer requirement) and I am failing at a few steps from the end.</p> <p>Basically I get the following error when I run the installation test command: ImportError: No module named nets.</p> <p>I have read some solutions on the...
<p>in linux: add export export PYTHONPATH=$PYTHONPATH:<code>pwd</code>:<code>pwd</code>/slim to ~/.bashrc attention:you should keep single quote mark</p> <p>if you work with windows, i guess it should like this:PYTHONPATH=$PYTHONPATH:'C:/tensorflow/models':'C:/tensorflow/models'/slim just my guess, you can take a try....
windows|tensorflow|environment-variables|object-detection
2
366,195
45,039,937
python pandas select rows where two columns are (not) equal
<pre><code>hsp.loc[hsp['Len_old'] == hsp['Len_new']] </code></pre> <p>I try this code, it's working.</p> <p>But I tried these three </p> <pre><code>hsp.loc[hsp['Type_old'] == hsp['Type_new']] hsp.loc[hsp['Type_old'] != hsp['Type_new']] hsp.loc[hsp['Len_old'] != hsp['Len_new']] </code></pre> <p>They are not worki...
<p>Use the <a href="https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python">complement operator</a> <code>~</code></p> <pre><code>hsp.loc[~(hsp['Type_old'] == hsp['Type_new'])] </code></pre> <p>which gives:</p> <pre><code> id Type_old Type_new Len_old Len_new 1 2 Num Char 12 ...
python|pandas
35
366,196
44,931,704
How to extract value
<p>i have called following data from the quantopian api and received following data:</p> <pre><code>{Equity(25600, symbol=u'LPHI', asset_name=u'LIFE PARTNERS HOLDINGS INC', exchange=u'NASDAQ', start_date=Timestamp('2003-10-21 00:00:00+0000', tz='UTC'), end_date=Timestamp('2015-03-27 00:00:00+0000', tz='UTC'), first_tr...
<p>A dirty way to do this is </p> <pre><code>s = a.find('Equity') # where a is your string you get from quantopian e = a.find('symbol') print(a[s+7:e-2]) </code></pre> <p>I find the indices of <code>Equity</code> and <code>Symbol</code> and then just get whatever is in the middle using the slicing operator after ap...
python|api|pandas
3
366,197
44,946,458
How to subtract cell values from one column with cell values from another column in xlsx files using python
<p>I want to subtract the cell values from one column with cell values from another column and write the sum to a new column in an excel file. Then I want the sum, if not equal to 0, to be added to a list for later use. The data in my excel file are structured like this:</p> <pre><code>Name | Number | Name1 | Number1 ...
<p>First create <code>DataFrame</code> from excel by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow noreferrer"><code>read_excel</code></a>.</p> <p>Then need substract <code>2.</code> with <code>4</code> columns:</p> <pre><code>df = pd.read_excel('file.xlsx') #se...
python|excel|pandas|openpyxl|xlrd
3
366,198
44,943,003
Python selecting row from second dataframe based on complex criteria
<p>I have two dataframes, one with some purchasing data, and one with a weekly calendar, e.g.</p> <pre><code>df1: purchased_at product_id cost 01-01-2017 1 £10 01-01-2017 2 £8 09-01-2017 1 £10 18-01-2017 3 £12 df2: week_no week_start week_end 1 31-12-2016...
<p>If your dataframes are to big you can use this trick.</p> <p>Do a full cartisian product join of all records to all records:</p> <pre><code>df_out = pd.merge(df1.assign(key=1),df2.assign(key=1),on='key') </code></pre> <p>Next filter out those records that do not match criteria in this case, where purchased_at is ...
python|pandas|numpy|dataframe
0
366,199
44,914,579
aggregate functions on groupby object giving incomplete output
<p>I have a dataframe that looks like this:</p> <pre><code> A B C D `` category labels 7937 0 0.00137174 0.0301783 0.00137174 Foo 0 15461 0 0 0.0132548 0.0441826 Bar 1 </code></pre> <p>I grouped the frame into a groupby obje...
<p>use <code>agg</code> (aggregate) and provide a list of functions. The default aggregate functions should be recognized as strings (ie. count, sum, unique...) but you can also define your own</p> <pre><code>groups.agg(['sum', 'count', lambda x : list(x)]) </code></pre>
python|pandas
1