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
13,200
59,436,089
How to keep the newest element of a numpy array each time this appear
<p>when I print list I get this result and I just want to get the latest value</p> <pre><code>print (list) ([[ 0], [ 0, 6], [0, 6, 12], [0, 6, 12, 18] . . . [0, 6, 12, 18, ... , n] ]) But I want it to be like this [0, 6, 12, 18, ... , n] </code></pre> <p>Any ideas? </p>
<p>Firstly don't name your variable <code>list</code>, as it is a keyword. </p> <p>And now the solution to your problem </p> <pre><code>&gt;&gt;&gt; l = [[1,2,3,4],[2,5,4,7]] &gt;&gt;&gt; l [[1, 2, 3, 4], [2, 5, 4, 7]] &gt;&gt;&gt; print(l[-1]) [2, 5, 4, 7] </code></pre>
python|arrays|list|numpy
1
13,201
59,399,572
How should I take the sign or check isnull() of a column in pandas eval/query function?
<p>Given a pandas dataframe, how should I do sth like the following?</p> <pre><code>df.eval('B * sign(A)') df.query('A.notnull()') </code></pre> <p>It is not letting me because sign(A) and A.notnull() is not recognized. </p>
<p>Try:</p> <pre><code>import numpy as np df['B']*np.sign(df['A'].to_numpy()) df[~df['A'].isna()] </code></pre> <p>As in the comments, remark that <code>np.sign(0)=0</code></p>
pandas
2
13,202
59,293,522
Pandas evaluate condition and convert to 0/1 int
<p>I'm trying to evaluate a dateTimeIndex to determine if a date is equivalent to a specific date and return a new series as a result containing the results of the conditional as 0/1.</p> <p>My sample in:</p> <pre><code>rng = pd.period_range('2019-11-04', '2019-11-12', freq='D',name="Active_Date").to_timestamp() </co...
<p>Compare the index with your "eval criteria", then convert the bool result to an Int64Index:</p> <pre><code>pd.Int64Index(rng == '2019-11-06') # Int64Index([0, 0, 1, 0, 0, 0, 0, 0, 0], dtype='int64') </code></pre>
python|pandas
1
13,203
59,281,644
Groupby & Sum from occurance of a particular value till the occurance of another particular value or the same value
<p>I have a dataframe as below. I want to <code>groupby</code> 'user' &amp; 'eve' and <code>sum</code> 'Ses' till 100/200 &amp; from 100 to 200. Also, return the value of column 'Name' where 100/200 occurs.</p> <p>If after an hundred, there is no 100 or 200 (like last row in group a &amp; 123 or a &amp; 456), ignore i...
<p>This is my approach:</p> <pre><code># valid IDs df['valids'] = df['ID'].isin([100,200]) # mask the trailing non-hundred ids heads = (df['ID'].where(df['valids']) .groupby([df['User'],df['eve']]) .bfill().notnull() ) df = df[heads] # groupby and output: (df.groupby(['User','eve', ...
python|python-3.x|pandas|dataframe|group-by
3
13,204
45,147,525
tensorflow: batches of variable-sized images
<p>When one passes to tf.train.batch, it looks like the shape of the element has to be strictly defined, else it would complain that <code>All shapes must be fully defined</code> if there exist Tensors with shape <code>Dimension(None)</code>. How, then, does one train on images of different sizes?</p>
<p>You could set <code>dynamic_pad=True</code> in the argument of <a href="https://www.tensorflow.org/api_docs/python/tf/train/batch" rel="noreferrer"><code>tf.train.batch</code></a>.</p> <blockquote> <p><code>dynamic_pad</code>: Boolean. Allow variable dimensions in input shapes. The given dimensions are padded upo...
tensorflow|neural-network|conv-neural-network|training-data
9
13,205
45,059,249
Tensorboard weights histogram only last layer visible change
<p>I added a TensorBoard visualization to my network and noticed that only the outlier changes a lot. Why do the weights of the network not change a lot? This is especially visible in the overlay histograms.</p> <p><strong>Histograms</strong> <a href="https://i.stack.imgur.com/UBZS9.png" rel="nofollow noreferrer"><img...
<p>I have faced a similar issue with the weight histograms in my neural network. Although Relu does deal with the vanishing gradient problem for your hidden layers, you should check your learning rate and ensure that the update to each variable is not too small. This is likely to cause close to zero updates, resulting ...
python|tensorflow|neural-network|tensorboard
1
13,206
45,176,801
Stacking multidimensional numpy arrays with one different dimension
<p>Alright - assume I have two numpy arrays, shapes are:</p> <pre><code>(185, 100, 50, 3) (64, 100, 50, 3) </code></pre> <p>The values contained are 185 or 64 frames of video (for each frame, width is 100 pixels, height is 50, 3 channels, these are just images. The specifics of the images remain constant - the only...
<p>This is a quick brainstorm idea that I've got, along with strategy and Python code. Note: I was going to stick to just comment but to illustrate this idea I'd need to type in some codes. So here we go! (grab a coffee / a strong drink is recommended...)</p> <h1> Current State</h1> <ul> <li>we have video 1 <code>vid1<...
python|arrays|numpy|multidimensional-array|neural-network
3
13,207
57,158,491
Please suggest approaches and code to solve the defined problem statement
<pre><code>x y z amount absolute_amount 121 abc def 500 500 131 fgh xyz -800 800 121 abc xyz 900 900 131 fgh ijk 800 800 141 obc pqr 500 500 151 mbr pqr -500 500 141 obc pqr -500 500 151 mbr pqr 900 900 </code></pre> <p>I need to find the duplicate rows in th...
<p>Use <code>transform</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.sum.html" rel="nofollow noreferrer"><code>groupby.sum()</code></a> to return sum transformed for each group and then compare the 2 conditions you have:</p> <pre><code>c=df.groupby(['x','y'...
python-3.x|pandas|group-by
0
13,208
57,144,409
Filtering a dataframe after groupBy and user-define-aggregate-function in Pyspark will cause java.lang.UnsupportedOperationException
<p>I found some strange error when I'm coding Pyspark UDAF. After I call groupBy function and agg function, I want to filter some data from remaining dataframe, but it seems not work. My sample code is below.</p> <pre><code>&gt;&gt;&gt; from pyspark.sql.functions import pandas_udf, PandasUDFType, col &gt;&gt;&gt; df =...
<p>I think it's probably a bug for PySpark. As you found out, the optimizer tried to optimize the plan, but encountered some expression it can't evaluate, i.e. <code>java.lang.UnsupportedOperationException: Cannot evaluate expression: mean_udf(input[1, double, true])</code>. </p> <p>To fix the issue, one needs to stop...
pandas|dataframe|apache-spark|pyspark|pyspark-sql
1
13,209
57,272,222
Merge two Dataframes with same columns with overwrite
<p>I have dataframe like this:</p> <pre class="lang-py prettyprint-override"><code> df = pd.DataFrame({"flag":["1","0","1","0"], "val":["111","111","222","222"], "qwe":["","11","","12"]}) </code></pre> <p>It gives:</p> <pre><code> flag qwe val 0 1 111 1 0 11 111 2 1 222 3 0 12 22...
<p><code>pd.merge</code> has an <code>on</code> argument that you can use to join columns with the same name in different dataframes.</p> <p>Try:</p> <pre class="lang-py prettyprint-override"><code>pd.merge(df, dff, how="left", on=['flag', 'qwe', 'val']) </code></pre> <p>However, I don't think you need to do that at...
python|pandas|dataframe|merge
2
13,210
57,246,210
Pandas Percent Change with Condition
<p>I have a dataframe from the following code:</p> <pre><code>import pandas as pd columns = ['type', 'value', 'weight'] fizz_or_bang = ['fizz', 'bang', 'fizz', 'bang', 'bang', 'fizz', 'bang', 'bang', 'fizz', 'bang', 'bang', 'fizz', 'bang', 'bang', 'fizz', 'bang'] values = [5, 4, 5, 7, 9, 4, 6, 12, 8, 12, 13, 2, 3, 4,...
<p>This is need <code>cumsum</code> create the key , and you need the <code>first</code> and <code>last</code> value only , so we can not using <code>pct_change</code></p> <pre><code>s=df.type.eq('fizz').cumsum() #Create the subgroup s1=df.value.mul(df.weight)[df.type.ne('fizz')].groupby(s).sum().values #using the g...
python|pandas|dataframe
0
13,211
56,951,409
IndexError: index 1040 is out of bounds for axis 0 with size 1040
<p>I'm trying to understand a code for a project and i am trying to compile it. So i found this problem.</p> <pre><code>cpt=0 for img in t : x = img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) X_train1[cpt,:,:] = x[0,:,:,:] cpt+=1 </code></pre> <blockquote> <p>IndexErrorT...
<p>Wherever <code>X_train1</code> is created, it is too small as the error suggests: <code>IndexError: index 1040 is out of bounds for axis 0 with size 1040</code>. Python lists as well as <code>numpy</code> arrays are 0-based. Therefore, the largest index in an array of size 1040 would be 1039.</p>
python|tensorflow|keras|index-error
1
13,212
35,660,473
Combing pandas dataframe values based on other column values
<p>I have a pandas dataframe like so: </p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame([['WY','M',2014,'Seth',5], ['WY','M',2014,'Spencer',5], ['WY','M',2014,'Tyce',5], ['NY','M',2014,'Seth',25], ['MA','M',2014,'Spencer',23]],columns = ['stat...
<pre><code>df[['sex','year','name','number']].groupby(['sex','year','name']).sum().reset_index() </code></pre> <p>For a brief description of what this does, from left to right:</p> <ol> <li>Select only the columns we care about. We could replace this part with <code>df.drop('state',axis=1)</code></li> <li>Perform a ...
python|numpy|pandas|dataframe
1
13,213
35,356,714
How to calculate the statistical persistence of a Pandas Series?
<p>Suppose I have a series:</p> <pre><code>from pandas import Series x = Series([2.3,6.7,1.2,8.0,7.5]) </code></pre> <p>I want to calculate the correlation. If I do this:</p> <pre><code>shift = x[:-1] x = x[1:] x.corr(shift) </code></pre> <p>Because the Series remembers the original indices of each element, it matc...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow"><code>shift</code></a> with parameter <code>periods</code> :</p> <pre><code>from pandas import Series x = Series([2.3,6.7,1.2,8.0,7.5]) shift = x.shift(periods=1) print shift 0 NaN 1 2.3 ...
python|pandas|statistics|dataframe
1
13,214
28,444,511
Simultaneous column assignment
<p>I just found that I can't assign like this:</p> <pre><code>df[['a','b','c']] = 'total' </code></pre> <p>or</p> <pre><code>df.loc[:, ['a','b','c']] = 'total </code></pre> <p>However, I can do</p> <pre><code>df['a'] = 'total' df['b'] = 'total' df['c'] = 'total' </code></pre> <p>or</p> <pre><code>df['a'] = df['b...
<p>Those look like <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow noreferrer">dictionaries</a> so have a read on the official documentation.</p> <p>You can assign a single key some value. The key must be unique and hashable (that's why dicts work so fast and are basically t...
python|pandas|variable-assignment
1
13,215
50,966,204
convert images from [-1; 1] to [0; 255]
<p>I know that question is really simple, but I didn't find how to bypass the issue:</p> <p>I'm processing images, the output pixels are <em>float32</em>, and values are in range <code>[-1; 1]</code>. The thing is, when saving using openCV, all negative data and float values are lost (I only get images with 0 or 1 val...
<p>You can use <code>cv2.normalize()</code></p> <p>Consider the following array <code>a</code>:</p> <pre><code>a = np.array([[-0.12547205, -1. ], [ 0.49696118, 0.91790167], [ 0.81638017, 1. ]]) norm_image = cv2.normalize(image, None, alpha = 0, beta = 255, norm_type = cv2.NO...
python|numpy|opencv
26
13,216
51,107,836
finding max element from column of dataframe gives error
<p>I am trying to find largest element from a column in my DataFrame but this gives the following error. And i have tested that it only gives error to this column name only and rest of the columns just work fine.</p> <p>This is my DataFrame created from a file posts1.csv</p> <pre><code>import pandas as pd posts_n = ...
<p><code>'score'</code> is not in the <code>(column) index</code>, so instead of loading in the first line of the csv as the header line, you read it in as data.</p> <p>try the following:</p> <p><code>posts = pd.read_csv('posts1.csv', header=1)</code></p>
pandas|dataframe|machine-learning|max|slice
0
13,217
51,068,981
Vectorized Update numpy array using another numpy array elements as index
<p>Let A,C and B be numpy arrays with the same number of rows. I want to update 0th element of A[0], 2nd element of A[1] etc. That is, update B[i]th element of A[i] to C[i]</p> <pre><code>import numpy as np A = np.array([[1,2,3],[3,4,5],[5,6,7],[0,8,9],[3,7,5]]) B = np.array([0,2,1,2,0]) C = np.array([8,9,6,5,4]) for ...
<p>The reason that your approach doesn't work is that you're passing the whole <code>B</code> as the column index and replace them with <code>C</code> instead you need to specify both row index and column index. Since you just want to change the first 4 rows you can simply use <code>np.arange(4)</code> to select the ro...
python|numpy|vectorization
1
13,218
5,872,235
Numpy: creating a symmetric matrix class
<p>based on <a href="https://stackoverflow.com/questions/2572916/numpy-smart-symmetric-matrix">this answer</a> I was coding a simple class for symmetric matrices in python with numpy, but I'm having (probably a very simple) problem. This is the problematic code:</p> <pre><code>import numpy as np class SyMatrix(np.nd...
<p>There are a few issues here.</p> <ol> <li><p>When <a href="http://docs.scipy.org/doc/numpy/user/basics.subclassing.html" rel="nofollow">subclassing <code>numpy.ndarray()</code></a>, you should overwrite <code>__new__()</code>, not <code>__init__()</code>. Your line</p> <pre><code>foo = SyMatrix(2) </code></pre> ...
python|arrays|numpy
3
13,219
66,343,575
Plotting characters distribution
<p>I am trying to plot the distribution of characters in text in a column in pandas. For example:</p> <pre><code>Phrase example1 example1+example2 example 3 example 4 example of sentence and so on.... </code></pre> <p>So I would need to determine the length of each string/text within the <code>Phrase</code> column. To...
<p>You normally plot distributions with histograms. In your case it can be like so:</p> <pre><code>sns.displot(df,x='Phrases length') </code></pre> <p>Check out further documentation <a href="https://seaborn.pydata.org/tutorial/distributions.html" rel="nofollow noreferrer">here</a>.</p>
python|pandas|matplotlib|seaborn
1
13,220
66,565,780
Conda - ModuleNotFoundError: No module named 'torch'
<p><strong>Steps to reproduce:</strong></p> <p>I am using Anaconda on Windows to set up environment for this repo.</p> <p><code>conda create --name pytorch-yolo</code></p> <p>Then I install all dependencies with <code>conda install --file requirements.txt</code></p> <p>Which returns</p> <pre><code>PackagesNotFoundError...
<p>You are probably using the wrong python binary. Can you try <code>python test.py --weights_path weights/yolov3.weights</code>?</p> <p>I am not familiar with Windows terminal, but you can get the path to the binaries by using the <code>where</code> command (<code>which</code> for Linux):</p> <pre><code>(pytorch-yolo)...
python|anaconda|pytorch|conda
4
13,221
66,394,017
Multiply two vectors element by element
<p>I want to multiply these two vectors, but I cannot It does not sum the result:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np x = np.array([1, 2, 3]) y = np.array([[0.2], [0.2], [0.2]]) t = [0] for i in range(0, 2): for j in range(0, 2): t = sum(x[i] ...
<p>I'm assuming this is a homework problem? Your biggest problem is that <code>for i in range(0, 2):</code> only loops through <code>i = 0, 1</code>, not <code>i = 0, 1, 2</code> as you intend.</p>
python|numpy|matrix|vector
0
13,222
66,543,936
Numpy exp() not callable
<p>If I use 2 np arrays as x,y input into the following expression...</p> <pre><code>out = np.exp(3(x-4)-0.0001*y) </code></pre> <p>...I get &quot;TypeError: 'int' object is not callable</p> <p>If I use the same as function and call this function with a curve fit I get a similiar error:</p> <pre><code>def func(X, a, b)...
<pre><code>out = np.exp(3(x-4)-0.0001*y) </code></pre> <p>The problem in this expression is that the np.exp() function takes one argument but you passed 2. I don't know this is the best solution but instead of this you can try:</p> <pre><code>operations = 3*(x-4) - (0.0001*y) out = np.exp(operations) </code></pre>
python|numpy|typeerror|exp
1
13,223
16,434,032
How to pick and choose columns from dataframes and put them into new ones?
<p>I sincerely regret going to the pub when i was supposed to be reading up on how to push and shove dataframe data around:</p> <p>Given two similar shaped dataframes, how do I combine them?</p> <pre><code>&gt; print aae.head(), aar.head() symbol open high low close volume date ...
<p>Try to use <a href="http://pandas.pydata.org/pandas-docs/dev/merging.html" rel="nofollow">merge</a> to achieve your goal. For example:</p> <pre><code>pd.merge(aae.reset_index()[['date', 'close']], aar.reset_index()[['date', 'close']], on=['date']) Out[129]: date close.x close.y 0 1992-01-2...
python|pandas
1
13,224
57,531,303
How to index correctly using Python 3.7 and address associated errors
<p>I have been having issues indexing in Python 3.7. I would greatly appreciate your insights and clarification on this.</p> <p>I have tried to research and fix this issue but I am not able to understand what I am doing. I would greatly appreciate your help</p> <pre><code> enroll = pd.read_csv('enrollment_forecast.cs...
<p>Just a heads up, Pandas <code>.ix</code> index accessor is deprecated.</p> <p>It's throwing the error error because you are passing it a tuple:</p> <pre><code> enroll_data = enroll.ix[:(2,3)].values </code></pre> <p>Try passing it a list instead of a tuple:</p> <pre><code> enroll_data = enroll.ix[:[2,3]].values ...
pandas|indexing|python-3.7
1
13,225
57,615,126
Variable scoping and sharing "global" reference dataframes
<p>Old-school programmer brand new to Python &amp; pandas. The mutable datatypes are super cool, but they make it hard to intuit how to set up "global" reference data structures.</p> <p>I have a bunch of reference data (currently tens of MB, but it will be hundreds of MB in final version). Quite a few different classe...
<p>Assuming you have a dataframe (or any other kind of object, really):</p> <pre><code>df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]}) </code></pre> <p>An assignment like the one below will make the new variable reference the same object:</p> <pre><code>df1 = df </code></pre> <p>This is explained in detail...
python|pandas
0
13,226
24,009,413
NumPy won't install in Python 3.4.0 in Win7
<p>I looked at a previous related post and the commenter said 'why don't you use the Windows installer?"</p> <p>So I followed the link and downloaded <a href="https://pypi.python.org/packages/3.4/n/numpy/numpy-1.8.1-cp34-cp34m-macosx_10_6_intel.whl#md5=08043cc4eaa6267ac2f872924e11ae7c" rel="noreferrer">https://pypi.py...
<p><strong>Not the solution but an easy workaround</strong></p> <p>Unfortunately standard packaging tools in Python 3 work terribly bad in Windows. Even if you have installed the compiler from MS Visual Studio 2010 you will probably meet propblems like yours in case package that being installed need to compile some na...
python|numpy|installation
6
13,227
43,878,386
Is it possible to do this pivot in pandas?
<p>Is it possible to turn this dataframe :</p> <pre><code> A_type A_1 A_2 1 a 1 x 1 b 2 y 2 a 3 z 2 b 4 w 3 b 5 u </code></pre> <p>Into this? :</p> <pre><code> a b A_1 A_2 A_1 A_2 1 1 x 2 y 2 ...
<p>IIUC you can do it this way:</p> <pre><code>In [195]: df.set_index('A_type', append=True).unstack() \ .swaplevel(axis=1).sort_index(axis=1) Out[195]: A_type a b A_1 A_2 A_1 A_2 1 1.0 x 2.0 y 2 3.0 z 4.0 w 3 NaN None 5.0 u </code></pre>
pandas|dataframe|pivot
3
13,228
43,897,056
Tensorflow: Peer access not supported between device ordinals
<p>Is it still possible to run trainning in some kind of multi gpu setting if I have <code>Peer access not supported between device ordinals</code>?(as I understand GPUs are 'not connected') for example by calculating each batch separately on GPU and then merge on CPU as I understand this is the way 'batch accumulation...
<p>This message is benign (it is an "INFO" message, not an error). Everything in Tensorflow will work, but perhaps more slowly than it could on different hardware that did support peer-to-peer access.</p> <p>The message means the NVIDIA driver is reporting that peer-to-peer access is not possible between your GPUs. Se...
tensorflow|deep-learning|gpu|caffe|nvidia-digits
3
13,229
43,662,472
pandas does not read csv data with exponetial form
<p>I'm trying to read a simple csv data file using pandas read_csv command. For some reason all values expressed in exponential form are converted to zeros.</p> <p>Can someone please help me understand what is going wrong here and give me the instructions on how to do this correctly?</p> <pre><code>nlv12097@acv0105 T...
<p>Your version is 0.7.3!? I can't even find documentation for that version anymore. Unless this version is absolutely critical to your system, please update it. That version has to be 7 years old or more. (Ok it's only 5 years old, but still.) </p> <p>Alright. So I was able to find that version and do some testing. G...
python|csv|pandas
4
13,230
72,907,091
Align value counts of two dataframes side by side
<p>If I have two dataframes - df1 (data for current day), and df2 (data for previous day).</p> <p>Both dataframes have 40 columns, and all columns are object data type.</p> <p>how do I compare Top 3 value_counts for both dataframes, ideally so that the result is side by side, like the following;</p> <pre><code> ...
<p>You can compare if same columns names in both DataFrames - first use lambda function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_counts</code></a>, top3 and create default index for both DataFrames and then join...
python-3.x|pandas
1
13,231
72,930,984
Pandas Sort, Groupby and running difference
<p>i have just started using Pandas and i'm amazed by how flexible it is but i've hit a roadblock and need some help</p> <p>I have a Data frame Df:</p> <pre><code>| Contract | Year | Val1 | Val2 | Val3 | | A | 2020 | 90 | 95. | 100 | |A | 2019 | 80 | 85.| 90| |A | 2018 | 75. | 70. ...
<p>If I understand you correctly, after the <code>.sort_values</code> you can do:</p> <pre class="lang-py prettyprint-override"><code>df.loc[:, &quot;Val1&quot;:&quot;Val3&quot;] = df.groupby(df[&quot;Contract&quot;]).diff().mul(-1).shift(-1) print(df) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-over...
python|pandas|dataframe|group-by
1
13,232
73,095,789
How to transpose two column header as row values and make values of these columns comes under another column name or header using Python Pandas?
<p>I want to make two column header as row values comes under a new column and also make their values comes under another column header or column name using Python Pandas. I searched about it, but I could not found a solution for this.</p> <p>First table: <a href="https://i.stack.imgur.com/pVnam.jpg" rel="nofollow nor...
<p>Try this:</p> <pre><code>df1 = df.melt(id_vars = ['name', 'place'], value_vars = ['weight', 'numbers'], var_name = 'measure', value_name = 'measureing_values') print(df1) name place measure measureing_values 0 apple delhi weight 2 1 orange up weight 3 2 onion ...
python-3.x|pandas|dataframe
2
13,233
73,007,247
Converting inches to CM on series
<p>I am trying to turn a series of heights that are in inches and turn them into cm amounts. below is the method I am using but am running into an issue that is also posted below. I have tried using regex but that did not work for me.</p> <p>Calling the data head of a series</p> <pre><code>fighter_details.Height.head()...
<p>It looks like you're using the wrong column.</p> <p>That said, better use a vectorial method for efficiency.</p> <p>You can extract the ft/in components, convert each to cm and sum:</p> <pre><code>df['Data_cm'] = (df['Data'] .str.extract(r'(\d+)\'\s*(\d+)&quot;') .astype(float) .mul([12*2.54, 2.54]) .sum(axis=1)...
python|pandas
2
13,234
73,028,716
transforms.ToTensor() and Numpy Issue
<p>I'm working on MNIST datasets using Pytorch and I'm trying to scale the images, I ran into problems associated with Numpy</p> <pre><code>train_dataset = datasets.MNIST(root='data', train=True, transform=transforms.ToTensor(), ...
<p>Figured it out, my Numpy version was outdated compared to pytorch. Updated it basically!</p>
python|pytorch|mnist|pytorch-dataloader
0
13,235
70,393,939
How to delete rows based on change in variable in pandas dataframe
<p>I've got a dataset with an insanely high sampling rate, and would like to remove excess data where the columnar value changes less than a predefined value down through the dataset. However, some intermediary points need to be kept in order to not loose all data.</p> <p>e.g.</p> <pre><code> t V 0 1.0 1.0...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html" rel="nofollow noreferrer"><code>DataFrame.diff</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>...
python|pandas|dataframe
1
13,236
70,442,096
Pytorch Lightning Tensorboard logger automatically adds "epoch" scalar
<p>As in: <a href="https://stackoverflow.com/questions/70183125/how-do-you-prevent-the-tensorboard-logger-in-pytorch-lightning-from-logging-the">How do you prevent the tensorboard logger in pytorch lightning from logging the current epoch?</a></p> <p>Pytorch Lightning Lightning Trainer with a LightningDataModule and Li...
<h2>In Short</h2> <p>You can disable automatically writing <code>epoch</code> variable by overwriting tensorboard logger.</p> <pre class="lang-py prettyprint-override"><code>from pytorch_lightning import loggers from pytorch_lightning.utilities import rank_zero_only class TBLogger(loggers.TensorBoardLogger): @rank...
python|pytorch|pytorch-lightning
1
13,237
70,461,830
Numpy.any() between two indices of a 1D array multiple times in one step
<p>I have a 1D numpy array of booleans and I need to check if there is a True element between two indices in the 1D array multiple times in one step (i.e. no looping).</p> <p>An example:</p> <pre><code>my_data = np.array([False, True, True, False, False, False, True, False]) inds2check = np.array([[0, 3], ...
<p>Unfortunately I think you have to iterate it, but the cost depends only on the output's size. In your exemple, you will need iterate only 3 times.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np data = np.array([False, True, True, False, False, False, True, False]) inds = np.array([[0, 3], ...
python|arrays|numpy|indexing
1
13,238
70,583,246
sentence transformer how to predict new example
<p>I am exploring sentence transformers and came across this <a href="https://www.sbert.net/docs/training/overview.html" rel="nofollow noreferrer">page</a>. It shows how to train on our custom data. But I am not sure how to predict. If there are two new sentences such as 1) this is the third example, 2) this is the exa...
<p>Q1) Sentence transformers create sentence embeddings/vectors, you give it a sentence and it outputs a numerical representation (eg vector) of that sentence. The reason you feed in two sentences at a time during training is because the model is being optimized to output similar or dissimilar vectors for similar or di...
python|nlp|huggingface-transformers|sentence|sentence-similarity
3
13,239
70,608,396
Python Rolling sum for 32 bit vs 64 bit
<p>I am getting strange results when doing <strong>rollingSum</strong> for 64 bit vs 32 bit precision. Please see the code for display 1 vs 2. <strong>Display 1</strong> shows the right rolling sum but <strong>Display 2</strong> shows empty result dataframe. I am using python 3.9 FYI</p> <pre><code>import pandas as pd ...
<p>This has been solved in Pandas version 1.4.0</p> <p><a href="https://github.com/pandas-dev/pandas/pull/42884" rel="nofollow noreferrer">BUG: dataframe.rolling along rows drops float16</a></p> <p><a href="https://github.com/pandas-dev/pandas/issues/41779" rel="nofollow noreferrer">BUG: DataFrame.rolling(axis=1) opera...
python|python-3.x|pandas|rolling-computation
0
13,240
42,800,046
pandas merge does weird job if left and right df's keys are different
<p>I have found pandas merge method does weird job if key index of left and right are different.</p> <p>for instances, I define left and right dataframes as follow</p> <p>left_df</p> <pre><code> 0 1 2 3 4 5 0 1 2 1 2 3 4 1 2 3 2 3 4 5 2 1 2 3 4 5 6 3 2 2 4 5 6 7 4 2 3 5 6 7 8 </c...
<p>I wondered a condition that the weird result occurs I mentioned, So I divide my own assumption into two cases.</p> <ul> <li><strong>When column name of each key is different</strong></li> <li><strong>When column index (In this case, absolute column position in data frame.) of each key is different</strong></li> </u...
python|pandas|join|merge
0
13,241
27,047,857
Theano gradient of sparse matrix multiplication
<p>I'm trying to implement an autoencoder with sparse inputs in Theano.</p> <p>I got the sparse autoencoder to work with a squared error cost function. But if I want to apply a cross-entropy error, which contains matrix multiplications, I get the following error:</p> <pre><code>AsTensorError: ('Variable type field mu...
<p>You can not use T.* function on sparse variable. In this case, you can use:</p> <pre><code>theano.sparse.sp_sum((x * T.log(z)) </code></pre> <p>\edit This diff fix in Theano fix this crash:</p> <pre><code>diff --git a/theano/sparse/basic.py b/theano/sparse/basic.py index 4620c5a..a352b9a 100644 --- a/theano/spars...
python|numpy|scipy|sparse-matrix|theano
1
13,242
28,903,969
Python multiprocessing+savefig leads to error or system lockup
<p>I have a big 3d numpy array, each slice (2d array) of I want to write out to an imshow-like figure (i.e. a heatmap of the values). As a concrete example, say the array is of shape 3x3x3000, so I want 3000 images, each of which represents a 3x3 matrix. Looping over it with a single thread is a bit slow. Since the ite...
<p>Do a <code>matplotlib.use('agg')</code> at the head of the script. Matplotlib appears to be trying to establish a GUI in each sub-process, which are conflicting with one-another. </p> <p>More generally, you may not want to use the pyplot interface, but rather the OOP one, in cases where you are not doing standard i...
python|numpy|matplotlib|figure|python-multiprocessing
4
13,243
33,857,132
Checking Pandas column value contains in a list and assigning a value
<p>I have a pandas dataframe and a list with certain values.<br> I want to check whether each column value under a column header is contained in the list and want to assign 1 if it is found else 0.<br> In the below example , the column values under column header v is tested against the values in the list l.</p> <p...
<p><code>df.v.isin(l)</code> will give you a boolean Series:</p> <pre><code>0 True 1 False 2 False 3 False 4 True Name: v, dtype: bool </code></pre> <p>You can convert it into zeros and ones using <code>astype</code>:</p> <p><code>df.v.isin(l).astype(int)</code></p> <pre><code>0 1 1 0 2 0 ...
python|pandas
9
13,244
23,801,559
Pandas grouping and summing just a certain column
<p>below is a minimal example, showing the problem that I am facing. Let our initial state be the following (I only use dictionary for the purpose of demonstration):</p> <pre><code>A = [{'D': '16.5.2013', 'A':1, 'B': 0.0, 'C': 2}, {'D': '16.5.2013', 'A':1, 'B': 0.0, 'C': 4}, {'D': '16.5.2013', 'A':1, 'B': 0.5, 'C': 7}...
<p>Assuming the other columns are always the same, and should not be treated specially.</p> <p>First create the <code>df_new</code> grouped by <code>B</code> where I take for each column the first row in the group:</p> <pre><code>In [17]: df_new = df.groupby('B', as_index=False).first() </code></pre> <p>and then cal...
python|pandas|group-by
2
13,245
23,906,324
ValueError: operands could not be broadcast together with shapes (224,224) (180,180)
<p>I am writing a program to find the cosine similarity between two vectors. For small text files it works fine but for large datas it gives error. I have gone through many examples of broadcasting but couldn't get the actual problem. (Getting an error at line p=x*y)</p> <pre><code>x = numpy.dot(u, u.T) y = numpy.dot(...
<p>If <code>x</code> and <code>y</code> do not have the same shape, then you will get this type of error. they all must be the same shape. Please read <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">this</a> <code>numpy</code> broadcast rule </p>
python|numpy
2
13,246
15,005,629
Calculate pairwise difference from specific columns in a dataframe
<p>I have the following dataframe where I show how many times I have seen a move from Item1 to Item 2. For example there is one transition from A to B, 2 from A to C , 1 from C to A </p> <hr> <pre><code> Item1 Item2 Moves 1 A B 1 2 A C 2 3 B D 3 4 C A ...
<p>I'm sure someone could simplify this down to fewer lines, but I've left it long to help clarify what is going on. In a nutshell, split the dataframe into two pieces based on whether 'Item1' is earlier in the alphabet than 'Item2'. Then flip 'Item1' and 'Item2' and negate 'Moves' for one piece. Glue them back toge...
python|indexing|dataframe|pandas
4
13,247
13,701,035
boolean indexing on index (instead of dataframe)
<p>When I have a <code>pandas.DataFrame</code> <code>df</code> with columns <code>["A", "B", "C", "D"]</code>, I can filter it using constructions like <code>df[df["B"] == 2]</code>.</p> <p><strong>How do I do the equivalent of <code>df[df["B"] == 2]</code>, if <code>B</code> is the name of a level in a <code>MultiInd...
<p>I would suggest either:</p> <p><code>df.xs(2, level='B')</code></p> <p>or</p> <p><code>df[df.index.get_level_values('B') == val]</code></p> <p>I'd like to make the syntax for the latter operation a little nicer.</p>
python|pandas
1
13,248
13,735,589
I keep getting a syntax error and it highlights tempvals[day+1] but I am not sure why i am getting this error
<p>Input:is given values such as sig and rho_c make a list of all the days find the time for each individual day by using a for loop save that times find the change in temp. for each individual day find the value of temp for each individual day figure out which value you need for A graph the data ouptut: graph of Day v...
<p>You are missing a <code>:</code> in the previous line. </p> <pre><code>if day &lt; 2999: # &lt;- need a colon here tempvals[day+1]= T+dT </code></pre> <p>Edit: You also have unmatched brackets/parentheses in this line:</p> <pre><code>dT =(((S*(1-A))-((epsilon_tow*sig*(tempvals[day]**4))/rho_c )*dt # missin...
python|syntax|numpy
3
13,249
62,253,755
Detectron2 Panoptic FPN Model Partial Execution - TypeError: 'NoneType' object is not iterable
<p>I am trying to extract the pre-output feature-map for the Panoptic Output of <a href="https://github.com/facebookresearch/detectron2/blob/master/MODEL_ZOO.md#coco-panoptic-segmentation-baselines-with-panoptic-fpn" rel="nofollow noreferrer">Detectron2 ResNet50 - based FPN model</a>.</p> <p>Hence, In order to get par...
<p>With a bit more digging, I solved the issue. There were a couple of problems in the above code:</p> <ol> <li>I did not set the model to eval mode first - <code>model.eval()</code>. The model needs to be set to <code>eval</code> fist.</li> <li>The <code>mode.proposal_generator()</code> expects inputs in the form of ...
python|pytorch|typeerror|image-segmentation|feature-extraction
1
13,250
62,380,240
PermissionError: [Errno 13] Permission denied: '/usr/local/bin/saved_model_cli'
<p><strong>Environment</strong>: </p> <ul> <li>TensorFlow: 2.0</li> <li>Ubuntu: 16.04</li> </ul> <p>The main thing I wanna do is to uninstall TensorFlow2.0, and install TensorFlow1.12... I wanna uninstall TensorFlow2.0 using command like : <code>python3 -m pip uninstall tensorflow</code> , but I encountered some erro...
<p>I didn't try though, Try the same command with sudo.</p> <p><code>sudo python3 -m pip uninstall tensorflow</code></p>
python|tensorflow
0
13,251
62,165,076
"Un-melt" Dataframe and keep rest of columns? Python Pandas
<p>I have a table in this format, which I would like to transform with the "opposite" of melting. There is another question that addresses this but it doesn't work with so many other columns that I'd like to keep. </p> <p>The original:</p> <pre><code>COUNTRY STATE CATEGORY RESTAURANT STARS REVIEWS...
<p>A combination of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html#pandas.DataFrame.set_index" rel="nofollow noreferrer">set_index</a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer">crosstab</a> an...
python|pandas|reshape|melt
0
13,252
62,312,876
asyncio run until complete not forever
<p>Could anyone give me a tip on how to run asyncio script to stop when complete? I know its something to do with how I am setting the main loop to run... in this portion of the complete code but what ever I try from what I can find online it doesnt work.</p> <pre><code>loop = asyncio.get_event_loop() try: asynci...
<p>You probably want <code>asyncio.gather</code> and <code>run_until_complete</code></p> <pre><code>async def main(): await asyncio.gather(firstWorker(), secondWorker()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() </code></pre>
python|pandas|python-asyncio
1
13,253
62,223,840
Cannot import torch problem [WinError 126] but the file is in place
<p>I have tried to import torch after I have installed it following the official site. However, I got this error. I seems like ctypes.CDLL(c:\Users\Jianr\Miniconda3\lib\site-packages\torch\lib\caffe2_nvrtc.dll) returned this error. And this file is indeed at the location specified. This is an absolute path. And the dll...
<p>I also have the same problem, neither don't know how to fix it elegantly. And then I try to move the caffe2_nvrtc files (caffe2_nvrtc.dll and caffe2_nvrtc.lib) to a tmp dir, and now the problem is fixed. And my program works now, which is a deep nlp program.</p>
python|pytorch
0
13,254
62,076,779
pandas perform multiple transformations and creating a new data frame
<p>I have a daframe where I want to perform multiple (independent) transformations, and they create a new data frame (with a multi-index), where each index correspond to one of the transformations.</p> <p>More concretely:</p> <pre><code>df = pd.DataFrame([[1, "X", 'H', 100], [2, "Y", 'K', 100] ,[3, "X", 'H', 200], [4...
<p>You can do:</p> <pre><code>groups = df.groupby('A') pd.concat({col:groups[col].value_counts().unstack() for col in ['XY','HK']}, axis=1) </code></pre> <p>Output:</p> <pre><code> XY HK X Y H K A 100 1.0 2.0 2.0 1.0 200 1.0 NaN 1.0 NaN </cod...
python|pandas|pandas-groupby|multi-index
1
13,255
62,358,983
Python Pandas Quotation Marks
<p>I am trying to load a large log file on pandas, but this file is not uniform. There is legacy and junk. Before I load the data on pandas, can I remove the first character of the row, if it is a quotation marks (")?</p> <p>I am aware I could pre-clean the data before adding it to PD. However, that seems like an inef...
<p>Use <code>read_csv</code> with <code>QUOTE_NONE</code> (<code>3</code>) and then strip the quotation marks:</p> <pre><code>df = pd.read_csv(file, sep='\n', header=None, engine='python', quoting=3) df = df[0].str.strip(' \t"').str.split('[,|;: \t]+', 1, expand=True).rename(columns={0: 'email', 1: 'data'}) </code></p...
python|pandas
1
13,256
62,226,479
How do I get a word frequency count that is grouped by a second variable (Python)
<p>I am new to Python, so its probable that I am just not wording this properly to find the answer.</p> <p>Using Pandas I was able to find the most frequent N words for every record in the description field of my data. However, I have two columns; a categorical column and the description field. How to I find the most ...
<p>Data</p> <pre><code>df=pd.DataFrame({'Property':['House','Car','Car','House','Car'],'Description':['Blue,Two stories,pool','Green,Dented,Manual,New','Blue,Automatic,Heated Seat','Blue,Furnished,HOA','Blue,Old,Multiple Owners']}) </code></pre> <p><strong>Chained solution</strong> <code>df.assign(words=df.Descriptio...
python|pandas
1
13,257
62,396,456
loss of index when using pd.merge_asof()
<p>I have a question in respect of pd.merge_asof and indexing.</p> <p>First of all I am creating a data frame with the columns/data I need and then sorting it as follows:</p> <pre><code>df1 = df[['A','B','C']].sort_values('B') df1.head() </code></pre> <p>The head shows that the index from df has been carried forwar...
<p>When you merge and do not merge on any part of the original indices, the index loses its relevance. You join rows from different DataFrames, so how would you know which index to choose?</p> <h3>Sample Data</h3> <pre><code>import pandas as pd df1 = pd.DataFrame({'foo': [1,2,3]}, index=list('abc')) df2 = pd.DataFram...
python|pandas|indexing|merge
1
13,258
62,077,143
Accessing elements in panda dataframe
<p>How do I iterate through this dataframe? I want to know what the nameis (AAL, AAME, or AACG) and be able to access the everything highlighted in red for name.</p> <p><a href="https://i.stack.imgur.com/zBbpN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zBbpN.png" alt="Pandas stock dataframe"><...
<p>You are trying to access the multi-index column. Accessing a multi-index column is pretty the same as the access a column in the general dataFrame. For example, if you want to access <code>2020-05-21</code> row in <code>AAL</code> then you have to...</p> <pre><code>df['AAL']['Date']['2020-05-21'] </code></pre>
python|pandas
0
13,259
62,116,024
Failed Remove Anaconda Package (InvalidArchiveError)
<p>I accidentally install tensorflow-gpu using <code>conda install -c anaconda tensorflow-gpu</code> in my base environment. When I try to remove that use the commands</p> <pre><code>conda clean -a conda remove tensorflow-gpu </code></pre> <p>It return InvalidArchiveError</p> <blockquote> <p>InvalidArchiveError('E...
<p>Providing the solution here (Answer Section), even though it is present in the Comment Section for the benefit of the community.</p> <p>This issue can be resolved in two methods</p> <p><strong><em>First Method</em></strong>: Remove <code>openssl-1.1.1g-he774522_0.tar.zst</code> and number of folders <code>openssl...
python|tensorflow|anaconda|conda|uninstallation
1
13,260
62,287,324
python to excel append in rows
<p>I have written a program and I am trying to export the results in excel. I have this inside the function (although I kinda think now that it should be outside the main function).</p> <pre><code> minas=minas_ex.get() data = pd.DataFrame(data =all_together) data=data.transpose() ##book= load_workbook('FromPython.xl...
<p>Apparently, it's not as simple as I thought. Stolen from <a href="https://medium.com/better-programming/using-python-pandas-with-excel-d5082102ca27#9cd6" rel="nofollow noreferrer">https://medium.com/better-programming/using-python-pandas-with-excel-d5082102ca27#9cd6</a></p> <pre class="lang-py prettyprint-override"...
python|pandas.excelwriter
1
13,261
62,450,840
how to multiply over all rows pandas
<p>Hello Guys i wannt to multiply over all rows </p> <pre><code>df_innerfinal['Value'] = df_innerfinal['MENGE'] * df_innerfinal['PERIODE4'] df_innerfinal['EXCHANGE_RT'] = df['EXCHANGE_RT'] df_innerfinal['ValueUSD'] = df_innerfinal['Value']*df['EXCHANGE_RT'] </code></pre> <pre><code> MNR EAN PERIODE4 ...
<p>Try this:</p> <pre><code>exchange_rate = pd.to_numeric(df.iloc[0]['EXCHANGE_RT']) df['ValueUSD'] = pd.to_numeric(df['Value']).multiply(exchange_rate) print(df) MNR EAN PERIODE4 MENGE 0 1 2 3 4 5 6 7 8 9 10 11 12 Value EXCHANGE_RT ValueUSD 0 ...
python|pandas
0
13,262
51,355,151
Calculate a mean of pandas dataframe whose cells are list
<p>Suppose I have the following pandas dataframe</p> <pre><code>import pandas as pd import numpy as np df= pd.DataFrame(np.nan, columns =["A","B","C"], index =np.arange(5)) df=df.astype(object) for c in list(df): for i in df.index.values: df.at[i, c]=np.arange(5).tolist() </code></pre> <p>This results in ...
<p>You might want to restructure your dataframe as mentioned. But to work with what you have, assuming you want the mean of each element in the dataframe, you can try the <code>applymap</code> method.</p> <pre><code>df.applymap(np.mean) </code></pre>
python|pandas|numpy
5
13,263
48,316,625
In a two class issue with one-hot label, why tf.losses.softmax_cross_entropy outputs very large cost
<p>I am training a mobilenet for semantic segmentation on tf. The targets has two classes: <em>foreground(1)</em> or <em>background(0)</em>. So this is a two class classification issue. I choose softmax cross entropy as the loss, using python code like: </p> <pre><code>tf.losses.softmax_cross_entropy(self.targets, log...
<p>The input targets format for <code>tf.losses.softmax_cross_entropy</code> and <code>tf.losses.sparse_softmax_cross_entropy</code> is different.</p> <blockquote> <ul> <li>For <code>sparse_softmax_cross_entropy_with_logits</code> labels must have the shape [batch_size] and the dtype int32 or int64. Each lab...
python|tensorflow
0
13,264
48,370,819
keras > always the same prediction value after loading saved model
<p>I am training some model via <code>keras</code> with <code>tensorflow</code> backend. </p> <p>When I call predict right after training on the same object it works fine and gives different values for different inputs. But when I save the model to a file, then load it from another <code>python</code> session, <code>p...
<p>I had the same issue, I solved by setting a fixed seed to tensorflow, numpy and python.</p> <pre><code>import tensorflow as tf import numpy as np import random as python_random tf.random.set_random_seed(42) np.random.seed(42) python_random.seed(42) </code></pre> <p>Be careful! Different versions of tensorflow may re...
python|tensorflow|keras
2
13,265
48,712,726
Find min index over all Panda data frame
<p> Hi </p> <p>I want to find minimum index overall data frame.Actually, my columns are not features and I just use their labels.</p> <p>assume my data frame is something like this :</p> <pre><code> 0 1 2 a 100 1 2 b 1 100 4 c 2 4 100 </code></pre> <p>I want a function which returns <...
<p>You can using <code>min</code> twice </p> <pre><code>s=(df==df.min().min()).dot(df.columns) s=s.loc[s!=''] s Out[177]: a 1 b 0 dtype: object </code></pre> <p>If you need <code>tuple</code> </p> <pre><code>list(zip(s,s.index)) Out[182]: [('1', 'a'), ('0', 'b')] </code></pre> <p>Or we using <code>np.where<...
python|pandas|dataframe
2
13,266
48,529,438
Why does the shape of a Pandas DataFrame change after reading/loading a saved file?
<p>I want my code to accomplish the following:</p> <ul> <li>Check if there is any file in the folder named 'ledger'. THIS WORKS.</li> <li>If no, make a file. THIS WORKS.</li> <li>If yes, read the file, update contents in the file, and save the file maintaining the shape of the file. THIS DOESN'T WORK.</li> </ul> <p>I...
<p>I think the issue is that when you are writing to the file, you write the indices too.</p> <pre><code>save.to_csv(os.path.join(path, r'ledger.csv'), index = False) </code></pre> <p>this will prevent writing the index to file. When you read this file it should have seven columns</p>
python|pandas|dataframe
3
13,267
48,520,816
How to loop over pandas dataframe and generate new rows?
<p>I have a pandas dataframe in the following format:</p> <pre><code>User app percent 1 a 0.8 1 b 0.3 1 c 0.2 1 d 0.9 1 e 0.6 1 f 0.8 1 g 0.4 1 h 0.2 1 i 0.1 1 j ...
<p>I think you need aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>size</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.prod.html" rel="nofollow noreferrer"><code>Gr...
python|pandas
0
13,268
70,866,454
How to parse and stack XML nodes and children correctly?
<p>I am currently trying to analyze some voting behavior in the European Parliament, using the parliaments XML interface. However, even though I am able to import the information and manipulate them somehow, I am not able to a meaningful pandas DataFrame.</p> <p>E.g. I try to set up two data frame with &quot;for&quot; ...
<p>I believe there's a bug in your code on this line:</p> <pre><code>for amep in avote.iter('PoliticalGroup.Member.Name'): </code></pre> <p>You should probably iterate over <code>anitem</code> objects instead of <code>avote</code>. There are two places where you need to fix it. I've just checked and this results in dif...
python|pandas|xml|parsing
2
13,269
70,992,199
Installing tensorflow on virtualbox ubuntu 20.04 python 2.7 - 'Illegal instruction (core dumped)'
<p>my goal is to follow this <a href="https://ndres.me/post/convert-caffe-to-tensorflow/" rel="nofollow noreferrer">guide</a> so that I can convert a Caffe model to a Tensorflow model. As my original OS is Windows 10 I am using the virtual Ubuntu 20.04 (using Oracle VirtualBox) with python 2.7 and anaconda virtual env....
<p>For those wondering, the pip or conda installation did not work in my case, so I followed the instructions on this <a href="https://chromium.googlesource.com/external/github.com/tensorflow/tensorflow/+/r0.10/tensorflow/g3doc/get_started/os_setup.md" rel="nofollow noreferrer">guide</a> for linux, python 2.7 using the...
python-2.7|tensorflow|virtualbox|ubuntu-20.04
0
13,270
70,746,957
Python Seaborn Ridge Plot tutorial not working
<p>If I copy paste the example given on <a href="https://seaborn.pydata.org/examples/kde_ridgeplot.html" rel="nofollow noreferrer">Seaborn website</a> to make a &quot;Ridge Plot&quot;, the code fails in two different points:</p> <pre><code>import numpy as np import pandas as pd import seaborn as sns import matplotlib.p...
<p>You can replace <code>g.figure</code> with <code>g.fig</code>. <code>g.figure</code> is intended to be the new name for the same variable. <code>refline()</code> is new in seaborn 0.11.2 (the website supposes you run the last published version). You could replace the call to <code>g.refline()</code> with <code>g.map...
pandas|matplotlib|seaborn
3
13,271
70,960,021
Python: programmatically supplying column names and datatypes to schema definition
<p>I am writing to snowflake through python. Once I create a final pandas dataframe, I am creating schema definitions with each columns and the data type I want it to be:</p> <pre><code>schema_name= [('col1', 'string'), ('col2', 'string'), ('col3', 'date'), ('col3', 'float')...] </code></pre> <p>which I then pass it to...
<p>Let's say you have following dataframe:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'ID': [23,24,25,26,27], 'x': [0.0,2.2,2.3,2.4,2.5], 'y': ['a','b','c','d','e'] }) </code></pre> <p>Using following expression</p> <pre><code>list(zip(df.columns, df.dtypes)) </code></pre> <p...
python|pandas
3
13,272
51,912,875
Lagged Sales for every product
<p>Good Evening,</p> <p>I have the following dataframe:</p> <pre><code>print(dd) dt_op quantity product_code 20/01/18 1 613 21/01/18 8 611 21/01/18 1 613 ... </code></pre> <p>I am trying to get the lagged Sales, but the following code does <strong>not</strong> ...
<p>IIUC, group with <code>pd.Grouper</code> and "product_code":</p> <pre><code>df.dt_op = pd.to_datetime(df.dt_op, errors='coerce') df.groupby([pd.Grouper(key='dt_op', freq='15D'), 'product_code']).quantity.sum() dt_op product_code 2018-01-20 611 8 613 2 Name: quantity, dtyp...
python|pandas
1
13,273
51,649,482
How to load new parts of Dataset dynamically during training of an Estimator?
<p>I have an interesting problem.</p> <p>I am doing regression on a large dataset (15M rows, 16 cols) using <code>tf.Estimator</code> and I used the common way to load data into <code>tf.Dataset</code>:</p> <pre><code>def input_fn_train(features, labels, batch_size, repeat_count): dataset = tf.data.Dataset.from_...
<p>Okay, I found a solution to my problem. It can be done using <code>Dataset.from_generator()</code> function. My solution uses one generator for generating DataFrames and second to generate rows while iterating over these DataFrames.</p> <pre><code>a = arange(20).reshape(10,2) df = DataFrame(a, columns=['x1','y1']) ...
python|tensorflow|tensorflow-datasets|tensorflow-estimator
2
13,274
51,605,570
How to read unsigned 16 bit integer binary data with Tensorflow from a file queue?
<p>I'm trying to modify the Advanced Convolutional Neural Networks tutorial of Tensorflow, which originally uses the CIFAR-10 dataset (<a href="https://www.tensorflow.org/tutorials/images/deep_cnn" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/deep_cnn</a>) to work with unsigned 16-bit integer d...
<p>I came up with a solution, which used the TFRecords format (<a href="https://www.tensorflow.org/api_guides/python/python_io#tfrecords_format_details" rel="nofollow noreferrer">https://www.tensorflow.org/api_guides/python/python_io#tfrecords_format_details</a>). </p> <p>The solution was inspired by this thread: <a h...
python|tensorflow|visual-studio-2017
0
13,275
64,313,712
creating dataframes from dict and appending them
<p>i have a directory of files which I'm parsing into dictionaries with multiple key-value pair and I want to store each dictionary as a row in pandas dataframe.</p> <pre><code>import pandas as pd df = pd.DataFrame() for file in os.listdir(directory): dict1 = parseFileToDict(file) df_temp = pd.DataFrame.from_d...
<p>Create list of dicts first in loop:</p> <pre><code>L = [] for file in os.listdir(directory): dict1 = parseFileToDict(file) L.append(dict1) </code></pre> <p>Or in list comprehension:</p> <pre><code>L = [parseFileToDict(file) for file in os.listdir(directory)] </code></pre> <p>and then pass to <code>DataFrame<...
python|pandas|dataframe
1
13,276
64,307,126
melt/Pivot in python dataframe
<p>I am trying to convert Input data frame to output data frame, but code is not working properly, not sure where am I missing.</p> <p>What I tried:</p> <ul> <li><p>I tried to use pandas.pivot(index, columns, values) function but its showing me error not sure where I am missing. I also tried to play around with index...
<p>You were not passing <code>value_vars</code> argument.</p> <pre><code>df=pd.DataFrame({'MeasurementDate':['22-07-2020', '23-07-2020','24-07-2020','25-07-2020','26-07-2020','27-07-2020','28-07-2020'], 'U1':['V1.1','V1.2','V1.3','V1.4','V1.5','V1.6','V1.7'], 'U2':['V2.1','V2.2','V2.3','V2.4','V2.5','V2.6',...
python|pandas|dataframe|data-manipulation|melt
3
13,277
64,601,776
How to get activation of a hidden layer in tensorflow.js?
<p>In TensorFlow.js, I have a very simple <code>tf.Sequential</code> model created like this:</p> <pre><code>let model = tf.sequential(); model.add(tf.layers.dense({inputShape: [784], units: 128, activation: 'relu'})); model.add(tf.layers.dense({units: 10})); model.add(tf.layers.softmax()); </code></pre> <p>During pred...
<p>For more complex models, there's an easier way. If <code>model</code> is the original model, you can create a copy using <code>tf.model({inputs:model.inputs, outputs: model.layers[2].output})</code>, thereby only needing to provide the first and last layer</p>
tensorflow|tensorflow.js
1
13,278
64,571,812
How to handle missing x-axis values when plotting multiple line charts using python-pptx
<p>I am trying to plots multiple line charts on same graph using <code>python-pptx</code> module. Here is my data:</p> <pre><code>month desc value 201911 a 1164 201912 a 971 202001 a 1125 202005 b 1549 202005 a 1038 202006 b 1244 202006 a 1475 202007 a 960 </code></pre> <p>The <code>mon...
<p>You need to use <code>None</code> as the value for any points you don't want to be plotted. I looks like your data retrieval simply <em>omits</em> missing data points. You need to get it so the categories sequence and the values sequence (for each series) are the same length and aligned by position.</p> <p>Like:</p>...
python-3.x|pandas|python-pptx
0
13,279
64,518,337
Installing TensorFlow for Raspberry Pi
<p>I am following this link to create a .whl package for Raspberry Pi:</p> <p><a href="https://www.tensorflow.org/install/source_rpi" rel="nofollow noreferrer">https://www.tensorflow.org/install/source_rpi</a></p> <p>Specifically, I am running the following command:</p> <p><code>tensorflow/tools/ci_build/ci_build.sh PI...
<p>Install anaconda. Create an env with python 3.5, activate it and then run the script</p>
python|tensorflow|raspberry-pi
0
13,280
47,946,967
Convert 4 one-to-one mapped lists into a list of dicts (python)
<p>I have 4 lists where the elements are one-to-one mapped. There are <em>tens of thousands of elements</em>. I want to create one dict giving the 4 properties for each element, and then I want to put these dicts into a list. (My end goal is to create a pandas DataFrame and save it as an HDF5 file.)</p> <p>Is there an...
<p>Since you tag <code>pandas</code> , By using <code>to_dict</code></p> <pre><code>pd.DataFrame({'obj':list1,'type':list2,'num':list3,'color':list4}).to_dict('r') Out[1204]: [{'color': 'red', 'num': 7, 'obj': 'obj1', 'type': 'cat'}, {'color': 'green', 'num': 8, 'obj': 'obj2', 'type': 'dog'}, {'color': 'blue', 'num...
python|pandas|numpy|dictionary|dataframe
5
13,281
47,555,231
Creating Numpy Matrix from pyspark dataframe
<p>I have a pyspark dataframe <code>child</code> with columns like:</p> <pre><code>lat1 lon1 80 70 65 75 </code></pre> <p>I am trying to convert it into numpy matrix using IndexedRowMatrix as below:</p> <pre><code>from pyspark.mllib.linalg.distributed import IndexedRow, IndexedRowMatrix mat = IndexedRowMatrix...
<p>You want to avoid pandas, but you try to convert to an RDD, which is severely suboptimal...</p> <p>Anyway, assuming you can <code>collect</code> the selected columns of your <code>child</code> dataframe (a reasonable assumption, since you aim to put them in a Numpy array), it can be done with plain Numpy:</p> <pre...
numpy|pyspark|apache-spark-sql
5
13,282
58,810,376
Two datastructures sharing an iterator in python
<p>I need to iterate over two datastructures, a DataFrame, and a list of empty lists. Since for my application they always share the same iterable length in common (i.e. there are <em>k</em> dataframe columns and therefore initially <em>k</em> empty lists), is it possible to have them in the same for loop like below? T...
<p>I liked this question a lot! I never had to do this before, but found it useful and fun. You most certainly can, here's an example!</p> <pre><code>import pandas as pd example_data = {'a':[1,2],'b':[2,3],'c':[4,5]} df = pd.DataFrame(example_data) example_list = [[],[],[]] for i in range(len(list(df))): example_...
python|python-3.x|pandas
1
13,283
58,674,232
iterating over a list of columns in pandas dataframe
<p>I have a dataframe like below. I want to update the value of column C,D, E based on column A and B.</p> <p>If column A &lt; B, then C, D, E = A, else B. I tried the below code but I'm getting <code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</code> erro...
<p><code>np.where</code> Return elements are chosen from A or B depending on condition.</p> <p><code>df.assign</code> Assign new columns to a DataFrame.</p> <p>Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten.</p> <pre class="lang-py p...
python-3.x|pandas
1
13,284
58,827,408
Python PANDAS: Apply Multi-Line Boolean Criteria Within Group?
<p>I have a dataset with the following general format:</p> <pre><code>id,thing_criteria_field,place_criteria_field 1,thing_1,place_2 1,thing_3,place_2 1,thing_3,place_2 1,thing_7,place_1 2,thing_3,place_3 2,thing_7,place_2 2,thing_9,place_2 2,thing_4,place_5 3,thing_1,place_1 3,thing_2,place_6 3,thing_3,place_6 3,thin...
<p>Try this:</p> <pre><code># Build a dataframe indicating whether each row meets # each of the individual criterion all_criteria = [thing_criteria, place_criteria] cond = pd.DataFrame(all_criteria).T \ .assign(id=df['id']) # Now group them by id and reduce the truth values # .any(): test if any row in the ...
python|pandas|pandas-groupby
1
13,285
70,196,272
Overcoming incompatibilities between tensorflow 1.x and 2.x when trying to view layer activity with backend
<p>I would like to run newer tensorflow routines like:</p> <pre><code> from tensorflow.keras.preprocessing import image_dataset_from_directory </code></pre> <p>for which I get error in 1.x:</p> <p>ImportError: cannot import name image_dataset_from_directory</p> <p>while preserving older functionality of 1.x like run...
<p>As suggested <a href="https://github.com/tensorflow/tensorflow/issues/34201#issuecomment-557308250" rel="nofollow noreferrer">#34201</a>, Just disable the eager execution and run the rest of your code</p> <pre><code>import tensorflow as tf tf.compat.v1.disable_eager_execution() from tensorflow.keras.preprocessing im...
python|tensorflow|keras|libraries
0
13,286
70,049,554
How to Test multiple columns of pandas for a condition at once and update them
<p>I have a data frame like this:</p> <pre><code>test = pd.DataFrame({'col1':[10,20,30,40], 'col2':[5,10,15,20], 'col3':[6,12,18,24]}) test </code></pre> <p>The dataframe looks like:</p> <pre><code> col1 col2 col3 0 10 5 6 1 20 10 12 2 30 15 18 3 40 20 24 </code></pre> <p>I wanna replace the val...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer">where</a>:</p> <pre><code>import pandas as pd test = pd.DataFrame({'col1':[10,20,30,40], 'col2':[5,10,15,20], 'col3':[6,12,18,24]}) test[['col2', 'col3']] = test[['col2', 'col3']].where(test[['co...
python|pandas|dataframe|pandas-loc
1
13,287
56,226,835
Pandas read_gbq init error using Dataflow
<p>I have been running a Dataflow job using Python that utilizes the pandas library. It suddenly started failing with the following error:</p> <blockquote> <p>File "/usr/local/lib/python2.7/dist-packages/pandas_gbq/auth.py", line 305, in _try_credentials client = bigquery.Client(project=project_id, credential...
<p>I had to add a BigQuery version to my setup file.</p> <pre><code>'google-cloud-bigquery==1.6.0' </code></pre> <p>According to Google <a href="https://cloud.google.com/dataflow/docs/concepts/sdk-worker-dependencies#dataflow-2x-python" rel="nofollow noreferrer">documentation</a> for Python SDK 2.5, the Dataflow work...
pandas|python-2.7|google-bigquery|google-cloud-dataflow
0
13,288
56,020,618
pandas version upgrade 0.24.2 apply problem
<p>Upgraded my pandas version to 0.24.2 and having problems with running existing code:</p> <p><em>base_smile</em> is a dataframe,</p> <p><em>xbar</em> is a float,</p> <p><em>spot</em> is also a float</p> <p>I am just trying a simple apply that used to work just fine in the older version. </p> <pre><code>base_smil...
<p>Your new code probably doesn't do what you want. Anyway it can be rewritten in a better way:</p> <pre><code>base_smile['xbar'] *= np.where(base_smile['strike'] &gt; spot, 1, -1) </code></pre> <p>This will work in any version, and be much faster.</p>
python|pandas
0
13,289
56,101,226
Install tensorflow on windows python 3.6
<pre><code>Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow </code></pre> <p>This message is shown when I try to <code>pip install</code>. I have tried it with python 3.7 when it didn't work. I also tried it with 3.6 and I still tensorf...
<p>Try using Christoph Gohlke's packages: <a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/#tensorflow" rel="nofollow noreferrer">https://www.lfd.uci.edu/~gohlke/pythonlibs/#tensorflow</a></p> <p>Download the package for Python 3.6, then use <code>pip install</code> on the package:</p> <pre><code>pip install tenso...
python|tensorflow|command-prompt
2
13,290
55,862,510
Pandas BuildPaths Efficiently
<p>I have a Pandas dataframe like below, which has two arbitrary customers with 2 months' data(there are more months) and ATL_Flag which are marketing channels(there are more of them too):</p> <pre><code>|App_Flag|ATL_Flag|Cust_No|month1|month2 | 0 | TV | 1 | 1 | 0 | 0 | FB | 1 | 0 | 0 ...
<p>First get all columns with <code>month</code>s, replace <code>1</code> values by <code>ATL_Flag</code> column and aggregate <code>join</code> per groups and then join columns together by another <code>join</code>:</p> <pre><code>c = df.filter(like='month').columns df[c] = np.where(df[c].astype(bool), df['ATL_Flag']...
python|python-3.x|pandas
2
13,291
55,772,329
How to get cumsum using custom aggregation function in pandas
<p>I have <code>DataFrame</code> like mentioned below</p> <pre><code>df = pd.DataFrame({'year':[2014,2017,2014,2016,2016],'prod':['A','B','C','D','E']}) </code></pre> <p>I can get it using this</p> <pre><code>df.groupby('year').count().cumsum() ## prod year 2014 2 2016 4 2017 5 </code></pre> <p>I ...
<p>Function <code>cumsum</code> as applied for output of aggregation - here one column <code>DataFrame</code>, so is necessary chain it after <code>agg</code>:</p> <pre><code>print (df.groupby('year').agg({'year':count_sum})) year year 2014 2 2016 2 2017 1 df1 = df.groupby('year').agg({'year':...
python|pandas|group-by
0
13,292
55,883,795
trainable_variables attribute of the custom layer in Keras returns empty list
<p>I tried to build my own custom layer in <code>tensorflow/keras</code> that enforces the layer to be symmetric and what I ended up with is the following:</p> <pre><code>import tensorflow as tf from tensorflow.python.framework.ops import enable_eager_execution enable_eager_execution() class MyDenseLayer(tf.keras.lay...
<p>You need to add variables using <code>add_weight</code> and then call <code>build()</code> method to create this variable. Alternatively, instead of calling <code>build()</code> directly you can pass an input (as you do in your question) and it will call implicitly the <code>build()</code> method. </p> <pre class="...
python|tensorflow|machine-learning|keras|keras-layer
3
13,293
64,704,146
Get non sorted column levels in pandas dataframe with multiIndex
<p><strong>Background:</strong></p> <p>I have a pandas dataframe with MultiIndex.</p> <p>I want to get the columns.levels NOT sorted.</p> <p>df.column.levels gives them to me but sorted.</p> <p><strong>Example:</strong></p> <pre><code>worms=['worm1', 'worm2', 'worm3'] bodyparts=['head', 'vulva', 'tail'] coords=['x', 'y...
<p>This gives you them in order of appearance:</p> <pre><code>pd.unique(df.columns.to_frame()['bodyparts']) </code></pre> <p>Outputs: <code>['head' 'vulva' 'tail']</code></p>
python|pandas|dataframe
1
13,294
64,728,190
Showing the proportions of values across each column in a DataFrame in Python
<p>I have created the following DataFrame:</p> <pre><code>dataset = pd.DataFrame(np.random.randint(0,3,size=(5, 8)), columns=list('ABCDEFGH')) </code></pre> <p>Now I wish to show the proportion of each value (0,1,2) across each column. Ideally I'd like to represent this as a stacked bar chart - Column names on the x ax...
<p>This seems to be the most efficient way. In terms of shortening it, is it this what you are looking for? It is really your solution, just condensed via comprehensions.</p> <pre><code>df = pd.concat([dataset[colid].value_counts(normalize=True).mul(100) for colid in list('ABCDEFGH')], axis=1,keys=('propo...
python|pandas|plot
0
13,295
64,981,663
Can't use .toPandas() or .collect() after applying pandas udf: IndexError
<p>I am using pandasUDF to apply standard ML python libraries to pyspark DataFrame. After defining the schema and making predictions I get the pyspark DF as an output. Now, I want to do some stuff with this predictions dataframe, e.g. I try to sum up all the values in the column &quot;weekly_forecast_1&quot;. When I ap...
<p>The error</p> <pre><code>IndexError: too many indices for array:array is 0-dimensional, but 1 were indexed </code></pre> <p>means that you are trying to index an array with too many indices for its dimensions. Here, it seems that your array is 0-dimensional (meaning it is a scalar) and you try to index it.</p> <p>Si...
python|pandas|pyspark|user-defined-functions
0
13,296
69,314,571
How to convert one record per change to continuous data?
<p>My data looks like this:<br /> print(df)</p> <pre><code>DateTime, Status '2021-09-01', 0 '2021-09-05', 1 '2021-09-07', 0 </code></pre> <p>And I need it to look like this:<br /> print(df_desired)</p> <pre><code>DateTime, Status '2021-09-01', 0 '2021-09-02', 0 '2021-09-03', 0 '2021-09-04', 0 '2021-09-...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html" rel="nofollow noreferrer"><code>DataFrame.asfreq</code></a> working with <code>DatetimeIndex</code>:</p> <pre><code>df = df.set_index('DateTime').asfreq('d', method='ffill').reset_index() print (df) DateTime Sta...
python|pandas|join
1
13,297
41,036,518
Pandas pivot table - setting the months index as chronological order, not alphabetical
<p>I am trying to make a heatmap using seaborn, with months as the y-axis. However I see that if I call calendar.head() after making the pivot table, that the pivot table has the months column in alphabetical order instead of the chronological order which I have in my csv file. Is there anyway of stopping pandas from o...
<p>Lets say you have the months of the year stored in a list (in order) like so:</p> <pre><code>months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] </code></pre> <p>And that these are the same strings used to represent months in your pivo...
pandas|pivot-table|seaborn
1
13,298
53,920,952
How to deal with pandas reading JSON too large integer values will be the same
<p>I have a JSON file where the value column is a large integer. The integer value will be the same when I read it with pandas.</p> <p>An example</p> <pre><code>import pandas as pd line = '{"value":"383088110696696320"}\n{"value":"383088110696696321"}' df = pd.read_json(line,lines=True) print(df) va...
<p>Not sure if you are on a 32 or 64 bit machine, but you should try to use <code>np.int64</code>:</p> <pre><code>import numpy as np import pandas as pd line = '{"value":"383088110696696320"}\n{"value":"383088110696696321"}' df = pd.read_json(line, lines=True, dtype=False) df['value'] = df['value'].astype(np.int64) d...
python-3.x|pandas|numpy
2
13,299
66,214,833
VS Code : ModuleNotFoundError: No module named 'pandas_datareader'
<p>I followed Microsoft's tutorial <a href="https://code.visualstudio.com/docs/python/data-science-tutorial" rel="nofollow noreferrer">https://code.visualstudio.com/docs/python/data-science-tutorial</a> and installed miniconda, I use it's python interpretor, and tried to import the following :</p> <pre><code>import mat...
<p>By default all the installations you do will be in base environment and not in the virtual environment.</p> <p>You'll have to activate the virtual environment in conda and then do a pip list to check if the package is present:</p> <pre><code>conda activate your_env_name pip list </code></pre> <p>If it's not present,...
python|pip|anaconda|pandas-datareader
0