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 |
|---|---|---|---|---|---|---|
372,600 | 34,945,456 | Is it possible to insert a worksheet into an existing workbook using Python? | <p><strong>The Problem</strong>
Creation of fancy reports using Pandas and Python.</p>
<p><strong>Proposed Solution</strong>
Using a template xlsx file containing a template sheet nicely formatted with references to another pre-populated worksheet, delete the pre-populated sheet and insert the new worksheet from panda... | <p>I solved this by creating a template as described and used the solution here:</p>
<p><strong>Proposed Solution</strong> Using a template xlsx file containing a template sheet nicely formatted with references to another pre-populated worksheet, insert the new worksheet from pandas. The template sheet does not lose t... | pandas|xlrd|xlwt | 3 |
372,601 | 35,078,269 | Numpy array documentation slicing rule | <p>In Basic slicing of numpy array <a href="http://docs.scipy.org/doc/numpy-1.5.x/reference/arrays.indexing.html#basic-slicing" rel="nofollow">http://docs.scipy.org/doc/numpy-1.5.x/reference/arrays.indexing.html#basic-slicing</a>,<br/>
I found the following rule which does not work for the example I shown below.</p>
<... | <p>The document is right, but it doesn't means that you can use the calculated start, end index in <code>slice</code> object again. It only tells you the logic to calculate the start & end index. To use the calculated index, you need to generate the index by <code>range()</code>:</p>
<p>Here is an example:</p>
<p... | python|numpy | 2 |
372,602 | 35,244,855 | Using nquad for a double integral | <p>Having a problem here. Here's my code so far:</p>
<pre><code>from scipy import integrate
import math
import numpy as np
a = 0.250
s02 = 214.0
a_s = 0.0163
def integrand(r, R, s02, a_s, a):
return 2.0 * r * (r/a)**(-0.1) * (1.0 + (r**2/a**2))**(-2.45)\\
*(math.sqrt(r**2 - R**2))**(-1.0) * (a_s/(1 + (R-0.02... | <p>If you write <code>integrate.nquad(integrand, [bounds_r(R, s02, a_s, a), bounds_R(s02, a_s, a)])</code>, python is expecting you to affect a value to <code>R</code>. But you didn't because integration is carried out over <code>R</code>.</p>
<p>This syntax should work :</p>
<pre><code>result = integrate.nquad(integ... | python|numpy|scipy|integration | 4 |
372,603 | 35,332,495 | Tensorflow tf.train.Saver saves suspiciously large .ckpt files? | <p>I'm working with a reasonably sized net (1 convolutional layer, 2 fully connected layers). Every time I save variables using <code>tf.train.Saver</code>, the <code>.ckpt</code> files are half a gigabyte each of disk space (512 MB to be exact). Is this normal? I have a Caffe net with the same architecture that requir... | <p>Hard to tell how large your net is from what you've described -- the number of connections between two fully connected layers scales up quadratically with the size of each layer, so perhaps your net is quite large depending on the size of your fully connected layers.</p>
<p>If you'd like to save space in the checkp... | neural-network|tensorflow|conv-neural-network | 6 |
372,604 | 34,910,393 | Trouble installing psycopg2 on Windows | <p>I tried using this:
<a href="http://stickpeople.com/projects/python/win-psycopg/" rel="nofollow">http://stickpeople.com/projects/python/win-psycopg/</a></p>
<p>But had no luck. I even did easy_install psycopg2-2.6.1...(the same name as the 64 bit link on the website).</p>
<p>I am using Windows 8.1 and Python 3.5. ... | <p>Sometimes the installed binaries are not up-to-date.</p>
<p>When it happens, a workaround is to add the PostgreSQL binary path (for instance <code>C:\Program Files\PostgreSQL\9.3\bin</code>) to the path variables.</p>
<p>You may need <a href="http://www.computerhope.com/issues/ch000549.htm" rel="nofollow">this</a>... | python-3.x|pandas|sqlalchemy | 3 |
372,605 | 35,042,510 | Efficiently save to disk (heterogeneous) graph of lists, tuples, and NumPy arrays | <p>I am regularly dealing with large amounts of data (order of several GB), which are stored in memory in NumPy arrays. Often, I will be dealing with nested lists/tuples of such NumPy arrays. How should I store these to disk? I want to preserve the list/tuple structure of my data, the data has to be compressed to conse... | <p>You may like the <a href="https://docs.python.org/3/library/shelve.html" rel="nofollow" title="shelve"><code>shelve</code></a> package. It effectively wraps heterogeneous pickled objects in a convenient file. <code>shelve</code> is oriented more toward a "persistent storage" than classic save-to-file model. </p>
<p... | python|arrays|numpy|serialization|storage | 0 |
372,606 | 35,144,471 | pandas combine_first but always overwrite | <p>Can the following be improved upon?</p>
<p>It achieved the desired result of copying values from <code>df2</code> to <code>df1</code> where the index can be matched. It seems inefficient and clunky.</p>
<pre><code>df1 = pd.DataFrame([[0, 1, 2], [3, 4, 5]], index=pd.MultiIndex.from_tuples(['AB', 'AC']), columns=['X... | <p>Why not use <code>merge</code> ??</p>
<pre><code>>>df3 = pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
>>df3
X Y_x Z Y_y
A B 0.0 1.0 2.0 NaN
C 3.0 4.0 5.0 102.0
D NaN NaN NaN 103.0
>>df3['Y'] = df3['Y_y'].combine_first(df3['Y_x'])
>>df3.dr... | python|pandas|merge | 0 |
372,607 | 35,162,318 | Need to skip line containing "Value Error" | <p>I'm trying to extract some legacy data from a Teradata server, but some of the records contain weird characters that don't register in python, such as "U+ffffffc2".</p>
<p>Currently, </p>
<ol>
<li><p>I'm using pyodbc to extract the data from Teradata</p></li>
<li><p>Placing the results into a numpy array (because ... | <p>If you have only 4-byte unicode points giving an error, this probably may help.
One solution is to register a custom error handler using codecs.register_error, which would filter out error points and then just try to decode:</p>
<pre><code>import codecs
def error_handler(error):
return '', error.end+6
codecs.... | python-3.x|numpy|pandas|teradata|pyodbc | 2 |
372,608 | 34,881,914 | Access numpy array from separate C process using shared memory | <p>I have a 1-D numpy array in memory</p>
<pre><code>>>> x = np.arange(5)
</code></pre>
<p>I want to share this data with a separate and independent (not forked) C process on the same computer using shared memory.</p>
<p>I expect to do something like the following:</p>
<ol>
<li>Allocate a new block of shar... | <p>Here is a minimal example:</p>
<h3>Python</h3>
<pre><code>import os
import posix_ipc
import numpy as np
x = np.arange(1000, dtype='i4')
f = posix_ipc.SharedMemory('test', flags=posix_ipc.O_CREAT, size=x.nbytes, read_only=False)
ff = os.fdopen(f.fd, mode='wb')
ff.write(x.data)
ff.close() # flush doesn't work, b... | python|c|numpy|shared-memory | 3 |
372,609 | 35,062,658 | MoviePy VideoFileClip instance has no attribute 'reader' | <p>I've searched for a few days regarding this issue but have come to no solution. I have a big script (I'm trying to concatenate large number of videos, ~100-500), which is why I was getting the error "Too many files open". Reading Zulko's responses to other issues, I saw that it was necessary to delete each VideoFile... | <p>Zulko himself <a href="https://github.com/Zulko/moviepy/issues/57#issuecomment-52453578" rel="nofollow">writes</a>:</p>
<blockquote>
<p>In the next versions of MoviePy just <code>del clip</code> will suffice.</p>
</blockquote>
<p>This was before version 0.2.2 was released. So it seems like you don't need to do <... | python|numpy|memory-leaks|imagemagick|moviepy | 4 |
372,610 | 35,208,553 | Python/Numpy find length variable spans | <p>Consider a numpy array of shape <code>(n,)</code> <s>that is monotonically increasing. </s></p>
<pre><code>X = np.array([2,3,7,19,110,112,120,140,161])
</code></pre>
<p>My problem is to extract efficiently every span <code>(i,j)</code> such that:</p>
<pre><code>X[i:j].sum() >= v and X[i:j-1].sum() < v
</cod... | <p>Vectorized approach based on <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>
<pre><code># Get cumulative summations
cumsums = X.cumsum()
# Elementwise subtractions between cumsums & its one place shifted version
diffs = cumsums[:,None] ... | python|algorithm|performance|numpy|scipy | 1 |
372,611 | 35,041,597 | Performance degradation of matrix multiplication of single vs double precision arrays on multi-core machine | <p><strong>UPDATE</strong></p>
<p>Unfortunately, due to my oversight, I had an older version of MKL (11.1) linked against numpy. Newer version of MKL (11.3.1) gives same performance in C and when called from python. </p>
<p>What was obscuring things, was even if linking the compiled shared libraries explicitly with t... | <p>I suspect this is due to unfortunate thread scheduling. I was able to reproduce an effect similar to yours. Python was running at ~2.2 s, while the C version was showing huge variations from 1.4-2.2 s.</p>
<p>Applying:
<code>KMP_AFFINITY=scatter,granularity=thread</code>
This ensures that the 28 threads are always ... | python|c|numpy|openmp|intel-mkl | 7 |
372,612 | 31,023,010 | python pandas dataframe unique values appending 'L' to data values | <p>I am running a python file as CGI which is reading a CSV into pandas dataframe. Problem is when I try to get unique values of columns that have just integer values, I get an extra appended 'L' to the data values.</p>
<p>Here's the code.</p>
<pre><code>def Main():
formData = cgi.FieldStorage()
fileName = str(fo... | <p>Here "L" refers to "Long". It shouldn't affect your code other than taking more memory.</p>
<p>example: 1L + 2 = 3L</p>
<p>Also, rather than doing:</p>
<pre><code>unique = pd.unique(df[field])
</code></pre>
<p>try this</p>
<pre><code>unique = df.drop_duplicates('field')
</code></pre> | python|pandas | 5 |
372,613 | 31,160,828 | Modify NumPy array in loops | <p>I have a problem with array manipulation in NumPy. If I create two arrays <code>x</code> and <code>y</code>, and do </p>
<pre><code>x = x - y
</code></pre>
<p>I get what I expect, that is each element of <code>y</code> is subtracted from the corresponding element of <code>x</code>, and thus <code>x</code> is modi... | <p>This is not related with numpy matrix, but how python deal with your </p>
<pre><code>i = i - y
</code></pre>
<p><code>i - y</code> produces a new reference of an array. When you assigns it to name i, so i is not referred to the one it was before, but the newly created array.</p>
<p>The following code will meet yo... | python|arrays|numpy | 4 |
372,614 | 31,191,594 | Sum all items in final row of dataframe | <p>I have the following dataframe:</p>
<pre><code> BBG.XSWX.KABN.S BBG.XETR.TKA.S BBG.XSWX.CON.S BBG.XLON.ISAT.S
date
20/02/2015 -0.004881 0.008011 0.007047 -0.000307
20/02/2015 -0.004881 0.008011 0.007047 -0.000307
17/02/2015 -0.005821 -0.0167... | <p>Just use <code>iloc[-1]</code>:</p>
<pre><code>In [3]:
df.iloc[-1].sum()
Out[3]:
-0.0027269999999999985
</code></pre>
<p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.tail.html#pandas.DataFrame.tail" rel="nofollow"><code>tail</code></a>:</p>
<pre><code>In [8]:
df.tail... | python|pandas | 2 |
372,615 | 31,164,731 | Python Chunking CSV File Multiproccessing | <p>I'm using the following code to split a CSV file into multiple chunks (sourced from <a href="https://stackoverflow.com/questions/8717179/chunking-data-from-a-large-file-for-multiprocessing">here</a>)</p>
<pre><code>def worker(chunk):
print len(chunk)
def keyfunc(row):
return row[0]
def main():
pool = ... | <p>Per <a href="https://stackoverflow.com/questions/31164731/python-chunking-csv-file-multiproccessing/31170795#comment50347868_31164731">the
comments</a>,
we wish to have each process work on a 10000-row chunk. That's not too hard to
to do; see the <code>iter/islice</code> recipe below. However, the problem with usin... | python|csv|numpy|multiprocessing|python-multiprocessing | 15 |
372,616 | 30,791,839 | Is there an easy way to group columns in a Pandas DataFrame? | <p>I am trying to use Pandas to represent motion-capture data, which has T measurements of the (x, y, z) locations of each of N markers. For example, with T=3 and N=4, the raw CSV data looks like:</p>
<pre><code>T,Ax,Ay,Az,Bx,By,Bz,Cx,Cy,Cz,Dx,Dy,Dz
0,1,2,1,3,2,1,4,2,1,5,2,1
1,8,2,3,3,2,9,9,1,3,4,9,1
2,4,5,7,7,7,1,8,3... | <p>You basically just need to manipulate the column names, in your case.</p>
<p>Starting with your original DataFrame (and a tiny index manipulation):</p>
<pre><code>from StringIO import StringIO
import numpy as np
a = pd.read_csv(StringIO('T,Ax,Ay,Az,Bx,By,Bz,Cx,Cy,Cz,Dx,Dy,Dz\n\
0,1,2,1,3,2,1,4,2,1,5,2,1\n\
... | pandas|dataframe|indices|columnname | 15 |
372,617 | 67,346,431 | Python matplotlib polar coordinate is not plotting as it is supposed to be | <p>I am plotting from a CSV file that contains Cartesian coordinates and I want to change it to Polar coordinates, then plot using the Polar coordinates.</p>
<p>Here is the code</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
df = pd.read_csv('test_for_plotti... | <p>For a polar plot, the "x-axis" represents the angle in radians. So, you need to switch x and y, and convert the angles to radians (I also added <code>ax=ax</code>, as the axes was created explicitly):</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import pandas as pd
im... | python|pandas|matplotlib|plot|seaborn | 3 |
372,618 | 67,241,123 | Tensorflow feeding image in memory | <p>I receive an image from network which I convert to a numpy array using <code>fromfile</code> function. Now I want to pass this <code>unit8</code> type array to <code>decode_image</code> of tensorflow v1. How can I achieve that? I do not want to have a file on disk and do it all in-memory.</p> | <p>It turned out that the answer is pretty simple. Supposed <code>nd</code> is the 1-D array returned from <code>fromfile</code> then you can call function <code>tostring</code> and pass that to <code>decode_image</code> of tensorflow.</p> | numpy|tensorflow | 0 |
372,619 | 67,185,860 | How to find the first result based on summed rows in a data frame? | <p>I have a data frame that looks like this.</p>
<pre><code>import pandas as pd
# intialise data of lists.
data = {'ID':[101762, 101762, 101762, 102842, 102842, 106755, 106755, 106755, 108615, 108615, 113402, 113402, 114711, 114711],
'Year':[2019, 2019, 2020, 2019, 2020, 2019, 2019, 2020, 2019, 2020, 2019, 2... | <pre><code># groupby ID and year and get the sum
g = df.groupby(['ID', 'Year'], as_index=False)['Amount'].sum()
# assign a new column called maxval to the max value of each groupped ID and filter
g[g['Amount'] == g.assign(maxval=g.groupby('ID').transform(max)['Amount'])['maxval']]
ID Year Amount
0 1017... | python|python-3.x|pandas|dataframe | 1 |
372,620 | 67,246,156 | How to split pandas data frame by repeating rows? | <p>I have the df like this:</p>
<pre><code>1 a 12
2 a 3
3 b 45
4 b 34
5 b 23
</code></pre>
<p>and I need to split it to two df like this:</p>
<pre><code>1 a 12
2 a 3
</code></pre>
<p>and</p>
<pre><code>3 b 45
4 b 34
5 b 23
</code></pre>
<p>Someone know any reasonable quick way?</... | <p>Try with</p>
<pre><code>d = {x : y for x , y in df.groupby('col')}
</code></pre> | pandas|dataframe | 0 |
372,621 | 67,444,863 | How to pass buffer address to c? | <p>I want to pass the address of a numpy array buffer to c function,
My C function looks like:</p>
<pre><code>void print_float_buff(void *buff)
{
float *b = (float *)buff;
printf("Float Data: %f, %f, %f,\n", b[0], b[1], b[2]);
}
</code></pre>
<p>In python my code is:</p>
<pre><code>import numpy as np
... | <p>If you specify <code>.argtypes</code> correctly, ctypes will tell you the type is wrong. Below requires a one-dimensional array compatible with <code>c_float</code>:</p>
<p>test.c</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# ... | python|python-3.x|numpy|ctypes | 1 |
372,622 | 67,559,783 | I am trying to build a object detection using Mask RCNN and get an error when i call MaskRCNN method | <p>I am trying to use matterport's keras implementation of Mask RCNN. When I call the function modellib.MaskRCNN, I get below error.</p>
<p>'''maskrcnnModel = modellib.MaskRCNN(mode='training', config=config, model_dir='/rootdir' )'''</p>
<p>/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/type_spec.p... | <p>Finally after lot of surfing, I found another repository in github that helped me to move forward. I am able to move ahead to train the model. Thanks to akTwelve for the great work to update the matterport's base code to work for TF 2.4.1 and Kears 2.4.0. You can get the github link @ <a href="https://github.com/akT... | tensorflow|object-detection | 1 |
372,623 | 67,319,626 | Run python function on groups of rows of dataframe column, return dictionary | <p>I am working with this df:</p>
<pre><code>data = {'material': [1,1,1,1,2,2,2,2,3,3,3,3], 'week': [5,6,7,8,5,6,7,8,5,6,7,8], 'demand': [20,5,0,15,4,3,8,9,15,74,12,3]}
df = pd.DataFrame.from_dict(data)
</code></pre>
<p>I have a function that iterates over an input list, calculates the mean and removes the first elemen... | <p>Create an empty dictionary and keep adding to it for each unique value</p>
<pre><code>l = df.material.unique()
d = {}
for i in l:
d[i] = get_means(df.loc[df['material'].eq(i),'demand'])
</code></pre>
<hr />
<pre><code>print(d)
{1: ([4, 3, 2], [10.0, 6.666666666666667, 7.5]),
2: ([4, 3, 2], [6.0, 6.666666666666... | python|pandas | 1 |
372,624 | 67,489,157 | How to calculate the correct change by item group? | <p>I have a list of products with the daily price that changes every day. I would like to calculate the price change by product by resampling on a different time basis (monthly, yearly, ...) but I get a calculation error on the first time series.</p>
<p>Here is an example of my dataframe with 2 products:</p>
<pre><cod... | <p>Perform additional <code>groupby</code> operation after calculating the rolling <code>mean</code> to calculate the percent change</p>
<pre><code>avg = df_change.groupby('symbol').resample('2D').mean()
avg_change = avg.groupby('symbol').pct_change()
</code></pre>
<p>Alternatively you can <code>resample</code> , <code... | python|pandas | 0 |
372,625 | 67,460,405 | Indexing using value from another DataFrame | <p>pandas version 1.1.3.</p>
<p>I am working with two dataframes (form csv's) in pandas, one containing the data I'm analysing, the other containing labels. Both contain a column with identification numbers. I have set the row indeces of dataframe 2 as the identification numbers. I am using a nlp processing library to ... | <p>When you use:</p>
<pre><code>df2[[index, 'hypothesis']] = 1
</code></pre>
<p>pandas searches for the passed <code>index</code> value in the column index and is unable to find <code>A2</code> among your column names. In your case, you are trying to find those values in the row index of <code>df2</code>, so you need ... | python|pandas|indexing | 0 |
372,626 | 67,497,271 | Creating new dataframe column using string filter of other column | <p>Below is the dataframe with column name 'Address'. I want to create a separate column 'City' with specific string using filter from Address column.</p>
<pre><code>df1
Serial_No Address
1 India Gate Delhi
2 Delhi Redcross Hospital
3 Tolleyganj Bus Stand Kolkata
4 Kolkata Howrah
5... | <p>Let us try <code>str.extract</code></p>
<pre><code>df['new'] = df.Address.str.extract(('(Delhi|Kolkata)'))[0]
</code></pre> | python|pandas|dataframe|if-statement|append | 2 |
372,627 | 67,538,710 | how to replace the values of one column by taking the duplicated values applied on the other column | <p>so i have a dataframe like</p>
<pre><code> name age year
0 ram 25 97
1 syam 12 95
2 jodu 15 96
3 ram 23 98
4 jodu 20 99
5 shyam 18 10
</code></pre>
<p>from the dataframe i see that the duplicate names e.g ram or shyam has different ages and different years. i want to raplac... | <p>Try groupby transform:</p>
<pre><code>df = df.assign(age = df.groupby('name')['age'].transform(min)) # here assign will return a new df
# or df.age = df.groupby('name')['age'].transform(min)) # change on same dataframe
</code></pre> | python|pandas|dataframe|replace|data-wrangling | 3 |
372,628 | 67,266,153 | how to convert generated data into pandas dataframe | <pre><code>from sklearn.datasets import make_classification
df = make_classification(n_samples=10000, n_features=9, n_classes=1, random_state = 18,
class_sep=2, n_informative=4)
</code></pre>
<p>after creating the data. it is tuple and after converting tuple into pandas dat... | <p>The first entry of the tuple contains the feature data and the the second entry contains the class labels. So if you want to make a <code>pd.dataframe</code> of the feature data you should use <code>pd.DataFrame(df[0], columns=["1","2","3","4","5","6","... | python|pandas|dataframe|machine-learning|scikit-learn | 1 |
372,629 | 67,574,162 | Creating a lagged variable subject to some condition in a pandas dataframe | <p>i am attempting to create a lagged feature as part of my dataframe.</p>
<p>I have done this using the shift() function and my dataframe has the following updated format:</p>
<pre><code>
df1[515:525]
Out[20]:
store_id units_sold Data_lagged
144378 8091 45 18.0
145533 8091 ... | <p>This may be redundant, but I think it can be solved in one line.
The following code:</p>
<pre><code>df1.Data_lagged = df1.Data_lagged.where([True] + [a == b for a, b in zip(df1.store_id[:-1], df1.store_id[1:])], 0.)
</code></pre> | python|pandas | 0 |
372,630 | 67,248,740 | How can we flatten the below structure using pandas dataframe | <p>Sample JSON for testing: I loaded this into a <code>dataframe</code> using <code>pandas</code>: There are many keys but I only need <code>Id</code> and <code>Events</code> so I loaded this into a separate <code>dataframe</code>.</p>
<p>I need to iterate for each <code>id</code>(ex:abcd) and extract the events for th... | <p>One possible solution is to loop through <code>events</code> key then special handle <code>origin</code> and <code>destination</code> key:</p>
<pre class="lang-py prettyprint-override"><code>import json
import numpy as np
import pandas as pd
with open('test.json') as f:
data = json.load(f)
res = []
for d in d... | python|json|pandas|python-requests | 0 |
372,631 | 67,592,439 | Pandas DF: Formatting Hyphenated Last Names | <p>I'm building a python module to help me format text for work. I work with application and survey data that I'm importing into our company's CRM so I'm trying to turn something like " louis-dreyfus " into "Louis-Dreyfus" where the name is capitalized in the beginning and after the hyphen. My code ... | <p>You can try this:</p>
<p><strong>Sample data:</strong></p>
<pre><code>import pandas as pd
df = pd.DataFrame({'names':[" louis-dreyfus ", "some-name ", " another-more-complex-name "]})
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>def format_names(s):
return '-'.join... | python|pandas|string|format | 1 |
372,632 | 67,300,217 | numpy array indexing: different columns of each row | <p>I am struggling with np array indexing.</p>
<p>Lets suppose we have an array called a.</p>
<pre><code>import numpy as np
a = np.ones((10000,100))
</code></pre>
<p>And another array called <code>idx</code></p>
<pre><code>idx = np.random.randint(low=0, high=a.shape[1], size=a.shape[0])
</code></pre>
<p>Now what I want... | <p>You can try:</p>
<pre><code>import numpy as np
a = np.ones((10000, 100))
a[:, 0] += 1
np.random.shuffle(np.transpose(a))
print(a)
</code></pre>
<p>Explanation:</p>
<ol>
<li>Import the necessary library:</li>
</ol>
<pre><code>import numpy as np
</code></pre>
<ol start="2">
<li>Define your array of ones:</li>
</ol>
<... | python|arrays|numpy|indexing | 0 |
372,633 | 67,565,423 | Getting death date of a person from a wikipedia link using BeautifulSoup | <p>I'm trying to scrape the dates a person died from a bunch of wikipedia links I have in a csv filen and save it as another column.
It has both people who are alive currently and those who have died. How do I scrape this data for the people who have a died date in the wikipedia article?</p>
<p>Below is the code that I... | <pre><code>from bs4 import BeautifulSoup
import requests
import pandas as pd
df = pd.read_csv('wiki_links.csv')
#print(df.head())
for index, row in df.iterrows():
req= requests.get(row['url'])
soup = BeautifulSoup(req.content, features='lxml')
dates = soup.select('table.infobox td.infobox-data span')
... | python|pandas|dataframe|beautifulsoup | 1 |
372,634 | 67,557,856 | python need to convert a "linspace" into something more "logarithmic" | <p>Forgive me, I'm always been very bad at math, now trying to learn some python (and some math aswell) by coding.</p>
<p>I have this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
whole = 1 # percentage: 1 = 100%, 0.1 = 10% ecc
nparts = 10 # how many "steps" we want to use
origin = 100 ... | <p>You can pass any <code>linspace</code> to <code>np.log</code>. This will give the logarithm of each point. To get the result within certain bounds, you can use a linear transformation: divide by the largest value and multiply with the desired range, perhaps add a baseline value.</p>
<p>For example:</p>
<pre class="l... | python|numpy | 3 |
372,635 | 67,190,520 | Getting NotImplementedError by using pd.eval() method | <p><strong>Sample data:</strong></p>
<pre><code>#importing libraries
import pandas as pd
from ast import literal_eval
#sample data
data=['{"level":0,"side":"Ask","price":"13745.75000","volume":"2"}',
'{"level":1,"side":"... | <p>I think <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.eval.html" rel="nofollow noreferrer"><code>pandas.eval</code></a> is used mainly for arithmetic operations in pandas, so cannot be used for parsing <code>string</code>s repr of dictionaries like <code>ast.literal_eval</code>.</p>
<p>Fo... | python|pandas | 1 |
372,636 | 67,545,518 | Fill NaN values within groups by number in pandas | <p>I have a dataframe such as</p>
<pre><code>Groups NAME VALUES
G1 A 1
G1 B 2
G1 C 3
G1 C 3
G2 D NaN
G2 E NaN
G2 D NaN
G3 F NaN
G3 G NaN
G3 H NaN
G4 I 8
G4 I 8
G4 J 89
G4 K 65
</code></pre>
<p>And I would simply like ... | <p>I would first select the unique NAMEs for the NaN rows:</p>
<pre><code>m = df['VALUES'].isna()
names = df.loc[m, 'NAME'].unique()
</code></pre>
<p>then create a mapping for these:</p>
<pre><code>mapping = dict(zip(names, list(range(1,len(names)+1))))
</code></pre>
<p>then fill your VALUES for the NaN rows with the m... | python|python-3.x|pandas | 2 |
372,637 | 67,260,979 | How to output Prediction Values into an Excel File? | <p>new to scikit-learn and I want to take the prediction values and convert it back to text and output it into an excel file.</p>
<p>The way the project is setup is it takes a row of strings and predicts whether or not the column is a certain category (there is approximately 5 categories).</p>
<div class="s-table-conta... | <p>You can do this:</p>
<pre><code>import pandas as pd
CSV = pd.DataFrame({
"Prediction": y_pred
})
CSV.to_csv("prediction.csv", index=False)
</code></pre>
<p>The file will be named "prediction.csv" and will be saved in your source code file directory.</p>
<p>Update:</p>
<pre><code>im... | python|pandas|sklearn-pandas | 0 |
372,638 | 67,251,172 | How to apply Max function between rows on 2D list in pandas grouped dataframe | <p>I have a dataframe similar to the following where "data" is a 2D array:</p>
<pre><code>id grouping_val data
1 a [[0, 1], [1, 0]]
2 a [[1, 0], [0, 1]]
3 b [[2, 0], [3, 0]]
4 b [[0, 4], [4, 5]]
</code></pre>
<p>How can I group them by "grouping_val" a... | <p>You can <a href="https://numpy.org/doc/stable/reference/generated/numpy.stack.html" rel="nofollow noreferrer"><strong><code>np.stack()</code></strong></a> the grouped arrays and take their <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.max.html" rel="nofollow noreferrer"><strong><code>max()<... | python|pandas|pandas-groupby | 4 |
372,639 | 67,273,903 | Unit test Tensorflow Transform operations | <p>I want to do unit test on my functions that contains Tensorflow Transform operations. Something like this:</p>
<pre><code>@pytest.mark.parametrize("inputs,expected_result",
[(
tf.linspace(start=0, stop=10, num=10),
tf.linspace(start=0, stop=1, num=10),
)]
)
def test_tft_scale(inputs... | <p>So you are trying to convert Python eager code into graph-compatible TensorFlow ops which you can do so using the <code>AutoGraph</code> library. You can use this by simply adding in the <code>@tf.function</code> decorator and chaining it with your <code>@pytest.mark.parametrize()</code> decorator. <code>@tf.functio... | python|tensorflow | 1 |
372,640 | 67,193,285 | How to read files from folder based on column value of dataframe | <p>I have column with some numbers , for each number i want to check in folder if this match to any file name in folder read this file ,if not match number go for next ...</p>
<pre><code>df=pd.DataFrame({'x':['2000','5000','10000']})
</code></pre>
<p>files_folder:</p>
<pre><code>P2000.csv
P4000.csv
P5000.csv
P6000.csv
... | <p>Use <code>glob</code> with test substring in <code>any</code> with list comprehension:</p>
<pre><code>import glob
df=pd.DataFrame({'x':['2000','5000','10000']})
for f in glob.glob('files_folder/*.csv'):
if any([x in f for x in df['x']]):
print (f)
files_folder\P2000.csv
files_folder\P5000.csv
</code><... | python-3.x|pandas|numpy|pandas-groupby | 1 |
372,641 | 67,407,508 | return 2 values from a function for two different columns with pandas in python | <p>i have applied a function to a column of my dataframe, this column contains the date with year, month, day and hour, minute, second and what i would like to do is to separate year, month, day and put it in a column and hour, minute, second put it in another column at the same time, my code looks like this</p>
<pre><... | <p>You can convert your tuple output to list using <code>.tolist()</code> and then use <code>pd.DataFrame()</code> to construct the dataframe with the 2 required columns, as follows:</p>
<pre><code>concatenar[["pubDate_date","pubDate_time"]] = pd.DataFrame(concatenar["pubDate"].apply(chang... | python|pandas | 3 |
372,642 | 67,404,972 | Filter text in Dataframe column (python/Pandas) | <p>Does anybody know how to remove such kind of "strange" <strong>characters</strong> from text column in python?</p>
<p><a href="https://i.stack.imgur.com/Vza0d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vza0d.png" alt="enter image description here" /></a></p>
<pre><code>Id tweet_id ... | <p>The simplest way to do it would be to use a lambda function:</p>
<pre><code>df.text.apply(lambda x: ''.join(filter(str.isascii,x)))
</code></pre>
<p>for larger datasets, regex, e.g., re.sub() is recommended.</p> | python|pandas|dataframe|text|filter | 0 |
372,643 | 67,601,997 | Scipy "masked arrays are not supported" error | <p>I am trying to calibrate a model using pykalman and the scipy optimiser. For some reasons scipy seem to think that my input is a masked array, but it is not. I have added the code below:</p>
<pre><code>
k = 0.00000000000001 #small sarting value
T = np.array([1, 2, 3, 4, 5] , dtype=int) #maturities
delta... | <p>I found the solution, which involves a small change in the utils.py file in the pykalman library (line 73):</p>
<pre><code> try:
cv_sol = solve_triangular(cv_chol, (X - mu).T, lower=True).T
except ValueError:
cv_sol = np.linalg.solve(cv_chol, (X - mu).T).T
</code></pre>
<p>Sour... | python|numpy|scipy|pykalman | 2 |
372,644 | 67,196,248 | Pandas Group By and Transform by condition and apply to whole column | <p>I have the following dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Value': [0, 1, 2,3, 4,5,6,7,8,9],'Name': ['John', 'John', 'John','John', 'John','John','John','John','John','John']
,'City': ['A', 'B', 'A','B', 'A','B','B','A','B','A'],'City2': ['C', 'D', 'C','D', 'C','D','D',... | <p>One trick is replace not matched values to missing values instead filtering:</p>
<pre><code>print (df.assign(Value = df['Value'].where(df['City2']== 'C')))
Value Name City City2
0 0.0 John A C
1 NaN John B D
2 2.0 John A C
3 NaN John B D
4 4.0 John A C
5 ... | python|pandas | 2 |
372,645 | 67,286,034 | Tokenizing a dataframe using Tensorflow and Transformers | <p>I have a labeled dataset in a pandas dataframe.</p>
<pre><code>>>> df.dtypes
title object
headline object
byline object
dateline object
text object
copyright category
country category
industry category
topic category
file object
dtype: obje... | <p>In short, yes. You also don't want to tokenize the entire, but just a numpy array of the text column. The steps missing are shown below.</p>
<pre><code># Create new index
train_idx = [i for i in range(len(train.index))]
test_idx = [i for i in range(len(test.index))]
val_idx = [i for i in range(len(val.index))]
# Co... | python|dataframe|tensorflow|tokenize|huggingface-transformers | 1 |
372,646 | 67,357,795 | Do we have lower performance and accuracy than when not using `pytorch.nn.Sequnetial` and if yes, why? | <p>I was checking out <a href="https://youtu.be/hlv79rcHws0?t=1731" rel="nofollow noreferrer">this</a> video where Phil points out to this fact that using <code>torch.nn.Sequential</code> is faster than not using it. I did quick google and came across <a href="https://discuss.pytorch.org/t/why-use-sequential-or-not-wil... | <p>I'm not familiar with what kind of optimizations the python interpreter does, but I'd guess it is very limited.</p>
<p>But the claim that one method is more accurate than another is completely nonsense. If you look at the implementation of <a href="https://pytorch.org/docs/stable/_modules/torch/nn/modules/container.... | python|machine-learning|neural-network|pytorch | 2 |
372,647 | 67,290,329 | Problem with Tensorflow lite conversion with dilation_rate !=1 | <p>I have the problem when importing the Tensorflow lite-model (last line code below) tf.lite.Interpreter, i get an error (see below) when the dilation_rate!=1. Since the code has to run on a embedded device, hence there will be many steps after this piece of code, the shortest way to get it work, would be a work-aroun... | <p>The recent TF versions including TF 2.5 rc version and TF nightly version have a fix for supporting dilation rate != 1 in the TFLite conversion. Please try out your code at the recent TF versions.</p> | interpreter|tensorflow-lite | 0 |
372,648 | 67,378,655 | How to deal with the unlabeled nodes in Pytorch Geometric? | <p>I have a dataset on my own, and the dataset contains two classes, let's say 0 and 1. Besides, there is a large part of nodes which class is unlabeled. My goal is to predict these unlabeled nodes using GCN. But I am confused about how to deal with these unlabeled nodes in Pytorch Geometric.</p>
<p>As far as I can thi... | <p>That very much depends on your use case and the data!</p>
<p><strong>Case 1 - Graph Autoencoder</strong></p>
<p>For this case let's assume the task is to find similar tweets. A way of doing this is to train a Graph Autoencoder (see <a href="https://github.com/pyg-team/pytorch_geometric/blob/master/examples/autoencod... | pytorch|pytorch-geometric | 0 |
372,649 | 67,226,612 | Apply a function to each cell of a pandas dataframe using information from a particular column | <p>I want to expand the list entries of a dataframe using the information in column <code>i</code>:</p>
<pre><code>i s_1 s_1 s_3
2 [1, 2, 3] [3, 4, 5] NaN
1 NaN [0, 0, 0] [2]
</code></pre>
<p>The i value just indicates how often the last value of each list should be copied:</p>
<pre><co... | <p>You can try to extend the lists inplace:</p>
<pre><code>for col in df.loc[:, "s_1":]:
m = df[col].notna()
for i, v in zip(df.loc[m, "i"], df.loc[m, col]):
v.extend([v[-1]] * i)
df.loc[~m, col] = 0
</code></pre>
<hr />
<p>Benchmark:</p>
<pre class="lang-py prettyprint-overrid... | python|pandas|numpy|apply | 3 |
372,650 | 67,277,813 | Saving TensorFlow Neural Network KFold Cross Validation model | <p>I am working on a sample Neural Network with KFold cross validation using TensorFlow 2.4.1. and sklearn.
Unfortunately, I am not able to save the model.</p>
<pre><code>def my_model(self,):
inputs = keras.Input(shape=(48, 48, 3))
x = layers.Conv2D(filters=4, kernel_size=self.k_size, padding='s... | <p>Yea your code has some typo:</p>
<pre class="lang-py prettyprint-override"><code>trained_model = trained_model.history # This is your train stats, so your train stats is a dictionary
model.save(f'model/saved_models/dummy_model_{date}') # This is what your saving the actual model
</code></pre> | tensorflow|machine-learning|scikit-learn|deep-learning | 0 |
372,651 | 67,533,336 | Implementing Cosine similarity loss gives different answer than Tensorflow's | <p>I was implementing cosine similarity loss with my custom python script but it gives me a very different answer than TensorFlow. First see <code>TensorFlow's</code> answer:-</p>
<pre><code>y_true = [[0., 1.], [1., 1.]]
y_pred = [[0., 1.], [0., 1.]]
loss = tf.keras.losses.CosineSimilarity()
print(loss(y_true, y_pred).... | <p>After going through some documentation,</p>
<p>results from <code>tf.keras.losses.CosineSimilarity()</code>and your function differs for two reasons:</p>
<ol>
<li>As presented in the example <a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/CosineSimilarity" rel="nofollow noreferrer">here</a>, in ... | python|tensorflow|keras | 2 |
372,652 | 67,402,007 | pyodbc can read the column names from a table, but a query on the table raises a does not exist error | <p>I'm trying to query a table an AWS athena via pyodbc. I have succesfully created a connection and can even read the column names via pyodbc, but when i try and query the table, it apparently does not exist.</p>
<pre><code>import pyodbc
import pandas as pd
cnxn = pyodbc.connect('DSN=databaseDSN;UID=user;PWD=passwor... | <p>I've solved my own problem, my table was within a schema.</p>
<p>I fixed it with:</p>
<pre><code>sql = "Select * From schema.tablename"
data = pd.read_sql(sql,cnxn)
</code></pre> | python|sql|pandas|pyodbc|amazon-athena | 0 |
372,653 | 67,524,236 | Duplicates when appending string to list from dataframe with common column value | <p>Beginner here, I am trying to isolate the names of neighborhoods from a dataframe of Toronto based on a cluster value I've assigned them. Instead of a list of 3 unique items, I end up with a list 2363 items long.</p>
<pre><code>Neigh_List = []
for n in toronto_merged['Cluster Labels']:
if n == 7 :
x... | <p>In general, looping over Pandas dataframes should be avoided for larger datasets (~1000+) as Pandas built-in vectorized functions are often faster (<a href="https://stackoverflow.com/questions/54028199/are-for-loops-in-pandas-really-bad-when-should-i-care">See this other stackoverflow post</a>).</p>
<p>You could try... | python|pandas | 2 |
372,654 | 67,191,350 | Selecting specific rows of a pandas data frame using a list | <p>Say I have a simple dataframe with the names of people. I perform a <code>groupby</code> on <code>name</code></p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col1' : [1,2,3,4,5,6,7], 'name': ['George', 'John', 'Tim', 'Joe', 'Issac', 'George', 'Tim'] })
df1 = df.groupby('name')
</code></pre>
<p><strong>Ques... | <p>If you have to do the filtering after the grouping -</p>
<pre><code>for group, group_df in df1:
if group in ['John', 'Tim', 'George']:
print(group_df)
# col1 name
# 0 1 George
# 5 6 George
# col1 name
# 1 2 John
# col1 name
# 2 3 Tim
# 6 7 Tim... | python|pandas|dataframe | -1 |
372,655 | 67,259,852 | How can I input single Image in CNN trained model? | <p>I trained the CNN model and trying to test with a single image.
I saved the .h5 file and tried to test with a single image.
But I got an error message as below.</p>
<p><strong>ValueError: Input 0 of layer sequential_1 is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input ... | <p>You've trained a model with an RGB image (3 channel) but tried to do inference on Grayscale. Try this</p>
<pre><code>face_image = cv2.resize(face_image, (48,48))
face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)
face_image = np.reshape(face_image, [1, face_image.shape[0], face_image.shape[1], 3])
predicted_cl... | python|tensorflow|image-processing|deep-learning|conv-neural-network | 1 |
372,656 | 67,506,638 | pandas to pyspark dataframe vs jdbc connection to pyspark dataframe | <p>I'm trying to improve the performance of my code by using the spark_session.read.format("jdbc") function. I got two different approaches:</p>
<ol>
<li><p>Using the jdbc connection to a oracle table such like this:</p>
<pre><code> testDF = spark_session.read.format("jdbc") \
.option("url"... | <p>I finally managed to make it faster, from 1 hour to 9 minutes. I was testing the code and what worked for me was to play with the values of:</p>
<pre><code> option("numPartitions", X)
option("lowerBound", Y)
option("upperBound", Z)
</code></pre>
<p>For the number of partiti... | pandas|dataframe|apache-spark|pyspark | 0 |
372,657 | 67,363,409 | call functions on a specific level of a numpy ndarray without for loops | <p>suppose a numpy ndarrary</p>
<pre><code>arr
</code></pre>
<p>has shape (100,100,5,5)</p>
<p>The following codes work:</p>
<pre><code>result=np.zeros((arr.shape[0], arr.shape[1], 10))
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
v=arr[i,j].flatten()
hist, bi= np.histog... | <p>Hmm, I thought <code>apply_along_axis</code> would help, but it doesn't seem to make much of a difference, at least at the problem sizes of interest to you. Maybe there's overhead in <code>myhist</code>.</p>
<p>See the code below.</p>
<pre><code>import numpy as np
import time
low = 0.0
high = 3.0
bins = 10
... | numpy | 0 |
372,658 | 67,360,505 | Is there a way to combine the 1st index of a list if the 0 values in the list are the same? | <pre class="lang-py prettyprint-override"><code>import csv
import pandas as pd
from matplotlib import pyplot as plt
# Declaring workout data to df variable
df = pd.read_csv('workout.csv')
# Declaring name variable and storing name data into it
name = df['name']
# Calculating the mass moved
moved_mass_data = df['sets... | <p>In the expected output the Incline Fly should be ('Incline Fly',3520), if yes,</p>
<p>This code should work-></p>
<pre><code>b = {}
for i in exercise_moved_mass_list:
try:
b[i[0]]+=i[1]
except:
b[i[0]]=i[1]
c = [(x, y) for x, y in b.items()]
</code></pre>
<p>Output:</p>
<pre><code>[('Facepull', 480),... | python|pandas | 0 |
372,659 | 67,411,621 | drop 100 percent match duplicates in pandas | <p>This is my CSV sample:</p>
<pre><code>Channel|Store_ID|Store_Code|Store_Type|Order_ID|Order_Date|Member_ID|Member_Tier|Coupon_ID|Order_Total|Material_No|Material_Name|Size|Quantity|Unit_Price|Line_Total|Discount_Amount
ECOM|ECOM|ECOM|ECOM|RBSKA1907002995|2019-07-23 00:06:00||||1064.00|DM7564|SPT Full Zip|750|2.00|39... | <p>Since you are setting <code>keep=False</code> all duplicates are being dropped on the <code>df.drop_duplicates</code> method, you need to set keep="first" or "last" in order to keep those duplicate entries.</p> | python|pandas|dataframe | 2 |
372,660 | 67,555,011 | Rearrange Pandas Dataframe using Pandas.Melt to take multiple columns at once? | <p>I have a pandas Dataframe set out as follows. There are in fact 192 X,Y,Z triplet columns, this is just the first three.</p>
<pre><code> shot V0e V0n V0d S0_Pe S0_Pn S0_Pd S0_Se S0_Sn S0_Sd
0 1001 457950.4 7331695.2 2.5 458004.5 7331794.1 2.2 457950.4 733169... | <p>You can use <a href="https://pyjanitor.readthedocs.io/reference/janitor.functions/janitor.pivot_longer.html#janitor.pivot_longer" rel="nofollow noreferrer">pivot_longer</a> from <a href="https://pyjanitor.readthedocs.io/index.html" rel="nofollow noreferrer">pyjanitor</a> to abstract the process. Your columns have ... | python|pandas|dataframe|pandas-melt | 1 |
372,661 | 67,392,523 | Two Seaborn plots on one twinx figure become distorted | <p>I saw variations of this question asked several times, but I don't think any of the variations I saw fixes it (other than "use matplotlib for combo-plots", but I'd appreciate help understanding <em>why</em> should I do that).</p>
<pre><code>df1 = pd.DataFrame({'height': {0: 161, 1: 173, 2: 168, 3: 185, 4: ... | <p>If you plot them separately and check their <code>xlim</code>, you can see seaborn shifts the bar plot's <code>x</code> values down to 0 (the years are displayed separately via <code>xticklabels</code>):</p>
<pre class="lang-py prettyprint-override"><code>ax = sns.barplot(x='year', y='weight', hue='sex', data=df2)
p... | pandas|seaborn | 2 |
372,662 | 67,308,810 | How to "flatten" a Pandas dataframe? | <p>I have a Pandas dataframe <code>df</code> that looks as follows:</p>
<pre><code> Expenses
date manufacturer department
2021.01.03 Mercedes Service 541
Sales 879
... | <p>If 'date', 'manufacturer' and 'department' are part of the index. This might help you:</p>
<p><code>df = df.reset_index()</code></p> | python|pandas | 2 |
372,663 | 67,365,218 | CUDA version of package not importing? | <p>Firstly, I installed torch 1.1.0, and then I installed its' dependencies. So, I can import torch_scatter 1.2.0 however I get this error when importing torch_scatter.scatter_cuda:</p>
<pre><code> import torch_scatter.scatter_cuda
ModuleNotFoundError: No module named 'torch_scatter.scatter_cuda'
</code></pre>
<p>I ha... | <p>As pointed out by phd - it looks like the setup.py file of pytorch_scatter checks for and uses an available cuda installation automatically.</p>
<p>Also in the version you are using as seen <a href="https://github.com/rusty1s/pytorch_scatter/blob/1.2.0/setup.py" rel="nofollow noreferrer">here</a>:</p>
<pre><code>...... | python|terminal|pip|pytorch|torch | 1 |
372,664 | 67,357,527 | ValueError: could not broadcast input array from shape (224,224,4) into shape (224,224,3) , error while testing with GRAYSCALE IMAGES | <p>The following code works great with RGB images but not working with GRAYSCALE images, Also I need to know why grayimages are having shape as (224,224,4) , according to my knowledge it should be (224,224,1).</p>
<pre><code>import silence_tensorflow.auto
import tensorflow.keras
from PIL import Image, ImageOps
import n... | <p>For the benefit of community providing solution here</p>
<blockquote>
<p><code>Grayscale</code> images have <code>1</code> channel, <code>RGB</code> images have <code>3</code>, and
<code>RGBA</code> has <code>4</code> channels last channel represents <em>alpha</em>. You can try <code>image = Image.open(img_path).con... | python|tensorflow|keras | 1 |
372,665 | 67,187,440 | Pandas Merge DF1 and DF2 Error on Size of Final DF3 | <p>I have two dfs - df1 and df2 and I'm trying to merge a single column of df2 with df1 on a common column. The result of the merge keeps giving me an unexpected result. Here is df1:</p>
<pre><code> plant_name year month power_kwh
0 CAYUGA RIDGE 2021 1 100013.479435
1 CAYUGA RID... | <p>In this case it looks like you can just <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer"><strong><code>concat()</code></strong></a> on <code>axis=1</code>:</p>
<pre class="lang-py prettyprint-override"><code>df3 = pd.concat([df1, df2["power_kwh_mean"]], ax... | pandas|dataframe|merge | 1 |
372,666 | 67,220,320 | Sum of all rows in specific column | <p>I am trying to generate the sum of all rows in a specific column in pandas. I am doing the project using a jupyterhub notebook.</p>
<p>The following code below generates a full list with the value in each row and not the total of all rows. Curious to know what I am doing wrong?</p>
<pre><code>ria_aum_total = ria_a... | <p>According to Pandas documentation you have to use Pandas Dataframe. Here is the example given in the documentation you have to cast the data to Dataframe and then you can use the .sum of the DataFrame datastructure.</p>
<p>Here is the example from the documentation (<a href="https://www.javatpoint.com/pandas-sum" re... | python|pandas | 0 |
372,667 | 67,557,429 | Merge and drop multiple rows based on column(s) value using Python | <p>I have a dataframe like:</p>
<pre><code>Task ID Value Sno
A A1 5 1
A A1 2 2
B A1 4 3
A A1 1 4
A B1 10 5
C B1 3 6
D B1 5 7
D B1 2 8
D B1 12 9
E C1 25 10
</code></pre>
<p>And the expected output should look li... | <p>Pretty similar to a groupby and aggregate join. However you have to first create a helper column to identify the consecutive groups:</p>
<pre><code>u = df[['Task','ID']]
g = u.ne(u.shift()).any(1).cumsum()
d = {"Value":"sum","Sno":lambda x: ','.join(x.astype(str))}
#d = {"Value&qu... | python|pandas|dataframe|aggregate | 1 |
372,668 | 67,555,241 | Grouping columns to form time series data (Python) | <p>I have a dataframe df which looks like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>restaurant</th>
<th>opentime</th>
<th>closetime</th>
<th>group</th>
</tr>
</thead>
<tbody>
<tr>
<td>ABX</td>
<td>10:00:00</td>
<td>21:00:00</td>
<td>Gold</td>
</tr>
<tr>
<td>BWZ</td>
<td>13:00:00<... | <p><strong>First part: Time</strong></p>
<p>Create a list that contains all hours between <code>opentime</code> and <code>closetime</code> then explode the list into rows and group by <code>(time, group)</code> and count values for each group.</p>
<p><strong>Second part: Date</strong></p>
<p>Create a datetime index tha... | pandas|date|datetime|time-series|pandas-groupby | 0 |
372,669 | 67,273,426 | How to groupby multiple columns in pandas and python? | <p>I have a Dataframe that I want to perform a <code>groupby</code> with multiple columns.</p>
<p>If I select the columns via code, it works.</p>
<p>What I want is to allow the user to select from the list of columns, and return the <code>groupby result</code>.</p>
<p>when I add this line the system crashes and display... | <p>After looking up streamlit I will assume, that your st.selectbox provides only one string (one column to select).
And st.multiselect provides a list. (multiple columns to select). But if this might be incorrect, please try to debug it, and look at the values of primary_col_pyplot and selected_column_names__pyplot in... | python|pandas|pandas-groupby|streamlit | 0 |
372,670 | 67,550,251 | Python looping to obtain different dataframes from a SQL database | <p>I'm trying to connect to an SQL database and, within a loop, create separate dataframes for each different instance of Id, containing all the data related to that Id. I've tried a number of ways, without any success so far. I'm pretty new to all of this, so I'm probably making some rookie mistakes.</p>
<p>Attempt 1:... | <p>I think that if you try a variation on your first attempt like:</p>
<pre><code>for x in Name:
SQL = '''
SELECT *
FROM Database
WHERE Id = ?'''
cursor = conn.cursor()
cursor.execute(SQL)
df = pd.read_sql_query(SQL, params={x})
</code></pre>
<p>It should probably work :)<... | python|pandas|loops|pyodbc | 1 |
372,671 | 67,493,095 | Is a .pth file a security risk, and how can we sanitise it? | <p>It's well-established that pickled files are [unsafe][1] to simply load directly. However, the advice on that SE post concludes that basically one should not use a pickled file if they are not sure of its provenance.</p>
<p>What about PyTorch machine-learning models that are stored as <code>.pth</code> files on, sa... | <p>As pointed out by <code>@MobeusZoom</code>, this is answer is about Pickle and not PyTorch format. Anyway as <a href="https://pytorch.org/docs/stable/generated/torch.load.html" rel="nofollow noreferrer">PyTorch load mechanism relies on Pickle behind the scene</a> observations drawn in this answer still apply.</p>
<h... | python|machine-learning|pytorch|pickle | 2 |
372,672 | 67,242,144 | reducing loops with numpy | <p>we are trying to implement the given Modified Gram Schmidt algorithm:
<img src="https://i.stack.imgur.com/y3b3W.jpg" alt="instructions here" /></p>
<p>We first tried to implement lines 5-7 in the next way:</p>
<pre><code>for j in range(i+1, N):
R[i, j] = np.matmul(Q[:, i].transpose(), U[:, j])
u = U[:, j] - ... | <p>The following piece of code does what you want, in a more efficient manner:</p>
<pre class="lang-py prettyprint-override"><code> Q_i = Q[:, i].reshape(1,-1)
R[i,i+1:] = np.matmul(Q_i , U[:,i+1:])
U[:,i+1:] -= np.multiply(R[i,i+1:] , Q_i.T)
</code></pre>
<p>First line is just a convenience, to... | python|numpy|linear-algebra|array-broadcasting | 1 |
372,673 | 67,520,166 | How to process the script within a loop using python | <p>I want to execute the script under a for loop, In last want to append back and concat to dataframe using python. script inside the loop is being executed but in last it gives the Error.</p>
<p>When i use the below script it gives the Error :</p>
<pre><code>df = df.apply(test, axis=1)
Error: AttributeError: '2021-01... | <p>Instead of using</p>
<pre><code>file['Joining_Date'][index] = ...
</code></pre>
<p>or</p>
<pre><code>file['Contact'][index] = file['Contact'].replace('[^\d.]', '', regex=True).astype(float)
</code></pre>
<p>you have to use your <code>index</code> variable to change your dataframe by index, because currently you are ... | python|pandas | 0 |
372,674 | 34,771,807 | Use NaN for values that can't be cast using astype | <p>I have a very large Pandas DataFrame that looks like this:</p>
<pre><code>>>> d = pd.DataFrame({"a": ["1", "U", "3.4"]})
>>> d
a
0 1
1 U
2 3.4
</code></pre>
<p>Currently the column is set as an <code>object</code>:</p>
<pre><code>>>> d.dtypes
a object
dtype: object
</code... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric</code></a> and specify <code>errors='coerce'</code> to force strings that can't be parsed to a numeric value to become <code>NaN</code>:</p>
<pre><code>>>> pd.to_numeric(d['a... | python|pandas|dataframe|nan | 9 |
372,675 | 34,830,280 | python - delete item from list of tuple by index | <p>I want to delete elements from list of tuple with given index values.</p>
<p><strong>Input</strong>: <code>[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]</code></p>
<p><strong>Task to be done</strong>:<br>
delete item at given index: 2,3 </p>
<p><strong>Desired output</strong>:
[(1, 2), (3, 4), (9, 10)] </p>
<p>I h... | <p>list.pop() will remove selected elements. they have to be done in reverse order so as not to modify the position of the later ones.</p>
<pre><code>list.pop(3)
list.pop(2)
</code></pre> | python|list|numpy|tuples | 3 |
372,676 | 34,482,707 | Insert a NumPy rec.array to MongoDB using PyMongo | <p>In an other question some people are trying to insert a Pandas DataFrame into MongoDB using Python internal structures (<code>dict</code>, <code>list</code>)
<a href="https://stackoverflow.com/questions/20167194/insert-a-pandas-dataframe-into-mongodb-using-pymongo">Insert a Pandas Dataframe into mongodb using PyMong... | <p><a href="http://odo.pydata.org/en/latest/" rel="nofollow">Odo</a> can do this</p>
<pre><code>In [1]: import pandas as pd
In [2]: import pymongo
In [3]: client = pymongo.MongoClient()
In [4]: collection = client['db_name']['collection_name']
In [5]: df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a', 'b', 'c'])
In [... | python|arrays|mongodb|numpy|pandas | 3 |
372,677 | 34,696,845 | How to see multiple images through tf.image_summary | <p>Problem - only one image is shown at TensorBoard</p>
<p>Inspired by this
<a href="https://stackoverflow.com/questions/33783672/how-can-i-visualize-the-weightsvariables-in-cnn-in-tensorflow/33794463#33794463">How can I visualize the weights(variables) in cnn in Tensorflow?</a></p>
<p>Here is code:</p>
<pre class=... | <p>You are right that you will only see one image. You are calling the image summary op once in each for loop, and each time you call it, you are passing it a single image.</p>
<p>What you could do to see all images that you want to see, would be to compile these images into a single tensor. If we refer to TensorFlow ... | tensorflow | 6 |
372,678 | 34,741,699 | Interpolation of curve | <p>I have a code where a curve is generated using random values. and a Horizontal line which runs through it. The code is as follows.</p>
<pre><code>import numpy as np
import matplotlib.pylab as pl
data = np.random.uniform(low=-1600, high=-550, size=(288,))
line = [-1290] * 288
pl.figure(figsize = (10,5))
pl.plot(da... | <p>I like <a href="https://stackoverflow.com/a/34744306/3381305">the Shapely answer</a> because <a href="http://toblerity.org/shapely/index.html" rel="nofollow noreferrer">Shapely</a> is awesome, but you might not want that dependency. Here's a version of some code I use in signal processing adapted from <a href="https... | python|numpy|scipy | 3 |
372,679 | 34,825,074 | Testing point with in/out of a vector shapefile | <p>Here is my question.</p>
<h3>1. Intro</h3>
<ul>
<li>a shapefile in polygon type represent the study area</li>
</ul>
<p><a href="http://i8.tietuku.com/08fdccbb7e11c0a9.png" rel="nofollow noreferrer">http://i8.tietuku.com/08fdccbb7e11c0a9.png</a></p>
<ul>
<li>some point located in the whole rectangle map</li>
</ul>
<p... | <p>you can use shapely:</p>
<pre><code>import numpy as np
from shapely.geometry import Polygon, Point
poly_data = [[0, 0], [0, 1], [1, 0], [0.2, 0.5]]
poly = Polygon(poly_data)
points = np.random.rand(100, 2)
mask = np.array([poly.contains(Point(x, y)) for x, y in points])
</code></pre>
<p>and here is the plot cod... | python|numpy|matplotlib|shapefile|matplotlib-basemap | 4 |
372,680 | 34,422,708 | Dataframe with column names derived from column values and cell values by condition | <p>I have to create a result pandas dataframe from a source pandas dataframe having two columns. The result dataframe should have headers of two types, one type should be from the source dataframe derived from one of the column values appending the column header with the values. The other header is taken as it is from ... | <p>You can use function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a>, then find values higher as <code>1</code> and convert it to <code>1</code> and <code>0</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Da... | python|pandas|dataframe | 2 |
372,681 | 34,699,779 | Pandas dataframe shift column by date | <p>I have a panel dataset which is indexed by Date and ID and looks something like this:</p>
<pre><code>df = pd.DataFrame({'Date':['2005-12-31', '2006-03-31', '2006-09-30','2005-12-31', '2006-03-31', '2006-06-30', '2006-09-30'],
'ID':[1,1,1,2,2,2,2],
'Value':[14,25,34,23,67,14,46]})
</code>... | <p>I would just make a copy of the dataframe, shift <code>Date</code> by 1 (seems you want shift by a quarter), and then merge back to the original dataframe. To shift date, you can convert string dates to pandas period so shifting will be easier.</p>
<pre><code>In [34]: df['Date'] = pd.PeriodIndex(df['Date'], freq='Q... | python|pandas|dataframe | 2 |
372,682 | 34,753,492 | Python: concatenate arrays stored in a dictionary | <p>I have a large dictionary which stores following arrays:</p>
<pre><code>Store = dict()
Store['A'] = A #size 500x30
Store['B'] = B #size 500x20
</code></pre>
<p>I am having only A and B for illustration. In my current real life situation I have about 500 keys and values in the dictionary I am using.</p>
<p>I want ... | <p>If the order does not matter, pass the values of your dictionary to <code>numpy.concatenate</code>:</p>
<pre><code>>>> store = {'A':np.array([1,2,3]), 'B':np.array([3,4,5])}
>>> np.concatenate(store.values(),1)
array([1, 2, 3, 3, 4, 5])
</code></pre>
<p>If the order does matter, you can use</p>
... | python|numpy | 7 |
372,683 | 34,657,132 | ImportError SciKit-learn | <p>I am trying to get started with machine learning, so I have installed the packages: <code>numpy, Scikit-learn, matplotlib, scipy</code>. Some I have installed directly from pip with:</p>
<pre><code>python -m pip install "package name"
</code></pre>
<p>and and others i have downloaded the binary files and then inst... | <pre><code>import sklearn.svm as svm
model = svm.SVC()
....
</code></pre>
<p><a href="http://scikit-learn.org/stable/modules/classes.html#module-sklearn.svm" rel="nofollow">http://scikit-learn.org/stable/modules/classes.html#module-sklearn.svm</a></p> | python|windows|numpy|pip|scikit-learn | 1 |
372,684 | 34,468,436 | python numpy get masked data without flattening | <p>How do I get the masked data only without flattening the data into a 1D array? That is, suppose I have a numpy array</p>
<pre><code>a = np.array([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])
</code></pre>
<p>and I mask all elements greater than 1,</p>
<pre><code>b = ma.masked_greater(a, ... | <p>Lets try an example that produces a ragged result - different number of 'masked' values in each row.</p>
<pre><code>In [292]: a=np.arange(12).reshape(3,4)
In [293]: a
Out[293]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [294]: a<6
Out[294]:
array([[ True, True, True, True... | python|arrays|numpy|mask | 2 |
372,685 | 60,136,941 | How to create mixed type data in pandas | <p>This is a rather non-standard question. For educational purposes, I'm trying to create a mixed type column in a csv file, so that I get a warning message when importing the dataset in a pandas <code>DataFrame</code> and later on, deal with that column to show how it's done. </p>
<p>The problem is that I'd type 0s i... | <blockquote>
<p>I'm trying to create a mixed type column in a csv file, so that I get
a warning message when importing the dataset in a pandas</p>
</blockquote>
<p>Pandas will always infer the type of a column (<code>Series</code> object) and this is always going to be a single type. If every value in the column is str... | python|pandas|mixed-type | 1 |
372,686 | 59,974,990 | customise correlation heatmap in seaborn | <p>I am new to python and i am trying to make a correlation heatmap on seaborn. Could anyone tell me how to customise the default values on the right of the heatmap with my own correlation cutoffs? I get something like the one in the picture but i want to customise with my own cutoffs and three values instead of four.<... | <p>If I understand your question correctly, you want to change the tick marks that display on the colorbar.</p>
<p>If so the heatmap function has an attribute <strong>cbar_kws</strong> which accepts a dictionary as input. A potential solution is:</p>
<pre><code>sns.heatmap(
new_df.corr(),
annot = False,
s... | python|pandas|dataframe|seaborn|correlation | 0 |
372,687 | 60,320,948 | Where is '_DataLoaderIter' in pytorch 1.3.1? | <p>When I use <code>pytorch 1.3.1</code> with <code>python3.7.4</code>, like this </p>
<pre class="lang-py prettyprint-override"><code>import torch
from torch.utils.data.dataloader import _DataLoaderIter
</code></pre>
<p>Here is an errer : <code>cannot import name '_DataLoaderIter' from 'torch.utils.data.dataloader'... | <p><code>_DataLoaderIter</code> does not exist any more. This <a href="https://github.com/pytorch/pytorch/blob/v1.1.0/torch/utils/data/dataloader.py" rel="nofollow noreferrer">code</a> is the latest one that contains <code>_DataLoaderIter</code>. You can use <code>_SingleProcessDataLoaderIter</code> or <code>_MultiProc... | python|pytorch | 4 |
372,688 | 59,925,821 | Concat successive rows in pandas based on regex | <p>I have a following dataframe that contains <code>date</code> is distorted way.</p>
<pre><code>index Date Particulars
0 01-12- AVON AGRO
1 2018 NaN
2 01-12- CASH
3 2018 NaN
4 03-12- NEFTOut/UTBIN18337459966/LUNI
5 2018 A MARKETING/SBIN00019
6 03-12- ANJANI ... | <p>First replace missing values to empty string and then join inpair and pair rows by <code>groupby</code> with <code>join</code>:</p>
<pre><code>df1 = df.fillna('').groupby(df.index // 2).agg(''.join)
print (df1)
Date Particulars
index ... | string|pandas|dataframe|rows|concat | 1 |
372,689 | 60,127,582 | Transforming groupedby pandas dataframe (multiple but not all columns) from long to wide | <p><strong>The problem:</strong></p>
<p>I have a dataset with yearly data of different companies. The data is stored in a long format, each year is a row therefore company ids are duplicated.
The data looks like this (however in the original dataframe I have lot more columns).</p>
<p><a href="https://i.stack.imgur.co... | <p>After you drop the years:</p>
<pre><code>del test['Year']
</code></pre>
<p>You can manage to group the lines together by adding an extra column with the row "index" for each row belonging to the same company.</p>
<pre><code>test['idx'] = test.groupby('Comp_id').cumcount() + 1
</code></pre>
<p>Then set it as part... | python|pandas|dataframe|pandas-groupby|transformation | 0 |
372,690 | 60,190,372 | Clustering in Python: Difference in result due to use of matrix vs data frame?Why is this happening? | <p>In calculating the difference between each data point and the center of its assigned cluster and squaring it then summing up, i tried using two different approaches</p>
<p>The sample1 approach use a matrix X and the sample2 approach uses the orignal dataframe.</p>
<p>I cannot seem to understand why are the results... | <p>If you look to the second result, you have 191.51 + 998.2311 = 1189.74 and you find back the first result.</p>
<p>When you work on matrix, <code>np.sum</code> add all the coefficients, on row and colums. You need to use the option axis if you want so sum only on a special axis.</p>
<p>In you code on dataframe, it'... | python|numpy|cluster-analysis | 2 |
372,691 | 59,958,934 | Why do Keras's evaluate_generator and evaluate report different accuracies on the same data? | <p>I'm using Keras's <code>ImageDataGenerator</code> and <code>flow_from_directory</code> to train a neural network. The issue I'm having is that <code>evaluate_generator</code> and <code>evaluate</code> report different accuracies for the same data. Here is a <a href="https://github.com/tinybike/keras-generator-mini... | <p>It turns out the discrepancy is caused by OpenCV's <code>imread</code> using BGR format, whereas Keras's <code>flow_from_directory</code> <a href="https://github.com/keras-team/keras-preprocessing/blob/master/keras_preprocessing/image/directory_iterator.py#L71" rel="nofollow noreferrer">expects RGB by default</a>. ... | python|tensorflow|machine-learning|image-processing|keras | 1 |
372,692 | 60,242,192 | GroupBy aggregation based on condition and year wise sum using pandas | <p>I have a data frame as shown below</p>
<pre><code>ID Sector Plot Tenancy_Start_Date Rental
1 SE1 A 2018-08-14 100
1 SE1 A 2019-08-18 200
2 SE1 B 2017-08-12 150
3 SE1 A 2020-02-12 300
5 SE2 A 201... | <p>You can do (<code>df</code> being your input dataframe):</p>
<pre class="lang-py prettyprint-override"><code>#in case if it's not already a datetime:
df["Tenancy_Start_Date"]=pd.to_datetime(df["Tenancy_Start_Date"])
df2=df.pivot_table(index=["Sector", "Plot"], columns=df["Tenancy_Start_Date"].dt.year, values="Rent... | pandas|pandas-groupby | 1 |
372,693 | 60,041,813 | Use IPython Widget Button to call Keras Training Function | <p>I would like to use an ipython button to run a function that trains a deep learning model using Keras's fit.generator() and ImageDataGenerator(). I tried to use <strong>lambda</strong> to pass the arguments to the function, but it returns <code>TypeError: expected str, bytes or os.PathLike object, not Button.</code>... | <p>Your <code>lambda</code> is bound to the <code>Button</code> class it was passed into, <a href="https://stackoverflow.com/questions/27627080/lambda-function-passing-not-desired-self">which implicitly made the first parameter the <code>Button</code> object itself.</a> The result was that the <code>trainpath</code> pa... | python|tensorflow|keras|jupyter-notebook | 0 |
372,694 | 59,971,592 | Can't pre-define dtype when reading data | <p>I am reading a pipe delimited file without headings into Pandas and I am using Pandas version 0.24.2. And this is public data so no worries around confidentiality.</p>
<p>The data looks like:</p>
<pre><code>999778247820|R|JPMORGAN CHASE BANK, NATIONAL ASSOCIATION|7.375|113000|360|02/2001|04/2001|95|95|1|52|665|Y|P... | <p>I got a different error:</p>
<pre><code>ValueError: Unable to convert column coborrower_fico_at_origination to type int
</code></pre>
<p>import you import the data into Excel, you will see that there are 3 rows in this columns that are blank. The <code>int</code> type cannot handle blanks. You should change it to ... | python|pandas | 0 |
372,695 | 60,205,543 | Reading raw json data of a table into df table? | <p>I am trying to download the json data into a df table from: "<a href="http://emweb.securities.eastmoney.com/NewFinanceAnalysis/lrbAjax?companyType=4&reportDateType=0&reportType=1&endDate=&code=SZ002475" rel="nofollow noreferrer">http://emweb.securities.eastmoney.com/NewFinanceAnalysis/lrbAjax?company... | <p>Using the given URL.</p>
<pre><code>import pandas as pd
import requests
url="http://emweb.securities.eastmoney.com/NewFinanceAnalysis/lrbAjax?companyType=4&reportDateType=0&reportType=1&endDate=&code=SZ002475"
json_data = requests.get(url).json()
out_df = pd.DataFrame(eval(json_data))
prin... | python|html|json|pandas|dataframe | 1 |
372,696 | 60,012,540 | How do you get the values around the perimeter of a numpy array in Python? | <p>I have a 2d numpy array, but I just want the values around the border as a list, as if you were walking around the box perimeter. </p>
<p>To illustrate, for a 2d array, I want to start in one corner and get the values all around the box</p>
<p><a href="https://i.stack.imgur.com/UMM5I.png" rel="nofollow noreferrer"... | <p>Given a 2d array called <code>array</code>...</p>
<pre><code>import numpy as np
x, y = np.meshgrid(range(1,6), range(5))
array=x*y
array[0,0]=999
</code></pre>
<p>...that looks like this:</p>
<pre><code>array([[999, 0, 0, 0, 0],
[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ ... | python|numpy | 0 |
372,697 | 60,245,147 | How necessary are activation functions after dense layer in neural networks? | <p>I'm currently training multiple recurrent convolutional neural networks with deep q-learning for the first time. </p>
<p>Input is a 11x11x1 matrix, each network consists of 4 convolutional layer with dimensions 3x3x16, 3x3x32, 3x3x64, 3x3x64. I use stride=1 and padding=1. Each convLayer is followed by ReLU activati... | <p>If I have to talk in general using an activation function helps you to include some non-linear property in your network. </p>
<p>The purpose of an activation function is to add some kind of non-linear property to the function, which is a neural network. Without the activation functions, the neural network could per... | deep-learning|neural-network|pytorch|activation-function|densenet | 6 |
372,698 | 60,021,927 | Calculate date from given weekday and month, but variable year (e.g. 3rd Sunday in August in "x" year) | <p>My pandas dataframe "MSYs" has a "start_yr" variable built from a datetime column "Start Date" showing the year of someone's start date (note that month and day of "Start Date" also vary).</p>
<p><code>start_yr = pd.DatetimeIndex(MSYs['Start Date']).year</code></p>
<p>I want to use start_yr to help me return a dat... | <p>This is an answer to a similar quesion which might help you.</p>
<p>Use the datetime library.</p>
<p>Loop through subset of days in august of that year.</p>
<p>Check if if it is thursday.</p>
<p><a href="https://stackoverflow.com/questions/18424467/python-third-friday-of-a-month">Python: third Friday of a month<... | python|pandas|datetime|calendar | 0 |
372,699 | 60,029,821 | Anaconda not loading Tensorflow | <p>Clean install of Windows10 with updates(iCore 5, 8Gb, 64bit). Installed Antivirus and Firewall. Installed Docker and pulled Tensorflow image and successfully created containers that works perfectly.
Then I downloaded and installed the latest Anaconda 64bit for Windows with all default settings on the host system. No... | <p>Managed to get some info on the Tensorflow Github release notes which I tried and it worked for me. </p>
<p>Installed the VSRedis as per article below, restarted and my Tensorflow was working on the host.</p>
<p>My Docker container worked because the host image is Linux, but here my host pc is Windows and needs th... | python-3.x|tensorflow|anaconda|anaconda3 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.