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
18,300
53,022,685
Random date based on certain range in pandas
<p>My main_csv.csv file looks like</p> <pre><code>Client_ID Frequency 123AASD45 10 2345OPU78 9 763LKJ90 2 </code></pre> <p>Here my frequency is the number of dates like if the frequency is 10 that client has to be met 10 times within my 1st quarter working days(Jan 2018-Mar 2018) my desir...
<p>First you define a function date_range that takes the start date and end dates and the size of the sample and returns a sample.</p> <pre><code>import pandas as pd df = pd.DataFrame({'client':['123AASD45', '2345OPU78', '763LKJ90'], 'frequency':[10,9,2]}) def date_range(n, start='1/1/2011', end='4/1/2011'): date...
python|pandas|date
1
18,301
65,827,920
Using regex and converting usernames in Twitter to "usrusr" token
<p>I need to find Twitter usernames in a dataframe and convert the usernames to “usrusr” token for ethical reasons. I tried this code:</p> <pre><code>def finduser(string): regex = &quot;(?&lt;=^|(?&lt;=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9-_]+)&quot; username = (regex,string) return[&quot;usrusr&quot; for...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>import re #... def finduser(string): return re.sub(r&quot;(?&lt;![a-zA-Z0-9_.-])@[A-Za-z]+[A-Za-z0-9_-]+&quot;, &quot;usrusr&quot;, string) </code></pre> <p>See the <a href="https://regex101.com/r/lJIqpd/1" rel="nofollow noreferrer">regex demo</a>.<...
python|regex|pandas|twitter
0
18,302
65,893,716
How to extract values in a JSON file into separate columns in a dataframe row
<pre><code>data = json.load(open(&quot;C:/Users/&lt;username&gt;/Downloads/one-day-run-record.json&quot;,&quot;rb&quot;)) df = pd.json_normalize(data)[[&quot;summaries&quot;, &quot;tags.com.nike.weather&quot;, &quot;tags.com.nike.name&quot;, &quot;start_epoch_ms&quot;, &quot;end_epoch_ms&quot;, &quot;metrics&quot;]] d...
<ul> <li>The <code>'values'</code> column in <code>'metrics'</code> is a <code>list</code> of <code>dicts</code> <ul> <li>In order to extract <code>'value'</code>, the <code>lists</code> need to be expanded with <code>.explode()</code> so that each <code>dict</code> is on a separate row.</li> <li><code>'values'</code> ...
python|json|pandas|json-normalize
0
18,303
53,670,447
Generate Dictionary from nested List, Python 3.6
<p>I have below List:</p> <pre><code>dimensionList = [{'key': 2109290, 'id': 'R', 'name': 'Reporter', 'isGeo': True, 'geoType': 'region'}, {'key': 2109300, 'id': 'C', 'name': 'Commodity', 'isGeo': False, 'geoType': None}, {'key': 2109310, 'id': 'P', 'name': 'Partner', 'isGeo': True, 'geoType': 'reg...
<p>Use <code>dict comprehension</code>:</p> <pre><code>d = {x['id']:x['name'] for x in dimensionList} print (d) {'R': 'Reporter', 'C': 'Commodity', 'P': 'Partner', 'TF': 'Trade Flow', 'I': 'Measure'} </code></pre>
python|python-3.x|pandas|dictionary
5
18,304
56,670,031
How to use multiple if in lamda function?
<p>In the date frame I have Date column and now want to extract a new column from Date called 'status' if Date> CurrentDate (datetime.now()) update the status as Expired, if Date&lt; CurrentDate update the status as SW Expires and year in the Date with the quarter (SW Expires 2018-Q4), if Date == CurrentDate or "X" or ...
<p>Best way is two write custom function and call in apply function.</p> <pre><code>def custom_funct(row): do anthing df['res']=df.apply(lambda row: custom_funct(row),axis=1) </code></pre>
python-3.x|pandas|numpy|datetime|lambda
0
18,305
56,488,017
Image recognition for dog types not working, my models might be the issue but am new to it
<p>I came across this dataset : <a href="https://www.kaggle.com/jessicali9530/stanford-dogs-dataset" rel="nofollow noreferrer">https://www.kaggle.com/jessicali9530/stanford-dogs-dataset</a></p> <p>Wanted to try experimenting with machine learning by my own as I tried following guides on youtube. Have no idea on how mod...
<p><strong>Classifying images of dogs into various categories is a Classification task</strong>. There are two types of problems in Machine Learning: <a href="https://medium.com/quick-code/regression-versus-classification-machine-learning-whats-the-difference-345c56dd15f7" rel="nofollow noreferrer">Classification and R...
tensorflow|machine-learning|keras|jupyter-notebook
1
18,306
56,730,118
Best algorithm for multi agent continuous space path finding using Reinforcement learning
<p>I am working on project in which I need to find best optimised path from 1 point to another in continuous space in multi agent scenario. I am looking for best algorithm which suits this problem using Reinforcement learning. I have tried "Multi-agent actor-critic for mixed cooperative-competitive environment" but it...
<p>Multi-agent reinforcement learning is quite hard to master and has yet to prove effective for general cases.</p> <p>The problem is that in multi-agent the environment becomes non-stationary from the perspective of each individual agent. This means that an agents action cannot be mapped to the state directly because...
deep-learning|artificial-intelligence|pytorch|reinforcement-learning|multi-agent
0
18,307
56,838,750
Nonexistant pytorch gradients when dotting tensors in loss function
<p>For the purposes of this MWE I'm trying to fit a linear regression using a custom loss function with multiple terms. However, I'm running into strange behavior when trying to weight the different terms in my loss function by dotting a weight vector with my losses. Just summing the losses works as expected; however, ...
<p>Use <code>torch.cat((loss1, loss2))</code>, you are creating new Tensor from existing tensors destroying graph.</p> <p>Anyway you shouldn't do that unless you are trying to generalize your loss function, it's pretty unreadable. Simple addition is <strong>way</strong> better.</p>
python|machine-learning|neural-network|pytorch|autograd
0
18,308
67,082,759
Python: My x axis labels do not show, only the column header
<p>The x-axis should be a series of dates; instead, I'm getting just the my_date header. How do I return the dates? By the way, I am visualizing the number of daily registrations for a project.</p> <pre><code>viz = registrations.groupby('my_date').count()[['event_type']] viz.plot() </code></pre>
<p>It's dificult to understant without seeing an example of your data frame, but is your 'my_date' column a datetime object? You could check that with a <code>registrations.info()</code></p> <p>You should see something like <code>my_date 4 non-null datetime64[ns]</code></p> <p>If it is not a datetime64, you nee...
python|pandas|axis-labels
0
18,309
47,427,837
How do I do mixing of multiple dataframes in pandas got ValueError
<p>In Pandas using Anaconda3 Spyder I am running the following DataFrame Merge excercise:</p> <p>I have two dataframes with structures below:</p> <pre><code>aur.columns ['Date','No','Clos'] bal.columns ['Date','No','Clos'] </code></pre> <p>Both are Pandas DataFrames</p> <p>I need to merge them into another data ...
<p>I think you need merge <code>DataFrames</code> with 2 columns - <code>Close</code> and <code>Date</code>, so select these columns in both <code>DataFrames</code> and then <code>merge</code>:</p> <p>Also there are 2 format of datetimes as <code>strings</code>, so first convert them to <code>datetimes</code> for sam...
python|pandas|merge
2
18,310
47,148,852
How to get another dataframe value according to the value of the column and set to the corresponding field
<p>This is my two dataframe , </p> <pre><code>df1 = pd.DataFrame([['@1','A',2],['@2','A',1],['@3','A',4],['@4','B',1],['@5','B',1],['@6','B',3],['@7','B',3],['@8','C',4]],columns=['key1','key2','value']) key1 key2 value 0 @1 A 2 1 @2 A 1 2 @3 A 4 3 @4 B 1 4 @5 B 1 ...
<p>Use <code>pd.DataFrame.merge</code> </p> <pre><code>df2[['key1', 'key2']].merge(df1, 'left') key1 key2 value 0 @5 B 1 1 @7 B 3 2 @6 B 3 3 @3 A 4 4 @6 B 3 </code></pre> <hr> <p>Or with <code>pd.DataFrame.join</code> </p> <pre><code>keys = ['key1', 'key2'] df...
python|pandas
2
18,311
47,389,117
Generate combinations from list within column
<p>We have a DataFrame with 2 columns as follows: </p> <pre><code>|Type |list_dates | |:----:|:-----------:| |1 |['a','b','c']| |2 |['d','e','f','g']| </code></pre> <p>We need to generate a combination of all list elements while duplicating the Type, as follows: </p> <pre><code>|Type |list_dates ...
<p>I think pure python solution working best. So first create tuples by <code>dict</code> and then create <code>list of tuples</code> by combinations. Last create <code>DataFrame</code> by constructor:</p> <pre><code>import itertools L = [] for x, y in zip(df['Type'], df['list_dates']): a = list(itertools.combina...
pandas
1
18,312
47,231,120
SVM on MNIST data with PCA using tensorflow
<p>I intended to learn about PCA using SVD and therefore implemented it and tried to use it on MNIST data.</p> <pre><code>import numpy as np class PCA(object): def __init__ (self, X): self.N, self.dim, *rest = X.shape self.X = X ''' U S V' = svd(X) ''' X_std = (...
<p>When we use PCA or feature scaling, we set the underlying parameters on the training dataset and then just apply/transform it on the test dataset. The test dataset is not used to calculate the key parameters, or in this case, SVD should only be applied on the train dataset. e.g. in sklearn's PCA, we use the followin...
tensorflow|classification|pca|svd|mnist
1
18,313
68,439,128
Write into slice references with map?
<p>I am trying to write into Python slices that should have been passed to the function by reference.</p> <pre><code>def mpfunc(r): r[:]=1 R=np.zeros((2,4)) mpfunc(R[0]) mpfunc(R[1]) print(R) </code></pre> <p>This code works as expected. <code>R</code> contains <code>1</code> now.</p> <p>When I use <code>map...
<p><code>map</code> (in Python 3) is lazy, you need to consume it to trigger function, consider following simple example:</p> <pre><code>def update_dict(dct): dct.update({&quot;x&quot;:1}) data = [{&quot;x&quot;:0},{&quot;x&quot;:0},{&quot;x&quot;:0}] mp = map(update_dict, data) print(data) lst = list(map(update_di...
python|numpy|multiprocessing|pass-by-reference
2
18,314
68,074,685
Smoothing the values of the column with the mean or median of the members belong to the same bin
<p>Dataframe <code>df</code> is given using <code>df = pd.DataFrame({'A':[10, 15, 12, 19, 11, 20, 25]})</code> as:</p> <pre><code> A 0 10 1 15 2 12 3 19 4 11 5 20 6 25 </code></pre> <p>The result of equal-frequency binning of the column <code>A</code> by using <code>df['B'] = pd.cut(df['A'], bins = 2)...
<p>You could group by the bins and <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer">transform</a> to the mean or median, depending on what you want:</p> <pre><code>&gt;&gt;&gt; df.groupby(pd.cut(df['A'], bins=2)).tr...
python|pandas|dataframe|numpy
3
18,315
68,190,451
Retrieve a csv uploaded to GridFS (mongodb)
<p>I uploaded a csv to gridfs using python and now I want to use this csv in my new python code. I tryed this:</p> <pre><code>client = MongoClient(&quot;localhost&quot;, 27017) db = client[&quot;grid_file&quot;] collection = db[&quot;fs.files&quot;] name=&quot;csv&quot; fs = gridfs.GridFS(db) gout = fs.get_last_versio...
<p>I finally got it, I leave my code here in case someone can help you in the future</p> <pre><code>client = MongoClient(&quot;localhost&quot;, 27017) db = client[&quot;grid_file&quot;] collection = db[&quot;fs.files&quot;] name=&quot;csv&quot; fs = gridfs.GridFS(db) gout = fs.get_last_version(name) ...
python|pandas|mongodb|gridfs
0
18,316
59,070,717
Getting NaN's instead of the correct values inside dataframe column
<p>I created a dataframe of zeros using this syntax:</p> <pre><code>ltv = pd.DataFrame(data=np.zeros([actual_df.shape[0], 6]), columns=['customer_id', 'actual_total', 'predicted_num_purchases', 'pred...
<p>You need same index values in both (and also same length of both DataFrames).</p> <p>So first solution is create default <code>RabgeIndex</code> in <code>actual_df</code>, in <code>ltv</code> is not specify, so created by default:</p> <pre><code>actual_df = actual_df.reset_index(drop=True) ltv['customer_id'] = act...
python|pandas
2
18,317
59,249,842
How to change only one value in a dictionary of numpy array
<p>I am stuck with a problem that I believe to be trivial.</p> <p>I have a dictionary with 2 entry (simulations). Each entry is another dictionary with 2 entrys (options). Each option is a numpy array. </p> <p>In a first step I am creating those arrays, so that they are equal in shape for each simulation. In the next...
<p>You can use <a href="https://docs.python.org/3/library/copy.html#copy.deepcopy" rel="nofollow noreferrer">deepcopy</a> for this. This is because you're assigning <code>zero_trips</code> to each simulation, rather than the value of <code>zero_trips</code>. If you edit one of them, all of the <code>zero_trips</code> v...
python|python-3.x|numpy|dictionary|numpy-ndarray
3
18,318
59,396,571
pyodbc - write a new column of data to existing table in ms access
<p>I have a ms access db I've connected to with (ignore the <code>...</code> in the drive name, it's working):</p> <pre><code>driver = 'DRIVER={...' con = pyodbc.connect(driver) cursor = con.cursor() </code></pre> <p>I have a pandas dataframe which is exactly the same as a table in the db except there's an additional...
<p>If the target MS Access table does not already contain a field to house the data held within the additional column, you'll first need to execute an <code>alter table</code> statement to add the new field.</p> <p>For example, the following will add a 255-character text field called <code>item</code> to the table <co...
python|pandas|ms-access|pyodbc
1
18,319
57,235,514
How to convert a list to a dataframe without dropping all data?
<p>I am testing the code below.</p> <pre><code>import pandas as pd from pandas_datareader import data as wb tickers = ['SBUX', 'AAPL', 'MSFT'] AllData = [] for ticker in tickers: print('appending prices for ' + ticker) tickers = wb.DataReader(ticker,start='2018-7-26',data_source='yahoo') AllData.append(t...
<p>There are a couple of issues with your code. </p> <p>First, you are iterating through <code>tickers</code> via <code>for ticker in tickers:</code> but you then reassign that variable in the loop via <code>tickers = wb.DataReader(...)</code>. Never change the object over which you are iterating. Although this act...
python|python-3.x|pandas|dataframe
3
18,320
46,157,709
Converting HDF5 to Parquet without loading into memory
<p>I have a large dataset (~600 GB) stored as HDF5 format. As this is too large to fit in memory, I would like to convert this to Parquet format and use pySpark to perform some basic data preprocessing (normalization, finding correlation matrices, etc). However, I am unsure how to convert the entire dataset to Parquet ...
<p>You can use <a href="https://arrow.apache.org/docs/python/" rel="noreferrer">pyarrow</a> for this!</p> <pre><code>import pandas as pd import pyarrow as pa import pyarrow.parquet as pq def convert_hdf5_to_parquet(h5_file, parquet_file, chunksize=100000): stream = pd.read_hdf(h5_file, chunksize=chunksize) ...
python|pandas|hdf5|parquet|hdf
18
18,321
45,812,581
Replicated rows as dictionary in pandas for feature extraction
<p>I have a pandas data frame like this</p> <pre><code>UID URL IMP UID1 URLX 10 UID1 URLY 1 UID3 URLX 100 UID4 URLY 2 UID2 URLY 10 UID2 URLZ 1 </code></pre> <p>I'd like to simplify the dataframe in order to have a single line foe each UID and a dictionary as second column</p> <pre><cod...
<p>IIUC:</p> <pre><code>In [55]: df.groupby('UID')[df.columns.drop('UID').tolist()] \ .apply(lambda x: x.to_dict('r')) \ .reset_index(name='DICT') Out[55]: UID DICT 0 UID1 [{'URL': 'URLX', 'IMP': 10}, {'URL': 'URLY', '... 1 UID2 [{'URL': 'URLY...
python|pandas|scikit-learn|feature-extraction
0
18,322
46,077,180
Pandas dataframe grouping values
<p>I have a pandas dataframe like this,</p> <pre><code>dd = pd.DataFrame( {'name': ['abc','bcd','abc'], 'seconds': [75,77,90], }) </code></pre> <p><a href="https://i.stack.imgur.com/LX1hn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LX1hn.png" alt="enter image description here"></a></p> <p>I n...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>apply</code></a> <code>list<...
python|pandas|dataframe|pandas-groupby
2
18,323
46,125,738
Concatenate and group-wise filling NaN values
<p>I have this dataframe:</p> <pre><code>df: companycode name address A B C ... 1234 asd qwe,56 Tyh 123 923 1234 asd qwe,56 Zfhs 4828 01992 6472 yui iop,56 Retgh 8484 8484 ... </code></pre> <p>I have another one that looks like this:</p...
<p><code>pd.concat</code> followed by a <code>groupby</code> operation should do it. </p> <pre><code>df = pd.concat([df1, df2], 0, ignore_index=True)\ .groupby('companycode').ffill() df A B C address companycode name 0 Tyh 123 923 qwe,56 1234 asd 1 Zfhs 48...
python|pandas|dataframe|group-by|pandas-groupby
3
18,324
45,974,521
Delay gap between reality and prediction
<p>Using machine learning (as library I've tried Tensorflow and Tflearn (which, I know is just a wrapping of Tensorflow)) I'm trying to predict the congestion in an area for the next week (see my previous questions if you want more backstory on it). My training set is composed of 400K tagged entry (with the date an con...
<p>Found it. It was a problem with the "def inverse_difference(history, yhat, interval=1):" function. In fact it make my result look like my last lines of training. This is why I had a gap, since there is a pattern in my data (peak always at more or less the same moment) I thought he was doing prediction while he was j...
python|machine-learning|tensorflow|lstm|tflearn
0
18,325
66,537,129
How to convert dataframe rows with cells containing multiple lines to separate columns
<p>I have an existing pandas dataframe with many rows that looks like TABLE-1. Each row has the same number of lines per cell. I.e. c1 has 4 lines, c2 has 2 lines, c3 has two lines, etc... And some have only a single line.</p> <p>TABLE-1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>c1</...
<p>You can do str split and then rename the columns</p> <pre><code>df = pd.concat([df[i].str.split('\n', expand=True) for i in df.columns], axis=1) df.columns = ['c{}'.format(i) for i in range(1,9)] </code></pre> <pre><code> c1 c2 c3...
python|pandas|dataframe
0
18,326
66,758,077
Issue apppending iterrow rows to list
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ind</th> <th>Pin</th> <th>Ar Code</th> <th>Area Name</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>11</td> <td>DL</td> <td>Delhi</td> </tr> <tr> <td>1</td> <td>12–13</td> <td>HR</td> <td>Haryana</td> </tr> <tr> <td>2</td> <td>14–15</td> <td>PB</...
<p>Create column filled by <code>range</code>s and use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a>:</p> <pre><code>def f(x): split = x.strip().split('–') #weird `-`, for me working chr(150) fo...
python|pandas|list|dataframe
0
18,327
73,007,611
Numpy: Perform an "Upsert" by adding columns based on others
<p>I have two numpy arrays, <code>x</code> and <code>y</code>. They each have 3 columns and the first two columns are identifying in the sense of a relational database compound primary key. I want to merge these two arrays based on these compound primary keys, while adding the third column where the two arrays overlap....
<p>This operation can be done in the following steps.</p> <ol> <li>Get a mask whether the first two columns are equal.</li> </ol> <pre class="lang-py prettyprint-override"><code>mask = x[:, :2] == y[:, :2] </code></pre> <ol start="2"> <li>Update the existing values:</li> </ol> <pre class="lang-py prettyprint-override">...
python|numpy
2
18,328
70,578,930
Search for keyword matches in one Dataframe contained in another Dataframe
<p>I have a dataframe A with values that were entered by humans, so they have a degree of variance even though they refer to the same keyword: foo001, foo1, 0foo1 all mean foo1.</p> <p>I have this other dataframe B with keywords as an index and properties associated to them in different columns.</p> <p>My goal is to go...
<p>This is my approach but you may change the part for similarity checking between strings of <code>col1</code>. I use <code>fuzzywuzzy</code> for similarity checking between strings and filter those who have score higher than <code>50</code>:</p> <pre><code>import pandas as pd import numpy as np from fuzzywuzzy import...
python|pandas|dataframe
0
18,329
51,146,960
converting a list to dataframe pandas
<p>Creating a list in a loop, my final list looks like below:</p> <pre><code>L [col1, col2, col3, col4 \ 0 N 225.0 12.0 03.0 B , col1, col2, col3, col4 \ 0 W 223.0 12.0 01.0 M , col1, col2, col3, col4 \ 0 X 203.0 11.0 04.0 P ] </code></pre> <p>Im trying to convert this to a pandas DataFrame?</p> <p>Each ro...
<p>I believe need create 2d numpy array with <code>DataFrame</code> contructor:</p> <pre><code>L = ['col1', 'col2', 'col3', 'col4', 'N 225.0', '12.0', '03.0', 'B' , 'col1', 'col2', 'col3', 'col4', 'W 223.0', '12.0', '01.0', 'M' , 'col1', 'col2', 'col3', 'col4', 'X 203.0', '11.0', '04.0', 'P' ] a ...
list|pandas|dataframe
1
18,330
70,910,861
Converting Zulu Date/Time to Just Date Using Python and Pandas
<p>I have start and end times that look as follows:</p> <p>Start: 2017-03-05T19:18:53Z</p> <p>End: 2017-03-05T19:57:54.042000Z</p> <p>Current iteration that leaves me with the right format but the wrong dtype:</p> <pre><code>format_time_user_df[['start', 'end']] = format_time_user_df[['start', 'end']].apply(pd.to_datet...
<p>If you use <code>.loc[:, ...] =</code>, your values will be updated but the column not, so:</p> <p>Replace:</p> <pre><code>df.loc[:, ['start', 'end']] = ... </code></pre> <p>By:</p> <pre><code>df[['start', 'end']] = ... </code></pre> <p>Now you can use:</p> <pre><code>&gt;&gt;&gt; df['start'].dt.normalize() 0 2017...
python|python-3.x|pandas|datetime
1
18,331
51,943,308
What is this attribute syntax in Python?
<p>I am current following <a href="https://pytorch.org/tutorials/beginner/pytorch_with_examples.html" rel="nofollow noreferrer">a tutorial in Pytorch</a> and there is this expression:</p> <pre><code>grad_h[h &lt; 0] = 0 </code></pre> <p>How does this syntax work and what does it do?</p>
<p>It means replace with zeros all the values in <code>grad_h</code> where its corresponding <code>h</code> is negative.</p> <p>So it is implementing some kind of mask, to keep the gradient values only when <code>h</code> is negative</p> <p>suppose that grad_h and h have the same shape.</p> <pre><code>grad_h.shape =...
python|python-3.x|list|syntax|pytorch
0
18,332
35,815,093
sine calculation orders of magnitude slower than cosine
<h2>tl;dr</h2> <p>Of the same <code>numpy</code> array, calculating <code>np.cos</code> takes 3.2 seconds, wheras <code>np.sin</code> runs 548 seconds <em>(nine minutes)</em> on Linux Mint.</p> <p>See <a href="https://gitlab.com/Finwood/numpy-sine.git" rel="noreferrer">this repo</a> for full code.</p> <hr> <p>I've ...
<p>I don't think numpy has anything to do with this: I think you're tripping across a performance bug in the C math library on your system, one which affects sin near large multiples of pi. (I'm using &quot;bug&quot; in a pretty broad sense here -- for all I know, since the sine of large floats is poorly defined, the ...
python|numpy|scipy|signal-processing
18
18,333
37,440,757
Matplotlib: Different colors for each date, labelled via colorbar
<p>I have a system in two variables, <code>v</code> and <code>u</code>, which change over time. I would like to plot them against each other, and have the time indicated by the color.</p> <p>Here is my data, where the index was generated using <code>pd.to_datetime()</code>:</p> <pre><code> v u d...
<p>Here a ugly solution that perfectly work : </p> <pre><code>N_TICKS = 10 fig, ax = plt.subplots() smap = ax.scatter(df['v'],df['u'],s=500,c=df.index, edgecolors='none', marker='o', cmap=cmap) ) indexes = [df.index[i] for i in np.linspace(0,df.shape[0]-1,N_TICKS).astype(int)] cb = fig.colorbar(sma...
python|pandas|matplotlib
0
18,334
64,220,734
Python - change X axis limits on dataframe plot
<p>Does anyone know how I can change the X-axis limits? I already tried using xlim property but it doesn't work</p> <p>here is my code:</p> <pre><code>test = df.groupby(['Age','Salary']).count()['race'].unstack() test.plot(kind='bar',subplots=True,sharex=False, figsize=(6,5), title=&quot;Age vs Income&quot;) plt.show()...
<p>I think what you want is to reduce the number of ticks. For this locator_params should help. For example you can use it like this:</p> <pre><code>test = df.groupby(['Age','Salary']).count()['race'].unstack() test.plot(kind='bar',subplots=True,sharex=False, figsize=(6,5), title=&quot;Age vs Income&quot;) plt.locator_...
python|pandas|dataframe|matplotlib
0
18,335
64,538,294
Not SELECTING data between two dates that are from different months in SQLite
<p>I am trying to write <a href="https://en.wikipedia.org/wiki/Microsoft_Excel#Current_file_extensions" rel="nofollow noreferrer">XLSX</a> from an SQLite table with a <em>WHERE</em> clause between two selected dates.</p> <p>Below is my example:</p> <pre><code>search_from = &quot;19-09-2020&quot; search_to = &quot;19-...
<p>Date strings need to converted into a valid date format for SQLite as below:</p> <pre><code>from dateutil import parser search_from = &quot;19-09-2020&quot; search_to = &quot;19-10-2020&quot; search_from = parser.parse(search_from, parser.parserinfo(dayfirst=True)) search_from = search_from.strftime('%Y-%m-%d') ...
python|pandas|sqlite
0
18,336
47,681,016
Python: How to create a step plot with offline plotly for a pandas DataFrame?
<p>Lets say we have following <code>DataFrame</code> and corresponding graph generated:</p> <pre><code>import pandas as pd import plotly from plotly.graph_objs import Scatter df = pd.DataFrame({"value":[10,7,0,3,8]}, index=pd.to_datetime([ "2015-01-01 00:00", "2015-01-01 10:00", "2015-01-01 20:00", "2015-01-02 22:00"...
<p>We can use the <code>line</code> parameter <code>shape</code> option as <code>hv</code> using below code:</p> <pre><code>trace1 = { "x": df.index, "y": df["value"], "line": {"shape": 'hv'}, "mode": 'lines', "name": 'value', "type": 'scatter' }; data = [trace1] plotly.offline.plot({ "data": data }) ...
python|pandas|dataframe|plot|plotly
13
18,337
47,700,304
New variable that connects year and quarter
<p>Hi i am a stata user and i am trying to pass my codes to Pandas. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)</p> <p>My ...
<p>My solution extends the idea of @johnchase: build a dictionary mapping from the Cartesian product of <code>year</code> by <code>quarter</code> that takes the string representation <code>year + quarter</code> to integers.</p> <pre><code>ys = df['year'].unique() qs = df['quarter'].unique() new_idx = pd.MultiIndex.fr...
python|pandas|date|numpy|datetime
1
18,338
49,317,991
Is there a way to speed up the following pandas for loop?
<p>My <code>data</code> frame contains 10,000,000 rows! After group by, ~ 9,000,000 sub-frames remain to loop through.</p> <p>The code is:</p> <pre><code>data = read.csv('big.csv') for id, new_df in data.groupby(level=0): # look at mini df and do some analysis # some code for each of the small data frames </code...
<p>Here is one way to speed that up. This adds the desired new rows in some code which processes the rows directly. This saves the overhead of constantly constructing small dataframes. Your sample of 100,000 rows runs in a couple of seconds on my machine. While your code with only 10,000 rows of your sample data tak...
python|pandas|numpy
3
18,339
59,011,145
"ValueError: Unknown optimizer: momentum" correct name for Momentum Optimizer?
<p>I am trying to train my program using the Momentum optimizer but when I input "momentum" as the optimizer, it gives me this error:</p> <pre><code>ValueError: Unknown optimizer: momentum </code></pre> <p>The code I am using is:</p> <pre><code>import tensorflow as tf from tensorflow import keras import matplotlib.p...
<p>Tensorflow has no plain "momentum" optimizer: <a href="http://tensorflow.org/api_docs/python/tf/optimizers" rel="nofollow noreferrer">tensorflow.org/api_docs/python/tf/optimizers</a> in TensorFlow. Though <a href="https://www.tutorialspoint.com/tensorflow/tensorflow_quick_guide.htm" rel="nofollow noreferrer">Tutoria...
python|tensorflow|optimization
2
18,340
58,630,513
How to get rows from dataframe which satisfy certain conditions
<p>I have a dataframe which contains columns education and education-num. I want to know if every row in with X value in education corresponds to Y value in education-num.</p> <p>I have been able to do this to some extent, being able to tell how many rows match or don't match this condition. </p> <pre class="lang-py ...
<p>To filter by multiple columns, you could do - </p> <pre class="lang-py prettyprint-override"><code>other[(other['education'] == 'Masters') &amp; (other['education-num'] == 14)].dropna() </code></pre> <p>For your second case, the code would be - </p> <pre class="lang-py prettyprint-override"><code>mom = other[(oth...
python-3.x|pandas|dataframe
1
18,341
70,161,693
How to search for the position of specific XY pairs in a 2 dimensional numpy array?
<p>I have an image stored as 3 Numpy arrays:</p> <pre class="lang-py prettyprint-override"><code># Int arrays of coordinates # Not continuous, some points are omitted X_image = np.array([1,2,3,4,5,6,7,9]) Y_image = np.array([9,8,7,6,5,4,3,1]) # Float array of RGB values. # Same index rgb = np.array([ [0.5543,0.266...
<p>The classical method to solve this problem is generally to use a <strong>hashmap</strong>. However, Numpy do not provide such a data structure. That being said, an alternative (generally slower) solution is to <strong>sort the values</strong> and then perform a <strong>binary search</strong>. Hopefully, Numpy provid...
python|arrays|numpy|performance|image-processing
2
18,342
56,433,637
Fast way to turn dictionary to (dense) matrix
<p>I have a list of dictionaries, with values always integers, and keys some strings. We can interpret this as a matrix, where each dictionary is a row, and each column corresponds to a key belonging to at least one of the dictionaries. The dictionaries represent polynomials, where the keys are monomials and the values...
<p>If, according to this part of the question:</p> <blockquote> <p>This basically corresponds to <code>sklearn.feature_extraction.DictVectorizer</code>. I'm working in sagemath, which does not ship with sci-kit learn, so using this is not ideal.</p> </blockquote> <p>the wish is to install scikit-learn into Sage...
python|numpy|sage
0
18,343
55,652,707
Replace 1 value in a subsection of dataframe with value of another column
<p>I have a one hot encoded dataframe such as:</p> <pre><code>| qtd| a | b | c | d | e | ...z| |-----+-----+-----|----|----+-----+-----| | 90 | 1 | 0 | 0 | 0 | 0 | 0 | | 10 | 0 | 0 | 0 | 0 | 0 | 1 | | 40 | 0 | 1 | 0 | 0 | 0 | 0 | | 80 | 0 | 0 | 1 | 0 | 0 | 0 | | 90...
<p>You can select all columns without first by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a> and multiple by column with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mul.html...
python|pandas|one-hot-encoding
3
18,344
64,670,943
Generate list of numbers from a list with probability weights
<p>How would one go about generating a list of random numbers from a list of 35 numbers with given probabilities:</p> <p>Probability of number in range (1,5) - <em>p1</em> = 0.5</p> <p>Probability of number in range (6,15) - <em>p2</em> = 0.25</p> <p>Probability of number in range (16,35) - <em>p3</em> = 0.25</p> <p>I ...
<p>If you want to select uniformly from each group:</p> <pre><code>p=np.array([0.5/5]*5+[0.25/30]*30) np.random.choice(np.arange(1,36),p=p/p.sum()) </code></pre> <p><strong>UPDATE</strong>:</p> <p>and if you would like to select a list of random numbers (you can also set with or without replacement flag):</p> <pre><cod...
python|arrays|numpy|random|probability
2
18,345
39,441,359
Where can I find the inner working of csr matrix addition in the SciPy library?
<p>I'm writing my own program that can convert form COO form to CSR form in C++. Where I get stuck is trying to figure out how to do addition with CSR format in an efficient way. I currently have a way to find matches of entries in an A and B matrix stored in CSR form, but I'd like to find where SciPy/NumPy actually h...
<p>This will give you a start:</p> <p><a href="https://github.com/scipy/scipy/tree/master/scipy/sparse" rel="nofollow">https://github.com/scipy/scipy/tree/master/scipy/sparse</a></p> <p><a href="https://github.com/scipy/scipy/blob/master/scipy/sparse/sparsetools/csr.h" rel="nofollow">https://github.com/scipy/scipy/bl...
c++|numpy|scipy
0
18,346
44,112,286
Python: Store directories and filenames as dataframe columns
<p>I want to read the contents of a directory that has multiple folders and files within each directory, and assign the folder and file names as values of the columns of a dataframe.E.g. directory is 'home' and within it several folders and files in each folder. The 'folder' column will be repeated for as many files in...
<p>I think you need create <code>tuples</code> of pair <code>folder-file</code> and then create <code>DataFrame</code>:</p> <pre><code>data = [] for folder in sorted(os.listdir('home')): for file in sorted(os.listdir('home/'+folder)): data.append((folder, file)) df = pd.DataFrame(data, columns=['Folder', ...
python|file|pandas|directory|subdirectory
9
18,347
44,301,429
How to use numpy to calculate mean and standard deviation of an irregular shaped array
<p>I have a numpy array that has many samples in it of varying length</p> <pre><code>Samples = np.array([[1001, 1002, 1003], ... , [1001, 1002]]) </code></pre> <p>I want to (elementwise) subtract the mean of the array then divide by the standard deviation of the array. Somethin...
<p>Don't make ragged arrays. Just don't. <code>Numpy</code> can't do much with them, and any code you might make for them will always be unreliable and slow because <code>numpy</code> doesn't work that way. It turns them into <code>object</code> dtypes:</p> <pre><code>Sample array([[1, 2, 3], [1, 2]], dtype=object)...
python|arrays|numpy
5
18,348
69,367,799
Pandas how to apply a function to groupby().first()
<p>I have a df,the code is:</p> <pre><code> df = &quot;&quot;&quot; ValOption RB test contrat 0 SLA 4 3 23 1 AC 5 4 12 2 SLA 5 5 23 3 AC 2 4 39 4 SLA 5 5 26 5 AC 3 4 52 6 SLA 4 3 64 0 SLA 4 3 ...
<p>You have to <code>reset_index</code> to access the row 'RB' &amp; 'test'. Use <code>.values</code> to set values to <code>new_col</code>:</p> <pre><code>df_u['new_col'] = df_u.reset_index().apply(func, axis=1).values print(df_u) # Output: ValOption contrat new_col RB test 2 4 ...
python|pandas|dataframe|numpy|numpy-ndarray
2
18,349
69,634,866
How to unstack the Period column
<p>I was wondering how I could unstack each year separately into its own column from the dentist.csv file found here <a href="https://www.kaggle.com/utkarshxy/who-worldhealth-statistics-2020-complete?select=safelySanitization.csv" rel="nofollow noreferrer">https://www.kaggle.com/utkarshxy/who-worldhealth-statistics-202...
<p>Use df=dent.groupby(&quot;period&quot;) To group the data and then apply df.unstack(level=-1) to unstack</p>
python|pandas|dataframe
0
18,350
41,094,076
Unsure how to use FFT data for spectrum analyzer
<p>I'm trying to create a home made spectrum analyzer with 8 strips of LED's.</p> <p>The part i'm struggling with is performing the FFT and understanding how to use the results.</p> <p>So far this is what I have:</p> <pre><code>import opc import time import pyaudio import wave import sys import numpy import math CH...
<p>Because of the way np.fft.fft works, if you use 1024 data points you will get values for 512 frequencies (plus a value zero Hz, <em>DC offset</em>). If you only want 8 frequencies you have to feed it 16 data points.</p> <p>You might be able to do what you want by down sampling by a factor of 64 - then 16 down sampl...
python|numpy|fft
4
18,351
53,858,136
Pandas filling in the missing data when the dataset has "-" and "None" cells
<p>I am working with a dataset that has "-" in the sourceusername column and "None" in the sourcehostname column of this dataframe. The IP usually stays the same for desktops, but changes for laptops. I am trying to fill in the blanks using the information I have. This data frame has computers where a user will log o...
<p>The following gives the desired output which has been posted:</p> <p>Append <code>sourceaddress</code> to the Index because the row number is like a time-series as discussed in the comments</p> <pre><code>df = df.set_index('sourceaddress', append=True) </code></pre> <p>Swap the <code>Index</code> levels and then ...
python|pandas
1
18,352
38,269,304
SymPy: lambdified dot() with (3,n)-array
<p>I have a <code>lambdify</code>d sympy function with a <code>dot</code> product in it, e.g.,</p> <pre><code>import numpy as np import sympy class dot(sympy.Function): pass x = sympy.Symbol('x') a = sympy.Matrix([1, 1, 1]) f = dot(x, a) ff = sympy.lambdify((x), f, modules='numpy') x = np.random.rand(3) pr...
<p>You're doing multiple odd things, but I can't tell how much of this is due to an oversimplified MCVE.</p> <p>First, a bit more elegant definition of your function:</p> <pre><code>import sympy as sym x = sym.Symbol('x') a = sym.Matrix([1, 1, 1]) dot = sym.Function('dot') f = dot(x, a) ff = sym.lambdify(x, f, ...
python|numpy|sympy
3
18,353
66,189,126
Numpy Python Numerical Errors
<p>when using the numpy module on my computer, in particular np.linalg.solve, I am getting numerical errors in the outputs that I do not get when running the same exact code on other computers. I have tried deleting and re-downloading anaconda and updating numpy however this does not fix things, and sometimes I would e...
<p>As a test, maybe create a new environment and only install numpy and its dependencies.</p>
python|macos|numpy|jupyter-notebook|anaconda
1
18,354
66,279,900
How to asynchronously distribute product-yielding from a dataframe in scrapy spider
<h2>Is there a way to utilize Scrapy's asynchronous architecture when yielding products from a dataframe?</h2> <hr /> <h3>Overview</h3> <p>I have a spider in one of my Scrapy projects that differs from your typical logic of a spider as follows:</p> <ol> <li>Crawls an online file directory to get the most recent version...
<p>Would it be possible to break it up into two separate .py?</p> <p>The first does the crawling and copying - after copying it updates a redis db that contains a list of the appropriate file names - its running on twisted or whatever).</p> <p>The second runs on an internal python scheduler or similar and accesses the ...
python|pandas|dataframe|asynchronous|scrapy
0
18,355
52,510,665
how to read multiple wav files in python, and convert to numpy arrays to plot
<p>I need to read multiple wave files named as chunk1.wav, chunk2.wav... in my project directory and convert them into numpy arrays to plot. I am able to do this for a single wav file, convert it to numpy and plot it using matplotlib, but am not able to do it for an array of wav files.</p> <p>I searched all over on ho...
<p>Looking at the scipy internals this is caused by the file signature not being understood, from the error message you get it looks like the file signature is missing (<code>''</code>), or there is some other issue reading data from the file:</p> <pre><code>def _read_riff_chunk(fid): str1 = fid.read(4) # File si...
python|numpy|scipy|wav
0
18,356
46,252,375
Detect object in specific region of frame
<p>I would like to detect objects from the region of a frame using tensorflows object detection api. I have split the frame into region_1 and region_2 but how do I perform detection only in region_1 from the frame and draw rectangles only in region1</p> <pre><code>def detect_objects(image_np, sess, detection_graph): ...
<p>You have to substitute the region you're interested in where image_np was before, so change </p> <pre><code>image_np_expanded = np.expand_dims(image_np, axis=0) </code></pre> <p>to:</p> <pre><code>image_np_expanded = np.expand_dims(region_1, axis=0) </code></pre> <p>and</p> <pre><code>vis_util.visualize_boxes_a...
python|opencv|tensorflow
0
18,357
46,548,561
Does tensorflow re-use nodes created with the same formulas?
<p>Suppose I have</p> <pre><code>wT = tf.transpose(w, perm=[0, 2, 1]) </code></pre> <p>line in different places of my graph creating code and <code>w</code> is always the same.</p> <p>Will <code>wT</code> also be the same?</p>
<p>TL;DR: yes if <code>w</code> really never changes</p> <hr> <p><strong>This bit you likely already know:</strong> </p> <p>With Tensorflow with Python (probably with everything but I only know python myself) you define the flow of tensors and then run the model to determine each tensor's value. When you define <cod...
python|tensorflow
0
18,358
58,390,209
ResNet50 Model is not learning with transfer learning in keras
<p>I am trying to perform transfer learning on ResNet50 model pretrained on Imagenet weights for PASCAL VOC 2012 dataset. As it is a multi label dataset, I am using <code>sigmoid</code> activation function in the final layer and <code>binary_crossentropy</code> loss. The metrics are <code>precision,recall and accuracy<...
<p>Please can you modify code as below and try to execute</p> <p>From:</p> <pre><code>predictions = Dense(num_classes, activation= 'sigmoid')(x) </code></pre> <p>To:</p> <pre><code>predictions = Dense(num_classes, activation= 'softmax')(x) </code></pre> <p>From:</p> <pre><code>model.compile(optimizer= adam, loss=...
python|tensorflow|keras|conv-neural-network|resnet
1
18,359
58,320,398
Plotting the count of occurrences per date
<p>I'm very new to pandas data frame that has a date time column, and a column that contains a string of text (headlines). Each headline will be a new row.</p> <p>I need to plot the date on the x-axis, and the y-axis needs to contain how many times a headline occurs on each date.</p> <p>So for example, one date may c...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_counts</code></a> with <code>date</code> column for <code>Series</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.sort_index...
python|pandas|data-science
3
18,360
58,414,137
How to save the structure and weights of trained tensorflow model?
<p>I have a model with a relatively complicated computational graph and am about to train it on a large set of data. How can I save the trained model afterwards, so that I can just load its (structure + weights) without specifying the complicated model structure again? I just want to a single file "trained_model" that ...
<p>You can save models in h5 file. And load them later on. You shouldn't rebuilt the whole thing again because then you have to train it every time you want to use it. </p> <pre><code># Save the model model.save('../resources/saved_models/my_model.h5') # Recreate the exact same model purely from the file new_model = ...
python|tensorflow
0
18,361
58,288,236
Pandas - read csv stored as string in memory to data frame
<p>With comma separated text stored in a var like below</p> <pre><code>data = """ Class,Name,Long,Lat A,ABC11,139.6295542,35.61144069 A,ABC20,139.630596,35.61045559 A,ABC03,139.6300307,35.61327781 B,ABC54,139.7787818,35.68847945 B,ABC05,139.7814447,35.6816882 B,ABC06,139.7788191,35.681865 B,ABC24,139.7790396,35.677816...
<p>With <a href="https://docs.python.org/3/library/io.html#io.StringIO" rel="noreferrer"><code>io.StringIO</code></a> object (in-memory stream for text I/O):</p> <pre><code>import pandas as pd from io import StringIO data = """ Class,Name,Long,Lat A,ABC11,139.6295542,35.61144069 A,ABC20,139.630596,35.61045559 A,ABC03...
python|pandas
17
18,362
58,462,142
How to convert from pandas dataframe to a dictionary
<p>I have look at <a href="https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary">Convert a Pandas DataFrame to a dictionary</a> for guides to convert my dataframe to a dictionary. However, I can't seem to change my code to convert my output into a dictionary. </p> <p>Below are my cod...
<p>I think that I find this dataset: <a href="https://data.gov.sg/dataset/government-procurement" rel="nofollow noreferrer">https://data.gov.sg/dataset/government-procurement</a></p> <p>Anyway, here is code </p> <pre><code>import pandas as pd df = pd.read_csv('government-procurement-via-gebiz.csv', ...
python|pandas
0
18,363
69,092,129
How can I recode 53k unique addresses (saved as objects) w/o One-Hot-Encoding in Pandas?
<p>My data frame has 3.8 million rows and 20 or so features, many of which are categorical. After paring down the number of features, I can &quot;dummy up&quot; one critical column with 20 or so categories and my COLAB with (allegedly) TPU running won't crash.</p> <p>But there's another column with about 53,000 unique ...
<p>Without knowing more details of the problem/feature, there's no obvious way to do this. This is the part of Data Science/Machine Learning that is <strong>an art, not a science</strong>. A couple ideas:</p> <ol> <li>One hot encode everything, then use a dimensionality reduction algorithm to remove some of the columns...
pandas|scikit-learn|one-hot-encoding
2
18,364
69,108,284
tf.data.Dataset, map functionality and random
<p>Manipulating <code>tf.data.Dataset</code> I get a behavior, I am not able to understand the origin. I am manipulating a <code>tf.data.Dataset</code> a simple integer buffer where I want to add a random integer to each number (the important point). TF provides a map function to apply a transformation (generator) to e...
<p>In the second case, generating random integers is a part of graph, because you use tf API. So each time the graph runs, the process of generating random integers will rerun. In the first case, the random integers are generated first, and then they take part in the computing graph. So they act like constant. This is ...
tensorflow|tensorflow2.0|tensorflow-datasets
0
18,365
69,186,951
I'm facing an error while importing tensorflow lately
<p>I'm trying to import the below packages , it was working previously , today all of sudden I'm unable to install these packages</p> <pre><code>import tensorflow from tensorflow.keras.preprocessing.image import ImageDataGenerator from sklearn.model_selection import train_test_split from keras.layers.pooling import Ave...
<p>Create a new environment for tensorflow and reinstall tensorflow in that environment using below code:</p> <pre><code>conda create -n tf tensorflow python=3.5 conda activate tf conda install pip pip install tensorflow </code></pre> <p>Then try again executing your codes. Let us know if still issue persists.</p>
python|python-3.x|tensorflow|image-processing|computer-vision
1
18,366
68,913,926
Python Loop Saving Twice in Loop to Excel Spreadsheet Tab
<p>I have my code that looks like the following as part of a long loop structure that writes 2 dfs to the same spreadsheet and excel tab. Here is the code I'm using trying to append with each write sequence:</p> <pre><code># WRITE OUTPUT TO EXCEL FILE - with pd.ExcelWriter('\\\porfiler03\\gtdshare\\ERA5-MAPPING\\PCA\\...
<p>It's not possible with how you're currently doing it. The docs for the <a href="https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html" rel="nofollow noreferrer">ExcelWriter class has this flag</a>:</p> <p>if_sheet_exists{‘error’, ‘new’, ‘replace’}, default ‘error’: How to behave when trying to write t...
python|excel|loops|xlsxwriter|pandas.excelwriter
1
18,367
44,665,547
How to compare values in pandas pivot_table with different indices?
<p>Pivot Table:</p> <pre><code>COURSE ENGLISH MATH ART STUDENT StudentA 95.0 83.0 97.0 StudentB 91.0 93.0 47.0 StudentC 85.0 84.0 92.0 StudentD 97.0 84.0 85.0 StudentE 93.0 88.0 ...
<p>This returns a list of tuples that show which student and in which subject had a grade more than 5% less that the average.</p> <pre><code>avg = df.loc['StudentAvg', :] i, j = np.where(((df / avg) - 1) &lt; -.05) list(zip(df.index[i], df.columns[j])) [('StudentB', 'ART'), ('StudentC', 'ENGLISH'), ('StudentC', 'AR...
python|pandas|pivot-table
2
18,368
44,472,692
How do I perform groupby only the values that exist?
<p>I have a dataframe like this:</p> <pre><code>Platform Genre Score PC Action 9 PS Adventure 8.5 Xbox Action 9.5.... </code></pre> <p>the dataframe is huge. I want to visualize a heatmap showing the platform on the x-axis, the Genre on y and the score as the value.</p> ...
<p>As <a href="https://stackoverflow.com/users/3868428/joecondron">JoeCondron</a> says, the pivot is giving it to you this way because it is creating a grid. However, I suspect you want it to be super clear in your heatmap that the values are null because if you create a platform X genre grid, those spots ARE going to ...
python|pandas|dataframe
0
18,369
44,734,613
pandas returning the unnamed columns
<p>The following is example of data I have in excel sheet. </p> <pre><code>A B C 1 2 3 4 5 6 </code></pre> <p>I am trying to get the columns name using the following code:</p> <pre><code>p1 = list(df1t.columns.values) </code></pre> <p>the output is like this</p> <pre><code>[A, B, C, 'Unnamed: 3', ...
<p>There is problem some cells are not empty but contains some whitespaces.</p> <p>If need columns names with filtering <code>Unnamed</code>:</p> <pre><code>cols = [col for col in df if not col.startswith('Unnamed:')] print (cols) ['A', 'B', 'C'] </code></pre> <p>Sample with <a href="https://dl.dropboxusercontent.co...
python|pandas
3
18,370
61,100,852
How to not overwrite csv file in dataframe?
<p>I am running python script. But it overwriting the file every time. Can you please help me how to do this?</p> <p>example:</p> <pre><code>DF1 Table Count case 20 recordtype 50 consumer 70 settlement 150 address 250 bridge 130 </code></pre> <p>I ran the proce...
<p>You need to choose mode=append to append it to your existing csv file. Check if file is present in path. If its present, set mode=append else create a new csv file. And you need to choose header=False to make sure header doesn't appearin append mode.</p> <pre><code>import os.path if(os.path.isfile('Your path')): ...
python|pandas|csv|dataframe
0
18,371
60,915,141
How to split a column by a delimiter, while respecting the relative position of items to be separated
<p>Below is my script for a generic data frame in Python using pandas. I am hoping to split a certain column in the data frame that will create new columns, while respecting the original orientation of the items in the original column.</p> <p>Please see below for my clarity. Thank you in advance!</p> <p>My script:</p...
<p>You can use the <code>justify</code> function from <a href="https://stackoverflow.com/a/44559180/9081267">this</a> answer with <code>Series.str.split</code>:</p> <pre><code>dfn = pd.DataFrame( justify(df['col1'].str.split(',', expand=True).to_numpy(), invalid_val=None, axis=1, ...
python|pandas|split|position
2
18,372
61,153,610
Matching panel data at time t-1 and time t Python Pandas
<p>I am currently working on a project involving financial data. I have a data frame containing a number of fundamental variables as well as stock returns for many different companies, just like this:</p> <pre><code> year ticker tot_assets return 0 1999 AAPL 10.345 ...
<p>This should get you the ticker of the firm with the closest match of tot_assets in year - 1. Hopefully, you only need to run it once to create the dataset. Otherwise, you'll have to investigate faster alternatives.</p> <pre><code>import numpy as np def closest_match(row, df): '''Uses absolute values and argmin...
python|pandas|numpy|finance
0
18,373
61,097,676
Is there a way where I can optimize the output restricting the parameters in fmin from scipy.optimize
<p><strong>What I am doing:</strong> I modified the code from the zombie invasion system to demonstrate how it should be written and tried to optimize the least square error (defined as score function) with the fmin function.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.integrate import...
<p>I'm not sure why the original author of <a href="http://adventuresinpython.blogspot.com/2012/08/fitting-differential-equation-system-to.html" rel="nofollow noreferrer">Adventures in Python : Fitting a Differential Equation System to Data</a> jumps through hoops to get at the samples corresponding to the given data p...
python|numpy|scipy|mathematical-optimization|ode
0
18,374
71,479,228
Remove outlier with Python
<p>I have a DataFrame which consists of 30 rows and 9 columns. I want to make a 2 sigma outlier removal.</p> <p>I do it with this:</p> <pre><code>from scipy import stats df[(np.abs(stats.zscore(df)) &lt; 2).all(axis=1)] </code></pre> <p>But it removes the whole line if there is a outlier in a single column. I just want...
<p>If you need to replace outliers by missing values, use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a>:</p> <pre><code>df = df.mask(np.abs(stats.zscore(df)) &lt; 2) #working for replace outlier by missing values...
python|pandas|numpy|scipy
3
18,375
71,642,386
How to open excel file in Polars dataframe?
<p>I am a python pandas user but recently found about polars dataframe and it seems quite promising and blazingly fast. I am not able to find a way to open an excel file in polars. Polars is happily reading <code>csv</code>, <code>json</code>, etc. but not excel.</p> <p>I am extensive user of excel files in pandas and ...
<p>This is more of a workaround than a real answer, but you can read it into pandas and then convert it to a polars dataframe.</p> <pre><code>import polars as pl import pandas as pd df = pd.read_excel(...) df_pl = pl.DataFrame(df) </code></pre> <p>You could, however, make a feature request to the Apache Arrow community...
python|excel|pandas|dataframe
1
18,376
71,577,895
Pandas : How to create an algorithm that helps me improve results and creating new columns?
<p>it's a little bit complicated , i have this dataframe :</p> <pre><code>ID TimeandDate Date Time 10 2020-08-07 07:40:09 2022-08-07 07:40:09 10 2020-08-07 08:50:00 2022-08-07 08:50:00 10 2020-08-07 12:40:09 2022-08-07 12:40:09 10 2020-08-08 07:40:09 2022-08-08 07:40:09 10 2...
<p>If I understand correctly, you can do something like:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df[&quot;TimeandDate&quot;] = pd.to_datetime(df[&quot;TimeandDate&quot;]) df.set_index(&quot;TimeandDate&quot;, inplace=True) print(df.groupby([df[&quot;ID&quot;], df.index.year, df.index.mon...
python|pandas|dataframe|machine-learning|pandas-groupby
1
18,377
71,650,214
obtain header "letter" searching for column name in excel with pandas and python
<p>im using pandas with excel and i would like to get the letter of the header in excel searching for column name.</p> <p>here´s an example</p> <p><img src="https://i.stack.imgur.com/2W3Wy.png" alt="1" /></p> <p>i would like to do something LIKE this: df.columns.get_loc(&quot;SR Status&quot;) and i would like to return...
<p>You can use <code>get_column_letter</code>:</p> <pre><code>import pandas as pd from openpyxl.utils import get_column_letter df = pd.read_excel('data.xlsx', usecols='D:F') offset = 4 # D col = get_column_letter(df.columns.get_loc('SR Status') + offset) print(col) # Output: D </code></pre>
python|excel|pandas
0
18,378
71,706,851
How to get N maximum values of each array from a numpy array of arrays
<p>I have a numpy array of arrays <code>x = [[1, 3, 4, 5], [6, 2, 5, 7]]</code>. I want to get N maximum values from each array of the numpy array: <code>[[5, 4], [7, 6]]</code>. I have tried using <code>np.argpartition(x, -N, axis=0)[-N:]</code> but it gives <code>ValueError: kth(=-3) out of bounds (1)</code>. What is...
<p>You can do this by sorting each row and slicing as you want:</p> <pre><code>np.sort(x, axis=1)[:, :2] # --&gt; [[1 3] [2 5]] 2 minimum in each row np.sort(x, axis=1)[:, 2:] # --&gt; [[4 5] [6 7]] 2 maximum in each row </code></pre>
python|arrays|numpy
1
18,379
69,778,061
How to calculate the Euclidean distance in python
<p>I have a dataset in .csv format. contains 2099846 rows and 38 columns I want to calculate the Euclidean distance of any pair of rows and set to another 2d array.</p> <pre><code>import pandas as pd import numpy as np data = pd.read_csv('fraudDataset.csv', encoding= 'unicode_escape') row = len(data) data = data.ast...
<p>I cannot replicate the problem, as there is inadequate information about the type of data, thus suggesting a fix to the error message. But from your problem description, I think <code>cdist</code> function from <code>scipy.spatial</code>* could solve your problem. As you have not provided an example data row, I crea...
python|pandas|numpy
0
18,380
70,016,216
Python algorithm with numpy
<p>I want to group in a 2D array (couples) to see the family:</p> <pre><code>rij = [[11, 2], [15, 6], [7, 8], [3, 6], [9, 2], [2, 3], [2, 3]] rij = np.sort(rij, axis=1) #sort inside array rij = np.unique(rij, axis=0) #remove duplicates </code></pre> <p>After this code I get this:</p> <pre><code>[[ 2 3] [ 2 9] [ 2 1...
<p>We can solve this using scipy's sparse matrix and graph module. Your <code>rij</code> forms an adjacency matrix. That is a matrix that is 1 if two nodes are connected and 0 if not. From this, we can compute other properties.</p> <p>Let's apply this to your problem. We start by cleaning up your input. As @Ali_Sh note...
python|numpy
0
18,381
69,895,418
Converting list to DataFrame how to remove leading 0 in the first row
<p>I am trying to use Panda to convert a <code>list</code> to a <code>DataFrame</code>. Every time I am trying to conver the list to a DataFrame I get a first row with <code>0</code> and it does not work correctly?</p> <p>Code:</p> <pre><code>import pandas as pd df = pd.DataFrame(list(data)) print(df) </code></pre> <p...
<p>What you want is something like:</p> <pre><code>pd.DataFrame(data[1:], columns=data[0].split(',')) </code></pre> <p>To get a clean dataframe with <code>datetime</code> and <code>float</code> types:</p> <pre><code>df = (pd.DataFrame(data[1:], columns=data[0].replace('&quot;', '').split(',')) .assign(DateTime=...
python|pandas|list|dataframe
1
18,382
69,733,719
ModuleNotFoundError: No module named 'keras' when using tensorflow 2.6
<p>I created a new conda env with</p> <pre><code>conda create --name tf tensorflow=2.6 </code></pre> <p>and tried to compile</p> <pre><code>import tensorflow as tf model = tf.keras.models.Sequential() </code></pre> <p>resulting in ModuleNotFoundError: No module named 'keras'</p> <pre><code>conda install keras </code></...
<p>What turned out is that I had both keras and keras nightly installed, the problem got resolved after uninstalling keras-nightly. If anyone encounters this check your <code>conda list</code> and <code>pip list</code> for duplicate keras installations</p>
tensorflow
0
18,383
43,299,256
Write df.value_counts to new file
<p>I have a data frame of cluster labels generated using DBSCAN and I am counting the frequency of the cluster labels. I can print the frequency using <code>df['cluster_labels'].value_counts()</code>, but when I go to write this to a new file, I just get the count of clusters but not their corresponding label. How can ...
<p>It's because you are using <code>index=False</code>. Change the <code>index=False</code> to <code>index=True</code> in the line</p> <pre><code>cluster_counts.to_csv('G:\Programming Projects\GGS 681\dmv_tweets_20170309_20170314_cluster_counts.csv', index=False, header=True) </code></pre> <p>You can see this in the ...
python|pandas
5
18,384
72,276,590
python, pandas - how to replace values in a data frame column
<p>I have a following code which suppose to create a new column &quot;TEMP1&quot; which is a column &quot;TEMP&quot; with some replacements - replace #1 to a value of column PARM1:</p> <pre><code>import pandas as pd d = {'col1': [1, 2], 'TEMP': ['kk(#1,#2)', 'kk(#1,#2)'], 'PARM1':['VAR1','VAR2'], 'PARM2':['VAR3','VAR1'...
<p>If your table format is pretty stable you could do something like this</p> <pre><code>d = {'col1': [1, 2], 'TEMP': ['kk(#1,#2)', 'kk(#1,#2)'], 'PARM1':['VAR1','VAR2'], 'PARM2':['VAR3','VAR1']} df = pd.DataFrame(data=d) df['TEMP1'] = df['TEMP'] for i in range(0, len(df)): df.at[i, 'TEMP1'] = df.iloc[i]['TEMP1'].r...
python|pandas|dataframe|replace
0
18,385
72,232,890
Calculate Decay Rate in Python
<p>I have dataset which somewhat follows an exponentional decay</p> <pre><code>df_A Period Count 0 1600 1 894 2 959 3 773 4 509 5 206 </code></pre> <p>I want to calculate the decay rate by using 2 methods as I'm expecting both to give the same result, however, I get different result...
<p>Not sure what you mean by &quot;over-complicated&quot;. Can you explain your 2 methods? I'm not sure I follow how you arrived by them? In any case, <code>scipy.optimize.curve_fit</code> does all the heavy lifting for you:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd from...
python|pandas|numpy|math|statistics
2
18,386
72,239,334
How to use dedicated GPU with TF2, given that multiple GPUs are available?
<p>As title. I thought these lines would work to use only one GPU:</p> <pre class="lang-py prettyprint-override"><code>_GPU = tf.config.list_physical_devices('GPU')[3] tf.config.experimental.set_memory_growth(_GPU, True) tf.config.set_visible_devices(_GPU, device_type='GPU') </code></pre> <p>But when I ran these follow...
<p>These lines should be run first after those <code>import</code>s:</p> <pre class="lang-py prettyprint-override"><code>os.environ[&quot;CUDA_DEVICE_ORDER&quot;]=&quot;PCI_BUS_ID&quot; os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;]=&quot;2&quot; # GPU according to nvidia-smi. </code></pre> <p>After these two commands, y...
python|gpu|tensorflow2.0
1
18,387
72,269,018
Adding new columns on hundreds excel file with path reference into one pandas dataframe
<p>I have probably hundreds or thousands small excel file with bracket into one pandas dataframe</p> <p>Before I merge them, I need to give flag for which category they come from</p> <p>Here's my table of reference <code>df</code></p> <pre><code> Dataframe_name Path Sheet 45 fin...
<p>This would be fairly simply, you can <code>assign</code> the flag dynamically for each iteration:</p> <pre><code>pd.concat([pd.read_excel(path, sheet_name=sheet).assign(df_name=name) for name, path, sheet in df.to_numpy()]) </code></pre>
python|pandas
1
18,388
72,240,334
how to access a specific data in two columns using if and statement
<p><a href="https://i.stack.imgur.com/jm1Gr.jpg" rel="nofollow noreferrer">My Data Frame</a></p> <p>My Code:</p> <pre><code>a = 10001 b = &quot;01.01.2001&quot; if a == np.any(df[&quot;Token_ID&quot;]) and b == np.any(df[&quot;Date_of_birth&quot;]): print(&quot;yes&quot;) else: print(&quot;no&quot;) </code></...
<p><strong>The current code</strong> compares <code>a</code> value with all values <code>Token_ID</code> column which results a column of <code>True</code> and <code>False</code> values and the same with <code>b</code> value with values of <code>Date_of_birth</code> column. Then, you put <code>and</code> operator betwe...
python|python-3.x|pandas
0
18,389
50,489,561
Can I use Tensorflow on Orange pi 4G IOT with Ubuntu?
<p>I am trying to build an imaging system and I want to use Tensorflow with Orange pi 4G. Does anyone know if there are limitations, is this possible? </p> <p>As I can see Orange PI 4g iot is still not compatible with Ubuntu but I hope it will be in the near future. Any information you could give me i will be happy.<...
<p>Official CI server for Tensorflow has some <a href="https://ci.tensorflow.org/view/Nightly/job/nightly-pi/" rel="nofollow noreferrer">nightly builds</a> with python wheels for raspberry pi armv7l, it is not officially supported by tensorflow yet, they officially support only 64-bit architectures so far, but I manage...
image-processing|tensorflow|iot|4g|orange-pi
0
18,390
50,644,639
Find elements in array such that inf < element < sup in Python
<p>Given an array of unsorted points I need to replace those in a given interval. Easiest way I think of is</p> <pre><code>import numpy as np def v1(array,inf,sup): for i in range(len(array)): if inf&lt;array[i]&lt;sup: array[i]-=10 return array </code></pre> <p>I was suggested to use <co...
<p>Use <code>&amp;</code> to have multiple conditions with <code>np.where</code>:</p> <pre><code>array[np.where((inf &lt; array) &amp; (array &lt; sup))[0]] -= 10 </code></pre> <p>Or without <code>np.where</code>:</p> <pre><code>array[(inf &lt; array) &amp; (array &lt; sup)] -= 10 </code></pre>
python|arrays|numpy
4
18,391
50,414,136
Pandas - Comparison between different strings always returns True
<p>I am trying to compare the value in a cell of a Pandas dataframe with the cell immediately below it. To obtain the value from the row below the current row, I am using shift:</p> <pre><code>df['shift_minus_1'] = df['company'].shift(-1) </code></pre> <p>However, when I compare these values, Pandas returns True, eve...
<p>You're comparing just the first value in the array rather than the whole series:</p> <pre><code>df['comparison'] = df['company'].shift(-1) == df['company'] </code></pre> <p>should work</p> <p>What you did</p> <pre><code>df['comparison'] = df['company'].shift(-1).values[0] == df['company'].values[0] </code></pre>...
python|pandas
1
18,392
45,397,244
Compute if value exists in a column on lists in pandas dataframe
<p>I have 2 columns in my dataframe</p> <ol> <li>product ID purchased by the customer "p"</li> <li><p>list of products IDs purchased by similar customers "p_list"</p> <pre><code>df = pd.DataFrame({'p': [12, 4, 5, 6, 7, 7, 6,5],'p_list':[[12,1,5], [3,1],[8,9,11], [6,7,9], [7,1,2],[12,9,8], [6,1,15],[6,8,9,11]]}) </cod...
<p>You can use <code>list comprehension</code>, last cast <code>True, False</code> values to <code>int</code>:</p> <pre><code>df["exist"] = [r[0] in r[1] for r in zip(df["p"], df["p_list"])] df["exist"] = df["exist"].astype(int) print (df) p p_list exist 0 12 [12, 1, 5] 1 1 4 [3, 1] ...
python|pandas|dataframe|apply
6
18,393
45,674,449
unable to get the updated value of tensor in tensorflow
<p>I used the code below for simple logistic regression. I was able to get the updated value of b: the values of <code>b.eval()</code> before/after training are different. However, the value of <code>W.eval()</code> remains the same. I was wondering what mistake I made? Thank you!</p> <pre><code>from __future__ import...
<p>When we print a numpy array only initial and last values will get printed, And in case of MNIST those indices of weights are not updating as corresponding pixels in images remains constant as all digits are written in centre part of array or image not along boundary regions. The actual pixels which are varying from...
python|tensorflow
0
18,394
45,622,069
Series object has no split attribute - reading in data from text file
<p>I am reading in data from a .txt file that looks like the following, and I am extracting the third item in each of the brackets with the code that is at the bottom.</p> <p>With the line, <code>data = data.iloc[0, ::4]</code>, I was removing 3 out of every 4 data points (I think). </p> <p>However, now I am trying ...
<p>Because <code>data</code> is a <code>pd.DataFrame</code>, so when you <code>.apply</code> a function to it, it passes a <code>pd.Series</code> as the argument to the function. <code>pd.Series</code> doesn't have a <code>.split</code> method. When you do:</p> <pre><code>data = data.iloc[0, ::4] </code></pre> <p>You...
python|pandas
1
18,395
62,592,893
How to index a tensor and change the value
<p>I am working on a algorithm with <code>tensorflow</code>. Following is the <code>NumPy</code> version of the wanted code:</p> <pre class="lang-py prettyprint-override"><code>x = [1,2,3,4,5,6,7,8,9,10] sets = {1,5,7} y = [0,0,0,0,0,0,0,0,0,0] for i in range(10): if i in sets: y[i] = x[i] </code></pre> <p...
<p>You can do that in TensorFlow like this:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf x = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) sets = tf.constant([1, 5, 7]) y = tf.constant([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) y2 = tf.tensor_scatter_nd_update(y, tf.expand_dims(sets, 1), tf.gather(x,...
python|tensorflow
1
18,396
54,252,345
Print the number of activations in a Tensorflow model
<p>I am attempting to count the number of activations in a model, for example in a LeNet. How could I count the total number of activations? </p> <p>There is a way to count the number of trainable parameters, however, there does not seem to be an option for calculating individual activations. </p>
<p>The number of activations depends on the layers of the model, for example:</p> <ul> <li>For a fully connected layer (Dense), the number of activations is equal to the number neurons.</li> <li>For a convolutional layer, the number of activation is number of filters times the spatial dimensions of the output feature ...
tensorflow|machine-learning|python-3.6
1
18,397
73,566,688
Performance improvement: Finding the number of unique rows that end with a specific string (for each row in the dataframe)?
<p><strong>Problem:</strong> I have a pandas dataframe (&quot;df&quot; in the code below) with ~1M rows. One of the columns contains seemingly random strings.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>column_A</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>f24g5.eegajk.cae<...
<p>Supposing your dataset is:</p> <pre><code>df = pd.DataFrame({&quot;column_A&quot;: [&quot;f24g5.eegajk.cae&quot;, &quot;43fsf5&quot;, &quot;gefae.43fsf5&quot;, &quot;w4.t4w.43fsf5&quot;, &quot;gefae.43fsf5&quot;]}) </code></pre> <p>And your searched string is <code>43fsf5</code>:</p> <pre><code>s = &quot...
python|pandas|performance
2
18,398
71,159,722
AttributeError: 'Tensor' object has no attribute 'is_initialized'
<p>I got this error when I try to fit the model. I tried to use a single GPU version but it remains. If I upgrade to TensorFlow 2 it will be solved but I need to keep it that in this version of TensorFlow.</p> <p>This is the code for the model that I have used. This model consists of different layers.</p> <pre><code>de...
<p>This is likely an incompatibility between your version of TF and Keras. Daniel Möller got you on the right path but tf.keras is a TF2 thing, and you are using TF1, so your solution will be different.</p> <p>What you need to do is install a version of Keras that is compatible with TF 1.14. According to pypi, TF 1.14...
tensorflow|keras|deep-learning|gpu|tf.keras
2
18,399
52,106,307
Matplotlib: pcolormesh or pcolor from 3 columns pandas dataframe
<p>I have a file 'mydata.tmp' which contains 3 colums like this:</p> <pre><code>3.81107 0.624698 0.000331622 3.86505 0.624698 0.000131237 3.91903 0.624698 5.15136e-05 3.97301 0.624698 1.93627e-05 1.32802 0.874721 1.59245 1.382 0.874721 0 1.43598 0.874721 0 1.48996 0.874721 4.27933 </code></pre> <p>etc.</p> ...
<p>Try this. Tested and working on some data I have. Spacing is very important. set it according the gridding you want for the plot. The higher the spacing the smoother THE image is but longer calculation.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import scipy.interpolate import numpy as np im...
python|pandas|matplotlib
2