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
367,000
41,696,355
Resample/Upsample Period Index and using both extreme time "edges" of the data
<p>I have the following DataFrame, a weekly price data timeserie with a Period Index. Let's call it <code>df</code></p> <pre><code> timestamp open high low close volume timestamp 2009-02-01/2009-02-07 733442.166309 830.540773 832.5869...
<p>Since you want to include the <code>start_time</code> corresponding to the first <code>PeriodIndex</code> and <code>end_time</code> corresponding to the last one, the keyword arguments present in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer">...
python|parsing|pandas
1
367,001
42,007,401
How to delete rows from a pandas DataFrame with method chaining?
<p>Does pandas have an analogue to dplyr's filter() operation? basically I'd like to be able to remove rows based on a predicate.</p> <p>I can of course do <code>df = df[condition]</code>, but that doesn't compose as nicely as method chaining.</p>
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>query</code></a></p> <p>Consider the dataframe <code>df</code></p> <pre><code>df = pd.DataFrame( np.random.randint(-5, 6, (10, 10)), columns=list('ABCDEFGHIJ')) df A B C D...
python|pandas|method-chaining
2
367,002
41,857,337
Deleting DataFrame row in Pandas based on number of values in the table
<p>I have the following DataFrame:</p> <pre><code>N numbers n1 1,2,3 n2 4,6,2 n3 1 n4 2,5 n5 6 </code></pre> <p>I need to remove the rows where <code>numbers</code> have only one value. What's the most efficient way to do this?</p>
<p>Here's one way, by splitting the string and finding <code>len</code> of list.</p> <pre><code>In [226]: df Out[226]: N numbers 0 n1 1,2,3 1 n2 4,6,2 2 n3 1 3 n4 2,5 4 n5 6 In [227]: df[df.numbers.str.split(',').apply(len) &gt; 1] Out[227]: N numbers 0 n1 1,2,3 1 n2 4,6,2 3 n4...
python|pandas
4
367,003
41,993,598
How to add a column to pandas dataframe based on time from another column
<p>I am trying to add a column into a <code>pandas dataframe</code>, that inserts <code>Morning</code>, <code>Evening</code> or <code>Afternoon</code>, based on the time slots that I choose.</p> <p>The code I am trying is as follows:</p> <pre><code>df_agg['timeOfDay'] = df_agg.apply(lambda _: '', axis=1) for i in ran...
<p><strong><em><code>pandas</code></em></strong><br> use <code>pd.cut</code> to break it by bins and give labels. This method makes it trivial to create more granular time slots as well</p> <pre><code>df_agg.assign( timeOfDay=pd.cut( df_agg.time_stamp.dt.hour, [-1, 12, 17, 24], labels=['Mo...
python|pandas
3
367,004
41,908,745
Tensorflow: How to convert a rank 1 tensor into a rank 2 tensor
<p>I'm trying to make a simple neural network and I have a simple question: How do I convert a tensor which is rank 1 to a tensor which is rank 2?</p>
<p>You might be looking for <code>tf.expand_dims()</code> <a href="https://www.tensorflow.org/api_docs/python/tf/expand_dims" rel="noreferrer">https://www.tensorflow.org/api_docs/python/tf/expand_dims</a></p>
python|tensorflow|neural-network|rank
5
367,005
41,714,743
dicom image resizing before converting to numpy array
<p>I have thousands of dicom images in a folder. I read them with <code>pydicom</code> like this</p> <pre><code>import numpy as np import dicom folder = "/images" imgs = [dicom.read_file(folder + '/' + s) for s in os.listdir(folder)] </code></pre> <p>I then want to stack all images as a numpy array, like this:</p> ...
<p>If you stored then as a list of numpy arrays then they can be different size. Otherwise use <code>scipy</code> zoom function,</p> <pre><code>import numpy as np import dicom import scipy xsize = 1000; ysize = 1000 folder = "/images" data = np.zeros(xsize, ysize, len(os.listdir(folder))) for i, s in enumerate(os.lis...
python|image|numpy|dicom|pydicom
1
367,006
42,012,729
convert string date to numeric for all values in column using pandas python
<p>I need to transform "Jan 11, 2017 9:00 PM" to 2017-01-11 21:00:00 for all values in ColumnA.</p> <p>Is there an easy way / function for doing this in python using pandas?</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html#pandas.to_datetime" rel="nofollow noreferrer"><code>to_datetime</code></a> seems to handle this just fine:</p> <pre><code>In [6]: pd.to_datetime('Jan 11, 2017 9:00 PM') Out[6]: Timestamp('2017-01-11 21:00:00') </code></pre> <p>...
python|string|date|pandas|numeric
1
367,007
41,929,493
Numpy array of distances to list of (row,col,distance)
<p>I have an nd array that looks as follows: </p> <pre><code>[[ 0. 1.73205081 6.40312424 7.21110255 2.44948974] [ 1.73205081 0. 5.09901951 5.91607978 1. ] [ 6.40312424 5.09901951 0. 1. 4.35889894] [ 7.21110255 5.91607978 1. 0. 5.09901951] [ 2.4...
<p><code>squareform</code> does all this. Read the docs and experiment. It works in both directions. If you give it a matrix it returns the upper triangle values (condensed form). If you give it those values, it returns the matrix.</p> <pre><code>In [668]: M Out[668]: array([[ 0. , 0.1, 0.5, 0.2], [ 0.1...
python|python-3.x|numpy|scipy|pdist
4
367,008
41,742,153
Why tensorflow equal gives incorrect result
<p>The <code>tf.equal()</code> function seems to be weired when we apply a CNN network. In the case below, <code>tf.equal()</code> returns incorrect result. </p> <pre><code>with tf.Graph().as_default(): images, labels = inputs("./test_data", [64, 64], 10, True) logits = inference(images, 2, 1...
<p>After the thinking, there is one possibility that each time I call <code>sess.run()</code> the <code>file_queue</code> would read shuffled images and labels so that the result is weired.</p>
python|tensorflow
1
367,009
41,826,434
NameError: name 'x_train' is not defined
<p>i'm new to this but can anyone tell me what's wrong it? I'm actually trying to do a predictive analysis(linear regression graph) based on the data i have in the excel . However , my graph isn't plotted out and i also faced this error. </p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot a...
<p>You make use of the variable <code>x_train</code> twice before you ever define it. You need to define it first, then use it.</p> <pre><code> x_train = np.array(x_train).reshape(len(x_train), -1) # ^^^^^^^ ^^^^^^^ ^^^^^^^ # | | | # | +------------...
python|numpy|matplotlib|machine-learning|scikit-learn
6
367,010
41,926,841
Using apply method on pandas series getting TypeError 'Series' objects are mutable, thus they cannot be hashed
<p>I have two data frames <code>D1</code> and <code>D2</code>. What I want to achieve is for any column pairs in <code>D1</code> and <code>D2</code> which are non-int and non-float type, I want to compute a distance metric using the formula </p> <pre><code> |A intersect B|/ |A union B| </code></pre> <p>I first define...
<p>So after floundering around, and finding exactly where the error occurs, and checking the <code>apply</code> docs, I've deduced that you need to call <code>apply</code> thusly:</p> <pre><code> D2.apply(jaccard_d, args=(D1[col],)) </code></pre> <p>Instead you were using</p> <pre><code> D2.apply(jaccard_d, axis=D1[...
python|pandas|numpy
2
367,011
42,087,099
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (9,)
<p>In this part of code: </p> <pre><code>for k, v in Candidates.iteritems(): Device = XDevice[XDevice[:, 1] == k, np.array([2, 3, 4, 5, 6, 7, 8, 9, 10])] </code></pre> <p>I've this IndexError: </p> <pre><code>shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (9,) </code></pr...
<p>Seems like you cannot do the selection on both dimensions at the same time !</p> <p>Split it in two lines :</p> <pre><code>for k, v in Candidates.iteritems(): Device_ = XDevice[XDevice[:, 1] == k,:] Device = Device_[:,np.array([2, 3, 4, 5, 6, 7, 8, 9, 10]) </code></pre>
python|arrays|numpy|array-broadcasting
0
367,012
41,720,910
What python data structure should I use to store multi-dimensional fantasy football data
<p>I have a list containing data on 600 or so football (soccer) players. Each players in the list is stored as a dictionary, with each attribute stored as for example</p> <pre><code>{'goals scored': 5} </code></pre> <p>In the dictionary as the total player stats over the course of the season. However there is also a ...
<blockquote> <p>"However I'm not sure whether this will translate well into a pandas dataframe, which is ultimately where I would like to perform most of my analysis."</p> </blockquote> <p>See: <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.io.json.json_normalize.html" rel="nofollo...
python|database|pandas
1
367,013
41,744,126
pandas apply to attribute instead of function
<p>Is it possible to use df.apply to get an attribute as opposed to running a function? I want to retrieve the year from a date to perform a groupby. For example ..</p> <pre><code>import pandas as pd import datetime import numpy as np df = pd.DataFrame({'date': [datetime.datetime(2010,1,1)+datetime.timedelta(days=i*1...
<p>You will be happy to know there is an entire set of functionality built to provide an abundance of date attributes. You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor" rel="nofollow noreferrer"><code>dt</code></a> accessor to get many datetime attributes. It can only be used...
python|pandas|python-datetime
4
367,014
7,900,261
Why do I have such a distortion with pygame sndarray objects?
<p>I'm using sndarray from pygame to play with basic sound synthesis. The problem is Whatever I do, I have an awful distortion on the generated sound.</p> <p>In the code I'll provide at the end of the question, you'll see a bunch of code coming from here and there. Actually, the main stuff comes from a MIT's source I ...
<p>Presuming you have some initialization code like</p> <pre><code>pygame.mixer.pre_init(44100, -16, 2) # 44.1kHz, 16-bit signed, stereo </code></pre> <p>sndarray expects you to be passing it 16-bit integer arrays, not float arrays.</p> <p>Your "peak" value needs to make sense given the 16-bit integer representation...
python|audio|numpy|pygame
2
367,015
7,841,017
Using Pylab to create a plot of a line and then getting the rasterized data from the line
<p>I am trying to get the rasterized line data from a pylab plot function. My code is like so:</p> <pre><code>fitfunc = lambda p, x: p[0] + p[1] * sin(2 * pi * x / data[head[0]].size + p[2]) errfunc = lambda p, x, y: fitfunc(p, x) - y data = np.genfromtxt(dataFileName, dtype=None, delimiter='\t', names=True) xAxisSe...
<pre><code>import numpy as np import matplotlib.pyplot as plt N=4 x=np.linspace(0, 10, N) y=np.cumsum(np.random.random(N) - 0.5) line=plt.plot(x,y)[0] path=line._path </code></pre> <p>These are the original (x,y) data points:</p> <pre><code>print(path.vertices) # [[ 0. 0.08426592] # [ 3.33333333 0.1420...
python|matlab|numpy|scipy|matplotlib
2
367,016
8,218,608
scipy: savefig without frames, axes, only content
<p>In numpy/scipy I have an image stored in an array. I can display it, I want to save it using <code>savefig</code> <em>without</em> any borders, axes, labels, titles,... Just pure image, nothing else.</p> <p>I want to avoid packages like <code>PyPNG</code> or <code>scipy.misc.imsave</code>, they are sometimes proble...
<p><strong>EDIT</strong></p> <p>Changed <code>aspect='normal</code> to <code>aspect='auto'</code> since that changed in more recent versions of matplotlib (thanks to @Luke19).</p> <hr> <p>Assuming : </p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt </code></pre> <p>To make a fi...
python|image|numpy|matplotlib|scipy
132
367,017
37,968,785
Merging two DataFrames
<p>I have 2 <code>DataFrames</code> which I would like to merge. I have looked at the documentation and tried to perform the following operation but an getting confused as to how to do it. Like I said I have 2 <code>DataFrames</code>:</p> <pre><code>df1: id name type currency 0 BTA.S Applewood Hard ...
<p>The error message indicates that <code>df2</code> is of type <code>pd.Series</code>. You need to convert <code>df2</code> <code>.to_frame()</code> as <code>.merge()</code> needs a <code>pd.DataFrame()</code> input (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noref...
python|pandas|numpy
43
367,018
37,796,916
Pandas read sql integer became float
<p>I met a problem that when I use pandas to read Mysql table, some columns (see 'to_nlc') used to be integer became a float number (automatically add .0 after that). Can anyone figure it out? Or some guessings? Thanks very much!</p> <p><a href="https://i.stack.imgur.com/1obo8.png" rel="noreferrer"><img src="https://i...
<p>Problem is your data contains <code>NaN</code> values, so <code>int</code> is automatically cast to <code>float</code>.</p> <p>I think you can check <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="noreferrer">NA type promotions</a>:</p> <blockquote> <p>When introducing ...
python|mysql|pandas|int
19
367,019
37,982,699
Count Distinct Group By Pandas Python
<p>Here's some sample data - </p> <pre><code>ID Owner Activity 1 A W1 1 A W2 1 B W3 1 C W4 2 C W5 2 C W6 2 D W7 3 A W8 3 B W9 </code></pre> <p>I want number of owners per ID. Output will be - </p> <pre><code>ID Number of Owners 1 3 2 2 3 2 </code></pre> <p>How can I do ...
<pre><code>df.groupby('ID').Owner.nunique() </code></pre>
python|pandas|group-by|distinct
4
367,020
38,047,366
Get the number index through boolean opearator in python-pandas
<p>Now I can get the expected value with boolean operator:</p> <pre><code>mask1 = df.val &gt; 10 mask2 = df.val &lt; 5 c1 = df[mask1] c2 = df[mask2] </code></pre> <p>And I wish to get the slice between each point in <code>c1</code> and <code>c2</code>, that is, given a data frame <code>df</code> as below:</p> <pre><...
<p>I think you can use:</p> <pre><code>c1 = df[mask1].index c2 = df[mask2].index print (c1) Int64Index([1, 4], dtype='int64') print (c2) Int64Index([3, 7], dtype='int64') print (df[c1[0]:c2[0]]) val 1 12 2 5 print (df[c1[1]:c2[1]]) val 4 11 5 9 6 9 </code></pre> <p>It is same as:</p> <pre><code...
python|pandas|indexing|dataframe|conditional-statements
2
367,021
37,911,669
OpenCV HSV value changes depending on location on the screen/camera
<p>I'm pretty new to all programming and have been trying to get a grasp on Python (2.7.6), OpenCV, and ROS to be able to use a neural network in a robot. </p> <p>I am now stuck in an OpenCV (2.4.8) problem with getting the correct HSV-values, in short, it suddenly changes from red (around 5 for Hue) or blue (about 11...
<p>After two days of struggling with this problem I finally found where I went wrong:</p> <p>The coordinates returned by this:</p> <pre><code>(x, y), radius = cv2.minEnclosingCircle(cnt) </code></pre> <p>Are not x and y coordinates but a row and column index. So when I moved my camera or the circle from left to rig...
python|opencv|numpy|image-processing|computer-vision
1
367,022
38,045,735
Pandas: How to read an excel file defining several columns to be multi indexes?
<p>I have a data frame that every row contains an office location object with several attribute like <code>Global Region</code>,<code>Primary Function</code>, and several energy consumption data as numerical values followed. The names of all columns is like below: </p> <pre><code>['Global Region', 'Primary Function...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow noreferrer"><code>read_excel</code></a> with parameter <code>index_col</code> which contains <code>list</code> of positions of necessary columns:</p> <p>Sample:</p> <pre><code>df = pd.read_excel('test.x...
python|excel|date|pandas|dataframe
2
367,023
37,812,325
pandas - scatter plot with different color legend for each point
<p>Starting from the following example:</p> <pre><code>fig, ax = plt.subplots() df = pd.DataFrame({'n1':[1,2,1,3], 'n2':[1,3,2,1], 'l':['a','b','c','d']}) for label in df['l']: df.plot('n1','n2', kind='scatter', ax=ax, s=50, linewidth=0.1, label=label) </code></pre> <p>what I obtained is the following scatterp...
<p>The following method will create a list of colors as long as your dataframe, and then plot a point with a label with each color:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors import numpy as np import pandas as pd fig, ax = plt.subplots() df = pd.Data...
python|pandas|matplotlib
9
367,024
37,734,907
Shifting a data array elements in TensorFlow Variable in a neat way
<p>I have set of variables in TensorFlow, say <code>x1, x2,..., x9</code><br> I am trying to shift the data of the variables in such a way that <code>x(i+1)</code> shifts to <code>x(i)</code> and eventually <code>x1</code> is lost and <code>x9</code> is the same. What I have tried is to create a dictionary of operation...
<p>Have you thought about rewriting your code as a sequence of slice operations? In general TensorFlow works best if you can express what you need to do as a series of operations on immutable objects, rather than changing variables. You'd do something like <code>tf.slice(n0, [1], [-1])</code> to pull out repeated seque...
arrays|variables|tensorflow|tensorboard
1
367,025
37,669,714
Python matrix represented as (40000,)
<p>I have seen and executed a python program where a matrix has been sliced into a column vector using <code>a[:,j]</code> and passed into a function. The column vector has dimensions <code>40000x1</code>. While tracing the output, I printed the dimensions of <code>a</code> in the function and it printed <code>(40000,)...
<p>I am assuming that you are referring to the <a href="https://docs.scipy.org/doc/numpy-dev/user/quickstart.html" rel="nofollow noreferrer"><code>numpy</code></a> package. There are other array packages available for Python, but that seems to be the most popular one.</p> <p><code>numpy</code> deals with multidimension...
python|numpy|matrix
1
367,026
37,918,586
How to add a new row to an existing DataFrame which is the sum of two rows?
<p>I have a DataFrame looks as follow:</p> <pre><code> Name1 Name2 Val1 1.2 2.2 Val2 2.3 4.2 </code></pre> <p>What I want is as follow:</p> <pre><code> Name1 Name2 Val1 1.2 2.2 Val2 2.3 4.2 Val3 0.52 0.52 </code></pre> <p>The values in <code>Val3</code> is <code>Val1/Vals2<...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label" rel="nofollow"><code>.loc</code> to grab each row individually</a> and divide them. Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow"><code>.append</code></a> to a...
python|pandas|dataframe
4
367,027
37,711,642
plot pandas period_range with matplotlib - set freq of axis
<p>I got a pandas DataFrame with values for time spans with variable lenths. I want to plot a horizontal line for the value of each timespan with the length of the timespan. Therfore, I converted the timespan to an PeriodIndex by</p> <pre><code>ax0=fig.add_axes([.16,.2,0.8,.7]) ax0.plot_date(data['periodIndex'], data[...
<p>I constructed data to demonstrate what I believe was your question.</p> <p>If you fill in a dataframe with data for only a specific range of the index and then plot it, it will only generate a line for when that data was not null.</p> <pre><code>import pandas as pd import numpy as np ts = pd.date_range(end='2016-...
python|pandas|matplotlib
1
367,028
37,686,139
TFLearn pip installation bug
<p>I've tried installing tflearn through pip as follows </p> <p><code>pip install tflearn</code></p> <p>and now when I open python, the following happens:</p> <p><code>&gt;&gt;&gt; import tflearn Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "//anaconda/lib/python2.7/sit...
<p>The <code>variance_scaling_initializer()</code> function was <a href="https://github.com/tensorflow/tensorflow/commit/eca3854bc5e4e7d8fa4db9f487c78ccac37b6c23" rel="nofollow">added on April 19th</a>, which means that it wasn't included in version 0.8.0rc0, and you need to upgrade to a newer version of TensorFlow. If...
python|tensorflow
3
367,029
37,699,684
Python Pandas CSV import / Unicode woes
<p>I am working with message board posts (contained in <code>CSV</code> files), trying to clean data/etc, before training classification models. </p> <p>Things were going well, until I got:</p> <blockquote> <p>TypeError: 'float' object is not iterable</p> </blockquote> <p>in response to the line:</p> <pre><code>l...
<p>I think you need check <code>NaN</code> values in your <code>DataFrame</code>, which is created from <code>csv</code>. You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html" rel="nofollow"><code>isnull</code></a> with <a href="http://pandas.pydata.org/pandas-docs/sta...
python|csv|pandas|classification
1
367,030
37,972,785
Retriving all the rows from a csv file and plotting
<p>I need to retrieve the rows from a csv file generated from the function:</p> <pre><code>def your_func(row): return (row['x-momentum']**2+ row['y-momentum']**2 + row['z-momentum']**2)**0.5 / row['mass'] columns_to_keep = ['#time', 'x-momentum', 'y-momentum', 'z-momentum', 'mass'] dataframe = pd.read_csv("./flas...
<p>you can adjust <code>pd.options.display.max_rows</code> option, but it won't affect your plots, so your plots will contain all your data</p> <p>demo:</p> <pre><code>In [25]: df = pd.DataFrame(np.random.randint(0,100,size=(10, 3)), columns=list('ABC')) In [26]: df Out[26]: A B C 0 93 76 5 1 33 70 12...
python|csv|pandas|plot
1
367,031
31,290,738
Create a triangular mesh using Delaunay methods
<p>I'm trying create a triangular mesh using python. As I know the boundary points, I think the delaunay method is more appropriated. I tried use scipy. the code is very simple</p> <pre><code>from scipy.spatial import Delaunay pixelpoints = np.transpose(np.nonzero(binaryImage)) tri = Delaunay(pixelpoints) import matpl...
<p>You can easily remove additional triangles using the <code>Polygon.IsPointInside(tCentroid)</code> where <code>tCentroid</code> is the triangle centroid. <code>IsPointInside()</code> can be derived by this: <a href="http://geomalgorithms.com/a03-_inclusion.html" rel="nofollow">http://geomalgorithms.com/a03-_inclusio...
python|numpy|scipy|triangulation|delaunay
0
367,032
31,239,839
Index Value of Last Matching Row Python Panda DataFrame
<p>I have a dataframe which has a value of either 0 or 1 in a "column 2", and either a 0 or 1 in "column 1", I would somehow like to find and append as a column the index value for the last row where Column1 = 1 but only for rows where column 2 = 1. This might be easier to see than read:</p> <pre><code>d = {'C1' : pd...
<p>It is not so straight forward, you have to do a few loops to get this result. The key here is the fillna method which can do forwards and backwards filling.</p> <p>It is often the case that pandas methods does more than one thing, this makes it very hard to figure out what methods to use for what.</p> <p>So let me...
python-3.x|numpy|pandas
2
367,033
31,671,160
Pandas: Dynamic centering of multiple columns
<p>I need to transform all group columns in a DataFrame except the one column with the output variable.</p> <pre><code>df = pd.DataFrame({ 'Branch' : ['A', 'A', 'A', 'B', 'B', 'B'], 'M1': [1,3,5,8,9,3], 'M2': [2,4,5,9,2,1], 'Output': [1,5,5,8,1,3] }) </code></pre> <p>Right now, I am centering all colu...
<p>You can define a list of the cols of interest and pass this to the groupby which will operate on each of these cols via a lambda and <code>apply</code>:</p> <pre><code>In [53]: cols = ['M1','M2'] df[cols] = df.groupby('Branch')[cols].apply(lambda x: x - x.mean()) df Out[53]: Branch M1 M2 Output 0 ...
python|pandas
0
367,034
31,518,937
Convert Two column data frame to occurrence matrix in pandas
<p>Hi all I have a csv file which contains data as the format below</p> <pre><code>A a A b B f B g B e B h C d C e C f </code></pre> <p>The first column contains items second column contains available feature from feature vector=[a,b,c,d,e,f,g,h] I want to convert this to occurence matrix look like ...
<p>Here is another way to do it using <code>pd.get_dummies()</code>.</p> <pre><code>import pandas as pd # your data # ======================= df col1 col2 0 A a 1 A b 2 B f 3 B g 4 B e 5 B h 6 C d 7 C e 8 C f # processing # =================================== ...
python|pandas|sparse-matrix
10
367,035
31,444,423
rename a non existing column in dataFrame
<p>I have a dataframe dfWaits like this</p> <pre><code>waitEvent snapDate gc cr block 3-way gc current block 3-way log file sync instance AAA 2015-Jul-01 NaN 2 9 BBB 2015-Jul-01 NaN 2 ...
<p>To get rid of your <code>waitEvent</code> label (actually a label on your columns), set</p> <pre><code>df.columns.name=None </code></pre> <p>For your plot set the snapDate as your index and then call <code>plot()</code> on the columns you want:</p> <pre><code>df.index = df.snapDate df.iloc[:,[2,3,4]].plot() </cod...
python|pandas
1
367,036
31,553,983
python - using numpy loadtxt reading a csv file with different data types for each column
<p>I created a csv file with two columns, the first column is time data, and the second one is some measured data values.</p> <pre><code>2015/1/1 0:00 5 2015/1/1 0:15 10 2015/1/1 0:30 10 2015/1/1 0:45 15 2015/1/1 1:00 5 2015/1/1 1:15 20 2015/1/1 1:30 20 2015/1/1 1:45 40 2015/1/...
<p>You are very close to what you are looking for. Try this </p> <pre><code>data = np.loadtxt('TS.csv', dtype='str,int', delimiter=',', usecols=(0, 1), unpack=True) </code></pre>
python|csv|numpy
4
367,037
31,618,828
Numpy mixing arrays with multiple index arrays
<p>I have a 3d mesh with points and the locations of the points are in an array that looks like this:</p> <pre><code>mesh_vectors = np.array([[-0.85758871, 0.8965745 , -0.1427767 ], [-0.23945311, 1.00544977, 1.45797086], [-0.57341832, -1.07448494, -0.11827722], ...
<p>This works:</p> <pre><code>scaled_tr1 = translate_1 / np.bincount(idx1)[idx1,None] np.add.at(mesh_vectors, idx1, scaled_tr1) </code></pre> <p>Note that the use of <code>np.add.at</code> instead of fancy indexing <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html" rel="nofollow">is req...
python|arrays|numpy
0
367,038
31,277,368
Import Error related to Yahoo Finance tool / html5lib install
<p>I am trying to get stock data from Yahoo! Finance. I have it installed (<code>c:\ pip install yahoo-finance</code>), but the import in the iPython console is not working. This is the error I get: <code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 4: invalid start byte</code>.</p> <p>I am usi...
<p>I had the same error about <code>html5lib</code> with Python 3.4 in PyCharm 4.5.3, even though I installed <code>html5lib</code>. When I restarted PyCharm console (where I run the code), the error disappeared and options loaded correctly.</p>
python|pandas|scrape|yahoo-finance
1
367,039
31,300,437
Rolling median for a large dataset - python
<p>I have a huge file with 200K lines, I need to find out the rolling median by counting distinct words in each line.</p> <p>I have used numpy to calculate median as below</p> <pre><code> a = np.array([]) np.insert(a, 0, len(unique_word_list_by_line)) median = np.median(a) </code></pre> <p>I feel that this i...
<p>It is never good to dynamically fill a numpy array, it involves resizing and copying.</p> <p>The rolling median is not trivial as it seems. <a href="https://rhettinger.wordpress.com/tag/running-median/" rel="nofollow">This blog article</a> talks about different implementations such as <a href="https://en.wikipedia....
python|numpy|pandas|scipy|median
4
367,040
31,240,625
Pandas + Scikit learn : issue with stratified k-fold
<p>When used with a Dataframe, <code>StratifiedKFold</code> from scikit-learn returns a list of indices from 0 to n instead of a list of values from the DF index. Is there a way to change that ?</p> <p>Ex : </p> <pre><code>df = pd.DataFrame() df["test"] = (0, 1, 2, 3, 4, 5, 6) df.index = ('a', 'b', 'c', 'd', 'e', '...
<p>The numbers you got are just indices of <code>df.index</code> selected by <code>StratifiedKFold</code>.</p> <p>To change it back to the index of your DataFrame, simply</p> <pre><code>for i, (train, test) in enumerate(StratifiedKFold(df.index)): print i, (df.index[train], df.index[test]) </code></pre> <p>which...
pandas|scikit-learn|cross-validation
3
367,041
31,567,401
Get the same hash value for a Pandas DataFrame each time
<p>My goal is to get unique hash value for a DataFrame. I obtain it out of .csv file. Whole point is to get the same hash each time I call hash() on it. </p> <p>My idea was that I create the function </p> <pre><code>def _get_array_hash(arr): arr_hashable = arr.values arr_hashable.flags.writeable = False ...
<p>As of Pandas 0.20.1, you can use the little known (and poorly documented) <code>hash_pandas_object</code> (<a href="https://github.com/pandas-dev/pandas/blob/v0.25.2/pandas/core/util/hashing.py#L57-L136" rel="noreferrer">source code</a>) which was recently <a href="https://pandas.pydata.org/pandas-docs/stable/whatsn...
python|pandas
46
367,042
31,614,011
DataFrame modified inside a function
<p>I face a problem of modification of a dataframe inside a function that I have never observed previously. Is there a method to deal with this so that the initial dataframe is not modified.</p> <pre><code>In[30]: def test(df): df['tt'] = np.nan return df In[31]: dff = pd.DataFrame(data=[]) In[32]: dff Out[3...
<pre><code>def test(df): df = df.copy(deep=True) df['tt'] = np.nan return df </code></pre> <p>If you pass the dataframe into a function and manipulate it and return the same dataframe, you are going to get the same dataframe in modified version. If you want to keep your old dataframe and create a new data...
python|pandas
56
367,043
64,578,668
Show first and last label in pandas plot
<p>I have a DataFrame with 361 columns. I want to plot it but showing only the first and last columns in the legend. For instance:</p> <pre><code>d = {'col1':[1,2],'col2':[3,4],'col3':[5,6],'col4':[7,8]} df = pd.DataFrame(data=d) </code></pre> <p>If I plot through <code>df.plot()</code> all the legends will be displaye...
<p>Let's try extracting the handlers/labels from the axis and defining new legend:</p> <pre><code>ax = df.plot() handlers, labels = ax.get_legend_handles_labels() new_handlers, new_labels = [], [] for h,l in zip(handlers, labels): if l in ['col1','col4']: new_handlers.append(h) new_labels.append(l)...
python|pandas|legend
1
367,044
64,533,790
**StreamExecutor device (0): Host, Default Version** in Tensorflow
<p>I am trying to execute a tensorflow script on my local computer. But the following warning appears. It would be really helpful if someone can specify what the common cause for this warning is.</p> <pre><code>2020-10-26 14:04:34.690753: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is op...
<p>The main reason for the above warning is the <code>Tensorflow</code> library is not optimized for your particular architecture which <code>Tensorflow</code> was originally compiled on different architecture machine.<br /> You can ignore this warning but you won't be getting maximum performance from the library.</p> ...
python|tensorflow|machine-learning|deep-learning
0
367,045
64,558,741
Trying to assign IDs to pairs in a pandas DataFrame, getting inconsistent results
<p>I have a df:</p> <pre><code>df = pd.DataFrame({'src':['LV','LA','NC','NY','ABC','XYZ'], 'dest':['NC','NY','LV','LA','XYZ','ABC'], 'dummy':[1,3,6,7,8,10]}) src dest dummy LV NC 1 LA NY 3 NC LV 6 NY LA 7 ABC XYZ 8 XYZ ABC 10 </code></pre> <p>I run it thr...
<p>Try with that is the propblem with <code>set</code> , you can change it to <code>frozenset</code></p> <pre><code>df['pair'] = pd.DataFrame(np.sort(df[['src','dest']].values,1)).agg(tuple,1).factorize()[0]+1 Out[108]: array([1, 2, 1, 2, 3, 3], dtype=int64) </code></pre>
python|pandas|dataframe|lambda|non-deterministic
1
367,046
64,475,635
How to fill missing values based on the current values using Python?
<p>My data is like this:</p> <pre><code>a=pd.DataFrame({'id':[0,1,2,3,4,5,6,7,8,9], 'value':[np.nan,np.nan,0,np.nan,np.nan,1,2,np.nan,3,np.nan]}) </code></pre> <p>I want to fill the missing values based on the previous known values. If there is no previous values, then fill -1. So, the result should loo...
<p>Use <code>df.ffill()</code> and <code>fillna()</code>:</p> <pre><code>In [1587]: a.ffill().fillna(-1) Out[1587]: id value 0 0 -1.0 1 1 -1.0 2 2 0.0 3 3 0.0 4 4 0.0 5 5 1.0 6 6 2.0 7 7 2.0 8 8 3.0 9 9 3.0 </code></pre>
python|pandas|dataframe|missing-data|fill
3
367,047
64,427,475
apply function to specific cells in a pandas dataframe
<p>I would like to apply a function to some cells in a pandas dataframe. Not along a column or row axis, across the entire dataframe, but only some cells.</p> <p>I have the cell indices stored (in a list of (col, row) tuples, but I can store in any format that would make this question more easily solved).</p> <p>so for...
<p>Use the underlying <code>numpy</code> array:</p> <pre><code>x, y = zip(*idx) df.to_numpy()[y, x] += 1 </code></pre> <hr /> <pre><code> 0 1 2 0 1 2 1 1 3 1 3 2 1 1 1 </code></pre>
python|pandas|dataframe
1
367,048
64,196,210
pandas dataframe duplicate each row 5 times while changing one column
<p>I have the dataframe:</p> <pre><code>vid_fn V1 V2 V3 a.avi 1 4 5 b.avi 7 8 1 </code></pre> <p>I want to change duplicate each row 5 times, while changing the first column:</p> <pre><code>frame_fn V1 V2 V3 a1.jpg 1 4 5 a2.jpg 1 4 5 a3.jpg 1 4 5 a4.jpg 1 4 5 a5.jpg 1 ...
<p>You can <code>map</code> the function <code>my_func</code> over <code>vid_fn</code> then <code>explode</code> the dataframe on <code>vid_fn</code>:</p> <pre><code>df.assign(vid_fn=df['vid_fn'].map(my_func)).explode('vid_fn')\ .rename(columns={'vid_fn': 'frame_fn'}).reset_index(drop=True) </code></pre> <hr /> <pre>...
python|pandas|data-science|data-munging
0
367,049
64,435,692
Finding the mirror of coordinates through a midpoint
<p>I want to find the reflection of a point after passing through a midpoint, ie. basically the opposite of the point. My midpoint (mid_x, mid_y) is (5, 5). Is there a simple function to do this?</p> <p>my df:</p> <pre><code> x1, y1, mid_x, mid_y 0 7 3 5 5 1 4 8 5 5 2 1 6 5 5 </co...
<p>You can get the columns for <code>new_x1</code> and <code>new_y1</code> by:</p> <pre><code>df['new_x1']=2*df['mid_x']-df['x1'] </code></pre> <p>Similarly for df['new_y1']</p> <pre><code>df['new_y1']=2*df['mid_y']-df['y1'] </code></pre>
python|pandas
1
367,050
64,413,058
Converting a pandas dataframe to a nested dictionary with specific key
<p>I am trying to create a nested dictionary from a pandas dataframe with the following format:</p> <pre><code>Name Info Location Alias AA InfoA locationA AliasA BB InfoB locationB AliasB CC InfoC locationC AliasC </code></pre> <p>The result dict that I am looking for has the following format:</p> <pre class="...
<p>My attempt:</p> <pre class="lang-py prettyprint-override"><code>d = df.set_index(&quot;Name&quot;).to_dict(&quot;index&quot;) for k,v in d.items(): d[k][&quot;Location&quot;] = {&quot;Where&quot;: v[&quot;Location&quot;], &quot;Alias&quot;: v[&quot;Alias&quot;]} d[k].pop(&quot;Alias&quot;, None) </code></pre...
python|pandas|dataframe|dictionary|pandas-groupby
2
367,051
64,345,704
How can I merge a Pandas dataframes based on a substring from one of the columns?
<p>I have 2 dataframes: df1 and df2</p> <pre><code>df1 School Conference 0 Air Force Mt. West 1 Akron MAC 2 Alabama at Birmingham C-USA 3 Auburn Sun Belt df2 SCHOOL_NAME RATE 0 Aubur...
<p>You can use list comprehension to check if the columns from each dataframe are <code>in</code> each other (you also compare case-insensitively) and then merge:</p> <pre><code>df1['SCHOOL_NAME'] = df1['School'].apply(lambda x: [y for y in df2['SCHOOL_NAME'] if x in ...
python|pandas|dataframe
4
367,052
64,609,057
iterate/loop over all columns
<p>I'm new to pandas, still learning and I wanted to ask if using <code>iloc[:,1]</code> is locating the column by index, how can I get all the columns if I want to get all the columns from 1-10? Does it has to way to iterate over all the columns or can be only done using <code>iloc[]</code> one by one? Because I wante...
<p>This will give you a new dataframe with the first ten columns of <code>X_test</code>:</p> <pre><code>X_test[X_test.columns[:10]] </code></pre>
python|pandas|linear-regression
0
367,053
64,347,174
How to execute tf.grad in tensorflow.js passing model.executeAsync(x)
<p>I am trying to pass <code>model.executeAsync(x).reshape([-1]).gather(2))</code> to <code>tf.grad</code> it returns me an error :</p> <blockquote> <p>Uncaught (in promise) TypeError: model.executeAsync(...).reshape is not a function</p> </blockquote> <p>When i remove <code>.reshape([-1])</code> it returns this error ...
<p>As indicated by name the method <code>executeAsync</code>, it is an async method which returns a promise that needs to be awaited.</p> <pre><code>chestgrad = tf.grad(async x =&gt; await model.executeAsync(x)).reshape([-1].gather(2)) </code></pre> <p>tf.grad does not seem to accept an async function. So the above wil...
javascript|keras|tensorflow.js
0
367,054
64,421,462
1) How do I toggle scientific notation in pandas Bokeh (using the plot_bokeh function) and 2) how do I center the colours at 0 (so white is 0)
<p>I have some dataframe like this:</p> <pre><code>df = pd.DataFrame({ 'FSA': ['T9X', 'T2B', ...], 'vals': [-1.1, 2.2, ...] 'geometry': [some elements of type shapely.geometry.polygon.Polygon] }) </code></pre> <p>Where I got the geometry boundaries from the 2016 Canadian census here: <a href="http://www12...
<p>This doesn't help with creating a custom color ramp, but one thing you can do to &quot;cheat&quot; and put 0 in the middle and get it to be white is to use your min (or max, or some other arbitrary end point on either end, as long as they are the same) on both sides of of the colormap_range. So depending on how you ...
python|pandas|plot|bokeh|geo
1
367,055
64,224,686
Matplotlib adding third line plot from separate CSV
<p><strong>Thank you in advance for your help!</strong> (Code Provided Below) (Data for: <a href="https://github.com/the-datadudes/deepSoilTemperature/blob/master/AllDeepSoilData.zip?raw=true" rel="nofollow noreferrer">Line 1</a>)(Data for <a href="https://raw.githubusercontent.com/the-datadudes/deepSoilTemperature/mas...
<p>If you want to draw a graph with two axes, you can use ax,ax1,ax2,ax3 on the left side and ax4 on the right side with <code>ax4=ax.twynx()</code>. The legend is based on a concatenation of ax and ax4.</p> <pre><code>fig = plt.figure() #= Plotting the topsoil ax = mean.plot(x='Day', y='Topsoil', color='black', figsi...
python|pandas|numpy|dataframe|matplotlib
1
367,056
64,566,235
Implementing TensorFlowjs model in Ionic framework with Capacitor
<p>I am working on a project where I am using Ionic and TensorFlow for machine learning. I have converted my TensorFlow model to a tensorflowjs model. I have put the model.json file and shard files of the tensorflowjs model in the assets folder in Ionic. Basically, I have put my tensorflowjs model in the assets folder ...
<p>The model is expecting you to pass in a <code>Tensor</code> input, but you're passing it some other image format that isn't in the tfjs ecosystem. You should first convert <code>this.photo</code> to a Tensor, or perhaps easier, convert <code>image.base64String</code> to tensor.</p> <p>Since you seem to be using node...
ionic-framework|tensorflow.js|capacitor
0
367,057
64,311,468
Pandas compare 3 columns and output the result if count more than 1
<p>I have 3 columns with value either A, B or C I want to compare these 3 columns and give output which value have more than 1 counts. If the count is tie then the output will be &quot;-&quot;</p> <p>Input:</p> <pre><code> | col1 | col2 | col3 | |-------|-------|-------| | A | A | B | | A ...
<p>Let's try with <code>Counter</code> to get the most common element:</p> <pre><code>from collections import Counter def most_common(): for s in df.to_numpy(): k, v = Counter(s).most_common(1)[0] yield '-' if v == 1 else k df['Result'] = list(most_common()) </code></pre> <hr /> <pre><code> col1...
python|pandas|dataframe
5
367,058
64,559,359
NetCDF get_dims too many values to unpack
<p>I am working with a NetCDF file (.nc) - 600+MB.</p> <pre><code>import netCDF4 from netCDF4 import num2date import numpy as np import os import pandas as pd # Open netCDF4 file file_location = '2m dewpoint temperature.nc' f = netCDF4.Dataset(file_location) </code></pre> <p>In order to convert the file to CSV I start...
<p>You appear to have more than 3 dimensions. As a result this should fail:</p> <pre><code>time_dim, lat_dim, lon_dim = d2m.get_dims() </code></pre> <p>You just need to check what <code>d2m.get_dims()</code> gives you then amend the line.</p> <p>A quicker way to convert to csv would be using xarray:</p> <pre><code>impo...
python|pandas|export-to-csv|netcdf|netcdf4
2
367,059
64,509,254
How to create multiple .md files based on a .csv file and enter the correct rows of the .csv file into each newly created .md file?
<p>Basically I have a .csv file with similar data structure to the following:</p> <pre><code>Name | Department | Committees | Years Jack | Finance | Party | 7.0 Jen | Marketing | Risk | 15.0 </code></pre> <p>I would like to be able to create individual markdown files based on the Name column in th...
<p>I figured it out:</p> <pre><code>import pandas as pd # Create a dataFrame from csv file data = pd.read_csv(&quot;Employee_Directory.csv&quot;, sep=',', engine='python', encoding=&quot;utf- 8&quot;).fillna('') # Filtering out unwanted characters data['Committees']=data['Committees'].str.replace(&quot;&lt;br&gt;&qu...
python|excel|pandas|csv|markdown
0
367,060
64,390,138
"init_dgelsd failed init" When using import numpy as np
<p>I am trying to run this simple code</p> <pre><code>import numpy as np my_first_array = np.array([1, 2, 3,4,5]) my_first_array([1, 2, 3, 4, 5]) </code></pre> <p>I believe I am using python 3.9 as i just bought this computer and downloaded the newest version. But keep getting the error code:</p> <pre><code>Traceback...
<p>If you care to read up on the issue here is where I found the <a href="https://github.com/numpy/numpy/issues/15947" rel="nofollow noreferrer">solution</a> below.</p> <pre><code>rm -v ~/Library/Caches/pip/wheels/*/*/*/*/*numpy* # clear the pip wheel cache of any built numpy wheels brew install openblas # make sure Op...
python|numpy
2
367,061
64,308,252
kerastuner INFO:tensorflow:Oracle triggered exit
<p>When using keras tuner to optimize my UNET AI-model, I get the following message in the terminal:</p> <pre><code>{'conv_blocks1': 2, 'filters1_0': 240, 'conv_blocks2': 3, 'filters2_0': 136, 'bottle': 4, 'filtersbot_0': 184, 'filtersbot_1': 32, 'filters2_1': 200, 'filters1_1': 208, 'filtersbot_2': 8, 'filtersbot_3': ...
<p>I've run into one similar problem, tuners need a location in the computer to store the files contains all the parameters, and I direct it to a local location in my computer, if I don't change that address and re-run the tuner, then I'll get &quot;INFO:tensorflow:Oracle triggered exit&quot;. sample codes that I'm usi...
python-3.x|tensorflow|keras|artificial-intelligence|tuner
0
367,062
64,460,619
pd.read_html error client remote disconnected
<p>Yesterday the following code was giving me the dataframe without problem. But today it started giving me the following error:</p> <pre><code> http.client.RemoteDisconnected: Remote end closed connection without response </code></pre> <p>Any solution? I know the problem is from the website but I need some solution t...
<p>The error is on the server side - sometimes the server returns error. One workaround is to repeat the requests until success, for example:</p> <pre><code>import http import pandas as pd j = 2020 i = 9 url = 'https://www.centrodeinformacao.ren.pt/userControls/GetExcel.aspx?T=REN_MENSAL&amp;P='+str(j)+'&amp;PP='+str...
python|pandas|web-scraping
0
367,063
64,510,512
What is the correct way to get the first row of a dataframe?
<p>The data in <code>test.csv</code> likes this:</p> <pre><code>device_id,upload_time,latitude,longitude,mileage,other_vals,speed,upload_time_add_8hour,upload_time_year_month,car_id,car_type,car_num,marketer_name 1101,2020-09-30 16:03:41+00:00,46.7242,131.140233,0,,0,2020/10/1 0:03:41,202010,18,1,, 1101,2020-09-30 16:0...
<p>To get the first and last <strong>element</strong> of the column, your option is already the most efficient/correct way. If you're interested in this topic, I can recommend you to read this other Stackoverflow answer: <a href="https://stackoverflow.com/a/25254087/8294752">https://stackoverflow.com/a/25254087/8294752...
python|pandas
0
367,064
64,180,334
How to create this matrix from numpy array?
<p>So I want to create the sparse matrix as below from the numpy array matrix as usual:</p> <pre><code>from scipy import sparse I = np.array([0,1,2, 0,1,2, 0,1,2]) J = np.array([0,0,0,1,1,1,2,2,2]) DataElement = np.array([2,1,2,1,0,1,2,1,2]) A = sparse.coo_matrix((DataElement,(I,J)),shape=(3,3)) print(A.toarray()) ## T...
<p>One way using <code>numpy.add.at</code>:</p> <pre><code>arr = np.zeros((3,3), int) np.add.at(arr, (I, J), DataElement) print(arr) </code></pre> <p>Output:</p> <pre><code>array([[2, 1, 2], [1, 0, 1], [2, 1, 2]]) </code></pre>
python|arrays|numpy
2
367,065
64,323,408
can't get the right shape of TensorFlow custom layer
<p>I am trying to train a model in TensorFlow with custom layers. I am having a problem with the last layer, I am trying to build a layer that gets a batch of images [None,100,100,1] and returns the sum of 10 different square zones, so the output should be the shape of [None,10].</p> <p>I've tried some different approa...
<p>I modified your code and come up with the following:</p> <pre><code>output = tf.concat( [tf.math.reduce_sum(inputs[:, 34:42, 28:40,:], axis=[1,2]), tf.math.reduce_sum(inputs[:, 34:42, 44:56,:], axis=[1,2]), tf.math.reduce_sum(inputs[:, 34:42, 60:72,:], axis=[1,...
python|tensorflow|neural-network|tensorflow2.0
1
367,066
64,197,151
Error when using run_eagerly=False in model.compile custom Keras Model in Tensorflow
<p>I am developing a custom model in Tensorflow. I am trying to implement a Virtual Adversarial Training (VAT) model from <a href="https://arxiv.org/abs/1704.03976" rel="nofollow noreferrer">https://arxiv.org/abs/1704.03976</a>. The model makes use of both labeled and unlabeled data in its classification task. Therefor...
<p>For anyone who is interested, I solved the issue by adding the following in the <code>train_step()</code> method:</p> <pre><code>missing.set_shape([None]) </code></pre> <p>It should be just after declaring the tensor <code>missing</code>. I solved this using this thread: <a href="https://stackoverflow.com/questions/...
python|tensorflow|keras|deep-learning|eager-execution
0
367,067
64,457,747
How to install cuda 11 on Ubuntu 20.04
<p><a href="https://i.stack.imgur.com/iteFq.png" rel="nofollow noreferrer">Tensorflow official recommendation</a></p> <p>So, I'm using Ubuntu 20.4 and I want to use Tensorflow with version 2.3. The offcial Tf sources say that 10.1 is supported, but I couldn't find the installation of CUDA 10.1 for Ubuntu 20.4. Is it po...
<p>Yes you can! The usual way would be to build TF from source, which can take many hours (thats atleast what I read). This is required, as tensorflow is compiled with a specific cuda version, thats why they have to match. After some research I found out, that davidenunes compiled different TF version with different cu...
tensorflow2.0
0
367,068
64,186,029
Select rows of pd.DataFrame where column values are "close" to each other
<h1>Dataset</h1> <p>I have a movie dataset where there are over half a million rows, and this dataset looks like following (with made-up numbers)</p> <pre><code>MovieName Date Rating Revenue A 2019-01-15 3 3.4 million B 2019-02-03 3 1.2 million ... .....
<p>In general, it is true that you should try avoiding loops when working with pandas. My idea is not ideal, but might point you in the right direction:</p> <ol> <li>Retrieve month and year from the date column in every row to create new columns &quot;month&quot; and &quot;year&quot;. You can see how to do it <a href="...
python|pandas
1
367,069
64,488,453
Split cell if there is '%'
<p>I would like to iterate through each row of the '% interest' column and split at '%' if it is found in that cell, if it is not found I want the code to ignore the cell.</p> <p>I have tried this:</p> <pre><code>for row in concat_data.index: if (concat_data['% interest'][row]).str.contains('%'): concat_data['% ...
<p>There is no need for a condition.</p> <p>Use <code>str.split(..., expand=True)</code> and assign the result back to itself and a new column:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;% percent&quot;: [ f&quot;25{x}&quot; for x in (&quot;%&quot;,&quot;00&quot;,&quot;00% with interest&quot;, &quot;...
python|pandas
1
367,070
64,252,773
How to use filter, group by and agg function together in Python
<p>I have a dataframe below:</p> <pre><code> A B C 0 asia 1000 ab 1 africa 2000 ab 2 asia 4000 bc 3 asia 6000 cd 4 USA 200 ab </code></pre> <p>I'd like to filter for column A = asia and sum column B group by column C. I am trying to use:</p> <pre><code>agg = df[df[...
<p>Try this:</p> <pre><code>df1 = df[df['A'] == 'asia'].groupby(['A', 'C'], as_index=False).sum() print(df1) A C B 0 asia ab 1000 1 asia bc 4000 2 asia cd 6000 </code></pre>
python|python-3.x|pandas
1
367,071
64,421,471
Mapping, sum, and conditions in python
<p>Is there a way to make this more efficient?</p> <p>I am using the congressional dataset in the “Data Folder” <a href="https://archive.ics.uci.edu/ml/datasets/congressional+voting+records" rel="nofollow noreferrer">https://archive.ics.uci.edu/ml/datasets/congressional+voting+records</a></p> <p>to answer How many repu...
<p>Here is an alternative approach:</p> <pre><code>import numpy as np import pandas as pd topics_col = [&quot;topic_%i&quot; % i for i in range(16)] df = pd.read_csv('house-votes-84.data', names = ['class name'] + topics_col) df = df.replace('y', np.NaN).replace('?', np.NaN) df['n_sum'] = df[topics_col].count(axis=1...
python|pandas
0
367,072
64,346,076
Merging Multiple Dataframes by Multiple Columns
<p>I am trying to merge about 5 Data Frames, each with 2 variables. Each data frame has two variables. The variables are Unique_ID and Year. Each data frame has a different amount of observations.</p> <p>DF 1</p> <pre><code>Unique ID Year 1 2010 2 2010 3 2011 </code><...
<p>You can use <code>functools.partial</code>:</p> <pre><code>import functools dfs = [df1,df2,df3,df4,df5] df = functools.partial(pd.merge, on=['Unique_ID', 'Year']) #may have to pass how='outer' or how='left', depending on what you are trying to accomplish </code></pre>
python|pandas|database|dataframe|merge
0
367,073
64,349,519
Error in Ray: "ModuleNotFoundError: No module named 'pandas' "
<p>I started ray on a terminal in an environment called p_c which has pandas installed with the command ray start --head --num-cpus=2 --num-gpus=0</p> <p>Then, I ran the following python script:</p> <pre><code>import ray import os import pandas as pd import sys ray.init(address='auto', redis_password='5241590000000000...
<p>The Ray runtime will look for Pandas in the configured virtual environment. If launching Ray locally ensure to install required Python libraries in the virtual environment serving the Ray runtime.</p> <p>e.g.</p> <pre><code>. .venv/bin/activate pip install pandas ray start --num-cpus=8 --object-store-memory=70000000...
python|pandas|ray
0
367,074
64,568,504
sklearn: chaining multiple transformers with ColumnTransformer
<p>How can I apply multiple transformers to a <em>single</em> pandas DataFrame column using the ColumnTransformer API?</p> <p>For example, I want to take the cubic root and then standardize the values in a DataFrame column:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( np.array([[1., 2., 3.],...
<pre><code>from sklearn.pipeline import Pipeline import pandas as pd import numpy as np from sklearn.preprocessing import FunctionTransformer, StandardScaler df = pd.DataFrame( np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]), columns=['a', 'b', 'c'] ) pipe = Pipeline([('function_transformer', FunctionTransforme...
python|pandas|machine-learning|scikit-learn
1
367,075
64,231,198
Replacing multiple values on multiple conditions in DataFrame
<p>I have the following code which produces a df with 7 columns and 40000 rows:</p> <pre><code>df = pd.DataFrame(np.random.random(size=(40000, 7)), columns=list('ABCDEFGH')) </code></pre> <p>How do I replace every value less than 1/3 to &quot;a&quot;, every value between 1/3 and 2/3 to be &quot;b&quot; and any above 2/...
<h2>Use applymap</h2> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer">Apply map documentation</a></p> <pre><code>def remap(x): if x &lt;= 1/3: return 'a' elif x &gt; 1/3 and x &lt; 2/3: return 'b' else: ...
python|python-3.x|pandas|dataframe
2
367,076
64,363,116
How to join two set without the default "sort"
<p>Looking to join two set as an append without sorting.</p> <p>Here is my code:</p> <pre><code>a = {123,456,789} b = {777,888} a = a.union(b) a </code></pre> <p>Output:</p> <pre><code>{123, 456, 777, 789, 888} </code></pre> <p>Desired output:</p> <pre><code>{123, 456, 789, 777, 888} </code></pre> <p>Thanks!</p>
<p>Sets are unordered so you can't guarantee an arrangement. The answer from BEN_YO will make it so the second sets elements are at the end but the internal ordering will differ, as shown in his sample output.</p> <p>If ordering matters you need to use a different collection type. A quick hack if you want both ordering...
python-3.x|pandas|numpy|dataframe|set
3
367,077
64,304,060
Is there any substitute of logging attribute in Tensorflow in Python 3?
<p>While using the <code>logging</code> attribute in TensorFlow in Python 3 I am getting an error that the attribute is invalid.<br> What can I use instead of it?<br> Error:</p> <pre><code>tf.logging.set_verbosity(tf.logging.ERROR) AttributeError: module 'tensorflow' has no attribute 'logging' </code></pre>
<p>In Tensorflow2 tf.logging is removed. tf.logging is for looging and summary.</p> <p><a href="https://www.tensorflow.org/guide/migrate/upgrade" rel="nofollow noreferrer">tf_upgrade_v2</a> will upgrade script and changes <code>tf.logging</code> to <code>tf.compat.v1.logging</code></p>
python|python-2.7|tensorflow|image-processing|python-3.7
0
367,078
64,242,573
How to split dataframe text column to boolean columns
<p>I have a dataframe containing information about approximately 300 small businesses. The column <code>'Business_Model'</code> looks as follows:</p> <pre><code>0 B2B business to business (companies sell to co... 1 B2B business to business (companies sell to co... 2 B2B2C business to business to consumer (comp...
<p>If values starting in column use:</p> <pre><code>df = pd.get_dummies(df['Modelo_de_Negocio'].str.split().str[0], dtype=bool) print (df) B2B B2B2C B2C 0 True False False 1 True False False 2 False True False 3 True False False 4 False False True </code></pre> <p>If values are not always i...
pandas|dataframe|split
1
367,079
64,472,712
accessing each element of a list according to given list of indexes TypeError
<p>I want to access each element of the area according to given list of indexes for loop, but I am getting a TypeError: 'float' object is not subscriptable.</p> <p>Is there a way I can do that ?</p> <p>really appreciated</p> <pre><code>index=[0, 1, 5, 6, 10, 11] area=[78.0, 125.0, 203.0, 266.0, 344.0, 141.0, 46.0, 187....
<p>You don't need to loop through area with <code>j</code>, because you are looping through the index and calling certain values of area based on index, so you can just use:</p> <pre><code>index=[0, 1, 5, 6, 10, 11] area=[78.0, 125.0, 203.0, 266.0, 344.0, 141.0, 46.0, 187.0, 245.0, 265.0, 78.0, 203.0] key_to_del = Fals...
python-3.x|numpy
1
367,080
64,177,019
How to match up x and y values then separate them by a comma, and have the output go to a new csv file?
<p>I have two lists, an X and a Y. I want to have those lists create a file with the values written as x,y.</p> <p>Right now I can get them to write to a file, but its just individual values in each excel cell and I need it to be x,y.</p> <p>Here's what I've got so far:</p> <pre><code>import random as rd X = [] Y = []...
<p>After you have created <code>Xsub</code> &amp; <code>Ysub</code>, you can write the pair <code>(Xsub[i], Ysub[i])</code> in the file in the following way:</p> <pre class="lang-py prettyprint-override"><code>with open('lab4.csv','w') as f: for x, y in zip(Xsub, Ysub): f.write(&quot;%s,%s\n&quot; % (x, y))...
python|numpy|csv
0
367,081
64,340,726
Dataframe to seperate lines in Python
<p>I am writing a model. I need help.</p> <p>The last part of my code is;</p> <pre><code>x_irp_sum_eliminated_df = pd.DataFrame(x_irp_sum_eliminated).T print(x_irp_sum_eliminated_df.head()) </code></pre> <p><strong>Output is;</strong></p> <p><a href="https://i.stack.imgur.com/Q0VyD.png" rel="nofollow noreferrer"><img ...
<p>Your dataframe has N rows and M columns. You want to join all values in each column with <code>&quot; + &quot;</code>. All you need to do is <code>&quot; + &quot;.join(df[colname])</code>. To get rid of the <code>None</code> values, we can do <code>df[colname].dropna()</code> before joining. To make sure they're str...
python|pandas
1
367,082
64,432,937
python dataframe change index type and remove duplicates
<p>i have a dataframe that looks like this</p> <pre><code>2020-01-01 10 2020-02-01 5 2020-05-01 2 2020-08-01 7 2020-01-01 00:00:00 0 2020-02-01 00:00:00 0 2020-03-01 00:00:00 ...
<p>change the index data type and filter with <code>.duplicated</code>:</p> <pre><code>df.index = pd.to_datetime(df.index) df = df[~df.index.duplicated(keep='first')] df Out[1]: 1 0 2020-01-01 10 2020-02-01 5 2020-05-01 2 2020-08-01 7 2020-03-01 0 2020-04-01 0 </code></pre> <p>If y...
python|pandas
3
367,083
64,570,520
Pandas dataframe: Based on some current row R1, find another row R2 for which all rows in between match a condition
<p>Given the following exemplary dataframe/series, I have - for some given reason - identified row number 6 as the relevant base row and I now want to find the row where the unbroken series of ones started (in this case that is row 3).</p> <p>I explicitly do not want to find the first row containing a one (which would ...
<p>Here's a solution that should be performant:</p> <pre><code>n = 6 # a new group id is formed every time the value changes in A df[&quot;group_id&quot;] = np.cumsum(df.A != df.A.shift()) # get group for n, return first column of that group group = df.group_id.iloc[n] df[df.group_id == group].head(1) </code></pre...
python|pandas|indexing
2
367,084
64,398,119
Pandas: replacing part of a string from elements in different columns
<p>I have a dataframe where numbers contained in some cells (in several columns) look like this: '$$10'</p> <p>I want to replace/remove the '$$'. So far I tried this, but I does not work:</p> <pre><code>replace_char={'$$':''} df.replace(replace_char, inplace=True) </code></pre>
<p>your code is (almost) right. this will work if you had AA:</p> <pre><code>replace_char={'AA':''} df.replace(replace_char, inplace=True) </code></pre> <p>problem is $$ is a regex and therefore you need to do it differently:</p> <pre><code>df['your_column'].replace({'\$':''}, regex = True) </code></pre> <p>example:</...
pandas|dataframe|replace|cell
1
367,085
64,429,618
Fix missing data value while joining dataframe in Python
<p>I am trying to join two dataframe one is data for choropleth with postcode and some other value in it another one is postcode and price.</p> <p>I am trying to join both of them according to correspond postcode in map_df.</p> <p>After I joined them, the prices are gone and all become NaN. How can I fix this?</p> <p>...
<p>I solved the problem by changing the type of data in my map_df dataframe. I changed the postcode column from &quot;object&quot; to &quot;int64&quot;.</p>
python|pandas|data-science
0
367,086
64,321,362
non fixed rolling window
<p>I am looking to implement a rolling window on a list, but instead of a fixed length of window, I would like to provide a rolling window list:<br /> Something like this:</p> <pre><code>l1 = [5, 3, 8, 2, 10, 12, 13, 15, 22, 28] l2 = [1, 2, 2, 2, 3, 4, 2, 3, 5, 3] get_custom_roling( l1, l2, np.average) </code></pre> <p...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/computation.html#custom-window-rolling" rel="nofollow noreferrer">Pandas custom window rolling</a> allows you to modify size of window.</p> <p>Simple explanation: <code>start</code> and <code>end</code> arrays hold values of indexes to make slices of y...
python|pandas|rolling-computation
1
367,087
64,200,117
fitting model several times in keras
<p>I am using <code>model.fit()</code> several times, each time is responsible for training a block of layers where other layers are freezed</p> <h1>CODE</h1> <pre><code> # create the base pre-trained model base_model = efn.EfficientNetB0(input_tensor=input_tensor,weights='imagenet', include_top=False) # add a...
<p>I solved this by removing the second compiler.</p>
python|tensorflow|keras|deep-learning|model
0
367,088
64,381,243
How to get max of a slice of a dataframe based on column values?
<p>I'm looking to make a new column, <code>MaxPriceBetweenEntries</code> based on the max() of a slice of the dataframe</p> <pre><code>idx Price EntryBar ExitBar 0 10.00 0 1 1 11.00 NaN NaN 2 10.15 2 4 3 12.14 NaN NaN 4 10.30 NaN NaN </code></pre> <p>turned into</p> <pre><code>idx...
<p>You can groupby the cumulative sum of non-null entries and take the max, unsing <code>np.where()</code> to only apply to non-null rows::</p> <pre><code>df['MaxPriceBetweenEntries'] = np.where(df['EntryBar'].notnull(), df.groupby(df['EntryBar'].notnull().cumsum())['Price'].tran...
python|pandas|dataframe
2
367,089
64,479,260
Delete first entry in CSV using Python
<p>I want to repetitively safe datas in a csv file. I want to have for example always only 200 values in the file and delete the old files, so a fifo or queue. I am currently trying different solutions, but so far without success. Besides I hope to achieve this in only one csv file. Here is the function as I imagine it...
<p>in the end this worked for me : df.drop(1, inplace = True) ... thanks for your help !</p>
python|pandas|csv
0
367,090
64,197,754
How do I rotate a PyTorch image tensor around it's center in a way that supports autograd?
<p>I'd like to randomly rotate an image tensor (B, C, H, W) around it's center (2d rotation I think?). I would like to avoid using NumPy and Kornia, so that I basically only need to import from the torch module. I'm also not using <code>torchvision.transforms</code>, because I need it to be autograd compatible. Essenti...
<p>So the grid generator and the sampler are sub-modules of the Spatial Transformer (JADERBERG, Max, et al.). These sub-modules are not trainable, they let you apply a learnable, as well as non-learnable, spatial transformation. Here I take these two submodules and use them to rotate an image by <code>theta</code> usin...
python|rotation|pytorch|image-rotation|rotational-matrices
12
367,091
64,258,996
Libtorch C++ - no matching member function for call to 'size' for InterpolateFuncOptions
<p>Using Libtorch 1.6.0 in C++, I get the following error:</p> <pre><code>error: no matching member function for call to 'size' </code></pre> <p>My line is the following:</p> <pre><code>image = F::interpolate(image, F::InterpolateFuncOptions().size({target_height, target_width}).mode(torch::kNearest)); </code></pre> <p...
<p>You should wrap it with <code>std::vector</code> like this:</p> <pre><code>image = F::interpolate(image, F::InterpolateFuncOptions() .size(std::vector&lt;&gt;{target_height, target_width}) .mode(torch::kNearest)); </code></pre> <p>Reason for this is <code>size</code> has no overloaded call f...
c++|pytorch|libtorch
2
367,092
64,514,797
Extract List in Column Pandas Dataframe
<p>please help..</p> <pre><code>file.json [ {&quot;fullname&quot;: &quot;mona&quot;, &quot;phones&quot;: [{&quot;phone&quot;: &quot;21323131&quot;}], &quot;areas&quot;: [{&quot;area&quot;: &quot;Texas&quot;}, {&quot;area&quot;: &quot;New York&quot;}] }, {&quot;fullname&quot;: &quot;joni&quot;, &quot;phones&quot;: [{&q...
<p>Let's try <code>explode</code> along with <code>Series.str.get</code>:</p> <pre><code>s = df['areas'].explode().str.get('area').groupby(level=0).agg(', '.join) d = df.explode('phones').assign(areas=s, phones=lambda x: x['phones'].str.get('phone')) </code></pre> <hr /> <pre><code>print(d) fullname phones ...
python|pandas|dataframe
2
367,093
64,247,684
Pandas dataframe: keep only rows depending on actual date and maximum 7 days old
<p>I have a dataframe with articles, here is the first articles:</p> <pre><code>0 La reprise de l’économie française s’étiole et... Sur le Vieux-Port, à Marseille, le 28 septembr... 2020-10-06 1 Aux Etats-Unis, un rapport parlementaire veut ... Les icones des services de Google, Amazon, Fac... 2020-10-07 2 ...
<pre><code>df = pd.DataFrame({ 'text': [&quot;t1&quot;, &quot;t2&quot;, &quot;t3&quot;], 'date' : ['2020-10-06', '2020-10-05', '2012-10-06'] }) df['date'] = pd.to_datetime(df['date']) till = pd.to_datetime(datetime.date.today() - datetime.timedelta(days=7)) df = df[df['date'] &gt;= till] </code></pre> <p>Outpu...
python|pandas
1
367,094
64,505,950
How do I display pandas dataframe so that its width fits my screen?
<p>I have a pandas dataframe with textual data and I want to display all texts without truncation so I set</p> <pre><code>pd.set_option('display.max_colwidth', None) pd.set_option('display.max_rows', None) </code></pre> <p>However, the table now doesn't fit my screen, you can see the scroll bar at the bottom of the ima...
<p>This is the solution I found</p> <pre><code>from IPython.display import display display(_df.style.set_properties(**{ 'width': '230px', 'max-width': '230px' })) </code></pre> <p>and I wrote a helper function for this</p> <pre><code># decorator def pandas_display(func): default_1 = pd.options.d...
python|pandas|dataframe|ipython
-1
367,095
64,348,978
How to show a string graph with '\n' in dataframe?
<p>I want to show a string graph with '\n' in dataframe, but i found it show '\n' instead of line feed. please see the following:</p> <pre><code># i have two string an='*' s1 = ' %s\n%s \n%s%s' % (an, an, an, an) # this is a string graph s2 = '%s%s\n %s\n%s ' % (an, an, an, an) </code></pre> <p>print it to get the str...
<blockquote> <p>in the grid, string should have several line, not one line with '\n', same with print() result.</p> </blockquote> <p>I believe the Series is printing out the correct representation of the data. <code>\n</code> appears in the Series to show that the row contains a new line <code>\n</code> character.</p> ...
python|pandas
0
367,096
64,614,302
Exporting data from python dataframe to googlesheets
<p>I am trying to export a python pandas dataframe into google sheets but the values that appear in the cells all start with an apostrophe ('). Is there a way for me to format the values so the output would be a normal number without manually formatting the numbers on google sheets? I am using df2gspread to upload my d...
<h3>Modification points:</h3> <ul> <li><p>In your script, it seems that <code>wks_name</code> and <code>wks_name1</code> are the string values. I think that this is the reason of your issue.</p> </li> <li><p>At gspread, it seems that <code>values_update</code> is the method of Class gspread.models.Spreadsheet.</p> </li...
python|pandas|dataframe|google-sheets-api|gspread
0
367,097
64,539,086
In Python/Pandas, what is the most efficient way, to apply a custom function, to a column of a dataframe, where the input includes strings?
<p>I have a very large Dataframe, where one column contains numbers and another contains text. I want to create a 3rd column, based on the number column and the text column and a complex custom function, in the most efficient way.</p> <p>According to this <a href="https://engineering.upside.com/a-beginners-guide-to-opt...
<pre><code>def fun_test2(no1, text, idx): if text[idx] == 'one': no2 = 1 elif text[idx] == 'two': no2 = 2 elif text[idx] == 'three': no2 = 3 res = no1[idx] + no2 return res Test2 = pd.DataFrame({'no1':[1, 2, 3], 'text':['one', 'two', 'three']}) Test2['...
python|pandas|performance|numpy|vectorization
0
367,098
47,744,927
Optimize a function that acts on a numpy array with an if statement
<p>Suppose I have a code like:</p> <pre><code>import numpy as np def value_error(x): if x &gt; 10: return 0. else: return np.sin(x) </code></pre> <p>This could give me a <code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</code> if cal...
<p>Many of the <code>ufunc</code> take a <code>where</code> parameter</p> <pre><code>In [98]: x=np.arange(10)*2 In [99]: mask = x&lt;10 In [100]: y = np.zeros(10) In [101]: np.sin(x,where=mask,out=y) Out[101]: array([ 0. , 0.90929743, -0.7568025 , -0.2794155 , 0.98935825, 0. , 0. , 0....
python|arrays|numpy
4
367,099
47,647,410
pandas pct_change() in reverse
<p>Suppose we have a dataframe and we calculate as percent change between rows</p> <pre><code>y_axis = [1,2,3,4,5,6,7,8,9] x_axis = [100,105,115,95,90,88,110,100,0] DF = pd.DataFrame({'Y':y_axis, 'X':x_axis}) DF = DF[['Y','X']] DF['PCT'] = DF['X'].pct_change() Y X PCT 0 1 100 NaN 1 2 105 0.050000 ...
<pre><code>DF.assign(_PCT_=DF.X.pct_change(-1)) Y X PCT _PCT_ 0 1 100 NaN -0.047619 1 2 105 0.050000 -0.086957 2 3 115 0.095238 0.210526 3 4 95 -0.173913 0.055556 4 5 90 -0.052632 0.022727 5 6 88 -0.022222 -0.200000 6 7 110 0.250000 0.100000 7 8 100 -0.090909 inf 8...
python|python-2.7|pandas|percentage
5