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
16,500
40,522,249
Sum amount associated with item in a column of lists
<p>I have a dataframe as follows:</p> <pre><code>country letter keywords amount c y ['fruits', 'apples', "banana"] 700 c y ["music", "dance", "banana"] 150 c y ['loud', "dance", "apples"] 350 </code></pre> <p>I'd like to...
<p>You can use:</p> <pre><code>df1 = pd.DataFrame(df.keywords.values.tolist()) .stack() .reset_index(level=1, drop=True) .rename('keywords') print (df1) 0 fruits 0 apples 0 banana 1 music 1 dance 1 banana 2 loud 2 dance 2 apples Name: keywords, dtype: object print ...
python|pandas|dataframe
2
16,501
62,040,978
Changing integer of year and week to datetime
<p>how can I convert a lot of data in a dataframe from an integer to a datetime? But I only have Year and Week data like the example. The column is named 'Year_Week' and should be tranformed complete.</p> <pre><code>for example: Year_Week 201601 201602 201603 ... 201652 </code></pre> <p>so ist should be converted lik...
<p>datetime.datetime.strptime(dateString + '-1', "%Y%W-%w") parameter only looks at one string object. To convert whole series into datetime, you need to do something like this:</p> <pre><code>pd.to_datetime(df['Year_Week']+ '-1',format="%Y%W-%w") </code></pre>
python|pandas|datetime
1
16,502
62,014,845
Need help in task of panda dataframe (juypternotebook) HELP NEW problem "Only the most traded stock of the firm"
<p>Hi guys i started at jupyter notebook few days ago.</p> <p>I need help, i have a dataframe by panda. something like this</p> <pre><code>Date Stock Company Volume 01/02 APPL3 Apple 1.000.000 01/02 YUSS Yusduqs 200.000 01/02 APPL4 Apple 200.000 01/02 DISN Disney 1....
<p>You can know the frequency of stocks which traded greater than 500000 for 80% of days by,</p> <pre><code>unique_dates=len(df['Date'].value_counts()) share_freq=df[df['Volume']&gt;=500000]]['Stock'].value_counts() stocks=share_freq/unique_dates for stock,value in stocks.items(): if(value&gt;0.8): print(s...
python|pandas|dataframe|jupyter-notebook
1
16,503
61,734,183
Slicing grouped dataframes carries more rows than expected
<p>I am trying to filter a dataframe, which has already been produced by a <code>groupby()</code>. An example of the grouped dataframe is below:</p> <pre><code>all_dists less more district answer N yes 9.0 1.0 no 0.0 0.0 maybe 0.0 0.0 W ye...
<p>With the given sample, both <code>grouped_df.loc[(slice(None), slice('yes')), 'less']</code> and <code>grouped_df.loc[(slice(None), slice('no')), 'less']</code> gives me the error:</p> <pre><code>UnsortedIndexError: 'MultiIndex slicing requires the index to be lexsorted: slicing on levels [1], lexsort depth 0' </c...
python|pandas|group-by|slice
0
16,504
57,878,438
Pandas - Create new column from calculation over irregular string patterns
<p>I have some data in a pandas dataframe like so:</p> <pre><code>| Data | ---------------------------- | 10-9 8-6 100-2 | ---------------------------- | 1-2 3-4 | ---------------------------- | 55-45 | ---------------------------- </code></pre> <...
<p>Make a function to contain the string parsing logic:</p> <pre><code>import pandas as pd import numpy as np def string_handling(string): values = [it for it in string.strip().split(' ') if it] values = [v.split('-') for v in values] first_values = [int(v[0]) for v in values] second_values = [int(v[1...
python|regex|pandas
0
16,505
57,876,318
How to drop/delete dataframes from a dictionary based on the number of unique values in a column?
<p>I have a dictionary of 12 <code>dfs</code> named <code>f</code> and each <code>df</code> have the same columns: <code>BacksGas_Flow_sccm, ContextID, StepID,Time_Elapsed, iso_forest, alarm</code>.</p> <p>What I am trying to do is to count the number of unique values in the <code>BacksGas_Flow_sccm</code> column and ...
<p>Celius Stingher is right about the reason for the error</p> <blockquote> <p>I think that after deleting an item in the loop, the index resets and that's why you might be getting the error [....]</p> </blockquote> <p>This should work.</p> <pre><code>dictNew = dict() for key,value in f.items(): if (value['B...
python|python-3.x|pandas|dataframe
3
16,506
57,777,126
Working with Large operations that kill the kernel
<p>I have written the following code to load data from a postgres data base and do some operations on it. There are about 1million rows and the kernel keeps dying. When i limit the data size to about 10k, it works.</p> <pre><code>import psycopg2 import sys, os import numpy as np import pandas as pd import creds as cre...
<p>I guess the problem is with the "apply" method because it consumes a lot of memory. </p> <p>Try to replace it with : </p> <pre><code>data['accounts'] = [(t.source, t.destination) for t in data.itertuples()] </code></pre> <p>Let's try to test a <strong>Dataframe with 600,000 rows and 4 columns</strong></p> <p><st...
python|pandas|numpy|bigdata
2
16,507
58,166,923
Pandas convert float to int if decimals are 0
<p>I have a pandas dataframe, in which some columns have numeric values while others don't, as shown below:</p> <pre><code>City a b c Detroit 129 0.54 2,118.00 East 188 0.79 4,624.4712 Houston 154 0.65 3,492.1422 Los Angeles 266 1.00 7,426.00 Miami ...
<p>Use <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow noreferrer"><code>g format</code></a>:</p> <blockquote> <p>General format. For a given precision p &gt;= 1, this rounds the number to p significant digits and then formats the result in either fixed-point for...
python-3.x|pandas|dataframe
4
16,508
34,072,671
Append more than 2 data frames in pandas
<p>I have about 25 data frames with identical column headers that I need to append to one another. I've tried this in the past using 24 .append() calls but it didn't work. Is there a simple way to do this?</p>
<p>check <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/merging.html</a>, and the picture there is also very illustrative, copy the code here,</p> <pre><code>frames = [df1, df2, df3] result = pd.concat(frames) </code></pre>
python-3.x|pandas|dataframe
4
16,509
37,072,881
TensorFlow - Slicing tensor results in: ValueError: Shape (16491,) must have rank 3
<p>I want to slice tensor to get specific tensor by list of index, for example:</p> <pre><code>word_weight = tf.get_variable("word_weight", [20]) a= word_weight[ [1,6,5] ] </code></pre> <p><em>(I want to get <code>word_weight[1], word_weight[6], word_weight[5]</code>)</em></p> <p>But I get the following error when...
<p>First, evaluate the tensor first. Then, you can index them:</p> <pre><code>import tensorflow as tf word_weight = tf.get_variable("word_weight", [20]) with tf.Session() as sess: tf.initialize_all_variables().run() x = sess.run(word_weight) print(x[[1,6,5]]) # Or evaluete like this print(sess...
python|tensorflow|deep-learning
1
16,510
55,065,471
How to feed an image ROI into session.run() of Tensorflow?
<p>I am trying to feed my image roi into the Tensorflow classifier I took from <a href="https://github.com/burliEnterprises/tensorflow-image-classifier/blob/master/classify.py" rel="nofollow noreferrer">here</a>. The idea is to first run a simple filter, get rectangle candidates, and then check (using the network) whet...
<p>It's not a rocket science, it turns out.</p> <p>One somehow needs to convert image so that he can pass a string of image bytes, because that's what the function <code>sess.run()</code> expects.</p> <p>If you don't have a file that you want to load from a file system, then the following is the way:</p> <pre><code>...
python|dictionary|tensorflow
1
16,511
28,028,557
Selecting a range of time-series data and performing data analysis
<p>I have a monitoring device that monitors temperature, pressure and humidity. With this data I get the date and time of measurement. The measurements occur every 5 seconds. I want to write a function that gives me the average and standard deviation of temp, press, and humidity within a particular range of dates and t...
<p>This should do it. Slicing the df by time and date. You can change the function to only accept dates and then use the format 'yyyy-mm-dd hh:mm:ss' to slice it if you want just a continuous range of datetimes instead of having to select the time and date every time. </p> <pre><code>import pandas as pd import numpy a...
python|pandas|time-series
0
16,512
73,305,294
Using Streamlit and matplotlib to display a pandas dataframe bar plot
<p>At the moment I have:</p> <pre><code>fig, ax = plt.subplots() ax = df.plot.barh(stacked=True) st.pyplot(fig) </code></pre> <p>The dataframe for reference if necessary looks like:</p> <pre><code> A B C D E Cat1 5.3 NaN NaN NaN NaN Cat2 NaN NaN 12.1 NaN NaN Cat3 NaN NaN N...
<p>You can remove fig from st.pyplot() and streamlit will show your plot. Or you can render the horizontal bar plot with altair.</p> <p>Internal streamlit chart builder (that is altair's wrapper) will also produce your plot, but not with horizontal bars.</p> <pre><code>import pandas as pd import altair as alt import ma...
python|pandas|matplotlib|streamlit
0
16,513
73,352,191
Pass date as an argument in method to determine if today's date is Monday and decrease the date by 3
<p>I want to determine if a day on the date is Monday and then print the date as of Friday's date i.e. Monday-3. I am trying this following code.</p> <pre><code>def giveDate(date): if datetime.today().weekday()==0: print(&quot;Monday&quot;) date=date-3 print(date) giveDate(&quot;2022-08-15&q...
<p>Is this what you're after?:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime, timedelta def giveDate(date: str) -&gt; None: # Convert given date string to datetime date = datetime.strptime(date, '%Y-%m-%d') if datetime.now().weekday() == 0: print(&quot;Monday&qu...
python|pandas
0
16,514
73,504,732
Pivot table in pandas then convert to json table
<p>This is the code for the table I am starting with.</p> <pre><code>data = [['tom', 'class a', 20], ['nick', 'class a', 14], ['juli','class b', 14],['jane','class b', 155],['jone','class c', 80]] df = pd.DataFrame(data, columns=['Name', 'class', 'grade']) </code></pre> <div class="s-table-container"> <table class...
<p>You can use <code>df.to_dict(&quot;records&quot;)</code>. Docs: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html</a></p> <p>Output:</p> <pre><code>[{'class': 'class a', 'jane': nan...
python|json|pandas
2
16,515
73,194,331
Python Pandas : How do we pivot on rows and columns combination
<p>I have the following table structure.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> </tr> </thead> <tbody> <tr> <td></td> <td>Baseline</td> <td>Baseline</td> <td>Baseline</td> <td>...
<p>You can combine both header rows into a header first then uses <code>pandas.melt</code> method to convert your table into a long format; lastly, split the header column into 2 columns.</p> <pre class="lang-py prettyprint-override"><code>## clean null values df = df.fillna(&quot;&quot;) ## combine 2 rows to 1 as a h...
python-3.x|pandas|dataframe
1
16,516
67,402,394
Is there a nullable boolean type I can use in a Pandas dataframe?
<p>In a program I am working on I have to explicitly set the type of a column that contains boolean data. Sometimes all of the values in this column are None. Unless I provide explicit type information Pandas will infer the wrong type information for that column.</p> <p>Is there a pandas-compatible type that represents...
<p><code>boolean</code> dtype should work:</p> <pre><code>&gt;&gt;&gt; pd.Series([True, False, None]) 0 True 1 False 2 None dtype: object &gt;&gt;&gt; pd.Series([True, False, None]).astype(&quot;boolean&quot;) 0 True 1 False 2 &lt;NA&gt; dtype: boolean </code></pre>
pandas
2
16,517
67,279,869
non-broadcastable output operand with shape (5377,1) doesn't match the broadcast shape (5377,15)
<p>When I want to transform back to original form by using <code>inverse_transform</code> , I get the following error:</p> <pre><code> X_train = [] y_train = [] for i in range(120, data_training.shape[0]): X_train.append(data_training[i-120:i]) y_train.append(data_training[i,0]) X_train , y_train = np.array(X_tr...
<p>This error tells you that <code>NumPy</code> can't perform element-wise operation on these two arrays.</p> <p>This happens because, as described <a href="https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html#Broadcasting-example-1" rel="nofollow noreferrer">here</a>, <code...
python|numpy
1
16,518
67,321,371
Deference index in a numpy submatrix in the large matrix
<p>I have a numpy matrix <code>a</code> and a submatrix <code>b</code> of <code>a</code>. Is there a possibility to get the index of <code>a</code> that corresponds to the <code>i,j</code>-th element in the indexing by <code>b</code>?</p> <pre><code>import numpy as np a = np.arange(10) b = a[3:] b[2] == a[5] ^^...
<pre><code>In [58]: a = np.arange(10) In [59]: b = a[3:] </code></pre> <p>The basic information of an array can be seen with:</p> <pre><code>In [60]: a.__array_interface__ Out[60]: {'data': (46666800, False), 'strides': None, 'descr': [('', '&lt;i8')], 'typestr': '&lt;i8', 'shape': (10,), 'version': 3} </code></p...
python|numpy
1
16,519
34,872,894
Building a sorted Bar-chart with pandas & bokeh
<p>As part of some basic data analysis I am trying to use bokeh to display some charts in HTML format. With the following code I created a very simple bar chart using a pandas data frame with 26 columns and 594 rows. My question is: How can I sort it descending by scrap value? Right now the graph is sorted by alphabet...
<p>Found a solution by creating a sorted DataFrame and using it to plot the barchart:</p> <pre><code>import pandas as pd from bokeh.charts import Bar, output_file, show from bokeh.charts.attributes import cat #Creating the DataFrame for chart1: Filtering/Grouping/Sorting df_chart1 = df_rolling[df_rolling.SCRAP&gt;0] ...
python|python-3.x|pandas|bar-chart|bokeh
1
16,520
60,032,131
Update dataframe values that match a regex condition and keep remaining values intact
<p>The following is an excerpt from my dataframe:</p> <pre><code>In[1]: df Out[1]: LongName BigDog 1 Big Dog 1 2 Mastiff 0 3 Big Dog 1 4 Cat 0 </code></pre> <p>I want to use regex to update BigDog values to 1 if LongName is a mastiff. I need other ...
<p>You don't need a loop or apply, use <code>str.match</code> with <code>DataFrame.loc</code>:</p> <pre><code>df.loc[df['LongName'].str.match('(?i)mastiff'), 'BigDog'] = 1 LongName BigDog 1 Big Dog 1 2 Mastiff 1 3 Big Dog 1 4 Cat 0 </code></pre>
python|regex|pandas
1
16,521
59,998,392
Distance transform with Manhattan distance - Python / NumPy / SciPy
<p>I would like to generate a 2d Array like this using Python and Numpy:</p> <pre><code>[ [0, 1, 2, 3, 4, 4, 3, 4], [1, 2, 3, 4, 4, 3, 2, 3], [2, 3, 4, 4, 3, 2, 1, 2], [3, 4, 4, 3, 2, 1, 0, 1], [4, 5, 5, 4, 3, 2, 1, 2] ] </code></pre> <p>Pretty much the the numbers spread left and right starting from the ze...
<p>Here's one with <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist" rel="noreferrer"><code>Scipy cdist</code></a> -</p> <pre><code>from scipy.spatial.distance import cdist def bwdist_manhattan(a, seedval=1): seed_mask = a==seedval z ...
python|numpy|scipy|distance
5
16,522
60,210,377
Appending to Numpy array produces one big array rather than an array of arrays
<p>I want to append arrays to an array in the following way:</p> <pre><code>np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) </code></pre> <p>Yet, when I don't write the arrays out, but try to do something like this</p> <pre><code>DataMatrix = np.array([])...
<p>Here's a modest tweak to your answer code. Without a txt file I can't test it, but I think it's right :)</p> <pre><code>alist=[] with open("fakedata.txt", "r") as file: for line in file.readlines(): rr = re.findall("[+-]?\d*[\.]?\d*(?:(?:[eE])[+-]?\d+)?", line) innerlist = [numbers in rr if num...
python|arrays|numpy
2
16,523
65,440,405
How do I iterate through a pandas dataframe and access a lagging or leading row?
<p>I have the following DataFrame:</p> <pre><code>df = pd.DataFrame( { 'date': ['2020-12-05', '2020-12-06', '2020-12-07'], 'day': ['Saturday', 'Sunday', 'Monday'], 'score': [2, 3, 0] } ) df </code></pre> <p><a href="https://i.stack.imgur.com/oFW5m.png" rel="nofollow noreferrer"><img src="https://i.s...
<pre><code>df = pd.DataFrame( { 'date': ['2020-12-05', '2020-12-06', '2020-12-07', '2020-12-05', '2020-12-06', '2020-12-07'], 'day': ['Saturday', 'Sunday', 'Monday','Saturday', 'Sunday', 'Monday'], 'score': [-0.2, 0, 0.0, -0.3, 0, 0.0] } ) </code></pre> <p>Based on the question, if we have to access...
python|pandas|dataframe
0
16,524
50,055,085
How to seperate date, month and year from the following data frame.its a data of 8.4 Million users
<p>I have tried using <code>DatetimeIndex</code> method.</p> <p>The column with values is as follows</p> <pre><code>reg_date 2013-06-10T00:00:00.000Z 2014-09-30T00:00:00.000Z 2014-09-30T00:00:00.000Z 2014-09-30T00:00:00.000Z 2014-10-01T00:00:00.000Z type(df.reg_date) yields pandas.core.se...
<p>You can convert your data to datetime objects : </p> <pre><code>import datetime as dt df['reg_date'] = pd.to_datetime(df['reg_date'], errors='coerce') </code></pre> <p>And then you can extract the month as below:</p> <pre><code>df['month'] = df['reg_date'].dt.month </code></pre> <p>Output:</p> <pre><code...
python|pandas|datetime|dataframe|datetimeindex
2
16,525
49,983,781
Remove linearly increasing "count" columns pandas
<p>I have a dataframe with some columns representing counts for every timestep, I would like to automatically drop these, for example like the <code>df.dropna()</code> functionality, but something like <code>df.dropcounts()</code>. </p> <p>Here is an example dataframe</p> <pre><code>array = [[0.0,1.6,2.7,12.0],[1.0,3...
<p>I believe need:</p> <pre><code>val = 1 df = df.loc[:, df.diff().fillna(val).ne(val).any()] print (df) 1 2 0 1.6 2.7 1 3.5 4.5 2 6.5 8.6 </code></pre> <p><strong>Explanation</strong>:</p> <p>First compare by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.diff.html" re...
python|pandas|dataframe
1
16,526
49,878,841
Pandas : How can I assign group number according to specific value?
<p>DataFrame</p> <pre><code>pd.DataFrame({'a': range(20)}) &gt;&gt; a 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 </code></pre> <p>Expected result:</p> <pre><code> a group_num 0 0 1 1 1 1 2 2 2 3 3 2 4 ...
<p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html" rel="nofollow noreferrer"><code>qcut</code></a> for evenly sized bins:</p> <pre><code>df['b'] = pd.qcut(df['a'], 10, labels=range(1, 11)) print (df) a b 0 0 1 1 1 1 2 2 2 3 3 2 4 4 3 5 ...
pandas
5
16,527
63,959,956
Changing header format python pandas to excel
<p>Is there any chance to change the header format of my pandas dataframe which is wrote to an excel file. Maybe it is unusual, but my header is composed of Dates and times and I want the 'cell format' of the excel file be 'date format'.</p> <p>I tried something like this:</p> <pre><code>import pandas as pd data = pd....
<p>There are a few things you will need to do to get this working.</p> <p>The first is to avoid the Pandas default header since that will set a cell header which can't be overwritten with <code>set_row()</code>. The best thing to do is to skip the default header and write your own (see <a href="https://xlsxwriter.readt...
python|pandas|date|header
0
16,528
64,047,501
Filtering employee dataframe with conflicted roles
<p>I have the following data frame that represents the employee number, the department they are and their role code in the company that can be &quot;1&quot; or &quot;2&quot;. On the column &quot;Department Name&quot; you can either have the department the employee has their role (naming convention being &quot;XX:Dept N...
<p>You could create new columns by splitting country and department. Then the rules can be applied with a combination of boolean masks, but the second part is quite complicated... follow the comments.</p> <pre><code>import pycountry ### double roles for same department # (treat 'all &lt;country&gt;' as just another de...
python|pandas|if-statement|lambda|filter
1
16,529
46,831,371
How to update plot by setting source with Select widget in bokeh
<p>I have 2 pandas dataframes, with identical column names. I try to update my plot based on the bokeh Select widget.</p> <p><strong><em>app.py</em></strong></p> <pre><code>from bokeh.models import ColumnDataSource from bokeh.plotting import figure, output_file, show, output_notebook from bokeh.models.widgets import ...
<p>Following <a href="https://bokeh.pydata.org/en/latest/docs/user_guide/server.html#single-module-format" rel="nofollow noreferrer">this example</a>, you need to set <code>source.data</code> to be a dict, not a DataFrame. So your new code for <code>update_plot()</code> would be:</p> <pre><code>def update_plot(attrnam...
python|pandas|visualization|bokeh
3
16,530
47,022,508
list of lists not spilt correctly adding 2 items to appended dataframe
<p>I am trying to generate a dataframe with a column of urls from a list of lists read from a file. This is what I am trying:</p> <pre><code>one_df= pd.DataFrame() with open(r"product_Url.txt", 'r') as infile: l = [x.split(',') for x in infile] for x in zip(*l): df = pd.DataFrame(list(x), columns=['url...
<p>This may not be the efficient way, but looking at the example you provided following may work where <code>[</code>, <code>]</code> are replaced and <code>dataframe</code> is created:</p> <pre><code>one_df= pd.DataFrame() with open("product_Url.txt", 'r') as infile: l = [x.replace(']', ',').replace("[",'').repla...
python-3.x|pandas|dataframe|split
1
16,531
46,687,480
Pandas - Group by Period of Time / deleting consecutive rows based on multiple conditions
<p>What's the best way to solve following problem:</p> <p>I have a Pandas dataframe which looks like this:</p> <pre><code>Index Date Name Product 01 2017-09-6 18:01:15 Mike xxx 02 2017-09-6 18:02:35 Mike yyy 03 2017-09-6 18:07:25 Mike xxx 04 2017-09-6...
<p>I think you'll need to loop over the Date series to create a filter.</p> <p>(Let's assume your Date column for each [Name, Product] group is sorted ascending already.)</p> <pre><code>def date_filter(s): s = s.values anchor = s[0] res = [False] * len(s) res[0] = True for idx, x in enumerate(s):...
python|pandas
1
16,532
46,718,610
How to iterate through 'nested' dataframes without 'for' loops in pandas (python)?
<p>I'm trying to check the cartesian distance between each set of points in one dataframe to sets of scattered points in another dataframe, to see if the input gets above a threshold 'distance' of my checking points. </p> <p>I have this working with nested for loops, but is painfully slow (~7 mins for 40k input rows, ...
<p>Try using scipy implementation, it is surprisingly fast</p> <pre><code>scipy.spatial.distance.pdist </code></pre> <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance...
python-3.x|pandas|iteration
1
16,533
46,714,307
How to convert a list of variables into numpy arrays
<p>I have a number of variables being passed into a function, V1, V2, etc and i want to automatically convert these to numpy arrays in as few lines as possible. These variables will be lists of numbers and i have already checked that they are either a list or a numpy array already</p> <p>I have tried packing them in a...
<pre><code>newlist= [np.asarray(item) for item in newlist] </code></pre>
python|python-3.x|numpy
0
16,534
46,855,033
skip the error and continue to run after getting 3 errors in a loop - Getting Price data from Pandas
<p>I'm creating a loop to iterate a function. The function is simply getting data from yahoo finance by a list of tickers. However, some tickers do not have data in yahoo finance and sometimes there has bug, so I need to re-run the function whenever I got this error. </p> <p>Basically, re-run can solve the bug, but it...
<p>You have to define the variable attempts outside the while loop to get it to work.</p>
python|pandas|while-loop|yahoo-finance|skip
1
16,535
46,951,800
Inplace join sub arrays of 2D numpy array
<p>I have a numpy array as this</p> <pre><code>a = array([[1,2], [3,4], [5,6] .....]) </code></pre> <p>I have two indexes as a tuple like this <code>(0,2)</code>. So I want to join the sub-arrays of these sub indexes in place. So the final expected output is somewhat like this-</p> <pre><code>a = array([[1,2,5,6], [...
<p>You cannot use <code>numpy</code> as <code>numpy arrays</code> require the same length <code>arrays</code> on <strong>all</strong> <code>axis</code>, however you can use nested <code>lists</code>.</p> <p>So using <code>lists</code>, you can simply create a <code>function</code> to do what you want, so:</p> <pre><c...
python|arrays|python-3.x|numpy
2
16,536
46,792,252
Numpy giving error when not imported.
<p>So I'm trying out machine learning, and following a tutorial I found online. </p> <p>For some reason when I run my code numpy is giving me an error, even-though I am not importing that library. (I've been having problems with numpy)</p> <p><strong>Code:</strong></p> <pre><code>#!/usr/bin/env python from sklearn i...
<p>Numpy is a scikitlearn dependency. That means SKlearn is made on top of numpy. Creating a virtualenv is a great idea so as to understand what the real issue is. </p> <p>The same code worked for me and I can tell you the prediction is "orange". :P</p>
python|python-2.7|numpy|machine-learning|scikit-learn
1
16,537
38,616,916
String extraction in Python / Pandas with repeated delimiter
<p>I have a data frame with a column that includes any combination of one or many variables, separated by a '/' delimiter, e.g.: </p> <pre><code>Rd/MLERS Rd Rd Rd/DLEPC/DLERS SLERS MLERS </code></pre> <p>Etc., etc. I want to extract the primary classifier, i.e.: the only or the first variable immediately p...
<p>use <code>str.split</code> and <code>str[0]</code> to access the first split, this will still return the initial string even without the separator:</p> <pre><code>In [121]: df["primaryEjecta1"] = df['text'].str.split('/').str[0] df Out[121]: text primaryEjecta1 0 Rd/MLERS Rd 1 ...
python|regex|python-3.x|pandas
2
16,538
38,552,688
Pandas gives an error from str.extractall('#')
<p>I am trying to filter all the <code>#</code> keywords from the tweet text. I am using <code>str.extractall()</code> to extract all the keywords with <code>#</code> keywords. This is the first time I am working on filtering keywords from the tweetText using pandas. Inputs, code, expected output and error are given ...
<p>Set braces in your calculus : </p> <pre><code>fout = data['tweetText'].str.extractall('(#)') </code></pre> <p>instead of </p> <pre><code>fout = data['tweetText'].str.extractall('#') </code></pre> <p>Hope that will work</p>
python|pandas
8
16,539
38,806,136
tensorflow shape of a tiled tensor
<p>I have a variable <code>a</code> of dimension (1, 5) which I want to 'tile' as many times as the size of my mini-batch. For example, if the mini-batch size is 32 then I want to construct a tensor <code>c</code> of dimension (32, 5) where each row has values the same as the original (1, 5) variable <code>a</code>. </...
<p>[<strong>EDIT:</strong> This was fixed in a <a href="https://github.com/tensorflow/tensorflow/commit/1eb2f659201d981b3c07780fbf3187de998f7ff4" rel="nofollow">commit</a> to TensorFlow on August 10, 2016.]</p> <p>This is a known limitation of TensorFlow's shape inference: when the <code>multiples</code> argument to <...
tensorflow
4
16,540
62,911,350
how to get a index of row after it satisfies certain condition
<p>a data frame of the country name in rows with corresponding medals win in summer and winter Olympics</p> <p>I want in this data frame to get the country name which has a max difference in summer gold and winter gold, let's say summer gold column name is <code>x</code> and winter gold column name is <code>y</code></p...
<p>It is always good to provide a sample data frame so we can help better. I think you are looking for this:</p> <pre><code>(df.y-df.x).idxmax() </code></pre> <p>And if you care only about the absolute value of difference:</p> <pre><code>(df.x-df.y).abs().idxmax() </code></pre> <p>Example:</p> <pre><code>df = pd.DataFr...
python|pandas|numpy|indexing|max
0
16,541
63,091,059
In PYTHON how do I associate values in dataframes to pass them both to a SQL update?
<p>Use Case: Project team emails the DBAs an excel with a list of hundreds of usernames that need to be updated for a system in an oracle db. The dba should be able to run a python script that automates the process of importing the data from the excel, connecting to the db and updating the table.</p> <p>My Idea: Use p...
<p>You can write this in a more concise way as follows:</p> <pre><code>mapping = df[['Usernames to be changed','new usernames']] mapping.columns = [['old','new']] mapping = mapping.drop_duplicates() if mapping.old.nunique() &lt; len(mapping): raise ValueError('Mapping inconsistent 2 olds point to 1 new') if mapping...
python|pandas|oracle|dataframe|cx-oracle
0
16,542
63,290,799
How to deal with "could not convert string to float" error
<p>This question has been asked several times here and I checked most of them, but couldn't figure out how to deal with it. I read a CSV file and I try to convert its values to float as following:</p> <pre><code>testdataframe = pd.read_csv(r'H:\myCSVfile.csv') testdataset = testdataframe.values testdataset = testdatase...
<p>As @<a href="https://stackoverflow.com/users/494134/john-gordon">John Gordon</a> correctly mentioned that it is a date/time string You should apply <code>astype(float)</code> to numeric columns. However, if you still want to proceed with applying the same, here goes the logic to ignore 'errors'</p> <pre><code>df=pd....
python|pandas|csv
1
16,543
63,117,404
Pandas. How to reset index in a df that is resampled
<p>Possible newbie question. I have a df of daily stock prices;</p> <pre><code>print(df.head()) </code></pre> <p>it prints the following:</p> <pre><code> High Low Open Close Volume Adj Close 100ma 250ma Date ...
<p>Create column that will retain date info</p> <pre><code>df['Date'] = df.index </code></pre> <p>Set generated range that is length of DataFrame as index</p> <pre><code>df.index = range(len(df)) </code></pre>
pandas
0
16,544
63,139,871
Data Formatting within a txt. File
<p>I have the following txt file that needs to be formatted with specific start and end positions for data throughout the file. For instance, column 1 is blank and will be read as an entry number. The values for this data type is a numeric 9 and should have the following positions (1-9). Next is employee ID with positi...
<p>You can try starting here:</p> <pre><code>import sys inFile = sys.argv[1] outFile = &quot;newFile.txt&quot; with open(inFile, 'r') as inf, open(outFile, 'w') as outf: for line in inf: line = line.split(',') print(line) </code></pre> <p>Where sys argv[1] is the name of your txt fil...
python|pandas
0
16,545
63,256,952
PIL Image from numpy array indexing
<p><em>This turned out to be a very specific bug in a pre-7.0 version of PIL. I'm leaving it here because I've seen other hit the same issue and there isn't a good overview of what you see. There is no programming error here - the solution is &quot;upgrade PIL&quot;</em></p> <p>I'm converting a numpy boolean array (ie,...
<p>PIL has reverse <code>x</code> and <code>y</code> locations. To fix it, exchange <code>x</code> and <code>y</code> in your code:</p> <pre><code>ary = np.zeros((100,100), dtype=np.bool) for x in range(1, 99): for y in range(1, 50): ary[y,x] = True Image.fromarray(ary) </code></pre> <p><a href="htt...
python|arrays|numpy|python-imaging-library
1
16,546
67,868,419
Difference between count() and sum() when finding NaN rows in table
<p>I have this table, values, - some of the values are NaN:</p> <pre><code>ID Value1 Value2 Value3 12 &quot;filled&quot; &quot;filled&quot; NaN 13 &quot;filled&quot; &quot;filled&quot; &quot;filled&quot; 14 &quot;filled&quot; &quot;filled&quot; NaN </code></pre> <p>I have to find the total numbe...
<p>For <code>pandas.DataFrame.count</code> we have:</p> <p><a href="https://i.stack.imgur.com/j1gZt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j1gZt.png" alt="enter image description here" /></a></p> <p>So in your case:</p> <pre><code>values[&quot;Value3&quot;].isnull() 0 True 1 False 2 ...
python|pandas|dataframe|count|sum
1
16,547
31,976,812
Does anyone have example numpy.fftn code that correctly implements multivariate_normal pdf?
<p>With the code below, I'm attempting to implement the Levy-Khintchine formula (<a href="https://en.wikipedia.org/wiki/L%C3%A9vy_process#L.C3.A9vy.E2.80.93Khintchine_representation" rel="nofollow">https://en.wikipedia.org/wiki/L%C3%A9vy_process#L.C3.A9vy.E2.80.93Khintchine_representation</a>). In the limit of no jumps...
<p>I figured it out: in 1-d I can get away with integrating over only positive wave numbers <code>k</code>, in higher dimensions I cannot.</p> <p>Here's the corrected code:</p> <pre><code>class LevyKhintchine: def __init__(self, mean, cov, jump_measure): self.mean = mean self.cov = cov sel...
python|numpy|fft|normal-distribution
0
16,548
41,295,662
How to transfer weightings to tensorflow RNN cell
<p>I have a set of weightings of the trained model implemented in matlab. I would like to port the weightings to tensorflow. However, tf.rnn.rnn_cell.LSTMCell with 500 cell has weight matrix with shape (1524, 2000). why 1524? why 2000? This does not fit the dimensions of my weightings at all.</p> <p>My model has 3 hid...
<p>It looks like you are calling your cell using x as input. The size of the weight matrix will be (500 + 1024) x (4 * 500). The LSTM has four gating functions but for efficiency reasons their individual matrices are concatenated together. That's why the second dimension of the matrix is 4 * 500. The first dimension is...
tensorflow
1
16,549
61,319,140
Difference between Numpy and Tensorflow?
<p>is <code>numpy</code> and <code>tensorflow</code> the same thing?? I just started learning programming..this i completely unrelated to my course.. I was learning AI and found <code>tensorflow</code>... I started to look videos and I saw the code below: </p> <pre><code>import tensorflow as tf tf.ones([1,2,3]) tf.z...
<p>I think it may be worth adding a bit more of information, although it is easy to find about it just searching around a bit.</p> <p>NumPy and TensorFlow are actually very similar in many respects. Both are, essentially, array manipulation libraries, built around the concept of tensors (or nd-arrays, in NumPy terms)....
python|numpy|tensorflow
12
16,550
68,806,521
Include only columns from DataFrame that I specify in a list?
<p>Okay, so I have a DataFrame with stock data. I want the DataFrame to only include information about the stocks that I include in a list and not show data for other tickers that are not included in my list. I would rather not manually write down which tickers I want by doing:</p> <p><code>dataframe[['Apple','MSFT','e...
<p>if <code>myportfolio</code> is a list of strings then this will return only the columns with names in the list:</p> <pre><code>dataframe[myportfolio] </code></pre>
python|pandas
1
16,551
68,748,196
How to add zeros and limit to 8 digits using Pandas
<p>I have a DataFrame column that's composed of numbers. It's necessary to add zeros to the left if some elements don't reach 8 digits.</p> <p>ex:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>column1</th> </tr> </thead> <tbody> <tr> <td>81234567</td> </tr> <tr> <td>1294569</td> </tr> <tr...
<p>You can use <a href="https://docs.python.org/3.8/library/stdtypes.html#str.zfill" rel="nofollow noreferrer"><code>.str.zfill</code></a>:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;column1&quot;] = df[&quot;column1&quot;].astype(str).str.zfill(8) print(df) </code></pre> <p>Prints:</p> <pre class="la...
python|pandas|dataframe
3
16,552
68,593,356
Can't load TFLite model according to TFLite official examples
<p>I am trying to create a smart reply app using TFLite and I am following the <a href="https://github.com/tensorflow/examples/tree/master/lite/examples/smart_reply/android" rel="nofollow noreferrer">pre-built example</a> from github.</p> <p>When cloned the referenced project from git and compiled, it works flawlessly...
<p>Encountered unresolved custom op: Normalize.</p> <p>Looks like your model has a custom op, Normalize, which means that you need to implement your own TFLite custom op and register it to the TFLite interpreter. If you have no plans to implement the custom op, please consider using the Select TF op option, which can l...
java|android|tensorflow|tensorflow-lite
0
16,553
36,382,100
Converting pandas data frame to dictionary in python
<p>My pandas dataframe (df):</p> <pre><code>Pattern Support Bread 4 Milk 4 Bread,Milk 4 </code></pre> <p>My code:</p> <pre><code>x = df.set_index('Pattern').to_dict() print(x) </code></pre> <p>Output of my code:</p> <pre><code>{'Support':{'MILK': 4,'BREAD':4, 'BREAD,MILK':4}} </code></pre...
<p>Packed too much in one line, but it will give you what you want.</p> <pre><code>list(df.set_index('Pattern').to_dict().values()).pop() </code></pre>
python|python-3.x|pandas
5
16,554
36,363,127
How can I create a Pivot Table that show sum() of group values, using my Pandas Data Frame?
<p>My <code>df1</code>:</p> <pre><code> cnpj num_doc bc_icms 0 02817342000124 0000010154 17827.07 1 54921580000189 0000112428 108000.00 2 08953538000122 0000012865 232.00 3 08953538000122 0000012865 239.00 4 08953538000122 0000012865 215.00 5 07374346000107 00...
<p>IIUC, you need a sum of each <code>cnpj</code> values, so I would use groupby as:</p> <pre><code>g = df.groupby('cnpj')['bc_icms'].sum().reset_index(name='sum') </code></pre> <p>that returns:</p> <pre><code> cnpj sum 0 2364118000124 93567.24 1 2817342000124 17827.07 2 7374346000107 ...
python|pandas|pivot-table
7
16,555
36,405,502
matplotlib 3D plot color coding by value range
<p>I am trying to produce a 3D plot with two colors. One color for values above zero and another color for values below zero. I just cannot figure out how to implement this in the code. </p> <p>Here is my current code: </p> <pre><code>from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib...
<p>if you pass to <code>scatter</code> a boolean array as the value of the optional argument <code>c</code>, you have your points in two colors from the extremes of the current colormap</p> <pre><code>ax.scatter(x,y, z, c = z&lt;0, s = 20) </code></pre> <p>You may want to set the edge width to zero, otherwise all the...
python|pandas|matplotlib
4
16,556
36,638,331
kwarg-splatting a numpy array
<p>How can I write a wrapper class that makes this work?</p> <pre><code>def foo(a, b): print a data = np.empty(20, dtype=[('a', np.float32), ('b', np.float32)]) data = my_magic_ndarray_subclass(data) foo(**data[0]) </code></pre> <hr> <p>Some more background:</p> <p>I had a pair of functions like this that I ...
<p>It may not be exactly what you want, but wrapping the array in a pandas DataFrame allows something like this:</p> <pre><code>import pandas as pd def foo(a, b): print(a) data = np.empty(20, dtype=[('a', np.float32), ('b', np.float32)]) data = pd.DataFrame(data).T foo(**data[0]) # 0.0 </code></pre> <p>Note t...
python|numpy|keyword-argument|structured-array
2
16,557
53,131,094
Remove low frequency items from pandas dataframe
<p>I am playing a little with <a href="http://www.dtic.upf.edu/~ocelma/MusicRecommendationDataset/lastfm-360K.html" rel="nofollow noreferrer">Last.fm</a> dataset. The dataset is consisting of user id, artist name, and number of plays. something like this:</p> <pre><code> user ...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.t...
python|pandas|dataframe|filter
2
16,558
65,793,051
Are chunks returned by 'np.array_split()' ordered by descending sizes?
<p>In <code>numpy.array_split</code> using an integer, when the number of parts isn't a divisor of the size on the axis considered, some parts may be smaller or larger, e.g.</p> <pre><code>import numpy as np [chunk.shape[0] for chunk in np.array_split(np.arange(12), 5)] </code></pre> <p>returns chunk sizes: <code>[3, 3...
<p><a href="https://numpy.org/doc/stable/reference/generated/numpy.array_split.html#numpy.array_split" rel="nofollow noreferrer">numpy.array_split</a> docs says</p> <blockquote> <p>For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.</p> ...
python|numpy
1
16,559
63,706,030
How do I convert train dataset frames into 5d tensor while maintaining label of frames dimension?
<p>I have used the image_dataset_from_directory() to create my train(529003 frames), validation(29388 frames) and test(28875 frames) data:</p> <pre><code> train_dataset = image_dataset_from_directory( directory=TRAIN_DIR, labels=&quot;inferred&quot;, label_mode=&quot;categorical&quot;, class_names=[&quo...
<p>I found the solution I need to make a custom generator that generates 5D Tensors from video input which considers the sequence length as the 5th element of the 5D Tensor. The one I am using from Keras, image_dataset_from_directory() produces a 4D Tensor.</p>
python|tensorflow|deep-learning
0
16,560
63,471,689
How many time a string value of a cell is repeated in other column of pandas data frame?
<p>I am trying to find out the number of times each cell value of column A appears in all the cells of the other column B using pandas. for example for cell A1 value, we need to vlookup its value in all cells of column B and to find out in how many cells of column B it's repeated and then put the count value against it...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extractall.html" rel="nofollow noreferrer"><code>Series.str.extractall</code></a> along with the regex pattern, then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="...
python|pandas|dataframe
3
16,561
63,652,692
Converting saved_model.pb to model.tflite
<p>Tensorflow Version: 2.2.0</p> <p>OS: Windows 10</p> <p>I am trying to convert a saved_model.pb to a tflite file.</p> <p>Here is the code I am running:</p> <pre><code>import tensorflow as tf # Convert converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir='C:\Data\TFOD\models\ssd_mobilenet_v2_quantized...
<p>Ok, I finally resolved it!</p> <p>What I did is use tf-nightly and use the following Python Script:</p> <pre><code>import tensorflow as tf saved_model_dir = &quot;C:/Data/TFOD/models/ssd_mobilenet_v2_quantized/tflite&quot; converter = tf.lite.TFLiteConverter.from_saved_model( saved_model_dir, signature_keys=['s...
python|tensorflow|tensorflow2.0|tensorflow-lite
4
16,562
63,685,970
Numpy unique changes integer to string
<p>I have data table which has string and integer columns such as:</p> <pre><code>test_data = [('A',1,2,3),('B',4,5,6),('A',1,2,3)] </code></pre> <p>I need unique rows, therefore I used numpy unique function:</p> <pre><code>summary, repeat = np.unique(test_data,return_counts=True, axis=0) </code></pre> <p>But after the...
<p>If you have python objects and you want to retain them as python objects, use python functions:</p> <pre><code>unique_rows = set(test_data) </code></pre> <p>Or better yet:</p> <pre><code>from collections import Counter rows_and_counts = Counter(test_data) </code></pre> <p>These solutions do not copy the data: they ...
python|numpy|unique
3
16,563
21,643,090
Extraction of common element from multiple arrays to make a new array
<p>In the example below, data1, data2, ...data10 are the given arrays. Now, I have to find out the element which exist in all the given arrays. Then, I have to make new array including only those common elements, and assigning all other elements as nan value.</p> <pre><code>import numpy as np data1 = np.array ([[1,2,...
<p>The <code>numpy</code> way:</p> <pre><code>import numpy as np data1 = np.array ([[1,2,33,4,33,6],[7,8,9,10,93,12]]) data2 = np.array ([[1,14,33,15,33,17],[18,19,20,21,93,23]]) data3 = np.array ([[24,25,33,26,1,28],[93,30,31,32,93,34]]) data4 = np.array ([[24,25,33,26,1,28],[93,30,31,32,93,34]]) data5 = np.array ([...
python|numpy|scipy
1
16,564
29,978,764
Create a Numpy FFT Bandpass Filter
<p>I have 2D array of numpy.int16 (44100Hz) audio samples (1376 of them). Each sample has this format (example values):</p> <p>[ -4 4 -5 -10 -5 -6 -11 -4 -9 -7 -10 1 -4 -8 -9 -8 -4 -13 -14 -11 -12 -4 -14 -13 -9 -2 -2 -16 -5 -5 -4 3 -5 -4 -8 -11 -10 -12 -16 -7 -8 -14 -14 -14 -16 -17 -8 -...
<p>If a brick wall filter is acceptable, you can just use,</p> <pre><code>bw_filter = np.zeros(freqs.shape, dtype='float32') f_0 = 0.5*(8000 + 5000) df_0 = 0.5*(8000-5000) bw_filter[np.abs(freqs - f_0) &lt; df_0] = 1.0 fft_spectrum *= bw_filter </code></pre> <p>I would have been better to use, for instance <code>sci...
python|audio|numpy|filter|fft
0
16,565
53,703,440
Input 0 is incompatible with layer flatten_5: expected min_ndim=3, found ndim=2
<p>I am trying to fine-tune VGG16 neural network, here is the code:</p> <pre><code>vgg16_model = VGG16(weights="imagenet", include_top="false", input_shape=(224,224,3)) model = Sequential() model.add(vgg16_model) #add fully connected layer: model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dropou...
<p>In officially <a href="https://keras.io/applications/" rel="nofollow noreferrer">keras</a> webpage, on </p> <blockquote> <p>Fine-tune InceptionV3 on a new set of classes</p> </blockquote> <pre><code>from keras.models import Model vgg16_model = VGG16(weights="imagenet", include_top="false", input_shape=(224,224,3...
python-3.x|tensorflow|keras|jupyter-notebook|vgg-net
2
16,566
53,682,428
How to use pandas groupby with a period of time to and find the average count over years within the same time period
<p>I have searched far and wide, but haven't found a good way of doing this yet. I have a pandas dataframe with my own text messaging data. It has columns 'utctime', 'sender', 'recipient', and 'message'. What I would like to do is to group this by an arbitrary minute time period (e.g. 10 or 20 min) and then see, over m...
<p>IIUC, you need to extract the hours and minutes from 'utctime', categorize the minutes in <code>bins</code> and perform <code>groupby</code> on hours and minute_bins for the <code>count</code> of messages:</p> <pre><code>df['Hour'] = pd.to_datetime(df['utctime']).dt.hour df['Minute'] = pd.to_datetime(df['utctime'])...
python|pandas
2
16,567
6,649,839
Removing nested loops in numpy
<p>I've been writing a program to brute force check a sequence of numbers to look for euler bricks, but the method that I came up with involves a triple loop. Since nested Python loops get notoriously slow, I was wondering if there was a better way using numpy to create the array of values that I need.</p> <pre><code>...
<p>Try to use .empty and .fill (http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.fill.html)</p>
python|numpy|nested-loops
2
16,568
6,626,194
Python : How to fill an array line by line?
<p>I have an issue with numpy that I can't solve. I have 3D arrays (x,y,z) filled with 0 and 1. For instance, one slice in the z axis : </p> <pre><code>array([[1, 0, 1, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0, 1], ...
<p>Accessing NumPy array elements one by one is not very efficient. You may do better with just plain Python lists. They also have an <code>index</code> method which can search for the first entry of the value in the list.</p> <pre><code>from numpy import * a = array([[1, 0, 1, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, ...
python|numpy|fill
4
16,569
15,683,588
Iterating through a pandas dataframe
<p>I have a pandas dataframe where one column represents if the location value in another column changed in the row below it. As an example,</p> <pre><code>2013-02-05 19:45:00 (39.94, -86.159) True 2013-02-05 19:50:00 (39.94, -86.159) True 2013-02-05 19:55:00 (39.94, -86.159) False 2013-02-05 20:00:00...
<p>Here's another take</p> <pre><code>df['group'] = (df.condition == False).astype('int').cumsum().shift(1).fillna(0) df date long lat condition group 2/5/2013 19:45:00 39.940 -86.159 True 0 2/5/2013 19:50:00 39.940 -86.159 True 0 2/5/2013 19:55:00 39.940 -86.159 False ...
python|pandas
7
16,570
12,490,762
How to groupby the first level index and apply function to the second index in Pandas
<p>I have multilevel dataframe 'df' like this :</p> <pre><code> col1 col2 first second a 0 5 5 1 5 5 2 5 5 b 0 5 5 1 5 5 </code></pre> <p>And I want to apply a function <code>func</code> (exp: <code>'lambda x: x*10'</code>) to <code>se...
<p>You can use the <code>set_levels</code> method of the index to change the values in a given level. So for a given <code>func</code> and <code>level</code> you can do: </p> <pre><code>new_values = map(func, df.index.get_level_values(level)) df.index.set_levels(new_values, level, inplace=True) </code></pre>
python|pandas
2
16,571
72,044,371
No step marker observed on tensorboard
<p>I'm working on keras model with an LSTM. To optimize performance I'd like to use the performance profiler from TensorBoard.</p> <p>However it shows this error message at the top:</p> <blockquote> <p>No step marker observed and hence the step time is unknown. This may happen if (1) training steps are not instrumented...
<p>I had the same problem. Above that warning, an error is shown: &quot;Failed to load libcupti (is it installed and accessible?)&quot;. As I checked when executing the model and observed that TensorFlow could not find CUPTI. So linked it as it is mentioned <a href="https://www.researchgate.net/post/Could_not_load_dyna...
tensorflow|keras
0
16,572
72,079,284
Numpy flatten a nested array using concatenate
<p>I have a numpy array with subarrays of different shapes. I was trying to use an iterator to flatten them into a 1D array. Below is the code:</p> <pre><code>import numpy as np a=np.array([np.random.rand(1,2),np.random.rand(2,2),np.random.rand(1,4)],dtype=object) b=np.concatenate(x.ravel for x in a) </code></pre> <p>T...
<pre><code>b=np.concatenate([x.ravel() for x in a]) print(b) array([0.0928126 , 0.26396728, 0.37416516, 0.86079876, 0.3070049 , 0.86714361, 0.67955231, 0.11715076, 0.34659847, 0.17392114]) </code></pre>
python|arrays|numpy
0
16,573
71,865,379
Please how can i use generate a formula in pandas
<p>​</p> <blockquote> <p>df['weight_MA']= (Pn ​ ∗W1 ​ )+(Pn−1 ​ ∗W2 ​ )+(Pn−2 ​ ∗W3 ​ )... / ∑W ​</p> </blockquote> <p>where: P = Price for the period <code>n</code> = The most recent period, <code>n-1</code> is the prior period, and <code>n-2</code> is two periods prior W = The assigned weight to each period, wi...
<pre><code>weight = numpy.array([1,2,3,4,5]) df = pandas.DataFrame([90.91,90.83,90.28,90.36,90.90]) df['weight_MA'] = df.rolling(weight.shape[0]).apply(lambda x: numpy.sum(x * weight) / numpy.sum(weight)) </code></pre> <p><code>rolling</code> gives you a dataframe consisting of the previous n row value. Then, applying...
python|pandas|dataframe
1
16,574
16,763,214
pivot "stacked" data with multiple indexes?
<p>I have some "stacked" or "record format" data that looks like this (coming from the database):</p> <pre><code>"recid","code","value","exam_num" "101703034","k_rat1","17/18","1" "200907062","e_mas1","AC YES","6" "203004134","k_rat1","5/18","5" "303505091","k_gtrdsc","Foo","1" "303505091","k_rat1","4/18","2...
<p>You can set your multilevel index and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a> the level within that index back to columns:</p> <pre><code>pivoted = my_df.set_index(['recid', 'exam_num', 'code']).unstack('code') </code...
pandas
2
16,575
17,095,958
Arrays on Python with numpy
<p>I have a problem with the floats on my arrays.</p> <pre><code> import numpy from StringIO import StringIO matrizgeometrica = numpy.loadtxt('geometrica.txt') # crea la matriz geometrica a partir del txt matrizvelocidades = numpy.loadtxt('velocidades.txt') # crea la matriz de velocidades a partir del txt ...
<p>This is your loop:</p> <pre><code>for x in matriztiempo: </code></pre> <p>This will set <code>x</code> to values from the array. This does not find the position of the values; it just gets the values.</p> <p>If you want to know the position, the best way is to use <code>enumerate()</code> like so:</p> <pre><cod...
python|numpy
4
16,576
18,981,710
how to define column range in python
<p>I wrote a python program and I got output like this </p> <pre><code>ATOM OW HOH 6.016 23.68 63.478 ATOM OW HOH 11.522 24.153 61.585 ATOM OW HOH 10.849 26.167 62.012 ATOM OW HOH 6.774 23.656 63.543 ATOM OW HO...
<p>Use the <code>%</code> formatting operator, letting it perform both the rounding and the padding:</p> <pre><code>with open('randomcoord.pdb', 'w') as f: f.write('ATOM OW HOH %6.3f %6.3f %6.3f\n' % (pacord[0], pacord[1], pacord[2])) </code></pre>
python|math|numpy
3
16,577
21,974,371
opencv: TypeError: mask is not a numerical tuple
<p>Hey I am getting error <code>TypeError: mask is not a numerical tuple</code> when trying to add scalar to a matrix while using a mask. The mask variable is printed here:</p> <pre><code>(15.0, array([[ 0, 255, 0, ..., 0, 0, 0], [ 0, 0, 0, ..., 0, 0, 0], [ 0, 0, 255, ..., 0, 0...
<p>According to the <a href="http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#add" rel="nofollow">opencv documentation</a>, <code>mask</code> needs to be an "8-bit single channel array". Your mask is not.</p> <p>Here is a small working example of using cv2.add with a mask:</p> <pre><code>In [43]: im...
python|opencv|numpy
3
16,578
55,209,582
How to accumulate my loss over mini batches then calculate my gradient
<p>My main question is; is averaging the loss the same thing as averaging the gradient and how do i accumulate my loss over mini batches then calculate my gradient?</p> <p>I have been trying to implement policy gradient in Tensorflow and run into the issue where i can not feed all my game states into my network at onc...
<p>What you can do is to accumulate gradients after each mini-batch and then update the weights based on gradient averages. Consider following simple case for fitting 50 Gaussian blobs with a single-layered perceptron:</p> <pre><code>from sklearn.datasets import make_blobs import tensorflow as tf import numpy as np x...
python|tensorflow|reinforcement-learning|tensorflow-gradient|policy-gradient-descent
0
16,579
55,399,197
How to compute weighted average of tensor A along an axis with weights specified by tensor B in tensorflow?
<p>I am trying to apply a weighted average scheme on RNN output.<br> RNN output is represented by tensor <code>A</code> having dimension <code>(a,b,c)</code>.<br> I can simply take <code>tf.reduce_mean(A,axis=1)</code> to get the tensor <code>C</code> having dimension <code>(a,c)</code>. </p> <p>However, I want to do...
<p>I don't quite get why <code>B</code> should have dimensions <code>(d,b)</code>. If <code>B</code> contains the weights to do a weighted average of A across only one dimension, <code>B</code> only has to be a vector <code>(b,)</code>, not a matrix.</p> <p>If <code>B</code> is a vector, you can do:</p> <p><code>C = ...
python|tensorflow|recurrent-neural-network|weighted-average
1
16,580
56,489,868
Tensorflow-serving client written in java is not giving correct results
<p>Sorry for a long question. But please help.</p> <p>I have written a tensorflow-serving client in java, that requests the tensorflow server hosted on another machine. The communication is through GRPC and it is working fine, i.e., responses come for the requests. However, the responses that come are wrong. The model...
<p>I am answering my own question, as I just figured the solution.</p> <p>The thing that I need to fix is to change to <code>addFloatVal()</code> to <code>addIntVal()</code>.</p> <p>Here:</p> <pre><code> TensorProto.Builder featuresTensorBuilder = TensorProto.newBuilder(); for (int i = 0; i &lt; featuresTens...
java|python|tensorflow|tensorflow-serving
0
16,581
56,533,432
Need function source code to get data from dataframe; to fine the mean median and mode
<p>Attempting to derive the mean, median and mode from the dataframe. I need to know how to code the source in the function instead of ":".</p> <p><code>source = [df.'DMC]</code> </p> <pre><code>import pandas as pd import nltk df.head(4) # This is the print out of the dataframe # When I came up with this code, the ...
<p>To answer your specific question, in order to select a specific column of a <code>pandas</code> dataframe, you can either use the syntax</p> <pre><code>source = df.DMC </code></pre> <p>or </p> <pre><code>source = df['DMC'] </code></pre> <p>However, you don't have to go to the trouble of implementing your own fu...
python|pandas
0
16,582
56,826,495
How to make Keras compute a certain metric on validation data only?
<p>I'm using <code>tf.keras</code> with TensorFlow 1.14.0. I have implemented a custom metric that is quite computationally intensive and it slows down the training process if I simply add it to the list of metrics provided as <code>model.compile(..., metrics=[...])</code>.</p> <p>How do I make Keras skip computation ...
<p>To do this you can create a tf.Variable in the metric calculation that determines if the calculation goes ahead and then update it when a test is run using a callback. e.g.</p> <pre><code>class MyCustomMetric(tf.keras.metrics.Metrics): def __init__(self, **kwargs): # Initialise as normal and add flag va...
python|tensorflow|keras
5
16,583
56,758,125
How to find skewness and kurtosis correctly in pandas?
<p>I was wondering how to calculate skewness and kurtosis correctly in pandas. Pandas gives some values for <code>skew()</code> and <code>kurtosis()</code> values but they seem much different from <code>scipy.stats</code> values. Which one to trust pandas or <code>scipy.stats</code>? </p> <p>Here is my code:</p> <pre...
<h3><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html" rel="noreferrer"><code>bias=False</code></a></h3> <pre><code>print( stats.kurtosis(x, bias=False), pd.DataFrame(x).kurtosis()[0], stats.skew(x, bias=False), pd.DataFrame(x).skew()[0], sep='\n' ) -0.314671076310255...
python|pandas|scipy
8
16,584
56,605,540
Find 'M' and multiply number by 1 million then find 'B' and multiply number by 1 billion
<p>I am downloading financial data and I have a few columns with data points that look like this: </p> <pre><code>34.60B 18.66M </code></pre> <p>This occurs in column number 6, which has a header of 'Market Cap'. It also occurs in column number 41, which has a header named 'Avg Volume'. How can I find the cells wit...
<p>You must iterate over the values as strings, since the letters prevent conversion to numeric types. Then you can trim and scale like this:</p> <pre><code>if value.endswith("M"): value = float(value[:-1]) * 10**6 elif value.endswith("B"): value = float(value[:-1]) * 10**9 else: value = float(value) </cod...
python|python-3.x|pandas
5
16,585
56,517,952
FileNotFoundError [WinError 2] The system cannot find the file specified
<p>I'm trying to read an Excel file into a Pandas dataframe and plot 2 columns. My code is as follows:</p> <pre><code>import numpy as np import pandas as pd from pylab import plt plt.style.use('seaborn') data1 = pd.read_excel('LogReturns_AAPL.xlsx') data1[['Returns', 'log_returns']].cumsum().apply(np.exp).plot(figsi...
<p>I assume your problem is about a file path. Therefore, please try this</p> <pre><code>df = pd.read_excel(r'C:/Users/DELL/Desktop/LogReturns_AAPL.xlsx') </code></pre> <p>This will direct pandas to an absolute path. It might be what you needed.</p>
python|pandas
0
16,586
66,956,632
Filtering / reindexing in Python
<p>I have the following problem in Python Pandas:</p> <p>final_list:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date</th> <th>test3</th> </tr> </thead> <tbody> <tr> <td>2001-11-01</td> <td>NaT</td> </tr> <tr> <td>2001-11-02</td> <td>NaT</td> </tr> <tr> <td>2001-11-02</td> <td>2001-11-0...
<p>You didn't say much about df_daily_strategy but I'm assuming it has a datetime index and you are trying to identify those dates with NaT values from final_list. You could try something like the following:</p> <pre><code># get the date column values where test3 is NaT dates = final_list.loc[final_list.test3.isna(), '...
python|pandas|dataframe|filtering
0
16,587
66,801,168
Python join dataframes by index
<p>I'm working with multiple dataframes in Python and I'm looking to map one onto the other based on a common column (similar to index/match in Excel). I want to join the <code>date</code> column of one dataframe, to the <code>index</code> of the other dataframe (where the date is stored as the index). How would I call...
<p>You can use <code>reset_index()</code>, and then <code>rename</code> the column:</p> <pre><code>df=df1.reset_index().rename(columns={&quot;index&quot;: &quot;Date&quot;}) df </code></pre>
python|pandas|dataframe
1
16,588
67,155,590
Producing a summary table from a pandas dataframe
<p>I have a log of events from an algorithmic trading bot loaded into a dataframe that looks like this:</p> <pre><code> datetime_long high low trade_direction trade_entry trade_exit 159 2021-02-05 10:15:00 88.915 88.6150 LE 1.0 0.0 160 2021-02-05 10:30:00 8...
<p>You can use <code>.str.contains()</code> to check if elements in Series contains value.</p> <pre class="lang-py prettyprint-override"><code>X_mask = df['trade_direction'].str.contains('X') X_previous_mask = X_mask.shift(-1).fillna(False) E_mask = df['trade_direction'].str.contains('E') </code></pre> <p>You can use</...
python|pandas|dataframe
1
16,589
66,850,762
How to synchronize two arrays with different length?
<p>let's consider two arrays containing indices:</p> <pre><code>x = [0,1,2,3,4,5...] y = [0,3,6,9,12,...] </code></pre> <p>These arrays may have slightly different length, approximately up to 3 indices. In this example let's assume that <code>len(x) = len(y) - 1</code> I want to return synchronized x, which will be ext...
<p>It is not clear what you mean by synchronized, but you can iterate over both of the arrays, filling the shortest with a default value with <a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest" rel="nofollow noreferrer"><code>itertools.zip_longest</code></a></p> <pre><code>from itertools im...
python|arrays|numpy|synchronize
2
16,590
66,843,633
The input tensor should have dimensions 1 x height x width x 3. Got 1 x 3 x 224 x 224
<p>I want to convert the Pytorch-trained model to the tensorflow model and use the model on mobile devices. For this, I follow these steps; First I convert the pytorch trained model to onnx format. Then I convert the onnx format to the tensorflow model.</p> <p>Firstly pytorch trained model to onnx;</p> <pre><code>impor...
<p>Maybe you could try <code>einops</code> for tensor transformations. It's elegant and powerful. In your case, the code should be</p> <pre class="lang-py prettyprint-override"><code> import einops input_tensor = einops.rearrange(input_tensor,'b c w h -&gt; b w h c') </code></pre>
python|tensorflow|machine-learning|pytorch|onnx
1
16,591
47,123,154
pandas groupby apply is really slow
<p>When I call <code>df.groupby([...]).apply(lambda x: ...)</code> the performance is horrible. Is there a faster / more direct way to do this simple query?</p> <p>To demonstrate my point, here is some code to set up the DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame(data= {'ticker': ['AAPL','A...
<p>You can save some time by precomputing the product and getting rid of the <code>apply</code>.</p> <pre><code>df['scaled_size'] = df['size'] * df['price'] g = df.groupby(['ticker', 'side']) g['scaled_size'].sum() / g['size'].sum() ticker side AAPL B 10.126667 S 10.140000 IBM B 20....
python|pandas|lambda|pandas-groupby|pandas-apply
5
16,592
47,208,361
How to gradually write large amounts of data to memory?
<p>I am performing a signal processing task on a large dataset of images, converting the images into large feature vectors with a certain structure <code>(number_of_transforms, width, height, depth)</code>.</p> <p>The feature vectors (or <code>coefficients</code> in my code) are too large to keep in memory all at once...
<p>As @juanpa.arrivillaga pointed out, the only change that needs to be made is using <code>numpy.lib.format.open_memmap</code> instead of <code>np.memmap</code>:</p> <pre><code>coefficients = numpy.lib.format.open_memmap( output_location, dtype=np.float32, mode="w+", shape=(n_samples, number_of_transforms, wi...
python|python-3.x|numpy|numpy-memmap
0
16,593
68,232,249
How to combine multiple files in a single pandas dataframe?
<p>I have 5 csv files in a folder: 1.csv, 2.csv, 3.csv, 4.csv, 5.csv. All files having the same structure and column names.</p> <p>I would like all of the files to be in a single pandas dataframe, df. Is there anyway to achieve this?</p>
<pre><code>df1 = pd.read_csv('1.csv') df2 = pd.read_csv('2.csv') df1.concat(df2) # this will concat rows from df1 into df2 </code></pre>
pandas
1
16,594
68,200,424
Combine Consecutive Rows for given index values in Pandas DataFrame
<p>I was extracting tables from a PDF with tabula-py. But in a table where some rows were more than one line, but in tabula-py, a single-table row is converted as multiple rows in DataFrame. I'm giving a sample here.</p> <pre><code> Serial No. Name Type Total 0 1 Easter Multiple 19 1 2 C...
<p>You can try:</p> <pre><code>df['Serial No.'] = df['Serial No.'].bfill().ffill() df['Total'] = df['Total'].astype(str).replace('nan', np.nan) df_out = df.groupby('Serial No.', as_index=False).agg(lambda x: ''.join(x.dropna())) df_out['Total'] = df_out['Total'].replace('', np.nan, regex=True).astype(float) </code></p...
python|pandas|dataframe|tabula-py
2
16,595
68,068,291
Python Pandas - trying to get counts and percentages for all fields - Can only get one or the other
<p>I want to import some survey data, loop through all fields, and run counts and percentages. I'm struggling to get this to work for both a count and percentage of each value in a question.</p> <p>For example, here's what a survey question might look like:</p> <p>Q1 |ID|Response| |---|-------| |1 |White|<br> |2 |Black...
<pre><code>import pandas as pd data = [['ID','Response'], ['1','White'], ['2','Black'], ['3','Black']] df = pd.DataFrame(data[1:], columns=data[0]) descriptive_df = (df.groupby(by='Response').count()) descriptive_df['percentages'] = descriptive_df[&quot;ID&quot;] / descriptive_df[&quot;ID&quot;].sum() print (descri...
python|pandas|numpy
1
16,596
68,084,837
Mean of column group by multiple values
<p>I'm new to pandas and I am struggling with this : I have a table like this one (of a much larger period of time) :</p> <p><a href="https://i.stack.imgur.com/3GWtw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3GWtw.png" alt="enter image description here" /></a></p> <p>I want to get the mean coun...
<p>Use the groupby function on Item, Day, and Hour:</p> <pre><code># setup import pandas as pd data = [ [&quot;Monday&quot;, &quot;8 to 9&quot;, &quot;itemname1&quot;, &quot;drinks&quot;, 3], [&quot;Monday&quot;, &quot;8 to 9&quot;, &quot;itemname1&quot;, &quot;drinks&quot;, 5], [&quot;Monday&quot;, &quot...
python|pandas|pandas-groupby|mean
0
16,597
68,361,071
Multiply outputs from two Conv2D layers in TensorFlow 2+
<p>I’m trying to implement SOLO architecture for instance segmentation in TensorFlow (Decoupled version).</p> <p><a href="https://arxiv.org/pdf/1912.04488.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1912.04488.pdf</a></p> <p>Right now, I need to compute the loss function and multiply each output map from first...
<p>It is basically the outer product of the last dimension followed by collapsing the last 2 dimensions. A short way to express this operation is to use <code>tf.repeat</code> and <code>tf.tile</code>.</p> <pre><code>#channel_dims is the length of the last dimension, i.e. 24 in your question @tf.function def outerprod...
python|tensorflow|machine-learning|computer-vision|tensorflow2.0
1
16,598
68,380,599
how to drop rows from dataframe pandas
<p>I have <code>dataframe</code></p> <pre><code> name cat1 cat2 cat3 'aa bb' A A-1 A-1-1 'cc dd' B B-1 B-1-1 'ee aa' C C-1 C-1-1 'gg bb' D D-1 D-1-1 </code></pre> <p>and I have list look like this</p> <pre><code>list_words = ['aa', 'gg'] </code></pre> <p>I want to dr...
<p>This is a better answer:</p> <pre><code>df={'name':['aa bb', 'cc dd', 'ee aa', 'gg bb'], 'cat1':['A', 'B', 'C', 'D'], 'cat2':['A-1', 'B-1', 'C-1', 'D-1'], 'cat3':['A-1-1', 'B-1-1', 'C-1-1', 'D-1-1']} df= pd.DataFrame(df) list_words =['aa', 'gg'] submask=df.name.str.split(expand=True) mask=~submask.isin(list_words) ...
python|pandas|dataframe
0
16,599
59,451,735
Pandas - Dynamically Generating Values in a Column and using them in next rows in Real-Time
<p>I have a DataFrame which looks like this:</p> <pre><code>Date Score Duration_Diff 2019-05-11 25 0 2019-05-14 30 0.1 2019-06-19 20 1.01 2019-07-23 56 1.04 </code></pre> <p>The <code>Duration_Diff</code> column is in months. Now I'm multiplying a time decay f...
<p>I suggest use <a href="http://numba.pydata.org/" rel="nofollow noreferrer"><code>numba</code></a> for improvement performance of loops:</p> <pre><code>from numba import jit import math @jit(nopython=True) def func(a): for i in range(1, a.shape[0]): a[i] = (a[i-1, 0] * math.exp(-a[i, 1]) + a[i, 0]) / 2 ...
python|pandas|time-series
2