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
361,200
49,419,104
Adding two columns in Python
<p>I am trying to add two columns and create a new one. This new column should become the first column in the dataframe or the output csv file. </p> <pre><code>column_1 column_2 84 test 65 test </code></pre> <p>Output should be </p> <pre><code>column column_1 column_2 trial_84_test 84 test...
<p><strong>Create sample data</strong>:</p> <pre><code>df = pd.DataFrame({'column_1': [84, 65], 'column_2': ['test', 'test']}) </code></pre> <p><strong>Method 1</strong>: Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer">assign</a> to create n...
python|python-3.x|string|pandas|dataframe
4
361,201
49,349,669
TFRecords for embedded text data
<p>For a project at Uni, I'm working on the implementation of a Question Answering (bAbI dataset Task 5 at the moment, see <a href="https://research.fb.com/downloads/babi/" rel="nofollow noreferrer">https://research.fb.com/downloads/babi/</a>) system with Neural Nets in TensorFlow, and I want to use TFRecords for my In...
<p>The solution to my question can be found here: <a href="https://github.com/simonada/q-and-a-tensorflow/blob/master/src/Q%26A%20with%20TF-%20TFRecords%20and%20Eager%20Execution.ipynb" rel="nofollow noreferrer">https://github.com/simonada/q-and-a-tensorflow/blob/master/src/Q%26A%20with%20TF-%20TFRecords%20and%20Eager%...
tensorflow|tensorflow-datasets|tfrecord|nlp-question-answering
1
361,202
49,528,440
Tensorflow batch normalization: difference momentum and renorm_momentum
<p>I want to replicate a network build with the lasagne-library in tensor flow. I'm having some trouble with the batch normalization. This is the lasagne documentation about the used batch normalization: <a href="http://lasagne.readthedocs.io/en/latest/modules/layers/normalization.html?highlight=batchNorm" rel="nofoll...
<p>There is a big difference between <code>tf.nn.batch_normalization</code> and <code>tf.layers.batch_normalization</code>. See <a href="https://stackoverflow.com/questions/48949318/what-is-the-difference-between-the-tensorflow-batch-normalization-implementation/48953548#48953548">my answer here</a>. So you have made t...
tensorflow|neural-network|batch-normalization
3
361,203
49,595,599
Subprocessing Data Loading in pytroch into Google Colab
<p>I'm working on training a deep neural network using <code>pytorch</code> and I use <code>DataLoader</code> for preprocessing data and multi-processing purpose over dataset. I set <code>num_workers</code> attribute to positive number like 4 and my <code>batch_size</code> is 8. I train network on <code>Google Colab</c...
<p>I think you can follow this page:</p> <p><a href="https://colab.research.google.com/notebook#fileId=1jxUPzMsAkBboHMQtGyfv5M5c7hU8Ss2c&amp;scrollTo=EM7EnBoyK8nR" rel="nofollow noreferrer">https://colab.research.google.com/notebook#fileId=1jxUPzMsAkBboHMQtGyfv5M5c7hU8Ss2c&amp;scrollTo=EM7EnBoyK8nR</a></p> <p>It prov...
subprocess|python-multiprocessing|pytorch|google-colaboratory
0
361,204
49,769,302
How to groupby().transform() to a specific row value rather than to a function result like min()?
<p>I have a pandas dataframe <code>df1</code> that look like this:</p> <p><strong>Input:</strong></p> <pre><code>Shop Item Card Price Butcher A AMEX 1.5 Butcher A VISA 0.9 Baker B AMEX 2.5 Baker B VISA 3.5 Candlestick maker C ...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by filtered <code>DataFrame</code> - only <code>VISA</code> rows:</p> <pre><code>df1['Price'] = df1['Shop'].map(df1.loc[df1['Card'] == 'VISA'].set_index('Shop')['Price']...
python|pandas|slice|pandas-groupby
1
361,205
49,545,171
Pandas Pivot Table Filtering Based on Criteria
<p>So I have a pivot_table, basically a multilevel df, that I want to filter by a couple of parameters.</p> <p>colum dtypes:</p> <pre><code>Report object Owner object Description object TimeToRun object FacilityName object Base Report object </code></pre> <p>pd func:</p> <pre><co...
<p>Figured it out:</p> <pre><code>pv[pv[('Base Report')]&gt;2].dropna(axis=0,how='all') </code></pre> <p>you can also apply it in place or just return it...thanks though!</p> <p>Result below, note that the blanks are 0 values:</p> <pre><code>None Base Report Base Report FacilityName Santa Clara Santa Teresa T...
python|pandas|pandas-groupby
0
361,206
49,395,100
Change pandas Multi-index from Row to Column
<p>Currently have a dataframe generated by groupby() in the following shape:</p> <pre><code> # avg total unique year month 2014 1 241.0 64.668050 15585.00 237.0 2 358.0 65.197877 23340.84 347.0 3 347.0 60.336...
<pre><code>df.unstack(0).swaplevel(0, 1, 1).sort_index(1) </code></pre>
python|pandas|pandas-groupby
5
361,207
49,609,092
Unable to convert to tensor proto : TypeError for tf.contrib.util.make_tensor_proto while sending a input file
<p><strong>1)</strong> I have written a simple program using tensor flow to read a text file and wanted to deploy in a server using tensorflow serving. This is the program</p> <pre><code>tf.app.flags.DEFINE_integer('model_version', 2, 'version number of the model.') tf.app.flags.DEFINE_string('work_dir', '', 'Working ...
<p>look at this url <a href="http://werkzeug.pocoo.org/docs/0.14/datastructures/" rel="nofollow noreferrer">http://werkzeug.pocoo.org/docs/0.14/datastructures/</a></p> <p>if I take a look at "def inference", the local "data" variable will hold a reference to an object of type "werkzeug.datastructures.FileStorage"</p> ...
python|tensorflow|protocol-buffers|tensorflow-serving|werkzeug
0
361,208
49,462,954
Getting Error while performing Undersampling for Sklearn
<p>I am trying built an randomforest classifier for binary classification . My data is inbalanced hence I am performing undersampling.</p> <pre><code>train = data.drop(['Co_Name','Cust_ID','Phone','Shpr_ID','Resi_Cnt','Buz_Cnt','Nearby_Cnt','parseNumber','removeString','Qty','bins','Adj_Addr','Resi','Weight','Resi_...
<p>Can you share the dataframe? or a sample of that! </p> <p>This error can be a lot of things, for example:</p> <ul> <li><p>If you try:</p> <p>np.asarray( [ [1, 2], [2, 3, 4] ], dtype=np.float) </p></li> </ul> <p>You will get:</p> <pre><code>ValueError: setting an array element with ...
pandas|scikit-learn
0
361,209
49,414,219
Seaborn plots are faded
<p>I've used seaborn plots several times from an online course. Originally plotted graphs are so different as that of my computer's. Is this because of anything on code or in graphics?</p> <p>Plot on my computer: <img src="https://i.stack.imgur.com/kCKzs.png" alt="Plot on my computer."></p> <p>Original plot <img src=...
<p>Supposing the code being run is exactly the same, the reason would be that you are using a newer version of seaborn than the "online course". </p> <p>In order to have your graphics appear in the same manner as in the online tutorial you may call </p> <pre><code>import seaborn as sns sns.set() </code></pre>
python|pandas|seaborn
2
361,210
49,715,554
ValueError: No gradients provided for any variable in Tensorflow research model, dp_sgd
<p>I tried to run the dp_sgd model in <a href="https://github.com/tensorflow/models/tree/master/research/differential_privacy" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/research/differential_privacy</a>. I found out the following error message on my mac after I followed the steps in REA...
<p>I had similar problems which could be fixed by using models/research/slim/download_and_convert_data.py which created the correct tfrecords format as described here: <a href="https://github.com/tensorflow/models/issues/2605" rel="nofollow noreferrer">https://github.com/tensorflow/models/issues/2605</a></p>
tensorflow|python-3.5
0
361,211
49,456,831
Multiple sets of duplicate records from a pandas dataframe
<p>How to get all the existing duplicated sets of records(based on a column) from a dataframe?</p> <p>I got a dataframe as follows:</p> <pre><code>flight_id | from_location | to_location | schedule | 1 | Vancouver | Toronto | 3-Jan | 2 | Amsterdam | Tokyo | 15-Feb | ...
<p>Is this what you need ? <code>duplicated</code>+<code>groupby</code></p> <pre><code>(df.loc[df['flight_id'].duplicated(keep=False)].reset_index()).groupby('flight_id')['index'].apply(tuple) Out[510]: flight_id 4 (2, 5) 9 (3, 6) Name: index, dtype: object </code></pre> <p>Adding <code>tolist</code> at the en...
python|pandas|dataframe|group-by|pandas-groupby
9
361,212
49,702,026
How to create a data-set for deep learning?
<p>I want to train a CNN with Keras. I understand that <code>x_train</code> contains the data features and <code>y_train</code>the labels.</p> <p>I tried <code>test_train_split(x_train,test_size=0.2,train_size=0.8)</code>.</p> <p>How do I create <code>y_train</code>?</p>
<p>Here you go:</p> <pre><code>from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=None, shuffle=False) </code></pre> <p>If it is Timeseries shuffle=False. test_size is 40% of your data. So you are going to train 60%</p>
python|tensorflow|scikit-learn|deep-learning|keras
0
361,213
49,375,722
Tensorflow CPU-only:TypeError: unbound method _as_graph_element() must be called with Variable instance as first argument
<p>I use Tensorflow without GPU, only CPU. I installed it with <code>pip install tensorflow</code>. My Ubuntu17 has Python3, but when I <code>pip install tensorflow</code> , It uses Python2.</p> <p>My code look like this:</p> <pre><code>h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) </code></pre> <p>I get ...
<p>It is really difficult to understand the error without the context. Maybe your dimensions for either of x_image or W_conv1 are wrong. Maybe you forgot to initialize the weights? </p> <p>You are more likely to get answers if you add a bit of context (reproducible if possible) code.</p> <p>Edit: install pip3 and do ...
python|tensorflow
0
361,214
49,564,773
Use numpy to solve transport equation with wave-like initial condition
<p>I'm trying to write a python program to solve the first order 1-D wave equation (transport equation) using the explicit Euler method with 2nd order spatial discretization and periodic boundary conditions. </p> <p>I'm new to python and I wrote this program using numpy but I think I'm making a mistake somewhere becau...
<p>Your implementation is correct. The distortion comes from relatively large spatial step dx. At its current value of 0.2 it is comparable to the size of the wave, which makes the wave visibly polygonal on the graph. These these discretization errors accumulate over 500 steps. This is what I get from <code>plt.plot(X,...
python|numpy|numerical-methods|differential-equations|pde
3
361,215
49,356,798
when I set value in dataframe(pandas) there is error: 'Series' objects are mutable, thus they cannot be hashed
<p>I want to change value in pandas DataFrame by condition that data[Bare Nuclei'] != '?'</p> <pre><code>import pandas as pd import numpy as np column_names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single E...
<p>For last line add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>, because need change column of <code>DataFrame</code>:</p> <pre><code>temp.loc[index,'Bare Nuclei'] = mean </code></pre> <hr> <p>But in pandas is the...
python|pandas|jupyter
2
361,216
49,613,477
Create array using lists (consisting of lists) but without flattening inner lists - python
<p>I am trying to create an array using two lists, one of which has a list for each element. The problem is that in the first case I manage to do what I want, using <code>np.column_stack</code> but in the second case, although my initial lists look similar (in structure), my list of lists enters the array flattened (wh...
<p>Your problem here seems to be that the first B list is jagged, while your second is rectangular.</p> <p>Look at the difference in how Numpy converts the following two lists into Arrays (which, as @hpaulj points out, is exactly what happens when you pass them to <code>column_stack</code>:</p> <pre><code>In [1]: b1 ...
python|arrays|list|numpy
3
361,217
49,681,124
Vectorized implementation for `numpy.random.multivariate_normal`
<p>I am trying to use <code>numpy.random.multivariate_normal</code> to generate multiple samples where each sample is drawn from a multivariate Normal distribution with a different <code>mean</code> and <code>cov</code>. For example, if I would like to draw 2 samples, I tried</p> <pre><code>from numpy import random as...
<p>As @hpaulj suggested, you can generate samples from the standard multivariate normal distribution, and then use, say, <code>einsum</code> and/or broadcasting to transform the samples. The scaling is done by multiplying the standard sample points by the square root of the covariance matrix. In the following, I use ...
python|numpy
6
361,218
49,528,251
How to merge DataFrames using a key inside of a column of a dict type?
<p>Say I have two datasets like this:</p> <pre class="lang-py prettyprint-override"><code>In [2]: df_names = pd.DataFrame([ ...: ['alpha', {'key': 'a'}], ...: ['beta', {'key': 'b'}], ...: ['gamma', {'key': 'g'}], ...: ], columns=['name', 'data']) ...: df_names Out[2]: name d...
<p>You can create list by list comprehension, convert to <code>array</code>s and use as input to <code>left_on</code> and <code>right_on</code> parameter in <code>merge</code>:</p> <pre><code>a1 = np.array([x['key'] for x in df_names['data']]) a2 = np.array([x['english_letter'] for x in df_symbols['meta']]) r = pd.me...
python|pandas
3
361,219
49,410,188
How to use pandas to pull out the counties with the largest amount of water used in a given year?
<p>I am new to python and pandas and I am struggling to figure out how to pull out the 10 counties with the most water used for irrigation in 2014. </p> <pre><code>%matplotlib inline import csv import pandas as pd import numpy as np import matplotlib.pyplot as plt data = pd.read_csv('info.csv') #reads csv data['Year...
<p>This may work for you:</p> <pre><code>res = df[df['WUCode'] == 'IR'].groupby(['Year', 'CountyName'])['Annual'].sum()\ .reset_index()\ .sort_values('Annual', ascending=False)\ .head(10) # Year CountyName Annual # 0 2014 ...
python|python-3.x|pandas
1
361,220
49,598,651
Extract text in CSS class
<p>Trying to extract the data from a webpage to table. For e.g.</p> <pre><code>Block Number XXX Building Name YYY Street Name zzz Pin Code 123456789 </code></pre> <p>I am trying to get all details of the company in tabular form using this code...</p> <pre><code>html_doc='https://s3.amazonaws.com/todel162/test.html' ...
<p>All the items you need are inside the <code>&lt;div class="col-md-3 col-sm-3"&gt;</code> tags. And, all the items other than <em>General Information</em> follow a specific format: first <code>div</code> tag is the label and the second is the corresponding text. So, you can simply find them all and then print them al...
python|pandas|beautifulsoup
1
361,221
49,508,324
Python pandas: rearranging data from 'dummy' date columns to rows
<p>I am trying to run a ML model but my independent variables are differently structured than my dependent variable.</p> <p>The independent variables are structured like this:</p> <pre><code>id . month/year . var_a . var_b 0 . 01/2016 . 1 . 2 0 . 02/2016 . 2 . 1 1 . 01/2016 . 2 . 3 </code><...
<p>Maybe try <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a>:</p> <pre><code>df_pivot = pd.pivot_table(df,index=['id'],columns=['month/year']) </code></pre> <p>giving you </p> <pre><code> var_a var_b date ...
python|pandas|dataframe
0
361,222
49,356,166
ParserError: Error tokenizing data. C error: Expected
<p>When I run this command: </p> <pre><code>k1=pd.read_table("https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/chipotle.tsv") </code></pre> <p>I receive this error:</p> <p>Command on Pandas: attached.</p> <blockquote> <p>---------------------------------------------------------------------...
<p>try this to handle bad lines:</p> <pre><code>k1=pd.read_table( r'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/chipotle.tsv' ,error_bad_lines=False ) </code></pre>
python|pandas|dataframe
1
361,223
49,714,991
How to read file delimited by space and :
<p>My data is of the form :</p> <p>1 440:0.033906222568727 730:0.0424739279722748 1523:0.0773048148348295 1893:0.0433930684646909 </p> <p>1 271:0.0646290650479301 405:0.0653366028581683 584:0.0744087075001463 770:0.0717824200677465 </p> <p>1 577:0.0679078686536282 761:0.0506946081073312</p> <p>-1 440:0.043761456446...
<p>You probably have bad data in line 134</p> <p>try using <code>error_bad_lines=False</code> .</p> <pre><code>x = pd.read_csv('rcv1_train.binary', sep = "\s+|:", engine = 'python', error_bad_lines=False) </code></pre>
python|pandas|csv
1
361,224
49,759,661
Subtract -1 from Year if month = October, November, or December, Else year python
<p>I am trying to subtract (1) year from the column 'yy' in my dataframe IF the month in my 'month' column for that row == 'October', 'November', 'December'.</p> <p>I've tried a number of methods and am stuck at this point. The loop below makes the entire yy2 column yy-1, rather than just the rows that have October, N...
<p>using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html#pandas.Series.where" rel="nofollow noreferrer"><code>Series.where</code></a></p> <pre><code>month_selection = { 'October', 'November', 'December'} df['yy2'] = df['yy'].where(~df['month'].isin(month_selection ), df['yy'] - ...
python|pandas
2
361,225
49,591,323
Pandas: Edit part of dataframe, have it affect main dataframe
<p><strong>EDIT:</strong> A suggested possible duplicate (<a href="https://stackoverflow.com/questions/43196084/pandas-loc-alternatives-with-conditions">this question</a>) is not a duplicate. I'm asking if a slice of a dataframe can be edited and have that slice affect the original dataframe. The "duplicate" Q/A sugg...
<p><strong>Short answer</strong></p> <p>No. You don't want to play the game where you have to keep checking / guessing whether you are using a copy or a view of a dataframe.</p> <p><strong>Single update: the right way</strong></p> <p><code>.loc</code> accessor is the way to go. There is <em>nothing</em> unwieldy abo...
python|python-2.7|pandas|dataframe|filter
2
361,226
49,431,428
How to ignore sql column names via Python?
<p>I am trying to run a sql query via python but every time I remove the two last lines of code I get an error which I don't understand - The code below is which I am trying to run, and these are the lines of code which I erased:</p> <p>1 - <code>columnNames = [n.replace('b','') for n in list(results.columns.values)]...
<p>Change your SQL query to</p> <pre><code>select b.* from trade.trades a inner join trade.legs b where a.tradeid = b.tradeid AND a.productmaintypeid = 'InterestRateCapFloor' limit 10 </code></pre> <p>essentially you need to remove extra where. </p>
python|sql|pandas|pyodbc
2
361,227
28,106,796
DataFrame.to_dict() is not always invertible
<p>My main point is that:</p> <pre><code>assert_frame_equal(DataFrame.from_dict(df.to_dict()), df) </code></pre> <p>fails in some cases. I would love to provide with a reproducible example but (i) the data would be too big to post, and (ii) for this I would need to provide with a DataFrame serialized (which is precis...
<p>One reason this can fail is that <code>df.to_dict()</code> creates a Python dictionary. The keys of dictionaries are not guaranteed to be in any particular order. </p> <p>The DataFrame's column names are mapped to the dictionary keys and, as per <a href="https://stackoverflow.com/questions/14224172/equality-in-pand...
python|pandas|dictionary|dataframe
1
361,228
28,277,672
turning igraph adjacency matrix into numpy array
<p>By writing</p> <pre><code>import igraph g = igraph.Graph() g.add_vertices(6) g.add_edges([(0,1),(0,3),(0,4),(0,5),(1,2),(2,4),(2,5),(3,0),(3,2),(3,5),(4,5),(3,3)]) A=g.get_adjacency() </code></pre> <p>I get the adjacency matrix of graph g, as a Matrix object. I want to calculate its eigenvalues by using, for examp...
<p>According to <a href="http://igraph.org/python/doc/igraph.datatypes.Matrix-class.html">the documentation of iGraph's matrix class</a>, you could retrieve the data as a list of lists and then convert easily to a numpy ndarray:</p> <pre><code>A = g.get_adjacency() A = np.array(A.data) </code></pre>
python|numpy|igraph
10
361,229
28,014,735
np.nanmean of 500 large numpy matrices
<p>I am trying to get the average(ignoring nan values) of very large bumpy matrices. I know I can load them in without taking up too much memory, doing something like :</p> <pre><code>X=np.load('my_matrix_1.npy', mmap_mode='r') </code></pre> <p>And then I can read some lines from it. I was thinking of reading 1000 li...
<p>This code has several problems. The first is that chunk_to_mean = [] creates an array. However, you add the numpy arrays as elements to that array - so it becomes a list of numpy arrays, but np.nanmean does not take a list of arrays, but an np.array.</p> <p>The second one is that you either have a dictionary, ...
python|numpy|matrix
0
361,230
27,988,429
Not able to add a column from a pandas data frame to mysql in python
<p>I have connected to mysql from python and I can add a whole data frame to sql by using df.to_sql command. When I am adding/updating a single column from pd.DataFrame, not able udate/add.</p> <p>Here is the information about dataset, result,</p> <pre><code>In [221]: result.shape Out[221]: (226, 5) In [223]: result...
<p>You cannot add a column to your table with data in it all in one step. You must use at least two separate statements to perform the DDL first (<code>ALTER TABLE</code>) and the DML second (<code>UPDATE</code> or <code>INSERT ... ON DUPLICATE KEY UPDATE</code>).</p> <p>This means that to add a column with a <code>NO...
mysql|python-2.7|pandas
2
361,231
28,253,315
Find root (limit of integration) in numerical integration
<p>I'm trying to rewrite a Mathematica code to construct the equipopulated rings:</p> <pre><code>Nr = 5; (*radial modes*) DF0[JJ_] := Exp[-JJ]; (*distribution function of long action*) Jmax = 20; (* max action for numerical cuts*) CF = NIntegrate[DF0[II], {II, 0, Jmax}]; DF[JJ_] := DF0[JJ]/CF; bJ = Array[0, Nr + 1]...
<p>There are a number of problems with what you have written. Since I don't really understand what you are trying to accomplish this won't be an <em>answer</em> but I'll point out the problems that I see. You should probably spend some time with <a href="https://docs.python.org/2.7/tutorial/index.html" rel="nofollow">...
python|numpy|scipy|wolfram-mathematica|numerical-integration
0
361,232
27,961,552
Loading data file with too many commas in Python
<p>I am trying to collect some data from a .txt file into my python script. The problem is that when the data was collected, it could not collect data in one of the columns, which has given me more commas than normally. It looks like this:</p> <pre class="lang-none prettyprint-override"><code>0,0,,-2235 1,100,,-2209 2,...
<p>It really depends on what you're trying to do. I'd need to see a code example to see what you're trying to do really. You could just replace the double comma with a single one</p> <pre><code>inputstr = "0,0,,-2235 1,100,,-2209 2,200,,-2209" inputstr = inputstr.replace(",,",",") </code></pre> <p>Or, if you don't ...
python|numpy|data-files
1
361,233
28,063,817
Grouping a series in pandas
<p>I am new to pandas. I do not know much about it so please take it easy on me. I was trying to plot Area vs. freuency of Fire in areas A and B from 2009 to 2013 in a line graph. I figured out how to import a .csv file but I am having problem grouping the series and creating graph. My csv file looks like this: </p> <...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.DataFrame.groupby</code></a> to group data in pandas.</p> <p>The main idea behind <code>groupby</code> and similar functions is <a href="http://pandas.pydata.org/pandas-do...
python|pandas
2
361,234
27,912,090
Appending CSV files, matching unordered columns
<p>Problem: matching columns while appending CSV files</p> <p>I have 50 .csv files where each column is a word, each row is a time of day and each file holds all words for one day. They look like this:</p> <pre><code>Date Time Aword Bword Cword Dword Date1 t1 0 1 0 12 Date1 t2 0 6 3 0 Da...
<p>IIUC, you can simply use <code>pd.concat</code>, which will automatically align on columns:</p> <pre><code>&gt;&gt;&gt; csvs = glob.glob("*.csv") &gt;&gt;&gt; dfs = [pd.read_csv(csv) for csv in csvs] &gt;&gt;&gt; df_merged = pd.concat(dfs).fillna("") &gt;&gt;&gt; df_merged Aword Bword Cword Date Dword Eword Fw...
python|csv|pandas
1
361,235
28,249,800
TypeError when using substring function in Python 3
<p>I wrote a function to open a csv, find max of data in a column &amp; then substring to take only last 4 digits. It worked very well for almost 2 hours. But suddenly failing with the error <code>TypeError: unorderable types: float() &gt; str()</code> Relevant code is:</p> <pre><code>import pandas mycsvfile = 'filep...
<p>Empty cell in the column caused that issue. Filling it with appropriate value resolved the issue.</p>
python|csv|pandas|substring
0
361,236
73,255,351
how to combine data from different tables with different metadata into csv
<p>I have below tables in SQL. type is always in 2nd position for all my tables.</p> <pre><code>ID type Col1 Col2 Col3 1 table1 AAA BRYA 123 2 table1 BBB QAA 234 ID type Col1 Col4 1 table2 CCCC VVV 2 table2 BBC QQQ ID type Col1 Col3 Col4 ...
<p>You need to <code>UNION ALL</code> all three tables, when you want to join the tables vertically.</p> <p>Missing column you add simply a <code>NULL</code> at the missng position because for <code>UNION</code> you need always the same amount of cpolumns</p> <pre><code>SELECT ID, type, Col1, Col2 , Col3, NULL...
sql|pandas
0
361,237
73,243,183
Create a separate column in Pandas dataframe based on a condition
<p>I have a pandas dataframe with a column named as 'Finding Ageing in Days' with integers ranging from 0 till 100. I want to create a new column called &quot;Ageing&quot; that contains values based on 3 conditions: none (if Finding Ageing in Days=0), '=1 day' (if Finding Ageing in Days=1), '&gt;1 day' (if Finding Agei...
<p>Not scalable but easy solution:</p> <pre class="lang-py prettyprint-override"><code>df.loc[df['Finding Ageing in Days'].eq(0), &quot;Ageing&quot;] = None df.loc[df['Finding Ageing in Days'].eq(1), &quot;Ageing&quot;] = '=1 day' df.loc[df['Finding Ageing in Days'].gt(1), &quot;Ageing&quot;] = '&gt;1 day' </code></pre...
pandas
0
361,238
73,325,135
how do i compute the average value of every n row of an array?
<p>I have an array (<code>a</code>) and need to find the average of every 4th row.</p> <p>Can I use <code>np.mean</code> to do this? I have tried this but it doesn't work:</p> <pre class="lang-py prettyprint-override"><code>means = np.mean(a, step=4, axis=1) print(means) </code></pre>
<p>You can do that with</p> <pre><code>means = np.mean(a[::4], axis=1) </code></pre> <p>Where <code>a[::4]</code> selects every 4th row from a.</p>
python|numpy
1
361,239
73,448,406
Group python dataframe and display all correspond values for each unique key in a dictionary
<p>I have the following dataset</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">id</th> <th style="text-align: left;">date</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">7510</td> <td style="text-align: left;">15 Jun 2020</td> </tr> <tr> <td style="...
<p>Try this:</p> <pre><code>df.groupby('id')['date'].agg(list).to_dict() </code></pre> <p>Output:</p> <pre><code>{7510: ['15 Jun 2020', '16 Jun 2020'], 7512: ['15 Jun 2020', '07 Jul 2020'], 7520: ['15 Jun 2020', '16 Aug 2020']} </code></pre>
python|pandas|dataframe|group-by|unique-key
1
361,240
73,497,734
Don't overwrite data when I upload new using pandas dataframe and postgressql
<p>I want to start uploading data to my <code>PostgresSql</code> table using <code>pandas</code>. I do the following,</p> <pre><code>import psycopg2 import pandas as pd from sqlalchemy import create_engine user = 'aaa' passw= 'bbb' host = 'ccc' database = 'ddd' conn_string = f'postgresql://{user}:{passw}@{host}/{datab...
<p>Replace the argument <code>if_exists='replace'</code> to <code>if_exists='append'</code></p>
python|pandas|postgresql
2
361,241
73,221,111
find out if the indexes of a grouped data frame match a column of another dataframe?
<p>I have a grouped data frame named <code>df_grouped</code> where <code>AF</code> &amp; <code>Local</code> are the indexes. I would like to assert whether the indexes in <code>df_grouped</code> are equal to a column from another dataframe <code>df[A]</code>.</p> <p>This is an example of my code</p> <pre><code>import p...
<p>To use assert for pandas series you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.testing.assert_series_equal.html" rel="nofollow noreferrer"><code>assert_series_equal</code></a> which checks that left and right Series are equal.</p> <pre><code>from pandas import testing as tm tm.assert_series...
python|pandas|list|dataframe|indexing
1
361,242
73,275,019
Python Pandas: divide a Series by a Dataframe
<p>I have a Series and a Dataframe that share the same index:</p> <pre><code>s = pd.Series([300, 300]) df = pd.DataFrame({ 'A': [10,20], 'B': [20,30] }) </code></pre> <p>When I do <code>s.div(df)</code>, I see:</p> <pre><code> A B 0 1 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN </code></pre> <p>I e...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rdiv.html" rel="nofollow noreferrer"><code>DataFrame.rdiv</code></a> for divide from right side:</p> <pre><code>df1 = df.rdiv(s, axis=0) print (df1) A B 0 30.0 15.0 1 15.0 10.0 </code></pre>
python|pandas|dataframe|series
0
361,243
73,490,864
Finding string with multiple condition between two data frame in python
<p>I have two dataframe <code>df1</code> and <code>df2</code>. <code>df1</code> has 4 columns.</p> <pre><code>&gt;df1 Neighborhood Street Begin Street End Street 8th Ave 6th St Church St Mlk blvd ..... </code></pre> <pre><code>&gt;df2 Intersection Roadway Mlk blvd Hue St. </code></pre> <p>I want to ...
<p>Flatten the values in <code>df1</code> and <code>map</code> to lower case, then convert the values in <code>df2</code> to lower case and use <code>isin</code> + <code>any</code> to test for the match</p> <pre><code>vals = map(str.lower, df1.values.ravel()) df2['count'] = df2.applymap(str.lower).isin(vals).any(1).ast...
python|pandas|string|dataframe|data-mining
2
361,244
73,336,975
Save each row of df to separate xml
<p>I am trying to iterate through each row of an excel file, and save the output for each row to it's separate .xml file. However, when I run the code, instead of having each row in a separate .xml file, I have all rows being saved to each generated .xml files. Obviously, I'm having confusion about iteration, and would...
<p>Try to change <code>df</code> in loop to <code>data</code> then convert <code>data</code> to one row DataFrame since there is no <code>Series.to_xml()</code></p> <pre class="lang-py prettyprint-override"><code>for name, data in df.iterrows(): (data.to_frame().T.to_xml('D:/Test/' + name + '.xml' , attr_cols=[&quo...
python|pandas
1
361,245
73,278,181
How to use dataset with costume function?
<p>I want to call <code>DatasetDict</code> <code>map</code> function with parameters, and I dont know how to do it.</p> <p>I have function with the following API:</p> <pre><code>def tokenize_function(tokenizer, examples): s1 = examples[&quot;premise&quot;] s2 = examples[&quot;hypothesis&quot;] args = (s1, s...
<p>Additional parameters, like the tokenizer object, need to be passed by the <a href="https://huggingface.co/docs/datasets/v2.4.0/en/package_reference/main_classes#datasets.Dataset.map.fn_kwargs" rel="nofollow noreferrer">fn_kwargs</a> parameter of <a href="https://huggingface.co/docs/datasets/v2.4.0/en/package_refere...
huggingface-tokenizers|huggingface-datasets|huggingface
1
361,246
73,179,713
How to compare two dates that are datetime64[ns] and choose the newest
<p>I have a dataset and I want to compare to dates, both are datetime64[ns] if one is the newest I need to choose the other.</p> <p>Here is my code:</p> <pre><code>df_analisis_invertido['Fecha de la primera conversion']=df_analisis_invertido.apply(lambda x: x['Fecha de creacion'] if df_analisis_invertido['Fecha de la ...
<p>The approach you chose is almost fine, except the comparison of the series objects. If you replace them with x instead of the df_analisis_invertido, it should work.</p> <p>Here an example:</p> <pre><code>import pandas as pd data = {'t_first_conv': [5, 21, 233], 't_creation': [3, 23, 234], } df = pd.DataFr...
python|pandas|datetime
1
361,247
73,384,095
How to fix value error broadcasting in python loop?
<p>I am having trouble fixing my broadcasting error, the current error i am getting is <code>ValueError: operands could not be broadcast together with shapes (10,) (5,) </code></p> <p>preprocessing data:</p> <pre><code>data1 = pd.DataFrame({&quot;cust_id&quot;: ['x111'], #customer data &quot;state...
<p>See if below code snippet works for you, and make changes as per your convenience:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np state_list = ['A','B','C','D','E'] #possible states data1 = pd.DataFrame({&quot;cust_id&quot;: ['x111'], #customer data &...
python|arrays|pandas|numpy|loops
1
361,248
73,389,146
Pandas - Move data in one column to the same row in a different column
<p>I have a df which looks like the below, There are 2 quantity columns and I want to move the quantities in the &quot;QTY 2&quot; column to the &quot;QTY&quot; column</p> <p>Note: there are no instances where there are values in the same row for both columns (So for each row, QTY is either populated or else QTY 2 is p...
<p>Try this:</p> <pre><code>import numpy as np df['QTY'] = np.where(df['QTY'].isnull(), df['QTY 2'], df['QTY']) </code></pre>
pandas
1
361,249
73,375,258
How to use tf.gather with index vector that may contain out-of-range indices?
<p>I have an index vector that may contain negative entries. How can I use this in <code>tf.gather</code>? My approach</p> <pre><code>params = tf.constant(range(5)) idx = tf.constant([-1, 1, 2]) tf.where( condition = idx &gt;= 0, x = tf.gather(params, idx), y = -1 ) </code></pre> <p>throws</p> <blockquote> ...
<p>You can do it as follows</p> <pre><code>tf.where(idx &gt;= 0, tf.gather(params, tf.where(idx &gt;= 0, idx, 0)), -1) </code></pre> <p>Output</p> <pre><code>&lt;tf.Tensor: shape=(3,), dtype=int32, numpy=array([-1, 1, 2])&gt; </code></pre>
tensorflow|indexing
1
361,250
73,235,334
Python: Filtering a datastructure depended on columnvalue
<p>I have two pandas dataframe structured like so:</p> <pre><code>DF1: |'ID'|'Zone'| |:---------:| | 11 | 1 | | 12 | 2 | | 10 | 0 | DF2: |'ID'|'Time'| |:---------:| | 11 | 1 | | 11 | 2 | | 12 | 1 | | 12 | 2 | </code></pre> <p>And I want to add a new column to DF2 named zone, that contain the corr...
<pre><code>df1.merge(df2, how='right') or df2.merge(df1,how='left') </code></pre> <p>joining df2 with df1 using ID columns</p>
python|pandas
1
361,251
73,229,047
Pandas complicated duplicate removal with three comparisons to other rows
<p>so I am looking for a &quot;pandas-idiomatic&quot; way to remove duplicates from a pandas dataframe, but I couldn't find any examples or other SO threads where the comparisons to determine duplicates are the same I need to perform. To give a quick example, this is what is considered a duplicate in my case:</p> <pre>...
<p>You can sort your player names alphabetically, forcing the format to be:</p> <ul> <li><code>First_Name_Alphabetically, Second_Name, Defense, Time</code></li> </ul> <p>And then drop the duplicates.</p> <pre><code>mask = df['PLAYER1'].gt(df['PLAYER2']) df['GAMETYPE'] = df['GAMETYPE'].mask(mask, 'Defense') df[['PLAYER1...
python|pandas|numpy|duplicates|vectorization
0
361,252
73,463,682
How to flatten a Pandas data frame per groupby in Python?
<p>I have the following Pandas data frame:</p> <pre><code>id c1 c2 1 A B 1 C D 2 E F 2 G H 3 I J 3 K L </code></pre> <p>(IDs always occur in the same number respectively.) I want to &quot;flatten&quot; this DF by ID (concatenate rows to have a single row by ID) to get the outcome like this:</p> <pre...
<p>You can use a <code>pivot</code>:</p> <pre><code>(df.assign(col=df.groupby('id').cumcount()) .pivot(index='id', columns='col') .sort_index(level=1, axis=1, sort_remaining=False) #.pipe(lambda d: d.set_axis(range(d.shape[1]), axis=1)) ) </code></pre> <p>Output:</p> <pre><code> c1 c2 c1 c2 col 0 0 1 1...
python|pandas
1
361,253
73,314,040
Expanding within the same df
<p>I am looking for expanding my dataset based on any number e.g., (5)</p> <p>I have the following data set</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;X&quot;: [&quot;A&quot;, &quot;B&quot; ], &quot;Y&quot;: [2, 1 ]}) print (df) </code></pre> <p>and I want to expand it by 5 and the ending dataset shoul...
<p>Let us do</p> <pre><code>out = df.reindex(df.index.repeat(5)).reset_index(drop=True) Out[834]: X Y 0 A 2 1 A 2 2 A 2 3 A 2 4 A 2 5 B 1 6 B 1 7 B 1 8 B 1 9 B 1 </code></pre>
python|pandas|database|dataframe|expand
1
361,254
73,467,581
Python Pandas round decimal using reference rows
<p>I want to round the number in bid_2 and ask_2 depends of the bid_1 and ask_1. If bid_1 has 4 digit after the dot, make the bid_2 with 4 digits after the dot.</p> <p>My df is like this:</p> <pre><code> symbol bid_1 ask_1 bid_2 ask_2 1222 1INCHUSDT 0.7135 0.714 0.71300000 0...
<p>The easiest way to get number of decimals in a float you can use the following:</p> <pre><code>a = 123.5666 decimal_count = len(str(a).split(&quot;.&quot;)[1]) </code></pre> <p>You can use the same in your dataframe like so:</p> <pre><code>df['bid_2'] = df.apply( lambda row: round(row['bid_2'], len(str(row['bid_1...
python|pandas
2
361,255
73,390,248
How to create a conditionnal column that carry the URL of a dataframe using Pandas
<p>I'm trying to make a conditionnal column using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">pandas.DataFrame.apply</a>.</p> <p>The goal is : when I click on the button <code>Click here</code>, I should get a csv with only the row matching the community ...
<p>here is one way to do it</p> <pre><code>df['URL'] = df.apply(lambda x: f&quot;&lt;a href=\&quot;https://{x['Community_name']}.com/\&quot;&gt;{x['Community_name']}&lt;/a&gt;&quot;, axis=1) </code></pre> <p>OR, without the use of apply</p> <pre><code>df['URL'] = &quot;&lt;a href=\&quot;https://&quot; + df['Community...
python|pandas|io|base64
1
361,256
73,387,493
Python/Pandas - How to split data based on the indicated position (row by row)
<p>I have a dataframe with a 'name' column which displays a name created according to some rules. These rules are in the following columns, where I have the 'separator' (if it's an underscore or any other) and the positions where each information is. For example in the first row I know that the name has an underscore s...
<p>Check Below code using <strong>itemgetter</strong></p> <pre><code>from operator import itemgetter results.apply(lambda x: ','.join( itemgetter(*[x.SKU, x.CAMPAIGN, x.GOAL])(x['name'].split(x['separator'])) ), axis = 1).str.split(',', expand=True) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/a...
python|pandas|split
2
361,257
73,344,922
How to do a linear regression with variables from a dataframe [Python]
<p>I have two variables A and B in a dataframe. When i try this:</p> <pre class="lang-py prettyprint-override"><code>x=df.['A'] y=df.['B'] M = LinearRegression() M.fit(A,B) </code></pre> <p>I get the following error</p> <pre><code>Expected 2D array, got 1D array instead: array=[86. 0. 86. ... 0. 0. 0.]. Reshape yo...
<p>You can try to change <code>x</code> to DataFrame rather than Series.</p> <pre class="lang-py prettyprint-override"><code>x = df[['A']] y = df['B'] </code></pre>
python|pandas|linear-regression
2
361,258
73,493,331
mp.Process and queue slower than serial counterpart
<p>I have a python code and I want to make it run faster.</p> <p>The code, at multiple locations, performs work using two 3 dimensional numpy arrays, using the np.einsum() function. The inputs to the np.einsum() are these two arrays. These operations have an embarrassingly-parallel logic: the can be parallelized becaus...
<p>You can rather easily do this with <a href="https://docs.dask.org/en/stable/array.html" rel="nofollow noreferrer">dask arrays</a>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np N_rs = 300 # reduced for demonstration - and my battery life's - sake ;) N_thetas = 70 Lobatto_matr = np.random.r...
python|arrays|numpy|optimization|parallel-processing
1
361,259
73,336,391
One hot encoding with duplicate columns
<p>I have a dataset with City and Province Name, but here in Belgium we have Provice Limburg and also City Limburg. So when I try to train the model, I get this error:</p> <pre><code>[LightGBM] [Fatal] Feature (Limbourg) appears more than one time. </code></pre> <p>I do hot encoding like this:</p> <pre><code>import pan...
<p>Given you are OHE the features and using them as input for LightGBM, it won't hurt to rename the conflicting values, or slightly modify them to avoid any issues. Therefore I would suggest to just proceed with:</p> <pre><code>import pandas as pd #One Hot Encoding of the Categorical features one_hot_city_name=pd.get...
python|pandas|lightgbm
1
361,260
73,349,437
Python dataframe drop negative values in multiple columns
<p>I want drop negative values in some columns of the dataframe. My code:</p> <pre><code>ad = pd.DataFrame({'A':[-1,2,3,4],'B':[5,-6,7,8],'C':[1,-2,0,1]}) A B C 0 -1 5 1 1 2 -6 -2 2 3 7 0 3 4 8 -1 </code></pre> <p>I want to drop negative value rows in A and B columns</p> <p>Expected resul...
<p>With <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.all.html" rel="nofollow noreferrer">all</a> you can check whether all elements in a row or column are true. You can use this in a filter on a subset of columns:</p> <pre><code>import pandas as pd ad = pd.DataFrame({'A':[-1,2,3,4],'B':[5,-6,7...
python|pandas|dataframe|numpy
3
361,261
73,450,660
Properly splitting YOLO3 model output name to obtain 3 variables and get the best model
<p>I have a lot of files, which are a result of machine learning with YOLO model, generated by Tensorflow.</p> <p>Each filename is named:</p> <pre><code>detection_model-ex-013--loss-0016.228.h5 </code></pre> <p>With the only differences, being:</p> <p>013 - epoch/generationNumber</p> <p>0016 - loss (kind of accuracy, b...
<p>You could use <a href="https://docs.python.org/3/library/re.html#re.match" rel="nofollow noreferrer">re.match</a> to return a <code>match object</code> from each of the files you already obtained with <code>glob.glob</code>. The use of <code>re.match</code> with named groups will result in a dictionary with 3 separa...
python|regex|tensorflow|machine-learning|split
0
361,262
73,376,677
Write pandas dataframe column by column to existing excel template skipping excel sheet columns that have formulas in it
<p>I am super stuck since a day or two and give up on this. I am new to using python with excel.</p> <p><strong>Here is my scenario</strong>; I am planning to write a pandas dataframe to an existing excel sheet. The sheet has 50 columns in it. 2 of the columns are derived (formula columns developed from other columns t...
<p>In short, change to:</p> <pre><code>ws.Cells(1+len(col_vals),xl_col_idx)).Value = [ [v] for v in col_vals.values] </code></pre> <p>The issue is that the <code>Range.Value</code> property can take a 1-D vector of values or a 2-D array. If <code>Value</code> receives a 1-D vector, Excel assumes it is a single row (NOT...
python|excel|pandas|pywin32|win32com
0
361,263
73,209,901
How to group by a column but use apply on another column
<p>I have to run a function on some data grouped according to their <strong>Category</strong> column. But, I have to run the function called <strong>runWordAug</strong> using apply on the other column called <strong>Query</strong>. How do I achieve this? Code I have as of now:</p> <pre><code>import nlpaug.augmenter.wor...
<p>You can try</p> <pre class="lang-py prettyprint-override"><code>df2.groupby('Category')['Query'].apply(runWordAug) </code></pre>
python|pandas|dataframe
0
361,264
73,230,505
Extract sub-arrays of consecutive numbers that meet condition
<p>I have the following input array:</p> <pre><code>a = np.array([np.nan, 10, 5, 7, np.nan, np.nan, 1, 2, 3, np.nan]) </code></pre> <p>I want to extract subarrays of consecutive numbers splitting them up whenever there is a <code>nan</code> value.</p> <pre><code>res = [[10, 5, 7], [1, 2, 3]] </code></pre>
<p>A one-line solution that requires no further dependencies would be</p> <pre class="lang-py prettyprint-override"><code>res = [[int(a_elem) for a_elem in list(a[ind])] for ind in np.ma.clump_unmasked(np.ma.masked_invalid(a))] </code></pre> <p>yielding</p> <pre class="lang-py prettyprint-override"><code>res &gt;[[10, ...
python|numpy
0
361,265
73,507,693
I'm trying to copy information from 1 dataframe to another where df_1['date'] = df_2['date']. i'm stuck
<p>I have 2 pandas dataframes.</p> <p>Both df(s) have a date column.</p> <p>I want to copy a column <code>['Volume']</code> from <code>df_2</code> to <code>df_1</code> where the <code>df_1['date'] = df_2['date']</code>.</p> <p>I can loop through the 1st df, but after that, I'm lost...</p>
<p>Use <code>df1.merge(df2[columns], how='inner', on='Date')</code>. For Example:</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({'Date': ['Monday', 'Tuesday'], 'Random': [1, 2]}) df2 = pd.DataFrame({'Date': ['Monday', 'Wednesday'], 'Volume': [3, 4]}) print(df1.merge(df2[['Date', 'Volume']], ho...
python|pandas
1
361,266
73,219,621
pandas.DataFrame: How to merge rows with a common column value in the same pandas.DataFrame
<p>I have a pandas.DataFrame that looks like that:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>projectid</th> <th>question</th> <th>answer</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1</td> <td>'q1'</td> <td>'str1'</td> </tr> <tr> <td>1</td> <td>1</td> <td>'q2'</td> <...
<p>You can use <code>cumcount</code> before pivoting to get your suffixes:</p> <pre><code>df['idx'] = df.groupby('projectid').cumcount() + 1 df = df.pivot(index='projectid',columns='idx')[['question','answer']] df.columns = [''.join(map(str, col)) for col in df.columns] print(df) </code></pre> <p>Output::</p> <pre><cod...
python|pandas|dataframe
0
361,267
73,198,391
import import tensorflow_docs error on Colab
<p>I've been using colab for deep learning for a over a month and all of a sudden <code>import tensorflow_docs as tfdocs</code> stopped working. Is anyone encountering the same issues???</p> <p>I'm running tf.<strong>version</strong> 2.8.2</p> <pre><code>&gt; !pip install git+https://github.com/tensorflow/docs &gt; &g...
<p>You can try this:</p> <pre><code>!pip install -q git+https://github.com/MJAHMADEE/docs import tensorflow_docs as tfdocs import tensorflow_docs.modeling import tensorflow_docs.plots </code></pre>
tensorflow|callback|google-colaboratory|tensorboard
1
361,268
73,414,845
Is there a function in models in tensorflow.keras similar to partial_fit in sklearn's MLPClassifier?
<p>I'm trying to create a keystroke biometrics program and am using the benchmark keystroke biometric dataset (<a href="https://www.cs.cmu.edu/%7Ekeystroke/DSL-StrongPasswordData.csv" rel="nofollow noreferrer">https://www.cs.cmu.edu/~keystroke/DSL-StrongPasswordData.csv</a>). My goal is to first train the model on the ...
<p>One pragmatic approach is just to make your Y data (and your final dense layer) much wider than your current number of users. If you start with 51 users have, say 100 columns in your Y data, of which the last 49 are always zero. Your final dense layer also has 100 units.</p> <p>If you train your model on that your m...
python|tensorflow|machine-learning|keras|scikit-learn
0
361,269
73,408,868
Groupby and Count the % of occurrence
<p>the following is my data, I want to count % occurrence of Flag=1 and Value.</p> <pre><code>df=pd.DataFrame({'ID':['A','B','C','D'], 'Group':['group1','group1','group2','group2'], 'Flag_1':[1,0,0,1], 'Flag_2':[1,1,0,1], 'Value':[30,40,60,70] ...
<p>Firsly, define 2 functions:</p> <pre class="lang-py prettyprint-override"><code>def get_flag_percentages(df): return df[['Flag_1', 'Flag_2']].agg(np.mean).to_frame().T def get_val_percentages(df): value_sum = df['Value'].sum() return (df[['Flag_1', 'Flag_2']] .agg(lambda col: df.loc[col.eq(1...
pandas
1
361,270
73,211,546
How do I replicate this R vector function with Rep in Python
<p>Here is my code:</p> <pre><code> df$two &lt;- c(0, rep(1:(nrow(df)-1)%/%120)) </code></pre> <p>Thanks!</p>
<p>This should be similar to what you've provided in R:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;two&quot;] = pd.Series([0] * ((len(df.index) - 1) // 120)) </code></pre> <p>WHERE:</p> <ul> <li>df is a Pandas dataframe with a column named &quot;two&quot;</li> <li>An equivalent structure to <code>c()<...
python|pandas|numpy
1
361,271
73,229,609
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list). eventhough the data is numpy
<p>I am trying to use BERT model which gives attention, input ids, token type ids. But when I tried to convert my dataset to TF Dataset, it throws the error below:</p> <pre><code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list). </code></pre> <p>I tried looking at <a href="https://...
<p>I have solved the same using the way I store the input_ids, attention_mask and token type ids. I tried using np.zeros((df.shape[0], 256)) and then added the data</p>
python|numpy|tensorflow
0
361,272
73,233,123
Python Read In Google Spreadsheet Using Pandas
<p>I have file in Google sheets I want to read it into a Pandas Dataframe. But gives me an error i don't know what's it. this is the code :</p> <pre><code>import pandas as pd sheet_id = &quot;1HUbEhsYnLxJP1IisFcSKtHTYlFj_hHe5v21qL9CVyak&quot; df = pd.read_csv(f&quot;https://docs.google.com/spreadsheets/d/{sheet_id}/exp...
<p>I found the answer, the problem it's just with access permissions of the file.</p> <p><a href="https://i.stack.imgur.com/5h0OH.png" rel="nofollow noreferrer">enter image description here</a></p> <p><a href="https://i.stack.imgur.com/MPAU3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MPAU3.png" ...
python|python-3.x|pandas|dataframe
1
361,273
73,228,035
Merge 3 dataframes together
<p>I have 2 similar dataframes that I would like to merge to another larger one. I have 2 ways to assign costs to part numbers (B1_df and B2_df) and would like to assign costs to all the item numbers.</p> <p>B1_df and B2_df have the same column headers</p> <p>A_df has the item numbers, and B1_df and B2_df are the ones ...
<p>Looks like you need <code>pd.concat()</code> <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.concat.html</a></p> <pre class="lang-py prettyprint-override"><code>result_df = pd.concat([B1_df,B2_df], ignore_index=Tr...
python|pandas
0
361,274
73,468,760
different dimension numpy array broadcasting issue with '+=' operator
<p>I'm new to numpy, and I have an interesting observation on the broadcasting. When I'm adding a 3x5 array directly to a 3x1 array, and update the original 3x1 array with the result, there is no broadcasting issue.</p> <pre><code>import numpy as np total = np.random.uniform(-1,1, size=(3))[:,np.newaxis] print(f'init =...
<p>according to <code>add function</code> overridden in numpy array,</p> <pre><code>def add(x1, x2, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ &quot;&quot;&quot; add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, e...
numpy|array-broadcasting
1
361,275
73,361,416
Finding frequency of items in cell of column pandas
<p>I have DataFrame with almost 500 rows and 3 columns.</p> <p>One of the columns has a string of dates and each cell has a unique date, but some cell have a common date and some cells are seem empty.</p> <p>I'm trying to find the frequency of each day in a cell</p> <pre><code>df|Number_of_dates | Date --|------...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.siz...
python|pandas|dataframe|count|frequency
2
361,276
73,272,021
Replace a string into numeric value
<p>I need help with the codes below:</p> <p>First I do this:</p> <pre><code>medias = [] for col in dataset_1: medias.append(dataset_1[col][~(dataset_1[col] == '?')].median()) </code></pre> <p>After i tried to replace &quot;?&quot; for the median:</p> <pre><code>for col in dataset_1: for media in medias: ...
<p>In the second code snippet you're modifying the <code>dataset_1</code>'s column with <code>Pandas.DataFrame.replace</code> method which by default returns the modified DataFrame instead of changing it in place. In order to fix your problem you either have to reassign the DataFrame column with the modified one or set...
python|pandas|dataframe|data-science
0
361,277
73,426,259
Looking for values from the list among column values
<p>So the problem I am facing that I am looking for a solution to do something like this: (general example)</p> <pre><code>def categotizer(value): toys = ['ball', 'bear', 'lego'] food = ['pizza', 'ice-cream', 'cake'] if value in toys: return 'toys' if value in food: return 'food' else: ...
<p>Because in <code>if value in toys:</code> for example, value here is &quot;red ball from...&quot; and it's not in the toys list. Same can be said for food. Instead, you might want to check the elements in toys/food against the value. Perhaps this would answer your concern?</p> <pre><code>import pandas as pd def ca...
python|pandas|dataframe|function|categories
1
361,278
73,454,858
How to use map() on a DataLoader dataset?
<p>I'm trying to train a pretrained visual transformer (ViT) on a new dataset. The dataset is made up of jpg images sorted into folders (train, val, test) and has 4 calsses. I want to use map() on the dataset for preprocessing. I added '<strong>getitem</strong>' and '<strong>len</strong>' so that it'll be a map-style...
<p>When you instantiate the <code>DataLoader</code> for train, test and val dataset, you can point the flag <code>collate_fn=preprocess_images</code> function. You will have to update the function to match to your requirement.</p> <p><em>e.g.,</em></p> <pre><code>DataLoader(train_data, collate_fn=preprocess_images, , b...
python|deep-learning|pytorch|computer-vision|transformer-model
0
361,279
73,429,702
pandas dataframe from several levels nested dictionary
<p>I am trying to convert a nested dictionary with more than one level of nesting to a Pandas data frame, so I followed <a href="https://stackoverflow.com/questions/31460234/python-pandas-convert-nested-dictionary-to-dataframe">this solution</a>:</p> <pre><code>new_df = pd.DataFrame.from_dict(nested_dict, orient=&quot;...
<p>This code gave me the result I needed:</p> <pre><code>new_df = pd.Dataframe.from_dict(nested_dict, orient=&quot;index&quot;) new_df[&quot;zipcode&quot;] = new_df.index new_df = new_df.melt([&quot;zipcode&quot;]).sort_values(&quot;zipcode&quot;) new_df = pd.json_normalize(new_df.to_dict(&quot;records&quot;)) new_df =...
python|pandas|dataframe
0
361,280
73,347,010
Why do I get an error when trying to read a file in geopanda's included datasets?
<p>I've just installed Anaconda in my new laptop, and created an environment with geopandas installed in it. I've tried to upload the world map that comes with geopandas through the following code:</p> <pre><code>import geopandas as gpd world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) </code></pre> <...
<p>This is caused by incompatibility of shapely 1.7 and numpy 1.23. Either update shapely to 1.8 or downgrade numpy, otherwise it won't work.</p>
python|conda|geopandas|shapely
4
361,281
73,374,435
How to group in pandas to create stacked barchart
<p>Is there a way to achieve this in Pandas?</p> <p>Sample of my dataset:</p> <pre><code>date_time version_A spend_A version_B spend_B 2022-07-30 User1 39734.582 User1 15354.253 2022-07-30 User2 11720.6742 User2 3486.8551 2022-07-30 User3 49015.5171 User3 18384.4266 2022-07-30 User4 23715.67...
<p>Ok, so far many attempts and some research I managed to find a solution for the problem I'm dealing with.</p> <p><a href="https://stackoverflow.com/questions/63014596/combining-two-stacked-bar-plots-for-a-grouped-stacked-bar-plot">Combining two stacked bar plots for a grouped stacked bar plot</a></p> <p>What I did w...
python|pandas|charts|group-by|bar-chart
0
361,282
73,464,987
How to find game series names from list of titles
<p>I'm working on a bit of data analysis for a project for school, but I'm having trouble figuring out how to search for help on the specific task.</p> <p>I have a dataset of <a href="https://www.kaggle.com/datasets/gregorut/videogamesales" rel="nofollow noreferrer">video game sales</a> consisting of title, genre, publ...
<p>Hey I think this example might help you out. The key things to consider is cleaning as much as possible your data, and then creating key words relating them to a Franchise to later use for labeling the data.</p> <pre><code>import pandas as pd import re initial_data = { &quot;title&quot;: [ &quot;::gta5&...
python|pandas
1
361,283
73,474,642
API pagination loop
<p>I have successfully created a loop to paginate an API I am working with. My challenge is on concatenating the dataframes once I am done with the loop so that I have one solid dataframe. Any help will go a long way.</p> <pre><code>import requests import json import pandas as pd from pandas import json_normalize url ...
<p>If I'm reading this correctly you are currently just printing them out? You could do something like this if I am understanding what you want correctly. Then print it out as one big df at the end.</p> <blockquote> <pre><code>page = 1 data_nested = [] loop = [] while data_nested is not None: data = [('vendor_id',...
python|pandas|loops|while-loop|pagination
1
361,284
73,292,690
How to assign a slice to a slice in a Pandas dataframe?
<p>Having:</p> <pre><code>np.random.seed(42) df_one = pd.DataFrame(np.random.rand(4,3), columns=['colA', 'colB', 'colC']) </code></pre> <p>And:</p> <pre><code>df_two = pd.DataFrame(np.ones([2,3]), columns=['colA', 'colB', 'colC']) </code></pre> <p>When I try to assign, like this:</p> <pre><code>df_one.loc[2:4, 'colB'] ...
<p>This can be done adding a to_list() at the end:</p> <pre><code>df_one.loc[2:4, 'colB'] = df_two.loc[:, 'colB'].to_list() </code></pre> <p>Or:</p> <pre><code>df_one.loc[2:4, 'colB'] = df_two.loc[:, 'colB'].values </code></pre>
python|pandas|slice
0
361,285
73,210,537
Remove rows before first occurrence of a row with data in all columns
<p>I have a pandas Dataframe as follows:</p> <p>col index -&gt; 0 1 2 3</p> <p>row0 stmt</p> <p>row1 stmt1</p> <p>row2 Name Place Animal Thing</p> <p>row3 abc pqr mdfh jsdfhq</p> <p>row2 is the row with actual column names and what follows is data. I want to remove all the rows before that. Currently, I'm using df.drop...
<p>Use this code: It is very easy</p> <pre class="lang-py prettyprint-override"><code>i = df['col3'].first_valid_index() df = df[i:] </code></pre>
python|pandas|dataframe
0
361,286
73,502,770
How to store all file names from the directory and save it in excel?
<p>Good evening Everyone.</p> <p>i wrote a small piece of code (Got help from this stackoverflow Search)</p> <p>I could able to get the list of files from the directory.</p> <p>I tried to store in Excel Spreadsheet. I could able to store only two lines of the file in excel, but not all the file names.</p> <p>Please che...
<pre><code>import os import pandas as pd #path of the file you want to enemurate path = &quot;//home//halovivek//Downloads//&quot; directory =[] filename=[] for (root,dirs, file) in os.walk(path): for f in file: directory.append(root) filename.append(f) print(f) #column name of the sheet d...
python|excel|pandas|directory|export-to-excel
0
361,287
73,192,372
Change a specific value in a particular position in dataframe and represent in graph
<p>My dataset files consists of data as follows</p> <pre><code>id speaker_header word_not word_very polarity subjectivity 1 guildenstern22_1_1 0 0 0.375 0.675 2 guildenstern22_2_1 0 0 0 0 3 guildenstern22_3_1 0 0 0 0 4 ...
<p>I think the mentioned <em>Error</em> is a warning message isn't it?</p> <p>However, you can fix it by changing all occurences where you update a value by <code>df[]</code> notation by <code>df.loc[RowValue, ColumnValue]</code> or <code>df.iloc[RowIndex, ColumnIndex]</code> e.g. here</p> <pre><code>df.polarity[i-1] =...
pandas|dataframe|matplotlib|multiplication
0
361,288
73,387,150
Find Missing Values by Index Without NaNs
<p>I have a pandas Dataframe with 3 columns: <code>pd.DataFrame(data, columns=['Date', 'Name', 'Payment'])</code> where I have made Date the index. If I have a list of all <code>Name</code> values that are possible, how can I find indexes (in this case Dates) that are missing names from the possible universe and list ...
<p>I think I get what you're trying to achieve. I've made a longer example which I think is better for comprehensive testing. I have not set the date as the index, as I will need to use it (I don't know if you have to do this for other reasons, but you can <code>reset_index</code> for this):</p> <pre><code> Dat...
python|pandas
0
361,289
73,427,444
How to create a DataGenerator for Numpy Data
<p>as we know, in Keras it is possible to use many functions like ImageDataGenerator or dataset_from_image to generate a train/test data from directories. In my situation, the data is organized in the following way:</p> <pre><code>/hog_features /train_data /class_a a1.npy ...
<p>a non-elegant solution is to recreate the dataset with the files in jpg format. Code below can convert a jpg image to .npy (to_jpg=False) or npy to jpg (to_jpg=True). Then use ImageDataGenerator.flow_from_directory as your generator. I will assume your dataset is in C:\hog_features. I set to name for the directory t...
python|numpy|tensorflow|keras|imagedatagenerator
0
361,290
73,321,370
PANDAS : converting int64 to string results in object dtype
<p>I have a dataframe:</p> <pre><code>df1 = pd.DataFrame({'GL': [2311000200.0, 2312000600.0, 2330800100.0]}) </code></pre> <p>df1.dtypes is float so first I convert it to int64 to removes .0 digitals df1.GL = df1.GL.astype('int64')</p> <p>Then I try to convert it to str but instead I receive object dtype.</p> <p><a hre...
<p>The type <code>object</code> is actually string in pandas dataframe.</p> <p>If you would like to retain the data as string, use <code>df.to_excel()</code> instead of <code>df.to_csv</code>. This is because when opening the CSV file, Excel will automatically convert the number data to numbers.</p> <pre><code>df1 = pd...
python|pandas
1
361,291
73,350,336
GroupBy Remove leading rows and last rows based on a column value
<p>I have a dataframe <code>df</code> :-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Date</th> <th>Event</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>30-10-2013</td> <td>Success</td> </tr> <tr> <td>1</td> <td>08-11-2013</td> <td>Success</td> </tr> <tr> <td>1</td> <td>06-1...
<p>Provided the dataframe is already sorted, this should work:</p> <pre><code>df[&quot;n&quot;] = df.groupby(&quot;ID&quot;)[&quot;Event&quot;].transform(lambda x: (x == &quot;Success&quot;).shift(1, fill_value=0).cumsum()) df[&quot;keep&quot;] = df.groupby([&quot;ID&quot;, &quot;n&quot;])[&quot;Event&quot;].transform(...
python-3.x|pandas|dataframe|group-by
2
361,292
73,499,083
sklearn cross_val_score() returning same MSE for different degree polynomials
<p>The title is clear, below a code to fully reproduce my example:</p> <pre><code>import numpy as np import pandas as pd from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_score, train_test_split np.random.seed(1) url = ...
<p>With every cross validation, the model you provided will be fitted with the training data. In your first code, even though you fitted the model with a polynomial <code>model = lm.fit(X_train_poly, y_train)</code> , with every iteration inside <code>cross_val_score</code> you will refit a linear model with <code>X_te...
python|pandas|machine-learning|scikit-learn
1
361,293
73,340,968
Sorting correlation matrix
<p>I want to convert the correlation matrix to the &quot;pandas&quot; table, sorted from the largest value to the smallest, as in the image. How can I do it?</p> <pre><code>df = pd.DataFrame(np.random.randint(0,15,size=(20, 6)), columns=[&quot;Ply_1&quot;,&quot;Ply_2&quot;,&quot;Ply_3&quot;,&quot;Ply_4&quot;,&quot;Ply_...
<pre class="lang-py prettyprint-override"><code>pd.concat([cor[col_name].sort_values(ascending=False) .rename_axis(col_name.replace('Ply', 'index')) .reset_index() for col_name in cor], axis=1) </code></pre> <h3>Explanation:</h3> <ul> <li><p><code>p...
python|pandas|sorting|correlation
3
361,294
35,203,186
NumPy docstring for function type and None type
<p>I am writing the following function:</p> <pre><code>def parse_zip_file(path, handler): """ Parse all files contained in a zip file (specified by the path parameter). Parameters ---------- path : str The path to the zip file. handler: function When looping through all the fil...
<p>I had this same question. This <a href="https://stackoverflow.com/questions/27784179/docstrings-when-nothing-is-returned">question</a> is really similar, and the accepted answer says to include it, but doesn't really make a claim about why or why not to do it, nor does it answer your particular question about where ...
python|numpy|pycharm|docstring
2
361,295
35,185,046
Using StatsModels to plot quantile regression for 2nd order polynomial
<p>I am following the StatsModels example <a href="http://statsmodels.sourceforge.net/devel/examples/notebooks/generated/quantile_regression.html" rel="noreferrer">here</a> to plot quantile regression lines. With only slight modification for my data, the example works great, producing this plot (note that I have modifi...
<p>After a day of looking into this, came up with a solution, so posting my own answer. Much credit to Josef Perktold at StatsModels for assistance.</p> <p>Here is the relevant code and plot:</p> <pre><code>d = {'temp': x, 'dens': y} df = pd.DataFrame(data=d) x1 = pd.DataFrame({'temp': np.linspace(df.temp.min(), df....
python|pandas|regression|statsmodels
8
361,296
34,893,510
Pandas: LEFT OUTER JOIN where (ON) 2 Conditions that Match
<p>I have 2 Dataframes that I'd like to combine in Pandas where two 2 conditions are met, but I'm not successfully getting there. Thanks in advance for assistance!</p> <pre><code>df1 A B C 0 1 2 3 1 4 5 6 2 7 8 9 df2 A B F 0 1 2 cat 1 4 5 dog 2 7 8 m...
<p>Maybe you can try add to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> multiple join keys <code>on=['A','B']</code>:</p> <pre><code>print pd.merge(df1, df2, on=['A','B'], how='left') A B C F 0 1 2 3 cat 1 4 5 6 dog 2 7...
python-2.7|pandas
1
361,297
34,909,446
Matplotlib histogram - plotting values greater than a given value
<p>I've the following histogram: <a href="https://i.stack.imgur.com/R5NUO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R5NUO.png" alt="enter image description here"></a></p> <p>It was produced with this code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as num treshold_file='fal...
<p>I'd use a manual <code>bar</code> plot after constructing the necessary data:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt # dummy data data2 = np.random.randint(low=0, high=450, size=200) bins = [100,110,120,130,140,150,160,180,200,250,300,350,400] bincent...
python|numpy|matplotlib
2
361,298
34,956,145
How to insert a second header row in pandas df for csv write
<p>I have a very large pandas df I am writeing out to csv. I need to add a second header row containing the data types. The below code works but produces a third unexpected empty row in the CSV:</p> <pre><code>#! /usr/bin/env python import pandas as pd df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB')) # get c...
<p>I used a work around in the end (a) write the original headers to csv (b) replace the headers with the second header line and append whole df to first file:</p> <pre><code># write the header to the file only pd.DataFrame(data=[df.columns]).to_csv("outfile.csv", header=False, index=False) # now replace header types...
python|csv|pandas|export-to-csv
3
361,299
34,945,274
How to find all elements in a numpy 2-dimensional array that match a certain list?
<p>I have a 2-dimensional NumPy array, for example:</p> <pre><code>array([[1, 1, 0, 2, 2], [1, 1, 0, 2, 0], [0, 0, 0, 0, 0], [3, 3, 0, 4, 4], [3, 3, 0, 4, 4]]) </code></pre> <p>I would like to get all elements from that array which are in a certain list, for example (1, 3, 4). The desired ...
<p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a> -</p> <pre><code>A*np.in1d(A,[1,3,4]).reshape(A.shape) </code></pre> <p>Also, <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"...
python|arrays|performance|numpy|vectorization
4