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
375,200
53,885,404
Python Setting Values Without Loop
<p>I have a time series dataframe where there is 1 or 0 in it (true/false). I wrote a function that loops through all rows with values 1 in them. Given user defined integer parameter called <code>n_hold</code>, I will set values 1 to n rows forward from the initial row.</p> <p>For example, in the dataframe below I wil...
<p>Completely changed answer, because working differently with consecutive <code>1</code> values:</p> <p><strong>Explanation</strong>:</p> <p>Solution remove each consecutive <code>1</code> first by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html" rel="nofollow noreferrer"><cod...
python|pandas|dataframe
2
375,201
53,819,651
How to normalize column names with '.1' in the column name and not drop any other characters?
<p>I have a df that looks like this:</p> <pre><code>col1_test col1_test.1 abc NaN </code></pre> <p>How do I drop only the <code>.1</code> while keeping all the other characters in the column name? </p> <p>current code to drop <code>.1</code>:</p> <pre><code>df.columns = df.columns.str.extract(r'\.?', exp...
<p>This is not recommended because it becomes difficult to index specific columns when there are duplicate headers. </p> <p>A better solution, however, since trying to perform a <code>groupby</code>, would be to pass a callable.</p> <pre><code>df col1_test col1_test.1 0 abc NaN df.groupby(by=lambda...
python|python-3.x|pandas|dataframe
2
375,202
54,181,590
Pandas - Comparing two Dataframe and finding difference
<p>I have two Dataframes with some sales data as below:</p> <p>df1:</p> <pre><code>prod_id,sale_date,new 101,2019-01-01,101_2019-01-01 101,2019-01-02,101_2019-01-02 101,2019-01-03,101_2019-01-03 101,2019-01-04,101_2019-01-04 </code></pre> <p>df2:</p> <pre><code>prod_id,sale_date 101,2019-01-01,101_2019-01-01 101,20...
<p>You can use <code>drop_duplicates</code></p> <pre><code>pd.concat([df1,df2]).drop_duplicates(keep=False) </code></pre>
python|pandas
0
375,203
54,145,967
Not able to plot the heatmap of one column with respect to others
<p>With the help of the question: <a href="https://stackoverflow.com/questions/39409866/correlation-heatmap">Correlation heatmap</a>, I have tried the following: </p> <pre><code>import pandas import seaborn as sns dataframe = pandas.read_csv("training.csv", header=0,index_col=0) for a in list(['output']): for b i...
<p>You are trying to build a heatmap from <code>pd.Series</code> - this does not work. <code>pd.Series</code> is a 1D object, while <code>seaborn.heatmap()</code> is commonly used for 2D data structures. </p> <p><code>sns.heatmap(corr[['output']])</code> - will do the job</p> <pre><code>df = pd.DataFrame(data=[[1,2,3...
python|python-3.x|pandas|heatmap|correlation
7
375,204
54,214,017
Converting all non-black pixels into one colour doesn't produce expected output
<p>I am trying to select non-black pixel and then colour them to black and the black pixels to white. I used a <a href="https://stackoverflow.com/questions/52735231/how-to-select-all-non-black-pixels-in-a-numpy-array">solution</a> provided on Stack Overflow but so far it isn't working for me.</p> <pre><code>import num...
<p>How about changing</p> <pre><code>black_pixels_mask = np.all(image == [0, 0, 0], axis=-1); </code></pre> <p>to</p> <pre><code>black_pixels_mask = np.all(image == [0, 0, 0], axis=2) </code></pre>
python|numpy|matplotlib|image-processing
0
375,205
54,043,484
Python 3.x: Create dataframe from two dictionaries
<p>I'm working on Python 3.x. What is to be achieved is: merge dictionaries based on keys and form a dataframe. This would clear:</p> <p>What I have:</p> <pre><code>import numpy as np import pandas as pd d1 = {(1, "Autumn"): np.array([2.5, 4.5, 7.5, 9.5]), (1, "Spring"): np.array([10.5, 11.7, 12.3, 15.0])} d2 = {(1,...
<p>Since all keys are present in both dictionaries (according to your comment), you could iterate through the keys of one dictionary and make a dataframe from each dictionary entry for each key:</p> <pre><code>d3 = dict() for k in d1.keys(): d3[k] = pd.DataFrame(np.array([d1[k],d2[k]]).T, columns=["d1","d2"]) </co...
python|python-3.x|pandas|dictionary
1
375,206
53,884,911
pd.read_sql_query single / double quotes formatting
<p>I'm using Python(Jupyter Notebook) and Postgres Database and am struggling to populate a Pandas dataframe.</p> <p>The sql code runs fine using the query builder in pgAdmin4 which is</p> <pre><code>SELECT "Date","Close" FROM test WHERE "Symbol" = 'AA' </code></pre> <p>However I can't get this to work in my Jupyter...
<p>This will work:</p> <pre><code>df = pd.read_sql_query("SELECT Date,Close FROM public.test WHERE Symbol = 'AA'", conn) </code></pre> <p>Sql chars must have single quotes, but column names don't need quotes at all.</p> <p>If you <em>really</em> need double quotes inside sql query, then just make sure you use triple...
python|sql|postgresql|pandas|quotes
2
375,207
54,179,450
AttributeError: type object 'numpy.ndarray' has no attribute '__array_function__' on import numpy 1.15.4
<p>Here the minimal code not working:</p> <pre><code>import numpy </code></pre> <p>Here the stack of error</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/samuele/.local/lib/python3.6/site-packages/numpy/__init__.py", line 142, in &lt;module&gt; f...
<p>Unfortunately, you have mixed two different installation systems. You need to clear everything that was installed when you did <code>pip3 install tensorflow</code>.</p> <p>The easiest is to start from scratch, and only do <code>conda install tensorflow</code>.</p> <p>The more complex version is to remove manually ...
python-3.x|numpy|import|conda
2
375,208
54,232,801
Print Keras Kernel
<p>I have written a custom keras layer and basically set up a kernel that looks like this as an example:</p> <pre><code>[[w1, 0, 0], [w2, w3, 0], [0, w4, w5]] </code></pre> <p>where w1,...w5 are trainable weights and the zero entries are not trainable.</p> <p>Now, I want to confirm if everything is working corre...
<p>So, I was lucky and found an answer in a not-related post. The answer is quite general:</p> <p>For a tensor, defined as a class member of the custom layer, you need to call its evaluation method with the correct session. That is</p> <pre><code>import keras.backend as K # Train your model... sess = K.get_session(...
tensorflow|keras|keras-layer
2
375,209
53,931,557
Convert column in excel date format (DDDDD.tttt) to datetime using pandas
<p>I have a dataframe with multiple columns and want to convert one of those columns which is a date of floats (excel date format - DDDDD.ttt) to datetime. </p> <p>At the moment the value of the columns are like this:</p> <pre><code>42411.0 42754.0 </code></pre> <p>So I want to convert them to:</p> <pre><code>2016-...
<p>Given </p> <pre><code># s = df['date'] s 0 42411.0 1 42754.0 Name: 0, dtype: float64 </code></pre> <p>Convert from Excel to datetime using: </p> <pre><code>s_int = s.astype(int) # Correcting Excel Leap Year bug. days = pd.to_timedelta(np.where(s_int &gt; 59, s_int - 1, s_int), unit='D') secs = pd.to_timed...
python|pandas|datetime|dataframe
1
375,210
53,961,983
How to hide column names while converting pandas dataframe to html using to_html
<p>I have a data set I am transposing with a loop that looks like this.</p> <pre><code> x = [] for index, row in s1.iterrows(): x = row tt = pd.DataFrame(x) </code></pre> <p>I am then using the pandas data frame to html function to send an email for each row of the s1 data frame transposed. My issue is ...
<p>I think there's an easy way, as <code>.to_html()</code> actually has a header flag. Check this out <code>tt.to_html(header=False)</code>?</p>
python|pandas|dataframe
1
375,211
54,127,301
How to parse a lot of txt files with pandas and somehow understand from which file each raw of the table
<p>I have a dataset containing the name, gender, and quantity of people with their names. There are a lot of text files (>100). Each of them has the same information with different quantity parameters but for 1880, 1881 .... 2008 years. Here is a link to make it more clear: <a href="https://github.com/wesm/pydata-book...
<p>There are two issues here:</p> <ol> <li>How to extract year from filename and assign to new column.</li> <li>How to concatenate multiple dataframes.</li> </ol> <p>You can use string slicing and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><...
python|pandas
0
375,212
53,850,611
Python Pandas, deleting NaN
<p>So basically I am stuck on a very simple thing. For some reason when I execute this code:</p> <pre><code>import pandas as pd x = pd.read_csv('titanic.csv') v = x.dropna(axis=0,how="any") z = v[["Survived"]] y = z.where(z == 1) print (y) </code></pre> <p>It still prints values with NaN, even though I have alread...
<p>try:</p> <pre><code>y = z.where(z == 1).dropna(subset=['Survived']) </code></pre>
python|pandas
2
375,213
53,824,848
Mask dataframe matching multiple conditions
<p>I would like mask (or assign 'NA') the value of a column in a dataframe if two conditions are met. This would be relatively straightforward if the conditions were performed row-wise, with something like:</p> <pre><code>mask = ((df['A'] &lt; x) &amp; (df['B'] &lt; y)) df.loc[mask, 'C'] = 'NA' </code></pre> <p>but I...
<p>Here's one solution. The idea is to construct two Boolean masks, <code>m1</code> and <code>m2</code>, from two mapping series, <code>s1</code> and <code>s2</code>. Then use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow noreferrer"><code>pd.Series.mask</code></...
python|python-3.x|pandas|dataframe|series
2
375,214
54,150,976
Dataframe assign blanket criteria if not matching
<p>I have a dataframe organized in the following manner for railcars. I'd like to count by ['Railroad'], but only if it matches 'VER'. If not, I want 'Railroad' to reassign the value to 'NOT' and count by that.</p> <p>Dataframe hierarchy:</p> <pre><code>df1 = df.reset_index().groupby(['Homebase','FINAL ETA','Code Des...
<p>It looks like only the railroad column is changing, try this:</p> <pre><code>ver = (df1['Railroad'] == 'VER') df1['Railroad'] = 'NOT' df1.loc[ver, 'Railroad'] = 'VER' </code></pre>
python|pandas|dataframe
0
375,215
38,169,487
Python sorting numbers in a multicolumn file
<p>I have a file with 4 column data, and I want to prepare a final output file which is sorted by the first column. The data file (rough.dat) looks like:</p> <pre><code>1 2 4 9 11 2 3 5 6 5 7 4 100 6 1 2 </code></pre> <p>The code I am using to sort by the first column is:</p> <pre...
<p>Strings are compared lexicographically (dictionary order):</p> <pre><code>&gt;&gt;&gt; '100' &lt; '6' True &gt;&gt;&gt; int('100') &lt; int('6') False </code></pre> <p>Converting the first item to <a href="https://docs.python.org/2/library/functions.html#int" rel="nofollow"><code>int</code></a> in key function wil...
python|list|sorting|numpy
0
375,216
38,504,907
Reading a .VTK polydata file and converting it into Numpy array
<p>I want to convert a .VTK ASCII polydata file into numpy array of just the coordinates of the points. I first tried this: <a href="https://stackoverflow.com/a/11894302">https://stackoverflow.com/a/11894302</a> but it stores a (3,3) numpy array where each entry is actually the coordinates of THREE points that make tha...
<p>You can use <code>dataset_adapter</code> from <code>vtk.numpy_interface</code>:</p> <pre><code>from vtk.numpy_interface import dataset_adapter as dsa polydata = reader.GetOutput() numpy_array_of_points = dsa.WrapDataObject(polydata).Points </code></pre> <p>From <a href="https://blog.kitware.com/improved-vtk-numpy...
python|arrays|numpy|vtk
8
375,217
38,199,408
How to use the dropna() to drop itme which is < 1?
<p>I have a DataFrame as follow:</p> <pre><code>mydf = pd.DataFrame({'Name1':(4.2, 0.3), 'Name2':(0.2, 4.2), 'Name3':(3.3, 5.5)}, index=('Val1', 'Val2')) </code></pre> <p>How can I drop a column in which any item's value &lt; 1?</p>
<p>This selects columns where all elements are <code>&gt;=1</code> (complement of any of them being smaller than 1):</p> <pre><code>mydf.ix[:, ~(mydf&lt;1).any()] Out[9]: Name3 Val1 3.3 Val2 5.5 </code></pre>
python|pandas
1
375,218
38,059,735
Pandas groupby with categorical and apply copies index to additional column
<p>Consider the following MWE with three alternative last lines:</p> <pre><code>df = pd.DataFrame({'a': np.arange(100)*3}) (df.assign(mybins = lambda df: pd.cut(df['a'],bins=np.linspace(0,300,6))) .groupby('mybins') .sum() #.apply(lambda x: x.sum()) #.apply(lambda x: x.count()/float(len(df))*100) ) </code>...
<p>is that what you want - pay attention at <code>.groupby('mybins')['a']</code> (<strong>['a']</strong>):</p> <pre><code>In [270]: %paste (df.assign(mybins = lambda df: pd.cut(df['a'],bins=np.linspace(0,300,6))) .groupby('mybins')['a'] #.sum() #.apply(lambda x: x.sum()) .apply(lambda x: x.sum()/float(len(...
python|pandas
2
375,219
38,131,287
Pandas: add column with the most recent values
<p>I have two pandas dataframes, both index with datetime entries. The <code>df1</code> has non-unique time indices, whereas <code>df2</code> has unique ones. I would like to add a column <code>df2.a</code> to <code>df1</code> in the following way: for every row in <code>df1</code> with timestamp <code>ts</code>, <code...
<p>You are describing an <a href="https://stackoverflow.com/questions/12322289/kdb-like-asof-join-for-timeseries-data-in-pandas">asof-join</a>, which was just <a href="http://pandas.pydata.org/pandas-docs/version/0.19.0/whatsnew.html#whatsnew-0190-enhancements-asof-merge" rel="nofollow noreferrer">released in pandas 0....
python|datetime|pandas
2
375,220
38,222,126
tensorflow efficient way for tensor multiplication
<p>I have two tensors in tensorflow, the first tensor is 3-D, and the second is 2D. And I want to multiply them like this:</p> <pre><code>x = tf.placeholder(tf.float32, shape=[sequence_length, batch_size, hidden_num]) w = tf.get_variable("w", [hidden_num, 50]) b = tf.get_variable("b", [50]) output_list = [] for ste...
<p>You could use <code>batch_matmul</code>. Unfortunately it doesn't seem <code>batch_matmul</code> supports broadcasting along the batch dimension, so you have to tile your <code>w</code> matrix. This will use more memory, but all operations will stay in TensorFlow</p> <pre><code>a = tf.ones((5, 2, 3)) b = tf.ones((3...
python|tensorflow|deep-learning
2
375,221
38,241,933
how to convert column names into column values in pandas - python
<pre><code>df=pd.DataFrame(index=['x','y'], data={'a':[1,2],'b':[3,4]}) </code></pre> <p>how can I convert column names into values of a column? This is my desired output</p> <pre><code> c1 c2 x 1 a x 3 b y 2 a y 4 b </code></pre>
<p>You can use:</p> <pre><code>print (df.T.unstack().reset_index(level=1, name='c1') .rename(columns={'level_1':'c2'})[['c1','c2']]) c1 c2 x 1 a x 3 b y 2 a y 4 b </code></pre> <p>Or:</p> <pre><code>print (df.stack().reset_index(level=1, name='c1') .rename(columns...
python|pandas
4
375,222
38,282,413
How to change colors of function plots in Tensorboard?
<p>I'm trying to compare different learning-rate-decays using Tensorflow. Therefore I visualize the cost functions in Tensorboard ('EVENTS'-tab). My problem is that the different plots of the functions are in very similar colors making it hard to compare them. Is there any possibility to change those colors?</p>
<p>Just create different summary writes with different log files for each learning rate. Then launch the tensorboard tool using: <code>tensorboard --logdir=tag1:/path/to/summary/one,tag2:/path/to/summary/two</code></p>
tensorflow|tensorboard
9
375,223
38,309,109
matplotlib x-axis formatting if x-axis is pandas index
<p>I'm using iPython notebook's %matplotlib inline and I'm having trouble formatting my plot.</p> <p><a href="https://i.stack.imgur.com/UsRHv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UsRHv.png" alt="Plot that needs x-axis formatting"></a></p> <p>As you can see, my first and last data point a...
<p>You can see the usage of xlim <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlim" rel="nofollow noreferrer">here</a>. Basically in this case if you ran <code>plt.xlim()</code> you would get<code>(0.0, 8.0)</code>. As you have an index that uses text and not numbers the values for xlim are actu...
python|pandas|matplotlib
0
375,224
38,459,793
numpy boolean indexing multiple conditions
<p>I have a two dimensional numpy array and I am using python 3.5. I am starting to learn about Boolean indexing which is way cool. I can do this with my two dimensional array, arr. mask = arr > 127 arr[mask] = 0</p> <p>This works perfect but now I am trying to change this logic to use boolean indexing</p> <pre><cod...
<p>This might help. Consider a numpy array of floating point values foo.</p> <pre><code>import numpy as np foo=np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]) </code></pre> <p>foo yields</p> <pre><code>array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8, 0.8]) </code></pre> <p>This is how you get the values in foo > 0.3</...
python|numpy
6
375,225
38,117,672
Deep Neural Network : Probability issue
<p>I'm working on a keyword spotting with deep neural network (Multi-Layer Perceptron) and I'm facing a following issue. </p> <p>I have to detect a keyword in a speech signal. I use the library Tensorflow and I write my code based on this <a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/exampl...
<p>In the world where numbers are infinitely precise, your model would be slightly different. You would actually use <code>tf.nn.softmax</code> at the end of your model, and optimize for <code>cross_entropy</code>. However, numbers have precision, and computing gradients for cross entropy followed by a softmax during t...
neural-network|tensorflow|probability|deep-learning
0
375,226
66,175,409
Reformat a Pandas dataframe with a tuple in a column?
<p>I have a dataframe that contains a tuple column as follows.</p> <pre><code>import pandas as pd d = {'col1': [('A', 0), ('A', 1), ('A', 2), ('B', 0), ('B', 1), ('B', 2)], 'col2': [1, 1, 1, 2, 2, 2]} df = pd.DataFrame(data=d) # Split the tuple to two cols and drop the tuple col ...
<p>So you can do <code>pivot</code> with <code>rename_axis</code></p> <pre><code>out = df.pivot(index='b1',columns='b2',values='col2').\ rename_axis(None,axis=1).rename_axis(None) Out[101]: 0 1 2 A 1 1 1 B 2 2 2 </code></pre>
python|pandas
2
375,227
66,258,756
Dropping rows based on timeseries using .loc
<p>I have a dataframe with a time series data. The dates have been parsed.</p> <pre><code>data_path = &quot;file.xlsx&quot; data = pd.read_excel(data_path, parse_dates=['date'], index_col='date') </code></pre> <p>I have dates from 2008 to 2017 but I want to drop all rows from 2017. I know that I can select dates by doi...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with test year by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.year.html" rel="nofollow noreferrer"><code>Datetime...
python|pandas|time-series
1
375,228
66,209,735
Copy values from column X+2 (two to the right of X) into column X
<p>I have a dataframe and one every three columns has a name (the others are unnamed 1,2,3...).</p> <p>I want values in the columns that have names to be equal to the value of two columns to the right of that.</p> <p>I was using <code>df.columns.get_loc(&quot;X&quot;)</code> and I can use this to correctly select my de...
<p>this would work, change 8 to fit your columns, or len(columns)//3*3</p> <pre><code>for n in range(0,8,3): df.iloc[:,n]= df.iloc[:,n+2] </code></pre> <p>it doesn't seem we can assign a multi column to a multi column, not sure if that is possible</p>
python|pandas
0
375,229
66,324,649
Can i simplify this creation of an array?
<p>I need to create an array like this with numpy in python:</p> <p><a href="https://i.stack.imgur.com/5bLeP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5bLeP.png" alt="array" /></a></p> <p>This is my current attempt:</p> <pre><code>array = np.zeros([3, 3]) array[0, 0] = 1 array[0, 1] = 2 array[...
<p>definitely :) One option that is straightforward:</p> <pre><code>arr = np.arange(1,4) my_arr = np.vstack((arr, 2*arr, 3*arr)) </code></pre> <p>or you can use broadcasting. <a href="https://numpy.org/doc/stable/user/basics.broadcasting.html" rel="nofollow noreferrer">Broadcasting</a> is powerful and straightforward...
arrays|python-3.x|numpy
2
375,230
66,215,270
Numpy - Searching in a 4D matrix (AKA messed-up meshgrids)
<p>I am sorry if a similar question has been already posted in some way, but I could not find it anywhere so far. My problem is the following:</p> <p>Suppose I have a 4D numpy matrix like this one</p> <pre><code>M= array([[[[0. , 0. , 0. ], [0. , 0. , 0.01]], [[0. , 0.01, 0. ], ...
<p>I don't see a strictly <code>numpy</code> solution because of <a href="https://stackoverflow.com/a/14772313/5431791"><code>this</code></a>. However, you can achieve this without <code>loop</code>s:</p> <pre><code>&gt;&gt;&gt; np.vstack([*map(lambda x: np.argwhere(np.equal(M, x).all(-1)), Points)]) array([[1, 1, 0],...
python|numpy|parsing|array-broadcasting
1
375,231
66,118,334
Pandas parse csv column from dict into table
<p>My csv file:</p> <pre><code>FILE_INFO, CATEGORY, AREA, BOX, NAME &quot;{'id': 1, 'width': 4032, 'height': 3024, 'file_name': 'pic1.jpeg', 'license...
<p>You can iterate over the values in a for loop and use JSON to extract the data you need.</p> <p>So in a for loop you would do something like this:</p> <pre><code>import json for row in rows: json.loads(row.replace(&quot;\'&quot;, &quot;\&quot;&quot;))['file_name'] </code></pre>
python|pandas|csv
1
375,232
66,309,302
multiinput GAN returning error ValueError: Graph disconnected:
<p>Been trying to troubleshoot this all weekend. I'm hoping someone can help.</p> <p>I have a model that would take a normal array and process it within a GAN, it worked but once I changed it to be multi-imput, I started to get:</p> <pre><code>ValueError: Graph disconnected: </code></pre> <p>My original code:</p> <pre>...
<p>When you build multi-input/multi-output models, you must compile and feed the model input and output as arrays, instead of concatenating them like you did. Moreover, the inputs of a model must always be <code>tf.keras.layers.Input</code>. So the correct code would be</p> <pre><code>gan_dataframe_input = Input(shape=...
python|numpy|tensorflow|keras|generative-adversarial-network
1
375,233
66,120,794
I'm Trying to sort pandas aggregation
<p>I'm trying to aggregate and sort data from my dataset, but I don't know how to do. Can someone help me?</p> <pre><code>data = {'message_id': ['1', '1', '1', '1', '2', '2', '2'], 'to': ['one', 'two', 'three', 'four', 'five', 'six', 'five'], 'idt': ['1','2','3','4','5','6','5'] } df = pd.Data...
<p>In <code>python set</code> is not defined order, so cannot sorting or change ordering there, possible soution is use <code>dict.fromkeys().keys()</code> trick for remove duplicates and output is <code>tuple</code> (which should be sorted and there is also defined order):</p> <pre><code>f = lambda x: dict.fromkeys(x)...
python|pandas
1
375,234
66,152,428
Python Pandas apply qcut to grouped by level 0 of multi-index in multi-index dataframe
<p>I have a multi-index dataframe in pandas (date and entity_id) and for each date/entity I have obseravtions of a number of variables (A, B ...). My goal is to create a dataframe with the same shape but where the values are replaced by their decile scores.</p> <p>My test data looks like this:</p> <p><a href="https://i...
<p>You solution appears over complicated. Your terminology is none standard, multi-indexes have levels. Stated as <code>qcut()</code> by level 0 of multi-index (not talking about sub-frames which are not pandas concepts)</p> <p>Bring it all back together</p> <ul> <li>use <code>**kwargs</code> approach to pass argume...
python|pandas|apply|multi-index
2
375,235
66,218,802
how to remove auto indexing in pandas dataframe?
<p>How to remove auto indexing in <code>pandas</code> dataframe? drop index does not work. So when I used <code>df.iloc[0:4]['col name']</code>, it always returns two-column, one for the actual data that I need, one for the auto row index. How could I get rid of the auto indexing and only return the column that I need?...
<p>If you work in JupyterLab / Jupyter Notebook, use the command</p> <pre><code>iloc[0:4]['col name'].style.hide_index() </code></pre> <hr /> <p><em>The explanation:</em></p> <p>Dataframes <strong>always</strong> have an index, and there is no way of how to remove it, because it is a <em>core part</em> of every datafra...
python|python-3.x|pandas|dataframe
1
375,236
65,924,250
Apply a function to specific rows of a Numpy array
<p>Let's say I have a 2 dimensional array, a function, and a &quot;mask&quot; of specific rows, as below:</p> <pre><code>my_array = np.array([[0,1],[2,3],[4,5],[6,7]]) my_mask = np.array([0,1,0,1]) my_func = lambda x: x * 2 </code></pre> <p>How can I apply this function to the rows of the the array that are true in the...
<p>You can use boolean indexing:</p> <pre><code>mask = my_mask==1 my_array[mask] = my_func(my_array[mask]) </code></pre> <p>Output:</p> <pre><code>array([[ 0, 1], [ 4, 6], [ 4, 5], [12, 14]]) </code></pre>
python|arrays|numpy
1
375,237
66,027,895
How to replace only NaN values in a column, with a specific function?
<p>I have a dataframe that looks like this:</p> <pre><code>article_id title NaN title_1 NaN title_2 NaN title_3 '202102011404103' title_4 '202102011404104' title_5 NaN title_6 </code></pre> <p>I would like to apply something like this code, to...
<p>You can use <code>apply</code> and <code>lambda</code> to achieve your goal.</p> <p>Here I'm applying the <code>now()</code> function to <code>NaN</code> but it can be any method you want.</p> <pre><code>import pandas as pd import numpy as np from datetime import datetime df = pd.DataFrame({ &quot;article_id&qu...
python|pandas
2
375,238
66,219,760
How to remove word which i connect with special character in python
<p>I have qeustion for you ! How to remove all words containing @, such as @AmericanVirgin. When I do</p> <pre class="lang-py prettyprint-override"><code>df['text'] = df ['text'].Str.replace('@', '') only removes @ </code></pre> <p>This is my dataframe :</p> <pre class="lang-none prettyprint-override"><code>weet_id air...
<p>Input :</p> <pre><code>tweet_id airline sentiment \ 0 0 570306133677760513 neutral 1 1 570301130888122368 positive 2 2 570301083672813571 neutral text Raiting \ 0 @VirginAmerica What @dhepburn said 2 ...
python|pandas|dataframe|for-loop
0
375,239
66,314,087
Using Pandas groupby in user defined function: why I can't use aggregation functions to groupyby
<p>I defined the following user function:</p> <pre><code>def group_by(df, columns): x = df.groupby(columns).sum() x = x.reset_index() return x </code></pre> <p>It works!</p> <p>But the following does not! :</p> <pre><code>def group_by(df, columns, aggfunc=sum): x = df.groupby(columns).aggfunc() x = ...
<p>When doing <code>df.groupby(columns).aggfunc()</code> you are doing a method call on the <a href="https://pandas.pydata.org/docs/reference/groupby.html" rel="nofollow noreferrer">groupby object</a>, this means Python will look for a method called aggfunc on this object. As this method does not exists it throws an At...
python|pandas|group-by
1
375,240
66,304,452
How to feed images into a CNN for binary classification
<p>I am trying to create a convolutional neural network that can detect whether or not a person is having a stroke, based upon a picture of their face. The images for my dataset are contained within a directory called <em>CNNImages</em>, which contains two subdirectories: <em>Strokes</em> and <em>RegularFaces</em>. Eac...
<p><code>(x_train, y_train), (x_test, y_test) = dataset</code> part of the code raises error. Because, when you use <code>tf.keras.preprocessing.image_dataset_from_director()</code>, it returns batches of images, <strong>it does not split</strong> your data into train set and test set. So you need to declare seperately...
python|tensorflow|keras|neural-network|conv-neural-network
0
375,241
66,175,410
Generating data frames, but only getting 1 row
<p>I wish to create a dataframe using faker library in Python, but I am able to get only a single row, dont understand whats the issue in the code. here's the same:</p> <pre><code>import pandas as pd for dat in range(int(input())): dat = [[fake.email(),fake.phone_number(),fake.address(),fake.name(),fake.date(),fak...
<p>You overwrite <code>dat</code> in each loop. You need to append the new data to the existing:</p> <pre><code>dat = [] for _ in range(int(input())): dat.append([fake.email(), fake.phone_number(), fake.address(), fake.name(), fake.date(), fake.pyint(0,3)]) </code></pre>
python|pandas|dataframe|faker
1
375,242
66,117,980
numpy: Randomly split array into 3 not equal parts
<p>Is there anyway so I can split an array into 3 not equal parts, with no duplicates, for example</p> <p>array1 = 70% of the elements of the array</p> <p>array2 = 10% of the elements of the array</p> <p>array3 = 20% of the elements of the array</p> <p>but without taking the same element twice?</p> <p>Thank you!</p>
<p>If you are okay with losing the original order of the array, you can simply randomly shuffle the array, and then split the array as you desire.</p> <pre><code>a = np.arange(100) # Example array. split1 = int(0.7 * len(a)) split2 = int(0.8 * len(a)) np.random.shuffle(a) p1 = a[:split1] p2 = a[split1:split2] p3 = a[...
python-3.x|numpy|random
0
375,243
66,317,262
Pandas: df (dataframe) is not defined
<p>I'm trying to load and edit a dataframe from a <code>xlsx</code> file. The file is located in the path which I defined in the variable <code>einlesen</code>. As soon as the bug is fixed, I want to delete a row and save the new dataframe in a new <code>xlsx</code> file in a specific path.</p> <pre><code>import os imp...
<p>You get the error because you only defined <code>df</code> inside the <code>rowdrop</code> function; variables defined inside function can only be accessed inside the functions unless you do something to change that.</p> <p>Change your function to return the <code>df</code>:</p> <pre><code>def rowdrop(): ei...
python|pandas|function|dataframe|nameerror
-1
375,244
65,958,671
Why does my model learn with Ragged Tensors but not Dense Tensors?
<p>I have a string of letters that follow a &quot;grammar.&quot; I also have boolean labels on my training set of whether the string follows &quot;the grammar&quot; or not. Basically, my model is trying to learn determine if a string of letters follows the rules. It's a fairly simple problem (I got it out of a textbook...
<p>So turns out the answer was that the shape of the dense tensor was different across the training set and validation set. This was because the longest sequence differed in length between the two sets (same with the test set).</p>
tensorflow|machine-learning|keras|machine-learning-model
0
375,245
66,097,006
How to concatenate key values of JSON object stored in pandas dataframe cell into a string per row?
<h3>My question is:</h3> <p>how to concatenate key values of JSON object stored in pandas dataframe cell into a string per row? Sorry, I feel my problem is pretty straight-forward but I cannot find a good way to phrase it.</p> <h3>My context is:</h3> <p>Let's say I have a pandas dataframe, df, that contains a column na...
<pre class="lang-py prettyprint-override"><code>In [16]: df['x'] = df['participants'].map(lambda x: ', '.join(str(i['participantId']) for i in x)) ...: print(df['participants'][0]) ...: print(df['x'][0]) ...: [{'participantId': 1, 'championId': 7}, {'participantId': 2, 'championId': 350}, {'participantId': ...
python|json|pandas|dataframe
1
375,246
65,964,411
How to write a earlystopping function in Python
<p>My loss is like this:</p> <pre class="lang-py prettyprint-override"><code>loss = np.sum(np.square(A-B)) </code></pre> <p>How to write help function that would carry out &quot;earlystopping&quot; like in Keras?</p> <p>Purpose:</p> <p>If the loss is rising or does not fluctuate much then we stop and the get <code>A</c...
<p>I looked into Keras sources and find out code for EarlyStopping. I made my own callback, based on it:</p> <pre><code>class EarlyStoppingByLossVal(Callback): def __init__(self, monitor='val_loss', value=0.00001, verbose=0): super(Callback, self).__init__() self.monitor = monitor self.value...
python-3.x|numpy|machine-learning|neural-network
0
375,247
66,117,429
Replacing data in column with mean value of corresponding bin?
<p>I make bins out of my column using pandas' <code>pd.qcut()</code>. I would like to, then apply smoothing by corresponding bin's mean value.</p> <p>I generate my bins with something like</p> <pre class="lang-py prettyprint-override"><code>pd.qcut(col, 3) </code></pre> <p>For example, Given the column values <code>[4,...
<p>It's exactly as you laid out. Using this technique to get <a href="https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value">nearest</a></p> <pre><code>df = pd.DataFrame({&quot;col&quot;:[4, 8, 15, 21, 21, 24, 25, 28, 34]}) df2 = df.assign(bin=pd.qcut(df.col, 3), ...
python|pandas
2
375,248
66,251,848
Dimensions Don't Match for Decoder in Tensorflow Tutorial
<p>I am following the Convolutional Autoencoder tutorial for tensorflow, using tensorflow 2.0 and keras, found <a href="https://www.tensorflow.org/tutorials/generative/autoencoder" rel="nofollow noreferrer">here</a>.</p> <p>Using the provided code for building a CNN, but adding one more convolutional layer to both the ...
<p>Remove <code>stride=2</code> in your last encoder layer, and add <code>stride=2</code> in your last decoder layer.</p> <pre><code>from tensorflow.keras import layers from tensorflow.keras import Model class Denoise(Model): def __init__(self): super(Denoise, self).__init__() self.encoder = tf.keras.Sequent...
python|tensorflow|keras|autoencoder|dimensions
1
375,249
65,997,499
Python statsmodel outpput and Excel/Google Sheet output doesn't match
<p>I have a small dataset, for some reason, the output doesn't match with Excel's.</p> <p>Here's what I did. I have to columns:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Miles Traveled</th> <th>Travel Time</th> </tr> </thead> <tbody> <tr> <td>89</td> <td>7.0</td> </tr> <tr> <td>66</td...
<p>By default, the <code>OLS</code> class doesn't include the constant term in the linear model. You can use <code>sm.add_constant</code> to create the appropriate <code>exog</code> argument for <code>OLS</code>:</p> <pre><code>In [36]: milesTraveled = [89.0, 66.0, 78.0, 111.0, 44.0, 77.0, 80.0, 66.0, 109.0, 76.0] In...
python|pandas|numpy|statsmodels
0
375,250
66,164,487
How to use Pandas split for retaining both parts of column?
<p>I have a file with columns such as:</p> <pre><code> A B C f&gt;g f=313/g=6535 1:123456 r&gt;t r=2/t=7020 1:56789 g&gt;f g=2/f=6764 1:65555 t&gt;r t=5337/r=677 1:115675 </code></pre> <p>and I am struggling with splitting them. I need not only to split them, but also save both parts ...
<p>You can try something like</p> <pre><code>df[['name_1', 'name_2']] = df['C'].str.split(':', expand=True) </code></pre> <p>Which results in what you want</p> <pre><code> A B C name_1 name_2 0 f&gt;g f=313/g=6535 1:123456 1 123456 1 r&gt;t r=2/t=7020 1:56789 1 56789 2 g&...
python-3.x|pandas
0
375,251
66,042,243
Pandas extrac number with a decimal operator afer $ from a string
<p>also there are several <a href="https://stackoverflow.com/questions/61897051/pandas-extract-number-with-decimals-from-string">similar questions</a> to that, I am still not able to solve my issue.</p> <p>I have a pandas column from a poker game and want to analyze the pot size out of it, therefore I need to extract t...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({'action':['Player (8, 5) won the $5.40 main pot with a Straight','Player (A, 2) won the $21.00 main pot with a flush']}) &gt;&gt;&gt; df['action'].str.extract(r'\$(\d+(?:[,.]\d+)*)', expan...
python|regex|pandas
2
375,252
66,254,073
Creating percent of total column in pandas
<p>I can't seem to figure out how to add a % of total column for each state and year in pandas.</p> <p>my data looks like this</p> <pre><code>year type Arizona_total Utah_total California_total Colorado_total 2018 Total 163,176 90,344 343,343 32,343 2018 bio. 272 270 23...
<p>Try this.</p> <pre><code>total = np.sum(df.ix[:,'Arizona_total':].values) df['percent'] = df.ix[:,'Arizona_total':].sum(axis=1)/total * 100 df </code></pre>
python|pandas
0
375,253
66,114,826
How can I append a data frame to another data frame?
<p>I have the following python pandas data frame:</p> <pre><code>master = pd.DataFrame(columns = ['Development id', 'Development Name', 'Integrated Development', 'Developer id', 'Developer', 'Ultimate Developer id', 'Ultimate Developer', 'Development Type', 'Sub Development Type', 'Joint-Venture', 'Year Completed', 'La...
<p>In fact, you can concat the xlsx file's all sheets together. then filter the condition.</p> <pre><code>xl = pd.ExcelFile('Template For Developer Footprint.xlsx') df = pd.concat([xl.parse(sheet_name) for sheet_name in xl.sheet_names ], ignore_index=True) cond = (df['Development Typ...
python|pandas|append
0
375,254
66,090,211
how to merge/concat/join 2 dataframes with a non-unique multi-index to reconcile the content?
<p>I have 2 below dataframes from 2 sources, the 3 white columns are indexes. These are from 2 reports about historical trades. the trades can only be compared when 3 columns &quot;Trade date&quot; &quot;Exchange Instrument&quot; and &quot;Prompt date&quot; are the same. &quot;Trade date&quot; is because they were repo...
<p>Dealing with non-unique indexing:</p> <pre><code>from seaborn import load_dataset #Create one dataframe with unique indexes, set multiindex df = load_dataset('tips') df = df.set_index(['day', 'time', 'sex', 'smoker']) #Create a unique label per inner most index df = df.set_index(df.groupby(level=[0,1,2,3]).cumcount...
python|pandas
2
375,255
66,312,962
Pandas DataFrame groupby, count and sum across columns
<p>I have a dataset like the following. It has the cumulative vehicle counts over time.</p> <p><a href="https://i.stack.imgur.com/81Nef.png" rel="nofollow noreferrer">Image Describing the Expected Output</a></p> <pre><code>LcounterCar,LcounterTruck,LcounterBus,LcounterMotorcycle,LcounterVan,Ltime,RcounterCar,RcounterTr...
<p>There is an inconsistency between your data and what you describe</p> <ul> <li>consider left &amp; right as separate data sets</li> <li>you describe <code>sum()</code> not <code>count()</code>, hence have used <code>sum()</code></li> <li><code>unstack()</code> the columns so that it becomes a straight forward <code...
pandas|dataframe|count|pandas-groupby
0
375,256
65,961,765
Using slice/mask instead of a for-loop to find items in an array
<pre><code>p= np.array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]) </code></pre> <p>I have the above array and need to find the items that are divisible by 2 and 3 without converting it to a flat array using for-loops and then slicing/masking.</p> <p>I was able to ...
<p>You nearly had it!</p> <pre><code>mask=np.logical_and(p%2==0,p%3==0) </code></pre> <p>gives you <code>True</code> where <code>p % 2 == 0 and p % 3 == 0</code>.</p> <pre><code>mask = array([[False, False, False, False, False], [ True, False, False, False, False], [False, True, False, False, False], ...
python|arrays|numpy
1
375,257
66,246,333
cannot stack numpy arrays with hstack in numba
<p>I have one matrix <code>mat</code> of the type</p> <pre><code>array([[0.00000000e+00, 1.98300000e+03, 1.57400000e+00, ..., nan, nan, 2.38395652e+00], [0.00000000e+00, 1.98400000e+03, 1.80600000e+00, ..., nan, 1.38395652e+00, 2.29417391e+00], [0.00000000e...
<p>Numba doesn't understand the <code>[:,None]</code>indexing for reshaping. Indeed, the latter is equivalent to <code>[:,np.newaxis]</code>, as you may already know, and at the present time, <code>np.newaxis</code> isn't a <a href="https://numba.pydata.org/numba-doc/dev/reference/numpysupported.html" rel="nofollow no...
numpy|matrix|vector|numba|hstack
1
375,258
65,951,501
Merge multiple .npy files into single .npy file
<p>I have a folder in which I have 100+ .npy files. The path to this folder is '/content/drive/MyDrive/lung_cancer/subset0/trainImages'.</p> <p>This folder has the .npy files as shown in the image <a href="https://i.stack.imgur.com/0kAcu.png" rel="nofollow noreferrer">the .npy files</a></p> <p>The shape of each of thes...
<p>So I found the answer out by myself and I am attaching the code below if anyone needs it. Change it according to your needs..</p> <pre><code>import os import numpy as np path = '/content/drive/MyDrive/lung_cancer/subset0/trainImages/' trainImages = [] for i in os.listdir(path): data = np.load(path+i) trainImages...
numpy|numpy-ndarray
2
375,259
65,936,263
Can I train in tensorflow with separate CUDA version in anaconda environment
<p>I need to train a model in TensorFlow-gpu==2.3.0 which needs the CUDA version to be 10.1. But when I type 'nvidia-smi' it shows CUDA version to be 10.0.</p> <p>I created a conda environment using, &quot;<strong>conda create -n tf2-gpu tensorflow-gpu cudatoolkit=10.1</strong>&quot; after initiating training, it throw...
<p>Yes, you can create two virtual environments in Anaconda with different tensorflow version. But <code>CUDA</code> and <code>CuDNN</code> will be installing compatible to that specified <code>tensorflow-gpu</code>.</p> <p>You can find <code>tensorflow-gpu</code> build configuration details <a href="https://www.tensor...
python-3.x|tensorflow|nvidia
0
375,260
66,167,521
Pandas: How can I substract an array from a column repeatedely
<p>I have monthly average temperature data for certain year, lets say 1900, so the dataframe looks like:</p> <pre><code>year | month | temp -----+-------+------- 1900 | 1 | 18.5 1900 | 2 | 18.8 1900 | 3 | 21.4 ... 1900 | 12 | 18.4 </code></pre> <p>Then I have monthly average temperatures that goes from 1...
<p>First create <code>Series</code> by index from months by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a>, so possible mapping original months by <a href="http://pandas.pydata.org/pandas-docs/stable/refe...
python|pandas|numpy
2
375,261
66,075,257
Select columns based on exact row value matches
<p>I am trying to select columns of a specified integer value (24). However, my new dataframe includes all values = and &gt; 24. I have tried converting from integer to both float and string, and it gives the same results. Writing &quot;24&quot; and 24 gives same result. The dataframe is loaded from a .csv file.</p> <p...
<p>Please try out the below codes. I'm assuming that the data type of &quot;hours&quot; and &quot;averages_590_nm_minus_blank&quot; is float. If not float, convert them to float.</p> <pre><code>data_PM1_query24 = data_PM1.query('hours == 24 &amp; averages_590_nm_minus_blank &gt; 0.3') </code></pre> <p>or you can also u...
pandas|dataframe
0
375,262
66,219,625
Cannot setup package in conda environment with Pytorch installed
<p>All</p> <p>After setting up the PyTorch 1.7.1 with CUDA 11.2 on a conda virtual environment, I run <code>python setup.py install</code> it always returns me the following error message.</p> <pre><code>Traceback (most recent call last): File &quot;setup.py&quot;, line 2, in &lt;module&gt; from torch.utils.cpp_e...
<p>Finally, I find the solution by just using the <code>pip</code> from the Pytorch official website.</p> <pre><code>pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio===0.7.2 -f https://download.pytorch.org/whl/torch_stable.html </code></pre>
anaconda|pytorch
2
375,263
66,084,663
extracting hour and minutes from a cell in pandas column
<p><a href="https://i.stack.imgur.com/NBVNq.png" rel="nofollow noreferrer">Example</a></p> <p>How can I split or extract 04:38 from 04:38:00 AM in a pandas dataframe column?</p>
<p>Using <code>str.slice</code>:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;hm&quot;] = df[&quot;time&quot;].str.slice(stop=5) </code></pre>
pandas|time
0
375,264
66,218,036
Question on discrete convolution with python
<p>I am struggling to understand why the np.convolve method returns an N+M-1 set. I would appreciate your help.</p> <p>Suppose I have two discrete probability distributions with values of <strong>[1,2]</strong> and <strong>[10,12]</strong> and probabilities of <strong>[.5,0.2]</strong> and <strong>[.5,0.4]</strong> res...
<p>I have managed to find the answer to my own question after understanding convolution a bit better. Posting it here for anyone wondering:</p> <p>Effectively, the convolution of the two &quot;signals&quot; or probability functions in my example above is not correctly done as it is nowhere reflected that the events [1,...
python|numpy|convolution
1
375,265
66,280,320
What would be the best way to convert a text file to a pandas dataframe?
<p>I have a text file that essentially goes.</p> <pre><code>Number|Name|Report 58|John|John is great John is good I like John [Report Ends] </code></pre> <p>and repeats over and over for different people.</p> <p>I want to turn this into a dataframe like the following</p> <pre><code>Number Name Report 58 John John...
<p>With a few lines of manual parsing, you can extract the info and adapt it before reading it into your dataframe.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd with open('info.txt', 'r') as fp: info = fp.readlines() df_dicts = [] cd = None for line in info[1:]: line = line.replace('\...
python|pandas|dataframe|txt
1
375,266
66,186,565
Using panda to convert string "yes" to 1 but failed
<p>I'd like to convert &quot;Yes&quot;and &quot;No&quot; from column&quot;ServiceLevel&quot; to &quot;1&quot; and &quot;0&quot;. This is my code:</p> <pre><code>mydata['ServiceLevel'].replace(to_replace ='Yes',value = 1,inplace = 'True') mydata['ServiceLevel'].replace(to_replace ='No', value = 0,inplace = 'True') myd...
<p><code>inplace</code> is a boolean argument - it takes either <code>True</code> or <code>False</code>, but you passed the <strong>string</strong> <code>'True'</code> (note the quotes). Remove the quotes to get a boolean literal, and you should be fine:</p> <pre class="lang-py prettyprint-override"><code>mydata['Servi...
python|pandas
1
375,267
66,063,155
Multiple time range selection in Pandas Python
<p>I have time-series data in CSV format. I want to calculate the mean for a different selected time period on a single run of the script, e.g. <code>01-05-2017: 30-04-2018, 01-05-2018: 30-04-2019</code> so on. Below is sample data</p> <p><a href="https://i.stack.imgur.com/A5auK.png" rel="nofollow noreferrer"><img src=...
<p>If you use dates as an index, you can extract the data with the conditions included in the desired range.</p> <pre><code>import pandas as pd import numpy as np import io data = ''' Date Mean 18-05-2016 0.31 07-06-2016 0.32 17-07-2016 0.50 15-09-2016 0.62 25-10-2016 0.63 04-11-2016 0.56 24-11-2016 0.56 14-12-2016 0....
python|pandas|time-series
0
375,268
66,251,149
How to create a grid in matplotlib out of a 2D numpy array where the items are classes
<p>I'm working with a 2D NumPy array of n dimensions where the items are a class Square that has a state of either a 1 or a 0. I didn't want to create a new array that contains the int values of my classes so is there a way I can map my array to a colored grid?</p> <pre><code>import numpy as np from random import randr...
<p>You can either create a numeric array directly via <code>np.array([[Square(...).state for y in ...] for x in ...])</code>. Or transform each element of the array of Square<code>s</code> to get their <code>state</code>:</p> <pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt from mat...
python|arrays|numpy|matplotlib|grid
1
375,269
66,202,758
Python AttributeError: 'list' object has no attribute 'to_csv'
<p>I'm currently encountering an error with my code, and I have no idea why. I originally thought it was because I couldn't save a csv file with hyphens in it, but that turns out not to be the case. Does anyone have any suggestions to what might be causing the problem. My code is below:</p> <pre><code>import pandas as ...
<p>The function <code>pd.read_html</code> returns a list of DataFrames found in the HTML source. Use <code>df_list[0]</code> to get the DataFrame which is the first element of this list.</p>
python|pandas|dataframe|export-to-csv
1
375,270
65,965,272
TypeError: 'in <string>' requires string as left operand, not NoneType
<p>I am trying to create a simple scraper to gatherbasketball stats. I was able to get the info I want, however, I can't figure out how to organized it all in a table.</p> <p>I keep getting a &quot;TypeError: 'in ' requires string as left operand, not NoneType.&quot;</p> <p>Please see my code below:</p> <pre><code>impo...
<p>Pandas already has a built-in method to get a dataframe from HTML which should make things way easier here.</p> <p><strong>Code</strong></p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd url = 'https://basketball.realgm.com/ncaa/boxscore/2021-01-29/North-Texas-at-Rice/367436' page = r...
python|pandas|web-scraping|beautifulsoup|screen-scraping
1
375,271
66,234,547
How to convert 'float64' to timestamp in pandas dataframe
<p>Here's my data</p> <pre><code>id enter_time 1 1.481044e+12 2 1.486d74e+12 </code></pre> <p>Here's my expected output</p> <pre><code>id enter_time enter_timestamp 1 1.481044e+12 2017-07-14 08:10:03 2 1.486774e+12 2017-07-15 08:10:00 </code></pre> <p>Note: value in &quot;enter_timestamp&quot; in expectatio...
<p>Try using pandas to_datetime() (I assumed that the character 'd' in your second input float is a typo, so I replaced it):</p> <pre><code>import pandas as pd df = pd.DataFrame([(1, 1.481044e+12), (2, 1.48674e+12)], columns=['id', 'enter_time']) df['enter_timestamp'] = pd.to_datetime(df['enter_time'], unit='ms') df ...
python|pandas|dataframe|timestamp
1
375,272
66,245,217
JSON inside column DataFrame
<p>I'm trying to make a <strong>bulk insert</strong> of a dataframe, my table in Postgres has a field type <strong>JSON</strong> and I want to insert raw JSON on it, but when I'm trying to make it, python change from double quote to <code>&quot;</code> to single quote <code>'</code> and it technically destroys my JSON ...
<p>pandas has automagically converted the json into a dictionary object. You can easily convert a dictionary to json using <code>dumps</code> from the built in <code>json</code> module.</p> <pre class="lang-py prettyprint-override"><code>import requests from json import dumps import pandas import psycopg2 #sample dat...
python|sql|json|pandas|postgresql
0
375,273
66,128,264
Vectorization & ValueError, but not from "or" and "and" operators
<p>This <a href="https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o">question and answer chain</a> do a great job explaining how to resolve ValueErrors that come up when utilizing conditionals, e.g. &quot;or&quot; instead of |, and &quot;and&quot; instead...
<p>You could try out numpy's <code>vectorize</code>:</p> <pre><code>vis_prime = np.vectorize(is_prime) df['optimize prime'] = vis_prime(df['Number']) </code></pre> <p>That gives you:</p> <pre><code> Number map prime apply prime optimize prime 0 0 False False False 1 1 False ...
python|pandas|numpy|vectorization|apply
2
375,274
66,123,800
Pandas drop nan in a specific row ('Feb-29') and shift remaining rows up
<p>I have a pandas dataframe containing several years of timeseries data as columns. Each starts in November and ends in the subsequent year. I'm trying to deal with NaN's in non-leap years. The structure can be recreated with something like this:</p> <pre><code>import pandas as pd import numpy as np from datetime imp...
<p>It sounds like you don't actually want to shift dates up, but rather number them correctly based on the day of the year? If so, this will work:</p> <p>First, make the DataFrame long instead of wide:</p> <pre><code>df = pd.DataFrame( { &quot;2016&quot;: {&quot;Feb-28&quot;: 36, &quot;Feb-29&quot;: 85, &qu...
python|pandas|dataframe|numpy|nan
1
375,275
66,060,254
Google Cloud Platform - AI Platform: why do I get different response body when calling API?
<p>I created 2 models on Google Cloud AI Platform and I am wondering why do I get different response body when calling REST API with Python?<br /> To be more specific:</p> <ul> <li>In the first case, I get 2 dictionaries (keys: &quot;predictions&quot; and &quot;dense_1&quot;, the latter is the output layer name of my t...
<p>I have reproduced the same behavior.<br/> From the list of endpoints, I have already tested the following:</p> <ul> <li>europe-west1</li> <li>asia-east1</li> <li>us-east1</li> <li>australia-southeast1</li> </ul> <p>And neither of them returns the output layer’s name like the global endpoint does.</p> <p>I have alrea...
python|tensorflow|google-cloud-platform|google-ai-platform
1
375,276
66,210,021
Is there a way to make numpy work with Maya 2020?
<p>I have Python 3.9.1 with numpy 1.19.4 install, and Maya 2020. I have installed a plug-in (SMPL, actually, from here: <a href="https://smpl.is.tue.mpg.de/downloads" rel="nofollow noreferrer">https://smpl.is.tue.mpg.de/downloads</a>), loads without any problems, but errors when it hits the first line that actually ref...
<p>OK, solved! Thanks @mad-physicist for nudging me towards the correct direction.</p> <p>The issue boiled down to requiring a maya-compatible build of numpy, to be pip-installed under the specific python instance (mayapy.exe) that ships with the Maya installation.</p> <p>The details here: <a href="https://forums.autod...
python|numpy
1
375,277
66,192,477
Iterating through multiple rows using multiple values from nested dictionary to update data frame in python
<p>I created nested dictionary to keep multiple values for each combination, example rows in the dictionary is as follows:-</p> <p><code>dict = {'A': {B: array([1,2,3,4,5,6,7,8,9,10]), C: array([array([1,2,3,4,5,6,7,8,9,10],...}}</code></p> <p>There are multiple As and in that multiple arrays for each array. Now I want...
<h1>EDIT Ver 2: Reference Dict and pick dict index val</h1> <p>The dictionary you created is a big confusing. I assume you wanted to reference it like the way I have shown (not an array of array as shown in C). Also assume <code>B</code> and <code>C</code> are values and not variables <code>B</code> and <code>C</code>....
python|arrays|pandas|dictionary|for-loop
0
375,278
65,959,870
Pandas Equivalent for SQL window function and rows range
<p>Consider the minimal example</p> <pre><code>customer day purchase Joe 1 5 Joe 1 10 Joe 2 5 Joe 2 5 Joe 4 10 Joe 7 5 </code></pre> <p>In BigQuery, one would do something similar to this to get how much the customer spent in the last...
<p>Not sure if this is the right way to go, and this is limited since only one customer is provided; if there were different customers, I would use <code>merge</code> instead of <code>map</code>; Note also that there is also an implicit assumption that the days are ordered in ascending already:</p> <p>Get the purchase ...
pandas|google-bigquery|range|window-functions
2
375,279
66,208,359
Delete rows from dataframe if column value does not exist in another dataframe
<p>I have two datasets, each with two columns (can be made into one column) and 1000s of rows.</p> <pre><code>A = pd.DataFrame([['07/05/2013 08:00', 1.871287], ['07/05/2013 08:15', 1.878118], ['07/05/2013 08:30', 1.882696], ['07/05/2013 08:45', 1.891523], ['07/05/2013 09:00', 1.876457]], columns=['C', 'D']) B = pd.Data...
<p>Your question doesn't contain enough information. So I'll try to guess and show you a toy example. If your using pandas then the solution would be:</p> <pre><code>&gt;&gt;&gt; df1 = pd.DataFrame([x for x in pd.date_range('1/1/2020', '3/1/2020')], columns=['date']) &gt;&gt;&gt; df2 = pd.DataFrame([x for x in pd.date_...
python|pandas|dataframe
4
375,280
66,003,985
How to do image recognition on nearly all black images?
<p>I've setup a camera in a squash club and want it to tell me if the squash court is occupied or empty. I trained it with a few hundred images of occupied and empty courts and the results are good.</p> <p>Now the catch is sometimes the club closes early and the lights get turned off. So I basically have almost black i...
<p>Think I figured it out by just using Imagemagick command line. I can convert the image to HSI or LAB and get the brightness (Intensity or Luminosity) from the average of the I or L channel.</p> <pre><code>convert court1.jpg -colorspace HSI -channel b -separate +channel -scale 1x1 -format &quot;%[fx:100*u]\n&quot; i...
tensorflow|computer-vision|image-recognition
0
375,281
66,104,657
How to fill NaN based on groupby transform without loosing the column grouped by?
<p>I have a dataset containing heights, weights etc, and I intend to fill the NaN values with the mean value for that gender.</p> <p>Example dataset:</p> <pre><code> gender height weight 1 M 5 NaN 2 F 4 NaN 3 F NaN 40 4 M NaN 50 </code...
<p>How about looping through the 2 columns you want to fill, and perform <code>GroupBy.transform</code>, grouping by 'gender':</p> <pre><code>for col in ['height','weight']: df[col] = df.groupby('gender')[col].transform(lambda x: x.fillna(x.mean())) print(df) gender height weight 0 M 5.0 50.0 1 ...
python|pandas
1
375,282
52,621,497
Pandas - group by column and transform the data to numpy array
<p>Having the following data frame, group A have 4 samples, B 3 samples and C 1 sample:</p> <pre><code> group data_1 data_2 0 A 1 4 1 A 2 5 2 A 3 6 3 A 4 7 4 B 1 4 5 B 2 5 6 B 3 6 7 C ...
<p>First is necessary add missing values - first solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="noreferrer"><code>unstack</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="noreferrer"><code>st...
python|pandas|pivot|grouping
18
375,283
52,723,136
Iterating by index groups in python
<p>I need to send VIN data to an api in groups. The VINs are grouped by their first three letters called a <code>wmi</code>. The <code>wmi</code> is the data frames index. I'm testing this as I go, and I cannot get just the VINs to print when trying to call by groups. The code below is the closest I got after a few ...
<p>What about <code>apply</code> for grouped data?</p> <pre><code>def do_something(df): print(df) df = pd.DataFrame(columns = ["vin"], data = ['LHJLC79U58B001633','SZC84294845693987', 'LFGTCKPA665700387','L8YTCKPV49Y010001', 'LJ4TCB...
python-3.x|pandas|iterator
0
375,284
52,878,460
How to calculate the accuracy when dealing with multi-class mutlilabel classification in tensorflow?
<p>I am working with FER2013Plus dataset from <a href="https://github.com/Microsoft/FERPlus" rel="nofollow noreferrer">https://github.com/Microsoft/FERPlus</a> which contains the fer2013new.csv file. This file contains labels for each image in the dataset. An example on labels could be:</p> <p>(4, 0, 0, 2, 1, 0, 0, 3)...
<p>Here is an excerpt from the paper:</p> <p>"We take the majority emotion as the single emotion label, and we measure prediction accuracy against the majority emotion."</p> <p>They are using a discrete classification task. So you just need to take the <code>tf.argmax()</code> on your logits to get the highest probab...
tensorflow|prediction|multilabel-classification|multiclass-classification
2
375,285
52,839,576
Cannot create a new Timestamp column in pandas based on a conditional w/np.where
<p>In the process of writing out a script to automate the compilation of a report, I'm trying to create a column of Timestamps based on a conditional using np.where(). The logic is as follows:</p> <pre><code>df['StartMonth'] = np.where( chng['Count'] == 1, pd.Timestamp( int(year), chng['Month'].astype(int)...
<p>There are a few issues:</p> <ol> <li>You should use <code>pd.to_datetime</code> for <strong>vectorised</strong> conversion, rather than <code>pd.Timestamp</code>.</li> <li><code>numpy.where</code> returns a NumPy array, which is not the same as a Pandas <code>datetime</code> series. But you can feed an array to <co...
python|pandas|datetime|dataframe
0
375,286
52,774,098
How to subtract value from same month last year in pandas?
<p>I have the below dataframe and I need to subtract value from same month last year and save it in output:</p> <pre><code>date value output 01-01-2012 20 null 01-02-2012 10 01-03-2012 40 01-06-2012 30 01-01-2013 20 0 01-02-2013 30 20 01-02-2014 ...
<p>First create <code>DatetimeIndex</code>, then subtract by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sub.html" rel="nofollow noreferrer"><code>sub</code></a> with new <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel=...
pandas
2
375,287
52,850,269
Dask: Drop NAs on columns?
<p>I have tried to apply a filter to remove columns with too many NAs to my dask dataframe:</p> <pre><code>df.dropna(axis=1, how='all', thresh=round(len(df) * .8)) </code></pre> <p>Unfortunately it seems that the dask <code>dropna</code> API is slightly different from that of pandas and does not accept either an <cod...
<h1>Update 10 Aug 2021:</h1> <p>Now Dask has <code>axis</code>, <code>thresh</code>, and <code>subset</code> args that may help. The previous answer can be rewritten as:</p> <pre><code>df.dropna(subset=columns_to_inspect, thresh=threshold_to_drop_na, axis=1) </code></pre> <h1>Old answer</h1> <p>You're right, there is n...
python|pandas|optimization|dask
5
375,288
52,457,962
Percentage change with groupby python
<p>I have the following dataframe:</p> <pre><code>Year Month Booked 0 2016 Aug 55999.0 6 2017 Aug 60862.0 1 2016 Jul 54062.0 7 2017 Jul 58417.0 2 2016 Jun 42044.0 8 2017 Jun 48767.0 3 2016 May 39676.0 9 2017 May 40986.0 4 2016 Oct 39593.0 10 2017 Oct 41439.0 5 20...
<p>Do not <code>groupby</code> <em>Year</em> otherwise you won't get, for instance, <code>Aug 2017</code> and <code>Aug 2016</code> together. Also, use <code>transform</code> to broadcast back results to original indices </p> <p>Try:</p> <pre><code>df['pct_ch'] = df.groupby(['Month'])['Booked'].transform(lambda s: s....
python|pandas
0
375,289
52,854,826
Python Pandas - Aggregation and count
<p>I have a dataframe (below there's a super simplified version) which has transactions data of product bought and device used:</p> <pre><code>CUST_ID PRODUCT DEVICE ---------------------- 1 A MOBILE 1 B TABLET 2 B LAPTOP 2 A MOBILE 3 C TABLET 3 C ...
<p>You can use <code>pd.get_dummies</code> and <code>df.groupby</code></p> <pre><code>pd.get_dummies(df, columns=['PRODUCT','DEVICE']).groupby(['CUST_ID'], as_index=False).sum() </code></pre> <p>Output:</p> <pre><code>CUST_ID PRODUCT_A PRODUCT_B PRODUCT_C DEVICE_LAPTOP DEVICE_MOBILE \ 0 1 1 ...
python|pandas|pivot-table
1
375,290
52,866,239
Getting lowest valued duplicated columns only
<p>I have a dataframe with 2 columns: <code>value</code> and <code>product</code>. There will be duplicated products, but with different values. What I want to do is to get all products, but remove any duplication. The condition to remove duplication will be to get the row with the lowest value and drop the rest. For e...
<pre><code>df.sort_values('value').groupby('product').first() # value #product #A 25 #B 22 #C 13 </code></pre>
python|pandas
2
375,291
52,743,888
Python arranging a list to include duplicates
<p>I have a list in Python that is similar to:</p> <pre><code>x = [1,2,2,3,3,3,4,4] </code></pre> <p>Is there a way using pandas or some other list comprehension to make the list appear like this, similar to a queue system:</p> <pre><code>x = [1,2,3,4,2,3,4,3] </code></pre>
<p>It is possible, by using <code>cumcount</code> </p> <pre><code>s=pd.Series(x) s.index=s.groupby(s).cumcount() s.sort_index() Out[11]: 0 1 0 2 0 3 0 4 1 2 1 3 1 4 2 3 dtype: int64 </code></pre>
python|pandas|list|duplicates|unique
2
375,292
52,807,109
Pandas dataframe, grouping 3 columns and counting the third
<p>I'm trying to group a dataframe by 3 columns, date, time and article, and return an object where i have the groups of date, time and article, and the count of each article per time (hour).</p> <p>This code does the trick with the grouping, but I can't figure out how to also get the count:</p> <pre><code>dfs.groupb...
<p>Assuming columns <code>Dato</code>, <code>Tid</code>, and <code>Varenavn</code> in your OG dataframe, try this:</p> <pre><code>df['datetime'] = df['Dato'] + str(' ') + df['Tid'] df['datetime'] = pd.to_datetime(df['datetime'], format = '%m.%d.%Y %H%M') df.groupby([pd.Grouper(key = 'datetime', freq = 'H'), 'Varenavn'...
python|python-3.x|pandas|pandas-groupby
1
375,293
52,645,495
add trailing 0's to a string in a df.Column dependent on length
<p>Looking for a sort of chain method to apply to a df.</p> <p>consider the following DF.</p> <pre><code>Store 1 33 455 </code></pre> <p>what I'm trying to do is ascertain the length and append a 0 based on the length.</p> <p>I've tried a simple for loop which i thought may work</p> <pre><code>for s in df.Store: ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.zfill.html" rel="nofollow noreferrer"><code>Series.str.zfill</code></a>.</p> <p>If want append <code>0</code> values by maximum length of string is possible count length by <a href="http://pandas.pydata.org/pandas-docs/stable/gener...
python|pandas
2
375,294
52,821,367
Tensorflow Serving crashes with multiple requests simultaneously
<p>Tensorflow Serving crashes with multiple requests simultaneously, the error message is:</p> <pre><code>*** Error in `tensorflow_model_server': double free or corruption (!prev): 0x00007ff474c18cc0 *** </code></pre> <p>I have tried batching, it doesn't work out.</p> <p>I tried: </p> <pre><code>sudo apt-get instal...
<p>Unfortunately, this isn't enough information here to debug the issue. If it's a problem with your model, then you'll likely get this issue eventually no matter how you serve it.</p>
tensorflow-serving
0
375,295
52,575,075
How to group a date column into year and sum a spending column according to the year?
<p>I am trying to group my data to years and sum the spending according to the year they belong to.</p> <p>Here's a sample data:</p> <pre><code>date: spend_amt: 2/1/2014 10000 2/5/2014 98 1/2/2015 5834.2 7/8/2017 561236 9/3/2017 568 28/1/2016 9898...
<p>Your error means there is no column <code>date</code>, I guess there is <code>index</code> called <code>date</code>:</p> <pre><code>df.index = pd.to_datetime(df.index) dfspendingYearly = df.groupby(df.index.year).sum().reset_index() print (dfspendingYearly) date spend_amt 0 2014 10098.0 1 2015 5834.2 2...
python-2.7|pandas|dataframe|pandas-groupby
0
375,296
52,784,204
how to create iterator.get_next() for validation set
<p>I am working on project to classify medical images using the CNN model, for my project I use tensorflow, after doing some search, at last, I could use new tensorflow input pipeline to prepare the train, validation and test set, here is the code:</p> <pre><code>train_data = tf.data.Dataset.from_tensor_slices(train_i...
<p>You should be able to use the same <code>next_element</code> to get validation and test set. </p> <p>For example, initialize the dataset by <code>sess.run(valid_init_op)</code> and then <code>next_element</code> generates data in the validation set. </p> <pre><code>with tf.Session as sess: sess.run(train_init_op...
python-3.x|tensorflow
1
375,297
52,821,931
Python3 can't see opencv-python, numpy, PyQt5
<p>I installed opencv-python numpy PyQt5 using brew. Unfortunately it installed only for python in version 2 but I wanted it to ver 3. So normally when I am using python2 I can import those libs, but in python3 there is just error about not module found.</p> <p>When I am typing for example brew info numpy, I am gettin...
<p>Problem solved. Recently, Python.org sites stopped supporting TLS version 1.0 and 1.1. This helped:</p> <pre><code>curl https://bootstrap.pypa.io/get-pip.py | python3 </code></pre>
python|python-3.x|macos|numpy|opencv
0
375,298
52,876,759
converting a python script into a function to iterate over each row
<p>How can i convert the below python script into a fucntion so that i can call it over each row of a dataframe in which i want to keep few variables dynamic like <strong>screen_name</strong>, <strong>domain</strong></p> <pre><code> # We create a tweet list as follows: tweets = extractor.user_timeline(screen_na...
<p>Here you go buddy :-</p> <pre><code>for index, row in dff.iterrows(): twt=row['twittername'] domain = row['domain'] print(twt) print(domain) extractor = twitter_setup() # We create a tweet list as follows: tweets = extractor.user_timeline(screen_name=twt, count=200) data = pd.DataFra...
python|python-3.x|pandas|dataframe|automation
0
375,299
52,594,686
Finding the number of occurrences of a specific string in a column
<p>I'm trying to count the number of words that have the string: "hanger" from the column "Description". So I defined a function:</p> <pre><code>def hanger_count(title): if 'hanger' in title.lower().split(): return True else: return False </code></pre> <p>Which seemed to be working correctly when I tested it...
<p>You appear to have mixed data types in your column, and since <code>lower()</code> is only a method for strings, you are getting an error when pandas attempts to call the function on a numeric value (in this case a float).</p> <p>This quick tweak might work for you:</p> <pre><code>def hanger_count(title): if ...
python|pandas|dataframe|data-analysis
4