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
350,000
35,140,235
MultIndex to fill in dataframe
<p>I have a df like this:</p> <pre><code> Allotments SH_Class SH_Percent A. Annex BNW 16.187500 A. Annex MTGP 1.0000000 A. Annex Meadow 39.687500 A. Annex PHP 29.687500 A. Annex SP 16.250000 A. Annex WMTGP 10.833333 A....
<p>You were close...</p> <pre><code>idx = pd.MultiIndex.from_product([df.Allotments.unique(), df.SH_Class.unique()], names=['Allotments', 'SH_Class']) &gt;&gt;&gt; df.set_index(['Allotments', 'SH_Class']).ix[idx].fillna(0).reset_index() Allotments SH_Class SH_Percent 0 A. Anne...
python|pandas
2
350,001
35,128,772
python manual fft botched
<p>Im trying to repoduce the fft functions in python. Iv'e seen a similar question <a href="https://stackoverflow.com/questions/22172619/manual-fft-not-giving-me-same-results-as-fft">Manual fft not giving me same results as fft</a> here, but I'm having trouble seeing if i'm doing the same error or a different one.</p> ...
<p>There are several things to mention. First of all, in Python we use <code>1j</code> to represent the imaginary unit, not <code>complex(0, 1)</code>. If you would like to compare your result to numpy, then you have to check how numpy implements the fft. See the <a href="http://docs.scipy.org/doc/numpy/reference/routi...
python|numpy|fft
2
350,002
35,039,550
Convert class 'pandas.tslib.Timedelta' to string when export to excel
<p>Initial dataframe:</p> <pre><code>arrivalTime 0 2016-01-12 06:35:42 2 2016-01-12 06:54:02 3 2016-01-12 07:01:43 4 2016-01-12 07:02:28 5 2016-01-12 07:12:29 6 2016-01-12 07:18:41 </code></pre> <p>On data I apply this function:</p> <pre><code>def function(df): df['arrivalTime_cal'] = pd.to_...
<p>IIUC then you can just cast the type to <code>str</code> and then <code>split</code> the str:</p> <pre><code>In [53]: df['diff_time'].astype(str).str.split().str[-1].str.rsplit('.').str[0] Out[53]: index 0 00:00:00 2 00:18:20 3 00:07:41 4 00:00:45 5 00:10:01 6 00:06:12 dtype: object </code></pre>...
excel|datetime|pandas|string-formatting|timedelta
2
350,003
34,951,501
Add (and calculate) rows to dataframe until condition is met:
<p>I'm attempting to build a dataframe that adds 1 to the prior row in a column until a condition is met. In this case, I want to continue to add rows until column 'AGE' = 100. </p> <pre><code>import pandas as pd import numpy as np RP = {'AGE' : pd.Series([10]), 'SI' : pd.Series([60])} RPdata = pd.DataFrame(...
<p>There may be other problems, but you're going to get in an infinite loop with <code>while [i &lt; 100]:</code> since a non-empty list will always evaluate to True. Change that to <code>while (i &lt; 100):</code> (parens optional) and remove your <code>break</code> statement, which is forcing just one iteration.</p>
python|loops|numpy|pandas|while-loop
0
350,004
35,070,562
Using pandas.get_dummies
<p>So essentially I have a data frame with a bunch of columns, some of which I want to keep (stored in to_keep) and some other columns that I want to create categorical variables for using pandas.get_dummies (these are stored in to_change).</p> <p>However, I can't seem to get the syntax of how to do this down, and all...
<p>Didn't understand the problem completely, I must say.</p> <p>However, say your DataFrae is <code>df</code>, and you have a list of columns <code>to_make_categorical</code>.</p> <p>The DataFrame with the non-categorical columns, is</p> <pre><code>wo_categoricals = df[[c for c in list(df.columns) if c not in to_mak...
python|pandas
2
350,005
35,206,101
Using numpy.argpartition
<p>I'm trying to obtain the top N larges values of an array.</p> <p>For example:</p> <pre><code>total_A = [0. 0. 30. 0. 20. 58. 0. 0. 31. 0. 0. 0. 398. 132. 0. 0. 316. 0.] </code></pre> <p>Using this:</p> <pre><code>top_A = numpy.argpartition(total_A, -18, axis=None)[-18:] </code></pre> <p>I get:</p> <pre><code>[...
<p>This line:</p> <pre><code>[(top_A[i], numpy.round(total_A[top_A[i]])) for i in top_A] </code></pre> <p>should be simplified to</p> <pre><code>[(i, numpy.round(total_A[i])) for i in top_A] </code></pre> <p>The values in <code>top_A</code> are the indices into <code>total_A</code>.</p> <p>For example,</p> <pre><...
python|sorting|numpy
2
350,006
34,967,273
Add metadata comment to Numpy ndarray
<p>I have a Numpy ndarray of three large arrays and I'd just like to store the path to the file that generated the data in there somewhere. Some toy data:</p> <pre><code>A = array([[ 6.52479351e-01, 6.54686928e-01, 6.56884432e-01, ..., 2.55901861e+00, 2.56199503e+00, 2.56498647e+00], ...
<p>TobiasR's comment is the simplest way, but you could also subclass ndarray. See <a href="https://numpy.org/doc/stable/user/basics.subclassing.html#simple-example-adding-an-extra-attribute-to-ndarray" rel="nofollow noreferrer">numpy documentation</a> or <a href="https://stackoverflow.com/questions/5149269/subclassing...
python|arrays|numpy
9
350,007
34,898,159
Python Pandas Series combine the rows
<p>My pd.series looks like this:</p> <pre><code>df.head() 0 status parentName name describe parent... 1 status parentName name describe parent... 2 status parentName name describe parent... 3 status parentName name describe parent... 4 status parentName name descr...
<p>You can use <code>pd.concat</code> and call <code>tolist</code> on your <code>Series</code>:</p> <pre><code>In [144]: s = pd.Series([pd.DataFrame(data=np.random.randn(5,3), columns=list('abc')), pd.DataFrame(data=np.random.randn(5,3), columns=list('abc')), pd.DataFrame(data=np.random.randn(5,3), columns=list('abc')...
python|pandas|dataframe|apply|series
0
350,008
34,890,861
How to run a large matrix for cosine similarity in Python?
<p>I want to calculate cosine similarity between articles. And I am running into the problem that my implementation approach would take a long time for the size of the data that I am going to run.</p> <pre><code>from scipy import spatial import numpy as np from numpy import array import sklearn from sklearn.metrics.p...
<p>You can use pairwise_kernels with metric='cosine' and n_jobs = . That will divide the data and run it in parallel</p>
python|numpy|scikit-learn|cosine-similarity
2
350,009
35,214,878
Python, Nested Dictionary to Dataframe
<p>In python need to flatten a large nested Dictionary that starts like this:</p> <pre><code>{u'February 19, 2016': {'calls': [{'%change': u'0.00%', 'ask': u'6.50', 'bid': u'5.20', 'change': u'0.00', 'interest': u'10', 'last': u'10.30', 'name': u'LVLT160219C00044000', 'strike': u'44.00', 'volatility': u'62.31%', 'volu...
<p>I would loop through your structure and cast it into a new format that pandas can automatically recognize, like a sequence of dicts. You'll have to customize it for your exact needs but this is a proof of concept based on your current data structure. </p> <pre><code>import pandas as pd #your data looks something li...
python|dictionary|pandas
1
350,010
35,153,319
pivoted data frame with catagorical column fails to print
<p>I'm using a Pandas DataFrame to manage some results data. To achieve ‘slice and dice’ on my data frame I use the ‘pivot_table’ function. In addition to this, to get a custom ordering of columns I convert one of my columns to be a ‘categorical’ column. I’m finding that when I try and print the data frame it gives the...
<p>You can reorder the labels at any level in a multiindex with the <code>reindex</code> function:</p> <p>First I reuse your code:</p> <pre><code>df = pd.DataFrame(data=data, columns=('Ord', 'Name', 'label', 'Value')) label_sort_order = {'3M': 1, '1Y': 2, '2Y': 3, '3Y': 4, '5Y': 5, '7Y': 6, '10Y': 7, '15Y': 8, '20Y':...
python|python-3.x|pandas
0
350,011
34,970,848
Find all combination that sum to N with multiple lists
<p><strong>Given</strong>: </p> <ul> <li><code>m</code> number of lists (<code>m</code> can vary).</li> <li>Each list contain <code>arange()</code> of numbers.</li> </ul> <p><strong>Want</strong>:</p> <ul> <li>Find the m-tuple (one number per list) that <code>sum()</code> to <code>N</code>.</li> </ul> <p><strong>Wh...
<p>As discussed in the comments, the ranges are all the same and we ought to use integers. Here's an imho neat way then.</p> <p>Instead of producing four numbers and testing whether they add up to 10, produce <strong>three</strong> numbers defining a partition of the interval [0, 10] into four intervals. For example w...
python|numpy
11
350,012
31,023,296
How to select with ease several circular areas in a square array?
<p>I am currently defining an area that way : </p> <pre><code>target=zeros((256,256)) </code></pre> <p>If I want to define for instance 2 squares areas out of this big zone, i can do that :</p> <pre><code>target[50:60,50:60] = 1 target[100:110,100:110] = 1 </code></pre> <p>If I want to define a circular area of par...
<p>Try this</p> <pre><code>xx,yy = np.meshgrid(np.arange(256),np.arange(256)) mask = ((xx-10)**2+(yy-10)**2 &lt; 8**2) | ((xx-123)**2+(yy-35)**2 &lt; 2**2) target[mask] = 1 </code></pre>
arrays|python-2.7|numpy
1
350,013
31,080,167
Complex row and column Manipulations pandas
<p>I am trying to perform both row and column operations at same time. I have a data with time series. I did check almost all the examples here and in document but no much luck and have been more confused than before. </p> <p>I have two files both in same path</p> <pre><code>Path = '/' File_1.csv Nos,00:00:00,12:0...
<p>Merge the two dataframes into one:</p> <pre><code>In [34]: df3 = pd.merge(df2, df1[['Nos', '12:00:00']], on=['Nos'], how='left') In [35]: df3 Out[35]: Nos 00:00:00 12:00:00 0 123 20 624 1 123 20 624 2 123 20 624 3 125 50 65 4 125 50 65 5...
python|file|csv|pandas|time-series
1
350,014
31,195,941
What is the correct way of passing parameters to stats.friedmanchisquare based on a DataFrame?
<p>I am trying to pass values to <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.friedmanchisquare.html#scipy.stats.friedmanchisquare" rel="nofollow noreferrer">stats.friedmanchisquare</a> from a dataframe <code>df</code>, that has shape <code>(11,17)</code>.</p> <p>This is what <strong>works<...
<p>The problem I see with your first attempt is that you end up passing one list with multiple dataframes inside of it. </p> <p>The stats.friedmanchisquare needs multiple array_like arguments, not one list</p> <p>Try using the <a href="https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists" rel=...
python|numpy|pandas|scipy
2
350,015
30,977,816
Pandas Dataframe Complex Calculation
<p>I have the following dataframe,df:</p> <pre><code> Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 </code></pre> <p>I want to write code that would do the following:</p> <p>Cita...
<p>I believe the following does what you want:</p> <pre><code>In [24]: df['New_Col'] = df['ActualCitations']/pd.rolling_sum(df['totalPubs'].shift(), window=2) df Out[24]: Year totalPubs ActualCitations New_Col 0 1994 71 191.002034 NaN 1 1995 77 2763.911781 NaN 2 199...
python|python-2.7|pandas|dataframe
1
350,016
30,787,391
Sorting entire csv by frequency of occurence in one column
<p>I have a large CSV file, which is a log of caller data.</p> <p>A short snippet of my file:</p> <pre><code>CompanyName High Priority QualityIssue Customer1 Yes User Customer1 Yes User Customer2 No User Customer3 No Equipment Cust...
<p>This seems to do what you want, basically add a count column by performing a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby" rel="nofollow noreferrer"><code>groupby</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#...
python|sorting|csv|pandas|frequency
14
350,017
31,167,896
KeyError in Dataframe
<p>I have a dataframe that looks just how I want it when I export it to a csv file. </p> <pre><code>CompanyName 1 2 3 4 5 6 7 8 9 10 11 12 Company 1 182 270 278 314 180 152 110 127 129 117 127 81 Company 2 163 147 192 142 186 231 214 130 112 117 93 101 Company 3 126 88 99 139 97 97 96 3...
<p>This is because you've set the index to <code>CompanyName</code>.</p> <p>You cannot reference the index in that manner.</p> <p>Use <code>pivot_table = pivot_table.reset_index()</code> to reset the index and try accessing it again.</p> <p>Here's the reproduced error:</p> <pre><code> In [45]: df = pd.read_clipboar...
python|pandas|dataframe|keyerror
11
350,018
31,107,095
Adding elements to numpy 1D array
<p>I have a numpy array (a). How can I add two elements in it?</p> <pre><code>import numpy as np a = np.array([5,6,7]) b = 3 c = 4 result = np.hstack((b,c,a)) print result </code></pre> <p>Works using answer from @BHAT IRSHAD</p> <p>I have to do it to use with np.savetxt; I wan to write the result as one row. But ...
<p><code>np.hstack</code> takes only one argument and you are passing three, so <code>result = np.hstack((b,c,a))</code> will work.</p> <p>Demo:</p> <pre><code>&gt;&gt;&gt; a = np.array([5,6,7]) &gt;&gt;&gt; b = 3 &gt;&gt;&gt; c = 4 &gt;&gt;&gt; np.hstack((b,c,a)) array([3, 4, 5, 6, 7]) </code></pre>
python|numpy
1
350,019
30,854,657
Finding indices of elements in vector
<p>I have a vector <code>orig</code> which is a p dimensional vector</p> <p>Now, I sampled c elements from this vector (with replacement), lets call it <code>sampled_vec</code>. So basically,<code>sampled_vec</code> has elements from <code>orig</code> Now, I want to find out the indices of these elements (in <code>sam...
<p>For example using list comprehensions:</p> <pre><code>In [1]: orig = [1,2,3,4,5] In [2]: sampled_vec = [3,1,3] In [3]: indices = [orig.index(i) for i in sampled_vec] In [4]: indices Out[4]: [2, 0, 2] </code></pre>
python|numpy
1
350,020
30,895,093
How to change numpy.array sample rate?
<p>Say, I've got a signal which is one dimensional numpy array lasting for one second with sample rate equal to 16 kHz. How can I resample this array for instance to 1024 Hz without loosing information about "peaks" present in this signal as shown below? I add only that intervals between "peaks" are not less, than 40 m...
<p>If you can use <code>scipy</code>, I suggest <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow"><code>scipy.interpolate.interp1d</code></a>.</p> <p>However also <code>numpy</code> has a 1D interpolation in <a href="http://docs.scipy.org/doc/numpy/refe...
python|arrays|numpy
2
350,021
31,141,826
How to add arbitrary kwargs and defaults to function using a decorator
<p>So I have a bunch of processing functions and all of them use a (for lack of a better word) 'master' function. This master function basically is a big AND operation that returns the relevant lines from a pandas data frame according to the value of a bunch of boolean or string columns (btw, the data are about roden...
<p><strong>update</strong></p> <p>The original answer, suggesting the use of functools.partial is bellow. In th meantime, years after answering this question, I needed the functionality being described: A decorator to add new specific keyword-args to the decorated function, and have these keywords show up in the functi...
python|pandas|decorator|python-3.4|function-calls
1
350,022
67,235,863
Filter dataframe based on columns determined from user input
<p>I would like to get help on the creation of a program, taking in user input based on up to 2 column names and their values, and returning the respective rows within a dataframe. Should the user enter only the first column name and value, they can choose to enter 'exit' for the second column name and value inputs, to...
<p>You can just do this</p> <pre class="lang-py prettyprint-override"><code>df[(df[first_column_name] == first_column_value) &amp; (df[second_column_name] == second_column_value)] </code></pre> <p>Do not forget to check every input column names is exists in dataframe</p> <pre class="lang-py prettyprint-override"><code>...
python|pandas|dataframe
0
350,023
67,462,060
Difference in differences DID in pandas with pivot table
<p>Difference in differences (DID) is a statistical technique that calculates the effect of a treatment on an outcome by comparing the average change over time in the outcome variable for the treatment group [1]. I have this dataset where <code>after</code> means the months where the treatment was introduced and <code>...
<p>As <a href="https://stackoverflow.com/users/8505817/igrinis">igrinis</a> suggests, I would also recommend putting everything (your and their code) in a function:</p> <pre><code>def diff_in_diff(data: pd.DataFrame, treatment: str, control: str, response: str): df_pv = df.pivot_table(index=treatment, columns=contr...
python|pandas
2
350,024
67,314,731
matplotlib plot sampling strategy at a 3H frequency
<h1>Problem Overview</h1> <p>I am trying to plot a sampling schedule for an experiment I ran. We set out to sample every 3 hours, and I want to be able to observe the time at which each sample was plotted on a daily cycle.</p> <ul> <li>The x-axis variable should be time of day (00:00 - 23:00).</li> <li>Each row (or may...
<p>Here is a complete and reproducible example with the following key features:</p> <ul> <li>the data is processed exclusively with pandas using vectorized operations;</li> <li>the simulation of the time deltas is corrected by replacing DateOffset with Timedelta objects, so about half the points are now blue;</li> <li>...
python|python-3.x|pandas|matplotlib
1
350,025
67,206,495
CUDA driver version is higher than the CUDA runtime version?
<p>The terminal shows the error:</p> <pre><code>RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:51 </code></pre> <p>But my driver version (440.118.02) is sufficient for cuda9.0</p> <p>Some info about my machine: cat /proc/driver/nvidia/v...
<p>You can upgrade the CUDA version to 9.2 or higher. After getting the new CUDA just check driver version 440 is still compatible or not. If not upgrade that too.</p> <p>Do these and then run your code and check.</p> <p>NOTE: If you have installed or upgraded the Nvidia driver or CUDA recently then reboot the system o...
python-3.x|cuda|pytorch
1
350,026
67,357,410
Python add values from multiple columns from one dataframe to another dataframe if it doesn't exists
<p>I have two dataframes df1 and df2, I need to check if the values in df1 column x1 and column x2 exist in df2 column x. If the value doesn't exists, then add it to df2 column x and NaN to df2 column y.</p> <p>The following is the what I have, it works but takes too long for large datasets and I feel it could be impro...
<p>Here is another way to get it done, using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.melt.html#pandas-dataframe-melt" rel="nofollow noreferrer"><code>melt</code></a> + <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.append.html#pandas-dataframe-append" rel="nofollow...
python|pandas|dataframe
3
350,027
67,398,739
An error when declaring the variable placeholder
<p>I am building sample Neural Network using Pycharm, tensorflow 2.4 and python v3.8.5. When Running this command:</p> <pre><code>X = tf.placeholder(&quot;float&quot;, [None, num_input]) #num_input is the sized of input vector </code></pre> <p>I get an error like this one:</p> <pre><code>raise TypeError(&quot;Error ...
<p>This row (tf.placeholder) is enable for tensorflow 1, but you have installed tensorflow2. Disable Tf2 and run your backend on Tf1 .</p> <pre><code>import tensorflow.compat.v1 as tf tf.disable_v2_behavior() X = tf.placeholder(&quot;float&quot;, [None, 8]) print(X) &lt;tf.Tensor 'Placeholder:0' shape=(?, 8) dtype=flo...
python|tensorflow|neural-network|pycharm
1
350,028
67,471,619
Combine 2 rows into one dataframe
<p>I try to combine two rows in dataframe into one</p> <pre><code> ID Value1 Value2 0 ID_1 NaN 2 1 ID_2 NaN 7 2 ID_1 5 NaN 3 ID_2 8 N...
<p>Use <code>set_index()</code> <strong>,</strong> <code>apply()</code> method and <code>sorted()</code> method:</p> <pre><code>newdf=df.set_index('ID').apply(lambda x : sorted(x,key=pd.isnull)) </code></pre> <p>Finally use boolean masking and <code>isna()</code> method:</p> <pre><code>newdf=newdf[~newdf.isna().all(1)]...
python|pandas|dataframe
1
350,029
67,254,642
How do I remove columns in Pandas that contains non-zero in less than 1% of number of rows?
<p>I have the following dataset:</p> <pre><code> Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 Col10 ... Col991 Col992 Col993 Col994 Col995 Col996 Col997 Col998 Col999 Col1000 rows Row1 0 0...
<p>You can use loc to get the specified columns or rows for your new df as shown in <a href="https://stackoverflow.com/a/57577991/13099243">this</a> answer, essentially you can do this:</p> <pre><code>df.loc[rows, cols] # accepts boolean lists/arrays </code></pre> <p>So the df with removed columns can be achieved with...
python|pandas|dataframe|data-analysis|data-filtering
3
350,030
67,300,611
Import duration from xlsx / convert object to duration
<p>I am using Python to webscrape lots of xlsx files (all in the same format) and consolidate them into a single file ready for further analysis using</p> <pre><code>In [206]: files = glob.glob(path + &quot;/*.xlsx&quot;) df= pd.DataFrame() df = pd.concat([pd.read_excel(fp, index_col = 0, header = 3).assign(New=os...
<p><em><strong>Background:</strong></em> Excel stores dates as a serial date, days since 1900 by default. See also: <a href="http://www.cpearson.com/excel/datetime.htm" rel="nofollow noreferrer">Dates and Times in Excel</a>. But there's no dedicated type for duration in Excel, they are just dates in Excel as well. So u...
python|excel|pandas|datetime|timedelta
0
350,031
67,579,206
Apply function to certain groups of columns of a pandas dataframe
<p>I have a pandas dataframe that looks like this:</p> <pre><code> col1 col2 col3 col4 1 10 10 20 25 2 15 20 10 20 3 20 10 15 10 </code></pre> <p>I want to calculate a p-value using the scipy stats package. Specifically, I want to get a p-value comparing the first two columns a...
<p>So we may do it with line by line</p> <pre><code>df['p_v'] = df.apply(lambda x : stats.wilcoxon(x['col1':'col2'], x['col3':'col4'])[1],axis=1) </code></pre>
python|pandas|dataframe|scipy|p-value
2
350,032
67,467,246
How to get a parallel row value in Pandas?
<p>I am trying to figure out a way to get the parallel row value from Dataframe.</p> <p>for Example : i have a dataframe</p> <pre><code>df = pd.DataFrame({&quot;TableName&quot;: [&quot;Table1&quot;, &quot;Table2&quot;], &quot;SQL&quot;: [&quot;abc&quot;, &quot;def&quot;]}) </code></pre> <p>Now i want to get the sql col...
<p>set the index and the fetch the value:</p> <pre><code>df = pd.DataFrame({&quot;TableName&quot;: [&quot;Table1&quot;, &quot;Table2&quot;], &quot;SQL&quot;: [&quot;abc&quot;, &quot;def&quot;]}) df = df.set_index('TableName') # set index result = df.loc['Table1'].values # fetch value </code></pre>
python|pandas
0
350,033
67,257,940
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same - PyTorch
<p>I'm trying to push both my mode and data, images and labels, to run on the GPU by doing:</p> <pre><code>device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;) </code></pre> <p>Followed by:</p> <pre><code>count = 0 loss_list = [] iteration_list = [] accuracy_list = [] epochs = 30 ...
<p>Your weights are saved on your gpu but your input is on your cpu. You can change that by: <code>images.cuda()</code></p>
python|pytorch
0
350,034
67,409,782
TypeError: melt() takes 1 positional argument but 2 were given
<p>I am trying to use <code>melt()</code> function but it is showing me an error for passing 2 argument, which really weird because i am passing <code>id</code> as an argument and in my DataFrame i have only one <code>id</code> column, Although this error only comes when i use data which split from dataset by <code>tra...
<p>The positional parameter is <code>self</code>, which is <code>X_train</code>. <code>melt</code> expects its parameters to be specified by keyword. Try <code>X_train.melt(id_vars=['id'])</code>.</p>
python|pandas|dataframe|rapids
1
350,035
67,345,480
Converting a tf.dataset to a PyTorch Dataset?
<p>I'm working on this project where all the data comes preprocessed and ready as a tensorflow datasets which looks like this:</p> <pre><code>&lt;MapDataset shapes: {input_ids: (128,), input_mask: (128,), label_ids: (), segment_ids: (128,)}, types: {input_ids: tf.int64, input_mask: tf.int64, label_ids: tf.int64, segmen...
<p>I use <code>tfds.as_numpy(dataset)</code> as the dataloader for my model training. To convert the data passed to my model, I use <code>torch.as_tensor(data, device=&lt;device&gt;)</code> inside my model's forward function.</p> <pre class="lang-py prettyprint-override"><code>import tensorflow_datasets as tfds import ...
tensorflow|pytorch|dataset|tensorflow-datasets
0
350,036
67,469,355
How to implement Flatten layer with batch size > 1 in Pytorch (Pytorch_Geometric)
<p>I am new to Pytorch and am trying to transfer my previous code from Tensorflow to Pytorch due to memory issues. However, when trying to reproduce <code>Flatten</code> layer, some issues kept coming out.</p> <p>In my <code>DataLoader</code> object, <code>batch_size</code> is mixed with the first dimension of input (...
<p>The way you want the shape to be <code>batch_size*node_num, attribute_num</code> is kinda weird.</p> <p>Usually it should be <code>batch_size, node_num*attribute_num</code> as you need to match the input to the output. And <code>Flatten</code> in Pytorch does exactly that.</p> <p>If what you want is really <code>bat...
python|neural-network|pytorch|conv-neural-network|flatten
4
350,037
67,206,847
Multiple figures with subplots from a dataframe
<p>I have a dataframe for which I am plotting the sorted values from the columns as a line and then plotting and labeling various percentiles along that line.</p> <p>I would like to have 12 subplots per figure and as many figures as I need depending on the number of columns (which will vary on my real datasets).</p> <p...
<p>A slightly different approach</p> <ul> <li>create all figures and axes upfront and flatten the array of axes</li> <li>then use more unto date Matplotlib API to <strong>plot</strong> against axis</li> <li>have used <strong>pandas</strong> instead of <strong>numpy</strong> as I found it simpler to define x-co-ordinate...
python-3.x|pandas|dataframe|numpy|subplot
0
350,038
67,196,075
PyTorch DataLoader uses identical random transformation across each epoch
<p>There is a <a href="https://tanelp.github.io/posts/a-bug-that-plagues-thousands-of-open-source-ml-projects/" rel="nofollow noreferrer">bug</a> in PyTorch/Numpy where when loading batches in parallel with a <code>DataLoader</code> (i.e. setting <code>num_workers &gt; 1</code>), the same NumPy random seed is used for ...
<p>The best way I can think of is to use the seed set by pytorch for numpy and random:</p> <pre><code>import random import numpy as np import torch from torch.utils.data import Dataset, DataLoader def worker_init_fn(worker_id): torch_seed = torch.initial_seed() random.seed(torch_seed + worker_id) if torch_...
python|numpy|parallel-processing|pytorch|dataloader
3
350,039
67,394,591
Pandas to check if value is NONE
<p>I have a dataFrame</p> <pre><code>df = pd.DataFrame({'k':['a','b','c'],'v':[1,None,3]}) k v 0 a 1.0 1 b NaN 2 c 3.0 </code></pre> <p>I want to check if column <code>k</code>'s <code>b</code> value is NaN or not</p> <p>I have tried</p> <pre><code>if df['v'][df['k']=='b'] is None: print(&quot;yes&quot...
<p>If, as long a you have a null value, you would want to return the <code>True</code> then use <code>.any()</code>. If you want all values to be Null (in this case it doesn't matter because there's a single value) then use <code>.all()</code>:</p> <pre><code>if df[df['k']=='b']['v'].isna().any(): print(&quot;yes&q...
python|pandas
1
350,040
67,302,560
Adding Brackets and comma at the end for the text file in pandas
<p>I have a text file that looks like this:</p> <pre><code>5,1730572382,8236,1600956334,12.95,1012.38,64.80 6,1730551647,8266,1600956334,13.42,1012.43,64.66 7,1730582880,8290,1600956334,13.18,1012.60,61.39 </code></pre> <p>I want the text file to look like this</p> <pre><code>[5,1730572382,8236,1600956334,12....
<pre><code>file = open('file.txt').read() print([[float(i) for i in line.split(',')] for line in file.splitlines()]) </code></pre>
python|pandas
0
350,041
67,205,948
How to load a pre-trained PyTorch model?
<p>I'm following <a href="https://pytorch.org/tutorials/recipes/recipes/saving_and_loading_a_general_checkpoint.html" rel="noreferrer">this</a> guide on saving and loading checkpoints. However, something is not right. My model would train and the parameters would correctly update during the training phase. However, the...
<p>The way you are loading your data is not the recommended way to load your parameters because you're overwriting the graph connections (or something along those lines...). You even save the model state_dict, so why not use it!</p> <p>I changed the load function to:</p> <pre><code>def load(self): try: ch...
python|pytorch
4
350,042
67,437,474
PermissionDeniedError: Failed to create a directory: /; Permission denied [Op:MergeV2Checkpoints]
<p>I am unable to save model. I am using Jupyter notebook.</p> <pre><code>epochs = 100 model.compile(optimizer=optimizer, loss=loss_fn,) model.fit(train_ds, epochs=epochs, callbacks=callbacks, validation_data=valid_ds, verbose=2) model.load_weights(checkpoint_filepath) </code></pre>
<p>I also meet this problem. My code is like this:</p> <pre><code>checkpoint_filepath = &quot;/tmp/checkpoint&quot; </code></pre> <p>And i changed it like this:</p> <pre><code>checkpoint_filepath = &quot;./tmp/checkpoint&quot; </code></pre> <p>I add a dot <code>.</code> before <code>/</code> and then it works.</p> <p>S...
tensorflow2.0
3
350,043
67,252,604
Loop over files in different folders
<p>How can I loop over 2 folders? In Apple and all its subfolders, I want to look for Excel files that contain &quot;green&quot;. In Banana, I want to look for files that contain &quot;yellow&quot;. I explicitly need to specify the folder paths and can't just loop over the whole C drive.</p> <pre><code>import os folder...
<p>The easiest way to get all the file paths that match your condition would be to use <code>glob</code> package:</p> <pre><code>import glob for file in glob.glob('C:/Desktop/apple/*green*.xlsx') + glob.glob('C:/Desktop/banana/*yellow*.xlsx'): print(file) df = pd.read_excel(os.path.join(root, file)) df['dat...
python|python-3.x|pandas|glob|pathlib
1
350,044
67,273,716
Error when reading Google Maps hyperlink in the excel using pandas
<p>I have an Excel spreadsheet with a column called Map that has the link to the locations on Google Maps. I'm trying to get this link, but in the column on Pandas the text &quot;Link&quot; appears. Is it possible to get the spreadsheet URL using Pandas? Could someone help me, please!</p> <p><a href="https://i.stack.im...
<p>This should work with openpyxl</p> <pre><code>import openpyxl wb = openpyxl.load_workbook('filename.xlsm') ws = wb['Sheet1'] hl = ws.cell(row=3, column=13).hyperlink </code></pre>
python|excel|pandas|hyperlink
0
350,045
67,281,277
Save inner arrays as images from 2D outer array
<p>I have a 4D array of shape <code>(7496, 32, 32, 1)</code> 7496 NumPy arrays arranged as 32x32 images in grayscale.<br /> I would like to loop through this array of arrays and save them all as images, either jpg or bmp. Any method would do whether using PIL, OpenCV or any other APIs or libraries, thank you all in adv...
<p>You were almost there.</p> <pre><code>import os for t in range(0, normal_imgs.shape[0]): original = normal_imgs[t] equalized = cv2.equalizeHist(original ) cv2.imwrite(os.path.join(CWD, 'image_after.bmp'), equalized) </code></pre>
python|numpy|opencv
0
350,046
67,229,249
My google colab session is crashing due to excessive RAM usage
<p>I'm training CNN with 2403 images 1280x720 px each. This the code that I'm running:</p> <pre><code>from tensorflow.keras.preprocessing.image import ImageDataGenerator import tensorflow as tf from tensorflow import keras from tensorflow.keras.layers import Conv2D,MaxPooling2D,Activation,Dense,Flatten,Dropout model =...
<p>Seems like you are having a large batch size which is consuming all the RAM. So I suggest first try with smaller batch size like 32 or 64. Also your image sizes are too large, you can reduce it initially for experiments.</p> <pre><code>train_generator = train_datagen.flow_from_directory( '/gdrive/MyDrive/shot/tr...
python|tensorflow|keras|google-colaboratory
4
350,047
67,220,667
Plotting multiple Gini Coefficients on the same graph
<p>I am trying to plot the gini coefficient on a graph, showing different data for different variables (GDP_PPP and GDP_MER) to show the inequalities between gdp market exchange rate and gdp as gross national income. I am struggling to get both variables to appear on the same graph.</p> <p>The below code is what I have...
<p>Unless I'm very mistaken, you've simply forgotten to add the argument to your function definition.</p> <p>You currently have:</p> <pre><code>def GiniCoeff_plot(pop, resource): </code></pre> <p>But internally you refer to both <code>resource</code> and <code>resource2</code>.</p> <p>I think all you need to do is to u...
python|pandas|gini
0
350,048
67,576,817
pandas dataframe find NaN explicitly
<p>I have a dataframe that can potentially contain NaN values. How do I find the NaNs and only the NaNs? Most suggestions suggest using df.isnull, but this returns None values as well. I only care about NaN.</p> <p>Thanks</p>
<p>To find <code>NAN</code> values you can use:</p> <pre><code>df.isna().sum(axis='index') # or axis = 0 df.isna().sum(axis='columns') # or axis = 1 df.isna().sum().sum() # to find all nan values in df </code></pre> <p><code>NOTE</code>: <code>df.isna()</code> will return a df(shape same as original df) with boolean v...
python|pandas|nan
1
350,049
67,223,947
how to find total play time of each week for the given date in python?
<p>I have a data frame that looks like the one below</p> <pre><code>k={'user_id':[1,1,1,1,1,2,2,2,3,3,3,3,3,4,4,4,5,5], 'created':[ '2/09/2021','2/10/2021','2/16/2021','2/17/2021','3/09/2021','3/10/2021','3/18/2021','3/19/2021', '2/19/2021','2/20/2021','2/26/2021','2/27/2021','3/09/2021','2/10/2021','2...
<pre class="lang-py prettyprint-override"><code># Get a list of unique id's user_ids = df[&quot;user_id&quot;].unique() # Get the start date of each user start_dates = [min(df[df[&quot;user_id&quot;]==usr][&quot;created&quot;]) for usr in user_ids] # We will subtract the start date to have a common baseline for all u...
python|pandas|loops|if-statement
0
350,050
67,434,489
How to print only part of an Excel column on pycharm?
<p>Using:</p> <pre><code>import pandas as pd x = pd.read_excel(r&quot;C:\Users\nan\PycharmProjects\giraffe\GENERA.xlsx&quot;, engine=&quot;openpyxl&quot;) print(x) </code></pre> <p>I can easily print the entire sheet from Excel into pycharm, but I needed only the first 5 lines of the Excel document. How can I do that?<...
<p>May be you want to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.head.html" rel="nofollow noreferrer">pandas.DataFrame.head()</a></p> <pre class="lang-py prettyprint-override"><code>x.head(5) </code></pre>
python|pandas
0
350,051
67,557,445
How to get barh plot with values displayed within each bar?
<p>I have such a dataframe <code>df_new</code> with index column <code>name</code> and column <code>length</code>:</p> <pre><code>name length U19 13 U17 14 U15 5 U13 10 U11 16 U9 17 U7 8 </code></pre> <p>I want to get a barh plot with the displayed values of column length within the corresponding column.</p> <p>I us...
<p>I think the error is coming from this line because <code>ind = df_new['name']</code> makes <code>ind</code> a string, and you cannot add a number to it:</p> <pre><code>ax.set_yticks(ind+width/2) </code></pre> <p>You used <code>enumerate(y)</code> to place the text, but <code>y</code> is not declared in the code, so ...
python|pandas|matplotlib
2
350,052
67,219,503
Can it be learned which column caused the anomaly in detecting anomaly?
<p>I'm trying to find anomalies in test data using semi-supervised machine learning. let's say we have data as follows. this data is unlabeled and this data is train data for anomaly detection. all values here are normal.(<strong>does not contain abnormal value</strong>)</p> <pre><code>column1 column2 column3 col...
<p>I don't know if you need the model to do that, or you already have the algorithm to train. Anyway, if all values are numbers and you assume normal distribution you can use 3 sigma rule and in that case, everything in the mean +/- 3*sigma (standard deviation) should be around 99.7% of your data. So if a number is ou...
python|pandas|dataframe|anomaly-detection
0
350,053
67,392,580
Appending a value from a Column to another Column based on a condition
<p>This is the type of my data:</p> <p><a href="https://i.stack.imgur.com/Dv53v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dv53v.png" alt="enter image description here" /></a></p> <p>I wish to write a Python script that can help me do the following:</p> <p>If ABC company bought chocolate and tea...
<p>Let us try with <code>transform</code></p> <pre><code>df['newcolumn'] = df.groupby('Company').Product.transform(lambda x : ';'.join(set(x))) </code></pre>
python|pandas|dataframe
1
350,054
67,473,597
How to select optimal number of components for NMF in python sklearn?
<p>There is not a built-in function in python's sklearn to do this.</p> <p>In my <a href="https://towardsdatascience.com/using-nmf-to-classify-companies-a77e176f276f" rel="nofollow noreferrer">research</a> I found out that a &quot;precision score&quot; err(components) can be calculated via</p> <p><a href="https://i.sta...
<p>I'm not sure about the transposition in your formula since sklearn seems to transpose already H but this should do the trick</p> <pre><code>err = np.linalg.norm(X - W @ H)**2/np.linalg.norm(X)**2 print(err) </code></pre>
python|scikit-learn|sklearn-pandas|nmf
1
350,055
67,549,748
unable to install tensorflow: PackagesNotFoundError: The following packages are not available from current channels
<h2>Im using anaconda, I created an enviroment called proyecto, then after activating it I wrote &quot;conda install tensorflow&quot; and this was the result:</h2> <p>(proyecto) C:\Users\min2&gt;conda install tensorflow Collecting package metadata (current_repodata.json): done Solving environment: failed with initial f...
<p>As mentioned by @drop90prog, After installing x64 version it works why because Tensorflow is tested and supported on the 64-bit Windows system.</p> <p>Refer the <a href="https://www.tensorflow.org/install" rel="nofollow noreferrer">Tensorflow portal</a> for more information.</p>
python|tensorflow|anaconda
0
350,056
67,567,310
AttributeError: 'tuple' object has no attribute 'flatten'
<p>can I know how to solve this error.</p> <p>AttributeError: 'tuple' object has no attribute 'flatten'</p> <pre><code>for i in indexes.flatten(): x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) confidence = str(round(confidences[i],2)) color = colors[i] cv2.rectangle(img, (x, y), (x+w, y+h...
<p>I don't know if you solved this already. <strong>You have to check for 0 length indexes before the for loop like this</strong>:</p> <pre><code>if len(indexes) &gt; 0: for i in indexes.flatten(): .... </code></pre> <p>That way it won't enter the for loop when indexes length is 0 which is causing the error...
numpy|cv2
1
350,057
67,281,915
Handle data exception while script execution in Python
<p>I have been working on the dataset cleaning and processing the data for further analysis, I have used different cleaning scripts.</p> <p>My script gets aborted whenever there is any unwanted exceptional data comes up in between the dataset , The script execution gets stuck and rest of the data doesn't gets processed...
<p>Here is one general way to do that, which you can adapt to your specific tasks.</p> <p>Let's say that you need to remove certain characters in a column, which contains strings <strong>and</strong> integers. This will raise an exception:</p> <pre class="lang-py prettyprint-override"><code>df['col_name'] = df['col_nam...
python|pandas
0
350,058
67,505,678
How to loop through json and create a dataframe
<p>I have a JSON file like below, how can I make a dataframe out of this. I want to make the main key an index and subkey as a column.</p> <pre><code>{ &quot;PACK&quot;: { &quot;labor&quot;: &quot;Recycle&quot;, &quot;actual&quot;: 0, &quot;Planned&quot;: 2, &quot;max&quot;: 6 }, &quot;SORT&quot;:...
<p>You can read your json file to dict. Then create dataframe with dict values as data and dict keys as index.</p> <pre class="lang-py prettyprint-override"><code>import json import pandas as pd with open('test.json') as f: data = json.load(f) df = pd.DataFrame(data.values(), index=data.keys()) </code></pre> <pr...
json|pandas
3
350,059
67,586,682
Plot separate pandas dataframe as subplots
<p>I would like to plot pandas dataframes as subplots.</p> <p>I read this post: <a href="https://stackoverflow.com/questions/22483588/how-can-i-plot-separate-pandas-dataframes-as-subplots">How can I plot separate Pandas DataFrames as subplots?</a></p> <p>Here is my minimum example where, like the accepted answer in the...
<p>If you have only one dimension (like 2 x 1 subplots), you can just used axes[0] and axes[1]. When you have two dimensional subplots (2 x 3 subplots for example), you indeed need slicing with two numbers.</p>
python|pandas|matplotlib
0
350,060
67,231,783
How to convert only when subtraction matches?
<p>Imagine you have the following df:</p> <pre><code>d = {'line amount#1': [10, 10], 'line amount#2': [10, 10], 'btw-amount#1': [5, 5],'btw-amount#2': [5,4], 'ExclBTW':[10, 10]} dfcount = pd.DataFrame(data=d) dfcount +----+-----------------+-----------------+----------------+----------------+-----------+ | | line...
<pre class="lang-py prettyprint-override"><code>lines = dfcount.filter(like=&quot;line&quot;) btws = dfcount.filter(like=&quot;btw&quot;) cond = (lines.sum(1) - btws.sum(1)).eq(dfcount.ExclBTW) new_lines = np.where(np.c_[cond], btws, lines) dfcount.loc[:, lines.columns] = new_lines </code></pre> <p>to get</p> <pre><...
python|pandas|dataframe|numpy
2
350,061
67,506,025
Intel RealSense - Align depth and color in two numpy arrays
<p>I am using the Intel RealSense L515. I want to align the depth and color images in two different numpy arrays so that their resolution is the same.</p> <p>Here is my code</p> <pre><code>import pyrealsense2 as rs import numpy as np pc = rs.pointcloud() pipe = rs.pipeline() config = rs.config() config.enable_stre...
<p>Check this librealsense example:</p> <p><a href="https://github.com/IntelRealSense/librealsense/blob/master/wrappers/python/examples/align-depth2color.py" rel="nofollow noreferrer">https://github.com/IntelRealSense/librealsense/blob/master/wrappers/python/examples/align-depth2color.py</a></p> <p>It uses pyrealsense2...
python|numpy|realsense
0
350,062
67,400,540
How to subdivide a datetime interval into multiple (smaller) ones?
<p>Let's suppose we have this dataframe called 'chosen_data' that contains start &amp; end dates &amp; duration of available slots in which we can perform a task (I shall provide a sample so you can reproduce it if you wish). Let's fix the task duration to x = 24h, if my first available slot's duration is 100hours I wa...
<p>Using <a href="https://stackoverflow.com/q/12680754/"><code>Explode value to multiple rows</code></a> :</p> <pre><code>x = 24 chosen_data['values'] = (chosen_data['Duration [Hours]'] - x).apply(lambda a: list(range(1, 1 + a))) result: pd.DataFrame = pd.DataFrame(chosen_data['values'].tolist(), index=chosen_data['Sta...
python|pandas|datetime|for-loop
1
350,063
67,604,383
Reshaping to all value combinations when unstacking a DataFrame
<h2>Background</h2> <p>I have a pandas DataFrame which serves as a register for key-values pairs <code>c</code> and <code>v</code> respective to a plan <code>p</code>:</p> <pre class="lang-py prettyprint-override"><code>In [1]: a = pd.DataFrame({ ...: 'p':[1, 1, 2], ...: 'c':['alpha', 'beta', 'alpha'], ...
<p>you can try <code>groupby</code> and <code>explode</code>:</p> <pre><code>df['nid'] = df.groupby('c')['c'].cumcount() df.set_index(['c', 'nid', 'p']).stack().unstack(0).sort_values('p').groupby(level='p').agg(lambda x: list(set(x))) for col in k.columns: k = k.explode(col) </code></pre> <p>OUTPUT:</p> <pre><code...
python|pandas|pivot-table|data-manipulation
1
350,064
67,211,615
How to draw single pixels in python Pillow from Numpy arrays without producing pixel noise?
<p>I am stuck with a basic problem to which I was not able to find any answer nor solution no matter what I tried. Please help me out and enlighten me, what I am doing wrong :-)</p> <p><strong>Task:</strong></p> <p>Make a Numpy array of Pixels, manipulate them by an algorithm and then print an image from that array.</p...
<p><strong>The solution to this is:</strong> Do not use .jpg data, the compression of this format causes observed pattern.</p> <p>When using .png, the bug was instantly solved! In this image (.png), you can now see that there is 0 pixel noise nor strange artifact patterns, when generating an array-based image as descri...
image|numpy|python-imaging-library|pixel|noise
0
350,065
67,233,819
Perspective & Affine image warping
<p>Say I have 2 transformations:</p> <ul> <li>2D-Affine Transformation (2x3 size)</li> <li>Perspective Transformation(3x3 size)</li> </ul> <p>The purpose of each transformation is to warp ImgA1 to ImgA2</p> <p><a href="https://i.stack.imgur.com/bWXKV.jpg" rel="nofollow noreferrer">This picture</a> shows the values of e...
<p>If you want to chain the warps, it is much simpler (and computationally cheaper) use one single transform equal to the product of the warps. In this case, as you have an affine warp parametrized by a 2x3 matrix, you'll just extend it to 3x3 adding a row of [0, 0, 1]:</p> <pre><code>BestMAffine3x3 = np.vstack((BestM...
python|image|numpy|opencv|computer-vision
0
350,066
67,581,647
Is there a way to integrate matplotlib/Pandas in Abaqus Python?
<p>i have been working with Abaqus python recently to solve some stress/strain problems. I wish to process the data from .odb file directly in python and then output it to excel. But turned out that these 2 libraries are not installed in Abaqus python. Since Abaqus python is a bit outdated. its still using python 2.7 I...
<p>You can use IDEs for development, but not debugging of Abaqus Python. You have to point to the abaqus python library in your IDE for it to recognize the imports. I have an image of how to do that in PyCharm. [Pycharm add Abaqus code library to project][1]</p> <p>You could probably insert &quot;import pdb; pdb.set_tr...
python|pandas|matplotlib|visual-studio-code|abaqus
0
350,067
67,257,249
Accessing a private method within a class is giving a name error saying it is not defined
<p>I'm creating a class with this method that computes for the centroid of a given area from coordinates. This is <a href="https://paste.pythondiscord.com/payiluqutu.rb" rel="nofollow noreferrer">my code</a> so far. And I'm having this error in jupyter notebook : <em>NameError: name '_Lot__getCentroid' is not defined</...
<p>There two reasons why your code will not work:</p> <ol> <li><code>self.centroid = __getCentroid()</code> will work only if <code>__getCentroid()</code> function will be declared outside the class. If it's inside the class, you should call <code>self.__getCentroid()</code></li> <li><code>__getCentroid()</code> is a s...
python|python-3.x|pandas|class|nameerror
1
350,068
67,435,909
Insert value into column if another column's value is present in another dataframe
<p>I want to insert a value into a dataframe column if another column's value is present in another dataframe. I wish to achieve this in a time-efficient manner. I have tried looping using iloc, but it takes too long. I have looked into list comprehension or .apply() but did not find a solution.</p> <p>I have:</p> <pre...
<p>Let's try a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html#pandas-dataframe-merge" rel="nofollow noreferrer">merge</a> left:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df1 = pd.DataFrame({&quot;Col1&quot;: [2, 1, 4, 3, 3, 1, 2, 3, 1]}) df2 = pd.DataFra...
python|pandas
0
350,069
67,434,832
give labels as a numpy array with shape(m,1) or shape(m,) to a model
<p>simply i trying to test a simple Dense neural network without hidden layer.first 50th columns of my data is features and last one is label.</p> <pre><code>X = data[:, :50] y = data[:, -1] input = keras.Input(shape=(50,)) output = keras.layers.Dense(1)(input) model = keras.Model(inputs=input, outputs=output) model.co...
<p>data[:, -1] returns the value of the last column for every row</p> <p>but data[:, 50:] will return the values of the all columns starting from column no 50. Since in your case there are only 50 columns it is same as data[:, -1] but with 1 in the second dimension indicating that only 1 column was picked</p> <p>Assume...
tensorflow|neural-network
0
350,070
67,185,018
Python: Expand one row into multiple rows and make calculations
<p>I have these two observations:</p> <pre><code> Date Confirmed Cases 0 2020-12-27 100 1 2020-12-28 1000 </code></pre> <p>Out of this dataframe, I want to make this table:</p> <pre><code> Date Confirmed Cases 0 2020-12-27 100 1 2020-12-27 280 2 2020-12-27 460 3 2020-12-27 640 4 2020-12-...
<p>Use -</p> <pre><code>rows=4 df1 = pd.concat([df.iloc[0:1], pd.DataFrame([[np.nan]*df.shape[1]]*rows, columns=df.columns), df.iloc[-1:]], ignore_index=True) df1['Confirmed_Cases'] = df1['Confirmed_Cases'].interpolate() df1['Date'] = df1['Date'].ffill() </code></pre> <p><strong>Output</strong></p> <pre><code> ...
python|pandas
1
350,071
67,295,584
Tensorflow model.fit doesn't start
<p>We have the following <code>tensorflow</code> model fitting code.</p> <pre class="lang-py prettyprint-override"><code>data, labels, data_test, labels_test = get_data_and_labels() model = tf.keras.models.Sequential( [ tf.keras.layers.InputLayer(input_shape=(data.shape[1],)), tf.keras.layers.Dense(...
<p>So, the problem wasn't with the actual training, but with the splitting of the train-test records.</p> <p>Here's how we initially did it:</p> <pre class="lang-py prettyprint-override"><code>def split_train_test(data: pd.DataFrame, label: pd.DataFrame, test_part: float = 0.3): size = data.shape[0] test_size =...
python|tensorflow|keras|neural-network
0
350,072
67,464,364
Fastest way to index a very large Pandas dataframe
<p>I have a very large knowledge graph in pandas dataframe format as follows.</p> <p>This dataframe <code>KG</code> has more than 100 million rows:</p> <pre><code> pred subj obj 0 nationality BART USA 1 placeOfBirth BART NEWYORK 2 locatedIn NEWYOR...
<p>I would personally go with <code>isin</code> or <code>query with in</code>.</p> <h2>Pandas doc says:</h2> <h3>Performance of query()</h3> <p>DataFrame.query() using numexpr is slightly faster than Python for large frames. Note: You will only see the performance benefits of using the numexpr engine with DataFrame.que...
python|pandas|performance|indexing
3
350,073
34,696,179
Product of a sequence in NumPy
<p>I need to implement this following function with NumPy - </p> <p><a href="https://i.stack.imgur.com/vBqof.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vBqof.jpg" alt="enter image description here"></a></p> <p>where <code>F_l(x)</code> are <code>N</code> number of arrays that I need to calcula...
<p>Listed in this post is a vectorized solution making heavy usage of <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html" rel="nofollow noreferrer">NumPy's powerful broadcasting feature</a> after extending dimensions of input arrays to 3D and 4D cases with <a href="http://docs.scipy.org/doc/n...
python|arrays|numpy|multidimensional-array|vectorization
2
350,074
34,759,227
TensorFlow CIFAR10 Example
<p>I am trying to run the entire CIFAR10 as is, with data from SVHN.</p> <p><a href="http://ufldl.stanford.edu/housenumbers/" rel="nofollow noreferrer">http://ufldl.stanford.edu/housenumbers/</a></p> <p>I formatted the data in the exact format as the bin file from Alex Krizhevsky's website.</p> <p><a href="http://ww...
<p>I realized the mistake. The SVHN dataset gave the number 0 a value of 10, instead of 0. I made this fatal assumption from the start and it wasted a lot of my time.</p> <p>Given 10 classes, the labels should range from 0-9, inclusive. The error happened because the labels ranged from 1-10.</p> <p><a href="http://uf...
tensorflow
4
350,075
34,595,601
Compare elements within two data frames in pandas
<p>I'm trying to compare two data frames using an if statement, with the output being a new data frame. I'd like to compare data frame A to B and for each element in A that is larger than the corresponding element in B, return 1 else 0.</p> <pre><code>A = 5 3 2 4 7 1 1 9 5 B = 1 2 9 2 5 6 7 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="nofollow"><code>astype</code></a>:</p> <pre><code>#create mask print (A &gt; B) 0 1 2 0 True True False 1 True True False 2 False True True print (A &gt; B).astype(int) 0 ...
python|pandas
1
350,076
34,752,625
NaN is not recognized in pandas after np.where clause. Why? Or is it a bug?
<p>NaN is not recognized in pandas after np.where clause. Why? Or is it a bug?</p> <p>The last line of this code should be "True"</p> <pre><code>In [1]: import pandas as pd In [2]: import numpy as np In [3]: a=pd.Series([1,np.nan]) In [4]: b=pd.DataFrame(["a","b"]) In [5]: b["1"]=np.where( a.isnu...
<p>You can see why if you look at the result of the <code>where</code>:</p> <pre><code>&gt;&gt;&gt; np.where(a.isnull(), np.nan, "Hello") array([u'Hello', u'nan'], dtype='&lt;U32') </code></pre> <p>Because your other value is a string, <code>where</code> converts your <code>NaN</code> to a string as well and g...
python|numpy|pandas
12
350,077
34,662,986
How to resample a Pandas dataframe of mixed type?
<p>I generate a mixed type (floats and strings) Pandas DataFrame df3 with the following Python code:</p> <pre><code>df1 = pd.DataFrame(np.random.randn(dates.shape[0],2),index=dates,columns=list('AB')) df1['C'] = 'A' df1['D'] = 'Pickles' df2 = pd.DataFrame(np.random.randn(dates.shape[0], 2),index=dates,columns=list('AB...
<h3>Use <code>resample</code> and <code>agg</code></h3> <p>Since <code>pandas-1.0.0</code>, the <a href="https://github.com/pandas-dev/pandas/pull/30139" rel="nofollow noreferrer"><code>how</code> and <code>fill_method</code> keywords no longer exist</a>. Besides, the <code>resample</code> method now <a href="https://p...
python|numpy|pandas|time-series
2
350,078
34,653,463
Find the minimum and maximum indices of a list given a condition
<p>I have a list, let's say: </p> <pre><code>list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0] </code></pre> <p>I would like to find the minimum and maximum indices of this list where <code>list_A &gt; 0</code>, i.e. in the above example, it would be 3 and 7. </p> <p>For other lists, which increase monotonically, I have be...
<p>Filter the zipped list with its indixes and take the min and the max: </p> <pre><code>&gt;&gt;&gt; list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0] &gt;&gt;&gt; filtered_lst = [(x,y) for x,y in enumerate(list_A) if y &gt; 0] &gt;&gt;&gt; max(filtered_lst) (7, 1.0) &gt;&gt;&gt; min(filtered_lst) (3, 1.0) </code></pre> ...
python|list|numpy|indices
6
350,079
34,814,904
Python - How to construct a numpy array out of a list of objects efficiently
<p>I am building a python application where I retrieve a list of objects and I want to plot them (for ploting I use <code>matplotlib</code>). Each object in the list contains two properties.</p> <p>For example let's say I have the list rawdata and the objects stored in it have the properties timestamp and power</p> <...
<p>From the <a href="http://matplotlib.org/users/pyplot_tutorial.html" rel="nofollow">matplotlib tutorial</a> (emphasis mine):</p> <blockquote> <p>If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. <strong>In fact, all sequences ...
python|numpy|matplotlib
3
350,080
34,694,965
Image recognition using TensorFlow
<p>I'm new to TensorFlow and I am looking for help on image recognition. Is there an example that showcases how to use TensorFlow to train your own digital images for image recognition like the image-net model used in the <a href="https://www.tensorflow.org/versions/master/tutorials/image_recognition/index.html#image-r...
<p>I would recommend using Google's trained Inception model to do image recognition. Please refer to the example "How to Retrain Inception's Final Layer for New Categories" on tensorflow website. It is at <a href="https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html" rel="noreferrer">https://www...
python|image-recognition|tensorflow
8
350,081
34,435,956
Accelerate the speed of loop over Pandas groupby
<p>I have a big Data Frame in which contains many subsets. For instance,</p> <pre><code>data = pd.read_csv(src) # I read from file gr = data.groupby('name') # group data by some criteria lgr = gr.groups.viewkeys() # find list key for group in lgr: # let say I have 10000 groups __data = gr.get_group(group) # do som...
<p>I would like to put here an approach and it works for me. You can check at <a href="https://github.com/josepm/MP_Pandas" rel="nofollow">https://github.com/josepm/MP_Pandas</a>.</p> <blockquote> <p>The basic idea in a multiprocessor group-by/apply is to assign groups resulting from the group-by step to different...
python|multithreading|pandas
0
350,082
34,768,916
Filling in hourly buckets of activity time - Python
<p>I have a list of devices and their activity time (start time and end time). A device can have one or more activity logs. What I am trying to do is to create a distribution for each device of when the device was active. </p> <p>My current dataframe looks something like this:</p> <pre><code>device_id start_time end_...
<p>You can do it using only pandas like below:</p> <pre><code>x=pd.DataFrame([[1, '03:53', '10:54'],[1, '06:00', '14:00'],[2, '20:29', '06:17']]) x.columns=['device_id', 'start_time', 'end_time'] x['start_time']=pd.to_datetime(x['start_time'],format ='%H:%M') x['end_time']=pd.to_datetime(x['end_time'],format ='%H:%M')...
python|pandas|dataframe|counting|python-datetime
1
350,083
34,498,417
Import text file from geonames using pandas python
<p>I downloaded one of the country datasets from <a href="http://download.geonames.org/export/dump/" rel="nofollow">geonames</a> and I used this line to parse the dataset into columns:</p> <pre><code>data = pd.read_csv("C:/Users/Documents/TR.txt", sep="\t", header = None) </code></pre> <p>But for some reason this do...
<p>Always read the readme.txt file.</p> <p>In this particular case, there are two noteworthy issues going on.</p> <p>1) The elevation (column 15) is expected as an int, but contains blanks. If you specify an int as the datatype, this will generate an error because there is no NaN values for ints. The work around i...
python-3.x|pandas|import|export|geonames
6
350,084
34,640,169
What is the fastest way to insert elements diagonally in 2D numpy array?
<p>Suppose we have a 2D numpy array like:</p> <pre><code>matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] </code></pre> <p>I want to insert a value say 0 diagonally such that it becomes:</p> <pre><code>matrix = [[0, 1, 2, 3], [4, 0, 5, 6], [7, 8, 0, 9], ...
<p>Create a new bigger matrix, that have space left for the zeros. Copy the original matrix to a submatrix, clip and reshape:</p> <pre><code>matrix = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) matrix_new = numpy.zeros((4,5)) matrix_new[:-1,1:] = matrix.reshape(3,4) matr...
python|numpy|matrix|diagonal
3
350,085
34,572,656
Stack columns in pandas dataframe to achieve record format
<p>I have a dataframe with the first column being country name, and the next 12 columns as annual gdp figures (with column headers '1999', '2000', '2001', etc):</p> <pre><code>import pandas as pd gdp = pd.read_csv('gdp.csv') gdp.head() Country Name 1999 2000 2001 2002 2003 \ 0 ...
<p>You could use <code>pd.melt</code> and then <code>sort_values</code>:</p> <pre><code>&gt;&gt;&gt; d2 = pd.melt(df, id_vars="Country Name", var_name="Year", value_name="GDP") &gt;&gt;&gt; d2 = d2.sort_values(["Country Name", "Year"]).reset_index(drop=True) &gt;&gt;&gt; d2.head(10) Country Name Year GDP 0 ...
python|pandas
3
350,086
60,206,776
Figuring out intersection of two different data frames in pandas
<p>I have two data frames. One includes the sales for Product A. The other has the sales for Product B.</p> <p>I'd like to figure out which Customers only bought Product A, which customers only bought Product B, and which customers bought both.</p> <p>DF 1:</p> <pre><code>Cust_ID Industry Product_Type ABC ...
<p>Add <code>indicator=True</code> and <code>suffixes</code> parameters to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a> in first step:</p> <pre><code>Sales = pd.merge(Sales_Prod_A, Sales_Prod_B, ...
python-3.x|pandas
4
350,087
60,296,674
Fastest, most efficient way to aggregate a large dataset in python
<p>Let's say I'm measuring the speed over time of a car moving forward on a single axis, with a new measure every 10 minutes.</p> <p>I have a column in my DataFrame called <code>delta_x</code>, which contains how much the car moved on my axis in the last 10 minutes, values are integers only.</p> <p>Now let's say that...
<p>You can try with following packages which are used for speeding up pandas operation</p> <p><a href="https://github.com/jmcarpenter2/swifter" rel="nofollow noreferrer">https://github.com/jmcarpenter2/swifter</a></p> <p><a href="https://github.com/modin-project/modin" rel="nofollow noreferrer">https://github.com/mod...
python-3.x|pandas|numpy|dataframe|pandas-groupby
0
350,088
60,274,589
Identifying a dateformat and change it into another
<p>I am working with the following piece of data which has a different format of dates and which creates confusion later in the process. The data is like:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-h...
<p>If it is ok to install a dependency then you can use <code>dateparser</code> <a href="https://dateparser.readthedocs.io/en/latest/" rel="nofollow noreferrer">link</a></p> <pre><code>import pandas as pd import dateparser df = pd.DataFrame({'Detection Date &amp; Time': ['03/05/2019 6:33', '06/03/2019 07:23:45 AM']}...
python|python-3.x|pandas|datetime
2
350,089
60,317,769
Load two model's weights into one on Keras
<p>What I'm trying to do is loading Keras layers' weights from <code>model A</code> and <code>model B</code>, both with same architecture, to <code>model C</code>. Let me explain:</p> <p>I know that typical way of loading weights is:</p> <pre><code>modelC.load_weights('name.h5') </code></pre> <p>But by doing this yo...
<p>Something ugly but that shoud work:</p> <pre><code>modelC.load_weights('name.h5') weights1 = np.array(modelC.get_weights()) modelC.load_weights('name2.h5') weights2 = np.array(modelC.get_weights()) modelC.set_weights(0.2 * weights1 + 0.8 * weights2) </code></pre>
python|tensorflow|keras
2
350,090
60,205,448
convert list of nested dicts to dataframe in python
<p>I have a list of nested dictionaries in python. I tried to convert it into a dataframe using:</p> <pre><code>data=pd.DataFrame(list_of_dicts) </code></pre> <p>This converts most of the dicts into columns. However there is still the first column which consists of another list of dicts. Data looks like this:</p> <p...
<p>It works</p> <pre><code>list_of_dicts = [{"qwerty":[1,2,3]}, {"lol":["l","o","l"]}] df = pd.concat([pd.DataFrame(e) for e in list_of_dicts], axis=1) </code></pre>
python|pandas|dictionary
0
350,091
59,936,599
How do I use Decision Tree Regressor on new data? (Python, Pandas, Sklearn)
<p>I've started learning python and machine learning very recently. I have been doing a basic Decision Tree Regressor example involving house prices. So I have trained the algorithm and found the best number of branches but how do I use this on new data?</p> <p>I have the below columns and my target value is 'SalePric...
<p>If you want to know the price (Y) given the independent variables (X) with an already trained model, you need to use the <code>predict()</code> method. This means that based on the model your algorithm developed with the training, it will use the variables to predict the <code>SalePrice</code>. I see you've already...
python|pandas|machine-learning|sklearn-pandas
3
350,092
60,229,551
Keras TLSTM ext Classification differing train and test shape
<p>I am working on a text classification problem in which I am feeding GloVe embeddings into an LSTM network. I have preprocessed the text and perform the following below:</p> <pre><code>max_features = 300 tokenizer = Tokenizer(num_words=max_features, split=' ') tokenizer.fit_on_texts(train['text'].values) train_f = ...
<p>I think that you have an error on the code of your test set :</p> <pre><code>tokenizer.fit_on_texts(test['text'].values) test_f = tokenizer.texts_to_sequences(train['text'].values) </code></pre> <p>should be :</p> <pre><code>tokenizer.fit_on_texts(test['text'].values) test_f = tokenizer.texts_to_sequences(test['t...
python|tensorflow|keras
0
350,093
60,030,390
Add or subtract rows in a pandas column depending on condition
<p>I have this script:</p> <pre><code>df1=pd.DataFrame([["a",10],["a",15],["b",16],["a",11],["b",12],["b",14],["b",17], ["b",19],["a",10]], columns=["col1","col2"]) </code></pre> <p>which gives the following output:</p> <pre><code> col1 col2 0 a 10 1 a 15 2 b 16 3 a 11 4 b 12 5...
<p>You can conditionally assign a sign with <code>np.where</code> and then use <code>cumsum</code>:</p> <pre><code>(np.where(df['col1'] == 'a', 1, -1) * df['col2']).cumsum() + 1000 0 1010 1 1025 2 1009 3 1020 4 1008 5 994 6 977 7 958 8 968 Name: col2, dtype: int64 </code></pre> <p>Same...
python|pandas|dataframe
4
350,094
60,307,973
Rename dataframe in Python for loop
<p>I am trying to rename a dataframe in each iteration of my for loop. For column "item" in the "data" dataframe, I would like to generate dataframes up to the number of unique items in "item" column.</p> <pre><code>for item in data.item.unique(): data+"item" = data[data["item"] == item] </code></pre>
<p>Use a dictionary:</p> <pre><code>frames = {} for item in data['item'].unique(): frames[item] = data[data['item'] == item] </code></pre>
python|pandas|dataframe
2
350,095
60,287,465
Pipeline Loading Models and Tokenizers for Q&A
<p>Hi I'm trying to use 'fmikaelian/flaubert-base-uncased-squad' for question answering. I understand that I should load the model and the tokenizers. I'm not sure how should I do this. </p> <p>My code is basically far</p> <pre><code>from transformers import pipeline, BertTokenizer nlp = pipeline('question-answering...
<p>As stated in <a href="https://github.com/huggingface/transformers/blob/7d22fefd3726ea86902646c8fe23e157f44f0dec/src/transformers/pipelines.py#L320" rel="nofollow noreferrer">the source</a>, there is a specific <code>QuestionAnsweringPipeline</code>. Below example is what I used to successfully load the Flaubert mode...
huggingface-transformers
0
350,096
60,306,817
Converting Object Data type to float data type in pandas results NaN values
<p>I'm doing a classification on the Ecoli data set as an assignment The Data Set is collected from the UCI repository. To create a decision tree classifier I need to convert the object data types into float. While converting the data types changes into float but the string in the column changes all to 'NaN' So that I ...
<p><a href="https://pandas.pydata.org/pandas-docs/version/0.22.0/generated/pandas.to_numeric.html" rel="nofollow noreferrer">pd.to_numeric</a> attempts to convert a sequence to numeric and coerces when told to do so.</p> <ul> <li><code>errors = 'coerce'</code> will convert anything it can to <code>float</code>, and an...
python|pandas|scikit-learn
0
350,097
60,146,981
How do I know my ImageDataGenerator is working?
<p>I am trying to use an <em>ImageDataGenerator</em> to artificially increase my total training images. My images are about 200,000 and the total number of images used per epoch when using <em>model.fit_generator</em> is about 5000+ which is the same number when I am using <em>model.fit</em>. Can I see the total number...
<p>You can plot some image of the data generator:</p> <pre class="lang-py prettyprint-override"><code>#catch a few image of train_generator. x_batch, y_batch = next(train_generator) plt.figure(figsize=(12, 9)) for k, (img, lbl) in enumerate(zip(x_batch, y_batch)): plt.subplot(4, 8, k+1)#4 rows with 8 images. ...
python-3.x|tensorflow|google-colaboratory
0
350,098
60,200,738
Pandas: set all values that are <= 0 to the maximum value in a column by group, but only after the last positive value in that group
<p>I am trying to set all values that are &lt;= 0, by group, to the maximum value in that group, but only after the last positive value. That is, all values &lt;=0 in the group that come before the last positive value must be ignored. Example:</p> <pre><code>data = {'group':['A', 'A', 'A', 'A', 'A', 'B', 'B', ...
<p>Start by adding a column to identify the rows with negative value (more precisely &lt;= 0):</p> <pre><code>df['neg'] = (df['value'] &lt;= 0) </code></pre> <p>Then, for each group, find the sequence of last few entries that have <code>'neg'</code> set to True and that are contiguous. In order to do that, reverse th...
python|pandas
2
350,099
60,075,335
How to add a new column in a loop?
<p>I want to add a column in my dataframe. That column represents the number of columns, per row, with no-nan values.</p> <p>I did this:</p> <pre><code>for i_diagn in range(0,len(df_diagnassoc)): df_diagnassoc['nr_diagnassoc'][i_diagn] = df_diagnassoc.shape[1] - df_diagnassoc.iloc[i_diagn].isnull().sum() </code...
<p>I can't try it without having the data, but I think this is a better way to add a column with the number of non-null values per row:</p> <pre><code>df_diagnassoc['nr_diagnassoc'] = df_diagnassoc.apply(lambda x: x.count(), axis=1) </code></pre> <p><code>apply</code> used on a dataframe with <code>axis=1</code> loop...
python|pandas|for-loop
0