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
20,000
53,013,038
Repartitioning parquet-mr generated parquets with pyarrow/parquet-cpp increases file size by x30?
<p>Using AWS Firehose I am converting incoming records to parquet. In one example, I have 150k identical records enter firehose, and a single 30kb parquet gets written to s3. Because of how firehose partitions data, we have a secondary process (lambda triggered by s3 put event) read in the parquet and repartitions it b...
<p>Parquet uses different column encodings to store low entropy data very efficiently. For example:</p> <ul> <li>It can use delta encoding to only store differences between values. For example <code>9192631770, 9192631773, 9192631795, 9192631797</code> would be stored effectively as <code>9192631770, +3, +12, +2</code...
pandas|parquet|amazon-kinesis-firehose|pyarrow
3
20,001
63,589,204
Filtering dataframe based on variable number of conditions
<p>I have a dataframe like this for example:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'A':['a', 'a', 'b', 'c', 'a', 'b',], 'B': [1, 2, 3, 4, 5, 6,]}) </code></pre> <p>What I need is to filter the df based on the value in column 'A'. The problem is that the values to filter by are supplied ...
<p>You can try with</p> <pre><code>df = df.loc[df['A'].isin(cond)] </code></pre>
python|pandas
2
20,002
63,509,387
Delete column and make next row column?
<p>If I have a column that I want to delete entirely and make the very next row the columns how can I do that?</p> <p>For example if I have</p> <pre><code>unnamed column 0 | unnamed column 1 | unnamed column 2 Year Month Day 1900 04 11 </code></pre> <p>New ...
<p>In case you are using pandas, would this work?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd old_df = pd.DataFrame([[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], [&quot;Year&quot;, &quot;Month&quot;, &quot;Day&quot;], [1990, 4, 11]]) new_df = old_df.loc[2:, :] new_df.columns = old_df.loc[...
python|python-3.x|pandas
3
20,003
63,556,933
Saving oversampled dataset as csv file in pandas
<p>I am new to Python and apologize in advance, if it is too simple. Cannot find anything and <a href="https://stackoverflow.com/questions/58654649/how-to-save-synthetic-dataset-in-csv-file-using-smote">this question</a> did not help.</p> <p>My code is</p> <pre><code># Split data y = starbucks_smote.iloc[:, -1] X = sta...
<p>You may create dataframe:</p> <pre><code>data_res = pd.DataFrame(X) data_res['y'] = y </code></pre> <p>and then save <code>data_res</code> to CSV.</p> <p>Solution based on concatenation od <code>numpy.arrays</code> is also possible, but <a href="https://numpy.org/doc/stable/reference/generated/numpy.vstack.html" rel...
python|pandas|numpy|resampling|smote
3
20,004
63,676,929
How to avoid automatic rounding in pandas
<p>How do I prevent that pandas makes rounding? This is kind of weird because I was coding yesterday and it didn't happen.</p> <p>I have this code:</p> <pre><code>import pandas as pd data = { 1:[1,2,3,4,5], 2:[1,2,3,4,5] } i = ['A','B','C','D','E'] df = pd.DataFrame(data, index=i) print(df) </code></pre> <p>I...
<p>set the datatype to int or int64. have a look here: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dtypes.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dtypes.html</a> you can set the types using <code>dtypes</code> f...
python|pandas
0
20,005
63,660,610
How to perform semi join with multiple columns in pandas?
<p>Let's say I have these two data frames:</p> <pre><code>&gt;&gt;&gt; df1 = pd.DataFrame({'grp':[1,1,2], 'x':[6,4,2], 'y':[7,8,9]}) &gt;&gt;&gt; df1 grp x y 0 1 6 7 1 1 4 8 2 2 2 9 </code></pre> <pre><code>&gt;&gt;&gt; df2 = pd.DataFrame({'grp':[1], 'x':[6], 'z':[3]}) &gt;&gt;&gt; df2 grp x z 0...
<p>Try with <code>tuple</code> and you can still with <code>isin</code></p> <pre><code>df1[df1[['grp','x']].agg(tuple,1).isin(df2[['grp','x']].agg(tuple,1))] Out[205]: grp x y 0 1 6 7 </code></pre>
pandas
3
20,006
63,422,201
Make a np array with one str column and one int column
<p>I like to make a simple 2D array that stores int in one column str in another column. I tried to make an int array first and then, change one column to str. But it did not work:</p> <pre><code>order= np.ones((300,2), dtype=int) order[:,0]=order[:,0].astype(str) </code></pre> <p>I look for a simple way, not merging (...
<p>If you want and array with ones like string and ones like number:</p> <pre><code>order= np.ones((300,2), dtype=object) order[:,0]=&quot;1&quot; order </code></pre> <p>Is it that you want?</p>
python|numpy
1
20,007
30,186,544
Pandas Multi-indexing from a Flatten DataFrame
<p>I want to resample flatten dataframe to multi-indexed columns. Dataframe looks like :</p> <pre><code>goods category month stock a c1 1 5 a c1 2 0 a c1 3 0 a c2 1 0 a c2 2 10 a c2 3 0 b c1 1 30 b c1 2 0 b ...
<p>With <code>unstack</code> (to use this you first have to set the multi-index):</p> <pre><code>In [48]: df.set_index(['goods', 'category', 'month']).unstack([0,1]) Out[48]: stock goods a b category c1 c2 c1 c2 month 1 5 0 30 0 2 0 10 0 40 3 0 0 ...
python-2.7|pandas
1
20,008
29,973,999
grouped data analysis in python with pandas
<p>I have a large dataframe. One of the columns is time (just integers representing seconds). I would like to do a groupBy where each group represents say 2 seconds of data. Doing this would allow me to use the std or mean functions on all of the groups with one line of code. The goal is to be able to throw out time in...
<p>You can try :</p> <pre><code>import pandas as pd df = pd.DataFrame([[22, 18], [21, 23], [20, 17], [23, 45]], columns=['time', 'value']) def sub_group_hash(x): return (x / 2).astype(int) * 2 grouped = df.drop('time', axis=1).groupby(sub_group_hash(df['time'])) groupStd = grouped.mean() print groupStd </code><...
python|pandas
0
20,009
53,747,080
Broadcast groupby result as new column in original DataFrame
<p>I am trying to create a new column in a Pandas dataframe based on two columns in a grouped dataframe. </p> <p>Specifically, I am trying to replicate the output from this R code:</p> <pre><code>library(data.table) df = data.table(a = 1:6, b = 7:12, c = c('q', 'q', 'q', 'q', 'w', 'w') ...
<p>Just fixing your code using <code>map</code>,<code>R</code> and <code>pandas</code> still have different , which mean not every <code>R</code> function you can find a replacement in <code>pandas</code></p> <pre><code>df.c.map(df.groupby(['c'])['a', 'b'].apply(lambda x: sum(x['a'])/sum(x['b']))) Out[67]: 0 0.294...
python|pandas|dataframe|group-by|pandas-groupby
7
20,010
53,594,472
Groupby using condition in python pandas
<p>I have a Table with details of Name,Priority,Date_Time</p> <pre><code>Name Priority Date_Time ABC P1 01/02/2017 06:30 BC P2 02/04/2017 14:50 XX P1 04/06/2017 02:00 ANM P2 ...
<p>Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> supports grouping by sets of columns. What you want could be achieved by first mapping datetimes into groups, and then grouping by that new mapping compounded with ...
python-3.x|pandas-groupby
1
20,011
53,674,906
iterate through pandas dataframe consecutive columns
<p>I am trying to create a loop in pandas to calculate difference between consecutive columns and give output in a new column:</p> <p>Original df:</p> <pre><code>**201601** **201602** **201603** 100 200 500 </code></pre> <p>Desired output</p> <pre><code>**201601** **201602** **201603** **201602...
<p>Using <code>diff</code> and simple list comprehension with <code>zip</code> to construct the columns' names.</p> <pre><code>cols = [f'{b}_{a}' for (a,b) in zip(df.columns, df.columns[1:])] df[cols] = df.diff(axis=1).dropna(axis=1) 201601 201602 201603 201602_201601 201603_201602 0 100 200 500 ...
python|pandas
2
20,012
53,458,369
TypeError: "value" parameter must be a scalar, dict or Series, but you passed a "DataFrame" in Python
<p>Currently I am breaking on subjected issue. I am not sure why is it breaking and what are the amendments required.</p> <p>Code:</p> <pre><code>table = df.pivot_table(values='LoanAmount', index='Self_Employed' ,columns='Education', aggfunc=np.median) def fage(x): return table.loc[x['Self_Employed'],x['Educatio...
<p>Hi Please make sure that </p> <p>I hope you didn't execute this line before for filling missing values of LoanAmount</p> <pre><code>df['LoanAmount'].fillna(df['LoanAmount'].mean(), inplace=True) </code></pre> <p>The error is the LoanAmount is already filled with other values and there are no missing values in it....
python|pandas
2
20,013
53,651,197
How to efficiently partial argsort Pandas dataframe across columns
<p>I would like to replace values with column labels according to the largest 3 values for each row. Let's assume this input:</p> <pre><code> p1 p2 p3 p4 0 0 9 1 4 1 0 2 3 4 2 1 3 10 7 3 1 5 3 1 4 2 3 7 10 </code></pre> <p>Given <code>n = 3</code>, I am looking for:</p> <pr...
<p>With a decent number of columns, we can use <code>np.argpartition</code> with some <code>slicing</code> and <code>indexing</code>, like so -</p> <pre><code>def topN_perrow_colsindexed(df, N): # Extract array data a = df.values # Get top N indices per row with not necessarily sorted order idxtopNpar...
python|pandas|performance|numpy|sorting
4
20,014
53,599,629
Pandas .at not working and the dataframe doesn't change
<p>Having a large <code>DataFrame</code> of text, I want to first train and LDA model on it. So I do:</p> <pre><code>doc_clean = df['tweet_tokenized'].tolist() dictionary = corpora.Dictionary(doc_clean) doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] lda = LdaMulticore(doc_term_matrix, id2word=diction...
<p>Using instructions in the following post, I was able to resolve it:</p> <p><a href="https://stackoverflow.com/questions/25478528/updating-value-in-iterrow-for-pandas">Updating value in iterrow for pandas</a></p> <pre><code>for row_index, row in df.iterrows(): row = row.copy() new_doc = dictionary.doc2bow(r...
python|pandas
2
20,015
17,413,348
vectorization code double for loop python
<p>I want to vectorize these two loops, I'm new to numpy try np.ogrid function but I returned wrong dimensions Thanks in advance</p> <pre><code>lamda=20 sigma=10 imagen1=np.zeros((N,N),dtype='float32') imagen2=np.zeros((N,N),dtype='float32') imagen3=np.zeros((N,N),dtype='float32') imagen4=np.zeros((N,N),dtype='float32...
<pre><code>import numpy as np N = 10 lamda = 20 sigma = 10 imagen1 = np.zeros((N, N), dtype='float32') imagen2 = np.zeros((N, N), dtype='float32') imagen3 = np.zeros((N, N), dtype='float32') imagen4 = np.zeros((N, N), dtype='float32') imagen5 = np.zeros((N, N), dtype='float32') imagen6 = np.zeros((N, N), dtype='float32...
python|numpy
0
20,016
17,652,182
Pandas HDFStore of MultiIndex DataFrames: how to efficiently get all indexes
<p>In Pandas, is there a way to efficiently pull out all the MultiIndex indexes present in an HDFStore in table format?</p> <p>I can <code>select()</code> efficiently using <code>where=</code>, but I want all indexes, and none of the columns. I can also <code>select()</code> using <code>iterator=True</code> to save R...
<p>Create a multi-index df</p> <pre><code>In [35]: df = DataFrame(randn(100000,3),columns=list('ABC')) In [36]: df['one'] = 'foo' In [37]: df['two'] = 'bar' In [38]: df.ix[50000:,'two'] = 'bah' In [40]: mi = df.set_index(['one','two']) In [41]: mi Out[41]: &lt;class 'pandas.core.frame.DataFrame'&gt; MultiIndex: ...
python|pandas|hdfstore
9
20,017
20,017,236
join three pandas data frames into one?
<p>Here is my pandas Data Frames:</p> <pre><code>pandas1 = pandas.DataFrame([1,2,3,4,5,6,7,8,9]) pandas2 = pandas.DataFrame([10,20,30,40,50,60,70,80,90]) pandas3 = pandas.DataFrame([100,200,300,400,500,600,700,800,900]) </code></pre> <p>How can I meld this there Data Frames into one,like so:</p> <pre><code>1,10,100 ...
<p>You can use this:</p> <pre><code>pandas1.join(pandas2, lsuffix ="2").join(pandas3, lsuffix="3") </code></pre> <p>the <code>lsuffix</code> is only required because all of your columns have the same default name of (<code>0</code>)</p> <p>This code is actually joining the dataframes on their indexes. See <a href="...
python|pandas
3
20,018
15,862,034
Access index of last element in data frame
<p>I've looking around for this but I can't seem to find it (though it must be extremely trivial).</p> <p>The problem that I have is that I would like to retrieve the value of a column for the first and last entries of a data frame. But if I do:</p> <pre><code>df.ix[0]['date'] </code></pre> <p>I get:</p> <pre><code...
<p>The former answer is now superseded by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html" rel="noreferrer"><code>.iloc</code></a>:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({"date": range(10, 64, 8)}) &gt;&gt;&gt; df.index += 17 &gt;&gt;&gt; df date 17 10 18 18 19 ...
python|pandas
165
20,019
12,326,049
Matlab/Octave/Numpy numeric difference
<p>I'm porting an algorithm that works in Matlab to numpy and observed a strange behavior. The relevant segment of code is</p> <pre><code>P = eye(4)*1e20; A = [1 -0.015 -0.025 -0.035; 0.015 1 0.035 -0.025; 0.025 -0.035 1 0.015; 0.035 0.025 -0.015 1]; V1 = A*(P*A') V2 = (A*P)*A' </code></pre> <p>This code, when I run ...
<p>They use doubles internally, which have only about 15 digits precision. Your math operations likely exceed this, which causes the mathematically wrong results.</p> <p>Worth a read: <a href="http://floating-point-gui.de/" rel="nofollow noreferrer">http://floating-point-gui.de/</a></p> <p><strong>Edit:</strong> From...
matlab|numpy|octave
6
20,020
72,004,301
Using numpy where functions
<p>I am trying to understand the behavior of the following piece of code:</p> <pre><code>import numpy as np theta = np.arange(0,1.1,0.1) prior_theta = 0.7 prior_prob = np.where(theta == prior_theta) print(prior_prob) </code></pre> <p><a href="https://i.stack.imgur.com/jRi2v.png" rel="nofollow noreferrer"><img src="http...
<p>This is just how floating point numbers work. You can't rely on exact comparisons. The number <code>0.7</code> cannot be represented in binary -- it is an infinitely repeating fraction. <code>arange</code> has to compute 0.1+0.1+0.1+0.1 etc,, and the round-off errors accumulate. The 7th value is not exactly the ...
python|numpy
3
20,021
72,102,651
Sequence item 0: expected str instance, numpy.int64 found
<p>I keep getting this issue when I try and plot p values. I don't understand what is the sequence item 0. I found a couple of similar questions but I still dont understand what is causing this issue in my code below nor how to fix it.</p> <pre><code>from statannotations.Annotator import Annotator cluster_0_wmd = Hub_...
<p>Here is some code to try to reproduce your issue using some dummy data. It seems <code>statannotations</code> doesn't like the numeric values in 'Module_ID'. You could try to change them to strings (also using them for <code>pairs2</code>). Depending on when you change them, you might also need to change the numeric...
python|string|numpy|seaborn
0
20,022
22,001,176
Pandas read csv data type
<p>I'm trying to read a csv with pandas using the read_csv command. However, one of my columns is a 15 digit number which is read in as a float and then truncated to exponential notation. So the entries in this column become 2.09228E+14 instead of the 15 digit number I want. I've tried reading it as a string, but I ...
<p>Just do <code>str(int(float('2.09228E+14')))</code> which should give you <code>'209228000000000'</code></p>
python|csv|pandas
1
20,023
22,067,205
When does Pandas xs drop dimensions and how can I force it to/not to?
<p>Sometimes I see <code>xs</code> would return a Series from a DataFrame if the return is only one row, sometimes not. How to enforce it happen / not happen? (may be related to <a href="https://stackoverflow.com/questions/22066771/why-pandas-xs-doesnt-drop-levels-even-if-drop-level-true">Why pandas xs doesn&#39;t drop...
<p>Ok, they are all defined behaviors. So it is my responsibility to deal with it.</p>
python|pandas
0
20,024
55,528,848
python IndexError: index 3 is out of bounds for axis 0 with size 3
<p>I am trying neural network feed forward in my anaconda using python3.7 under ipython script. </p> <p>I'm not familiar and still learning the problem with python and don't know how to debug this.</p> <pre><code>import numpy as np w1 = np.array([[11, 11, 9, 11, 7,13, 14, 6, 6, 12], [11, 11, 9, 11, 7,13, 14, 6, 6, 12...
<p>Are you sure you wanted to write:</p> <pre class="lang-py prettyprint-override"><code>for j in range(w[l].shape[l]): </code></pre> <p>and not</p> <pre class="lang-py prettyprint-override"><code>for j in range(w[l].shape[1]): </code></pre> <p>Hope I helped!</p>
python|arrays|numpy|ipython|python-3.7
1
20,025
55,180,400
Access pandas DataFrame from pandas accessor
<p>Is it possible to access the pandas <code>DataFrame</code> to which my accessor belongs, from within the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.api.extensions.register_dataframe_accessor.html#pandas.api.extensions.register_dataframe_accessor" rel="nofollow noreferrer">accessor cla...
<p>After looking through public examples of accessors (eg, <code>GeoAccessor</code>, <code>.dt</code>), there do not appear to be built-in methods for this, unfortunately.</p>
python|pandas|dataframe|accessor
0
20,026
10,128,187
Choose weights that minimize portfolio variance
<p>I am looking for a method that chooses the weights that minimize the portfolio variance.</p> <p>For example:</p> <p>I have 3 assets; their returns are given in an array below:</p> <pre><code>import numpy as np x = np.array([[0.2,-0.1,0.5,-0.2],[0, -0.9, 0.8, 0.2],[0.4,0.5,-0.3,-.01]]) </code></pre> <p>I can weig...
<p>Please see the accepted answer to this question: <a href="https://stackoverflow.com/questions/4119054/finance-lib-with-portfolio-optimization-method-in-python">Finance Lib with portfolio optimization method in python</a></p> <p>Relevant bit is here:</p> <blockquote> <p>Here's a quote from a post I found.</p> ...
python|numpy
0
20,027
56,818,644
Error when checking target: expected dense_10 to have shape (2,) but got array with shape (1,)
<p>I have been following <a href="https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e" rel="nofollow noreferrer">this</a> tutorial on building my own image classifier, but when I get to this section of code :</p> <pre><code>model = Sequential() model.add(InputLayer(input_s...
<p>By looking at the error closely, it seems like there is something wrong with the size of <code>one-hot encoded</code> array. I tried your code on my laptop and it's working after making some modifications in the original code(not containing the test part). See the modified code below:</p> <pre><code>import cv2 impo...
python|tensorflow|keras|conv-neural-network
0
20,028
56,718,582
Select all rows from Time Series data for a given day (by timestamp)
<p>My dataframe has timestamps index and a column of data for many days. I would like to retrieve the data of particular days. </p> <pre><code>raw_df = Temp TIMESTAMP 2015-01-01 09:50:00-05:00 0.064 2015-01-01 09:51:00-05:00 0.236 2015-01-01 09:52:00-05:00 0.268 2...
<p>There are a multitude of options but all of them will need to bridge the gap between the datetime index and the date string.</p> <h3>Boolean Indexing</h3> <pre><code># df[df.index.tz_localize(None).floor('D') == '2015-01-04'] df[df.index.floor('D') == '2015-01-04'] # Or, df[df.index.normalize() == '2015-01-04'] </...
python|pandas|dataframe
3
20,029
56,678,664
Calling a column name based on a different columns values?
<p>I want to very simply call a column in a df based on a different columns value.</p> <p>Below is what I would use, but how can I add another method on top of this that says give me all the values in a column called minutes or <strong><em>df['minutes']</em></strong> if another called <strong><em>column_name</em></str...
<p>A DataFrame usually contains <strong>multiple</strong> rows (and columns).</p> <p>So if you ask whether particular column (say <em>xx</em>) has some value:</p> <pre><code>df.xx == 20 </code></pre> <p>you will get a <strong>boolean Series</strong> with:</p> <ul> <li>indices copied from <em>df</em>,</li> <li>value...
python|python-3.x|pandas|data-science|data-analysis
2
20,030
26,302,745
how can the string convert to int in python?
<p>In <strong>Machine learning in action</strong> Chapter 2, one example reads records from file, each line like:</p> <pre><code>124 110 223 largeDoses </code></pre> <p>(forget its actual meaning)</p> <p>One function in <code>kNN.py</code> is:</p> <pre><code> def file2matrix(filename): fr = open(filename) ...
<p>You should convert those 'largeDoses' 'smallDoses' 'didntLike' to the number by hand. String cannot convert to int unless the String inside is int.</p> <pre><code>if (listLine[-1]=='largeDoses'): listLine[-1] = '3' elif (listLine[-1]=='smallDoses'): listLine[-1] = '2' else: listLine[-1] = '1' </code></p...
python|numpy
1
20,031
67,051,776
Grouped Boxplot Alternate Color, Label and Tight Spacing Issue
<p>With the following data (for a quick csv file generation, dataset <a href="https://pastebin.com/0dZyThPx" rel="nofollow noreferrer">link</a>):</p> <p><a href="https://i.stack.imgur.com/54Rfq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/54Rfq.png" alt="dataset" /></a></p> <p>and the following co...
<p>If you're open to using seaborn, you can use <a href="https://seaborn.pydata.org/generated/seaborn.boxplot.html" rel="nofollow noreferrer"><strong><code>sns.boxplot()</code></strong></a> and set the melted <code>variable</code> as <code>hue</code>:</p> <pre class="lang-py prettyprint-override"><code>import seaborn a...
python|pandas|boxplot
3
20,032
66,822,117
Pandas merge different excel sheets into one along with a new column derived by sheet name
<p>I need to merge different excel sheets into one and also add a new column as a corresponding sheet name</p> <p>The below code merge all sheets, but how do I add a sheet name as a column ??</p> <pre><code>import pandas as pd df = pd.concat(pd.read_excel(r&quot;C:\\Users\\xx\\FC_List.xlsx&quot;, sheet_name=None), igno...
<p>Split it into steps.</p> <pre><code> import pandas as pd dfs = pd.read_excel(r&quot;C:\\Users\\xx\\FC_List.xlsx&quot;, sheet_name=None) df = pd.concat(dfs,keys=dfs.keys()) </code></pre> <p>This will set your index as the column name, you can then reset it and rename it.</p> <p>you could also do something like.</p>...
python|pandas
1
20,033
67,103,766
bounding box format in tensorflow object detection api
<p>thanks in advance.<br /> I try to use tensorflow object detection api with manual and web.<br /> But I confused about bounding box format in tensorflow object detection api.<br /> in tutorial, TODA(tensorflow object detection api) serve several pretrained model, and its trained with coco dataset.</p> <p>in coco data...
<p><strong>Foreknow:</strong> There are two annotation formats for images, Pascal VOC and COCO formats. Both have their own specification here's the main difference between both:</p> <p><strong>Pascal VOC:</strong></p> <ol> <li>Stores annotation in .xml file format.</li> <li>Bounding box format [x-top-left, y-top-left,...
tensorflow
1
20,034
66,949,108
How to use for loop along with if inside lambda python?
<p>I have a dataframe <strong>df</strong> that has a column <strong>tags</strong> . Each element of the column <strong>tags</strong> is a <strong>list of dictionary</strong> and looks like this:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;id&quot;: &quot;leena123&quot;, &quot;nam...
<p>Use <a href="https://www.w3schools.com/python/python_lists_comprehension.asp" rel="nofollow noreferrer"><code>List Comprehension</code></a> with <code>df.apply</code>:</p> <pre><code>df['id'] = df.tags.apply(lambda x: [i['id'] for i in x if i.get('type') == 'UserTag']) </code></pre> <p>Create a <code>list</code> fro...
python|pandas|dataframe|dictionary|lambda
1
20,035
67,167,585
Pandas multiple dataframes into one
<p>I'm looping through list with multiple dicionaries and want them to be appended into single data frame.</p> <pre><code>#getting values of specific key from AWS' boto3 response events_list = response_event.get('Events') for e in events_list: df = pd.DataFrame.from_dict(e) print(df) </code></pre> <p>Current a...
<p>Try with <code>concat</code></p> <pre><code>out = pd.concat(pd.DataFrame.from_dict(e) for e in events_list) </code></pre>
python|pandas|dataframe
4
20,036
66,763,854
Data augmentation using ImageDataGenerator
<p>I'm trying to do a simple data augmentation on my data using ImageDataGenerator. However, my generator is giving my distorted images due to the zoom parameter. I would like the random zoom to only zoom in on my data, and when it zooms in to apply the same zoom on the width and height (to avoid distorted image output...
<p>What you're looking for is random cropping:</p> <pre><code>def random_crop(image): height, width = image.shape[:2] random_array = numpy.random.random(size=4); w = int((width*0.5) * (1+random_array[0]*0.5)) h = int((height*0.5) * (1+random_array[1]*0.5)) x = int(random_array[2] * (width-w)) y ...
python|tensorflow|keras
1
20,037
66,972,274
How to append new row to Dataframe's specific column and fill missing values with Nan
<p>I have this dataframe:</p> <pre><code>NAME 4/6/2021 4/7/2021 #Everyday new Column is added T1 True False T2 True True T3 False True T4 True True T5 True True </code></pre> <p>Say, a new row is added with a <code>Name</code> which is not already present in the dataframe. I ...
<p>You can first add a new empty line with :</p> <pre class="lang-py prettyprint-override"><code>df = df.append(pd.Series(dtype=int), ignore_index=True) </code></pre> <p>You'll end up with :</p> <pre><code>NAME 4/6/2021 4/7/2021 #Everyday new Column is added T1 True False T2 True True T3 False ...
python|pandas|dataframe
1
20,038
47,505,790
Grouping using Sliding Window and Transpose
<p>A dataframe (df) contain two columns as below:</p> <pre><code>A B 46 0 45 1 46 1 51 1 47 1 46 1 45 0 48 0 47 0 45 1 49 1 </code></pre> <p>I need to design a sliding window kind of grouping for each three rows, such that:</p> <p>1) Take first three rows, transpose column(A) and append thir...
<p>Here's a numpy and python approach </p> <pre><code>def get_list(x,m) : return list(zip(*(x[i:] for i in range(m)))) A = np.array(get_list(df['A'],3)) B = np.array(get_list(df['B'],3))[:,-1] new = np.append(A,B[:,None],1) array([[46, 45, 46, 1], [45, 46, 51, 1], [46, 51, 47, 1], [51, 47, 46...
python|pandas|numpy|dataframe
2
20,039
68,309,137
How to cross checking 2 pandas dataframes file and use 1 dataframe's value as a variable?
<p>I have 2 pandas dataframes:</p> <p>modal2:</p> <pre><code> Mode month1 month2 month3 month4 month5 month6 month7 month8 month9 month10 month11 month12 0 100 0 0 0 0 0 0 0 0 0 0 0 0 2 602 0 2 1 0 2 1 0 2 1 0 2 1 3 603 1 0 2 1 0 2 1 0 2 1 ...
<p>Another solution:</p> <pre class="lang-py prettyprint-override"><code>x = pd.merge(df_ia, modal2, on=&quot;Mode&quot;, how=&quot;left&quot;) x[&quot;dynamic_month_value&quot;] = x.apply( lambda x: x[&quot;month&quot; + str(x[&quot;RevalMonth_plus&quot;])], axis=1 ) print(x[[&quot;RevalMonth_plus&quot;, &quot;Mod...
python|pandas|dataframe|numpy
2
20,040
68,179,937
I set my data types in pandas , but while convert to pyspark all data go to string
<p>I'm trying to define the data types of my dataframe, so they're good for a table soon...</p> <p>So when I convert to spark, it ignores the datasource and sets everything to string</p> <p>My code:</p> <pre><code>BDtable_FINAL = pd.DataFrame({'data': ['0001-01-01 00:00:00', '2020-02-02 00:00:00', '2021-01-01 00:00:00'...
<p>i resolved this problem: I forgot to infer the schema, it lacked: BD_Table_FINAL = BD_Table_FINAL.astype({...})</p>
python|pandas|dataframe|pyspark|databricks
0
20,041
68,393,884
How make a dataframe in wide format creating new column names from the existing ones?
<p>I have a dataframe, which looks like</p> <pre><code>import pandas as pd df=pd.DataFrame({'group': ['bmw', 'bmw', 'audi', 'audi', 'mb'], 'date': ['01/20', '02/20', '01/20', '02/20','01/20'], 'value1': [1,2,3,4,5], 'value2': [6,7,8,9,10]}) </code></pre> <p>I wa...
<p>Use <code>pivot</code>:</p> <pre><code>out = df.pivot(index='date', columns='group', values=['value1', 'value2']) out.columns = out.swaplevel(axis='columns').columns.to_flat_index().map('_'.join) </code></pre> <pre><code>&gt;&gt;&gt; out.reset_index() date audi_value1 bmw_value1 mb_value1 audi_value2 bmw_va...
python|pandas
3
20,042
68,336,649
Save/Load numpy array as column in Pandas to csv file
<p>I have the following DataFrame</p> <pre><code>index word decoded_Word language 0 potato [17, 24, 1, 21, 1, 24] english 1 animal [21, 13, 23, 18, 21, 25] english 2 שלום ... hebrew </code></pre> <p>and I want to con...
<p>That is normal, because pandas does not store the format of the columns in a csv file, and there is only so much it can infer.</p> <p>To solve this simply, after loading the dataset (so after <code>data = pd.read_csv('dataset.csv')</code>) do:</p> <pre><code>data[decoded_word] = data[decoded_word].astype(list) </cod...
python|pandas|numpy|csv
2
20,043
59,189,325
how to fill NaN values of Pandas column with values from another column
<p>I have a column with missing values after a certain number of rows, and another column with missing values up to that point. How can I join the two columns so that I have one column with all the values?</p> <p>Columns as is:</p> <pre><code> COL 1 COL 2 0 A NaN 1 B ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.combine_first.html" rel="nofollow noreferrer"><code>Series.combine_first</code...
python|pandas
4
20,044
59,367,365
How do I remove unnamed headers?
<p>I'm able to read in multiple datasets into a dictionary, however, I keep getting a header row with an unnamed title.</p> <pre><code> Unnamed: 0 Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4 Unnamed: 5 \ 0 year month day hour minute WDIR 1 2016 ...
<p>Try using <code>header</code> argument:</p> <pre><code>values = ['2015','2016','2017','2018'] mother_data = {} keys = range(4) for i in keys: mother_data[i] = pd.read_csv('data/pcbf1h'+values[i]+'_df.csv', sep=",", header=0) </code></pre>
python|pandas|dictionary
0
20,045
59,073,028
Get Values of Pandas's Error messages / Exceptions
<p>I have a bad csv data frame with a wrong line. Pandas raises an Error message with the line number. Is it possible to get this number to use it as except?</p> <p>Here the error message:</p> <pre><code>pandas.errors.ParserError: Expected 187 fields in line 55898, saw 188. Error could possibly be due to quotes being...
<p>Use <code>repr</code> to get the error string and <code>re</code> to munge the error.</p> <pre><code>import re try: &lt;code that raises exception&gt; except pandas.errors.ParserError as e: errorstring = repr(e) matchre = re.compile('Expected (\d+) fields in line (\d+), saw (\d+)') (expected, line, saw...
python|pandas|parsing
2
20,046
59,184,700
TensorFlow: Get input batch from numpy array for 3D CNN
<p>I have 3D image(tiff) data and each volume inside a folder. I want to read the data and make batch tensor for convolution network. I can read the data as numpy array but I don't how to make batch tensor input for CNN. Here is the code I have</p> <pre><code>import os import tensorflow as tf import numpy as np from s...
<p>With your approach, you have to load all data at once into memory and also you have to take care of all dimensions. I would suggest using Keras <code>flow_from_directory</code> and <code>generators</code>. Keras has this <code>ImageDataGenerator</code> class which allows the users to perform image collection from di...
python|numpy|tensorflow|keras
0
20,047
59,227,837
Iterative outer addition Numpy
<p>I want to apply outer addition of multiple vectors/matrices. Let's say four times:</p> <pre><code>import numpy as np x = np.arange(100) B = np.add.outer(x,x) B = np.add.outer(B,x) B = np.add.outer(B,x) </code></pre> <p>I would like best if the number of additions could be a variable, like <code>a=4</code> --> 4...
<p><strong>Approach #1</strong></p> <p>Here's one with array-initialization -</p> <pre><code>n = 4 # number of iterations to add outer versions l = len(x) out = np.zeros([l]*n,dtype=x.dtype) for i in range(n): out += x.reshape(np.insert([1]*(n-1),i,l)) </code></pre> <p><strong>Why this approach and not iterative...
python|numpy|addition
3
20,048
59,459,475
Concatenate value from 3 excel columns in Python
<p>very new to Python here.</p> <p>I'm triying to concatenate value from 3 columns from an excel sheet into 1 columns. I do have about 300-400 rows to do</p> <p>Values are like this</p> <pre><code>COl1 COL 2 COL3 CNMG 432 EMU TNMG 332 ESU ... </code></pre> <p>Output should be </p> <pre><code>COL3 C...
<p>seems like some simple string concatenation should do the trick</p> <pre><code>df['concat'] = df['COL1'] + df['COL 2'].astype(str) + df['COL3'] </code></pre> <p>if you have ints, you'll need to cast them as strings, you can check which columns with a simple <code>print(df.dtypes)</code></p> <p>if you have ints or...
python|excel|pandas|concatenation
2
20,049
59,415,879
What is .numpy() function means and why there is a error here
<p>'numpy.float64' object has no attribute 'numpy'</p> <p>I found it in this code</p> <pre><code>print("Training Loss:", loss.numpy(), "Validation Acc:", accuracy_score(y_true=y_valid, y_pred=y_valid_pred)) </code></pre> <p>I cannot find another part about loss, because it is assignment and I need to c...
<p>What is <code>loss</code>? Look at what produces it:</p> <pre><code>loss, cur=network.evaluate(X,y) </code></pre> <p>and check that method's docs:</p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/Sequential" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/Sequential<...
python|numpy|tensorflow|keras
0
20,050
44,859,113
Pandas and Matplotlib plotting df as subplots with 2 y-axes
<p>I'm trying to plot a dataframe to a few subplots using pandas and matplotlib.pyplot. But I want to have the two columns use different y axes and have those shared between all subplots.</p> <p>Currently my code is:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'Area':['A', '...
<p>To create a secondary y axis, you can use <code>twinax = ax.twinx()</code>. Once can then join those twin axes via the <code>join</code> method of an axes <code>Grouper</code>, <code>twinax.get_shared_y_axes().join(twinax1, twinax2)</code>. See <a href="https://stackoverflow.com/questions/42973223/how-share-x-axis-o...
python|pandas|matplotlib
1
20,051
44,978,255
Tensorflow stratified_sample error
<p>I'm trying to use <code>tf.contrib.training.stratified_sample</code> in Tensorflow to balance classes. I made a quick example below to test it, drawing samples from two unbalanced classes in a balanced way and verifying it, but I'm getting an error.</p> <pre><code>import tensorflow as tf from tensorflow.python.fram...
<p>I've modified the code into something that works for me. Summary of the changes:</p> <ul> <li>Use <code>enqueue_many=True</code> to enqueue a batch of examples with different labels. Otherwise it's expecting a single scalar label Tensor (which can be stochastic when evaluated by the queue runners).</li> <li>The fir...
python|python-3.x|machine-learning|tensorflow
3
20,052
45,077,165
Reading CSV - Python
<p>I have a csv file with some data, I have names in column b and some related information in column A. However not all names have related information</p> <pre><code> A B 1 JOHN 2 JANE 3 jane@email.com 4 phone:0800etcetc 5 ZAIN ...
<p>Use the <a href="https://docs.python.org/3.6/library/csv.html" rel="nofollow noreferrer">csv library</a>: </p> <p>So, something like this:</p> <pre><code>import csv with open('tmp.csv', 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') name = None for row in reader: if row[1]: ...
python|python-3.x|csv|pandas
0
20,053
45,130,048
Parse tsv with very specific format into python
<p>I have a tsv file containing a network. Here's a snippet. Column 0 contains unique IDs, column 1 contains an alternative ID (not necessarily unique). Each pair of columns after that contains an 'interactor' and a score of interaction. </p> <pre><code>11746909_a_at A1CF SHPRH 0.11081568 TRIM10 ...
<p>Producing an output dataframe like you specified above shouldn't be too hard</p> <pre><code>from collections import OrderedDict import pandas as pd def open_network_tsv(filepath): """ Read the tsv file, returning every line split by tabs """ with open(filepath) as network_file: for line in...
python|pandas
0
20,054
45,046,819
launching tensorboard from google cloud datalab
<p>I need help in luanching tensorboard from tensorflow running on the datalab, My code is the followings (everything is on the datalab):</p> <pre><code>import tensorflow as tf with tf.name_scope('input'): print ("X_np") X_np = tf.placeholder(tf.float32, shape=[None, num_of_features],name="input") with tf.name_s...
<p>If you are using datalab, you can use tensorboard as below:</p> <pre><code>from google.datalab.ml import TensorBoard as tb tb.start('./logs') </code></pre> <p><a href="http://googledatalab.github.io/pydatalab/google.datalab.ml.html" rel="noreferrer">http://googledatalab.github.io/pydatalab/google.datalab.ml.html<...
tensorflow|tensorboard|google-cloud-datalab
8
20,055
44,853,093
Python, Numpy, User Guide 1.13.0. Is there written a wrong output by mistake?
<p>I have just read the user guide of Numpy. And wrote the codes in a Python console that were written in the guide. What I want to ask is about the below image. <a href="https://i.stack.imgur.com/07eSH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/07eSH.png" alt="enter image description here"></a>...
<p>As said in the comment, you seem to be in a 32bit architecture. On a 64 bit architecture, the <code>dtype</code> was indeed <code>int64</code>.</p>
python|numpy
1
20,056
57,073,937
improving performance of iteration over a very large dataframe
<p>I have a pandas dataframe which consists of 3 million rows and 50 columns which all contain integers (either positive or negative). I want to create a new column called 'feature' which takes the biggest negative number from the 50 existing columns.</p> <p>For example, if for a given row the 50 columns contain the v...
<p>You could instead use <code>DataFrame.where</code> to set all values above <code>0</code> to <code>NaN</code> and return the rowwise <code>max</code>:</p> <pre><code>df['feature'] = df.iloc[:,:50].where(df.iloc[:,:50].lt(0)).max(1) </code></pre>
python|pandas|dataframe|iteration|list-comprehension
1
20,057
57,278,838
Drop rows based on indices in a sorted df
<p>How can I, after sorting the rows of a df, drop rows based on their index, and not their new row position?</p> <p>A small example of what I mean:</p> <pre><code>import pandas as pd df = { 'ELEMENT_DATE' : ['01/03/2010', '01/01/2010', '01/02/2010', '01/04/2010', '01/5/2010'], 'ELEMENT' : ['A', 'B',...
<p>It seems you have a slight misconception of what you should be passing to <code>pd.DataFrame.drop</code>. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer">From the documentation</a>, the first argument is <code>labels</code>:</p> <blockquote>...
python|pandas
2
20,058
46,067,224
Embedding feature vectors in Tensorflow
<p>In text processing there is <a href="https://www.tensorflow.org/programmers_guide/embedding" rel="nofollow noreferrer">embedding</a> to show up (if I understood it correctly) the database words as vector (after dimension reduction). now, I am wondering, is there any method like this to show extracted features via C...
<p>I have taken help of Tensorflow documentation.</p> <p>For in depth information on how to run TensorBoard and make sure you are logging all the necessary information, see <a href="https://www.tensorflow.org/versions/r0.12/how_tos/embedding_viz/" rel="nofollow noreferrer">TensorBoard: Visualizing Learning.</a></p> <...
tensorflow|deep-learning
1
20,059
45,878,443
Pandas: groupby
<p>I have dataframe</p> <pre><code>df = pd.DataFrame({'member_id': [111, 111, 111, 111, 222, 222, 333, 333], 'event_duration': [12, 242, 3, 21, 4, 76, 34, 12], 'period': [1, 2, 2, 2, 3, 3, 4, 4]}) event_duration member_id period 0 12 111 1 1 242 111 2 2 ...
<p>Could this be what you really need:</p> <pre><code>df.groupby(['member_id', 'period'], as_index=False)['event_duration'].sum().groupby(['member_id'], as_index=False).agg({'period': pd.Series.nunique, 'event_duration': np.median}) member_id event_duration period 0 111 139 2 1 22...
python|pandas|dataframe|pandas-groupby
1
20,060
45,822,062
Python: Merge Pandas Data Frame with Pivot Table
<p>I have the two following dataframes that I want to merge.</p> <pre><code>df1: id time station 0 a 22.08.2017 12:00:00 A1 1 b 22.08.2017 12:00:00 A3 2 a 22.08.2017 13:00:00 A2 ... pivot: station A1 A2 A3 0 time 1 22.08.2017 12:00:00...
<p>I guess you got the dataframe <code>pivot</code> using either <code>pivot</code> or <code>pivot_table</code> in pandas, if you can perform the merge using the dataframe you had before the pivot it should work just fine.</p> <p>Otherwise you will have to reverse the pivot using <code>melt</code> before merging:</p> ...
python-3.x|pandas|merge|pivot-table
1
20,061
50,892,080
Negative dimension size caused by subtracting 3 from 2 for 'Encoder/conv6/Conv2D'
<p>I am trying to implement an AutoEncoder in Tensorflow. I am a beginner in Python as well as StackOverflow. These two are my encoder and decoder.My train_data.shape is (42000,28,28,1) (mnist dataset).</p> <pre><code>def Network(Input): with tf.name_scope("Encoder"): #encoder starts here conv1 = tf.layers.con...
<p>To visualize the shape of the tensor <code>t</code> you use <code>t.get_shape()</code>. The error explicitly says that you're trying to use a too big kernel on a too small input. From <a href="http://cs231n.github.io/convolutional-networks/" rel="nofollow noreferrer">Stanford's CS231n class notes</a> you can get the...
python|tensorflow|autoencoder
2
20,062
50,706,125
iterate the rows and join in python pandas
<p>i have master dataset like this</p> <pre><code>master = pd.DataFrame({'Channel':['1','1','1','1','1'],'Country':['India','Singapore','Japan','United Kingdom','Austria'],'Product':['X','6','7','X','X']}) </code></pre> <p><a href="https://i.stack.imgur.com/9CKfm.png" rel="nofollow noreferrer"><img src="https://i.sta...
<p>IIUC, you need:</p> <pre><code>pd.concat([pd.merge(master,user[(user.User==x)],how='left',on=['Country']) for x in list(user['User'].unique())], ignore_index=True) </code></pre> <p>Output:</p> <pre><code> Channel Country Product User count 0 1 India X 101 2 1 1 ...
python|pandas|merge
0
20,063
20,462,542
How do I duplicate the values for the last dimension in a numpy array?
<p>I am getting an error in numpy when I perform the pairwise multiplication of two arrays a and b since a has dimensions 100 x 200 x 3, while b has dimensions 100 x 200. However, b contains only 0s and 1s. How do I repeat the last dimension of b 3 times to turn b into a 100 x 200 x 3 array?</p> <p>This is something a...
<pre><code>a * b[..., np.newaxis] </code></pre> <p>Give <code>b</code> another length-1 axis on the end, and broadcasting will handle this for you without needing to actually construct a tripled array.</p>
python|numpy
4
20,064
20,522,488
Why equal variables are compared in Pandas Cython code?
<p>Looking at ewma method in <a href="https://github.com/pydata/pandas/blob/master/pandas/algos.pyx" rel="nofollow">https://github.com/pydata/pandas/blob/master/pandas/algos.pyx</a>, there is a strange code:</p> <pre><code>for i from 1 &lt;= i &lt; N: cur = input[i] prev = output[i - 1] if **cur == cur:**...
<p><code>cur == cur</code> will be True for all numbers / objects EXCEPT if cur is a <code>np.nan</code> essentially a quick way of nan testing</p>
pandas|cython
6
20,065
20,827,005
how to solve 3 nonlinear equations in python
<p>I have the following system of 3 nonlinear equations that I need to solve:</p> <p>-xyt + HF = 0</p> <p>-2xzt + 4yzt - xyt + 4z^2t - M1F = 0</p> <p>-2xt + 2yt + 4zt - 1 = 0</p> <p>where x, HF, and M1F are known parameters. Therefore, y,z, and t are the parameters to be calculated.</p> <p><strong>Attemp to solve ...
<p>@Christian, I don't think the equation system can be linearize easily, unlike the post you suggested.</p> <p>Powell's Hybrid method (<code>optimize.fsolve()</code>) is quite sensitive to initial conditions, so it is very useful if you can come up with a good initial parameter guess. In the following example, we fir...
python-2.7|optimization|numpy|scipy|nonlinear-optimization
6
20,066
6,256,583
Using Matplotlib to create a partial multiplication table checkerboard?
<p>My kid is trying to learn his multiplication tables and I was thinking of using matplotlib to create a partially filled out multiplication table for him to practice on. The tricky part is to have the text of the horizontal and vertical axes line up between the tic marks instead of being centered on the tic marks. </...
<p>As everyone has already said, matplotlib is really not the best tool for this... If you really want to do it programatically, generating HTML would honestly be easier. </p> <p>That having been said, it makes a nice example.</p> <p>The easiest way to tweak the axis label positions is to either replace them with te...
python|numpy|matplotlib
6
20,067
66,455,115
how can i find the missing values in my data frame and what is the best method for handle this missing values?
<p>Assume the following data frame:</p> <p>&quot;?&quot;==missing value</p> <p>how can i find &quot;?&quot; in this data frame by python and how can i handle this missing values by the bestest method?</p> <pre><code>col1 col2 col3 col4 col5 target ? 1 ? 1 20 0 90 1 ...
<p>What do you mean by &quot;finding&quot;?</p> <p>For example, you could get the null values like this:</p> <pre><code>df.loc[df['col1'].isnull(), 'col'] </code></pre> <p>There is no &quot;best method&quot; to fill in missing values - it depends on the nature of your data. For example, you can fill in missing values w...
python|pandas
0
20,068
66,362,174
Numpy: partially transpose and stack
<p>Suppse I have a 3 dimension array A</p> <pre><code>A = np.random.rand(4,4,5) AT = np.zeros((4,4,5)) # Firstly I want to transpose the first two dimension of A but keep the third dimension fixed # that is a, b, c = A.shape for i in range(c): AT[:,:,i] = A[:,:,i].T # then I want to stack the A and AT into a 4 d...
<p>Short answer to your question 1) <code>swapaxes</code> and 2) <code>stack</code>:</p> <pre><code>B = np.stack([A,A.swapaxes(0,1)], axis=2) </code></pre>
python|numpy|numpy-ndarray
3
20,069
66,486,569
How to read one Numpy Array and get the value from another Numpy array
<p>I am new to Numpy / python so any help is much appreciated. I have 2 arrays for each row in <code>X</code>. I have to get the value from <code>X2</code> and append it to a new array depending on if the <code>X</code> array value is <code>0</code> or <code>1</code>.</p> <p>Steps:</p> <ol> <li>See how many <code>0</co...
<p>You can try the Numpy module <code>take_along_axis</code> <a href="https://numpy.org/devdocs/reference/generated/numpy.take_along_axis.html" rel="nofollow noreferrer">link</a></p> <pre><code>X = np.array([[0,1,1,1,1], [0,1,1,1,0]]) X2 = np.array([[0.2,0.5,0.5,0.5,0.5], [0.3,0.6,0.6,0.6,0.3]]) e...
python|arrays|numpy|loops|indexing
0
20,070
57,375,344
How to create new array based on position in python?
<p>I have an array (b) and I want to add new rows according to the position of 1s in the (a) array.</p> <pre><code>a=np.array([1,1,0,1,0] b=np.array([1,2,3,4,5]) </code></pre> <p>I'd need to make a new array like this:</p> <pre><code>Output: array([1,2,3,4,5],[1,0,0,0,0],[0,1,0,0,0],[0,0,0,1,0]) </code></pre> <p>H...
<p>One-liner with <code>broadcasting</code> -</p> <pre><code>In [14]: np.vstack((b,np.arange(len(a)) == np.flatnonzero(a)[:,None])) Out[14]: array([[1, 2, 3, 4, 5], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0]]) </code></pre> <p>With <code>zeros-initialized</code> array -</p> <pre><code>In...
python|arrays|loops|numpy
1
20,071
57,709,758
using transforms.LinearTransformation to apply whitening in PyTorch
<p>I need to apply ZCA whitening in PyTorch. I think I have found a way this can be done by using transforms.LinearTransformation and I have found a test in the PyTorch repo which gives some insight into how this is done (see final code block or link below)</p> <p><a href="https://github.com/pytorch/vision/blob/master...
<p>ZCA whitening is typically a preprocessing step, like center-reduction, which basically aims at making your data more NN-friendly (additional info below). As such, it is supposed to be applied once, right before training. </p> <p>So right before you starts training your model with a given dataset <code>X</code>, co...
pytorch
1
20,072
57,469,970
no module named 'tensorflow' in mac
<p>i have just install python, anaconda, tensorflow and i was trying to do first test of tesorflow in jupyter notebook but i doesn't work plz help me Thank you</p> <p>python version == <code>3.7.0</code></p> <p>using macbook 2015</p> <pre><code>import tensorflow as tf ModuleNotFoundError Trace...
<p>There could be so many different reasons the import is not working, you need to give us more information.</p> <ul> <li>what environment did you install tensorflow in (if at all)?</li> <li>did you check to see if the environment had tensorflow installed through <code>conda list</code>?</li> <li>why did you choose to...
python|macos|tensorflow
1
20,073
57,705,851
replacing values based on different conditions
<p>I have a dataframe looks like below:</p> <pre><code>test = pd.DataFrame({"location": ["a", "b", "c"], "store": [1,2,3], "barcode1" : [1, 0 ,25], "barcode2" : [4,0,11], "barcode3" : [5,5,0]}) </code></pre> <p><a href="https://i.stack.imgur.com/QebXs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur....
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> with <code>iloc</code>:</p> <pre><code>m1 = test.iloc[:,2:] &lt;= 0 m2 = test.iloc[:,2:] &lt;= 5 test.iloc[:,2:] = np.select([m1, m2], ['zero','low'], default='ok') ...
python-3.x|pandas
2
20,074
57,405,199
How to get full decimal values from the column in python?
<p>I have a pandas dictionary with columns as shown below</p> <p><a href="https://i.stack.imgur.com/JDWju.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JDWju.png" alt="enter image description here"></a></p> <p>The values if i copy from variable explorer and paste in my script, i get more decimals...
<p>As per @CodeIt comments, I tried as follows and worked</p> <pre><code>import decimal for c1 in data.keys(): subset_df = subset_df.append({'good': data[c1].good.values.astype(decimal.Decimal), 'values': data[c1].value.values.astype(decimal.Decimal)},ignore_index = True) </code></pre> <p>In my csv I got</p> <p...
python|pandas
1
20,075
57,369,207
Elegant way to strip spaces at once across dataframe than individual columns
<p>I have a dataframe <code>hash_file</code> and it has two columns <code>VARIABLE</code> and <code>concept_id</code>.</p> <pre><code>hash_file = pd.DataFrame({'VARIABLE':['Tes ','Exam ','Evaluation '],'concept_id': [1,2,3]}) </code></pre> <p>To strip spaces in the values of these two columns, I use the below code</p...
<p><code>stack()</code> , <code>strip()</code> , <code>unstack()</code>:</p> <pre><code>final=hash_file.astype(str).stack().str.strip().unstack() </code></pre> <p>Or: <code>applymap()</code>:</p> <pre><code>final=hash_file.astype(str).applymap(lambda x: x.strip()) </code></pre> <p>Performance on 9000 similar rows, ...
python|python-3.x|pandas|list|dataframe
2
20,076
43,484,358
Count occurrences in Pandas data frame
<p>I have the following data frame:</p> <p><a href="https://i.stack.imgur.com/lxx86.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lxx86.png" alt="enter image description here"></a></p> <p>I'm looking to come up with this data frame: <a href="https://i.stack.imgur.com/YKoOk.png" rel="nofollow nor...
<p>The trick is to use <code>collections.Counter</code></p> <pre><code>In [1]: from collections import Counter In [2]: s = pd.Series(["AAA|BBB"]) In [3]: s.str.split("|").apply(Counter).apply(pd.Series) Out[3]: AAA BBB 0 1 1 </code></pre> <p>Though, you might also want to rename and concat them (assumin...
python|pandas
1
20,077
43,579,250
Appending or Concatenating DataFrame via for loop to existing DataFrame
<p>Posted in the output you will see that this code take the Location column(or series), and places it in a data frame. After which, the first,second, and third part of the nested for loop then takes the first index of each column and then creates a dataframe to add to the first dataframe. What I have been trying to do...
<p>Good practice when asking questions is to provide an example of what you want your output to look like. However, this is my best guess at what you want. </p> <pre><code>pd.concat({i: d.shift(i) for i in range(18)}, axis=1) </code></pre>
python|pandas
0
20,078
43,726,428
Filter numpy array of tuples
<p><code>Scikit-learn</code> library have a brilliant example of data clustering - <a href="http://scikit-learn.org/stable/auto_examples/applications/plot_stock_market.html" rel="nofollow noreferrer">stock market structure</a>. It works fine within US stocks. But when one adds tickers from other markets, <code>numpy</c...
<p>So <code>quotes</code> is a list of recarrays, and in <code>date_all</code> you collect the intersection of all values in the <code>date</code> field.</p> <p>I can recreate one such array with:</p> <pre><code>In [286]: dt=np.dtype([('date', 'O'), ('year', '&lt;i2'), ('month', 'i1'), ('day', ...: ...: ),...
python|numpy|filter|scikit-learn|stockquotes
0
20,079
72,873,194
Pandas: Renaming headers with identical names
<p>I have several columns named the same (or not named at all, to be specific) in a dataframe. I need to rename them separately but df.rename method renames them altogether. For example, in a following df:</p> <pre><code># nan nan a nan nan b nan nan # 1 2 3 4 5 6 ...
<p>You can simply reset column names by this:</p> <p><code>df.columns = [&quot;nan&quot;, &quot;nan&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;b&quot;] </code></p>
python|pandas|dataframe
1
20,080
73,112,301
Replace null values per country with the min of a column for that country specifically
<p><a href="https://i.stack.imgur.com/KtFOi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KtFOi.png" alt="enter image description here" /></a></p> <p>I'm trying to</p> <ul> <li>step 1. Get the min incidence of malaria for each country</li> <li>step2 -If a country has a nan value in the 'IncidenceOf...
<p>A better approach would be something like this</p> <pre><code>malaria_data.groupby('CountryName')['IncidenceOfMalaria'].apply(lambda gp : gp.fillna(gp.min()) </code></pre> <p>Will probably give you what you want, i didnt test it out because there is no sample data but please tell me if an error occurs.</p>
python|pandas
0
20,081
73,119,120
Unsupported operand type(s) for -: 'str' and 'float' when normalizing against negative controls in pandas dataframe
<p>The <code>neg_ctl_df</code> dataframe contains negative control and the <code>coding_gene_df</code> contains my gene-of-interest.</p> <p>I want to perform normalization for each sample by subtracting the median of the negative controls within the sample.</p> <p>Both <code>samples</code> and <code>neg_ctl_median</cod...
<p>in your series that has sample value, the values are string type such as '5.29' , '8.46' , etc. python can not operate &quot;-&quot; between string and floats. you must first convert your sample to floats format. you can use from &quot;to_numeric&quot; method in pandas for this</p> <p>use this code (suppose your 29t...
pandas|statistics
0
20,082
70,562,621
How to compare average value from recent 2 weeks to average of previous 6 weeks by group
<p>I'm trying to create a function that would affectively analyze merchant bank balance transaction averages across time in order to identify trends that could notify a lender of an increase in likelihood of missing a payment.</p> <p>So if the merchants most recent 2 week average bank balance is significantly below the...
<p>I understood that your issue is that you don't manage to get the rolling average based on the category &quot;merchant&quot;. If that is it, one way would be this one:</p> <ol> <li><p>First groupby with resample Write the resample, the same way that you already had, I just added a ffill (fill down to avoid nans if yo...
python|pandas|transactions|analysis|bank
0
20,083
70,480,529
Run Custom Tflite Model in Flutter | Didn't find op for builtin opcode 'CONV_2D' version '5'
<p>I am working on a flutter app that uses a custom Tflite Model based on the Densenet Architecture.</p> <p>Currently I am trying to get the Model running in my App.</p> <p>Model Input:</p> <ul> <li>(224,224,3) RGB image in float format in range [0, 255.0] with Imagenet pre-processing.</li> </ul> <p>Output:</p> <ul> <l...
<p>Conv2D version 5 is supported by TensorFlow Lite 2.4.0 or above, which was released in Dec 2020.</p> <p>You can try to update the version of the TensorFlow Lite runtime. However the Flutter/Dart packages are not officially supported but contributed by the community, so I'm unsure if there's a build for 2.4.0 or newe...
flutter|machine-learning|computer-vision|tensorflow-lite
0
20,084
70,547,910
How to solve AttributeError: module 'pandas' has no attribute 'read_xlsx'
<pre><code>AttributeError Traceback (most recent call last) C:\Users\BAMIGB~1\AppData\Local\Temp/ipykernel_15512/4291769960.py in &lt;module&gt; ----&gt; 1 data = pd.read_xlsx ('HRDataset_v14 ().xlsx') 2 data ~\Anaconda3\lib\site-packages\pandas\__init__.py in __getattr__(name) 242...
<p>Instead of this <code>[ data = pd.read_xlsx ('HRDataset_v14 ().xlsx') ]</code> use</p> <pre><code>data = pd.read_excel ('filename.xlsx') </code></pre>
python|pandas
1
20,085
70,428,623
numpy.random.multinomial at version 1.16.6 is 10x faster than later version
<p>Here are codes and result:</p> <pre><code>python -c &quot;import numpy as np; from timeit import timeit; print('numpy version {}: {:.1f} seconds'.format(np.__version__, timeit('np.random.multinomial(1, [0.1, 0.2, 0.3, 0.4])', number=1000000, globals=globals())))&quot; </code></pre> <pre><code>numpy version 1.16.6: ...
<p><strong>TL;DR:</strong> this is a <a href="https://en.wikipedia.org/wiki/Software_regression" rel="nofollow noreferrer">local performance regression</a> caused by the overhead of <strong>additional checks</strong> in the <code>numpy.random.multinomial</code> function. <em>Very small arrays</em> are strongly impacted...
numpy|performance|multinomial
3
20,086
43,015,881
Python 3; MatplotLib ; Box Plot Error
<p>I am new to python/ pandas and trying to create a boxplot using the iris data set. </p> <p>Here is my code.:</p> <pre><code>import pandas as pd iris_filename = '/Users/pro/Documents/Code/Data Science/Iris/IRIS.csv' iris = pd.read_csv(iris_filename, header = None, names= ['sepal_lenght','sepal_width','petal_le...
<p>You are calling matplotlib to boxplot the DataFrame iris... as you are already using Pandas for importing the .csv you should also use it for plotting:</p> <pre><code>iris.boxplot() </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.boxplot.html" rel="nofollow noreferr...
python-3.x|pandas|matplotlib
2
20,087
42,951,744
Creat symbol matrix using numpy, sympy in function?
<p>My code:</p> <pre><code>def crearMatrix(name,shape=(2,2)): X = np.empty(shape) for i in range(shape[0]): #X.shape[1] for j in range(shape[1]): X[i][j] = Symbol("a"+'_{'+str(i*10+j+11)+'}') return X </code></pre> <p>Error message:</p> <blockquote> <p>TypeError: can't convert expre...
<p>You probably don't want <code>numpy</code> matrix'es to store <code>sympy</code>'s symbols. Better use <code>sympy.Matrix</code> for this.</p> <pre><code>import sympy def crearMatrix(name,shape=(2,2)): X = [] for i in range(shape[0]): row = [] for j in range(shape[1]): row.appen...
python|arrays|numpy|matrix|sympy
0
20,088
42,949,548
Tensorflow: Gradient Calculation from Input to Output
<p>I would like to calculate the gradients of the output of a neural network with respect to the input. I have the following tensors:</p> <pre><code>Input: (num_timesteps, features) Output: (num_timesteps, 1) </code></pre> <p>For the gradients from the inputs to the entire output vector I can use the following:</p> ...
<p>First up, I suppose you mean the gradient of <code>Output</code> <em>with respect to</em> the <code>Input</code>.</p> <p>Now, <a href="https://www.tensorflow.org/api_docs/python/tf/gradients" rel="nofollow noreferrer">the result</a> of both of these calls:</p> <ul> <li><code>dO = tf.gradients(Output, Input)</code>...
python|tensorflow|machine-learning|artificial-intelligence|tensorflow-gradient
1
20,089
27,276,972
Error when importing module in main Python installation: module is called from an inexistent venv Python
<p>I am working in an IPython interpreter started from the terminal (MacOSX) with just an <code>ipython</code> + <code>enter</code>. When I try to import <code>pandas</code>, I get the following error:</p> <pre><code>/Users/myusername/Documents/somefolder/virtualenvironment/adam_py/lib/python2.7/site-packages/pandas/_...
<p>I just deleted the folder containing the former virtual environment, closed the interpreter, pip-uninstalled pandas, pip-installed it again, and reopened the interpreter. Now I can import pandas without problems.</p>
python|macos|pandas|virtualenv|geopandas
0
20,090
14,541,833
How to install Numpy & Scipy for Python 3.3 on Moutain Lion
<p>Haven't found a working solution as of yet. I have three different versions of Python on my system, the default bundled with OSX (2.7.2), 2.7.3 installed via homebrew and 3.3.0 installed via homebrew. Running <code>pip install numpy</code> or <code>pip install scipy</code> will install it for the 2.7.3 version.</p> ...
<p>you need to call <strong>pip3</strong> instead of pip. Homebrew installs pip3 with python3.</p> <p>I just tried <code>pip3 install numpy</code> on my OSX 10.7.5 python 3.3.0 machine and it failed. It looks like numpy v1.6 is not compatible but numpy v1.7 (beta, not available via pip3) is.</p> <p>Link: A post on SO...
python|macos|numpy|scipy
1
20,091
14,570,513
Which is faster, numpy transpose or flip indices?
<p>I have a dynamic programming algorithm (modified Needleman-Wunsch) which requires the same basic calculation twice, but the calculation is done in the orthogonal direction the second time. For instance, from a given cell <em>(i,j)</em> in matrix <em>scoreMatrix</em>, I want to both calculate a value from values "up"...
<p>In NumPy, transpose returns a view with a different shape and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html">strides</a>. It does not touch the data.</p> <p>Therefore, you will likely find that the two approaches have identical performance, since in essence they are exactly...
python|performance|numpy|transpose
10
20,092
25,430,583
eigenvectors from numpy.eig not orthogonal
<p>my problem is the following: using scipy.linalg.eig to get eigenvectors and eigenvalues i see that all my eigenvalues have multiplicity 1 yet when i run the code below it doesn't confirm that the eigenvectors are orthogonal as they should be in this case. any reason why this would be? or how to fix it?</p> <pre><co...
<p>Why should they be orthogonal? Your matrix</p> <pre><code>a=matM(60000) </code></pre> <p>is far from being symmetric,</p> <pre><code>abs(a-a.T).max() -&gt; 2.16 </code></pre> <p>with </p> <pre><code>abs(a).max() -&gt; 1.08 </code></pre> <p>so I wouldn't necessarily expect orthogonal eigenvectors. Is it possibi...
python|numpy|eigenvector
4
20,093
30,604,907
generate sequence by indices / one-hot encoding
<p>I have a sequence <code>s = [4,3,1,0,5]</code> and <code>num_classes = 6</code> and I want to generate a Numpy matrix <code>m</code> of shape <code>(len(s), num_classes)</code> where <code>m[i,j] = 1 if s[i] == j else 0</code>.</p> <p>Is there such a function in Numpy, where I can pass <code>s</code> and <code>num_...
<p>Since you want a single <code>1</code> per row, you can fancy-index using <code>arange(len(s))</code> along the first axis, and using <code>s</code> along the second:</p> <pre><code>s = [4,3,1,0,5] n = len(s) k = 6 m = np.zeros((n, k)) m[np.arange(n), s] = 1 m =&gt; array([[ 0., 0., 0., 0., 1., 0.], [ ...
python|numpy
4
20,094
30,673,684
Pandas dataframe first x columns
<p>I have a dataframe with about 500 columns and that's why I am wondering if there is anyway that I could use head() function but want to see the first 50 columns for example.</p> <p>Thanks</p>
<p>I wasn't sure if you meant rows or columns.</p> <p>If it's rows, then</p> <pre><code>df.head(50) </code></pre> <p>will do the trick.</p> <p>If it's columns, then</p> <pre><code>df.iloc[:, : 50] </code></pre> <p>will work.</p> <p>Of course, you can combine them.</p> <hr> <p>You can see this stuff at <a href=...
pandas|dataframe
70
20,095
26,873,415
Python Random Array of 0s and 1s
<p>I want to <em>randomly</em> produce an <code>array</code> of <code>n</code> ones and <code>m</code> zeros.</p> <p>I thought of this solution:</p> <ol> <li>produce the ones array (<code>np.ones</code>)</li> <li>produce the zeros array (<code>np.zeros</code>)</li> <li>combine them to one array (<code>np.hstack</code...
<p>Your solution seems reasonable. It states exactly what it's doing, and does it clearly.</p> <p>Let's compare your implementation:</p> <pre><code>a = np.hstack((np.ones(n), np.zeros(m))) np.random.shuffle(a) </code></pre> <p>… with an obvious alternative:</p> <pre><code>a = np.ones(n+m) a[:m] = 0 np.random.shuffl...
python|numpy|random
9
20,096
19,364,149
Numpy Routine(s) to create a regular grid inside a 2d array
<p>I am trying to write a function that would create a regular grid of 5 pixels by 5 pixels inside a 2d array. I was hoping some combination of <code>numpy.arange</code> and <code>numpy.repeat</code> might do it, but so far I haven't had any luck because <code>numpy.repeat</code> will just repeat along the same row.</...
<p>Similar to Jaime's answer:</p> <pre><code>np.repeat(np.arange(0, 10, 3), 4)[..., None] + np.repeat(np.arange(3), 5)[None, ...] </code></pre>
python|numpy|grid
3
20,097
29,150,346
Pandas: Modify a particular level of Multiindex
<p>I have a dataframe with Multiindex and would like to modify one particular level of the Multiindex. For instance, the first level might be strings and I may want to remove the white spaces from that index level:</p> <pre><code>df.index.levels[1] = [x.replace(' ', '') for x in df.index.levels[1]] </code></pre> <p>H...
<p>Thanks to @cxrodgers's comment, I think the fastest way to do this is:</p> <pre><code>df.index = df.index.set_levels(df.index.levels[0].str.replace(' ', ''), level=0) </code></pre> <hr> <p>Old, longer answer:</p> <p>I found that the list comprehension suggested by @Shovalt works but felt slow on my machine (usin...
python|pandas|immutability|multi-index
53
20,098
33,566,983
pandas Series elementwise boolean checks are ambigious
<p>Not sure how to use .bool(), any, all, or empty, to make the two different examples work. Each throws me the Ambiguous Value error</p> <pre><code>import pandas as pd first = pd.Series([1,0,0]) second = pd.Series([1,2,1]) number_df = pd.DataFrame( {'first': first, 'second': second} ) bool_df = pd.DataFrame( {'...
<p>You need to use the bitwise and (<code>&amp;</code>) to compare Series elementwise - more in the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">docs</a></p> <pre><code>In [3]: bool_df['double_zero_check'] = (number_df['first'] != 0) &amp; (number_df['second'] != ...
python|pandas
2
20,099
33,904,777
Add column to Pandas DataFrame based on formula
<p>I have a dictionary with JSON values keyed to the value of a column (<code>name</code>) in my data frame, and I want to add some columns to the data frame drawn from the dictionary.</p> <p>I've tried to do this with something like:</p> <pre><code>df['district_name'] = data[df['name']]['district_name'] </code></pre...
<p>You are quite close. Try this:</p> <pre><code>df['district_name'] = df['name'].map(data.get)['district_name'] </code></pre>
python-3.x|pandas
2