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
15,700
38,336,061
Bokeh Mapping Counties
<p>I am attempting to modify <a href="http://bokeh.pydata.org/en/latest/docs/gallery/texas.html#gallery-texas" rel="nofollow noreferrer">this example</a> with county data for Michigan. In short, it's working, but it seems to be adding some extra shapes here and there in the process of drawing the counties. I'm guessing...
<p>I have a solution to this problem, and I <em>think</em> I might even know why it is correct. First, let me show quote from Bryan Van de ven in a Google groups Bokeh discussion:</p> <blockquote> <p>there is no built-in support for dealing with shapefiles. You will have to convert the data to the simple format that Bo...
python-3.x|pandas|bokeh|shapefile
5
15,701
38,306,293
first date of week greater than x
<p>I would like to get the <strong><em>first</em></strong> monday in july that is greater than July 10th for a list of dates, and i am wondering if there's an elegant solution that avoids for loops/list comprehension. Here is my code so far that gives all july mondays greater than the 10th:</p> <pre><code>import panda...
<p>IIUC you can do it this way:</p> <p>get list of 2nd Mondays within specified date range</p> <pre><code>In [116]: rng = pd.date_range('1-Jan-1999',last_date, freq='WOM-2MON') </code></pre> <p>filter them so that we will have only those in July with <code>day &gt;= 10</code></p> <pre><code>In [117]: rng = rng[(rng...
python|pandas
1
15,702
38,313,770
Count the number of specific values in a pandas dataframe
<p>I have to count the number of 'No' in a dataframe and add that count to a separate column called 'count'.</p> <p>For example:</p> <pre><code> MachineName Logs Jobs Performance 121 Yes No Yes 123 Yes No No 126 No No No </code></pre> <p>Output:</p>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a>, because <code>boolean mask</code> is converted to <code>int</code>:</p> <pre><code>df['Count'] = (df[['Logs','Jobs','Performance']] == 'No').sum(axis=1) print (df) MachineName Logs ...
pandas|dataframe
3
15,703
65,955,750
What does "Function call stack: train_function" mean in image recognition AI?
<p>So I am trying use a image recognition AI for a project. The module I using is the one on this website <a href="https://towardsdatascience.com/train-image-recognition-ai-with-5-lines-of-code-8ed0bdd8d9ba" rel="nofollow noreferrer">https://towardsdatascience.com/train-image-recognition-ai-with-5-lines-of-code-8ed0bdd...
<p><code>train_function</code> is a function hidden under the hood when you call <code>model.fit()</code>. It looks roughly like this:</p> <pre><code>def train_step(self, data): x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass # Compute our own loss ...
python|tensorflow|keras
0
15,704
66,029,867
one hot encoding returns all 0 vector for last categorical value
<p><code>tf.one_hot()</code> is yielding <code>[0,0,0]</code> vector for the third class of possible categorical values.</p> <p>I would expect a <code>[1,0,0]</code>. What am I doing wrong with this function?</p> <p>There are 3 possible categorical classes that I want to One-Hot encode. 1,2,3 using <code>tf.one_hot()</...
<p>The problem is because <code>tf.one_hot</code> also consider <code>0</code> as a class, so given that your labels are 1-3, when passed to <code>tf.one_hot</code> it just filled the <code>3</code> class with <code>0</code>s.</p> <p>Simple example:</p> <pre><code>indices = [0, 1, 2] tf.one_hot(indices, 3) # &lt;tf.Ten...
python|tensorflow|keras|neural-network|one-hot-encoding
1
15,705
66,244,373
How to find the streak using email ids in Pandas Python
<p>I have a DataFrame that has students and the days they have attended their classes</p> <pre><code>Email Day mala@gmail.com 1 vika@gmail.com 1 rupa@gmail.com 1 vika@gmail.com 2 vika@gmail.com 3 rupa@gmail.com 3 </code></pre> <p>Expected Output:</p> <pre><code>Email ...
<p>Here's one way that returns the length of the longest consecutive streak within each <code>'Email'</code>.</p> <p>First <code>drop_duplicates</code> that way repeated days for the same e-mail don't ruin any streaks, and sort. Then create labels for groups of consecutive days taking the cumsum of where the difference...
python|pandas
4
15,706
66,279,246
How to align y and x axis using matplotlib
<p>I am starting Python and I would like to use pandas and matplotlib to trace plots. I am using this code :</p> <pre><code>import pandas as pd from matplotlib import pyplot as plt from matplotlib.dates import AutoDateLocator plt.style.use('ggplot') nbColonnes = list(range(0, 15)) monCSV = pd.read_csv('DUT_1_SS1#24.c...
<p>Your <code>time</code> and <code>wake_time</code> are being converted from datetime format to string format. If you keep them as <code>datetime</code> you will get the following output:</p> <p><a href="https://i.stack.imgur.com/KKGuG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KKGuG.png" alt="...
python|pandas|dataframe|csv|matplotlib
0
15,707
52,888,564
Getting the index of the minimum value in each slice of `ndarray`
<p>I am trying to do something that should be straightforward and can be accomplished in a <em>for-loop</em> but I am trying to avoid that.</p> <p>I would like to get the <strong>index</strong> of the minimum value in each slice along a certain axis of a <code>numpy.ndarray</code>, <strong>a</strong>. I am more intere...
<p>For the specific case given in your question, you can reshape your array, then use <code>argmin</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([[[1, 9, 4, 0, 7], ... [6, 3, 1, 6, 8], ... [7, 8, 2, 0, 2], ... [8, 6, 1, 6, 5]], ... ... [[8, 7, 0, 6, 9], ... [7, 2, 6, 4, 5], ...
python|numpy-ndarray
2
15,708
52,877,876
pandas writing to excel sheet deleting other sheets in file
<p>I have simple code to export python dataframe to existing excel file with sheets but the writer keep deleting the existing sheet from the file </p> <pre><code>read = pd.ExcelFile('Saw_Load.xlsx') print(read.sheet_names) writer = pd.ExcelWriter('Saw_Load.xlsx') result.to_excel(writer,'saw', index = False) read2 = pd...
<p>Your problem is that <strong>you're not writing again the old <code>sheets</code></strong> that the book contains. Let's say that you need to write it from scratch again, but no to execute <code>to_excel</code> again but just specify the workbook.</p> <p>This happens beacause <code>xlsxwriter</code> creates a new f...
excel|python-3.x|pandas|pandas-groupby
9
15,709
52,586,643
Memory issues with creating an adjacency matrix using Coo-matrix
<p>Hi i am trying to generate an adjacency matrix with a dimension of about 24,000 from a CSV with two columns showing combinations of pairs of genes and a column of 1's to indicate a present interaction....My goal is to have it be square and populated with zeros for combinations not in the two columns</p> <p>I am usi...
<p>Most likely what you want isn't <code>m.toarray</code> but <code>m.tocsr()</code>. a <code>csr</code> matrix can do simple linear algebra (like <code>.dot()</code> and matrix powers) natively, for instance this works:</p> <pre><code>m.tocsr() random_walk_2 = m.dot(m) random_walk_n = m ** n # see https://stackove...
python|numpy|scipy
1
15,710
46,244,629
What is causing this simple function to plot poorly?
<p>This function is giving me some grief, I think something is possible rounding or not behaving like I expect it to. I've tried changing phi in small increments and the value of AFn jumps around in a way that it definitely shouldn't. It should be a round radiation pattern like this: <a href="https://i.stack.imgur.com/...
<p>Try it like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt N = 7 #number of arrays phi = np.arange(0.0, np.pi, np.pi/1000.0) k = 4.0 def ArrayFactor(phi,N,k): i = 0.0 d = 1.0 AF = 0.0 while i&lt;N: d = d+2 AF = AF + np.cos( k*d * np.cos(phi) ) #array ...
python|numpy|math|matplotlib|plot
2
15,711
46,482,124
Linear Regression in Tensor Flow - Error when modifying getting started code
<p>I am very new to TensorFlow and I am in parallel learning traditional machine learning techniques. Previously, I was able to successfully implement linear regression modelling in matlab and in Python using scikit.</p> <p>When I tried to reproduce it using Tensorflow with the same dataset, I am getting invalid outpu...
<p>One major problem with your estimator is the loss function. Since you use <code>tf.reduce_sum</code>, the loss grows with the number of samples, which you have to compensate by using a smaller learning rate. A better solution would be to use <em>mean</em> square error loss</p> <pre><code>loss = tf.reduce_mean(tf.sq...
machine-learning|tensorflow|linear-regression
1
15,712
58,218,623
Efficient ways to represent a (possibly big) graph with unknown structure using numpy?
<p>My setup is basically the following: </p> <ul> <li>I have a set of nodes (represented as integer numbers <code>0, ...</code>). Possibly several millions of them. </li> <li><p>These nodes are connected in an undirected graph without weights.</p></li> <li><p>The structure of the graph is unknown, both sparse and dens...
<p>Using a <code>numpy.ndarray</code> seems to be unfeasible for your specifications since you describe 1,000,000+ nodes, i.e. the corresponding matrix would have 1e12+ entries.</p> <p>Instead you can use one of the <a href="https://docs.scipy.org/doc/scipy/reference/sparse.html" rel="nofollow noreferrer"><code>scipy....
python|numpy|graph
1
15,713
69,189,813
Json in python rename, delete
<p>I work with big geojson data (more than 1 Gb) with this structure. Is part of it.</p> <pre><code>{'type': 'FeatureCollection', 'crs': {'type': 'name', 'properties': {'name': 'EPSG:4326'}}, 'features': [{'type': 'Feature', 'properties': {'date_create': '15.03.2008', 'statecd': '06', 'cc_date_approval': N...
<p>This answer works if you are sure that the data is a GeoJSON and it is structured properly:</p> <p>For reading GeoJSON data you can use <code>Geopandas</code> library:</p> <pre><code>import geopandas as gpd gdf = gpd.read_file('data_file_name.json') </code></pre> <p>This will load the GeoJSON file in geopandas GeoD...
json|python-3.x|pandas|geojson|geopandas
0
15,714
69,281,985
Why is my dataframe returning 0 on the index column
<p>I'm creating a matrix of random weights for 3 assets through the following code</p> <pre><code>import pandas as pd import numpy as np assets = ['WMT', 'FB', 'BP'] num_assets = len(assets) df1 = pd.DataFrame() for i in range(1000) : weights = np.random.random(num_assets) weights /= np.sum(weights) df1...
<p>use <code>ignore_index=True</code> in <code>pd.concat</code> hence your last line of code should update to</p> <pre class="lang-py prettyprint-override"><code> df1 = pd.concat( [df1, pd.DataFrame( [weights], columns= assets)],ignore_index=True) </code></pre>
python|pandas|dataframe
0
15,715
69,276,478
Grouping by entries in a column in Pandas Dataframe
<p>I have a Pandas DataFrame with <code>id</code> as <code>index</code>, <code>brand</code>, <code>type</code> and <code>price</code> as columns that looks like the following:</p> <pre><code> brand type price id 1234567 A ...
<p>i think you can use <code>.groupby</code> and <code>.unstack</code></p> <pre><code>df1 = df.groupby(['brand','type'])['price'].mean().unstack(1,fill_value=0) print(df1) type X Y Z brand A 39.0 20.0 0.00 B 12.4 0.0 94.15 C 32.0 0.0 0.00 </code></pre>
python|pandas|dataframe
3
15,716
60,932,928
How do I remove float64 from Pandas query
<p>I am working on my first student project with the Iris Dataset and learning Pandas. I wondered if anyone can help? I'm trying to remove dtype: float64 from the pandas results. I am also noticing the results are prefixed with 37m on the other part of the print statement.</p> <p>Reading solutions to similar questions...
<p>You should make the difference between a data and the way it is displayed. The <code>dtype: float64</code> is displayed because you are printing a pandas <code>Series</code>. A simple way to get rid of it is to convert the Series into a DataFrame:</p> <pre><code>print(pd.DataFrame(averageofdata)) </code></pre> <p>...
python|pandas
0
15,717
61,083,284
Getting substrings between '@' and ';' and before '@'
<p>I have a pandas column <code>Amort</code> with each row containing string values like <code>3,312.50 @ Mar 31, 2020; 3,312.50 @ Jun 30, 2020; 3,312.50 @ Sep 30, 2020; 3,312.50 @ Dec 31, 2020; 3,312.50 @ Mar 31, 2021</code> in each row and I want to create columns associated with each year that contains the summed va...
<p>IIUC, you can use <code>extractall</code>:</p> <pre><code>s = df.Amort.str.extractall('(?P&lt;Amort&gt;[\d,\.]+) \@ (?P&lt;date&gt;[\w ,]+);') s['date'] = pd.to_datetime(s['date']) s['Amort'] = s['Amort'].str.replace(',','').astype(float) s = s.reset_index('match',drop=True).set_index(s['date'].dt.year.rename('yea...
python|pandas
2
15,718
71,749,600
Plotting barplot category-wise in pandas
<p>I have a dataframe containing columns code, year and number_of_dues. I want to plot barplot having year on x axis and no of claims for each year on y axis for each code in one after after subplot fashion. please help me. Sample data is given below.</p> <pre><code>Code Year No_of_dues 1 2016 100 1 2017 ...
<p>Try this one:</p> <pre><code> df.groupby(['Code', 'Year'])['No_of_dues'].sum().to_frame().plot.bar() </code></pre>
python|pandas|matplotlib|bar-chart
0
15,719
71,455,256
Count the number of timestamp instances with an interval in Python
<p>I have a text-file with the following timestamps:</p> <p>0:01</p> <p>0:02</p> <p>0:02</p> <p>0:02</p> <p>0:03</p> <p>...</p> <p>2:05:52</p> <p>2:05:52</p> <p>2:05:52</p> <p>2:05:53</p> <p>2:05:53</p> <p>2:05:53</p> <p>2:05:53</p> <p>2:05:54</p> <p>2:05:54</p> <p>2:05:54</p> <p>2:05:54</p> <p>Currently, I have a dict...
<p>First you need to clean your data. I don't know whether &quot;0:01&quot; means 1 second after midnight or one minute after, and neither does Pandas. Write it as &quot;0:00:01&quot; or &quot;0:01:00&quot; as appropriate. Then try this:</p> <pre><code>df = pd.read_table('mydata.txt', header=None) df.index = pd.to_t...
python|pandas|numpy
0
15,720
71,460,261
How to change the date time format for only SOME ROWS in Pandas?
<p>I have a dataframe in which there are some columns. One of them is Date but some dates are in the format of dd-MMM-YY (eg: 03-May-2022) and some are in the format dd-mm-yy(eg: 03-05-2022). How do I change all the dates in the column to one format(eg: dd-mm-yy)?</p> <p><strong>Initial Dataframe:</strong></p> <div cla...
<p>I can think of one solution where you handle the two different cases based on length of the date string:</p> <pre><code>def format_date(date): reformatter = { &quot;Jan&quot;: &quot;01&quot;, &quot;Feb&quot;: &quot;02&quot;, &quot;Mar&quot;: &quot;03&quot;, ... &quot;Dec&q...
python|pandas|date|datetime
0
15,721
42,504,984
python pandas select both head and tail
<p>For a DataFrame in Pandas, how can I select both the first 5 values and last 5 values?</p> <p>For example</p> <pre><code>In [11]: df Out[11]: A B C 2012-11-29 0 0 0 2012-11-30 1 1 1 2012-12-01 2 2 2 2012-12-02 3 3 3 2012-12-03 4 4 4 2012-12-04 5 5 5 2012-12-05 6 6 6 2012-12-06 7 7 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="noreferrer"><code>iloc</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="noreferrer"><code>numpy.r_</code></a>:</p> <pre><code>print (np.r_[0:2, -2:0]) [ 0 1 -...
python|pandas|slice|tail|head
32
15,722
69,975,203
plotting stations on map
<p>i have three stations named as <code>A, B, C</code>. I want to plot them on a map using matplotlib basemap.</p> <pre><code>station A: latitude=17.8 longitude=74.48 station B: latitude=-25.02 longitude=25.60 station C: latitude=44.58 longitude=-123.30 </code></pre> <p>As i am new to python and that to matplotlib, i a...
<p>Here's an example based on your data with which you might play around:</p> <pre><code>import pygmt import pandas as pd # create df with station information data = {'lon':[74.48, 25.60, -123.30], 'lat':[17.8, -25.02, 44.58], 'station':['A', 'B', 'C']} df = pd.DataFrame(data) fig = pygmt.Figure() py...
pandas|matplotlib|matplotlib-basemap|obspy|pygmt
1
15,723
69,765,962
Python Pandas leaking memory?
<p>I have a script that is constantly measuring some data and regularly storing it in a file. In the past I was storing the data in a &quot;manually created CSV&quot; file in this way (pseudocode):</p> <pre><code>with open('data.csv','w') as ofile: print('var1,var2,var3,...,varN', file=ofile) # Create CSV header. ...
<h1>Pandas was not the problem</h1> <p>After struggling with this problem for a while, I decided to create a MWE to do some tests. So I wrote this:</p> <pre><code>import pandas import numpy import datetime df = pandas.DataFrame() while True: df = df.append({f'col_{i}': numpy.random.rand() for i in range(99)}, igno...
python|pandas|memory-leaks
0
15,724
43,409,811
One-hot encoding using scikit-learn
<p>I am working on a machine learning project and one feature of my dataset consists of categorical data. This data is first stored in an panda series (<code>&lt;class 'pandas.core.series.Series'&gt;</code>) <code>mesh</code> with dimmensions of<code>(2000,)</code>. The number of rows corresponds to the total number of...
<p><code>str(s)</code> converts Pandas.Series of strings into a single string, delimited by <code>'\n'</code>, so use <code>Pandas.Series.str.split()</code> method instead.</p> <p>replace</p> <pre><code>str(s).split(', ') </code></pre> <p>with</p> <pre><code>s.str.split(',\s*') </code></pre> <p>Demo:</p> <pre><co...
python|numpy|scikit-learn|categorical-data|one-hot-encoding
1
15,725
72,308,007
Removing multiple occurrence of an element from the given dataset
<p>I have a dataset as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Elements</th> </tr> </thead> <tbody> <tr> <td>Cat</td> <td>friend, friend, friend</td> </tr> <tr> <td>Dog</td> <td>friend, friend</td> </tr> <tr> <td>Crow</td> <td>friend</td> </tr> <tr> <td>Cow</t...
<p>I am going to assume that there are possibly going to be more types of elements and possibly rows with no elements.</p> <p>I am assuming that df['elements'] is a string (since you don't give a code example to see the formatting). The list will be [item.strip() for item in df['elements'].split(',')].</p> <p>I would t...
python|pandas|list|dataframe|data-cleaning
0
15,726
72,180,134
Accumulate specific rows from pandas dataframe
<p>My Pandas dataframe looks like this:</p> <p><a href="https://i.stack.imgur.com/IgEwl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IgEwl.png" alt="enter image description here" /></a></p> <p>Notice that for each task there are exactly 2 rows: row for begin and and row for end of task.<br /> I ne...
<p>Using <code>pandas.pivot()</code> function you can simply do it like this assuming df is your dataframe:</p> <pre><code>new_df = df.pivot(index=&quot;Task&quot;, columns=&quot;Action&quot;, values=&quot;DateTime&quot;) </code></pre>
python|pandas|dataframe
1
15,727
50,437,427
Passing string to dataframe iloc
<p>I have a <code>ProductDf</code> which have many versions of the same product. I want to filter the last iteration of the product. So I did this as below:</p> <pre><code>productIndexDf= ProductDf.groupby('productId').apply(lambda x:x['startDtTime'].reset_index()).reset_index() productToPick = productIndexD...
<p>Pandas Dataframe <strong>iloc</strong> method works only with integer type indexed value. If you want to use string value as index for accessing data from pandas dataframe then you have to use Pandas Dataframe <strong>loc</strong> method.</p> <p>Know more about these method from these link.</p> <p><a href="https:/...
python|pandas|python-3.5
4
15,728
50,284,498
Error in inserting a new data column with pd.IntervalIndex
<p><strong>Problem statement :</strong> Have 2 data frames A &amp; B .</p> <pre><code>A: Timestamp datetime64[ns, UTC] CH_0 float64 CH_1 float64 CH_2 float64 B: Video Start Time datetime64[ns, UTC] Video End Time datetime64[ns, UTC] Vid...
<p>First covert the times in A and B to datetime format and then use <code>IntervalIndex.from_arrays</code> as below</p> <pre><code>A['Timestamp'] = pd.to_datetime(A['Timestamp']) B['Video Start Time'] = pd.to_datetime(B['Video Start Time']) B['Video End Time'] = pd.to_datetime(B['Video End Time']) idx = pd.IntervalI...
python-3.x|pandas
1
15,729
45,604,688
Apply function on each row (row-wise) of a NumPy array
<p>So, I have the function - </p> <pre><code>def function(x): x , y = vector return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2) </code></pre> <p>and let's say that I would like to evaluate it at the following points (first column are the x-values and second column are the y-values) - </p> <pre><code...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html" rel="noreferrer"><strong><code>np.apply_along_axis</code></strong></a>:</p> <pre><code>np.apply_along_axis(function, 1, array) </code></pre> <p>The first argument is the function, the second argument is the axis al...
python|arrays|numpy|apply
84
15,730
62,486,779
ImportError: cannot import name 'device_spec' from 'tensorflow.python.framework'
<p>When i try to run <code>python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config</code></p> <p>command this error pops out. (tensorflow1.13)</p> <blockquote> <p>C:\tensorflow1\models\research\object_detection&gt;python train.py --logtostderr --train_dir...
<h2>EDIT -&gt; The TF OD API now supports TF2</h2> <p>FRCNN is one of the supported models. Soooooooo, update your TF Models version and you should be good to go :)</p> <p>You can check out the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">updated TF OD A...
python|python-3.x|tensorflow|training-data|faster-rcnn
1
15,731
62,619,879
While performing the time Series Analysis I have got the error Date time while converting the string to datetime
<p>I have the data which is in the column of date and I want to convert into DateTime, an error occurs like the below</p> <pre><code> Month Sales of shampoo over a three year period 0 1-01 266.0 1 1-02 145.9 2 1-03 183.1 3 1-04 119.3 4 1-05 180.3 pd.to_datetime(data['Month']) </code></pr...
<p>I think you have a zero-padding problem. If you use &quot;01&quot; instead of &quot;1&quot; you can convert the object to DateTime.</p> <p>Just like this;</p> <pre><code>x=['1-01','1-02','1-03','1-04','1-05'] y=[266.0,145.9,183.1,119.3,180.3] data=pd.DataFrame(list(zip(x,y)),columns=['month','sth']) data['month']='0...
python|pandas|datetime|time-series
1
15,732
62,829,604
Slicing pandas dataframe with list of list with columns
<p>So I have a huge dataframe, of which I iteratively need to slice some different columns. All columns to slice, I have in a list, like</p> <pre><code>[col1, col2, col3] [col2, col3, col4] [col1, col2, col4] </code></pre> <p>etc etc.</p> <p>What I do now, is I loop through the list of columns and then use loc to selec...
<p>Probably not worth an answer, just a comment, but: in this case, you are probably overthinking it - in any case, a simple list comprehension is probably sufficient...</p> <pre><code>In [1]: from pandas import util ...
python|pandas|dataframe
1
15,733
62,518,015
How to iterate over key and values within a pd.DataFrame?
<p>I have a pd.DataFrame containing 3 dictionaries that looks like this:</p> <pre><code> 0 1 0 land_cover {'y2001': [120], 'y2002': [120], 'y2003': [120... 1 ndvi {'y2001': [3513], 'y2002': [3411], 'y2003': [3... 2 precipitation {'y2001': ...
<p>you can do a targeted regular expression replacement.</p> <pre><code>df = pd.DataFrame({'A' : [0,'y123', 'y00123']}) print(df) A 0 0 1 y123 2 y00123 df1 = df.replace({r'(y)(\d+)' : r'\2'},regex=True) print(df1) A 0 0 1 123 2 00123 </code></pre>
python|json|pandas|dataframe
0
15,734
62,627,575
Create a list from rows values with no duplicates
<p>I would need to extract the following words from a dataframe.</p> <pre><code>car+ferrari </code></pre> <p>The dataset is</p> <pre><code> Owner Sold type car+ferrari J.G £500000 car+ferrari R.R.T. £276,550 car+ferrari motobike+ducati motobike+ducati ... <...
<pre><code>def lister(x): #function to split by '+' return set(x.split('+')) df['listcol']=df['type'].apply(lister) # applying the function on the type column and saving output to new column </code></pre> <p>Adding @AMC's suggestion of a rather inbuilt solution to split series in pandas:</p> <pre><code>df['ty...
python|pandas
0
15,735
54,565,054
Python 3.x: Pandas DataFrame How do we combine multiple csv files into one csv file?
<p>I have multiple datasets that has the same number of rows and columns. The column is 0.1,2,3,4,5,6,7,8. For instance, Data1</p> <pre><code>0.1 3 2 3 3 0.1 4 10 5 5 6 7 7 9 8 2 </code></pre> <p>Data2</p> <pre><code>0.1 2 2 1 3 0.1 4 0.5 5 4 6 0.3 7 9 8 2 </code></pre> <p>I want to...
<p>Assuming the first column is the <code>index</code> and the second is <code>data</code>:</p> <p><code>df = Data1.join(Data2, lsuffix='_1', rsuffix='_2')</code></p>
python-3.x|pandas|dataframe
0
15,736
54,317,326
At the end of my script, how to move my downloaded files to a new folder?
<p>I have a script that downloads about 1000 csv files, sorts them into 5 csv files and sorts those 5 files into 1 csv file.</p> <p>The script works fine but obviously when you run it you end up with like a thousand csv files wherever you ran the program from. Is there a way to <strong>once the script has finished</st...
<p>This code worked for me:</p> <pre><code>import glob, os, shutil source_dir = 'C:/Users/george/Desktop/my aemo app/a' dst = 'C:/Users/george/Desktop/my aemo app/b' files = glob.iglob(os.path.join(source_dir, "*.csv")) for file in files: if os.path.isfile(file): shutil.copy2(file, dst) </code></pre>
python|pandas|numpy
1
15,737
73,642,295
Applying custom function to groupby object keeps groupby column
<p>I have a dataframe which as a column for grouping by and several other columns. Play dataframe:</p> <pre><code>d = {'group_col': [&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;a&quot;],'col1': [1, 2, 3, 4], 'col2': [3, 4, 5, 6]} df = pd.DataFrame(data=d) </code></pre> <p>When using a groupby on this dataframe foll...
<p>You can try to use <code>.agg</code> instead of <code>.apply</code>:</p> <pre class="lang-py prettyprint-override"><code>def tss(x): return ((x - x.mean()) ** 2).sum() print(df.groupby(&quot;group_col&quot;).agg(tss)) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> col...
python|pandas|dataframe|group-by
2
15,738
73,579,837
the scoring average of every name in a new column
<pre><code>data = {'Name' : [&quot;ana&quot;,&quot;ini&quot;,&quot;unu&quot;],'ID' : [&quot;1027&quot;,&quot;1028&quot;,&quot;1029&quot;],'Score1' : [3,5,2], 'Score2' : [5,5,4],'Score3' : [1,2,5]} </code></pre> <p>how can i know the scoring average?</p> <p><code>data[&quot;Average&quot;] = data.mean(axis=1)</code> i tr...
<p>It tries to take the average over the entire row, including <code>Name</code> and <code>ID</code>.</p> <pre><code>df = pd.DataFrame(data) df[&quot;Average&quot;] = df[['Score1', 'Score2', 'Score3']].mean(axis=1) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df Name ID Score1 Score2 Score3 Average 0 ...
python|pandas|dataframe
1
15,739
73,765,650
How to locate the Occurrences of a Specific value in pandas Dataframe
<p>I want to locate a specific value which can occur in multiple columns . In my case it's &quot;False&quot; . I know how to search &quot;False&quot; in individual columns as</p> <pre><code>df.loc[df['column1']==False] df.loc[df['column2']==False] </code></pre> <p>Is there a way to find all at once ?</p> <pre><code>Un...
<p>If you want to get the indices <code>stack</code>, then slice:</p> <pre><code>s = df.stack() s[s.eq(False)].index </code></pre> <p>Or if you only have <code>True</code>/<code>False</code>:</p> <pre><code>s[~s].index </code></pre> <p>In one line:</p> <pre><code>df.stack().loc[lambda s: ~s].index </code></pre> <p>If y...
python|pandas|pandas-loc|python-applymap
3
15,740
71,204,207
Python pandas concat to multi index groupby
<p>I'm new to pandas and I need help. I have two following reports which are quite simple.</p> <pre><code>$ cat test_report1 ID;TYPE;VAL 1;USD;5 2;EUR;10 3;PLN;3 $ cat test_report2 ID;TYPE;VAL 1;USD;5 2;EUR;10 3;PLN;1 </code></pre> <p>Then I'm using concat to connect two reports with unique index:</p> <pre><code>A=pd.r...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename_axis.html" rel="nofollow noreferrer"><code>DataFrame.rename_axis</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.sta...
python|pandas|dataframe|multi-index
1
15,741
71,400,114
Is there a way to concatenate columns by groups of 2 same values in pandas
<p>Say i have something like this in a pandas dataframe :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Entity</th> <th>Type</th> <th>Doc</th> <th>Proj</th> </tr> </thead> <tbody> <tr> <td>Daniel</td> <td>PER</td> <td>1</td> <td>1</td> </tr> <tr> <td>Daniel</td> <td>PER</td> <td>4</td> <t...
<p>here is one way:</p> <ol> <li>reset_index to copy the index as a column</li> <li>use merge to join df with itself on entity and type columns</li> <li>remove the duplicate pairs by only keeping the smaller index of original right side of merge.</li> </ol> <pre><code>df = df.reset_index() res = pd.merge(df, df, on=['E...
python|pandas|dataframe
0
15,742
71,299,230
cnn model after bert
<p>I try get output from last hidden state of bert model and pass it through CNN MOdel</p> <pre><code>class MixModel(nn.Module): def __init__(self,pre_trained='distilbert-base-uncased'): super().__init__() self.bert = AutoModel.from_pretrained('distilbert-base-uncased') self.hidden_...
<pre><code> def __init__(self,pre_trained='distilbert-base-uncased'): super().__init__() self.bert = AutoModel.from_pretrained('distilbert-base-uncased') self.hidden_size = self.bert.config.hidden_size self.conv = nn.Conv1d(in_channels=768, out_channels=256, kernel_size=5, pa...
python|pytorch|conv-neural-network|bert-language-model
0
15,743
71,396,518
Reading csv file into pandas dataframe from certain string to certain string
<p>I have a .csv file with data from different runs. So, my file looks like:</p> <pre><code>execution on Monday name1, name2, name3 1,2,3 4,5,6 end Monday execution on Tuesday name1, name2, name3 7,8,9 10,11,12 end Tuesday </code></pre> <p>Thereby, it is unknown how many rows there are for one run.</p> <p>I am looking...
<p>It seems you have empty line betwin runs - so you could use this fact.</p> <p>And you can use fact that <code>pandas</code> can read from <code>file-like-object</code></p> <p>You can read all as single string and split on empty lines</p> <pre><code>runs = text.split(&quot;\n\n&quot;) </code></pre> <p>and use selecte...
python|pandas|csv
1
15,744
71,283,207
Allocating a path to a numpy array
<p>I have an image as an np array and I want to pass it to a model which just accepts the image path as the input. What is the best and most optimized way of getting a path for my image?</p> <p>Writing on the disk doesn't seem reasonable for a large number of images. Is there a way to get a path on the memory?</p>
<p>Create a tmpfs filesystem (aka a RAM disk), save the NumPy array as a file there. This way it won't do any actual disk I/O.</p> <p>Of course, with modern SSDs I doubt you'll measure any speedup in your overall system.</p>
python|numpy|image-processing|memory|temporary-files
0
15,745
52,221,180
python for loop calculation too inefficient/long
<p>I am running a back-testing program on python. However, even though the maths/logic is simple, python seems to be taking an extremely long time to calculate the FOR loop. </p> <p>For each row/line, it takes on average 1-sec; and when I have thousands to potentially ten-of-thousands of rows-of-data, the time-taken i...
<p>It seems (well, it seems to be relatively known) that numpy processes looped calculations much more effectively than pandas (as it has to re-built the whole array each time).</p> <p>Basically, I create a numpy array [x,y] within the function. Then, I calculate via a for-loop and populate the numpy array, row-by-row...
python-3.x|pandas|for-loop|calculation
0
15,746
72,555,410
Pandas : Why the order of merged keys are the way they are when we merge two DataFrames?
<p>I am new to <code>pandas</code> and I am learning data manipulation. In the following example, while <code>merging</code> two <code>DataFrames</code> with some similar keys, why is the order of the keys in the merged DataFrame like below?</p> <p><a href="https://i.stack.imgur.com/nO0rD.png" rel="nofollow noreferrer"...
<ol> <li>If you do not specify <code>on</code> keyword the intersection of the columns is used.</li> </ol> <blockquote> <p>on : label or list</p> <p>Column or index level names to join on. These must be found in both DataFrames. If <code>on</code> is None and not merging on indexes then this defaults to the intersectio...
python|pandas|dataframe
1
15,747
72,520,755
Print or save output of tf.keras model, paired with inputs
<pre class="lang-py prettyprint-override"><code>def locations_model(...): input_shape = image_shape + (3,) base_model = tf.keras.applications.MobileNetV2(...) base_model.trainable = False inputs = tf.keras.Input(...) ... ... outputs ...
<p>Thanks for the confirmation <strong>@EduardoriosChicago</strong>. I am mentioning your answer here for the benefit of the community.</p> <blockquote> <p>The code is</p> <pre><code>probas = model(x_in); x_classes = probas.argmax( axis = - 1) </code></pre> </blockquote>
python|tensorflow|keras|file-io
0
15,748
72,808,985
Save pandas dataframe as txt file in Python, with dataframe columns containing either single int values or python lists
<p>I am trying to save a complex pandas dataframe as txt file in Python. The dataframe is composed of data obtained using openCV, with different characteristics of objects being detected using a computer vision code. For example, data present in the dataframe are object height, object width, class label, and contour co...
<p>This is more of a comment with a bunch of observations - but with more room.</p> <p>First I've never been able to get the <code>df_to_save.to_string()</code> approach for creating an exact string representation of a dataframe to work. Usually it is that the string representation is collapsed on a wide column.</p> <...
python|pandas|list|dataframe|opencv
0
15,749
72,783,948
Compare current element in one list to next element in another list
<p>I have two equally long lists representing the start and end frames of an event. They look something like this:</p> <pre><code>START END 111 113 118 133 145 186 </code></pre> <p>The next element of the START list is always going to be bigger than the previous element in the END lists a.k.a 1...
<p>Is this that you're looking for ? You can compare start[i] with end[i-1] ?</p> <pre><code>start = [111,118, 145] end = [113, 133, 186] for i in range(1, len(start)): print(start[i] - end[i-1]) </code></pre>
python|list|numpy
1
15,750
59,851,896
update seaborn from inside jupyter notebook
<p>Here my problem:</p> <pre><code>sns.scatterplot(x=[x,x,x], y=[x,x,x]) </code></pre> <blockquote> <blockquote> <blockquote> <p>AttributeError: module 'seaborn' has no attribute 'scatterplot'</p> </blockquote> </blockquote> </blockquote> <p>I read that seaborn needs to be updated, to solve this. S...
<p>Update jupyter notebook in the Anaconda navigator. All modules will get updated. This should resolve your issue.</p>
python|pandas|seaborn
0
15,751
32,441,912
How to split continuous data into groups?
<p>I have two data sets, the first one with discrete data and the second one with continuous data:</p> <pre><code>import numpy as np # discrete data1 = [1, 1, 2, 2, 2, 3, 4, 4,7, 7, 7, 7, 7, 7] # continuous data2 = np.random.normal(size=100) </code></pre> <p>Now I want to calculate frequencies. It's straightforward...
<p>For numpy, have a look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html" rel="nofollow noreferrer"><code>np.histogram</code></a> for the continuous data and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html#numpy.bincount" rel="nofollow noreferrer"><...
python|numpy|dataframe
6
15,752
40,519,308
Trying to merge DataFrames with many conditions
<p>This is a weird one: I have 3 dataframes, "prov_data" with contains a provider id and counts on regions and categories (ie. how many times that provider interacted with those regions and categories). </p> <pre><code>prov_data = DataFrame({'aprov_id':[1122,3344,5566,7788],'prov_region_1':[0,0,4,0],'prov_region_2':[2...
<p><strong><em>code</em></strong></p> <pre><code># the first columns of each dataframe are the ids # i'm going to use them several times tid = tender_data.values[:, 0] pid = prov_data.values[:, 0] # first columns [1, 2, 3, 4] are cat columns # we could have used filter, but this is good # for this example pc = prov_da...
python|python-3.x|pandas|dataframe
2
15,753
40,512,072
Can a TensorFlow model run as a Linux/Unix service?
<p>I have built a TensorFlow model using TensorFlow’s high-level machine learning API (tf.contrib.learn). I need to run this model as a Linux/Unix service. Or export the model as an executable. Is this possible? And if yes how can I do so?</p> <p>Any help is appreciated.</p>
<p>The best way is probably to run a <a href="https://tensorflow.github.io/serving/" rel="nofollow noreferrer">tensorflow server</a> on your local machine, then connect to it via RPC. You can put the serving command in <code>/etc/initd</code> or <code>/etc/systemd</code>.</p>
linux|unix|tensorflow|tensorflow-serving
0
15,754
40,503,892
How to build CUDA JIT caches for all available kernels in TensorFlow programmatically?
<p>I encountered the "first-run slow-down" problem with GTX 1080 cards and nvidia-docker as discussed in <a href="https://stackoverflow.com/questions/36842169/">this question</a>.</p> <p>I'm using the TensorFlow build from <a href="https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0rc2-cp35-cp35m-lin...
<p>There seems to be no easy way to achieve this since CUDA runtime implicitly, lazily compiles missing cubin from the given kernel sources <a href="https://github.com/NVIDIA/nvidia-docker/issues/224" rel="nofollow noreferrer">as discussed here</a>.</p> <p>Solved this problem by rebuilding TensorFlow by myself, with s...
cuda|tensorflow|nvidia
1
15,755
40,463,431
Creating a matrix from CSV file
<p>I've been working on Python for around 2 months now so I have a OK understanding of it. </p> <p>My goal is to create a matrix using CSV data, then populating that matrix from the data in the 3rd column of that CSV file.</p> <p>I came up with this code thus far:</p> <pre><code>import csv import csv def readcsv(cs...
<p>You should seriously consider using <a href="http://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a>. It is really ideal for this sort of work. I can't give you an actual solution because I don't have your data, but I would try something like the following:</p> <pre><code>import pandas as pd df = pd.read_cs...
python|csv|parsing|numpy|matrix
3
15,756
40,381,870
Count unique ID overlap between two strings
<p>I have a data set with two columns. The first column contains unique user IDs and the second column contains attributes connected to these IDs. </p> <p>For example:</p> <pre><code>------------------------ User ID Attribute ------------------------ 1234 blond 1235 brunette 1236 blond 123...
<p>From your pivoted table, you can calculate the transposed crossproduct of itself, and then transform the upper triangular result to the long format:</p> <pre><code>import pandas as pd import numpy as np mat = df.pivot_table(index='User ID', columns='Attribute', aggfunc=len, fill_value=0) tprod = mat.T.dot(mat) ...
python|python-3.x|pandas|correlation
1
15,757
40,581,511
Python export range values to csv
<p>Currently prints range values to terminal. I need to export these values to a csv file. "print S[t-1], I[t-1], R[t-1]" are the values...</p> <pre><code>import matplotlib.pyplot as plt import numpy beta = 0.24 gamma = 0.142857 Tstart = 0 Tend = 151 r = 0 s = (306.8 * 10**6) i = (22 * 10**6) def compute_next_day(t,R...
<p>Something like this should work:</p> <pre><code>def compute_next_day(t,R,I,S,): ... return S[t-1], I[t-1], R[t-1] # return values instead of printing to terminal with open('path_to_file.csv','w') as f: for ... : # your choice of loop vals = compute_next_day(...) # compute your values f....
python|arrays|python-3.x|csv|numpy
0
15,758
61,866,352
How can I have this table with the correct figures from this data here?
<p>How do I end up with this?</p> <p><a href="https://i.stack.imgur.com/Shsjj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Shsjj.png" alt="outcome"></a></p> <p>From this kind of data</p> <p><a href="https://i.stack.imgur.com/rkHxg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.c...
<p>Your solution is changed by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> for 2 columns <code>DataFrame</code>, then is used <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.ht...
pandas
1
15,759
61,846,804
Covert table dataframe to json api request in python
<p>I scrape a table on a site using pandas and get a dataframe. I only need one column of data from the dataframe that has long titles. I need to insert these titles into a json api request that looks like this:</p> <pre><code>payload = "{\n \"campaign_id\": 1,\n \"identifiers\": [\n {\n \"iden...
<p>Try this,</p> <pre><code>items = [1, 2, 3, 4, 5...] # list comprehension.. print([{'identifier': item, 'type': 'keyword'} for item in items]) </code></pre> <p>Output</p> <pre><code>[{'identifier': 1, 'type': 'keyword'}, {'identifier': 2, 'type': 'keyword'}..] </code></pre>
python|json|pandas
1
15,760
61,828,201
Pandas: read csv from github
<p>I created a public github repo and I uploaed a .csv file that I would like to read</p> <p><a href="https://github.com/emanuelemassaro/pois/blob/master/indonesia_education.csv" rel="nofollow noreferrer">https://github.com/emanuelemassaro/pois/blob/master/indonesia_education.csv</a></p> <p>This what I am doing</p> ...
<p>Your url is an invalid github request. You forgot the branch name. Using the corrected url, you can read simply with <code>pd.read_csv</code>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd url = "https://raw.githubusercontent.com/emanuelemassaro/pois/master/indonesia_education.csv" pd.rea...
python|pandas
2
15,761
61,867,890
What is the fastest way to compute a sparse Gram matrix in Python?
<p>A Gram matrix is a matrix of the structure <code>X @ X.T</code> which of course is symmetrical. When dealing with dense matrices, the <code>numpy.dot</code> product implementation is intelligent enough to recognize the self-multiplication to exploit the symmetry and thus speed up the computations (see <a href="https...
<p>Thanks to the comment of the user CJR, I worked out a satisfying solution. In fact, I found <a href="https://github.com/flatironinstitute/sparse_dot" rel="nofollow noreferrer">a library on GitHub</a> which wraps the MKL routine <code>mkl_sparse_spmm</code> for Python. This routine is for fast multiplication of two s...
python|python-3.x|numpy|matrix|sparse-matrix
3
15,762
61,733,389
How to change the key value of a dictionary?
<p>i got a large textfile (<a href="https://int-emb-word2vec-de-wiki.s3.eu-central-1.amazonaws.com/vectors.txt" rel="nofollow noreferrer">https://int-emb-word2vec-de-wiki.s3.eu-central-1.amazonaws.com/vectors.txt</a>) and put the file into a dictionary:</p> <pre><code>word2vec = "./vectors.txt" with open(word2vec, 'r...
<p>why not just <code>str.decode()</code> it?</p> <p>the line would be</p> <pre><code>model = {k.decode(): np.array(list(map(float, v))) for k, *v in file} </code></pre>
python|numpy
0
15,763
57,804,903
Randomly keeping a single element different from zero along one axis of a numpy array
<p>I need an efficient way to create a numpy array of shape (x,y,3) where only one random element out of the 3 for each tuple (x,y) has a value randomly selected from [-1,0,1]</p> <pre><code> np.random.randint(-1, 2, (x,y,3)) </code></pre> <p>does the work only for the second half of my requirements.</p> <p>I could ...
<p>Rather than generating a whole bunch of extra numbers and turning most of them off, I'd approach this from the point of view of only generating the numbers you need. You want to assign to a random index between 0 and 2 for each x-y pair. So generate a random index, and the random values, and assign:</p> <pre><code>...
python|numpy
0
15,764
33,979,392
Pandas concatenate, with no duplicate indices or columns
<p>The pandas docs <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow noreferrer">give an example of <code>concat</code></a> that combines indices (<code>axis=0</code>), by concatenating along the columns (<code>axis=1</code>):</p> <pre><code>In [1]: df1 = pd.DataFrame({'A': ['A0', 'A1', ...
<p>I'm essentially asking for an "upsert" (insert, update) operation. So that's an approach that could work:</p> <p>First, the "insert", of rows that don't currently exist in <code>df1</code>:</p> <pre><code># Add all rows from df4 that don't currently exist in df1 result = pd.concat([df1, df4[~df4.index.isin(df1.in...
python|pandas
3
15,765
34,397,982
Access multiple items with not equal to, !=
<p>I have the following Pandas DataFrame object <code>df</code>. It is a train schedule listing the date of departure, scheduled time of departure, and train company.</p> <pre><code>import pandas as pd df = Year Month DayofMonth DayOfWeek DepartureTime Train Origin Datetime 1988-01-01 1988 1 ...
<pre><code>df[~df['Train'].isin(['DeutscheBahn', 'SNCF'])] </code></pre> <p><code>isin</code> returns the values in <code>df['Train']</code> that are in the given list, and the <code>~</code> at the beginning is essentially a <code>not</code> operator.</p> <p>Another working but longer syntax would be:</p> <pre><cod...
python|pandas
62
15,766
34,181,505
Understanding row iteration in pandas (python)
<p>I have a dataframe with (in this example) 2 rows and the dataframe looks a bit like this:</p> <pre><code>PERON START END AB 100 120 CC 110 115 </code></pre> <p>(What I want , but which is not the question I have, is to make a new column with a flag <strong>for each row if "START"-'END' is equ...
<p>This is down to how pandas vectorizes operations where it can.</p> <pre><code>abs(df.START-df.END) ==20 </code></pre> <p>itself returns a series. This series is the column you seek:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[100,120],[110,115]],index=['AB','CC'],columns=['START','END']) ... df ... abs(df.STA...
python|pandas|iterator|ambiguous
1
15,767
34,229,253
Filtering Pandas DataFrame on Time values
<p>I have a Pandas DataFrame which has a column with times in the format hhmm and am looking to filter out rows where the time is more than a particular time e.g. 08:00.</p> <p>I know that if I only had convert 1 value I could do something like <a href="https://stackoverflow.com/questions/22221858/compare-string-in-fo...
<p>You can try something like the following.</p> <pre><code>import pandas as pd data = ['08:00', '09:00','10:00'] dataframe = pd.DataFrame(data) dataframe.columns = ['ttime'] dataframe[dataframe['ttime'] &gt; '08:00'] #to select where time is greater than 08:00 </code></pre> <p>Hope this helps.</p>
python|pandas|time
0
15,768
36,798,038
pandas: compare 2 excel files in pandas, return row where value from one column is present in the other
<p>I have two excel files, both contain employee information. File1 is is 195K rows, File2 is less than 100. I need to return the entire row in File1 where the id# from the File2 is present. I've done something like this in PHP but can't sort it out in python/pandas.</p> <p>I'm looking at the isin() method to work out...
<p>Your column order is wrong, it should be:</p> <pre><code>df0[df0['staffid'].isin(df1['staffid'])] </code></pre> <p>the error is because <code>df1</code> length is not the same as <code>df0</code></p> <p>You want to find the staffid values in <code>df0</code> that are present in <code>df1</code>, not the other way...
excel|python-2.7|pandas
1
15,769
73,192,073
Pandas averaging by specific row
<p>I have table taht looks like following</p> <pre><code>A | B | C __________ na| 1 | 2 3 | 3 | 4 na| 5 | 6 na| 7 | 8 2 | 9 | 10 na| 11| 12 na| 13| 14 3 | 15| 16 </code></pre> <p>I would like to average all by column A. All the nan values till the number, final outcome should look like</p> <pre><code>A | B | C ________...
<p>You could backward fill column A and then perform a <code>groupby</code> with <code>mean()</code>:</p> <pre><code>df.assign(A = lambda col:col['A'].bfill()).groupby('A',as_index=False).mean() </code></pre> <p>prints:</p> <pre><code> A B C 0 2.0 7.0 8.0 1 3.0 2.0 3.0 </code></pre> <p><strong>EDIT:</st...
python|pandas
2
15,770
73,315,945
Python dataframe not updating
<p>I have this dataset:</p> <pre><code>date event ticker initialprice120 initialprice90 initialprice60 initialprice30 initialprice7 finalprice 0 2010-11-18 MELA Mela Sciences FDA Panel MELA 0.0 0.0 0.0 0.0 0.0 0.0 1 2010-12-07 OREX Orexigen Therapeutics Inc PDUFA OREX 0.0 0.0 0.0 0....
<p>See <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.Series.html</a> for operations on series.</p> <p>To access a single value by a label use <code>row.at[label] = ...</code> or <code>fda1.at[index, label] = ...</c...
python|pandas
0
15,771
73,327,719
Renaming Pandas Column Names to String Datatype
<p>I have a df with column names that do not appear to be of the typcial string datatype. I am trying to rename these column names to give them the same name. I have tried this and I end up with an error. Here is my df with column names:</p> <pre><code>dfap.columns Out[169]: Index(['month', 'plant_name', 0, 1, 2, 3, 4]...
<p>You can't rename only some columns using that method.</p> <p>You can do</p> <pre><code>tempcols=dfap.columns tempcols[2:7]=newcols dfap.columns=tempcols </code></pre> <p>Of course you'll want <code>newcols</code> to be the same <code>len</code> as what you're replacing. In your example you're only assigning a <code...
pandas|multiple-columns|rename
0
15,772
73,425,410
Apply something to a row containing a certain term
<p>I want to print data from an Excel document that I imported. Each row comprises a Description and an Ugence level. What I want is to print in red each row that has the &quot;Urgent&quot; statement in it, I made a function which works for that (red_text).</p> <p>I can print the entire rows in red but I can't find how...
<p>Given that I can't verify the output because of the lack of a reproducible example, I think you want to do something like:</p> <pre><code>df = pd.DataFrame({'Description':['urgent stuff','asdasd','other urgent'],'Urgence':['Urgent','sadasd','Urgent']}) print(df) urgent_stuff = df.loc[df['Urgence'] == &quot;Urgent&q...
python|pandas
1
15,773
35,183,120
Group by 2 columns while sorting sorting by a 3rd
<p>I have a pandas dataframe with 3 columns: A, B and C. I would like to group by A and B and display those sorted by C with python. Is this possible? </p>
<p>I think you can first we can group by A and B column and then can apply the sort for C column this will sort the data frame by C column.</p> <pre><code>df.groupby(['A', 'B']) df.sort('C', ascending=False) </code></pre>
python|pandas
0
15,774
30,894,267
Defining a function (pandas)
<p>This works already, but I want to optimize a bit:</p> <pre><code>df['Total Time'] = df['Total Time'].str.split(':').apply(lambda x: (int(x[0])*60.0) + int(x[1]) + (int(x[2]) / 60.0)) </code></pre> <p>I am taking a timestamp (string) in Excel which represents Hours:Minutes:Seconds and turning it into a float which ...
<p>At the moment, the idomatic (but more general soln) is actually slower, see the issue <a href="https://github.com/pydata/pandas/issues/6755" rel="nofollow">here</a></p> <pre><code>In [28]: pd.set_option('max_rows',12) In [29]: s = Series(pd.timedelta_range('0',freq='s',periods=10000).format()) In [30]: s Out[30]:...
python|pandas
1
15,775
67,396,633
Pandas grouping based on a column in a very specific format
<p>I have a data-frame df -</p> <pre><code> a b c 0 1 5 0 1 1 6 1 2 1 7 0 3 3 8 0 </code></pre> <p>need to group it based on column-c like -</p> <pre><code> a b c 0 [1, 1] [5, 6] [0, 1] 1 1 7 0 2 3 8 0 </code></pre> <p>It can be done through...
<p>Not sure but do you need this?</p> <pre><code>k = 0 temp = [] for i in df.c: if i == 0: k+=1 temp.append(k) df = df.groupby(temp).agg(list) </code></pre> <p><strong>Output:</strong></p> <pre><code> a b c 1 [1, 1] [5, 6] [0, 1] 2 [1] [7] [0] 3 [3] [8] [0] ...
pandas
1
15,776
34,780,630
Count all categories in pandas data frame and add their values
<p>I've got a data frame that looks something along these lines:</p> <pre><code> Dog_breed Dog_name Points ============================================================ Monday Pug George 12 Tuesday Poodle Fido -15 Wednesday ...
<p>You're looking for pandas' <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="noreferrer"><code>groupby</code></a>.</p> <pre><code>df.groupby('Dog_breed').agg(['count', 'sum']) </code></pre> <p>Read the following for a firmer understanding: <a href="http://pandas.pyd...
python|pandas|dataframe
7
15,777
65,123,413
Can I force Python to return only in String-format when I concatenate two series of strings?
<p>I want to concatenate two columns in pandas containing mostly string values and some missing values. The result should be a new column which again contain string values and missings. Mostly it just worked fine with this:</p> <pre><code>df['newcolumn']=df['column1']+df['column2'] </code></pre> <p>Most of the values i...
<p>Type conversion is not required in this case. You can simply use</p> <pre class="lang-py prettyprint-override"><code>df[&quot;newcolumn&quot;] = df.apply(lambda x: f&quot;{str(x[0])}{str(x[1])}&quot;, axis = 1) </code></pre> <p>Output: <a href="https://i.stack.imgur.com/dMbup.png" rel="nofollow noreferrer"><img src=...
python|pandas|string|concatenation|scientific-notation
0
15,778
65,357,797
Importing Numpy Failes
<p>Numpy fails to import.</p> <h3>Steps to reproduce:</h3> <p>Installed by PIP Version = <code>1.19.3</code> <br> Python version = <code>3.9.1</code> <br></p> <p>OS = <code>Wndows 10 , Version 2004</code> <br></p> <h3>Error message:</h3> <pre><code>ImportError: cannot import name 'dtype' from partially initialized mod...
<p>Re-Installing fixed it. As usual</p>
python-3.x|numpy|import
0
15,779
65,301,212
Find common sequence of elements in list of lists
<p>I have list of lists containing Id's as following-</p> <pre><code>[[45, 41, 20, 25, 78], [54, 12, 45, 36, 59], [45, 12, 45, 41, 88], [74, 85, 41, 20, 25], [54, 45, 36, 59], [74, 20, 25]] </code></pre> <p>Problem 1: I need all the lists having same prefix(list starting with same number) in one list. Desired out...
<p>You can use <code>itertools.groupby</code> For Problem 1:</p> <pre><code>from itertools import groupby orig_list = [[45, 41, 20, 25, 78], [54, 12, 45, 36, 59], [45, 12, 45, 41, 88], [74, 85, 41, 20, 25], [54, 45, 36, 59], [74, 20, 25]] sorted_list = sorted(orig_list, key=lambda l: l[0]) list1 = [list(g) for _,...
python|pandas|list
1
15,780
49,975,629
Error while importing Tensorflow. A dynamic link library (DLL) initialization routine failed
<p>I am using tensorflow CPU for a while and decided to install tf gpu and now when i try to import tf it gives me this error. My system specs are: Intel Xeon w5320 2.8 Ghz 8threads. 10 GB Ram Nvidia GTX 1050 2GB I have installed latest drivers, Cuda 9.0 and cuDNN v7.1.3 (April 17, 2018), for CUDA 9.0. Any kind of help...
<p><a href="https://github.com/rohit-patel/Install_Instructions-Win10-Deeplearning-Keras-Tensorflow" rel="nofollow noreferrer">https://github.com/rohit-patel/Install_Instructions-Win10-Deeplearning-Keras-Tensorflow</a> I followed this post precisely and got it working. Actual problem was i didn't have a CPU with AVX an...
python|python-3.x|tensorflow
2
15,781
64,081,308
Initialize a np array randomly with a determined quantity of 1's and 0's
<p>I want to initialize an array randomly with a certain quantity of 1's and 0's. The following code is all I've got. I just managed to initialize it with a random quantity of 1's and 0's, but I'd like to do it, for example (knowing that the matrix is 10x10) with 25 1's and 75 0's.</p> <pre><code>matrix = np.random.ran...
<p>Easy: make an array of the elements you want in order, then shuffle:</p> <pre><code># start with 100 zeroes arr = np.zeros((100,)) # change 25 of them to 1s arr[:25] = 1 # shuffle the array to put all the elements in random positions np.random.shuffle(arr) # reshape to final desired shape arr = arr.reshape((10,10)) ...
python|arrays|numpy|random
6
15,782
63,767,432
Sending parameters to Keras Tuner model- builder function
<p>I want to send parameters to <a href="https://github.com/keras-team/keras-tuner" rel="nofollow noreferrer">Keras Tuner</a>'s <strong>model-builder</strong> function to parameterize</p> <ul> <li>number of layers dense/dropout,</li> <li>number of neurons,</li> <li>activation,</li> <li>and optimizer</li> </ul> <p>for h...
<p>If you have an existing hypermodel and you want to search over only a few parameters (such as the <code>learning_rate</code>), you can pass a hyperparameters argument to the tuner constructor. You also need to set <code>tune_new_entries=False</code> to specify that parameters that you didn't list should not be tuned...
machine-learning|tensorflow2.0|recurrent-neural-network|hyperparameters|keras-tuner
2
15,783
63,970,483
How to check if an array contains all the elements of another array? If not, output the missing elements
<p>I need to check if an array A contains all elements of another array B. If not, output the missing elements. Both A and B are integers, and B is always from 0 to N with an interval of 1.</p> <pre><code>import numpy as np A=np.array([1,2,3,6,7,8,9]) B=np.arange(10) </code></pre> <p>I know that I can use the following...
<p>IIUC you can try the following and assuming that B always is an &quot;index&quot; list:</p> <pre class="lang-py prettyprint-override"><code>[i for i in B if i not in A] </code></pre> <p>The output would be : [0, 4, 5]</p> <h3>Best way to do it with numpy</h3> <p>Numpy actually has a function to perform this : <a hre...
python|numpy
3
15,784
46,995,204
Deletes a specific cell while moving the line to the left
<p>I have a data frame where the error has crept. Example:</p> <pre><code> data1 data2 data3 0 111 555 1 222 666 2 A 333 777 3 444 888 </code></pre> <p>I would like to remove the letter 'A' from the column 'data1' while simultaneously moving all the rest of the row 2 to the lef...
<p>Here is the one of the solution .</p> <pre><code>df=df.apply(pd.to_numeric,errors='coerce').\ apply(lambda x: sorted(x, key=pd.isnull), 1).fillna('') df Out[931]: data1 data2 data3 0 111.0 555.0 1 222.0 666.0 2 333.0 777.0 3 444.0 888.0 </code></pre>
python|pandas
4
15,785
46,852,741
Python: Storing values in a 3D array to csv
<p>I have the follwoing problem. I have a 3D array like <code>matrix = np.zeros((30,30,100))</code> where every entry is a coordinate and gets a value. So <code>matrix [0][0][0]</code> is the coordinate x=0,y0,z=0 and has a value of 0. Now i want to store all the values in a csv like this where the first 3 rows are th...
<p>You could use pandas, it can both reshape the array and save it as csv.</p> <pre><code>import numpy as np import pandas as pd # create an example array a = np.arange(24).reshape([2,3,4]) # convert it to stacked format using Pandas stacked = pd.Panel(a.swapaxes(1,2)).to_frame().stack().reset_index() stacked.columns ...
python|arrays|csv|numpy
9
15,786
32,743,587
Use pythons complex type in numpy-array
<p>For example when I do this:</p> <pre><code>In : b = 0.05 + 0j In : b Out: (0.05+0j) In : type(b) Out: complex </code></pre> <p>Okay as expected. Now if I do this inside an numpy-array:</p> <pre><code>In : a = numpy.array([0,0,0], dtype = complex) In : a[1] = 0.05 In : a[1] Out: (0.050000000000000002775557561563+0...
<p>There's no loss of precision; 0.05 = 5/100 isn't precisely representable in binary floating point (the denominator should be a power of 2 to allow precise representation).</p> <p>Perhaps more convincing is the output of this</p> <pre><code>import numpy b = 0.05 + 0j a = numpy.array((b, )) print(b, a[0]) print(b == a...
python|numpy
1
15,787
38,626,704
Filling NaN values in a Pandas DataFrame conditionally on the values of non-NaN columns
<p>I have a question regarding filling <code>NaN</code> values in a Pandas <code>DataFrame</code> conditionally on the values of non-<code>NaN</code> columns. To illustrate:</p> <pre><code>import numpy as np import pandas as pd print pd.__version__ 0.18.1 df = pd.DataFrame({'a': [1, 0, 0, 0, 1], '...
<p>You may set <code>a, b, c</code> columns as a multi-index and use pandas <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#merging-together-values-within-series-or-dataframe-columns" rel="nofollow"><code>combine_first</code></a>.</p> <p>First, you would need a frame of defaults. In your setting it c...
python|pandas
1
15,788
38,832,218
How to 'unpack' a list or tuple in Python
<p>I'm writing a Python program to play Tic Tac Toe, using Numpy arrays with "X" represented by <code>1</code> and "O" by <code>0</code>. The class includes a function to place a mark on the board:</p> <pre><code>import numpy as np class Board(): def __init__(self, grid = np.ones((3,3))*np.nan): self.grid...
<p>With Numpy, there's a difference between indexing with lists and multi-dimensional indexing. <code>self.grid[[0,1]]</code> is equivalent to concatenating <code>self.grid[0]</code> and <code>self.grid[1]</code>, each 3x1 arrays, into a 3x2 array.</p> <p>If you use tuples instead of lists for indexing, then it will b...
python|numpy
3
15,789
38,729,550
Apply condition on pandas columns to create a boolen indexing array
<p>I want to drop specific rows from a pandas dataframe. Usually you can do that using something like</p> <pre><code>df[df['some_column'] != 1234] </code></pre> <p>What <code>df['some_column'] != 1234</code> does is creating an indexing array that is indexing the new df, thus letting only rows with value <code>True</...
<p>What you're looking for is <code>isin()</code></p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 2], [1, 3], [4, 6],[5,7],[8,9]], columns=['A', 'B']) In[9]: df Out[9]: df A B 0 1 2 1 1 3 2 4 6 3 5 7 4 8 9 mydict = {1:'A',8:'B'} df[df['A'].isin(mydict.keys())] Out[11]: A B 0 1 2 1 1 3...
python|pandas
2
15,790
38,574,222
OneHotEncoded features causing error when input to Classifier
<p>I’m trying to prepare data for input to a Decision Tree and Multinomial Naïve Bayes Classifier.</p> <p>This is what my data looks like (pandas dataframe)</p> <pre><code>Label Feat1 Feat2 Feat3 Feat4 0 1 3 2 1 1 0 1 1 2 2 2 2 1 1 3 3 ...
<p>First, you have to swap <code>chk</code> and <code>Y</code> consider <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.cross_val_score.html" rel="nofollow"><code>cross_val_score</code></a> documentation. Next, you didn't specify what is <code>Y</code> so I hope it's a 1d-array. And t...
python|pandas|machine-learning|scikit-learn|categorical-data
1
15,791
62,967,073
Fetch non-empty cells from .xls file using pandas
<p>i am new to python. i want to fetch the values from the cells &amp; empty cells should be discarded. i want to loop through rows &amp; columns &amp; assign to list</p> <pre><code>import pandas as pd from pandas import ExcelFile from pandas import ExcelWriter df=pd.read_excel('16Junedata_03062020_80163767_action_030...
<p>You can get the list of non NaN values using below code, this is only for one column:</p> <pre><code>zone_id_updated = [] for item in df.zone_id.iteritems(): if pd.isna(item[1])==False: zone_id_updated.append(item[1]) </code></pre> <p>Similarly can be done for other columns.</p>
python|pandas
0
15,792
63,060,824
Finding distinct values of a column from a sheet of excel file in python
<blockquote> <p><strong>How can I find the first column's distict values from sheet3 ?</strong></p> </blockquote> <pre><code>import sys import pandas as pd excel_file = &quot;dataset.xlsx&quot; datasets = pd.ExcelFile(excel_file) sheet0 = pd.read_excel(datasets, 'Title Sheet') sheet3 = pd.read_excel(excel_file, shee...
<p>To get the unique values of the specific sheet, you can do:</p> <pre><code>unq = sheet3.iloc[:,0].unique() print(unq) </code></pre> <p>To get the count of unique values, you can do:</p> <pre><code>unq = sheet3.iloc[:,0].nunique() print(unq) </code></pre>
excel|pandas|python-3.8
1
15,793
67,619,706
Replace for decode errors in read_csv
<p>I am converting a stream to csv using the following code:</p> <pre><code> req_cont = requests.get(csvfile, headers=headers).content inp_df = pd.read_csv( BytesIO(req_cont) ) </code></pre> <p>read_csv is throwing a unicode error. Streams with different encodings appear so I can not guess what is th...
<p>You can detect what is the encoding of the stream and as soon as you correctly detect it, try to import full stream</p> <pre><code>lst = ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp273', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737' , 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861...
python|python-3.x|pandas|python-unicode|bytesio
0
15,794
67,818,200
Close a silent figure opened with pandas
<p>I plot multiple figures in <code>pandas</code> and save them to a file with:</p> <pre><code>import pandas as pd for i in range(30): # loop example ax = df.plot(x=date_name, y=metric, legend=False, figsize=(4.5, 3)) ax.set_title(title, fontdict={'fontsize': 14, 'fontweight': 'medium'}) ax.set(xlabel=Non...
<ol> <li>The code that you used was OK and should have solved this problem.</li> </ol> <pre><code> import matplotlib.pyplot as plt for i in range(30): # loop example ... plt.close(ax.get_figure()) </code></pre> <ol start="2"> <li><p>In case you still face issues after this, try to comment out lines th...
python|pandas|matplotlib
1
15,795
31,785,317
Construct pandas DataFrame from nested dictionaries having list as item
<p>I have several dictionary data and I want to convert to Pandas DataFrame. However, due to unnecessary key '0' (for me), I've obtained undesirable format of DataFrame when I convert these dict to DataFrame. Actually, these dicts are short part of whole data.</p> <pre><code>dict1 = {1: {0: [-0.022, -0.017]}, ...
<p>You should simply drop a level from your nested dict to make life easier. The code below drops the unnecessary part of your dicts and concatenates the dataframes from each of the dicts together.</p> <pre><code>all_dicts=[dict1,dict2,dict3] df=pd.concat([pd.DataFrame({k:v[0] for k,v in d.items()}) for d in all_dict...
python|list|pandas|dataframe
0
15,796
31,820,578
How to plot stacked event duration (Gantt Charts)
<p>I have a Pandas DataFrame containing the date that a stream gage started measuring flow and the date that the station was decommissioned. I want to generate a plot showing these dates graphically. Here is a sample of my DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = {'ind...
<ul> <li>I think you are trying to create a Gantt plot.</li> <li><a href="https://stackoverflow.com/q/18066781/7758804">How to create a Gantt plot</a> suggests using <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hlines.html" rel="nofollow noreferrer"><code>hlines</code></a></li> <li>Tested in <co...
python|pandas|matplotlib|time-series|gantt-chart
23
15,797
31,910,407
Numpy.argsort - can't see what's wrong
<p>I am trying to sort a numpy array using the argsort function.</p> <p>Unfortunately this is not working and I can't see why :(</p> <p>The code is:</p> <pre><code>import numpy as np distance = np.array([38.26, 33.01, 32.33, 30.77, 37.96, 44.37, 32.72, 36.56, 27.77, 33.62, 42.85, 34.6 , 32.04, 2...
<p><code>distance.argsort()</code> returns an array of indices. The <code>ith</code> index does <em>not</em> tell you the rank of the <code>ith</code> element in <code>distance</code>. Rather, the <code>ith</code> index tells you that the <code>ith</code> element in the sorted array is <code>distance[i]</code>.</p> <p...
python|arrays|sorting|numpy
14
15,798
41,309,972
input dimension reshape in Tensorflow conolutional network
<p>In the expert mnist tutorial in tensorflow website, it have something like this :</p> <pre><code>x_image = tf.reshape(x, [-1,28,28,1]) </code></pre> <p>I know that the reshape is like </p> <pre><code>tf.reshape(input,[batch_size,width,height,channel]) </code></pre> <p>Q1 : why is the batch_size equals -1? What d...
<blockquote> <p>Q1 : why is the batch_size equals -1? What does the -1 means?</p> </blockquote> <p>-1 means "figure this part out for me". For example, if I run:</p> <pre><code>reshape([1, 2, 3, 4, 5, 6, 7, 8], [-1, 2]) </code></pre> <p>It creates two columns, and whatever number of rows it needs to get everything...
tensorflow|deep-learning|dimensions
1
15,799
41,487,069
Build error with TensorFlow Android demo
<p>Getting protobuf error while compiling TensorFlow Android demo Using Android Studio on OSX.</p> <p>Steps taken:</p> <ol> <li><p>installed Bazel upgraded view brew</p></li> <li><p>Cloned tensorflow repo with --recursive flags.</p></li> <li><p>run .configure .</p></li> <li><p>run the project</p></li> </ol> <blockqu...
<p>You'll need to also edit your WORKSPACE file with your NDK and SDK settings according to the directions at <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android</a>. /bin/fa...
android|tensorflow
1