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
364,300
72,420,233
groupby and apply in pandas
<p>The purpose I would like to achieve: calculate the volume weighted daily return (formula is volume * daily return / cumulative volume per ticker), since this should be per ticker, I used the groupby ticker and then date, Here is the code I have right now.</p> <pre><code>stock_data['VWDR'] = stock_data.groupby(['Tick...
<p>Created the function 'func_data', which performs calculations. The result is placed in the 'test' column, which was previously created with nan values.</p> <pre><code>stock_data['test'] = np.nan def func_data(x): x['test'] = x['Volume'] * x['DailyReturn'] / x['Volume'].cumsum() return x stock_data['test']...
python|pandas|dataframe
1
364,301
72,401,377
ERROR: Could not build wheels for pandas, which is required to install pyproject.toml-based projects
<p>I'm trying to install pandas via <code>pip install pandas</code> on my laptop.</p> <p>Environment:</p> <ul> <li>Window 11 Pro</li> <li>Python 3.10.4</li> <li>Pip version 22.0.4</li> </ul> <p>Compatibility:</p> <ul> <li><a href="https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html#python-version-...
<h3>Step one</h3> <p><a href="https://www.lfd.uci.edu/%7Egohlke/pythonlibs/#_pandas" rel="nofollow noreferrer">Download pandas wheel</a>, Choose one that suits your operating system</p> <h3>Step two</h3> <p>install the wheel from absolute path</p> <pre><code>pip install pandas-1.4.2-cp310-cp310-win32.whl </code></pre> ...
python|pandas|installation|pip
0
364,302
72,311,209
How do I convert time from being an object to an integer in Python?
<p>I would like to convert a column from a large dataset that has the value of time as an object to an integer.</p> <p>I would like to convert &quot;Duration&quot;, &quot;Talk Time&quot; to int so I can perform some basic math such as the mean, the maximum and the minimum time recorded in the dataset.</p> <div class="s...
<p>Assuming you want to convert to seconds (and that is HH:MM:SS representation) and that is always an 8 digit string, the fastest way would be: <strike> df['dur_in_secs'] = int(df['duration'][0:2])*3600 + int(df['duration'][3:5])*60 + int(df['duration'][6:8])</p> <p>if it is not, try to isolate each part with</p> <pre...
python|pandas
0
364,303
72,308,835
Concatenating columns in Pandas DataFrame, deleting concatenated ones
<p>I got a DataFrame with weather Data from a whole year, one line being the data for a Day. Now I want to concatenate the rain and snow data as precipitation and delete concatenated ones. Looking through stackoverflow I came up with the following:</p> <pre><code> data is from a different function: df = pd.read...
<p>Probably they are int/float and you have to convert to string.</p> <p>There are basically two ways:</p> <ul> <li><code>xx = data[['Rain', 'Snow']].astype(str).apply(' '.join, axis = 1)</code> =&gt; 750ms</li> <li><code>yy=df.Rain.astype('str')+' '+df.Snow.astype('str')</code> =&gt; 200ms</li> </ul> <p>Benchmarked <c...
python|pandas|dataframe|concatenation
0
364,304
72,420,891
How do I merge or update dataframes?
<p>I have an original dataframe as:</p> <p>import pandas as pd</p> <pre><code>df = pd.read_excel(&quot;Weights.xlsx&quot;, sheet_name='Old') df: Name S_Name Height Weight 0 John Wright 5.3 52 1 Seven Taylor 6.4 75 2 Ramsay Sen 7.2 77 </code></pre> <p>I get a new file with...
<p>If you cannot guarantee that the indices are aligned, you need to use <strong>both</strong> <code>merge</code> and <code>update</code> (or <code>combine_first</code> of you do not want to modify <code>df1</code> in place)</p> <p>You can align the DataFrames with <code>merge</code>, then <code>update</code>:</p> <pre...
python|pandas|dataframe|merge
1
364,305
72,364,013
convert polygon recorded as object to shapely polygon gives 'str' object has no attribute '__array_interface__'
<p>Initially, I have 2 datasets. One is dataset with 45 polygons defined in Excel and another one is geometric coordinates of points. I need to know for each geometric point in which of 45 polygons it locates.</p> <p>For file with polygons, I have a csv file which recorded POLYGON(......) as objects. I want to later ch...
<p>To use the spatial features of geopandas, your shapes need to be geometry type, not strings. You can see what type the objects are using the <code>dtype</code> attribute - you should see something like the following:</p> <pre class="lang-py prettyprint-override"><code>In [6]: df.geometry.dtype Out[6]: &lt;geopandas....
python|polygon|geopandas|shapely
3
364,306
50,371,649
How to convert a column in data with date format to works it pandas
<p>I am trying to use the date from the "fechas" column to make a analysis with pandas, can someone explain how to give the date format to that column.</p> <pre><code> LEY Unnamed: 3 \ 0 Por medio de la cual se regula el uso del Desf... Salud 1 ...
<p>The <code>dateparser</code> module is capable of handling numerous languages including french, russian, spanish, dutch and over 20 more. It also can recognize stuff like time zone abbreviations, etc.</p> <pre><code>import dateparser dateparser.parse('3 de agosto, 2017') # output - datetime.datetime(2017, 8, 3, 0, ...
python|pandas|datetime
4
364,307
50,668,621
Pandas: how to have preview of several rows sorted under certain columns
<p>If i have a Data Frame(df) as :</p> <pre><code>Year Rate 2001 10 2001 3 2001 5 2001 3 2001 6 2002 2 2002 7 2002 4 2002 9 2002 8 ... ... 2018 8 2018 6 2018 4 2018 6 2018 5 </code></pre> <p>How do i get a Data Frame that show only first 2 rows of each years, like:</p> <pre><code>Year Rate 2001 10 2001 3 2002 2 2...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.head.html" rel="nofollow noreferrer"><code>GroupBy.head</code></a>:</p> <pre><code>df1 = df.groupby('Year').head(2) print (df1) Year Rate 0 2001 10 1 2001 3 5 2002 2 6 2002 7 10 2018 8 11 ...
pandas
3
364,308
50,579,384
Bin data into ranges
<p>I have a dataframe like below and I want to create 4 columns to compute accuracy distribution </p> <pre><code>Company Error_Rate A 9 B 10 c 20 GK 17 GK 18 GK 30 GK 35 GK 25 GK 32 GK 40 GK 50 MB 60 MB 70 MB 70 </code></pre> <p>And I desire to have a table ...
<p>If you have to write 4 <code>np.where</code> conditions to compute a column, you're doing it wrong. I think it'd be wise to consider a different approach. </p> <p>One succinct option involves <code>pd.cut</code> + <code>pd.get_dummies</code>.</p> <pre><code>bins = [0, 65, 80, 90, 100] labels = ['Below 65%', '65% -...
python|pandas|dataframe|conditional
2
364,309
50,665,110
Tensorflow/models uses COCO 90 class ids although COCO has only 80 categories
<p>The labelmaps of Tensorflows object_detection project contain 90 classes, although COCO has only 80 categories. Therefore the parameter <code>num_classes</code> in all sample configs is set to 90.</p> <p>If i now download and use the COCO 2017 dataset, do I need to set this parameter to 80 or leave it to 90?</p> <...
<p>The MSCOCO paper describes that the dataset has actually 91 classes but in the 2014 dataset they released only a subset of 80 classes because they didn't annotated the segmentation of the remaining 11 classes. Seems that tensorflow models were trained using 90 classes.</p> <p>MSCOCO paper: <a href="https://arxiv.or...
tensorflow|tensorflow-datasets|tfrecord
8
364,310
50,532,840
Data Comparison in Python Pandas Series
<p>That are 2 Data Series that i wish to compare based on a third.</p> <p>data_SKU1:</p> <pre><code>SKU Weight1 1234 20 1235 30 111 40 101 23 </code></pre> <p>data_SKU2:</p> <pre><code>SKU Weight2 1234 22 1235 35 111 47 101 87 </code></pre> <p>flag_Data:</p> <pre><code>SKU...
<p><strong><em>Setup</em></strong><br> <strong><code>merge</code></strong></p> <pre><code>df = df1.merge(df2) SKU Weight1 Weight2 FLAG 0 1234 20 22 True 1 1235 30 35 False 2 111 40 47 True 3 101 23 87 False </code></pre> <p><strong><em>Option 1</em>...
python|pandas|dataframe|timestamp|series
2
364,311
50,410,775
Pandas, get elements in an specific order
<p>I have a pandas dataframe</p> <pre><code>col1 col2 Apple 70 Lemon 80 Banana 90 </code></pre> <p>and I have a list with the elements of <code>col1</code> in a specific order:</p> <pre><code>my_list = ['Banana', 'Apple', 'Lemon'] </code></pre> <p>I need to get the values of <code>col2</code> followin...
<p>Pandas 0.15 introduced <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow noreferrer">Categorical Series</a></p> <pre><code>df = ... my_list = ['Banana', 'Apple', 'Lemon'] df['col1'] = pd.Categorical(df['col1'], my_list ) df.sort("col1") result = df['col2'] </code></pre>
python|pandas
2
364,312
50,461,840
How to perform transfer learning on .tflite models
<p>Currently, I'm trying to make an Android food recognition application. I manage to build an application to process the image and run on the "mobilenet_quant_v1_224.tflite" pretrained model. Everything works fine and now I want to add call of my own to the model to predict.</p> <p>I do know that TFLITE is still in i...
<p>As of now, TFLite does not support training. You can do the transfer learning on the TF model, and then convert the transfer-learnt model to TFLite. This <a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets-2-tflite/index.html#0" rel="nofollow noreferrer">TF-for-poets-2-tflite codelab</a> w...
android|tensorflow|machine-learning|tensorflow-lite
4
364,313
50,456,281
Pandas merge multiple string and Nan columns into one
<pre><code> Chat A B C D ...... X 0 I'm groot Nan Nan Nan Nan 1 I am rocket Nan Nan Nan </code></pre> <p>I have a df with multiple columns contain Strings in it and some of them are Nan I want to merge them all into one column and drop the rest...
<h3><code>fillna</code> + <code>str.join</code></h3> <p>Fill, join, and cleanup:</p> <pre><code>df = df.fillna('').agg(' '.join, 1).str.replace('\s{2,}', ' ').str.strip() df Chat 0 I'm groot 1 I am rocket </code></pre>
python|string|pandas|nan
2
364,314
50,652,295
I want to convert pandas Timedelta to string with format
<p>I would like to convert pandas Timedelta to string but as you know it differ from what Timedelta got</p> <ol> <li><p>if it's <code>00:00:00</code> then <code>0 days 00:00:00</code></p></li> <li><p>but if it's <code>00:00:02.043000</code> (means it has ms info) <code>0 days 00:00:02.043000</code></p></li> </ol> <p>...
<p>I'm not sure it's good this way. but I found a solution for me.</p> <p>Situation. - I got a column <code>data['time']</code> which <code>dtype</code> is <code>pandas._libs.tslib.Timedelta</code></p> <p>What I did in one line</p> <ol> <li>change <code>dtype</code> from <code>Timedelta</code> to <code>datetime</cod...
pandas|timedelta
4
364,315
50,312,018
Merge two dataframes in Pandas by taking the mean between the columns
<p>I have the following dataframes:</p> <p><strong>df1</strong></p> <pre><code> C1 C2 C3 0 0 0 0 1 0 0 0 </code></pre> <p><strong>df2</strong></p> <pre><code> C1 C4 C5 0 1 1 1 1 1 1 1 </code></pre> <p>The result I a...
<p>You can using <code>concat</code> and <code>groupby</code> axis =1 </p> <pre><code>s=pd.concat([df1,df2],axis=1) s.groupby(s.columns.values,axis=1).mean() Out[116]: C1 C2 C3 C4 C5 0 0.5 0.0 0.0 1.0 1.0 1 0.5 0.0 0.0 1.0 1.0 </code></pre> <p>A nice alternative from @cᴏʟᴅsᴘᴇᴇᴅ</p> <pre><code...
python|pandas|dataframe
3
364,316
50,526,032
Error while loading .so file in android project from tensorflow
<p>I wanted to add tensorflow support to my android project (my own version of object detection from the demo)and didn't want to deal with <code>bazel</code> or <code>cmake</code> to build the native libraries that tensorflow uses. So as recommended through many issues posted at the tensorflow GitHub project I download...
<p>As suggested, downloading and including the <code>.so</code> file to your own project was not enough. Since we're including a pre-compiled version of the library the native methods (in the <code>.cpp</code> files) have the package name of the tensorflow demo on their names. That's why this error occur since our own ...
android|tensorflow|gradle
0
364,317
50,293,992
Reading all values from certain columns in csv into one array python
<p>I have data in csv format of the following form:</p> <pre><code>A B a1 a2 a3 a4 a5 1 0 100 34 44 1 1 2 0 101 1 44 11 3 3 0 105 3 55 21 22 4 0 45 4 52 1 45 5 0 57 5 42 3 56 6 0 89 78 1 3 67 7 0 34 99 2 4 98 8 0 57 23 2 5 2 </code></pre...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html" rel="nofollow noreferrer"><code>numpy.ravel</code></a> with selecting columns by columns names:</p> <pre><code>A = df[['a2', 'a3', 'a4', 'a5']].values.ravel() </code></pre> <p>Or by <a href="http://pandas.pydata.org/pandas-docs/sta...
python|pandas|csv
2
364,318
50,520,835
xarray: simple weighted rolling mean example using .construct()
<p>Xarray can do weighted rolling mean via the <code>.construct()</code> object as stated in answer on SO <a href="https://stackoverflow.com/questions/48510784/xarray-rolling-mean-with-weights">here</a> and also in the <a href="http://xarray.pydata.org/en/stable/computation.html#rolling-window-operations" rel="nofollow...
<p>In the first example, you use evenly spaced data for <code>arr</code>. Therefore, the weighted mean (with [0.25, 5, 0.25]) will be the same as the simple <code>mean</code>.</p> <p>If you consider non-linear data, the result differs</p> <pre><code>In [50]: arr = xr.DataArray((np.arange(0, 7.5, 0.5)**2).reshape(3, 5...
pandas|python-xarray
1
364,319
50,251,435
tensorflow in VS, already downloaded but not working
<p>Ive downloaded microsoft visual studio with python 3.6. I then downloaded tensorflow within VS using pip install within the python environment tools. However when i run a script using tensorflow, i received an error:</p> <pre><code>ImportError: Traceback (most recent call last): File "C:\Program Files (x86)\Micro...
<p>On Windows and using python v3.6.x ensure that when you install tensorflow you use</p> <pre><code>pip3 install --upgrade tensorflow </code></pre> <p>for cpu only support...or</p> <pre><code>pip3 install --upgrade tensorflow-gpu </code></pre> <p>if you have a supported gpu.</p> <p>Also ensure that you run any v...
python|visual-studio|tensorflow|pip
1
364,320
50,604,182
Why does the Tensorflow tf.FIFOQueue close early in the following code?
<p> I am trying to implement a queue that has an <code>enqueue</code> running in the background and a <code>dequeue</code> running in the main thread.</p> <p>The goal is to run an optimizer in loop that depends on a value stored in a buffer and only changes with each step in the optimization. Here is a simple example ...
<p>So I found the "how to fix it" part, but not the why.</p> <p>It seems that the first enqueue/dequeue must be run before the second enqueue/dequeue is placed in the QUEUE_RUNNERS collection - but with a caveat, we need to run <code>sess.run(data_.initializer)</code> twice:</p> <pre><code>with tf.Session() as sess: ...
python|tensorflow|python-multithreading
0
364,321
50,375,913
Stack groups in a DataFrame on top of each other
<p>I have a pandas df with duplicate indices and a single column:</p> <pre><code> value 1 0.996957 1 1.098198 1 1.184518 2 1.255916 2 1.312393 </code></pre> <p>What I want to do is to obtain a df with the unique indices, and the different values that each index takes as column...
<h3><code>set_index</code> + <code>unstack</code></h3> <pre><code>df.set_index(df.groupby(level=0).cumcount(), append=True).unstack()['value'] 0 1 2 1 0.996957 1.098198 1.184518 2 1.255916 1.312393 NaN </code></pre>
python|pandas|dataframe|group-by|pandas-groupby
3
364,322
50,467,369
single mangement system covers several ML frameworks
<p>Question: is there any open source project which covers all ML framework management in a single system?</p> <p>Scenario Description: in some education scenario, many studies and teachers would like to use different ML frameworks such as Tensorflow, Caffe, Mxnet, etc. It's hard for environment guys to prepare all of...
<p>Maybe you can use the <a href="https://aws.amazon.com/machine-learning/amis/" rel="nofollow noreferrer">AWS Deep Learning AMI</a>. The AMI has all the frameworks you mentioned pre-installed for you.</p> <p>The AMI itself is free of cost. You only pay for the EC2 instances you use.</p>
tensorflow|caffe|mxnet
0
364,323
50,521,961
TensorFlow.js returning TypeError: Cannot read property 'concat' of undefined when loading models
<p>Trying to recreate the <a href="https://github.com/google/emoji-scavenger-hunt" rel="nofollow noreferrer">emoji scavenger</a> hunt from google and it returned me the following error:</p> <p><a href="https://i.stack.imgur.com/q50rO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q50rO.jpg" alt="en...
<p>Discovered that the error was being caused by an upgraded version of tfjs-core and tfjs-converter. I downgraded it according to the demo and seems to be working. a long term solution as it still doesnt solve the problem for new developers. Raised it in GitHub too</p>
javascript|tensorflow|tensorflow.js
1
364,324
50,411,641
Pandas.to_datetime giving an error when given 15-Jan-0001 is there a way around this?
<p>I've got a dataset which goes back to 15-Jan-0001 (yes that is 1 CE!), it was originally 0 CE but since that year doesn't exist I cut those 12 months out of the data. </p> <p>I am trying to get pandas to convert to date-time string in my datasdf.datetime=pd.to_datetime(df.datetime) to an internal datetime object. <...
<p>One way is convert this problematic values to <code>NaT</code>s:</p> <pre><code>df.datetime = pd.to_dtaetime(df.datetime, errors='coerce') </code></pre>
python|pandas|datetime
0
364,325
50,458,188
Write to Teradata with python (aos_td)
<p>I have a Pandas dataframe that I want to insert into a Teradata table. </p> <pre><code>with aos_td.default_session(username='my_username', password='my_password', system='blah.blah.com') as session: session.executemany("""SCHEMA.TABLE(col1,col2,col3,col4) V...
<p>To get the records without the index use </p> <pre><code>.to_records(index=False) </code></pre> <p>Here is the full code to write to Teradata from python with aos_td:</p> <pre><code>with aos_td.default_session(username='my_username', password='my_password', system='blah.blah.com') as sess...
python|pandas|dataframe|teradata
0
364,326
50,649,794
Combine Layers with Input
<p>Is it possible in keras add external input to Merge layer? I have simple embedding which I would like to combine with external values, but every time I try to do I always get error. Is there way to add external input to Keras layers?</p> <pre><code>models = [] inputs =Input(shape=(10,)) models.append(inputs) for i i...
<p>Not sure what is your intention, but you're mixing models and tensors in the same list <code>models = [inputs, model1, model2]</code>. This is the cause of the error. </p> <p>Now, we have no idea about what kinds of input you have, so we cannot help further, but assuming a few things (that may be wrong) this code c...
python|tensorflow|keras
2
364,327
50,273,261
load numpy.ndarray from csv string
<p>I converted images to numpy array and saved to csv file</p> <pre><code>back_ground = Back_ground() X = make_test_set('back_ground.csv',back_ground,3500) Y = back_ground.make_answer() with open('background.csv','w',newline='') as csvfile: fieldnames = ['image','answer'] writer = csv.DictWriter(csvfile,field...
<pre><code>In [26]: import csv In [27]: X = np.arange(12).reshape(3,4) In [28]: Y = np.arange(12) In [29]: with open('background.csv','w',newline='') as csvfile: ...: fieldnames = ['image','answer'] ...: writer = csv.DictWriter(csvfile,fieldnames=fieldnames) ...: ...: writer.writeheader() ...
python|python-3.x|csv|numpy
0
364,328
50,644,567
Tensorflow: variable sequence length AND batch size
<p>My dataset consists of sentences. Each sentence has a variable length and is initially encoded as a sequence of vocabulary indexes, ie. a tensor of shape [sentence_len]. The batch size is also variable.</p> <p>I have grouped sentences of similar lengths into buckets and padded where necessary, to bring each sentenc...
<p>Unfortunately there is no workaround here unless you provide a <code>tf.Variable()</code> (which is not possible in your case) to the <code>parameter</code> of <code>tf.nn.embedding_lookup()</code>/<code>tf.gather()</code>. This is happening because, When you declare them with a placeholder of shape <code>[None, No...
python|tensorflow|machine-learning
0
364,329
50,369,082
ValueError when read_html using Pandas
<p>I have a web application which is made using flask and I have used pandas to_html() function to export excel as html table in the first place. I have made few changes to the html table using javascript and want to write those changes to the excel also so that they get saved everytime I reload the page. </p> <p>Now,...
<p>You can parse tables to a template using:</p> <p><em>This example is made with pandas, but I hope to help you.</em></p> <p>Having a table like this:</p> <pre><code>ipdst proto time count 10.3.20.102 HTTP 2017-03-20 17:08:56 1 10.3.20.102 HTTP 2017-03-20 17:08:57 ...
python|pandas
0
364,330
50,529,279
Matplotlib: Getting full hour ticks on y-axis in scatterplot
<p>I'm plotting some measured speeds from cars in a scatterplot. I'd like to show that low speeds often occur during certain periods of the day. Plotting works fine, but I'm not happy about the y-axis.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt Time = ['2018-03-16 16:15', '2018-03-16 16:30', '...
<p>It's something to do with how matplotlib handles datetime.time objects. Try this:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt from datetime import datetime Time = ['2018-03-16 16:15', '2018-03-16 16:30', '2018-03-16 16:45'] time = [datetime.strptime(d,'%Y-%m-%d %H:%M') for d in Time] Speed =...
python-3.x|pandas|matplotlib
1
364,331
50,561,412
Capitalize a string column in pandas
<p>How to replace a multiple version in easiest way?</p> <p>Here's my data:</p> <pre><code>No Device 1 asus 2 Xiaomi 3 xiaomi 4 Asus 5 Samsung </code></pre> <p>I want to make it:</p> <pre><code>No Device 1 Asus 2 Xiaomi 3 Xiaomi 4 Asus 5 Samsung </code></pre> <p>What I did is:</p> <pre><code...
<p>Why not just go with <code>str.title</code>?</p> <pre><code>df['Device'] = df.Device.str.title() df No Device 0 1 Asus 1 2 Xiaomi 2 3 Xiaomi 3 4 Asus 4 5 Samsung </code></pre> <p>There's no need for any mappings or dictionary this way.</p>
python|string|pandas|dataframe
6
364,332
50,582,168
Pandas: Get all columns that have constant value
<p>I want to get the names of the columns which have same values across all rows for each column.</p> <p>My data:</p> <pre><code> A B C D 0 1 hi 2 a 1 3 hi 2 b 2 4 hi 2 c </code></pre> <p>Desired output:</p> <pre><code>['B', 'C'] </code></pre> <p>Code:</p> <pre><code>import pandas as pd d = {'A...
<p>Use the pandas not-so-well-known builtin <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nunique.html" rel="noreferrer"><em><strong><code>nunique()</code></strong></em></a>:</p> <pre><code>df.columns[df.nunique() &lt;= 1] Index(['B', 'C'], dtype='object') </code></pre> <p>Notes:<...
python|pandas
33
364,333
50,317,305
Using Numpy to find combination of rows in an array such that each column sums to the same value
<p>I'm trying to use <code>numpy</code> to find configurations of rows in a matrix such that summing the columns of the rows will result in the same value. As an example, for the matrix/array</p> <pre><code>[[0,0,0,1], [1,0,1,0], [1,1,0,0], [0,1,0,0]] </code></pre> <p>I would like to have the first, second, and la...
<p>One solution is to enumerate the power set of rows and then check each possible subset of rows for the summation condition. For matrices with a large number of rows, this is likely to be quite slow.</p> <p>Use the standard itertools recipe for the power set:</p> <pre><code>from itertools import chain, combinations...
python|numpy|linear-algebra|data-science
1
364,334
50,510,642
How do I index a merged CSV file from the web
<p>I need help in properly indexing my dataframe from the web. I'm using the pandas module</p> <pre><code>df1 = pd.read_csv('https://raw.githubusercontent.com/bonsalakot00/Test-Server/master/Data_2012.csv') </code></pre> <p>This is one of my codes for accessing my data repository and reading it as a dataframe</p> <p...
<p>If you're concerned about multiples of each index number, you can simply reset the index.</p> <pre><code>results = pd.concat([df1, ..., dfn], axis=0, join='inner') results = result.reset_index(drop=True) </code></pre>
python|pandas|sorting|indexing|preprocessor
0
364,335
50,261,604
Scikit-learn Decision Tree Classifier
<p>I am trying to build a tree classifier with the scikit-learn package but I have problems getting the correct format for the classifier input..</p> <pre><code>import pandas as pd import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split #import dataset da...
<p>Try this to make sure you are passing integers, if your set contains strings or categorical values, or shows another issue, I'll edit this answer with the solution:</p> <pre><code>cols = ['clump_thickness','shape_uniformity','marginal_adhesion','epithelial_size','bare_nucleoli','bland_chromatin','normal_nucleoli','...
python|numpy|scikit-learn|decision-tree
0
364,336
50,432,454
Counting Words in a Column
<p>The video game is a FPS shooter game called PUBG. I want to count the number of times someone died by a particular weapon. However the items are in a column.</p> <p>The game <code>killed_by</code> has a list of ways for a player to die:</p> <pre><code>df.(['Grenade', 'SCAR-L', 'S686', 'Down and Out', 'M416', 'Pu...
<p><code>df.([]).counter</code> gives you an syntax error because you are not calling any method.</p> <p>i don't know exactly what were you trying to achieve by that line of code, however if you wanna get the occurrences of each weapon this might be one of the many ways you can do it.</p> <pre><code>a = ['Grenade', '...
pandas|jupyter-notebook|unique|histogram|counter
0
364,337
50,284,390
Rearranging and solving an equation in Python
<p>I have the following velocity equation and I want to solve for <code>position</code>. I want Python to define a new equation so that <code>position = (Velocity + 100) / 0.1</code>.</p> <p>However, if I change the velocity equation then I would also have to change the position equation. This is time consuming and I ...
<p>Rearranging equations needs symbolic math. You need SymPy for that.</p> <p>For example, define the symbols (usually these are single characters, not words):</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import sympy &gt;&gt;&gt; v, p = sympy.symbols('v p') </code></pre> <p>Now you can make an expres...
python|numpy
3
364,338
50,264,008
Signal Input/Output Relationship Tensorflow
<p>I'm trying to build a neural network using tensorflow to predict a vibration output from a given actuator input. I have 500 sample input/output signals that can be used for training and testing. Most of the examples in the tensorflow tutorial are for classification, so I'm currently stumped. My input is a series of ...
<p>There is no <em>right</em> answer for this as there are many algorithms you could try to find the optimal one. From the description you've given, I'd start with the Tensorflow <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/LinearRegressor" rel="nofollow noreferrer">LinearRegressor</a> estimator.</p...
tensorflow
0
364,339
50,296,531
Use Pandas to write to excel sheets in specified order
<p>At the end of Pandas <code>.to_excel</code> <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer">documentation</a> it shows how to write sheets in order:</p> <pre><code>&gt;&gt;&gt; writer = pd.ExcelWriter('output.xlsx') &gt;&gt;&gt; df1.to_excel(...
<p>As <a href="https://stackoverflow.com/questions/21118823/possible-to-alter-worksheet-order-in-xlsxwriter">jmcnamara</a> wrote, it's not advisable to change the order of sheets because of Excel's internal structure, but you can change which sheet is active when the Excel file opens using <code>activate()</code>:</p> ...
python|pandas|export-to-excel
4
364,340
50,567,008
ValueError: multiclass-multioutput format is not supported using sklearn roc_auc_score function
<p>I am using <code>logistic regression</code> for prediction. My predictions are <code>0's</code> and <code>1's</code>. After training my model on given data and also when training on important features i.e <code>X_important_train</code> see screenshot. I am getting score around 70% but when I use <code>roc_auc_score(...
<p><strong>First of all, the <code>roc_auc_score</code> function expects input arguments with the same shape.</strong></p> <pre><code>sklearn.metrics.roc_auc_score(y_true, y_score, average=’macro’, sample_weight=None) Note: this implementation is restricted to the binary classification task or multilabel classificati...
python|pandas|scikit-learn|logistic-regression
6
364,341
45,461,399
XML parsing in python Pandas get a complete block of tags in one row
<p>Hi I can convert my xml file to pandas dataframe. But challenge i have is i am not getting records in proper row, lets say we have a set of tag in xml which is getting repeated for eg. 4 times, and it has multiple child node which should be columns for my dataframe, now when i am trying to read xml i want to get onl...
<p>Consider a lxml's <code>xpath()</code> on the <code>&lt;xs:topcol&gt;</code> nodes and use lxml's <code>parse()</code> to read directly from file. The XPath loop iteratively appends to list and dictionary containers to cast to dataframe. Also, your desired output is actually not aligned to the node values:</p> <pre...
python|xml|pandas|lxml
1
364,342
45,399,618
Pandas: map function along each row of columns defined at runtime (using *args)
<p>I want to apply a function on the row data of a Pandas DataFrame using *args. This can be done like this (toy example to retrieve maximum of row):</p> <pre><code>df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) def f(*args): cols = [c for c in args] return max(cols) m = list(ma...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer"><code>apply</code></a> with <code>axis=1</code> for process by rows and each row is converterted to <code>Series</code>:</p> <pre><code>def f(x): print (x) #sample function return...
python|pandas|dataframe
6
364,343
45,610,657
How to find a partial numeric value in column in Pandas?
<p>I have a data frame created with Pandas. It has 3 columns. One of them has the date in the format %Y%m%d%H. I need to find the rows that match a date with the format %Y%m%d. </p> <p>I tried </p> <pre><code>df.loc[df["MESS_DATUM"] == 20170807] </code></pre> <p>which doesn't work. Only when I do </p> <pre><code>df...
<p>We can "integer divide" <code>MESS_DATUM</code> column by <code>100</code>:</p> <pre><code>df.loc[df["MESS_DATUM"]//100 == 20170807] </code></pre> <p>Demo:</p> <pre><code>In [29]: df Out[29]: MESS_DATUM 0 2017080719 1 2017080720 2 2017080721 3 2017080722 4 2017080723 In [30]: df.dtypes Out[30]: MESS_DATU...
python|pandas
2
364,344
45,585,699
how to map tensor to it's indices in tensorflow
<p>Suppose I have a 2D tensor with shape (size, size), and I want to get 2 new tensors that containing the original tensors row index and column index. So if size is 2, I want to get [[0, 0], [1, 1]] and [[0, 1], [0, 1]]</p> <p>What's tricky is that size is another tensor whose value can only be known when running the...
<p>Seems like you are looking for <a href="https://www.tensorflow.org/api_docs/python/tf/meshgrid" rel="nofollow noreferrer">tf.meshgrid</a>.</p> <p>Here's an example:</p> <pre class="lang-python prettyprint-override"><code>shape = tf.shape(matrix) R, C = tf.meshgrid(tf.range(shape[0]), tf.range(shape[1]), indexing='...
tensorflow
3
364,345
45,505,410
Error in numpy argmax with sparse matrix
<p>I'm using np.argmax function in one of my python programme for one of my data frame which is completely sparse matrix.my data frame contains 253 rows &amp; 22 column. The head function return this sample data set</p> <pre><code> var1 var2 Var3 var4 ... .. var18 var19 ... var22 0 ...
<p>The code works fine for me when I use - </p> <pre><code>y=np.argmax(train_y.values, axis=1) </code></pre> <p>The <code>np.argmax</code> is a numpy function, passing in a dataframe could be causing this error. Instead convert it into a numpy nd array using the <code>.values</code> attribute of dataframes</p>
python|numpy
1
364,346
45,384,684
Replace all nonzero values by zero and all zero values by a specific value
<p>I have a 3d tensor which contains some zero and nonzero values. I want to replace all nonzero values by zero and zero values by a specific value. How can I do that?</p>
<p>Pretty much exactly how you would do it using numpy, like so:</p> <pre class="lang-py prettyprint-override"><code>tensor[tensor!=0] = 0 </code></pre> <p>In order to replace zeros and non-zeros, you can just chain them together. Just be sure to use a copy of the tensor, since they get modified:</p> <pre class="lan...
pytorch
26
364,347
45,674,507
Copying 1 line from a panda dataframe into multiple lines of another
<p>I have 2 pandas data frames (df1 and df2) with the same columns, and I am trying to copy 1 line from df1 into multiple lines of df2. df2 is a multi-index data frame, with the first index corresponding to the index values of df1, and the second index an integer value.</p> <p>Here is how they are defined:</p> <pre><...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.align.html" rel="nofollow noreferrer"><code>DataFrame.align</code></a>, what return <code>DataFrames</code> in tuples, so add <code>[1]</code> for select second one:</p> <pre><code>np.random.seed(23) df1 = pd.DataFrame(index...
python|pandas|dataframe
2
364,348
45,585,860
Shuffle a pandas dataframe by groups
<p>My dataframe looks like this</p> <pre><code>sampleID col1 col2 1 1 63 1 2 23 1 3 73 2 1 20 2 2 94 2 3 99 3 1 73 3 2 56 3 3 34 </code></pre> <p>I need to shuffle the dataframe keeping same samples together a...
<p>Assuming you want to shuffle by <code>sampleID</code>. First <code>df.groupby</code>, shuffle (<code>import random</code> first), and then call <code>pd.concat</code>:</p> <pre><code>import random groups = [df for _, df in df.groupby('sampleID')] random.shuffle(groups) pd.concat(groups).reset_index(drop=True) ...
python|pandas|dataframe|shuffle
22
364,349
45,390,756
pandas: cannot do positional indexing on DatetimeIndex with these indexers [2016-08-01 00:00:00] of Timestamp
<p>I a newbie using pandas, I am trying to access my (date indexed) dataframe <code>df</code> using code similar to this:</p> <pre><code>for idx, row in df.iterrows(): if idx &lt; startrow: continue col1_data = df.iloc[idx]['col1'] </code></pre> <p>I get the following error:</p> <pre><code>cannot do...
<p>The <code>iloc</code> needs to be <code>loc</code>, as the former is <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.iloc.html" rel="noreferrer"><em>integer-location based indexing</em></a>; To select rows by labels (or the actual index as is <code>idx</code>) you need <a href...
python|pandas|dataframe
17
364,350
45,475,368
How to combine two pandas series which are differently indexed?
<p>I try to combine two differently indexed series together (same number of rows). I tried <code>pd.concat((s1, s2), axis=1)</code>. For example, s1 is:</p> <pre><code>index | s1 ----- | ----- 0 | 1.5 ----- | ----- 1 | 2 </code></pre> <p>and s2 is:</p> <pre><code>index | s2 ----- | ----- a | 1 ----- | --...
<p>Set index of <code>s1</code> by <code>s2</code> index first:</p> <pre><code>s1.index = s2.index df = pd.concat([s1, s2], axis=1) print (df) s1 s2 a 1.5 1 b 2.0 2 </code></pre>
python|pandas
4
364,351
45,307,525
Getting "ValueError: operands could not be broadcast together with shapes" when trying to subtract from channel wise mean in Caffe
<p>This is a follow-up question from <a href="https://stackoverflow.com/questions/45294732/caffes-transformer-preprocessing-takes-too-long-to-complete">this</a>. Basically what I want to do is to simply subtract each image from the mean.</p> <p>Based on this issue on <a href="https://github.com/BVLC/caffe/issues/1928"...
<p>replace</p> <pre><code>mu = mean_file.mean(1).mean(1) </code></pre> <p>with</p> <pre><code>mu = mean_file.mean(1).mean(1)[:,None,None] </code></pre> <p>It seems like you are trying to subtract a 1D vector (<code>shape</code> of <code>(3,)</code>) from a 3D array (<code>shape</code> of <code>(3,224,224)</code>). ...
python|numpy|caffe|pycaffe
1
364,352
45,440,423
Sorting DataFrame by values of a column
<p>I want to sort this dataframe by values of "Score"(from giggest to smalles or vice versa, I just want some order here) I coded at end: <code>models.sort_values(by='Score', ascending=False)</code></p> <pre><code> Model Score 0 Support Vector Machines 0.685315 1 ...
<p><code>sort_values</code> is not in-place by default. From the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>DataFrame.sort_values(by, axis=0, ascending=True, <strong>inplace=False</strong>, kind='quicksort...
python|pandas
2
364,353
45,640,525
Determining Sum while excluding certain values
<p>I need some help with a vert quick calculation, in the denominator line below I need to get the sum of the string occurances, yet only need to sum over values which are above a value, so for example, I need to get the sum of all of them, but exclude the number that comes with a certain occurance at 2, so theoretical...
<p>Using a conditional index:</p> <pre><code>denominator = occurances[occurances &gt; occurances(2)].sum() </code></pre>
python|excel|pandas|sum
0
364,354
45,535,976
Aggregating time series data keeping date column in Python
<p>I have a dataset as below:</p> <pre><code>date jobcategory 2016-01-01 SP 2016-01-01 DP 2016-01-01 SP 2016-01-01 CP 2016-01-01 DP 2016-01-01 DP 2016-01-01 DP 2016-01-02 SP 2016-01-02 CP 2016-01-02 SP 2016-01-02 CP 2016-01-02 D...
<p>First use <code>df.groupby</code> on <code>date</code> and then <code>df.merge</code> with the original date column to get 0 counts as well.</p> <pre><code>In [921]: df[df.jobcategory == 'SP'].groupby('date', as_index=False).count().merge(df[['date']].drop_duplicates(), how='outer').fillna(0) Out[921]: dat...
python|pandas|dataframe|time-series|aggregate
0
364,355
45,707,040
Panda Index Datetime Switching Months and Days
<p>I have a panda df.index in the format below.</p> <p>It's a string of day/month/year, so the first item is 05Sep2017 etc:</p> <ol> <li>05/09/17 #05Sep2017</li> <li>07/09/17 #07Sep2017</li> <li>...</li> <li>18/10/17 #18Oct2017</li> </ol> <p>Applying</p> <pre><code>df.index = pd.to_datetime(df.index) </code></p...
<p>In pandas is default format of <code>date</code>s <code>YY-MM-DD</code>.</p> <pre><code>df = df.set_index('date_col') df.index = pd.to_datetime(df.index) print (df) val 2017-05-09 4 2017-07-09 8 2017-10-18 2 print (df.index) DatetimeIndex(['2017-05-09', '2017-07-09', '2017-10-18'], dtype='date...
pandas|datetime|indexing|format
0
364,356
45,667,375
Problems with running model zoo models for Tensorflow object detection API
<p>I am running Google's tensorflow object-detection API's jupyter notebook on an Ubuntu 16.04 Parallels desktop on my Mac. I wanted to test out one of the non-default models (i.e. not SSD with Mobilenet) to see how the accuracy of the bounding boxes may change on an object-detection task.</p> <p>I changed the section...
<p>As it turns out, this issue was caused because I was not allocating sufficient memory to Parallels. The script worked after I allocated more memory. Thanks for the tip Jonathan!</p>
tensorflow|object-detection
1
364,357
45,529,073
Moving/running window of a Multi-dimensional image array
<p>I am trying to work on an efficient numpy solution to perform a running average of an array of color images across the 4th dimension. A set of color images in a directory is read in a loop and I would like to average in subsets of 3. ie. If there are n = 5 color images in the directory I would like to average [1,2,3...
<p>For performing local operations (such as a running average) across the pixels of an image (or across multiple images), <a href="https://en.wikipedia.org/wiki/Kernel_(image_processing)#Convolution" rel="nofollow noreferrer">convolution with a kernel</a> is usually a good approach.</p> <p>Here's how this could be don...
python|opencv|numpy|moving-average
2
364,358
45,362,726
How to properly serve an object detection model from Tensorflow Object Detection API?
<p>I am using Tensorflow Object Detection API(github.com/tensorflow/models/tree/master/object_detection) with one object detection task. Right now I am having problem on serving the detection model I trained with Tensorflow Serving(tensorflow.github.io/serving/).</p> <p><strong>1.</strong> The first issue I am encount...
<p>The current exporter code doesn't populate signature field properly. So serving using model server doesn't work. Apologies to that. A new version to better support exporting the model is coming. It includes some important fixes and improvements needed for serving, especially serving on Cloud ML Engine. See the <a hr...
tensorflow|object-detection|tensorflow-serving
2
364,359
45,424,430
dealing with "NA" as both missing value and ordinal feature value
<p>I have a <code>.txt</code> dataset with about 80 features, where it appears that <code>"NA"</code> is used as both an indicator of a missing value, as well as an actual value for particular ordinal string features, such as:</p> <p><a href="https://i.stack.imgur.com/Jbhs9.png" rel="nofollow noreferrer"><img src="htt...
<p>In <code>Jupyter</code> I use the <code>%%writefile</code> magic to set up a test file. This isn't necessary if you already have a file. </p> <pre><code>%%writefile test.csv col1,col2,col3 Ex,1.,2. Gd,3.,4. TA,5.,NA NA,6.,7. </code></pre> <p><strong>Solution</strong><br> parse twice, requires that I know the nam...
python|pandas|missing-data
2
364,360
45,439,382
Python How to improve numpy array performance?
<p>I have a global numpy.array <strong>data</strong> which is a 200*200*3 3d-array containing 40000 points in the 3d-space.</p> <p>My goal is to calculate the distance from each point to the four corners of the unit cube ((0, 0, 0),(1, 0, 0),(0, 1, 0),(0, 0, 1)),so I can determine which corner is the nearest from the ...
<p>You could use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>Scipy cdist</code></a> -</p> <pre><code># unit cube coordinates as array uc = np.array([[0, 0, 0],[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # buffer output buf = cdist(data.reshape...
python|performance|numpy|optimization|profile
3
364,361
45,535,727
Why Pandas allows editing DataFrames but not Series objects
<p>Suppose I have a dataset like below : <a href="https://i.stack.imgur.com/UGgRj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UGgRj.png" alt="enter image description here"></a></p> <p>When I try to overwrite a specific column (Series object), I get the error with the following code :</p> <pre>...
<p>There is problem you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> for avoid <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy" rel="nofollow noreferrer">chained indexing</a...
python|pandas
0
364,362
45,296,275
Setting up pie charts subplots with an appropriate size and spacing
<p>I'm struggling setting up pie chart subplots with an appropriate size and spacing. If the size of a pie chart is to small then the data is not visible, if the spacing between subplots is not appropriate then the graph will be crammed up. So the layout of the subplots is the following 3 rows; 2 columns. Please see be...
<p>Have a look at this excellent answer: <a href="https://stackoverflow.com/questions/39629735/how-to-plot-pie-charts-as-subplots-with-custom-size-with-plotly-in-python">How to plot pie charts as subplots with custom size with Plotly in Python</a></p> <p>In order to get identically size plots their <code>domain</code>...
python|python-3.x|pandas|plotly
1
364,363
45,584,557
How to show all my images in tensorboard?
<p>I only see images which are currently residing in symbolic tensor (logits, label):</p> <pre><code>with tf.name_scope("Train"): optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(cost_function) tf.summary.image('logits', tn_logits, max_outputs=4) tf.summary.image('label', t_label, max_outpu...
<p>The first dimension of image tensor and <code>max_output</code> argument of <code>tf.summary.image</code> define number of images in tensorboard gallery. Since you write 1 image at a time, the existing images are overwritten. </p> <p>Instead of iterating, concatenate 4 images such that <code>tn_logits</code> and <c...
tensorflow|tensorboard
4
364,364
45,372,019
How can I loop over only specific columns from a text file using pandas?
<p>I want to only do this loop:</p> <pre><code>for col in result.columns: result[col] = result[col].str.strip("{} ") </code></pre> <p>for columns "1H.L" and "1H_2.L" because the other columns aren't strings.</p> <p>My code is:</p> <pre><code>import pandas as pd result = {} text = 'fe' filename = 'fe_yellow.xpk...
<p>why can't you go with straight forward,</p> <pre><code>for col in result.columns: if col == ("1H.L" | "1H_2.L"): result[col] = result[col].str.strip("{} ") </code></pre>
python|pandas
1
364,365
45,301,319
How to vectorize/tensorize operations in numpy with irregular array shapes
<p>I would like to perform the operation</p> <p><img src="https://latex.codecogs.com/gif.latex?%24A_%7Bijk%7D%3D%20%5Csum_%7Bp%7DX_%7Bijp%7D%5Calpha_%7Bipk%7D%24" alt="form1"></p> <p>If <img src="https://latex.codecogs.com/gif.latex?%24A_%7Bijk%7D" alt="form2"> had a regular shape, then I could use np.einsum, I beli...
<p>I know this sounds obvious, but, if you can afford the memory, I'd start just by checking the performance you get simply by padding the data to have a uniform size, that is, simply adding zeros and perform the operation. Sometimes a simpler solution is faster than a more supposedly optimal one that has more Python/C...
python|numpy|vectorization|tensor|numpy-einsum
1
364,366
45,519,420
ValueError: Maximum allowed size exceeded, variable will range from 0 to 3e33
<p>I have this strange problem with np.arange. I want to plot a simple equation which basically looks like y = Ax^{-1/3}(1-Bx^{4/3})^{1/2}</p> <p>However, I can get a almost working-quality plot from wolfram mathematica with my provided equation but I am struggling to generate the same plot in python! </p> <pre><code...
<p>There are several problems in the code:</p> <ol> <li><code>x</code> has too many points. Reduce the number of points, to e.g. 1000 points.</li> <li><p><code>x</code> should not start at <code>0</code>, since <code>0**(-1/3)</code> is undefined (you cannot divide by 0). Thus a sensible definition of <code>x</code> m...
python|numpy|matplotlib
2
364,367
62,832,360
SVD image reconstruction in Python
<p>I am trying to do a Singular Value Decomposition of this image:</p> <p><img src="https://i.stack.imgur.com/sqrAy.jpg" alt="enter image description here" /></p> <p>taking the first 10 values. I have this code:</p> <pre><code>from PIL import Image import numpy as np img = Image.open('bee.jpg') img = np.mean(img, 2) U...
<p>The issue is the dimension of <code>s</code>, if you print the <code>U</code>, <code>s</code> and <code>V</code> dimensions, I get:</p> <pre><code>print(np.shape(U)) print(np.shape(s)) print(np.shape(V)) (819, 819) (819,) (1024, 1024) </code></pre> <p>So <code>U</code> and <code>V</code> are square matrix, <code>s<...
python|python-3.x|image|numpy|svd
1
364,368
62,595,943
Concatenate two object columns pandas
<p>I am trying to conceatenate three columns of datatype object. I am reading a XLSM file:</p> <pre><code>for filename in os.listdir(input_dir): if filename.endswith(&quot;.XLSM&quot;): file_dir = os.path.join(input_dir, filename) df = pd.read_excel(file_dir, sheet_name=0) B = df[&quot;- &...
<p>removing <code>index = ID</code> solved my problem!</p> <pre><code>df_ = pd.DataFrame(columns=[&quot;ACTIVE&quot;, &quot;NAME&quot;]) </code></pre>
python|python-3.x|pandas|csv
0
364,369
62,660,437
Tensorflow / Tflearn ValueError: Cannot feed value of shape (4, 11, 11) for Tensor 'input/X:0', which has shape '(?, 4, 11, 11)'
<p>I have following error:</p> <p>File &quot;D:\python\WPy64-3740\python-3.7.4.amd64\lib\site-packages\tensorflow\python\client\session.py&quot;, line 1149, in _run str(subfeed_t.get_shape())))</p> <p>ValueError: Cannot feed value of shape (4, 11, 11) for Tensor 'input/X:0', which has shape '(?, 4, 11, 11)'</p> <p>My c...
<p>I sloved this problem by myself. Actually the construction of this network is correct, the problem is in the second last line:</p> <pre><code>x0=train_state[34] pred0=m.predict(x0) </code></pre> <p>when I change these two line to:</p> <pre><code>x0=[train_state[34]] pred0=m.predict(x0) </code></pre> <p>then it works...
python|tensorflow|tflearn
0
364,370
62,589,217
How to read boto3 StreamingBody into .parquet file?
<p>I am reading a parquet file with a pandas dataframe inside.</p> <pre><code>o = s3_client.get_object(Bucket='zak-zak', Key='2020-01/2000001.parq') o['Body'].read() </code></pre> <p><code>'b\'PAR1\\x15\\x00\\x15,\\x15,,\\x15\\x02\\x15\\x00\\x15\\x06\\x15\\x08\\x00\\x00\\x02\\x00\\</code> but it is in the bit-format.</...
<p>Have you tried using <code>o['Body'].read().decode('utf-8')</code>?</p>
pandas|dataframe|boto3|parquet
0
364,371
62,876,421
Within group move date to same date in prior year if certain condition is met
<p>I have a pandas dataframe which looks like this</p> <pre><code>pd.DataFrame({'a':['cust1', 'cust1', 'cust1', 'cust1', 'cust1', 'cust1', 'cust1', 'cust2', 'cust2', 'cust3', 'cust3', 'cust3'], 'date':[date(2017, 6, 15), date(2017, 12, 15), date(2018, 6, 15), date(2019, 1, 20), date(2019, 6, 15), dat...
<p>Let's try <code>ffill()</code> on the <code>shift()</code> month series</p> <pre><code>months = df.date.dt.month s = months.eq(12).groupby(df['a']).shift() df['date'] = np.where(months.eq(1) &amp; s.where(s).groupby(df['a']).ffill(), df['date'] - pd.tseries.offsets.MonthOffset(), ...
python|pandas|dataframe
2
364,372
62,774,246
Creating timedelta column from a datetime64[ns] column which has NaT values?
<p>I am reading in a CSV file.</p> <pre><code>df = pd.read_csv('xyz.csv',parse_dates=['last_time']) </code></pre> <p>The <code>dtype</code> of <code>last_tweeted</code> column is <code>datetime64[ns]</code>.</p> <p>The column contains only <code>1 datetime64[ns]</code> rest are all <code>NaT</code> for now.</p> <pre><c...
<p>Remove <code>df[]</code>, it is used for <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> by some mask:</p> <pre><code>df['time_since'] = df['last_time'] - datetime.datetime.now() </code></pre>
python|pandas|dataframe
1
364,373
62,642,728
Generating DataFrame from Key Value Pairs
<p>I have a list of dictionaries with key value pairs that I would like to create a DataFrame from and I thought that the <code>from_items()</code> method would be the simplest method to do so, but it appears that attribute does not exist. What could be wrong about my approach that is throwing the error and is there a ...
<p>IIUC, you have:</p> <pre><code>ldicts = [{'id': 'people5', 'title': 'Stakeholder', 'text': '', 'type': 'multiple-person', 'value': None }, {'id': 'people5', 'title': 'Stakeholder', 'text': 'Test', 'type': 'multiple-person', 'value': 'Michael' }] </code></pre> <p>You can use the pd.DataFrame c...
pandas
1
364,374
62,606,468
How to search a 1 x 9 x N dimension np.array for a 1 x 9 dimension np.array?
<p>I am solving the 8 Puzzle Problem. After creating the possible move states and selecting the best one, I am appending the array for the current best move, to an array called used set.</p> <pre><code>bestMove = [0,1,2,3,4,5,6,7,8] usedSet = [0,1,2,3,4,5,6,7,8] [1,0,2,3,4,5,6,7,8] [0,1,2,3,4,5,6,7,8] [1,0,2,3,4,5,6,...
<p>Unless you have a compelling reason to use numpy arrays this seems like a better fit for the Python built-in types:</p> <p>You can encode your moves as <code>tuple</code>s and store them in a <code>set</code>:</p> <pre><code>&gt;&gt;&gt; usedset = set() &gt;&gt;&gt; bestmove = (0, 1, 2, 3, 4, 5, 6, 7, 8) &gt;&gt;&gt...
python|arrays|python-3.x|numpy|sorting
0
364,375
62,484,920
How to use date in the index in the same way as in a column?
<p>I am trying to follow the excellent answer from <a href="https://stackoverflow.com/questions/62478968/how-to-make-day-of-the-week-flags-from-datetime-index-in-pandas">How to make day of the week flags from datetime index in pandas</a>. The code I am using is:</p> <pre><code>pd.concat((testdf, pd.get_dummies(testdf.i...
<pre><code>import pandas as pd df = pd.concat((testdf.reset_index(), pd.get_dummies(testdf.index.astype('datetime64[ns]').day_name())), axis=1).set_index('Time (CET)') df = df[['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']] df </code></pre>
python|pandas
1
364,376
62,756,323
Dynamic pandas dataframe filter not working
<p>I can't get this dynamic filter work</p> <p><strong>df_dates</strong></p> <pre><code>print(df_dates) Type Entry Exit 0 2008-03-03 2008-03-17 1 2010-05-19 2010-06-10 </code></pre> <p><strong>This hardcoded filter is working</strong></p> <pre><code>df_to_filter = df_to_filter[ (df_to...
<p>If You have for example dataframes:</p> <p><code>df_dates:</code></p> <pre><code>Type Entry Exit 0 2008-03-03 2008-03-17 1 2010-05-19 2010-06-10 </code></pre> <p><code>df_to_filter:</code></p> <pre><code>date 2008-03-03 2010-06-11 </code></pre> <p>Then You can filter it using <code>filter_mask</c...
python|pandas|filter
1
364,377
62,621,926
How to do rolling applying a function using all historic data up to a date?
<p>I have a monthly time-series pandas dataframe and would like to do rolling using all past data e.g. I have data from 1990-01-01 to 2020-01-01. Then I'd like to start from 1999-12-31 and do:</p> <pre><code>df = pd.DataFrame() df['1990-01-01':'1999-12-31'].apply(myfun) df['1990-01-01':'2000-01-31'].apply(myfun) df['19...
<p>the rolling function can apply to a Pandas Series. You can caluclate the rolling mean, or any other function that you need. For example:</p> <pre><code>import pandas as pd serie = pd.Series([1, 2, 0, 0, 1, 2, 0, 0]) serie.rolling(window=3).mean() </code></pre> <p>output: Out[19]: 0 NaN 1 NaN 2 1...
python|pandas|time-series
1
364,378
62,843,629
Can a model trained using a GPU be used for inference on a CPU?
<p>I want to run inference on the CPU; although my machine has a GPU. I wonder if it's possible to force TensorFlow to use the CPU rather than the GPU?</p> <p>By default, TensorFlow will automatically use GPU for inference, but since my GPU is not good (OOM'ed), I wonder if there's a setting to force Tensorflow to use ...
<p>Assuming you're using TensorFlow 2.0, please check out this issue on GitHub:</p> <ul> <li><a href="https://github.com/tensorflow/tensorflow/issues/31135" rel="nofollow noreferrer">[TF 2.0] How to globally force CPU?</a></li> </ul> <p>The solution seems to be to hide the GPU devices from TensorFlow. You can do that u...
tensorflow|tensorflow-serving
1
364,379
62,549,528
Should I use any() when applying a mask to a pandas dataframe here? And if so, how?
<p>I am trying to filter rows from a dataframe by applying a mask with a bunch of logical statements like so:</p> <pre><code>mask = ( (stock_hist['confirmed'] == True and \ stock_hist['prevday_confirmed'] == False and \ stock_hist['nextday_confirmed'] == False \ ) \ or \ ...
<p>In place of <code>and</code> and <code>or</code>, you need to use <code>&amp;</code> and <code>|</code>, respectively. Something like:</p> <pre><code>( (stock_hist['confirmed'] &amp; \ ~(stock_hist['prevday_confirmed']) &amp; \ ~(stock_hist['nextday_confirmed']) \ ) \ |...
python|pandas
0
364,380
62,777,889
Transfer learning with TensorFlow Hub: using a single test image?
<p>I have successfully followed this official tutorial on image classification with transfer learning: <a href="https://www.tensorflow.org/tutorials/images/transfer_learning_with_hub" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/transfer_learning_with_hub</a></p> <p>My experimental model is now...
<p>Here's how to do it with mobilenet transfer learning with keras but most of the code should be the same. A full transfer learning tutorial can be found <a href="https://towardsdatascience.com/transfer-learning-using-mobilenet-and-keras-c75daf7ff299" rel="nofollow noreferrer">here</a>. I found it very useful.</p> <pr...
tensorflow|keras
1
364,381
62,746,529
How to migrate Dense layers from Tensorflow 1 to Tensorflow 2?
<p>How I could migrate this layer to tf2</p> <pre><code>observations = tf.placeholder(tf.float32,[None, OBSERVATIONS_SIZE]) h = tf.layers.dense( observations, units=hidden_layer_size, activation=tf.nn.relu, kernel_initializer=tf.contrib.layers.xavier_initializer() ) </code></pre> <p>I Found that t...
<p>Keras layers are not used as <code>tf.layers</code>, they are callable instead of passing a tensor as the first parameter, so it should be:</p> <pre><code>observations = tf.keras.Input( shape = [ None, OBSERVATIONS_SIZE ], dtype = tf.float32 ) h = tf.keras.layers.Dense( units=hidden_layer_size, ...
python|tensorflow|keras
1
364,382
62,648,122
Python Vaex data type conversion
<p>I'm utilizing the Vaex library in Python for a project; I'm still very new to Vaex so I apologize if this is elementary. I'm having an issue with a data type conversion. One of my columns 'Paid_at' has a datatype of str, and it should be a DateTime. <a href="https://i.stack.imgur.com/sgHGN.png" rel="nofollow norefer...
<pre><code>df2['pdate']=df2.date.astype('datetime64[ns]') </code></pre> <p>was solved here: <a href="https://github.com/vaexio/vaex/pull/440" rel="noreferrer">https://github.com/vaexio/vaex/pull/440</a></p>
python|pandas|dataframe|vaex
6
364,383
62,491,166
numpy index access vs numpy.array.item performance
<p>I've been using <em>numpy</em> for sometime, and was used to access arrays by using the <code>index</code> operation, just like python lists, like so:</p> <pre class="lang-py prettyprint-override"><code>img = np.zeros((640,480,3)) img[34, 19, 2] </code></pre> <p>However reading a certain book, I came across the <a h...
<p><strong>TL;DR:</strong> The difference of speed comes from the <strong>different types</strong> used by <code>item</code>/<code>itemset</code> and the fact that the <code>[]</code> operator is <strong>more generic</strong>. Indeed, both use the built-in <code>float</code> type of the Python interpreter while <code>i...
numpy
2
364,384
62,516,260
Dataframe rolling mean, replaces column, how do I keep the original column and add the rolling mean as a new column?
<p>I have a DF:</p> <pre><code> tbname stat_day count 0 calc_10 2020-05-01 0 1 calc_10 2020-05-02 0 2 calc_10 2020-05-03 0 &lt;snip&gt; 49 calc_10 2020-06-19 361 50 calc_10 2020-06-20 506 51 calc_10 2020-06-21 0 52 calc_10 2020-06-22 0 53 cal...
<p>You don't have to do it in two steps. You can use the <code>transform</code> function to do it in one line and just add the moving average column to your base dataframe.</p> <p>I changed your data a bit to make an example. See below for base data, the command, and the output that I think you're looking for. I use...
pandas|dataframe|mean|rolling-computation
0
364,385
62,514,654
How to merge using outer join if there is common / no common column or unknown column in pandas
<p><strong>Problem Statement:</strong> How to perform outer join if we dont have common key (as any additional key appear on</p> <p><strong>df_a from json_1:</strong></p> <pre><code>[ { &quot;bookid&quot;: &quot;12345&quot;, &quot;bookname&quot;: &quot;who am i&quot; } ] </code>...
<p>One way is to align both the data frames so that the columns are same using <code>.align()</code>.</p> <pre><code>_, df_a = df_b.align(df_a, fill_value=np.NaN) _, df_b = df_a.align(df_b, fill_value=np.NaN) </code></pre> <p>Once you do this, both <code>df_a</code> and <code>df_b</code> will have the same columns.</p>...
python|json|pandas|merge
1
364,386
62,642,034
How to write a RNN with RNNCell in pytorch?
<p>I am trying to rewrite a code from <a href="https://ethen8181.github.io/machine-learning/deep_learning/rnn/1_pytorch_rnn.html#Vanilla-RNN" rel="nofollow noreferrer">this simple Vanilla RNN</a> to RNNCell format in pytorch. This is the full code</p> <pre><code>import torch import torch.nn as nn from torch.autograd im...
<p>I am not sure the rest of your code is alright, but in order to fix this error, you can convert your rnn_out list to a torch tensor by adding the following line after the ending of your for loop:</p> <pre><code>rnn_out = torch.stack(rnn_out) </code></pre>
nlp|pytorch|recurrent-neural-network|seq2seq
1
364,387
62,573,318
How to find the exact name of the output node in .pb file?
<p>I was trying to freeze a pb file for using in the OpenVino. For freezing, i need to know the output node name. For that, i tried loading the pb file and reading the output names, but, it got an error. Then i tried to get the output name from the model summary and it was dense_7 (Dense).</p> <p>I followed the command...
<ul> <li><p>Question 26 in the ‘Model Optimizer Frequently Asked Questions’ page addresses the error that you are facing. See <a href="https://docs.openvinotoolkit.org/2020.3/_docs_MO_DG_prepare_model_Model_Optimizer_FAQ.html" rel="nofollow noreferrer">https://docs.openvinotoolkit.org/2020.3/_docs_MO_DG_prepare_model_M...
tensorflow|tensorflow2.0|openvino
3
364,388
62,872,089
How to split test and train data in a dataset based on number of targets in each category
<p>I have an <code>imageFolder</code> in PyTorch which holds my categorized data images. Each folder is the name of the category and in the folder are images of that category.</p> <p>I've loaded data and split train and test data via a sampler with random <code>train_test_split</code>. But the problem is my data distri...
<p>Use the <code>stratify</code> argument in <code>train_test_split</code> according to the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer">docs</a>. If your label indices is an array-like called <code>y</code>, do:</p> <pre class="lang...
python|pytorch
3
364,389
62,669,537
Does TensorFlow Lite Have a Low Power Consumption Mode?
<p>I saw that TF Lite has a <a href="https://www.tensorflow.org/lite/performance/nnapi" rel="nofollow noreferrer">delegate</a> that uses NNAPI for hardware acceleration. I was reading up on <a href="https://developer.android.com/ndk/guides/neuralnetworks" rel="nofollow noreferrer">NNAPI</a> and I saw that it has a <a ...
<p>You can use the low-power option on the NNAPI delegate by setting <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/delegates/nnapi/java/src/main/java/org/tensorflow/lite/nnapi/NnApiDelegate.java#L42" rel="nofollow noreferrer">this option</a> while creating the delegate as mentioned in th...
android|tensorflow|tensorflow-lite
0
364,390
62,627,235
cv2.imshow and write video frames in colab
<p>I am trying to run this <a href="https://github.com/xamyzhao/timecraft/blob/master/make_timelapse.py" rel="nofollow noreferrer">https://github.com/xamyzhao/timecraft/blob/master/make_timelapse.py</a></p> <p>and colab does not support cv2.imshow so I changed this part</p> <pre><code>for i in range(n_samples): pre...
<p>This is not a google colab issue. pred_vid_im holds the normalized value. So all the values will be between 0 and 1. That's why the saved image is black. So you need to multiply pred_vid_im with 255.0. Change the code to this,</p> <pre><code>pred_vid_im = vis_utils.visualize_video(pred_vid[0], normalized=True) * 255...
tensorflow|opencv|keras|google-colaboratory
1
364,391
62,710,532
Combine two graphs of two dataframe into one graph
<p>I want to combine two graphs into one graph. I think it is quite simple but I could not figure it out. haha..</p> <p><code>sns.countplot(x=low_tenure.Partner)</code></p> <p><a href="https://i.stack.imgur.com/uoNVfm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uoNVfm.png" alt="enter image descri...
<p>You could use common axis.</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(111) sns.countplot(data1, ax=ax) sns.countplot(data2, ax=ax) </code></pre>
python|pandas
2
364,392
62,661,477
Fill Zero values in Pandas column based on last non-zero value if a criteria is fulfilled
<p>Consider a Pandas DataFrame <code>test = pd.DataFrame(data = [0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0], columns = ['holding'])</code></p> <p><code>Output:</code></p> <pre><code>+----------+ | Holdings | +----------+ | 0 | | 0 | | 1 | | 0 | | 0 | | 0 | | -1 | | 0 ...
<p>My approach:</p> <pre><code>after = test.holding.eq(1) before = test.holding.eq(-1) test['pos_holding'] = test.holding.mask(test.holding.where(after|before).ffill()==1,1) </code></pre> <p>Equivalent code, a bit shorter:</p> <pre><code>mask = test.holding.where(test.holding != 0).ffill() test['pos_holding'] = test.h...
python|pandas|multiple-conditions
2
364,393
62,581,275
How do I parse data points in numpy array python?
<p>I have a numpy array with shape (100,100). It has values in it like -.320+0.323i. How do I separate this into two separate numpy arrays, one with the real values and one with the &quot;i&quot; values?</p>
<p>You can use built-in functions .real and .imag like this:</p> <pre><code>import numpy a = numpy.array([1.+0.j, 1.+0.j, 1.+0.j]) realparts = a.real imagparts = a.imag </code></pre>
python|arrays|numpy|parsing
0
364,394
62,518,906
Keras ImageDataGenerator : how to use data augmentation with images paths
<p>I am working on a CNN model and I would like to use some data augmentation, but two problems arise :</p> <ol> <li><strong>My labels are images</strong> (my model is some kind of autoencoder, but the expected output images are different from my input images), thus I cannot use functions such as <code>ImageDataGenerat...
<p>Ok so I finally found out how to deal with these issues thanks to <a href="https://medium.com/the-artificial-impostor/custom-image-augmentation-with-keras-70595b01aeac" rel="nofollow noreferrer">this article</a>. My mistake was that I kept using <code>ImageDataGenerator</code> despite its lack of flexibility, the so...
python|tensorflow|keras|deep-learning|data-augmentation
3
364,395
62,643,383
Why does this matrix calculation goes 0?
<p>I'm in trouble with this matrix calculation in python. I have matrix as numpy array<code>a = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]])</code> and tried some calculation. But I got the error like</p> <blockquote> <p>RuntimeWarning: invalid value encountered in true_divide</p> </blockquote> <p>So I checked out some ...
<p>Matrix multiplication is done using <code>@</code> in Python with <code>np.array</code>. With <code>*</code> you get the Hadamard product.</p>
python|python-3.x|numpy
2
364,396
62,764,999
How to check if every first element of the tuple is equal to its second element in a dataframe column python
<p>I have a dataframe as below:</p> <pre><code> Data (15019, 20218) (20218, 20218) (20210, 20210) (2266, 4905) (2429, 2429) </code></pre> <p>I need check if first element of the tuple is equal to its second element for Data column and flag as yes.</p> <p>desired output:</p> <pre><code> Data ...
<p>Change to</p> <pre><code>df['Flag'] = np.where(df['Data'].str[0]==df['Data'].str[1] , 'Yes', 'No') </code></pre>
python|pandas|numpy|tuples
1
364,397
62,835,006
pandas matching database with string keeping index of database
<p>I have a database with strings and the index as below.</p> <pre><code>df0 idx name_id_code string_line_0 0 0.01 A 1 0.5 B 2 77.6 C 3 29.8 D 4 56.2 E 5 88.1000005 F 6 66.4000008 G 7 2.1 H 8 99 I 9 550.9999999 J df1 idx string_line_1 0 A 1 F 2 J 3 G 4 D </code></pre> <p>Now, I want to match the df1 with df0, taking ...
<p>Because is filtered <code>df0</code> DataFrame then is index values not changed if use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> by <code>df1['string_line_1'</code>, only order of columns is like in original <cod...
python|pandas
3
364,398
62,591,987
How to aggregate data in hour based on timestamp in pandas?
<p>I have a dataframe a day full from 00:00:00 to 23:59:59 the table bellow is just and example, I can't paste it here because it's too long.</p> <pre><code>id sm_log_time score 1 score 2 0 2020-04-15 15:25:49 10 10 1 2020-04-15 15:38:55 ...
<p>First setting index is necessary. Then use <code>resample</code> method of time series index:</p> <pre><code>df.set_index('sm_log_time').resample('H').sum().reset_index() </code></pre> <p>Result:</p> <pre><code> sm_log_time id score 1 score 2 0 2020-04-15 15:00:00 3 30 30 1 2020-04-15 16:00...
python|pandas
0
364,399
62,729,238
How to merger same column values based on other column values?
<p>How to add a new column in pandas dataframe based on other column values , for example, Id columns has value and column Value has different values for Id, it needs to be merged as in the output.</p> <p>df:</p> <pre><code># dictionary of lists data = {'Id':[&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;,...
<pre><code>df.groupby('Id')['Value'].apply(', '.join).reset_index() print(df) </code></pre> <p>Output:</p> <pre><code> Id Value 0 A S1, S2 1 B S3, S3, S5 2 C S6 3 D S7 4 E S8, S9 </code></pre>
python|python-3.x|pandas|python-2.7
3