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
6,900
46,622,031
Try to plot finance data with datetime but met error TypeError: string indices must be integers, not str
<p>I'd like to plot finance data with datetime, as below data example shown. But I get the error: </p> <pre><code>TypeError: string indices must be integers, not str </code></pre> <p>Could you please kindly help me to know why I meet this error, and the solution? </p> <pre><code>from datetime import datetime, timed...
<p>The following could be used to plot your data. The main point is that you need to specify the (rather unusual) format of the datetimes (<code>"%Y/%m/%d/%H/%M"</code>), such that it can be converted to a datetime object.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("data/minut...
python|pandas|matplotlib
0
6,901
46,541,445
Pandas resample timeseries in to 24hours
<h2>I have the data like this:</h2> <pre><code> OwnerUserId Score CreationDate 2015-01-01 00:16:46.963 1491895.0 0.0 2015-01-01 00:23:35.983 1491895.0 1.0 2015-01-01 00:30:55.683 1491895.0 1.0 2015-01-01 01:10:43.830 2141635.0 0.0 2015-01-01 01:11:08.927 1491895.0 1.0 2015-01-0...
<p>I think you need:</p> <pre><code>#remove `[]` and add parameter values for remove MultiIndex in columns df = pd.pivot_table(data_series.reset_index(), index='CreationDate', columns='OwnerUserId', values='Score', fill_value=0) #truncat...
python|pandas|dataframe|time-series
1
6,902
46,604,760
What is the equivalent of length in R to python
<p>I have been using R to program and a naive in Python programming. I have a working code in R where I'm reading multiple files in a folder and sub-setting the file by few columns. The columns are not same in all the files. So, in R, I wrote a code:</p> <pre><code>selectedcolumns &lt;- df[,c(1,3:5,7:length(df))] </co...
<p>It looks a little bit complex after R, but if you want to copy all columns after selected up to the end you should use code like this:</p> <pre><code>df1 = df.iloc[:,7:] </code></pre> <p>It will copy all columns from 7 to the last.</p> <p>You can select multiple ranges this way:</p> <p><code>df1 = df[df.columns[...
python|pandas|numpy
2
6,903
58,478,845
Moving duplicate rows from a subset of columns to another data frame in Python
<p>Using Python and Pandas I want to find all columns with duplicate rows in a data frame and move them to another data frame. For example I might have:</p> <pre><code>cats, tigers, 3.5, 1, cars, 2, 5 cats, tigers, 3.5, 6, 7.2, 22.6, 5 cats, tigers, 3.5, test, 2.6, 99, 52.3 </code></pre> <p>And I want cats, tigers, ...
<p>You can use</p> <pre><code>df1 = pd.DataFrame(df.val.str.extract('([a-zA-Z ]+)', expand=False).str.strip().drop_duplicates()) #'val' is the column in which you have these values print(df1) </code></pre> <p><strong>Output</strong></p> <pre><code> val 0 ABCD </code></pre> <p>and </p> <pre><code>df2 = pd.Dat...
python|pandas
1
6,904
58,229,964
How to move around Pandas Dataframe column?
<p><a href="https://i.stack.imgur.com/QN6RD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QN6RD.png" alt="enter image description here"></a></p> <p>I've attached a screenshot. I need some method to move the 'DATE' column to be aligned with the actual columns of the dataframes, which are SMA &amp; ...
<p>First column is called <code>index</code> in pandas and for convert to column use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>DataFrame.reset_index</code></a>:</p> <pre><code>df = df.reset_index() </code></pre> <hr> <p>But n...
python|python-3.x|pandas|dataframe
3
6,905
58,237,181
How to do a pivot in pandas with duplicated entries
<p>How does one do a pivot in pandas? I can't around the 'duplicate entries' error. The input and the output should look like what is outlined below.</p> <pre><code>import pandas as pd input = pd.DataFrame({'measure': ['length','length','length','weight','weight','weight','sex','sex','sex'], 'sp...
<p>In this situation, we usually resolve to <code>groupby().cumcount()</code> to get the new index:</p> <pre><code>indf['idx'] = indf.groupby('measure').cumcount() (indf.pivot_table(index=['idx','species','set'], columns='measure', values='value') .reset_index(('species','set')...
python|pandas|dataframe|pivot
5
6,906
58,185,803
Trying to Reset column for every change in opponent
<p>Have a Batting Order here and trying to reset it based on changing opponent</p> <p>For example: When opponent changed from Colorado State to UTSA Batting Order needs to reset back to 1</p> <pre><code>df['Batting Order'] = df['pa'].cumsum().mod(9).apply(lambda x: 9 if x == 0 else x) pa Battin...
<pre class="lang-py prettyprint-override"><code>def reset(df): grouping = df.groupby('Opponent') teams = grouping.groups.keys() batting_Order = [] for team in teams: subset = grouping.get_group(team) for i in range(len(subset)): batting_Order.append(i) df['Batting Order']...
python|pandas
0
6,907
69,238,330
DCGAN how to go RGB instead of greyscale
<p>I have this DCGAN that is pretty close to the TensorFlow docs.</p> <p>Here is the tutorial: <a href="https://www.tensorflow.org/tutorials/generative/dcgan" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/generative/dcgan</a></p> <p>It uses greyscale values in the test data. I am looking to start train...
<p>Yes the generator needs to be changed too. Greyscale has one channel and you need three.</p> <p>So you need to change</p> <pre><code> model.add(layers.Conv2DTranspose(1, (20, 20), strides=(8, 8), padding='same', use_bias=False, activation='tanh')) assert model.output_shape == (None, 112, 112, 1) </code></pre>...
python|tensorflow|machine-learning|keras|deep-learning
1
6,908
69,160,914
Why does "load_model" cause RAM memory problems while predicting?
<p>I trained neural network (transformer architecture) and saved it by using:</p> <pre><code>model.save(directory + args.name, save_format=&quot;tf&quot;) </code></pre> <p>After that, I want to load the model again with another script to test it by letting it make iterative predictions:</p> <pre><code>from keras.models...
<p>There is a fundamental difference between <code>load_model</code> and <code>load_weights</code>. When you save an model using <code>save_model</code> you save the following things:</p> <p>A Keras model consists of multiple components:</p> <ul> <li>The architecture, or configuration, which specifies what layers the m...
python|tensorflow|tensorflow2.0
0
6,909
44,555,763
Is there a way to check for linearly dependent columns in a dataframe?
<p>Is there a way to check for linear dependency for columns in a pandas dataframe? For example:</p> <pre><code>columns = ['A','B', 'C'] df = pd.DataFrame(columns=columns) df.A = [0,2,3,4] df.B = df.A*2 df.C = [8,3,5,4] print(df) A B C 0 0 0 8 1 2 4 3 2 3 6 5 3 4 8 4 </code></pre> <p>Is there a way ...
<p>If you have <code>SymPy</code> you could use the <a href="https://en.wikipedia.org/wiki/Row_echelon_form" rel="noreferrer">"reduced row echelon form"</a> via <a href="http://docs.sympy.org/dev/tutorial/matrices.html#rref" rel="noreferrer"><code>sympy.matrix.rref</code></a>:</p> <pre><code>&gt;&gt;&gt; import sympy ...
python|pandas|dataframe|linear-algebra
9
6,910
44,708,739
Pandas/datetime/total seconds : numpy.timedelta64' object has no attribute 'total_seconds'
<p>I have a data frame. I converted two of my date columns to datetime format. And I want to calculate the difference in minutes. But I get the following error.</p> <pre><code>from datetime import datetime df['A'] = df['A'].apply(lambda t: datetime.strptime(t, '%Y-%m-%d %H:%M:%S')) df['B'] = df['B'].apply(lambda t: d...
<p>It seems I need to do this:</p> <pre><code>df['C'] = (df['B'] - df['A'])/ np.timedelta64(1, 's') </code></pre>
python|pandas|datetime|numpy
3
6,911
71,739,322
scipy `SparseEfficiencyWarning` when division on rows of csr_matrix
<p>Suppose I already had a <code>csr_matrix</code>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy.sparse import csr_matrix indptr = np.array([0, 2, 3, 6]) indices = np.array([0, 2, 2, 0, 1, 2]) data = np.array([1., 2., 3., 4., 5., 6.]) mat = csr_matrix((data, indices, indptr), shape=...
<p>Your matrix:</p> <pre><code>In [208]: indptr = np.array([0, 2, 3, 6]) ...: indices = np.array([0, 2, 2, 0, 1, 2]) ...: data = np.array([1., 2., 3., 4., 5., 6.]) ...: mat = sparse.csr_matrix((data, indices, indptr), shape=(3, 3)) In [209]: mat Out[209]: &lt;3x3 sparse matrix of type '&lt;class 'numpy....
python|numpy|scipy|sparse-matrix
4
6,912
71,757,164
Catalog rows according to type conditions
<p>I have a given dataFrame with four columns -</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>X1</th> <th>X2</th> <th>X3</th> <th>X4</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1.2</td> <td>1.2</td> <td>2</td> </tr> <tr> <td>1</td> <td>1.3</td> <td>1.2</td> <td>1.2</td> </tr> <tr> <td...
<pre><code>df['new_column'] = df.apply(lambda x: 1 if isinstance(x['X1'],int) and isinstance(x['X4'],int) else 'bug', axis=1) </code></pre>
python|pandas|dataframe
1
6,913
71,536,438
Xlwings - unable to insert values for a range of rows
<p>I am trying to insert a value <code>n</code> into a specific <code>H</code> column from position H10:H20</p> <p>So, I tried the below</p> <pre><code>start_index = int(10) for n in range(20): print(type(n)) # this returns int range('H' + str(start_index)).value = n start_index = start_index + 1 </code><...
<p>Try the following <code>from xlwings import range as xlrange</code> and rename the code at line 4 as <code>xlrange</code>.</p> <p>Or use <code>import xlwings</code> and at line 4 use <code>xlwings.range</code>.</p> <p>Try to avoid asterisk in your import statements in order to avoid polluting the namespace. For more...
python|excel|pandas|dataframe|xlwings
1
6,914
69,985,881
How the shape is (3 2 1) | Numpy |
<p>I am learning numpy , have a question in my mind not able to clearly visualise from where this 1 as come in shape</p> <pre><code>import numpy as np a = np.array([ [[1],[56]] , [[8],[98]] ,[[89],[62]] ]) np.shape(a) </code></pre> <p>The output is printed as : <code>(3 ,2 , 1)</code></p> <p>Will be appreciated if you...
<p>Basically, that last 1 is because every number in <code>a</code> has brackets around it.</p> <p>Formally, it's the length of your &quot;last&quot; or &quot;innermost&quot; dimension. You can take your first two dimensions and arrange <code>a</code> as you would a normal matrix, but note that each element itself has ...
python|numpy|matrix
1
6,915
69,788,182
How to approach dataframe list to html (how to iterate in html code)?
<p>I have serveral pandas dataframes in a list. So I have several dataframes (df[0], df[1]). Each dataframe I want to write to html.</p> <p>The html code in the python file looks as follows:</p> <pre><code>html = f''' &lt;html&gt; &lt;head&gt; title&gt;{&quot;test&quot;}&lt;/title&gt;...
<p>I'm assuming that you want to join the HTML strings of all DataFrames into a single one.</p> <p>Just create a function that produces the HTML code for a given DataFrame</p> <pre class="lang-py prettyprint-override"><code>def df_to_html(df): return f''' &lt;html&gt; &lt;head&gt; ...
python|html|pandas|dataframe
0
6,916
69,790,781
TensorFlow model correctly predicting images, but not frames from real time video stream?
<p>Why does my TensorFlow model <strong>correctly predict JPG and PNG images</strong> but <strong>incorrectly predict frames from real time video stream?</strong> All frames in the real time video stream are all being incorrectly classified as class 1.</p> <p>Attempt: I saved a PNG image from the realtime video stream....
<p>the reason for the real time prediction not correct is because of the preprocessing. The preprocessing of the inference code should be always same as the preprocessing used while training. Use <strong>tf.keras.preprocessing.image.load_img</strong> in your real-time prediction code but it takes image path to load the...
python|tensorflow|opencv|keras|video-streaming
1
6,917
43,395,584
Comparing two Pandas dataframes for differences on common dates
<p>I have two data frames, one with historical data and one with some new data appended to the historical data as:</p> <pre><code>raw_data1 = {'Series_Date':['2017-03-10','2017-03-11','2017-03-12','2017-03-13','2017-03-14','2017-03-15'],'Value':[1,2,3,4,5,6]} import pandas as pd df_history = pd.DataFrame(raw_data1, co...
<p>Simply run a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>query</code></a> filter to capture ...
python|python-2.7|pandas
0
6,918
43,252,197
python convert list to numpy array while preserving the number formats
<p>My goal is to convert my data into numpy array while preserving the number formats in the original list, clear and proper.</p> <p><br>for example, this is my data in list format:</p> <pre><code>[[24.589888563639835, 13.899891781550952, 4478597, -1], [26.822224204095697, 14.670531752529088, 4644503, -1], [51.450405...
<p>Simple array creation from the nested list:</p> <pre><code>In [133]: data = np.array(alist) In [136]: data.shape Out[136]: (8, 4) In [137]: data.dtype Out[137]: dtype('float64') </code></pre> <p>This is a 2d array, 8 'rows', 4 'columns'; all elements are stored as float.</p> <p>The list can be loaded into a struc...
python|arrays|numpy
1
6,919
72,212,756
How to import an arff file to a pandas df and later convert it to arff again
<p>I want to preprocess a data base with scikit learn from an arff file, and later use on an python-weka-wrapper3 model the preprocessed data base, so I need a function to load the arff as df or transform the arff to csv, and later again download the edited df on an arff or transform a csv to arff.</p> <p>Some people r...
<p>If you want to stay within the scikit-learn ecosystem, you could have a look at the <a href="https://github.com/fracpete/sklearn-weka-plugin" rel="nofollow noreferrer">sklearn-weka-plugin</a> library, which uses <a href="https://github.com/fracpete/python-weka-wrapper3" rel="nofollow noreferrer">python-weka-wrapper3...
pandas|dataframe|csv|weka|arff
0
6,920
72,294,420
Email Classifier to classify emails according to the time
<p>I have to design a program that can classify emails as spam or nonspam using Python and Pandas.</p> <p>I have done to classify the email as spam or nonspam according to the email's subject. For my second task, I have to classify the emails as spam or nonspam according to the time. If the email gets received on ('Fri...
<p>There are a million ways you could do this, but this is how I would do it. I provided comments and some naming conventions simply for clarity which should allow you to take and modify as necessary to fit your specific needs</p> <pre><code>#All necessary imports import pandas as pd import numpy as np import datetime ...
python|pandas
0
6,921
72,399,738
How to fix error: operands could not be broadcast together with shapes (450,600,3) (277,330,3)
<pre><code>import math import cv2 import numpy as np original = cv2.imread(r&quot;C:\Users\HP\Documents\fyp\img\4.bmp&quot;, 1) contrast = cv2.imread(r&quot;C:\Users\HP\Documents\fyp\img\dehaze4.png&quot;, 1) def psnr(img1, img2): mse = np.mean((img1 - img2) ** 2) if mse == 0: return 100 PIXEL_MAX...
<p>The two images are of different shapes. I'm not sure what you're trying to do comparing two images of different sizes, but one way to do it is to resize one of the images to the size of the other:</p> <pre><code>def psnr(img1, img2): if img1.shape != img2.shape: img2 = cv2.resize(img2, img1.shape, interp...
python|arrays|numpy|opencv
3
6,922
72,266,130
TypeError: unhashable type: 'numpy.ndarray' when taking first occurence
<p>I am trying to get the first occurence of unique values of <strong>chain_id</strong> in a pandas df. I am using the following code:</p> <pre><code>import pandas as pd import re df = pd.DataFrame(columns=&quot;Sender&quot;, &quot;Subject&quot;, &quot;Body&quot;, &quot;Datetime&quot;, &quot;chain_id&quot; first_occu...
<p>So, just to be clear, what you want is the first row where each <code>chain_id</code> occurs? You can use</p> <pre><code>first = df.drop_duplicates( ['chain_id'], keep='first' ) </code></pre> <p>Keeping the first is the default, but since it is important, you might as well specify it.</p>
python|pandas|dataframe
1
6,923
72,329,302
How to write a FAST API function taking .csv file and making some preprocessing in pandas
<p>I am trying to create an API function, that takes in .csv file (uploaded) and opens it as pandas DataFrame. Like that:</p> <pre><code>from fastapi import FastAPI from fastapi import UploadFile, Query, Form import pandas as pd app = FastAPI() @app.post(&quot;/check&quot;) def foo(file: UploadFile): df = pd.read...
<p>To read the file in pandas, the file must be stored on your PC. Don't forget to import <code>shutil</code>. if you don't need the file to be stored on your PC, delete it using <code>os.remove(filepath)</code>.</p> <pre><code> if not file.filename.lower().endswith(('.csv',&quot;.xlsx&quot;,&quot;.xls&quot;)): ...
python|pandas|python-requests|request|fastapi
1
6,924
50,662,176
Best practices for indexing with pandas
<p>I want to select rows based on a mask, <code>idx</code>. I can think of two different possibilities, either using <code>iloc</code> or just using brackets. I have shown the two possibilities (on a dataframe <code>df</code>) below. Are they both equally viable?</p> <pre><code>idx = (df["timestamp"] &gt;= 5) &amp; (d...
<p>No, they are not the same. One uses direct syntax while the other relies on chained indexing.</p> <p>The crucial points are:</p> <ul> <li><a href="https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>pd.DataFrame.iloc</code></a> is used primarily ...
python|pandas|dataframe|indexing|series
8
6,925
50,537,777
How Can I Extract Predictions from A Softmax Layer on Tensorflow
<p>I'm trying to extract predictions, use predictions in calculating accuracy/precision/recall/F1 and prediction probability. I know I have 10 output classes therefore I can't calculate precision per see but I will be doing all these in other models moreover I'd like to be able to extract prediction probabilities. My m...
<p>The code shared in the question covers training, but not "using" (infering) with the resulting model.</p> <p>Two issues:</p> <ul> <li>The trained model is not serialized, so future runs will run on an <em>untrained</em> model, and predict whatever their initialization tells them to. Hence a <a href="https://stacko...
python|tensorflow|prediction|softmax|categorization
3
6,926
45,511,995
Pandas Modify DataFrames in Loop Part 2
<p>Given the following data frames:</p> <pre><code>import pandas as pd k=pd.DataFrame({'A':[1,1],'B':[3,4]}) e=pd.DataFrame({'A':[1,1],'B':[6,7]}) k A B 0 1 3 1 1 4 e A B 0 1 6 1 1 7 </code></pre> <p>I'd like to apply a group-by sum in a loop, but doing so does not seem to modify the data...
<p>Ok , you can try this </p> <pre><code>import pandas as pd k=pd.DataFrame({'A':[1,1],'B':[3,4]}) e=pd.DataFrame({'A':[1,1],'B':[6,7]}) fields=['k','e'] dfsout=[k,e] variables = locals() for d,name in zip(dfsout,fields): variables["{0}".format(name)]=d.groupby(d.columns[0]).apply(sum) k Out[756]: A B A ...
python|loops|pandas|dataframe
0
6,927
62,477,692
ValueError: Expected 2D array, got 1D array instead: for the matrix?
<p>I get the following error and unsure as to why? ValueError: Expected 2D array, got 1D array instead: The dataset I used is <a href="https://catalog.data.gov/dataset/demographic-statistics-by-zip-code-acfc9" rel="nofollow noreferrer">https://catalog.data.gov/dataset/demographic-statistics-by-zip-code-acfc9</a></p> <...
<p>The <code>y</code> you used to fit the model is 1D, so will the result of the prediction from the model.</p> <p>If you want to make a prediction from a unique value <code>x</code>, you can try:</p> <pre class="lang-py prettyprint-override"><code>p = model.predict([[78]])[0] </code></pre> <p>p will be 1D, so you j...
python|arrays|pandas|matplotlib|scikit-learn
0
6,928
62,495,372
Jupyter notebook is giving me error for correct codes
<p>My jupyter notebook is giving error for codes that are correct. specifically this is my error: <code>AttributeError: ‘NoneType’ object has no attribute ‘plot’</code></p> <p>I have check and check again, i have re written my codes, i also ran my code cell by cell and also use <code>Run all</code>. but not working. Yo...
<p>Your stacktrace precisely indicates the offending row:</p> <pre><code>----&gt; 2 cleaned_data_count = recent_grads.count() ... AttributeError: 'NoneType' object has no attribute 'count' </code></pre> <p>Apparently <em>recent_grads</em> is <em>None</em>, so you can't invoke any method on it, including <em>count</em> ...
python|pandas|jupyter-notebook
1
6,929
62,595,431
How to map a list to a column with repeating values python
<p>I have a list of .png logos like so:</p> <pre><code>logos ['C.png', 'E.png', 'FUR.png', 'FaZe.png', 'GenG.png', 'HER.png', 'MiBR.png', 'X6.png'] </code></pre> <p>I have another column consisting of those values repeating multiple times, like so:</p> <pre><code>teams HER MiBR C E HER FaZe ... </code></pre> <...
<p>Creating DataFrame and lists:</p> <pre><code>pngs = ['C.png', 'E.png','FUR.png', 'FaZe.png', 'GenG.png', 'HER.png', 'MiBR.png', 'X6.png'] dataframe = pd.DataFrame({'teams': ['HER','MiBR','C','E','HER','FaZe','teste']}) </code></pre> <p>Getting only names of .png list:</p> <pre><code>pngs_only_name = [x[:-4] for x i...
python|pandas|dataframe|mapping
2
6,930
62,638,401
df.to_csv without separator and spaces python
<p>I want to create a txt File so I used this.</p> <pre><code>df1.to_csv('C:/Users/junxonm/Desktop/Filetest.txt',sep=&quot; &quot; ,index=False, header=False) </code></pre> <p>I can completely remove the separator</p> <p>I tried this...</p> <pre><code>df1.to_csv('C:/Users/junxonm/Desktop/Filetest.txt',sep=&quot;&quot; ...
<p>Try to write your pandas dataframe to the new text file like this (use a raw-string for your filename, and use None values instead of False for header and index):</p> <pre><code>df1.to_csv(r'C:/Users/junxonm/Desktop/Filetest.txt', header=None, index=None, sep=' ', mode='w'...
python|pandas
1
6,931
54,336,881
How to get back DataFrame after using str(df)?
<p>I think I messed up trying to save a Pandas Series that contained a bunch of Pandas Dataframes. Turns out that the DataFrames were each saved as if I called <code>df.to_string()</code> on them.</p> <p>From my observations so far, my strings have extra spacing in some places, as well as extra <code>\</code> when the...
<h3>New answer</h3> <p>In response to your new, edited question, the best answer I have is to use <code>to_csv</code> instead of <code>to_string</code>. <code>to_string</code> doesn't really support this use case as well as <code>to_csv</code> (and I don't see how I can save you from doing a bunch of conversions to an...
python|pandas|dataframe
2
6,932
71,265,442
Convert JSON to CSV but each json object should be contained in one row
<p>I want to convert my json file which has multiple jsons into a csv such that each json is in one column. I don't want to convert it such that each field in json is a seperate column. So there will be only one column and the entire json object is stored as string in it.</p> <p>Sample JSON file:</p> <pre><code>[ {&quo...
<p>Use:</p> <pre><code>import pandas as pd js = [ {&quot;Name&quot; : &quot;abcd&quot;,&quot;Id&quot; : &quot;123&quot;} , {&quot;Name&quot; : &quot;efgh&quot;,&quot;Id&quot; : &quot;124&quot;} ] df = pd.DataFrame([str(x) for x in js], columns = ['data']) </code></pre> <p>output:</p> <p><a href="https://i.stack.imgur....
python|json|pandas|csv
0
6,933
71,226,400
Drop Duplicate Rows in Excel based on Column Data in Pandas
<p>I am attempting to use pandas to drop duplicate entries in an excel document based on very specific conditions. Here is an excerpt from my dataframe:</p> <pre><code> WD MSN TAIL REV 3425 30-11-11 26154 N754CX IR 3426 30-21-11 26154 N754CX IR 3427 31-31-11 26154 N754CX IR 3428 31-31-41 26154...
<p>A partial answer that assumes that the last entry is the newest.</p> <pre><code>&gt;&gt;&gt; df.groupby([&quot;WD&quot;, &quot;MSN&quot;]).tail(1) WD MSN TAIL REV 3425 30-11-11 26154 N754CX IR 3426 30-21-11 26154 N754CX IR 3427 31-31-11 26154 N754CX IR 3429 31-31-41 26154 N754CX B ...
python|pandas|duplicates|boolean
0
6,934
52,302,474
pandas regex new column nan - but regex tester shows regex is valid
<p>I have a csv of error messages from test regression failures and I'm importing it into a pandas dataframe, but I want to find some substrings pertaining to the exceptions, specifically. </p> <p>I populate my dataframe with the contents of the .csv like so:</p> <pre><code>df = pd.read_csv('ErrorMessage3.csv', heade...
<pre><code>teststring1 = &quot;&quot;&quot;Step 13 - Iteration 1 Failed: Action: &lt;Update Latest CC Exp Date Record from Epay Account {DBServer;UserName;Password='', DatabaseName='',Year Offset='-10'}&gt; ---&gt; System.Data.SqlTypes.SqlNullValueException1: Data is Null. This method ...
python|regex|pandas|dataframe
1
6,935
60,631,279
Not able to get tensorflow-go
<p>Im trying to make api for my ML model but Im not able to install the go package for this. Im getting this error:</p> <pre><code>go get github.com/tensorflow/tensorflow/tensorflow/go </code></pre> <pre><code>package github.com/tensorflow/tensorflow/tensorflow/go/core/core_protos_go_proto: cannot find package "githu...
<p>That's a well-known issue that isn't going to be fixed (it seems).</p> <p>So I decided to maintain a fork that fixes the problem <a href="https://github.com/galeone/tensorflow" rel="nofollow noreferrer">https://github.com/galeone/tensorflow</a></p> <pre><code>go get github.com/galeone/tensorflow/tensorflow/go@r2.4-g...
tensorflow|go|machine-learning
0
6,936
60,480,780
How to make dataframeA None if A's Id exist in B
<p>dataframeA, dataframeB<br/> Id, name <br/></p> <p>if I want to make dataframeA's name None if Id exist in dataframeB</p> <p>dataframA <br></p> <pre><code>ID, name 1 jake 2 kim </code></pre> <p>dataframe B <br/></p> <pre><code> ID, name 1, None </code></pre> <p>result <br/></p> <pre><code>ID, name 1...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html" rel="nofollow noreferrer"><code>Series.mask</code></a>:</p> <pre><code>dfa['name'] = dfa['name'].mask(dfa['ID'].isin(dfb['ID']), None) </code></pre> <p>or</p> <pre><code>dfa.loc[dfa['ID'].isin(dfb['ID']), 'name'] = No...
python|python-3.x|pandas|dataframe|data-science
1
6,937
60,563,566
pivot data frame in pandas?
<pre><code>people1 trait1 YES people1 trait2 YES people1 trait3 NO people1 trait4 RED people2 trait1 NO people2 trait2 YES people2 trait4 BLACK </code></pre> <p>etc..</p> <p>It's possible to create from that table something like this?</p> <pre><code> trait1, trait2, trait3, trait4 ... people1 YES YES ...
<p>I think problem is missing values in column <code>trait</code>, so <code>join</code> function failed. So possible solution is replace missing values to empty strings:</p> <pre><code>print (data1) 1 name trait 0 p1 YES NaN &lt;- missing value 1 p1 BLACK t2 2 p1 NO t3 3 p2 NO t1 4 p2...
python|pandas|dataframe
1
6,938
72,601,854
Manipulating DataFrame
<p>I have the following dataframe <code>df</code> where there are 3 columns: Date, value and topic. I want to create a new dataframe <code>df1</code> where the topic is the column and is indexed by day, and each topic has its own value per day. My problem is that I don't know how to match the value to the topic per day...
<pre><code>df1 = (df.assign().pivot_table(index='Date', columns='Topic', values='Val')) </code></pre> <p>Output</p> <pre><code>Topic 0 1 2 3 4 Date 2015-02-24 00:00:00 ...
python|pandas|dataframe|numpy
0
6,939
72,774,839
Find the third vertex of an equilateral trainable given two N-dimensional verteces in python
<h2><strong>Given:</strong></h2> <p>Two vertices of an equilateral trainable as A,B ∊ R<sup>N</sup> when N &gt; 1.</p> <h2><strong>Goal:</strong></h2> <p>Find the third vertex Z ∊ R<sup>N</sup> in which <code>||A-B|| = ||A-Z|| = ||B-Z||</code>.</p> <p>I have the following python script from <a href="https://stackoverfl...
<p>You can use a general function to find a perpendicular to a vector based on <a href="https://math.stackexchange.com/a/3175858">this method</a>. Then you just add a perpendicular vector of the right length to the midpoint of the first two vertices. As noted in comments, there are an infinite number of vertices that w...
python|numpy|math|geometry|triangle
0
6,940
59,699,577
Failure on Pandas Installation Using PyPy interpreter on PyCharm
<p>I've been trying to install pandas using the PyPy interpreter on Pycharm on a windows machine. I've troubleshooted the issues online extensively and can't resolve it. I've used the built in Pycharm module installer and also the CMD window. I've tried with and without the no-cache-dir command. I've installed microsof...
<p>The problem is that pandas wants numpy, numpy installation is failing to find your compiler: <code>error: Microsoft Visual C++ 14.1 is required.</code>. </p> <p>You might want to update setuptools (the module that looks for the compiler) via <code>pip install --upgrade setuptools</code>. Hopefully you are using the...
python|pandas|pip|pypy
1
6,941
59,650,713
Why does my line fit result in a gradient of np.nan when line fitting in Log-Log scale?
<p>I'm trying to find the gradient under which my graph is plotted whilst line fitting in the double log scale. Therefore I've written the function below.</p> <pre class="lang-python prettyprint-override"><code>def calc_coefficients_signal_shift(n: int, N: int, num: int, shift: int, operations: int): wnss = white_...
<p>After some research, I found out that <code>slope_loglog</code> was defined incorrectly. The way it was defined was correct for plotting a straight line in the double-log graph, but since I was studying power-law behavior I needed to use the power-law formula. So, <code>slope_loglog</code> became <code>c * x ** m</c...
python|numpy|signal-processing|curve-fitting
0
6,942
32,365,668
array passing between numpy and cython
<p>I would like to pass an numpy array to cython. The Cython C type should be float. Which numpy type do I have to choose. When I choose float or np.float, then its actually a C double.</p>
<p>You want <code>np.float32</code>. This is a 32-bit C <code>float</code>.</p>
numpy|cython
1
6,943
32,528,850
how to sort descending an alphanumeric pandas index.
<p>I have an pandas data frame that looks like:</p> <pre><code>df = DataFrame({'id':['a132','a132','b5789','b5789','c1112','c1112'], 'value':[0,0,0,0,0,0,]}) df = df.groupby('id').sum() value id a132 0 b5789 0 c1112 0 </code></pre> <p>I would like to sort it so that it looks like:</p> ...
<p>Categoricals provide a reasonably easy way to define an arbitrary ordering</p> <pre><code>In [35]: df['id'] = df['id'].astype('category') In [39]: df['id'] = (df['id'].cat.reorder_categories( sorted(df['id'].cat.categories, key = lambda x: int(x[1:]), reverse=True))) In [40]: df.groupby('i...
python|sorting|pandas
2
6,944
32,231,547
Saving Python Numpy Structure As MySQL Blob
<p>One of my programs creates a very large numpty array that I wish to save as a Blob within a database as accessing the array is far faster than going back to the previous level and creating it. I can add it to the database by saving an .npz file to disc using:-</p> <pre><code>import numpy as n n.savez(outfile,**kwar...
<p>I know this is quite some time later - I was able to do this using pandas <code>pd.to_sql</code>. Say I have some numpy array <code>x</code> that I want to insert as a blob column. Then you can do the following:</p> <pre><code>row = [x.dumps()] data = pd.DataFrame(row, columns = ['myBlob']) data.to_sql(name = "myTa...
python|mysql|numpy
1
6,945
32,573,868
What is the proper way to create a numpy array of transformation matrices
<p>Given a list of rotation angles (lets say about the X axis):</p> <pre><code>import numpy as np x_axis_rotations = np.radians([0,10,32,44,165]) </code></pre> <p>I can create an array of matrices matching these angles by doing so:</p> <pre><code>matrices = [] for angle in x_axis_rotations: matrices.append(np.as...
<p>Here's a direct and simple approach:</p> <pre><code>c = np.cos(x_axis_rotations) s = np.sin(x_axis_rotations) matrices = np.zeros((len(x_axis_rotations), 3, 3)) matrices[:, 0, 0] = 1 matrices[:, 1, 1] = c matrices[:, 1, 2] = -s matrices[:, 2, 1] = s matrices[:, 2, 2] = c </code></pre> <hr> <p>timings, for the...
python|arrays|performance|numpy|matrix
3
6,946
40,731,524
UnicodeDecodeError: ('utf-8' codec) while reading a dta file in Pandas
<p>I am trying to open a <code>dta</code> file with Pandas but get a <code>UnicodeDecodeError</code>:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; pd.read_stata('/some/stata/file.dta',encoding='utf8') # I've tried 'utf8', "ISO-8859-1", 'latin1', 'cp1252' and not putting in anything, same error. Traceb...
<p>A fix was committed to master on Github and should be released with version <code>0.25</code>.</p> <p>See details about this issue <a href="https://github.com/pandas-dev/pandas/issues/25960" rel="nofollow noreferrer">here</a>.</p> <p>For a temporary fix, change line <code>1334</code> of <code>pandas.io.stata</code...
python|pandas|utf-8|stata
0
6,947
61,995,249
Cant train tensorflow ssd_mobilenet_v2.Failed to get matching files
<p>After successfully training the <code>faster_rcnn_inception_v2_coco_2018_01_28</code> model on a custom data set and getting good results, I attempted to use the <code>ssd_mobilenet_v2_quantized_300x300_coco</code> model using the same dataset and following the same tutorial linked below. I get this error when tryin...
<p>There is a rouge whitespace in the tutorial if followed exactly as is. this was causing the error. </p> <p>Line 156. Change fine_tune_checkpoint to: "C:/tensorflow1/models/research/object_detection/ ssd_mobilenet_v2_quantized_300x300_coco_2019_01_03/model.ckpt"</p>
python|tensorflow|object-detection|google-coral
0
6,948
61,678,885
How to calculate the sum of rows with the maximum date country wise
<p>I am trying to calculate the sum of the rows with the maximum date per country and if the country has more than one province then it should add the confirmed cases with the maximum date . For ex <a href="https://i.stack.imgur.com/KAqc6.jpg" rel="nofollow noreferrer">input</a> This is the input that I have and the o...
<p>The strategy is to sort the values such that the last date is the first row of the Country/Region-Province/State pairs, then roll up the dataset twice, filtering the max date between roll ups.</p> <p>First, sorting to put most recent dates at the top of each group:</p> <pre><code>(df .sort_values(['Country/Region...
pandas|dataframe
1
6,949
61,766,636
adding percentage column by value in a column
<p>I'm trying encoding categorical column value to percentage frequency (binary encoding) as new feature.</p> <pre><code>Value Count Frequency (%) 20190 14723 16.2% 20100 11235 12.4% 20120 9449 10.4% 20130 7744 8.5% 20210 5920 6.5% 20140 5192 5.7% 20270 432...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> for new column:</p> <pre><code>s = df1['A_group_of_materials'].value_counts(normalize=True) * 100 df1['binary_group_of_materials'] = df1['A_group_of_materials'].map(s)...
python|pandas|encoding|categorical-data|feature-selection
0
6,950
57,793,718
Iterate through two columns and match values from different rows in pandas
<p>My pandas DataFrame looks like this:</p> <pre><code> ID NAME PARENT_ID 0 1 Fruits 0 1 2 Bananas 1 2 3 Apples 1 3 4 Peaches 1 4 ...
<p>As per @user3483203 's answer:</p> <pre><code>df['PARENT'] = df['PARENT_ID'].map(df.set_index('ID')['NAME']) </code></pre>
python|pandas
1
6,951
58,081,592
Pandas calculate average value of column for rows satisfying condition
<p>I have a dataframe containing information about users rating items during a period of time. It has the following semblance : <a href="https://i.stack.imgur.com/8rytV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8rytV.png" alt="enter image description here" /></a></p> <p>In the dataframe I ha...
<p>Se if you do have a dataframe looks like </p> <pre><code> review_id user_id business_id stars date 0 1 0 3 2.0 2019-01-01 1 2 1 3 5.0 2019-11-11 2 3 0 2 4.0 2019-10-22 3 4 3 4 3.0 ...
python|pandas
0
6,952
34,065,412
np.vectorize giving me IndexError: invalid index to scalar variable
<p>trying out something simple and it's frustratingly not working:</p> <pre><code>def myfunc(a,b): return a+b[0] v = np.vectorize(myfunc, exclude=['b']) a = np.array([1,2,3]) b = [0] v(a,b) </code></pre> <p>This gives me "IndexError: invalid index to scalar variable." Upon printing b, it appears that the b taken...
<p>When you use <code>excluded=['b']</code> the <em>keyword</em> parameter <code>b</code> is excluded. Therefore, you must call <code>v</code> with keyword arguments, e.g. <code>v(a=a, b=b)</code> instead of <code>v(a, b)</code>. </p> <p>If you wish to call <code>v</code> with positional arguments with the second posi...
python|numpy
8
6,953
34,085,823
how to assign non contiguous labels of one numpy array to another numpy array and add accordingly?
<p>I have the following labels</p> <pre><code>&gt;&gt;&gt; lab array([3, 0, 3 ,3, 1, 1, 2 ,2, 3, 0, 1,4]) </code></pre> <p>I want to assign this label to another numpy array i.e</p> <pre><code>&gt;&gt;&gt; arr array([[81, 1, 3, 87], # 3 [ 2, 0, 1, 0], # 0 [13, 6, 0, 0], # 3 [14, 0, ...
<p>You could use <code>groupby</code> from <a href="http://pandas.pydata.org/" rel="nofollow"><code>pandas</code></a>:</p> <pre><code>import pandas as pd parr=pd.DataFrame(arr,index=lab) pd.groupby(parr,by=parr.index).sum() 0 1 2 3 0 2 0 1 0 1 0 0 0 0 2 0 0 0 0 3 108 7 4 117 4 ...
python-3.x|numpy
1
6,954
37,095,161
Number of rows changes even after `pandas.merge` with `left` option
<p>I am merging two data frames using <code>pandas.merge</code>. Even after specifying <code>how = left</code> option, I found the number of rows of merged data frame is larger than the original. Why does this happen?</p> <pre><code>panel = pd.read_csv(file1, encoding ='cp932') before_len = len(panel) prof_2000 = pd....
<p>This sounds like having more than one rows in <code>right</code> under <code>'name2'</code> that match the key you have set for the <code>left</code>. Using option <code>'how='left'</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noreferrer"><code>pandas.D...
python|pandas
44
6,955
37,086,677
Pandas pivot table with mean
<p>I have a pandas data frame, df, that looks like this;</p> <pre><code>index New Old MAP Limit count 1 93 35 54 &gt; 18 1 2 163 93 116 &gt; 18 1 3 134 78 96 &gt; 18 1 4 117 81 93 &gt; 18 1 5 194 108 136 &gt; 18 ...
<h3>Solution</h3> <pre><code>df.groupby('Limit')['New', 'Old', 'MAP'].mean().T Limit &lt;= 18 &gt; 18 New 108.5 121.615385 Old 56.0 72.769231 MAP 73.0 88.692308 </code></pre>
python|pandas
4
6,956
36,694,549
Access line by line to a numpy structured array
<p>I am trying to access to a structured array line by line by iterating on the values of one field of it but even if the value iterate well, the slice of the array doesn't change. Here is my SWE :</p> <pre><code>import numpy as np dt=np.dtype([('name',np.unicode,80),('x',np.float),('y',np.float)]) a=np.array( [('a',0...
<p>The last line is not right. The array index evaluates to True or False rather than doing a lookup of a named column. Try this:</p> <pre><code>for n in a['name']: print n,a[a['name']==n] </code></pre>
python|arrays|numpy|structured-array
4
6,957
36,931,732
Creating a numpy array fails when I try to create from an array of QString
<p>If the array has a size of 2x2 or greater all is well, but if the dimension of the row is 1, for example 1x2, numpy does something I did not expect.</p> <p>How can I solve this?</p> <pre><code># TEST 1 OK myarray = np.array([[QString('hello'), QString('world')], [QString('hello'), QString('moon...
<p>Try different length strings: </p> <pre><code>np.array([[QString('hello'), QString('moon')]], dtype=object)`. </code></pre> <p>or the create and fill approach to making an object array</p> <pre><code>A = np.empty((1,2), dtype=object) A[:] = [QString('hello'), QString('moon')] </code></pre> <p>I'm not familiar ...
python|numpy|pyqt4
2
6,958
54,811,207
Using Distributed Tensorflow on a Keras model on GCP Dataproc
<p>I am completely new to cloud computing on GCP Dataproc. I installed TonY (Tensorflow on Yarn) when I was creating my cluster in order to be able to run tensorflow on it. </p> <p>I am stuck on the part where I create the tf.train.ClusterSpec portion in order to run distributed tensorflow on my keras model. It seems ...
<p>In order to access your Cluster configuration, please use <code>CLUSTER_SPEC</code> from your TensorFlow code. You can follow <a href="https://github.com/linkedin/TonY/blob/master/tony-examples/mnist-tensorflow/mnist_distributed.py#L191" rel="nofollow noreferrer">this</a> working example:</p> <pre><code> cluster...
tensorflow|keras|google-cloud-platform|google-cloud-dataproc|tony
3
6,959
49,738,489
Python Filter multiple row
<p>I am using this query script to get data from api rest.</p> <p><a href="https://github.com/cubewise-code/TM1py-samples/blob/master/Query%20Data/cube%20data%20into%20pandas%20dataframe.py" rel="nofollow noreferrer">Script</a></p> <p>After doing this, I got the following data:</p> <p><a href="https://i.stack.imgur....
<p>You have 2 options to filter a MultiIndex dataframe:</p> <p><strong>1. Elevate index to columns and filter by columns</strong></p> <pre><code>df = df.reset_index() df1 = df[(df['Meses'] != 'Total') &amp; (df['Orcado x Realizado'] == 'Realizado')] </code></pre> <p><strong>2. Filter by index directly</strong></p> ...
python|pandas|numpy|data-manipulation
1
6,960
28,099,881
How can I install matplotlib for my AWS Elastic Beanstalk application?
<p>I'm having a hell of a time deploying matplotlib on AWS Elastic Beanstalk. <a href="https://stackoverflow.com/a/15881797/656912">I gather</a> that my issue comes from some dependencies and the way that EB deploys packages installed with PIP, and have attempted to follow the <a href="https://stackoverflow.com/a/15881...
<p>I have used many approaches to build and deploy numpy/scipy/matplotlib, on Windows as well as Linux systems. I have used system-provided package managers (aptitude, rpm), 3rd-party package managers (pypm), Python package managers (easy_install, pip), source releases, used different build environments/tools (GCC, but...
numpy|amazon-web-services|matplotlib|pip|amazon-elastic-beanstalk
5
6,961
28,111,791
Conditional selection of data in a pandas DataFrame
<p>I have two columns in my pandas DataFrame.</p> <pre><code> A B 0 1 5 1 2 3 2 3 2 3 4 0 4 5 1 </code></pre> <p>I need the value in A where the value of B is minimum. In the above case my answer would be 4 since the minimum B value is 0.</p> <p>Can anyone help me with it?</p>
<p>To find the minimum in column B, you can use <code>df.B.min()</code>. For your DataFrame this returns <code>0</code>.</p> <p>To find values at particular locations in a DataFrame, you can use <code>loc</code>:</p> <pre><code>&gt;&gt;&gt; df.loc[(df.B == df.B.min()), 'A'] 3 4 Name: A, dtype: int64 </code></pre> ...
python|pandas|dataframe|min
5
6,962
35,051,651
how to get a random sample in a multiindex pandas dataframe?
<p>I have a dataframe that is indexed according to the following variables: NAME - date. Name is some sort of bizarre ID, and date is.. a date.</p> <p>The data is very large and I would like to inspect the data I have for several random choices of NAME. </p> <p>That is, </p> <ol> <li>pick a random NAME among the pos...
<pre><code>import pandas as pd import numpy as np import random import string df = pd.DataFrame(data={'NAME': [''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(17)) for _ in range(10)], 'Date': pd.date_range('1/01/2016', periods=10), 'Whateve...
python|pandas|random
2
6,963
31,148,758
python pandas create correlation matrix from price dataframe
<p>I have a dataframe populated with stock price returns (indexed by Date). Could someone let me know how I can get a correlation matrix from this dataframe.</p> <p>The dataframe would look like:</p> <pre><code> BBG.XSTO BBG.XLON BBG.XETR BBG.XHEL Date 06/02/2014 0.001418 0.00708 0.019437 ...
<p>Assuming your dataframe is named <code>df</code>.</p> <pre><code>df.corr() Out[106]: BBG.XSTO BBG.XLON BBG.XETR BBG.XHEL BBG.XSTO 1.0000 0.5801 0.3057 0.7185 BBG.XLON 0.5801 1.0000 0.1709 0.5366 BBG.XETR 0.3057 0.1709 1.0000 0.3340 BBG.XHEL 0.7185 0.5366 0....
python|pandas
1
6,964
31,050,714
pandas 'as_index' function doesn't work as expected
<p>This is a minimum reproducible example of my original dataframe called 'calls':</p> <pre><code> phone_number call_outcome agent call_number 0 83473306392 NOT INTERESTED orange 0 1 762850680150 CALL BACK LATER orange 1 2 476309275079 NOT INTERESTED orange ...
<p>I believe that, irrespective of the <code>groupby</code> operation you've done, you just need to call <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> to say that the index column should just be a regular column.</p> <p>Starti...
python|pandas
4
6,965
31,030,096
Concatenating url pages as a single Data Frame
<p>I'm trying to download historic weather data for a given Location. I have altered an example given at <a href="http://flowingdata.com/2007/07/09/grabbing-weather-underground-data-with-beautifulsoup/" rel="nofollow">flowingdata</a> but I've stuck in the last step - how to concate multiple <code>Data Frames</code></p>...
<p>You should declare a list outside your loop and append to this then outside the loop you want to concatenate all the dfs into a single df:</p> <pre><code>import pandas as pd frames = pd.DataFrame(columns=['TimeEET', 'TemperatureC', 'Dew PointC', 'Humidity','Sea Level PressurehPa', 'VisibilityKm', 'Wind Dir...
python|pandas
3
6,966
67,356,885
How do I forward propagate in just subset of Dataframe columns with inplace=True?
<p>I want to fill missing values with fillna() and &quot;inplace=True&quot;. How do I forward propagate values in just two columns of a Dataframe that has more than two columns? Thanks</p>
<p>I don't believe there is a way to forward propagate a column subset with <code>method='ffill'</code> and <code>inplace=True</code>.</p> <p>You'll have to use assignment, e.g. for columns <code>A</code> and <code>D</code>:</p> <pre class="lang-py prettyprint-override"><code>df[['A','D']] = df[['A','D']].fillna(method...
python|pandas|missing-data
1
6,967
67,279,026
How to upload pandas, sqlalchemy package in lambda to avoid error "Unable to import module 'lambda_function': No module named 'importlib_metadata'"?
<p>I'm trying to upload a deployment package to my AWS lambda function following the article <a href="https://korniichuk.medium.com/lambda-with-pandas-fd81aa2ff25e" rel="nofollow noreferrer">https://korniichuk.medium.com/lambda-with-pandas-fd81aa2ff25e</a>. My final zip file is as follows: <a href="https://drive.google...
<p>There is a <a href="https://github.com/keithrozario/Klayers" rel="nofollow noreferrer">third party github repo</a> with public layers, including pandas. You don't have to do anything to use, except adding the layer arn to your function. The arn <a href="https://github.com/keithrozario/Klayers/tree/master/deployments...
python|pandas|amazon-web-services|lambda|aws-lambda
2
6,968
67,530,273
Interactive error when plotting the decision tree classifier, get an array of values.. makes the tree very hard to visualize
<p>This is the code needed to reproduce the decision tree classifier tree that gives far too many values to interpret the graph, I would like to avoid the overt array of values for a more simple value array if possible. Most of this code is needed for the processing of the dataset before attempting to plot the tree.</p...
<p>Your target variable, <code>Response Days</code>, has lots of unique values, so using a classifier means each leaf keeps track of how many samples of each are there, hence the long lists. You probably would rather use a regression model, and if you do that the reported value of each leaf is just the (single!) avera...
python|pandas|scikit-learn|decision-tree|pygraphviz
0
6,969
67,530,483
Why does keras neural network predicts the same number for all different images?
<p>I'm trying to use keras neural network of tensorflow to recognize the handwriting digit number. But idk why when i call <code>predict()</code>, it returns same results for all of input images.</p> <p>Here is code:</p> <pre><code> ### Train dataset ### mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test,...
<p>Normalize your data in inference time same what you did on the training set</p> <pre><code>img = np.array([img]) / 255 </code></pre> <p>Check <a href="https://stackoverflow.com/a/66191381/9215780">this answer (Inference)</a> for more details.</p> <hr /> <p>Based on your 3rd comment, here are some details.</p> <pre><...
python|tensorflow|keras|neural-network|handwriting-recognition
1
6,970
67,403,569
Get date that is closest to given timestamp from two series python pandas
<p>I have a series of timestamps called <code>dates</code> that look as such:</p> <pre><code>1 2021-04-21 09:34:00+00:00 2 2021-04-21 10:30:02+00:00 3 2021-04-21 15:54:00+00:00 4 2021-04-22 18:33:57+00:00 5 2021-04-23 18:48:04+00:00 </code></pre> <p>I am trying to find the closest date from another series cal...
<p>Thanks @Quang Hoang, merge_asof worked. Since it was new to me as well, I tried it out and here's the result.</p> <p>First get the df from the question and reformat type to match the type in &quot;PublishTime&quot; series</p> <pre><code>df = pd.DataFrame({'dates': [&quot;2021-04-21 09:34:00+00:00&quot;, &quot;2021-0...
python|pandas|datetime
1
6,971
67,584,691
Working with webp and jpeg images have different number of channels
<p>I'm working with computer vision project, where my images are combination of webp and jpeg. I'm using tensorflow '2.3.2'<br /> You can think my directories like this :</p> <pre><code>IMAGES |-img1.jpeg |-img2.webp </code></pre> <p>For reading webp, I use <a href="https://www.tensorflow.org/io/api_docs/python/tfio/...
<p>If you want to train a single model with both <em>*.jpeg</em> and <em>*.webp</em> images then you should create the same input layer layout for both.</p> <p>To do so, you basically need to convert either RGB to RGBA or (what I would do) RGBA to RGB. If you want to simply drop the alpha-channel you can use tensorflow...
python|tensorflow
0
6,972
34,826,371
Add header to np.matrix
<p>I am trying to export a numpy matrix to ASCII format, but I want to add a header to it first.</p> <p>My code concept is this:</p> <ol> <li>Import ASCII file as np.ndarray, say matrix A </li> <li>Take the header of A (first 6 rows). The header contains both float values and characters</li> <li>Take the rows of A t...
<p>The problem is that your header has not the same format than data.</p> <p>A way to solve that : Treat header as a normal file text, and data as numeric.</p> <pre><code>with open('chm_plot_1_sample.txt') as f : header="".join([f.readline() for i in range(6)])[:-1] a=np.loadtxt('chm_plot_1_sample.txt',delimit...
python|arrays|numpy|ascii
1
6,973
65,204,523
TypeError: backward() got an unexpected keyword argument 'grad_tensors' in pytorch
<p>I have the following</p> <pre><code>w = torch.tensor([1.], requires_grad=True) x = torch.tensor([2.], requires_grad=True) a = torch.add(w, x) b = torch.add(w, 1) y0 = torch.mul(a, b) # y0 = (x+w) * (w+1) y1 = torch.add(a, b) # y1 = (x+w) + (w+1) loss = torch.cat([y0, y1], dim=0) # [y0, y1] weig...
<p>You are calling the <a href="https://pytorch.org/docs/stable/_modules/torch/tensor.html#Tensor.backward" rel="nofollow noreferrer"><code>torch.Tensor.backward</code></a>, not <code>torch.autograd.backward</code>.</p> <p>As for your second question about the difference b/w the two, <code>torch.Tensor.backward</code>...
python-3.x|pytorch|gradient
3
6,974
65,113,529
How did the number of elements in each array end up being less than they were in their parent array (array of arrays)
<p>This problems seems to go away when I dont use <strong>shuffle(train_data)</strong>. I also tried doing <strong>shuffle(train_data_1)</strong> and <strong>shuffle(train_data_2)</strong> seperately but in that case too, the distribution seems to change.</p> <pre><code>import numpy as np import pandas as pd from colle...
<p>Dont use shuffle(train_data) instead after the formation of forwards, lefts and rights array, use shuffle() on them individually.</p> <pre><code>shuffle(forwards) shuffle(lefts) shuffle(rights) </code></pre> <p>Now there isn't any problem with the distribution and shuffling is also performed correctly.</p>
python|arrays|pandas|numpy|dataframe
0
6,975
49,844,290
TensorFlow saving model - Paradoxical exception
<p>I've tried to save a basic MNIST model:</p> <pre><code>from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import tensorflow as tf sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, sh...
<p>Here is an extract of your code</p> <pre><code>saver.save(sess, './mnist_to-save-saved') for _ in range(1000): batch = mnist.train.next_batch(100) train_step.run(feed_dict={x: batch[0], y_: batch[1]}) correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correc...
python|tensorflow|save
8
6,976
50,192,731
IOError: [Errno 21] Is a directory: '/tmp/speech_dataset/'
<p>I'm following the speech recognition tutorial from TensorFlow(link: <a href="https://www.tensorflow.org/versions/master/tutorials/audio_recognition#advanced_training" rel="nofollow noreferrer">https://www.tensorflow.org/versions/master/tutorials/audio_recognition#advanced_training</a>), and when I'm running the foll...
<p>OK, I solved the problem, so I'm posting it here if anyone runs to the same problem.</p> <p>There was some confusion with the TensorFlow documentation. I thought that the <code>--data-url</code> argument should get the path to my data set, but this argument should only be used whenever you want to download some dat...
python|tensorflow|machine-learning|io
1
6,977
49,976,550
convolutional neural network image recognition
<p>Currently I am working on a project with convolutional network using tensorflow and I have set up the network and now i need to train it. I don't have a clue of how could the image should be for training. Like how much of % of the image the object is training on. It's a cigarette that I have to detect and I have tr...
<p>The object you are trying to recognise is too small. In the <a href="https://imgur.com/a/KjTfes4" rel="nofollow noreferrer">Sample</a>, I think first one will be the best bet for you. Convolution neural network works by doing convolution operations on image pixels. In the second picture, background is too large comp...
tensorflow
0
6,978
50,025,451
Issue installing pip and pandas
<p>I am trying to install Pandas with Pip and am running into some strange issues. Command prompt reported that pip is an unrecognized command. I thought that was strange, but decided to definitively remedy that by installing pip with the following commands:</p> <pre><code>curl https://bootstrap.pypa.io/get-pip.py -...
<p>The <code>pip</code> command is not found because it's not in your path. </p> <p>You should add the following to your <code>PATH</code> environment variable:</p> <pre><code>;%PYTHON_HOME%\;%PYTHON_HOME%\Scripts\ </code></pre> <p>A simple Google search should help you find how to change environment variables for y...
python|pandas|pip
2
6,979
63,821,088
how to continue pulling data from a server like binance?
<p>I am trading on binance, I have a code that pulling data for 5 minutes candle (for example), when I click on run code, it will collect data, but how to continue pulling also for new candles ? this is my code:</p> <pre><code>import binance.client from binance.client import Client import pandas as pd import numpy as ...
<p>As @Selcuk mentioned is his comment, you can loop the binance read and pause between each read. In your case, you are retrieving data at 5 minute intervals, so you can wait 5 minutes before reading again and request the previous 5 minutes. You can append to the initial dataframe using <code>append</code>.</p> <p>Try...
python|pandas|algorithm|algorithmic-trading
1
6,980
63,860,201
Safe data retrieved from multiple pages from API
<p>I found a solution to print data from several pages from an api:</p> <pre><code>for page in range(1, 3): url = &quot;https://www.balldontlie.io/api/v1/players?page={}&quot;.format(page) ot_data_response = requests.get(url) ot_data = ot_data_response.text ot_dataparsed = json.loads(ot_data) ot_dat...
<p>You may wish to use <code>pd.concat</code>:</p> <pre><code>pd.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, copy=True) </code></pre> <p>For your case, it should be sth like this:</p> <pre><code>json_df_list = [] for page in range(1, 3): url = &...
python|pandas|api|python-requests
1
6,981
64,148,319
CSV to JSON output only if all values are present in CSV
<p>I have a concatenated CSV file that I am attempting to output into JSON format. How should I go about implementing the logic that the CSV file only get converted to a JSON object all fields have a value ?</p> <pre><code>import glob , os import pandas as pd import json import csv with open('some.csv', 'r', newline...
<p>First I loop through all the elements of <code>CSV</code> and add it to a <code>JSON array</code>. If any row element <code>value is empty</code>, that row will be <code>ignored</code>. Once I have the all rows in the <code>JSON array</code>, I will output it to the <code>JSON</code> file</p> <pre><code>import json ...
python|json|pandas|dataframe|csv
0
6,982
47,004,304
How to combine two data columns in pandas?
<p>I have two tables, like below. I want to merge two table into 1. I tried to merge,concat, join in panda but it gives a new table of height 20, I want to have a height of 10 in the new combined table. How to do this one panda data frames? <a href="https://i.stack.imgur.com/SML9N.png" rel="nofollow noreferrer"><img s...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <code>axis=1</code>:</p> <pre><code>df = pd.concat([df1, df2], axis=1) </code></pre>
pandas
1
6,983
46,938,530
Produce balanced mini batch with Dataset API
<p>I've a question about the new dataset API (tensorflow 1.4rc1). I've a unbalanced dataset wrt to labels <code>0</code> and <code>1</code>. My goal is to create balanced mini batches during the preprocessing.</p> <p>Assume I've two filtered datasets:</p> <pre><code>ds_pos = dataset.filter(lambda l, x, y, z: tf.resha...
<p>You are on the right track. The following example uses <code>Dataset.flat_map()</code> to turn each pair of a positive example and a negative example into two consecutive examples in the result:</p> <pre><code>dataset = tf.data.Dataset.zip((ds_pos, ds_neg)) # Each input element will be converted into a two-element...
tensorflow|tensorflow-datasets
7
6,984
46,649,363
Removing inf/nan values from Pandas
<p>I'm aware that there are several posts about this, but none of the solutions seem to work and I can't figure out what I'm doing wrong.</p> <p>My dataframe has data with inf values.</p> <pre><code>print [x for x in train_x['meh'] if not np.isfinite(x)] </code></pre> <p>returns</p> <pre><code>[inf, inf, inf, inf, ...
<p>Seems like you can just use boolean indexing</p> <pre><code>train_x[np.isfinite(train_x) &amp; train_x.notnull()] </code></pre> <p>You actually don't even need the <code>train_x.notnull()</code>.</p>
pandas|numpy
0
6,985
63,073,304
How to edit mnist dataset?
<p>I want to have digit 0 to 5 in the &quot;mnist dataset&quot;. How can I do this on python? I try to solve this problem with numpy.delete, but it didn't work.</p>
<p>Assuming you have the images stored in a numpy array of shape <code>(num_examples, num_pixels)</code> and the labels stored in an array of shape <code>(num_examples,)</code>, you can do this:</p> <pre><code>images = images[labels &lt;= 5].copy() labels = labels[labels &lt;= 5].copy() </code></pre>
python|numpy|keras|dataset|mnist
1
6,986
67,756,332
Error creating model "segmentation_models" in Keras
<p>A week ago, my Notebook in Google Colaboratory was working fine after installing the following libraries:</p> <pre><code>!pip install te !pip install tensorflow==2.1 !pip install keras==2.3.1 !pip install -U segmentation-models !pip install -U --pre segmentation-models </code></pre> <p>and</p> <pre><code>import ten...
<p>You may need to install <code>h5py</code> of the following version, <a href="https://github.com/qubvel/segmentation_models/issues/424" rel="nofollow noreferrer">source</a>.</p> <pre><code>pip install -q h5py==2.10.0 </code></pre> <p>FYI, I was able to reproduce your error on colab and the above solution resolve this...
python|tensorflow|machine-learning|keras|deep-learning
1
6,987
67,631,375
Concatenating dataframes with a common column
<p>I have 2 data frames with one common column denoting the row number.</p> <pre><code>Df1: Rownum A B C 11 S V L 11 F U M 11 T C O 11 B X P Df2: Rownum E F G 12 S V L 12 F U ...
<p>Remove <code>axis=1</code> in <code>concat</code> with convert <code>Rownum</code> to index for both <code>DataFrames</code>:</p> <pre><code>df = pd.concat([df1.set_index('Rownum'),df2.set_index('Rownum')]).reset_index().fillna('') print (df) Rownum A B C E F G 0 11 S V L 1 11 F U M...
python|pandas|dataframe
0
6,988
67,896,571
Filter by column with rows having multiple value using python
<p>I have data frame as in below and I am filtering by column 'STC' for a value '30'.</p> <p>I am using below code and I am getting empty data frame. How can I get rows with '30' only?</p> <pre><code>STC = [30] (df.loc[df['STC'].isin(STC)]) </code></pre> <pre><code> Code Desc STC ... 0 PUT123 Deduc...
<p>Staged with the assumption that the values in STC are a string of numbers, the example provided does not make them look like lists.</p> <p>You can use str.contains to find matches.</p> <pre><code>import pandas as pd data_dict= {'code': ['PUT123', 'MAT456', 'CAT123'], 'Desc': ['Deduct', 'Coin', 'Copay'], 'STC': ['30...
python|pandas
0
6,989
67,955,351
`np.linalg.solve` get solution matrix?
<p><code>np.linalg.solve</code> solves for x in a problem of the form Ax = b.</p> <p>For my application, this is done to avoid calculating the inverse explicitly (i.e inverse(A)b = x)</p> <p>I'd like to access what the effective inverse is that was used to solve this problem but looking at the <a href="https://numpy.or...
<p>Following the docs and source code, it seems NumPy is calling LAPACK's <code>_gesv</code> to compute the solution, the <a href="https://software.intel.com/content/www/us/en/develop/documentation/onemkl-developer-reference-fortran/top/lapack-routines/lapack-linear-equation-routines/lapack-linear-equation-driver-routi...
python|numpy
1
6,990
67,716,231
How can I print the keys and values of a dictionary by passing a set as an argument?
<p>I have a dictionary containing the names and roll numbers of students namely class_details. And I want to print the roll numbers along with the names of students who are absent, the names of the students who are absent are stored in a set .</p> <p>Source Code :</p> <pre><code>import pandas as pd df = pd.DataFrame({'...
<pre><code># Python program to demonstrate # passing dictionary as argument # A function that takes dictionary # as an argument def func(d): for key in d: print(&quot;key:&quot;, key, &quot;Value:&quot;, d[key]) # Driver's code D = {'a':1, 'b':2, 'c':3} func(D) </code></pre>
python|pandas|dictionary|set
0
6,991
41,298,078
Scipy interp2d interpolate masked fill values
<p>I want to interpolate data (120*120) in order to get output data (1200*1200).</p> <p>In this way I'm using <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.interp2d.html" rel="nofollow noreferrer"><code>scipy.interpolate.interp2d</code></a>.</p> <p>Below is my input data, wher...
<p>I found a solution with <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html" rel="nofollow noreferrer">scipy.interpolate.griddata</a> but I'm not sure that's the best one.</p> <p>I interpolate data with the <code>nearest</code> method parameter which returns the valu...
python|arrays|numpy|scipy|interpolation
1
6,992
41,664,734
Splitting MNIST data tensorflow
<p>I've been following the tensorflow tutorials. I've imported the MNIST dataset and ran the code for a 2 layer convolutional neural net. It took nearly 45 minutes to train. I want to cut down the training data by discarding some of the data. How do I do that? Here's the code:</p> <pre><code>import tensorflow as tf im...
<p>You are using dataset provider defined in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py</a></p> <p>To reduce...
tensorflow|mnist
1
6,993
41,232,621
Python: Error while installing Numpy & Pandas
<p>I am trying to install numpy, scipy and pandas but getting the following error:</p> <pre><code>Aleeshas-MacBook-Air:~ aleesha$ pip install numpy scipy pandas Requirement already satisfied (use --upgrade to upgrade): numpy in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python Requirement alre...
<p>I suggest you install Anaconda, with it you will solve a lot of issues. It supports the latest 3.5 version, comes equipped with most of the data analitics libraries and the ones you dont have you can get with pip install, which is guaranteed to work since pip get comes with Anaconda as well. </p>
python|python-3.x|pandas|numpy|scipy
0
6,994
68,453,360
Change dtype of a Pd DataFrame using a for loop
<p>I have a DataFrame that has 400 columns, and I need to change the dtype from object to categorical for all of the 400 columns, how can I use loops to do that?</p>
<p>Try this:</p> <pre><code>df = df.astype(pd.CategoricalDtype()) </code></pre>
python|pandas|dataframe
1
6,995
68,476,928
matplotlib error : loop of ufunc does not support argument 0 of type float which has no callable rint method
<p>This is my dataSeries : df =</p> <pre><code> count 17 83396.142857 18 35970.000000 19 54082.428571 20 21759.714286 21 16899.571429 22 19870.571429 23 32491.285714 24 40425.285714 25 30780.285714 26 11923.428571 27 13698.571429 28 28028.000000 29 52575.000000 </code></pre...
<p>you want this:</p> <pre><code>_, ax = plt.subplots(1,2) df.plot.pie(ax = ax[1], y = 'count') plt.show() </code></pre> <p>The mistake is you use <code>y=df['count']</code> instead of simply <code>y='count'</code>. You are using pandas plotting and no need to send column values, only column name. Also, you do not need...
python-3.x|pandas|numpy|matplotlib|plot
0
6,996
68,512,301
Python & Pandas: How to address NaN values in a loop?
<p>With Python and Pandas I'm seeking to take values from CSV cells and write them as txt files via a loop. The structure of the CSV file is:</p> <pre><code>user_id, text, text_number 0, test text A, text_0 1, 2, 3, 4, 5, test text B, text_1 </code></pre> <p>The script below success...
<p>The issue here is that you are creating a range index which is not necessarily in the data frame's index. For your use case, you can just iterate through rows of data frame and write to the file.</p> <pre><code>for t in df.itertuples(): if t.text_number: # do not write if text number is None wi...
python|pandas|csv|nan
1
6,997
53,317,172
CSV Data preprocessing and reformatting python
<p>I have a csv file with 22000 rows. I need to convert the csv file from the normal rows and columns format to rows with elements separated with commas using python. Elements with same id are to be in a row. New row is to be created for each id.</p> <p><a href="https://i.stack.imgur.com/tUoxG.png" rel="nofollow noref...
<p>I think you need this,</p> <pre><code>print pd.Series(sum(df.T.values.tolist(),[])).value_counts().reset_index() </code></pre>
python|pandas|csv|numpy
0
6,998
53,042,404
Command Line: Python program says "Killed"
<p>I'm extracting xml data from 465 webpages ,and parsing and storing it in ".csv" file using python dataframe. After running the program for 30 mins, the program saves "200.csv" files and kills itself. The command line execution says "Killed". But when I run the program for first 200 pages and rest of 265 pages for e...
<p>It looks like you are running out of memory.</p> <p>Can you try to increase allowed memory (fast solution)<br> Or optimize your code for less memory consumption (best solution)</p> <p>If speed is not what is required, you can try to save data to temp files and read from them when needed, but I guess that for loop ...
python|xml|linux|pandas|dataframe
4
6,999
65,863,498
Dropping rows with duplicate string values in the DateTimeIndex
<p>This is my first problem! I'll try to explain it as clearly as possible:</p> <p>I have a Series with a DateTimeIndex like this:</p> <p><a href="https://i.stack.imgur.com/YwuxC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YwuxC.jpg" alt="DateTime Series" /></a></p> <hr /> <p>And I need a functio...
<p>Just make a new column, with <code>date</code> instead of <code>datetime</code>, and drop the duplicates based on that column.</p> <p>Create column with Date as type.</p> <pre class="lang-py prettyprint-override"><code>df['Dates'] = df1['DT'].dt.date </code></pre> <p>Drop duplicates based on <strong>Dates</strong> ...
python|pandas|data-manipulation
2