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
365,400
67,745,283
Accuracy is dropped after adding a dense layer to a pretrained Mobilenet model
<p>I have the following code, utilising mobilenetv2 for two class classification. After adding the dense layer with 2 units, the accuracy is dropped significantly to 45%. I couldn't figure out what could be the issue, I changed optimiser but still accuracy didnt improve. My training dataset is 2000 with two categories,...
<p>You can use the <code>include_top=False</code> statement when you load the pretrained model. This code statement removes the last part of the pretrained model.</p>
tensorflow|machine-learning|keras|conv-neural-network
0
365,401
67,708,255
Populate one dataframe based on information in another dataframe
<p>I have two large dataframes, but am only showing a small subset of them for convenience. One is in the following form (Table 1):</p> <pre><code>| Country | Date | flag | M | notes | V | |--------------------------------------------------| | UK | 20210319 | 1 | 3.0 | No Change | C1 | | UK | 20...
<p><code>Restructure</code> the 1st dataframe / <code>manipulate columns</code> and then <code>update</code> the other dataframe with this restructured dataframe.</p> <pre><code>k = df1.pivot(index=['Country','Date'] , columns= ['V'] , values= ['flag','M','notes']) k.columns = ['_'.join(col[::-1]) if 'M' not in col els...
python|pandas|dataframe|validation|data-cleaning
1
365,402
68,007,040
Create new column with a group ID that changes based on the value of another column
<p>I have a dataframe with a bunch of Q&amp;A sessions. Each time the speaker changes, the dataframe has a new row. I'm trying to assign question characteristics to the answers so I want to create an ID for each question-answer group. In the example below, I want to increment the id each time a new question is asked (<...
<p>you can use <code>eq</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a> like:</p> <pre><code>Q_A['gr2'] = Q_A['speakertype_id'].eq(3).cumsum() print(Q_A) qna_id qnacomponentid speakertype_id group gr2 0 ...
python|pandas
2
365,403
67,645,989
Double pandas groupby operation with pairwise comparison between outer/inner loop groups
<p>I'm trying to do a somewhat complicated pandas groupby operation. Here's some functional but slow pandas code.</p> <pre class="lang-py prettyprint-override"><code># Construct a toy dataframe idx1 = [&quot;bar&quot;, &quot;baz&quot;, &quot;foo&quot;] idx2 = list(range(100, 104)) idx3 = list(range(3)) num_data = len(i...
<p>You can try this, not sure if this is more efficient or not:</p> <pre><code>dfi = input_df['x'].unstack(level=['second','fourth']) dfi.update(dfi.groupby('first').ffill()[['positive']]) dfi = dfi.stack() neg_nulls = dfi['negative'].isna() pos_nulls = dfi['positive'].isna() dfi = dfi.fillna(False) dfi['tru...
python|pandas|pandas-groupby
3
365,404
67,923,985
StandardScaler.inverse_transform() return the same array as input :/ Is sklearn broken or am I?
<p>Good evening,</p> <p>I'm currently pursuing a PhD in chemistry and in this framework I'm trying to apply my few knowledge in python and stats to discriminate sample based on their IR spectrum. After a few of weeks of data acquisition I'm finally able to build my data set and was about to see what PCA can offer (this...
<p>Good evening,</p> <p>After putting the problem aside for a few days I finally re-coded the function I needed (as suggested by Robert Dodier).</p> <p>For reminder, I wanted to have a function that could take my data from a pandas dataframe and mean-centered it in order to do PCA, but also that could reverse the prep...
python|syntax|statistics|sklearn-pandas
0
365,405
67,830,659
Data quality Numeric Columns only
<p>I'm trying to setup a data quality check for numeric columns in a dataframe. I want to run the describe() to produce stats on each numeric columns. How can I filter out other columns to produce stats. See line of code I'm using.</p> <p>df1 = pandas.read_csv(&quot;D:/dc_Project/loans.csv&quot;) print(df1.describe(i...
<p>Went with the following from a teammate: import pandas as pd import numpy as np</p> <p>df1 = pandas.read_csv(&quot;D:/dc_Project/loans.csv&quot;) df2=df1.select_dtypes(include=np.number)</p>
python|pandas
0
365,406
67,860,242
python: how do I randomly sample a number of samples from a population?
<p>I have generated 100 samples with specific mean and variance:</p> <pre><code>import numpy as np mean = 0 variance = 0.1 std_dev = np.sqrt(variance) t = np.random.normal(mean, std_dev, 100) print(t) </code></pre> <p>I want to <b>randomly sample 10 samples</b> from this population. Is there a way to extract samples ra...
<p>You can use the np.random.choice() function to get a numpy array of 10 random samples (second parameter is the size of the array you want)</p> <pre><code>import numpy as np mean = 0 variance = 0.1 std_dev = np.sqrt(variance) t = np.random.normal(mean, std_dev, 100) print(t) sample = np.random.choice(t,10) print(sam...
python|numpy
1
365,407
67,853,434
How to import the pandas library?
<p>I had installed Python 3 on my laptop running Windows 10. I was trying to import pandas library so that I can read and edit Excel files for a project. However, it is giving an error.</p> <p>The code I use is the standard:</p> <pre><code>import pandas as pd </code></pre> <p>I get a <code>Traceback, ModuleNotFoundErro...
<pre><code>pip uninstall pandas pip install pandas </code></pre> <p>Run these commands.</p>
python|pandas
1
365,408
67,655,914
how to make existing tensorflow 2.4 installation to use GPU
<p>I have python 3.7.6, tensorflow 2.4.1 and keras 2.4.0 successfully installed. The code is working too. I have Nvidia graphic card on my computer. I wanted to make tensorflow use GPU to speed up training. I followed all steps to install CUDA 10.2 and cuDNN 8.0.4 as given in various internet blogs. Installation is suc...
<p>According to this list (<a href="https://www.tensorflow.org/install/source#gpu" rel="nofollow noreferrer">https://www.tensorflow.org/install/source#gpu</a>) Tensorflow 2.4 requires CUDA 11.</p>
tensorflow
0
365,409
67,652,589
Problems storing data from csv in dictionary in a for loop
<p>I’m creating a system to keep track of the performance of stocks over an extended period. What I intend for it to do is take tickers from a spreadsheet, search for those tickers on Yahoo finance, pull the historical data for those stocks and then stores the data against the ticker as dictionary or list. While I’ve g...
<p>Here is a pretty simple solution that uses a function that returns a combined DataFrame from all the tickers within the date range provided:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime import pandas as pd def get_quotes(tickers: list[str], start_date: datetime, ...
python|pandas|for-loop
1
365,410
67,978,673
fastest way to iterate through uneven columns to find the existing value
<p>I have 2 DataFrames of (df1) 35k and (df2) 76k rows where I need to check whether <code>df1[&quot;col1&quot;]</code> elements exist in <code>df2[&quot;col2&quot;]</code> sub-elements. The code seems to be working fine on a sample dataset I have provided but the runtime takes forever on the original one. Here is a fo...
<p>I am not sure if it is what you want. If you just want to check which values in df1 also exist in df2, you can transform two dataframes into arrays and use <code>np.in1d()</code> to do so.</p> <p>Try this:</p> <pre><code>array1 = np.array((','.join(df1['col1'].apply(lambda x: ','.join(x)))).split(',')) array2 = np.a...
python|pandas|dataframe
0
365,411
32,059,397
pandas groupby without turning grouped by column into index
<p>The default behavior of pandas groupby is to turn the group by columns into index and remove them from the list of columns of the dataframe. For instance, say I have a dataFrame with these columns </p> <pre><code>col1|col2|col3|col4 </code></pre> <p>if I apply a groupby say with columns <code>col2</code> and <code...
<pre><code>df.groupby(['col2','col3'], as_index=False).sum() </code></pre>
python|pandas|dataframe
155
365,412
32,017,268
How to extract nominal labels for d3 chart
<p>I'm struggling to get used to accessing and manipulating data objects in d3.</p> <p>Essentially, I'm trying to create bar chart reflect the average price of a property based on whether its address is in a <code>Way</code>, <code>Close</code>, <code>Street</code>, <code>Avenue</code>.</p> <p>I've munged the data usin...
<p>The way I did it was to create a set of every value of the street_extent column based on the original, un-nested data, like this:</p> <pre><code>var street_extent = d3.set(); data.forEach(function(d) { street_extent.add(d['street_split']); }); </code></pre> <p>Then created a v...
javascript|json|d3.js|pandas
0
365,413
31,863,250
Ravel() 3D array in a peculiar order - Python
<p>Let's say I have the following array:</p> <pre><code>array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) </code></pre> <p>and I use the standard <code>ravel()</cod...
<pre><code>&gt;&gt;&gt; a.transpose(1, 2, 0).ravel() array([ 0, 9, 18, 1, 10, 19, 2, 11, 20, 3, 12, 21, 4, 13, 22, 5, 14, 23, 6, 15, 24, 7, 16, 25, 8, 17, 26]) </code></pre>
python|numpy|multidimensional-array|flatten
4
365,414
31,978,879
2D Color coded scatter plot with user defined color range and static colormap
<p>I have 3 vectors - <code>x</code>,<code>y</code>,<code>vel</code> each having some 8k values. I also have quite a few files containing these 3 vectors. All the files have different x,y,vel. I want to get multiple scatter plots with the following conditions:</p> <ol> <li>Color coded according to the 3rd variable i.e...
<p>You will have to iterate over all your data files to get the maximum value for <code>vel</code>, I have added a few lines of code (that need to be adjusted to fit your case) that will do that. </p> <p>Therefore, your <code>colorbar</code> line has been changed to use the <code>max_vel</code>, allowing you to get ri...
python|numpy|matplotlib|scatter-plot
1
365,415
32,042,116
Can't access pure index data in option dataframe in pandas
<p>I'm doing calculating work from yahoo option web page with the following code:</p> <pre><code>from pandas.io.data import Options aapl = Options('aapl', 'yahoo') data = aapl.get_all_data() middle = data.query('Expiry == "2015-08-28" &amp; Type == "call"') strike = middle.ix[:, 0] </code></pre> <p>I find I can't a...
<p>The quickest way to "Explode" a nested index is to call <code>reset_index</code>:</p> <pre><code>data = data.reset_index() data.head() Strike Expiry Type Symbol Last Bid Ask Chg PctChg Vol Open_Int IV Root IsNonstandard Underlying Underlying_Price Quote_Time 0 34....
python|pandas|indexing
2
365,416
31,723,126
Force datetime with hour and minutes to null pandas
<p>I want to cut the hours / minutes on the following data to keep only the 'YYYY-MM-DD 00:00:00'.</p> <p>Is it a shortest way than this one (I want to get a datetime[ns]) as result and why np.array() force a timezone... ?</p> <pre><code>In[229]: index = pd.date_range('2015-01-01', freq = 'H', periods=10) In[230]: df...
<p>Just access the <code>.date</code> attribute:</p> <pre><code>In [88]: index = pd.date_range('2015-01-01', freq = 'H', periods=10).date df = pd.DataFrame(index = range(len(index)), data=index) df Out[88]: 0 0 2015-01-01 1 2015-01-01 2 2015-01-01 3 2015-01-01 4 2015-01-01 5 2015-01-01 6 2015-01-01...
python|datetime|pandas
1
365,417
32,118,749
Python 2.7: When importing into dataframe, I get IO error 'file does not exist', even when I provide absolute path
<p>I'm using Anaconda to run Pandas, and I'm attempting to import a CSV into a dataframe.</p> <blockquote> <p>import pandas as pd</p> <p>df = pd.read_csv(r'C:/users/aliceell/desktop/oregon_2013_var_list')</p> </blockquote> <p>Even though I have directly copy-pasted the path directly from the file, it still keeps saying...
<p>You're missing the file extension from the end of your file path. From the screenshot you provided, it looks like the file extension is <code>.csv</code>. Give this a shot:</p> <pre><code>import pandas as pd df = pd.read_csv(r'C:/users/aliceell/oregon_2013_var_list.csv') </code></pre> <p>Also, from your screensho...
python|python-2.7|pandas|io|anaconda
1
365,418
32,127,536
Inplace transpose of 3D array in PyCuda
<p>I have a 3D array and would like to transpose its first two dimensions (x &amp; y), but not the 3rd (z). On a 3D array A I want the same result as numpy's <code>A.transpose((1,0,2))</code>. Specifically, I want to get the "transposed" global <code>threadIdx</code>. The code below is supposed to write the transposed ...
<p>Creating the numpy array with strides that are consistent with the CUDA kernel code solves the problem. Default layout of a numpy array is not row, column, depth as my kernel assumes. However, the strides can be set when creating the array.<br> The above kernel works fine if the array is created like this:</p> <pre...
python|numpy|multidimensional-array|cuda|pycuda
2
365,419
31,687,572
Get the (x,y) coordinate values from an image array's RGB value using numpy
<p>I am new to python so I really need help with this one.</p> <p>I have an image greyscaled and thresholded so that the only colors present are black and white.</p> <p>I'm not sure how to go about writing an algorithm that will give me a list of coordinates (x,y) on the image array that correspond to the white pixel...
<p>Surely you must already have the image data in the form of a list of intensity values? If you're using Anaconda, you can use the <code>PIL Image</code> module and call <code>getdata()</code> to obtain this intensity information. Some people advise to use NumPy methods, or others, instead, which may improve performan...
python|arrays|numpy|rgb
3
365,420
32,106,431
Python: Convert Column of letters into number
<p>I read in a csv file into a pandas dataframe and have something like this:</p> <pre><code> A B C D ...Z 1 5 P 8 H ...1 2 5 K 8 K ...2 3 6 K 8 K ...5 </code></pre> <p>How do I convert Column B and Column D (and any other columns in dataframe) into a number? It could be A =1, B =2, etc OR I tried ord() function but...
<ol> <li><p>You can use this for column A for example:</p> <p><code>dataframe.A = [ ord(x) for x in dataframe.A ]</code></p></li> <li><p>If you want A to be 1, B to be 2 etc...</p> <p><code>dataframe.A = [ ord(x) - 64 for x in dataframe.A ]</code></p></li> </ol>
python|pandas|dataframe
6
365,421
41,232,021
Using if/else in pandas series to create new series based on conditions
<p>I have a pandas df. Say I have a column "activity" which can be "fun" or "work" and I want to convert it to an integer. What I do is:</p> <pre><code>df["activity_id"] = 1*(df["activity"]=="fun") + 2*(df["activity"]=="work") </code></pre> <p>This works, since I do not know how to put an if/else in there (and if yo...
<p>You can create a dictionary with id as the key and the string as the value and then use the <code>map</code> series method to convert the integer to a string.</p> <pre><code>my_map = {1:'fun', 2:'work'} df['activity']= df.activity_id.map(my_map) </code></pre>
python|pandas|series
6
365,422
41,559,814
Build conditional graph with first axis shape is "None" in tensorflow
<p>When at the graph building phase, suppose the tensor <code>x</code> which is a <strong>neural network's fully connected layer</strong>. </p> <p>So assume the shape of <code>x</code> is <code>(?, 5)</code>. I want to set the last column like this in python:</p> <pre><code>for i in range(x.shape[0]): if x[i,-1] ...
<p>Like this?</p> <pre><code>import tensorflow as tf import numpy as np a = tf.placeholder(tf.int32, shape=[None, 5]) r, c = a.get_shape() x_split = tf.split(1, c, a) # split a along axis 1 last_col = x_split[-1] mask = tf.greater(last_col, tf.constant(6)) cond = tf.where(mask, tf.add(last_col, tf....
python|tensorflow|neural-network
2
365,423
41,409,248
softmax and sigmoid function for the output layer
<p>In the deep learning implementations related to object detection and semantic segmentation, I have seen the output layers using either sigmoid or softmax. I am not very clear when to use which? It seems to me both of them can support these tasks. Are there any guidelines for this choice?</p>
<p><code>softmax()</code> helps when you want a probability distribution, which sums up to 1. <code>sigmoid</code> is used when you want the output to be ranging from 0 to 1, but need not sum to 1.</p> <p>In your case, you wish to classify and choose between two alternatives. I would recommend using <code>softmax()</c...
tensorflow|computer-vision|deep-learning|theano|keras
20
365,424
41,311,990
Python Pandas: differences between two dates in weeks?
<p>When trying to find differences between two dates in weeks:</p> <pre><code>import pandas as pd def diff(start, end): x = millis(end) - millis(start) return x / (1000 * 60 * 60 * 24 * 7 * 1000) def millis(s): return pd.to_datetime(s).to_datetime64() diff("2013-06-10","2013-06-16") </code></pre> <p>As...
<p>I think you can convert to <code>int</code> by dividing by numpy scalar:</p> <pre><code>def diff(start, end): x = pd.to_datetime(end) - pd.to_datetime(start) return int(x / np.timedelta64(1, 'W')) print (diff("2013-06-10","2013-06-16")) 0 print (diff("2013-06-10","2013-06-26")) 2 </code></pre> <p>See <a h...
python|pandas
14
365,425
41,521,661
How to reshape an array in NumPy?
<p>I have a numpy array: <code>array([[59], [72], [117], ..., [15530], [13091], [983]], dtype=object)</code>, witch shape is <code>(39104L,)</code>. How to reshape it into array, like <code>array([59, 72, 117, ..., 15530, 13091, 983], dtype=float32</code>?</p>
<p>I suspect your original array is a 1d array of lists:</p> <pre><code>array([[59], [72], [117], ..., [15530], [13091], [983]], dtype=object) # shape (39104L,) </code></pre> <p>Normally something like that would be a 2d array in integers</p> <pre><code>In [796]: x=np.array([[59], [72], [117], [15530], [13091], [983...
python|arrays|numpy
1
365,426
41,244,681
fill in dataframe with two for loops and if condition in python
<p>I have two DataFrames, one looks something like this:</p> <p>df1:</p> <pre><code>x y Counts a b 1 a c 3 b c 2 c d 1 </code></pre> <p>The other one has both as index and as columns the list of unique values in the first two columns:</p> <p>df2</p> <pre><code> a b c d a b c d </...
<p>You can do something like this: </p> <pre><code>import pandas as pd #df = pd.read_clipboard() #df2 = df.copy() df3=df2.pivot(index='x',columns='y',values='Counts') print df3 print new=sorted((set(df3.columns.tolist()+df3.index.tolist()))) df3 = df3.reindex(new,columns=new).fillna(0).applymap(int) print df3 </code>...
python|pandas|dataframe
5
365,427
41,316,204
Reshape numpy array from 3D to 2D
<p>I have a an array that is of shape (5,2,1)</p> <pre><code>array([[[-0.00047776], [-0.00065181]], [[-0.00065181], [ 0.00130446]], [[ 0.00130446], [ 0.00151989]], [[ 0.00151989], [ 0.00121407]], [[ 0.00121407], [-0.00121259]]], dtype=float32) </code></pre> <p>I want to convert it ...
<p>Every NumPy array has a natural 1D order to its items. This is the order that you see when you <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html#numpy.ravel" rel="nofollow noreferrer"><code>ravel</code></a> the array. Reshaping (with the default order='C') does not change the order of th...
python|arrays|numpy
3
365,428
41,339,388
Flatten pandas object to column
<p>I am trying to flatten a list from a DataFrame. My existing DataFrame looks like this:</p> <pre class="lang-none prettyprint-override"><code>CreationDate 2013-12-22 15:25:02 &lt;ubuntu&gt;&lt;mac-osx&gt;&lt;syslinux&gt; 2009-12-14 14:29:32 &lt;ubuntu&gt;&lt;mod-rewrite&gt;&lt;laconica&gt;&lt;a...
<p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extractall.html" rel="nofollow noreferrer">.str.extractall()</a> method in this case:</p> <pre><code>In [57]: df Out[57]: CreationDate Tags 0 2013-12-22 15:25:02 ...
python|pandas|dataframe
2
365,429
41,297,019
Join multiple csv files from a folder into a single csv python
<p>i have around 100 csv files in a folder.</p> <pre><code>/path/to/directory/*.csv it has files abc.csv,dsf.csv,rgfb.csv.....etc </code></pre> <p>a view of csv file.</p> <pre><code>182 a 1 4 242 52450 182 a 1 2 242 7176 182 c 1 1 242 7176 182 c 1 1 242 7410 </code></pre> <p>i want to take ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with parameter <code>axis=1</code> if need append vertically:</p> <pre><code>combined_csv = pd.concat([ pd.read_csv(f, header=None) for f in csv_list ], axis=1) </cod...
python|csv|pandas
3
365,430
41,327,077
How to make item based collaborative filtering run faster?
<p>I am trying to find similarity between each pair of items. Items are in a python dictionary and I find the similarity taking pair at a time. The code is - </p> <pre><code>def allSimilarity(itemsDict, similarityMetric): itemList = itemsDict.keys() itemSimilarityDict = {} for item1 in itemList: it...
<p>I don't think a machine learning library would be particularly helpful here if there is no operations or building blocks readily available for this type of all to all similarity comparison. </p> <p>I think you'd have better luck by looking at more generic parallelization solutions: OpenMP, TBB, MapReduce, AVX, CUDA...
python|tensorflow|theano|collaborative-filtering
1
365,431
41,488,641
numpy: Compressing block matrix
<p>Consider a matrix <code>M1</code> giving values for all combinations <code>x,y</code>. Consider a partition <code>f(x)-&gt;X</code> and a partition <code>g(y)-&gt;Y</code>. Furthermore consider an operation <code>p(A)</code> on a set <code>A</code> of numbers, i.e. <code>max(A)</code> or <code>sum(A)</code>.</p> <p...
<p>The most straightforward way I can think of to do this, although perhaps not the most efficient (especially if your matrix is huge), is to convert your matrix to a one-dimensional array, and then have corresponding arrays for the partition group indices <code>X</code> and <code>Y</code>. You can then group by the pa...
python|numpy|matrix|scipy|block
4
365,432
41,583,040
Assigning values based on a small mask placed over a pixel
<h1>The problem</h1> <p>I have a circular boolean mask of <em>arbitrary radius</em> (always perfectly symmetrical):</p> <pre><code>array([[False, False, True, False, False], [False, True, True, True, False], [ True, True, True, True, True], [False, True, True, True, False], [False...
<p>A mask can be created directly in terms of the indices of the image, eliminating the bound checking: </p> <pre><code>x = np.arange(image.shape[0]) y = np.arange(image.shape[1]) image[np.add.outer((x-point[0])**2, (y-point[1])**2) &lt;= radius**2] = 1 </code></pre> <p>Here x, y are indices of the <code>image</code...
numpy
3
365,433
41,317,928
Installing TensorFlow with Pip Python on Windows
<p>Last month they released tensor-flow comparability with windows. Looking at the docs I've installed python 3.6 and run</p> <pre><code>pip install tensorflow-gpu </code></pre> <p>but it doesn't find it and therefore doesn't install it.</p> <pre><code>could not find a version that satisfies the requirements tensor...
<p>A stable release of Python 3.6 for Windows became available on 12/23/2016, and we have not yet built TensorFlow packages for that version. (We will look into doing this after the holidays.) For now, your best options are:</p> <ol> <li>Downgrade to Python 3.5 (64-bit version), which the pre-built packages support.</...
python|tensorflow
11
365,434
41,605,892
Mayavi has stopped working, crashes Python Jupyter notebook
<p>I had installed Mayavi package in Anaconda Python on my Windows 7 machine. It was working until today. Today, it has stopped working, and crashes my Python Jupyter notebook. For example, the following simple script causes "Python has stopped working" message and Python kernel death:</p> <pre><code>import numpy as n...
<p>Apparently the issue is that Mayavi display does not work over a remote desktop connection, which is what I was working through yesterday! I have not clue why, and am curious to know if someone has an answer. I'm logged into the machine directly today, and it works.</p>
python|numpy|anaconda|vtk|mayavi
3
365,435
41,584,225
How to convert JSON to a Dataframe in python
<p>I have the below JSON format, I need to convert this to a dataframe in python. Please let me know, how to go about it.</p> <p>JSON :</p> <pre><code> User Patterns [{"Jane": [{"Thermostat": 20, "Days": [1, 2], "Hour": 6, "Minute": 43}], "John": [{"Thermostat": 18, "Days": [1, 2], "Hour": 0, "Minute": 15}], "Jen"...
<pre><code>jstr = """[{"Jane": [{"Thermostat": 20, "Days": [1, 2], "Hour": 6, "Minute": 43}], "John": [{"Thermostat": 18, "Days": [1, 2], "Hour": 0, "Minute": 15}], "Jen": [{"Thermostat": 22, "Days": [1, 2], "Hour": 10, "Minute": 1}]}]""" pd.DataFrame.from_dict( {k: v[0] for k, v in json.loads(jstr)[0].items()}...
python|json|python-2.7|pandas|dataframe
4
365,436
41,375,297
split, map data in two columns in pandas data frame
<p>I want to split data in two columns from a data frame and construct new columns using this data.</p> <p>My data frame is,</p> <pre><code>dfc = pd.DataFrame( {&quot;A&quot;: [&quot;GT:DP:RO:QR:AO:QA:GL&quot;, &quot;GT:DP:RO:QR:AO:QA:GL&quot;, &quot;GT:DP:RO:QR:AO:QA:GL&quot;, &quot;GT:DP:GL&quot;, &quot;GT:DP:GL&quot...
<p>Use an <code>OrderedDict</code> to preserve the order after creating a <code>dict</code> mapping of the two concerned columns of the dataframe split on the sep "<code>:</code>", flattened to a <code>list</code>. </p> <p>Feed this to the dataframe constructor later.</p> <pre><code>from collections import OrderedDic...
python|pandas|dictionary|split
3
365,437
41,428,194
Pyplot is showing different colors for the same value?
<p>Given that, I have two, almost identical, arrays and then I plot them as gray images but the output shows the <strong>value 12 as gray from one array</strong> and <strong>white from the other</strong>, what am I missing?</p> <pre><code># coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt ...
<p>As said <a href="https://stackoverflow.com/users/681870/j-p-petersen">J. P. Petersen</a> the problem is that the colormap automatically chooses the color scale.</p> <p>You can fix it with <code>vmin</code> and <code>vmax</code>:</p> <pre><code>plt.imshow(ori, interpolation='nearest',cmap=plt.cm.binary, vmin=11, vm...
python|arrays|numpy|matplotlib|signal-processing
3
365,438
41,309,584
Extracting one row from a numpy matrix
<p>I currently testing a NN implementation, in which the train data is stored in numpy matrix. </p> <pre><code>print train_set_data_vstacked_normalized.shape (219970,400) </code></pre> <p>The input data currently looks like this, i have to feed each row to my neural network .. </p> <p>It takes in input of shape (no...
<p>You need a simple <code>for</code> loop to go through all the rows of the array.</p> <pre><code>nrows = train_set_data_vstacked_normalized.shape for i in range(nrows[0]): row = train_set_data_vstacked_normalized[i, :] # now change shape to (1, 400) resized_row = row[np.newaxis] # now, "resized_row"...
python|numpy|matrix|neural-network|numpy-ndarray
0
365,439
27,873,190
Creating new pandas DataFrame from existing DataFrame and index
<p>I have a DataFrame like this:</p> <pre><code> a b A 1 0 B 0 1 </code></pre> <p>and I have an array ["A","B","C"].</p> <p>From these, I want to create a new DataFrame like this:</p> <pre><code> a b A 1 0 B 0 1 C NaN NaN </code></pre> <p>How can I do this?</p>
<p>Assuming I understand what you're after (setting aside weird duplicated-index cases), one way is to use <code>loc</code> to index into your frame:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a': {'A': 1, 'B': 0}, 'b': {'A': 0, 'B': 1}}) &gt;&gt;&gt; arr = ["A", "B", "C"] &gt;&gt;&gt; df a b A 1 0 B 0 1 ...
python|numpy|pandas
4
365,440
27,903,980
Getting the minimum from elements of a Numpy array and a float
<p>Problem: I want to compare each element of a Numpy array with a float, returning an array with the smaller value. For example, using the inputs:</p> <pre><code>import numpy as np input_a = 3 input_b = np.array([1,2,3,4,5]) </code></pre> <p>the output should be</p> <pre><code>output = np.array([1,2,3,3,3]) </code>...
<p>Your best bet is to use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">logical indexing.</a></p> <pre><code>import numpy as np input_a = 3 input_b = np.array([1,2,3,4,5]) input_b[input_b &gt; input_a] = input_a print(input_b) # [1 2 3 3 3] </code></pre> <p><code>input_b &...
python|arrays|numpy|min
3
365,441
27,534,746
Importing financial data into Python Pandas using read_csv
<p>I have a .csv with the following structure:</p> <pre><code>date_begin,date_end,name,name_code,active_accounts,transaction_amount,transaction_count 1/1/2008,1/31/2008,Name_1,1001,"123,456","$7,890,123.45","67,890" 2/1/2008,2/29/2008,Name_1,1001,"43,210","$987,654.32","109,876" 3/1/2008,3/31/2008,Name_1,1001,"485,079...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#text-string-methods" rel="noreferrer">vectorized string methods</a> to parse those columns after the call to <code>read_csv</code>:</p> <pre><code>import pandas as pd import decimal D = decimal.Decimal data = pd.read_csv('data', parse_dat...
python|csv|pandas|import
14
365,442
27,821,256
how to make use of Python scalars correctly?
<pre><code>&gt;&gt;&gt; numpy.sin(range(11)) array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.4121184 -0.54402111]) &gt;&gt;&gt; numpy.array(range(11))*2 array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]) &gt;&gt;&gt; str(numpy.array(ra...
<p>I think this is what you want:</p> <pre><code>&gt;&gt;&gt; a = numpy.arange(10) &gt;&gt;&gt; a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) &gt;&gt;&gt; a.astype(str) array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], dtype='|S21') </code></pre>
python|numpy|scalar
5
365,443
27,608,884
Finding the roots of two lines using brentq
<p>I am trying to write a function which returns the x value of some data when the y value is approximately zero. I am given two lists to enter in to the function as [1,4,5] for x values and [-3,5,9] for y values for example. I have written this function by using interpolation and then using indexing to first find inde...
<p>Although you can use brentq on the interpolated function, since you are already using interpolation, just use it to invert the function:</p> <pre><code>finv = inter.interp1d(y, x) print (finv(0)) </code></pre>
python|numpy|scipy
0
365,444
27,455,979
Concatenate two datetimes into a string date range
<p>I have a pandas dataframe.</p> <pre><code>Data = pd.DataFrame([[datetime.datetime(2014,1,1),datetime.datetime(2014,1,3)]],columns=['date1','date2') </code></pre> <p>That dataframe has two datetime columns date1 and date2.</p> <p>I want to create a new column that contains a string in the format below:</p> <pre><...
<blockquote> <blockquote> <p>Finding it hard to strip just the date out since I am working with two columns rather than two values</p> </blockquote> </blockquote> <p>Well, since you're already using <code>apply</code>, you're dealing with two values (not columns), so you can call the <code>date</code> method o...
python|string|datetime|pandas|concat
1
365,445
27,708,977
Python - Grayscale very low with a mask
<p>I'm working on pictures that have been converted to grayscale with:</p> <pre><code>Image.open('image.png').convert('LA') </code></pre> <p>I add a mask and I plot my picture with it, but while I expect to get grayscale values between 0 and 255, the values are very low as you can see below. There must be something w...
<p>By using OpenCV it works...</p> <p>img = cv2.imread('test.png',0)</p>
python|numpy|grayscale
0
365,446
61,357,345
How to change dataframe column names without changing the values?
<p>I have a bunch of CSV files which are read as dataframes. For each dataframe, I want to change some column names, if a specific column exists in a dataframe:</p> <p>column_name_update_map = {'aa': 'xx'; 'bb': 'yy'}</p> <p>In such a map, if 'aa' or 'bb' exists in a dataframe, I want to change the aa to xx, and 'bb'...
<p>To rename specific columns then follow this code. </p> <blockquote> <p>Code:</p> </blockquote> <pre><code>import pandas as pd import numpy as np #creating sample dataframe df=pd.DataFrame({'aa':[1, 2], 'bb':[3, 4], 'c':[5, 6], '':[7, 8]}) #replace columns 'aa' to 'xx', 'bb' to 'yy' and '' to 'NaN' df.rename(...
python|pandas
2
365,447
61,543,640
Merging two tables in Pandas, and adding in multiple Indices too
<p>I have data that's to be analysed for a project I'm working in, mostly done using pandas at the moment as the data comes in from Excel.</p> <p>I'm trying to merge some of these tables, based on a column, which isn't the issue, the issue is that the tables have column names that are the same, looking kind of like b...
<p>I hope I understood your issue</p> <p>Using the Merge function you can set suffix for each of the columns from each of the dataframes. E.g.:</p> <pre><code>df1.merge(df2, left_on='lkey', right_on='rkey',suffixes=('_left', '_right')) </code></pre> <p>This way you will differentiate between columns coming from each...
python|python-3.x|pandas|numpy
0
365,448
61,421,459
How to rest a row value to the nths rows values of another dataframe
<p>I have this two df's </p> <pre><code> df1: lon lat 0 -60.7 -2.8333333333333335 1 -55.983333333333334 -2.4833333333333334 2 -51.06666666666667 -0.05 3 -66.96666666666667 -0.11666666666666667 4 -48.483333333333334 -1.3833333333333333 5 -54.71666666666667 -2.4333333333...
<p>You can create list of <code>Series</code>:</p> <pre><code>L = [df1.loc[i,'lat']-df2['lat'] for i in df1.index] </code></pre> <p>Or you can use numpy for new <code>DataFrame</code>:</p> <pre><code>arr = df1['lat'].to_numpy() - df2['lat'].to_numpy()[:, None] df3 = pd.DataFrame(arr, index=df2.index, columns=df1.ind...
python|pandas|exec
1
365,449
61,599,239
Using Pandas Dataframe to perform comparison
<p>I have a .csv file that has a bunch of words with ratings between 0 and 10. I import it using pd.read_cvs, which apparently works (see screen capture). Then I want to import a txt file into python and then look to see if there are common words between this txt file and the words in the .csv file. If so I want the r...
<p>you have an error in the code:</p> <pre><code>for ind_row, content_row in dataset.iterrows(): </code></pre> <p><code>ind_row</code> will give you the index and <code>content_row</code> will give you the row. If you like to compare the content of the text file row by row, you can iterate trough the text file and us...
python|pandas|csv
0
365,450
61,327,527
How can I change the values in my multi index?
<p>I have a multi index dataframe. I'm trying to change some of the inner values in the index. </p> <p>My dataframe looks like this:</p> <pre><code> 2019 2020 1 2 1 2 L0 L1 L2 Blue Red X 100 150 200 250 Blue Yellow Y 100 150 200 250 Blue Green Z 100 ...
<p>Instead of using <code>set_levels()</code> or <code>set_labels</code> methods, try to use <code>rename()</code>.</p> <p>Check for the oficial documentation <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.rename.html" rel="nofollow noreferrer">here</a></p>
python|pandas
0
365,451
61,428,823
Comparing 2 values of same variable in single dataframe
<p>I have a data frame as follow:</p> <pre><code>Obs. ID Name type 1) 123 abc duplicate 2) 123 abc duplicate 3) 145 abc abc 4) 156 abc duplicate 5) 156 abc duplicate </code></pre> <p>if ID is same, like in obs. 1 and 2 or 4 and 5 then I want to create a new variable type=duplicate else type=vaul...
<p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>duplicated</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> to set the va...
python|pandas|dataframe|string-comparison
1
365,452
61,350,735
Unnest DataFrame List
<p>I have a pandas dataframe with a column containing data nested in the following way:</p> <p>1st Row: <code>[('QT', 0, 2, 'PERSON'), ('Billionaire Jack Ma', 102, 121, 'PERSON'), ('$14 million', 131, 142, 'MONEY'), ('U.S.', 204, 208, 'GPE'), ('33', 226, 228, 'MONEY')]</code></p> <p>2nd Row: <code>[('My PhD Mol', 6...
<p>I don't know about the performance, but if I understood well your problem this would work:</p> <pre><code>result_df = pd.DataFrame(data={'org_id': [idx_val for idx_val in org_df.index for i in range(len(org_df.loc[idx_val, 'target_col']))], 'col_1': [single_tuple[1] for row_value in org_df['ta...
python|pandas|spacy
0
365,453
61,330,427
set y-axis in millions
<p>I have a problem with this plot: </p> <p>[![enter image description here][1]][1]</p> <p>The y-axis is in unit but I need them to be in millions as such:</p> <p>[![enter image description here][2]][2]</p> <p>Do you know a method to achieve this? Thanks in advance.</p>
<p>You can use a custom FuncFormatter like this:</p> <pre class="lang-py prettyprint-override"><code>from matplotlib.ticker import FuncFormatter import matplotlib.pyplot as plt def millions(x, pos): 'The two args are the value and tick position' return '%1.1fM' % (x * 1e-6) formatter = FuncFormatter(millions)...
python|pandas|matplotlib|axis
15
365,454
61,408,276
Could not dlopen library 'libcudnn.so.7'; dlerror: libcudnn.so.7: LD_LIBRARY_PATH: /usr/local/cuda-10.0/lib64:
<pre><code> Could not dlopen library 'libcudnn.so.7'; dlerror: libcudnn.so.7: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/local/cuda-10.0/lib64: </code></pre> <p>I can find libcudnn.so.7 in /usr/local/cuda-10.0/lib64/.Also, I have added the following path in my .bashrc file:</p> <...
<p>A common reason for this error is incompatibility between the TensorFlow version and the CUDA version. Try looking up which CUDA version to use with your TF version (or vice-versa). Alternatively, try going one version up and down in both to see if they match.</p>
python|tensorflow
1
365,455
61,431,500
XLNetForSequenceClassification Pretrained model unable to load
<p>I tried loading the XLNet pretrained but this occurred. I've tried this before and it worked, however, now it doesn't. Any suggestion on how to fix this problem?</p> <pre><code>model = XLNetForSequenceClassification.from_pretrained("xlnet-large-cased", num_labels = 2) model.to(device) </code></pre> <pre><code>----...
<p>You should import <a href="https://huggingface.co/transformers/model_doc/xlnet.html" rel="nofollow noreferrer">XLNetForSequenceClassification</a> from <a href="https://github.com/huggingface/transformers" rel="nofollow noreferrer">transformers</a> and not from pytorch-transformers. First, make sure transformers is i...
nlp|pytorch|pre-trained-model
1
365,456
61,400,122
how to multiply each row of a tensor to the rest of rows element wise in tensorflow
<p>I have a tensor like this:</p> <pre><code>tf_docs = tf.constant([[0, 2, 1], [1, 2, 2], [2, 1, 3], [5, 2, 2]], dtype=tf.int32) </code></pre> <p>I need to multiply each row by rest of the rows, element wise and then sum up result. </p> <p>When don...
<p>Here is a way to do that:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf tf_docs = tf.constant([[0, 2, 1], [1, 2, 2], [2, 1, 3], [5, 2, 2]], dtype=tf.int32) # Non-diagonal elements nondiag = tf.matmul(tf_docs, tf_doc...
python|tensorflow
1
365,457
61,298,880
Pandas: create dataframe with column headers and cell values from tuples in a dictionary
<p>I have a simple pandas dataframe, with two columns:</p> <pre><code>document document_topics 0 [(0, 0.0280), (1, 0.0372), (2, 0.0131), ... (42, 0.0969)] 1 ... [(1, 0.0829), (3, 0.0161), (4, 0.0141), ... (27, 0.2275)] </code></pre> <p>The column 'document_topics' is a tuple of (topic, weight). I would ...
<p>You can <code>explode</code> the lists, then grab the first and second element of the tuples and <code>pivot</code>.</p> <pre><code>df = df.explode('document_topics') df = (df.assign(topic=df.document_topics.str[0], vals=df.document_topics.str[1]) .pivot(index='document', columns='topic',...
python|pandas|dataframe|dictionary|tuples
3
365,458
61,315,653
How do I output this Python, jyputer, deepplavlov code correctly on a notebook cell?
<p>I have a functional setup with Tensorflow and Jupyter. I have configured Tensorflow==1.14 to run on gpu.</p> <p>Now to the questions: I'm using an open source conversational AI framework called DeepPavlov. Its all up and running (in the configuration side) but I don't have much experience with calling python from a...
<p>DeepPavlov comes with a bunch of predefined components powered by TensorFlow and Keras for solving NLP-related problems. </p> <p><strong>The one you are using is the BERT for Question Answering.</strong> Context question answering is the task of finding an answer to a question over a given context (e.g, a paragraph...
python|python-3.x|tensorflow|jupyter-notebook|cell
1
365,459
61,253,195
python pandas apply how to replace function with lambda function?
<p>I have a dataframe and the function that I would like to apply:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; df = pd.DataFrame({ ... 'A' : ['A1', 'A2', 'A3'], ... 'B' : ['B1', 'B2', 'B3'], ... 'format_str' : [None, np.nan, 'A = {A}, B = {B}'] ....
<p>This seems to be doing the job :</p> <pre class="lang-py prettyprint-override"><code>df['new_field'] = df.apply( lambda ser: ser.A if pd.isna(ser.format_str) else ser.format_str.format(**ser), axis=1 ) </code></pre>
python-3.x|pandas|lambda|apply
1
365,460
61,294,990
Check an unknown type of argument
<p>I'm passing an argument(lets say the variable 'a') to a function, and this variable can either equal None or be a np.array.</p> <pre class="lang-py prettyprint-override"><code># Option 1 a = None # Option 2 a = np.array(range(0,10)) </code></pre> <p>Depending on what a equals, I want to do different things.</p> ...
<p>Use <code>is</code> instead of <code>==</code>:</p> <pre><code>if a is None: do this else: do that </code></pre>
python|python-3.x|if-statement|numpy-ndarray|nonetype
1
365,461
61,225,212
Take n last rows of a dataframe with no NaN
<p>Let's take this dataframe :</p> <pre><code>df = pd.DataFrame(dict(Col1 = [1,2,np.nan,4,5,6], Col2=[4,np.nan,5,np.nan,1,5])) Col1 Col2 0 1.0 4.0 1 2.0 NaN 2 NaN 5.0 3 4.0 NaN 4 5.0 1.0 5 6.0 5.0 </code></pre> <p>I would like to extract the n last rows of df with no NaN.<br> Could you pl...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>DataFrame.dropna</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.tail.html" rel="nofollow noreferrer"><code>DataFrame.tail</code></a...
python|pandas|numpy|dataframe
3
365,462
61,506,854
Pandas - chunk read_csv with overlap between chunks
<p><strong>Problem statement</strong></p> <p>How to chunk read a csv file using pandas which has an overlap between chunks?</p> <p>For an example, imagine the list <code>indexes</code> represents the index of some dataframe I wish to read in.</p> <pre><code>indexes = [0,1,2,3,4,5,6,7,8,9] </code></pre> <p>read_csv(...
<p>I think you should pass a number to <code>skiprow</code> instead of the list, try:</p> <pre><code>for i in list(range(0, row_count-overlap_count, chunksize - overlap_count)): print (pd.read_csv('test.csv', skiprows=i+1, #here it is +1 because the first row was header ...
python|pandas|csv
0
365,463
61,503,956
Concatenate sequence of frames from a NumPy array horizontally
<p>I have a NumPy array with size: <code>img_array.shape = (20, 10, 56, 56, 3)</code> which corresponds to 20 different sequences of 10 frames with size <code>(56, 56, 3)</code>. What to combine all 10 frames of each of these sequences into one bigger image. Therefore to output a new NumPy array with size <code>(20, 56...
<p>Use <code>np.stack</code>, which can stack along your favorite dimension: <a href="https://www.geeksforgeeks.org/numpy-stack-in-python/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/numpy-stack-in-python/</a></p>
python|arrays|numpy
1
365,464
61,600,563
Problems rotating xtick labels when using twinx
<p>I have problems with the rotation of my X-axis, I have tried to do the rotation the output plot without errors, but I do not have the results.</p> <pre><code># Import Data #df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv") x = total_test["Dia"].values[:]; y1 = total_test["Confirmados"...
<ul> <li>Any commands for the xaxis need to occur before <code>ax2</code>.</li> <li>Verify date is in a <code>datetime</code> format and set as the index.</li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt # read data df = pd.read_csv(&quot;https://github.com...
python|pandas|matplotlib|rotation|axis-labels
7
365,465
61,530,776
remove multiple and double brackets with dataframe pandas
<p>I have a dataframe and I need to remove the individual brackets, until I was able to remove the individual brackets. However, the location column has two square brackets and I cannot remove it.</p> <pre><code> value car location [R$ 40.590] [FIAT ARGO] [[São, Paulo, (SP)]] </code></pre> ...
<p>Try this</p> <pre><code>df.location = df.location.str[0] </code></pre>
python|pandas
0
365,466
61,602,341
Trying to sum combine a whole lot of columns faster/easier... help appreciated
<p>I'm trying to sum columns into groups of 30 (month). Each column is a day. There are almost 2,000 columns</p> <p>Each row is an individual product and there are about 30,000 of them. </p> <p>Below is what I am doing to sum them in jupyter.</p> <p>My question is that is there an easier/faster way to do this withou...
<pre><code>Month1 = df_sales.loc[:, "d_1":"d_30"].sum(axis=1) </code></pre> <p>If every month in your table has 30 days (columns) and you start with the first column, you may perform</p> <pre><code>all_months = pd.concat((df_sales.iloc[:, i:i+30].sum(axis=1) for i in range(0, df_sales.sha...
python|pandas
0
365,467
61,398,117
How to apply conditions for rows in a tensor where there is boolean values
<p>I have the following tensor:</p> <pre><code>predictions = torch.tensor([[ True, False, False], [False, False, True], [False, True, True], [ True, False, False]]) </code></pre> <p>I applied conditions along the axis like below.</...
<p>The type of <code>predictions</code> is <code>torch.Tensor</code> while <code>([True, False, False])</code> is a list, first, you have to make sure both sides have the same type. </p> <pre class="lang-py prettyprint-override"><code>predictions == torch.tensor([True,False,False]) &gt;&gt;&gt; tensor([[ True, True, T...
python|pytorch|tensor
0
365,468
61,346,081
Recreate this chart in python - what type of chart is it?
<p>I'm trying to recreate the chart from <a href="https://www.reddit.com/r/dataisbeautiful/comments/g4uyfe/sleep_pattern_of_baby_36_months_oc/" rel="nofollow noreferrer">this post</a> on Reddit. How would I recreate a chart like this in python? What would you even call this type of chart? </p> <p>The chart looks like ...
<p>This gets you part of the way...</p> <h3>Convert to proper types</h3> <pre><code>df['Date'] = pd.to_datetime(df.Date.radd('2020/'), format='%Y/%m/%d') df['Asleep'] = pd.to_datetime(df.Asleep) - pd.Timestamp('now').normalize() df['Awake'] = pd.to_datetime(df.Awake) - pd.Timestamp('now').normalize() </code></pre> <...
python|pandas|plot|data-visualization
2
365,469
61,205,628
How to merge cells in the HTML output of a pandas dataframe in Python
<p>I have a pandas dataframe which looks something like the below...</p> <p><a href="https://i.stack.imgur.com/SKgQC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SKgQC.png" alt="enter image description here"></a></p> <p>I am aware that i am unable to merge cells of the dataframe itself, but is t...
<p>This is a bit hacky (as I parse the html text) but may work for your particular case...</p> <pre><code>df = pd.DataFrame({ 'col1': ['A', 'A', 'B', 'B'], 'col2': [1, 2, 3, 4], 'col3': [5, 6, 7, 8]}) df['cleanme'] = 'cleanme' df = df.set_index(['col1', 'cleanme']) html = df.to_html(index_names=False) h...
python|html|pandas
0
365,470
61,285,622
TfidfTransformer and stop words
<p>I am importing <code>TfidfTransformer</code> from <code>sklearn</code> and trying to use <code>stop_word</code> argument, but it is showing error.</p> <pre><code>from sklearn.feature_extraction.text import TfidfTransformer tfidf = TfidfTransformer(stop_words='english') TypeError Tr...
<p>I think you intent to use <code>TfidfVectorizer</code>, which has the parameter <code>stop_words</code>. Refer the documentation <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" rel="nofollow noreferrer">here</a></p> <p>Example:</p> <pre><code>from sk...
python|machine-learning|scikit-learn|sklearn-pandas
3
365,471
61,551,393
Pandas: Creating new column based on values from existing column
<p>I have a pandas dataframe with two columns as following:</p> <pre><code>A B Yes No Yes Yes No Yes No No NA Yes NA NA </code></pre> <p>I want to create a new column based on these values such that if any of the column values are <code>Yes</code>, the value in the new column should also be...
<p>Something like </p> <pre><code>df.fillna('').max(axis=1) Out[106]: 0 Yes 1 Yes 2 Yes 3 No 4 Yes 5 dtype: object </code></pre>
python|pandas
7
365,472
61,605,998
Is there a function for finding the first member in an array which greater then a threshold
<p>I need to find the index of the first member in an array where the cumulative sum until that point is bigger then a specific threshold, the code I got is this:</p> <pre><code>def calc(source, threshold): sum=0 for counter, num in enumerate(source): sum = sum + num if sum &gt;= threshold: ret...
<h1>Solution</h1> <p>You can do this in a single line using</p> <ul> <li><code>a[a.cumsum() &gt; threshold][0]</code> for matched <strong><code>value</code></strong></li> <li><code>np.where(a.cumsum() &gt; threshold)[0][0]</code> for matched <strong><code>index</code></strong></li> </ul> <p>as follows.</p> <pre cla...
python|performance|numpy|cumsum
0
365,473
61,456,634
how can i get an 3 dimensional numpy array out of list of nesteld list
<p>I've got a list cars and want to convert it into an multidimensional array</p> <pre><code>&gt;&gt;&gt; cars = [[[2,1],[1,1]],[[0,2],[0,1],[0,0]],[[5,0],[5,1],[5,2]],[[1,5],[2,5]]] &gt;&gt;&gt; cars_np = np.array(cars) &gt;&gt;&gt; cars_np.shape (4,) &gt;&gt;&gt; cars_np array([list([[2, 1], [1, 1]]), list([[0, 2], ...
<p>numpy arrays must have well defined shape, eg <code>(2,2,2)</code> in your final example. Your list <code>cars</code> is a list of lists where the inner lists have length <code>2,3,3,2</code> which is inconsistent with a well defined shape for numpy.</p> <p>May I suggest that you add some NaN values to your <code>c...
python|arrays|list|numpy
1
365,474
61,292,078
nested loop and newaxis numpy
<p>Let's say, I have a empty list labelled Energies and I'd fill this list by looping over some others variables as below, </p> <pre class="lang-py prettyprint-override"><code>r=read('atoms_positions.txt') e=read('previous_calculations.txt') Energies=np.zeros([len(e), len(r)]) spd=3 for a in range(len(r)): for b i...
<pre><code>Energies[:,a]+=dos_site(a,spd) </code></pre> <p>This adds (then assigns) the one-d array (returned by <code>dos_site</code>) to the <em>a'th</em> column</p> <pre><code>&gt;&gt;&gt; a = np.zeros([5, 6]) &gt;&gt;&gt; a[:,0] += np.arange(5) &gt;&gt;&gt; a array([[0., 0., 0., 0., 0., 0.], [1., 0., 0., 0...
python|arrays|numpy
0
365,475
61,482,329
Pandas count monthly occurrences with across-rows condition
<p>I have a Dataframe like this</p> <pre><code> oper_status 2012-01-01 00:26:54.250 0 2012-01-01 12:11:54.250 1 2012-01-01 13:57:54.250 2 2012-01-02 00:16:54.250 0 2012-01-02 14:26:54.250 1 2012-01-02 17:20:54.250 0 2012-01-...
<p>Counting sequential patterns is a two step process. First, build a sequence for each row, representing the pattern ending at that row:</p> <pre><code>df['seq'] = df.order_status.astype(str).shift(periods=0) + '-' + df.order_status.astype(str).shift(periods=1) + '-' + df.order_status.astype...
python-3.x|pandas|dataframe|datetime|data-analysis
2
365,476
61,217,381
Automating the process of identifying subgroups of a pandas dataframe that do not significantly differ on a value
<p>I have the following dataframe, which, for the sake of this example, is full of random numbers:</p> <pre><code>import numpy as np import pandas as pd from scipy.stats import ttest_ind df = pd.DataFrame(np.random.randint(0,1000,size=(100, 4)), columns=list('ABCD')) df['Category'] = np.random.randint(1, 3, df.shape[...
<p>Here is my suggestion, by using <code>combinations</code> from <code>itertools</code> as rightfully suggested by @rpanai with <code>groupby</code> and <code>pipe</code>that enables you to get different groups within the same operation. You return a Boolean for the pvalue being above or below threshold 0.05 and you b...
python|pandas|numpy|statistics
2
365,477
61,250,081
How to find the max of the sums of the absolute values of each column in a matrix
<p>I am trying to write a function to find the maximum value of the sums of each value in each column of a matrix without using a numpy function.</p> <p>For example, given the following array, I want the answer 2.7657527806024733.</p> <pre><code>A = np.array([[0.94369777, 0.34434054, 0.80366952, 0.665736], ...
<p>Heres my solve. I loop over the columns and push each sum into an array. Then i loop over that array to find the largest value. It's very verbose but it doesn't use numpy for anything but creating the matrix.</p> <pre><code>import numpy as np matrix = np.array([[0.94369777, 0.34434054, 0.80366952, 0.665736], ...
python|numpy|sum
2
365,478
61,597,531
how to extract columns for dictionary that do not have keys
<p>so I have tried resources of how transform dict in data frame, but the problem this is an weird Dict. </p> <p>it is not like <code>key: {} , key: {} and etc..</code> </p> <p>the data has lots of items. But the goal is extract only the stuff inside of dict {}, if possible the dates also is a plus.</p> <p>data:</p...
<p>Format data into a valid csv stucture:</p> <pre><code>id,client,source,status,request,response,queued,created_at,updated_at 54252,sdf,https://asdasdadadad,,'{ "ag": "2010", "ca": "aca", "ve": "p", "Group": "57981" }',,1,"2020-05-02 11:06:17","2020-05-02 11:06:17" 54252,msc-lp,https://discover,,'{ "ag": "27", "ca": ...
python|json|pandas|dictionary
1
365,479
61,540,062
Insert dataframe cell value (list) to mysql multiple columns Python
<p>I'm working with Data-frames in Python and trying to insert data in MySQL Database. I know I can use <code>df.to_sql</code> to insert dataframe into sql but in my case, I've a list in one of the cells of dataframe and I've to insert that list into multiple columns of table in database.</p> <p>Here is my dataframe:<...
<p>You can split your list column to multiple columns and then use <code>df.to_sql</code> on the new dataframe:</p> <pre><code>In [971]: df ...
python|mysql|pandas|dataframe
2
365,480
61,229,310
Pandas Panel Data - Returns rolling cumulative sum with year gaps
<p>I am currently working with a panel data of financial information on pandas, and I am trying to generate a column of cumulative abnormal returns for 3-year on a rolling basis. Unfortunately my data is a bit spotty and therefore for the same company I might have a gap in the years. This means that I can not simply ap...
<pre><code>import more_itertools as mit s = """datadate,fyear,tic,ab_ret 31/12/1998,1998,AAPL,0.045 31/12/1999,1999,AAPL,0.012 31/12/1999,2000,AAPL,0.012 31/12/2002,2002,AAPL,-0.031 31/12/2003,2003,AAPL,-0.007 31/12/2005,2005,AAPL,0.001 31/12/2005,2007,AAPL,0.001 31/12/2005,2008,AAPL,0.001 31/12/2005,2009,AAPL,0.001 3...
python|pandas|numpy|finance|panel-data
1
365,481
61,280,171
how to perform group by and sum on dataframe . I have a Dataframe1 I want to convert into Dataframe2 like this
<p>This is a given Dataframe df1 . </p> <p><a href="https://i.stack.imgur.com/IvlEN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IvlEN.png" alt="enter image description here"></a></p> <hr> <p>I want to convert it into Dataframe like below. How to do so?? Thanks in advance</p> <h2><a href="http...
<p>You can try with this approach:</p> <pre><code>df1.groupby(['Month', 'StoreCode'], as_index=False)['Value'].sum() </code></pre> <p>It returns a new DF with three colums: <code>Month, StoreCode &amp; Sum</code> which are the only uniques ones if I understood correctly.</p> <p>Note: If there's another unique column...
python|pandas|dataframe
0
365,482
61,373,296
HTML table in pandas with single header row
<p>I have the following dataframe:</p> <pre><code> ID mutex add atomic add cas add ys_add blocking ticket queued fifo Cores 1 21.0 7.1 12.1 9.8 32.2 44.6 2 121.8 40.0 119.2 ...
<p>Initial setup:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], columns = ['attr_a', 'attr_b', 'attr_c', 'attr_c']) df.columns.name = 'ID' df.index.name = 'Cores' df ID attr_a attr_b attr_c attr_c Cores 0...
python|pandas|dataframe
3
365,483
68,552,017
creating new column values depending on other column values in a dataframe
<p>I have a data frame and a snippet of it is given below.</p> <pre><code>data = {'ID':['A', 'A', 'A,'A', 'B', 'B', 'B', 'B', 'C', 'C'], 'Date':['03/25/2021', '03/25/2021',03/27/2021', '03/29/2021', '03/10/2021','03/11/2021','03/15/2021','03/16/2021', '03/21/2021','03/25/2021']} df = pd.DataFrame(data) </code></pr...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>def fn(x): dr = pd.date_range(x[&quot;Date&quot;].min(), x[&quot;Date&quot;].max()) out = pd.DataFrame({&quot;Date&quot;: dr}, index=range(1, len(dr) + 1)) out[&quot;Missing_Date&quot;] = (~out[&quot;Date&quot;].isin(x[&quot;Date&quot;])).astype(in...
python-3.x|pandas|dataframe|series|data-processing
1
365,484
68,551,593
Is this JSON I made using jsonify with flask and python 3 formatted correctly for making a D3 graph? And if not, how should I format it?
<p>I have a few pandas dataframes that I'm sending from flask to react in my project. This is what one of the tables looks like:</p> <pre><code>Year | Word 1 | Word 2 | Word 3 ------------------------------- 1990 | 532 | 2425 | 649 1991 | 334 | 2789 | 894 1992...etc. </code></pre> <p>Basically, I have a ta...
<p>I'm interpreting here, but it looks like D3 wants a list with one object per line, like you'd get from a CSV file:</p> <pre><code>[ { &quot;Year&quot;: 1990, &quot;Word 1&quot;: 531, &quot;Word 2&quot;: 2425, &quot;Word 3&quot;: 649 }, { &quot;Year&quot;: 1991, &quot;Word 1&quot;: 334, ...
python|json|pandas|flask|d3.js
0
365,485
68,744,398
creating a dataframe from nested dictionary of list
<p>I have a nested dictionary of list which looks like:</p> <pre><code> dictionary = {'ss':{'feat1':[12,8173,9173,13], 'feat2':[73,1938,183,38]}, 'dd':{'feat1':[324,42,56,839], 'feat2':[13,398,817,9173]}} </code></pre> <p>I want to convert it to dataframe so that it...
<p>Try via <code>stack()</code>+<code>explode()</code>+<code>pivot()</code>:</p> <pre><code>df=pd.DataFrame(dictionary).stack().explode().reset_index() df['key']=df.groupby(['level_0','level_1']).cumcount() df=df.pivot(['level_1','level_0'],'key',0).reset_index() df.columns=range(len(df.columns)) </code></pre> <p>OR</p...
python-3.x|pandas|dictionary
1
365,486
68,580,717
How can I solve this issue? input must have 3 dimensions, got 4
<p>The Below is data which I passed to the Data Loader,</p> <pre><code>train_path='/content/drive/MyDrive/Dataset_manual_pytorch/train' test_path='/content/drive/MyDrive/Dataset_manual_pytorch/test' train = torchvision.datasets.ImageFolder(train_path,transform=transformations) test = torchvision.datasets.ImageFolder(t...
<p>You can do the size conversion of torch.Size([64, 3, 32, 32]) to torch.size([64, 32, 32]) by following the bottom code:</p> <pre><code>x = torch.ones((64, 3, 32, 32)) x = x[:, 0, :, :] #Check code: print(x.size()) </code></pre>
python-3.x|deep-learning|pytorch
1
365,487
68,570,458
Pandas split columns on first % sign, on 2nd letter
<p>We have the following dataframe</p> <pre><code># raw_df print(raw_df.to_dict()) {'Edge': {1: '-1.9%-2.2%', 2: '+5.8%-9.4%', 3: '+3.5%-7.2%'}, 'Grade': {1: 'D+D', 2: 'BF', 3: 'B-F'}} </code></pre> <p><a href="https://i.stack.imgur.com/mBQNXm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mBQNXm.p...
<p>We can use <code>str.extract</code> as follows:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;edge_1&quot;] = df[&quot;Edge&quot;].str.extract(r'^([+-]?\d+(?:\.\d+)?%)') df[&quot;edge_2&quot;] = df[&quot;Edge&quot;].str.extract(r'([+-]?\d+(?:\.\d+)?%)$') df[&quot;grade_1&quot;] = df[&quot;Grade&quot;]...
python|pandas
2
365,488
68,462,845
How to test if a string contains one of the substrings stored in a list column in pandas?
<p>My question is very similar to <a href="https://stackoverflow.com/q/26577516/10499953">How to test if a string contains one of the substrings in a list, in pandas?</a> except that the list of substrings to check varies by observation and is stored in a list column. Is there a way to access that list in a vectorized ...
<p>You can just use <code>zip</code> and list comprehension:</p> <pre><code>df['c'] = [int(any(w in a for w in b)) for a, b in zip(df.a, df.b)] df # a b c #0 Bob Smith is great. [Smith, foo] 1 #1 The Sun is a mass of incandescent gas. [Jones, ...
python|pandas|string|dataframe|match
2
365,489
68,707,496
Sort pandas dataframe where values are date (how to create pivot_table without aggregation)
<p>I have a dataframe with columns A, B, C, and Date. I don't care about C. I want to create a pivot table where I have A in the first column, then B, and then in the third column I want to have the Dates.</p> <p>I get an error saying</p> <blockquote> <p>DataError: No numeric types to aggregate</p> </blockquote> <p>I'm...
<p>It looks like what you want to do is just drop <code>C</code> and set <code>A</code>/<code>B</code> as index:</p> <pre><code>df.set_index(['A', 'B'])[['D']] </code></pre> <p>output:</p> <pre><code> D A B apple sweet 2019-07-02 sweet 2016-11-25 sweet...
python|pandas|sorting
1
365,490
68,665,581
How to find True Postive only for Data Frame while having Ground Truth?
<p>first of all, sorry for the long description but I want that everyone understands my problem with what I doing.</p> <p>I am working on a detection model which predicts 14 different pathologies and I have made an inference file that does prediction for any new test images. The dataset having test images of about 25k+...
<p>From your <code>DataFrame</code> :</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df file set label bbx Atelectasis Cardiomegaly Consolidation Edema Effusion Emphysema Fibrosis Hernia ...
python|pandas|dataframe|model|prediction
1
365,491
68,630,024
How to evaluate columns that contain lists in pandas?
<p>Say I have a dataframe which describes the dimensions of hundreds of cardboard boxes:</p> <pre><code>df = [[17829292, (13, 14, 20)], [17739292, (20, 10, 15)], [17827792, (10, 10, 12)]] df = pd.DataFrame(df, columns = ['Serial Number', 'Box Dimensions']) </code></pre> <p>Given that the 'Box Dimensions' column contain...
<p>You can try:</p> <pre><code>m=pd.DataFrame(df['Box Dimensions'].tolist()).le(15).all(1) #OR(If needed to check dimensions seperately above method can be modified as well) m=df['Box Dimensions'].map(lambda x:x[0]&lt;=15 and x[1]&lt;=15 and x[2]&lt;=15) #Finally: df[m] #OR df.loc[m] </code></pre> <p>output of above co...
python|pandas|list
2
365,492
68,745,490
Best way to select rows and respective columns below a certain value in pandas
<p>I have a large dataframe with 30+ columns.</p> <p>The first two columns (&quot;A&quot; and &quot;B&quot;) contain general infromation about a feature, while the rest of columns represent different experiments for that feature.</p> <p>I want to slice my dataframe to only contain rows with respective columns, in which...
<p>Try:</p> <pre><code>df=df.loc[df.le(0.05).any(1),['A','B',*df.columns[df.le(0.05).any(0)]]] #OR df=df.loc[df.le(0.05).any(1),(df.le(0.05).any(0)) | (df.columns.isin(['A','B']))] </code></pre> <p>output of <code>df</code>:</p> <pre><code> A B D E 0 1 10 0.80 0.04 2 2 5 0.01 0.30 </code><...
python|pandas|dataframe
0
365,493
68,519,303
Pandas groupby with isin for consecutive groups
<p>I have a dataframe that looks like the following:</p> <pre><code>arr = pd.DataFrame([[0,0],[0,1],[0,4],[1,4],[1,5],[1,6],[2,5],[2,8],[2,6]) </code></pre> <p>My desired output is booleans that represent whether the value in column 2 is in the next consecutive group or not. The groups are represented by the values in ...
<p>You could create a helper column with lists of shifted group items, then check against that with a function that returns <code>True</code>, <code>False</code> of <code>NaN</code>:</p> <pre><code>import pandas as pd import numpy as np arr = pd.DataFrame([[0,0],[0,1],[0,4],[1,4],[1,5],[1,6],[2,5],[2,8],[2,6]]) arr = ...
pandas|group-by|isin
1
365,494
68,600,336
Need to implement Deep Learning architecture quite similar to Siamese Network
<p>I must implement this network:</p> <p><a href="https://i.stack.imgur.com/4xP5c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4xP5c.png" alt="enter image description here" /></a></p> <p>Similar to a siamese network with a contrastive loss. My problem is <code>S1</code>/<code>F1</code>. The paper ...
<p>I will give an answer to your two questions without going too much into details:</p> <ol> <li><p>If you're working with a CNN, you're most likely having spatial information in your input, that is your input is a two dimensional multi-channel tensor <code>(*, channels, height, width)</code>, not a feature vector <cod...
python|deep-learning|neural-network|pytorch|siamese-network
0
365,495
68,686,134
Dask: Sorting truly lazily
<p>If I have a dataset with unknown divisions and would like to sort it according to a column and output to Parquet, it seems to me that Dask does at least some of the work twice:</p> <pre class="lang-py prettyprint-override"><code>import dask import dask.dataframe as dd def my_identity(x): &quot;&quot;&quot;Does ...
<p>The explanation below may not be accurate, but hopefully helps a bit.</p> <p>Let's try to get into dask's shoes on this. We are asking dask to create an index based on some variable... Dask only works with sorted indexes, so Dask will want to know how to re-arrange data to make it sorted and also what will be the ap...
python|pandas|sorting|dask|dask-dataframe
0
365,496
68,502,532
BERT: Is it possible to filter the predicted tokens in masked language modelling?
<p>I have trained a masked language model using my own dataset, which contains sentences with emojis (trained on 20,000 entries).</p> <p>Now, when I make predictions, I want emojis to be in the output, however, most of the predicted tokens are words, so I think that the emojis are right at the bottom of the list somewh...
<p>yes, you should try it once- i am writing hints only.</p> <p>if output is not contains char:</p> <p>print(output)</p> <p>or</p> <p>also you can use regex to create pattern for emojis and filter out them. plz,check it once ,it might be helpful for you. <a href="https://stackoverflow.com/questions/33404752/removing-em...
python|machine-learning|bert-language-model|huggingface-transformers|huggingface-tokenizers
0
365,497
68,618,227
Replace a column value based on max count of values in a groupby scenario pandas
<p>I have a dataframe which looks like this:</p> <pre><code>df = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9],'sid':['X','Y','X','Z','X','Y','X','Y','Z'], 'cl':[0,1,1,0,0,1,0,0,1]}) df id sid cl 0 1 X 0 1 2 Y 1 2 3 X 1 3 4 Z 0 4 5 X 0 5 6 Y 1 6 7 X 0 7 8 Y 0 8 9 Z 1 ...
<p>You can use <code>groupby.transform</code> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mode.html#pandas-series-mode" rel="nofollow noreferrer"><code>Series.mode</code></a>:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;cl_new&quot;] = df.groupby(&quot;sid&quot;)...
python|pandas|dataframe
0
365,498
68,615,411
The way to change the bilinear resize to nearest neighbor(NN) in TF2.0 saved or frozen graph or onnx model
<p>I have the customized onnx model and want to implement it into specific embedded device.</p> <p>Before to implement it, It is needed to convert the model to the embedded device compatible model.</p> <p>But the thing is that..</p> <p>My model has Bilinear resize layer(ResizeBilinear) but the conversion tool only supp...
<p>Yes, you can edit the onnx model directly. Try using the onnx2py script.</p> <p><code>pip install onnxconverter-common</code></p> <p><code>python -m onnxconverter_common.onnx2py model.onnx model.py</code></p> <p>Then edit <code>model.py</code> and make the new model</p> <p><code>python model.py new_model.onnx</code>...
tensorflow|tensorflow2.0|onnx
1
365,499
68,800,382
How to pass possible class names to distilbert
<p>I've been trying to get distilbert to work and I've downloaded the model and used AutoTokenizer.from_pretrained() and AutoModelForSequenceClassification.from_pretrained(). I tried for a couple days now to pass the parameters from the &quot;Possible class names&quot; on the huggingface model card page: <a href="https...
<p>You don't have to append classes to the input text but you can define them in a separate list.</p> <p>The <code>AutoModelForSequenceClassification</code> will generate the logits which when passed through <code>softmax</code> will give you the class label.</p> <p>[One more suggestion: see the way I defined tokenizer...
python|machine-learning|pytorch|huggingface-transformers|transformer-model
0