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
351,600
70,642,617
How do I split parts of a dataframe by a character?
<p>I have this kind of input:</p> <pre><code>[[&quot;October&quot;, &quot;Steve&quot;, &quot;Apples&quot;], [&quot;November&quot;, &quot;Joe&quot;, &quot;Oranges&quot;], [&quot;December&quot;, &quot;James&quot;, &quot;Apples/Oranges&quot;] ] </code></pre> <p>I would like to split James' two occurrences in to separate...
<p>Assuming this input:</p> <pre><code> A B C 0 October Steve Apples 1 November Joe Oranges 2 December James Apples/Oranges </code></pre> <p>You could <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><cod...
python|pandas
2
351,601
70,494,486
Matplotlib Animation not completing
<p>I've tried to create an animation using Matplotlib, it seems to be animating correctly but it's not showing all the data points in the dataset. Its a time series from Jan 2020 to Dec 2021 - it seems to be animating to 2020-06 only right now.</p> <p>Below is the entire code</p> <pre><code>import yfinance as yf import...
<p>The basic form of the animation is to set the empty graph type and the x-axis and y-axis ranges, and then update the data with the animation function. It is rewritten in an object-oriented way because it is easy to set up the details. The animation is set to repeat for a number of records in a number of frames.</p> ...
python|pandas|matplotlib
1
351,602
70,582,759
Filtering pandas series based on patterns
<p>Happy new year!</p> <p>I have a quick question: Let's say I have a panda Series with 3 events like this</p> <pre><code>myEvents = pd.Series(['up', 'down', 'None', 'None, 'up', 'down', 'down', 'up', 'up']) </code></pre> <p>I would like to keep the 'valid' events only: A valid event is an up followed by a down or a do...
<p>Algorithm:</p> <ol> <li>Remove all &quot;None&quot; rows from the series</li> <li>Get a column of the previous row's value</li> <li>Filter out rows where the current is equal to the previous row's value</li> </ol> <p>Code:</p> <pre><code># 1) df = pd.DataFrame( {&quot;my_events&quot;: my_events} ) df = df[df[&quot...
python|pandas|state-machine
1
351,603
70,495,978
Cluster values within two columns in groups in pandas
<p>I have a <code>dataframe</code> like this:</p> <pre><code>VAL1 VAL2 A A B B E E F F G G H H I I J J A B A C B A B C C A C B D E E D F E E F G H H G I J J I I H H I K K </code></pre> <p>And I would like to cluster into <code>Groups</code> t...
<p>Create <a href="https://stackoverflow.com/a/53886179/2901002">connected_components</a> for list <code>L</code> and then convert to <code>DataFrame</code>:</p> <pre><code>import networkx as nx # Create the graph from the dataframe g = nx.Graph() g.add_edges_from(df[['VAL1','VAL2']].itertuples(index=False)) new = l...
python|python-3.x|pandas
1
351,604
70,454,171
pandas fill null values by the mean of that category (use loop?)
<p>I am trying to fill in the missing data in the data set based on the average of the values observed during that year, and it takes a long time to write one by one. I can't create this structure with a for loop. How should it be coded?</p> <pre class="lang-py prettyprint-override"><code>df['TOTAL_REVENUE'] = df.TOTAL...
<p>You'd do it like this (use <code>df[column]</code> instead of <code>df.column</code>):</p> <pre><code>for column in df.columns: df[column] = df[column].fillna(df.groupby('YEAR')[column].transform('mean')) </code></pre>
pandas|dataframe|pandas-groupby
0
351,605
70,579,291
Create new column using str.contains and based on if-else condition
<p>I have a list of names 'pattern' that I wish to match with strings in column 'url_text'. If there is a match i.e. <code>True</code> the name should be printed in a new column 'pol_names_block' and if <code>False</code> leave the row empty.</p> <pre><code>pattern = '|'.join(pol_names_list) print(pattern) 'Jon Kyl|D...
<p>Change your pattern to enclose it around a capture group <code>()</code> and use <code>extract</code>:</p> <pre><code>pattern = fr&quot;({'|'.join(pol_names_list)})&quot; df['pol_name_block'] = df['url_text'].str.extract(pattern) print(df) # Output &lt;- with the sample of @tlentali id url_text pol_name_...
python|pandas|lambda|apply
2
351,606
70,579,088
When running a loop using prange from numba to parallelize it, are elements appended in the same order?
<p>I am using numba prange to try to paralelize the following function:</p> <pre><code>@njit(parallel=True) def contrast_16bit(video): n = video.shape[0] #New max value high = 65535 video16 = [] for i in prange(n): data = video[i,:,:] #Old max and min vmin = np.mi...
<p>As for the literal question you're asking - no idea, and it's honestly hard to know without digging in the implementation, so I would honestly be scared to depend on the ordering of this parallelized operation.</p> <p>However, you can sidestep the whole issue by allocating an array instead: <code>video16 = np.empty(...
python|numpy|loops|parallel-processing|numba
1
351,607
70,474,556
Unix ms timestamp pandas index (plotting polygon.io data with mplfinance)
<p>I am pulling data from <a href="https://polygon.io/docs/stocks/get_v2_aggs_ticker__stocksTicker__range__multiplier___timespan___from___to" rel="nofollow noreferrer">polygon.io</a> and it returns time as a Unix Msec timestamp as below, afterwhich I am having trouble converting this to a index that is useable by mplfi...
<p>Try replacing</p> <pre class="lang-py prettyprint-override"><code>df.index = [from_unixtime(ts) for ts in df['t']] </code></pre> <p>with</p> <pre class="lang-py prettyprint-override"><code>df.index = pd.DatetimeIndex( pd.to_datetime(df['t'],unit='s') ) </code></pre> <p>lmk</p>
python|pandas|dataframe|mplfinance
1
351,608
70,693,764
OpenAIGPTModel PyTorch Error- ValueError: too many values to unpack (expected 2)
<p>I am having issues getting the Persona-Dialogue-Generation model(from github) to run. It seems that it should have only one output parameter but I provided two.How to modify the code?</p> <p>The problem code is</p> <p><code>self.transformer_module = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt',num_special_toke...
<p>It looks like <code>OpenAIGPTLMHeadModel</code> will only return <code>lm_logits</code>, so just remove <code>hidden_states</code> from model outputs. <code>lm_logits = self.transformer_module(input_seq, None, dis_seq)</code></p> <pre><code> def forward(self, input_ids, position_ids=None, token_type_ids=None, lm_...
python|pytorch
0
351,609
70,552,801
How to ignore NaNs when reassigning values to variables
<p>I imported and concatenated a couple of csv files. All of them contain the variable &quot;prac_type&quot; but the observations are listed in different ways. Some are strings (yes, no, unsure) while the others are numeric (1,2,3). Here is a look at the variable:</p> <pre><code>print(df.prac_type.unique()) [nan 1.0 2...
<p>Try <code>df.prac_type = [prac_dic.get(item) for item in df.prac_type]</code></p>
python|pandas
1
351,610
70,564,428
module 'pandas' has no attribute 'sparsedtype' - Catboost classifier
<p>I am working on catboost classifier algorithm and while doing model fit - I am getting this error -module 'pandas' has no attribute 'sparsedtype'. Any suggestion pls.</p> <p>I am using Pandas version - 0.23.4</p>
<p>SparseDtype was introduced in version 0.24.0 of pandas.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.SparseDtype.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.SparseDtype.html</a></p> <p>Install more recent version.</p>
pandas|catboost
0
351,611
70,449,518
Why am I getting Empty Dataframe message when using concat
<p>I am trying to view the predicted price for MSFT and I am referring to a book titled 'Machine learning and data science blueprints for finance'. It provides a sample code as a case study to determine the future stock price of MSFT. The code is below. However, when I start debugging it, the terminal shows the followi...
<p>This is because you drop all row containing <code>NaN</code>. You should replace</p> <pre><code>dataset = pd.concat([Y, X], axis=1).dropna().iloc[::return_period, :] </code></pre> <p>with</p> <pre><code>dataset = pd.concat([Y, X], axis=1).iloc[::return_period, :] </code></pre> <p>which returns:</p> <pre><code> ...
python|python-3.x|pandas|numpy|concatenation
1
351,612
70,535,511
Keep entry with least missing values for a given observation in dataframe
<p>I have a dataframe that includes US company identifiers (Instrument) as well as the company's Name, ISIN and it's CIK number.</p> <p>Here is an example of my dataset:</p> <pre><code>dict = { &quot;Instrument&quot;: [&quot;4295914485&quot;, &quot;4295913199&quot;, &quot;4295904693&quot;, &quot;5039191995&quot;, &quot...
<p>You could use the number of null values in a row as a sort key, and keep the first (lowest) of each <code>Instrument</code></p> <pre><code>import pandas as pd import numpy as np dict = { &quot;Instrument&quot;: [&quot;4295914485&quot;, &quot;4295913199&quot;, &quot;4295904693&quot;, &quot;5039191995&quot;, &quot;503...
python|pandas|dataframe
1
351,613
70,436,611
Fast way to check if a list of points is close to a list of linestrings in python with shapely and geopandas
<p>I have a large list of shapely points (around 150k) and a large list of shapely linestrings (around 240k). I was wondering if there was a fast way to check if these points are close to any of the linestrings.</p> <p>This was the code I used for 300 points and it took 387 seconds.</p> <pre class="lang-py prettyprint-...
<ul> <li>an approach that works well is <a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.sjoin_nearest.html" rel="nofollow noreferrer">https://geopandas.org/en/stable/docs/reference/api/geopandas.sjoin_nearest.html</a></li> <li>using UK motorway network for <em>LineString</em> and NHS hospitals for...
python|geometry|gis|geopandas|shapely
0
351,614
70,541,324
Is there anyway to load a .tflite without keras or tensorflow in python android app?
<p>I'm fairly new to this so please excuse mylack of knowledge. I'm trying to make an ML app with kivy, which detects certain objects. The problem is that I cannot include tensorflow and keras in my code because kivy doesn't allow apk conversion with it. So I came across tensorflow lite, which can run on android, but w...
<p>Sure. The easiest way is using TensorFlow Lite <a href="https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/package-summary" rel="nofollow noreferrer">Java API</a>, and it does not depend on TensorFlow or Keras at all.</p> <p>You can also read the TensorFlow Lite Android quick start <a href="https://ww...
android|tensorflow|model|tensorflow-lite
0
351,615
70,474,303
xml elements in elements to python dataframe
<p>i'm trying to convert the xml data into pandas dataframe. what i'm struggling is that i cannot get the elements in the element.</p> <p>here is the example of my xml file.</p> <p>i'm trying to extract the information of</p> <p>-orth :&quot;decrease&quot;</p> <p>-cre_date:2013/12/07</p> <p>-morph_grp -&gt; var type :&...
<p>Making some assumptions about what you want, here is an approach using XPath.</p> <p>I'm assuming you will be iterating over multiple XML files that each have one superEntry root node in order to generate a DataFrame with more than one record. Or, perhaps your actual XML doc has a higher-level root/parent element ab...
python|pandas|xml
0
351,616
70,562,477
How can I speed up raw data computation
<p>I have the temperature according to x,y,z as raw data.</p> <p>I want to turn the raw data of x, y, z, t into grid data.</p> <p>When transforming data by applying t values to the x and z coordinates according to z, I created a zero array and converted it into a pandas data frame.</p> <p>Afterwards, the data was proce...
<p>OK, so first I would create the temporary dataset with given <code>z</code></p> <pre><code>t_data = data[data['z']==0.25] </code></pre> <p>Then, I would create a new, transformed coordinates (if you would like to have resolution 1, 0.1, 0.01 it's quite easy):</p> <pre><code>t_data['x_new'] = t_data['x'].round(0) t_d...
python|pandas|heatmap
0
351,617
70,643,096
How to plot plotBox and a line plot with different axes
<p>I have a dataset that can be crafted in this way:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt date_range = pd.date_range(start='2021-11-20', end='2022-01-09').to_list() df_left = pd.DataFrame(columns=['Date','Values']) for d in date_rang...
<p>One of the problems is that <code>resample('W', on='Date')</code> and <code>.dt.strftime(&quot;%Y-%U&quot;)</code> seem to lead to different numbers in both dataframes. Another problem is that <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.boxplot.html" rel="nofollow noreferrer">boxplot</a> int...
pandas|dataframe|matplotlib|plot|boxplot
2
351,618
70,654,893
geopandas midpoint on line
<p>I have a geopandas dataframe of linestrings. Each line string is a single line.</p> <p>I want to get the midpoint of the line and append the point geometry to geodataframe in a column <code>centroid</code>.</p> <p>How do I achieve this?</p>
<ul> <li><strong>LineString</strong> has a centroid, hence case of using it</li> <li>solution demonstrates this with output as visual and as data</li> </ul> <pre><code>import geopandas as gpd import shapely.geometry import numpy as np world = gpd.read_file(gpd.datasets.get_path(&quot;naturalearth_lowres&quot;)) # pic...
python|geopandas
2
351,619
70,736,405
LSTM model with parameters
<p>I'm trying to make a LSTM model in Keras with the following parameters:</p> <p><a href="https://i.stack.imgur.com/rpLo7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rpLo7.png" alt="enter image description here" /></a></p> <p>However, I'm not sure my code is right.</p> <pre><code>model = Sequent...
<p>As per the your requirement below code can be used</p> <pre><code>model = Sequential() model.add(LSTM(16, return_sequences=True, activation='relu', input_shape=(3, 1))) #16 neurons (?) model.add(LSTM(32, return_sequences=True)) model.add(LSTM(64)) model.add(Dense(units =128)) model.compile(optimizer=tf.keras.op...
python|tensorflow|keras|lstm
0
351,620
70,737,939
The column label 'call_id' is not unique. For a multi-index, the label must be a tuple with elements corresponding to each level
<p>I have two PANDAS data-frames and I need to merge them on call_id. I have done this with different data frames. However, this time when I try</p> <pre><code>df = pd.merge(labels, sequences, on = &quot;call_id&quot;) </code></pre> <p>I get</p> <pre><code>The column label 'call_id' is not unique. For a multi-index, th...
<p>You have to call the merge function different:</p> <pre><code>labels.merge(sequences, how='inner', on='call_id') </code></pre> <p>Please look in the <code>how=</code> method here: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">https://pandas.pydata.org/do...
python|pandas
0
351,621
70,669,191
How to add new column in dataframe based on the other dataframe?
<p>Hi I have 2 dataframes but both are not same. I have to update one based on the 2nd.</p> <p>Example: df1:</p> <pre><code>Region Sub_Region Run_Date Status Reason ASPAC CRM 2022-01-11 Success ASPAC Genesys 2022-01-11 Failed LATAM CRM 2022-01-11 Success </code></pre> <p>df2:</p> <pr...
<p>Filter out your dataframe after <code>merge</code>:</p> <pre><code>df1['Max_Load_Date'] = df1.merge(df2, on=['Region', 'Sub_Region'], how='left') \ .query(&quot;Status == 'Success'&quot;)['Max_Load_Date'] print(df) # Output Region Sub_Region Run_Date Status Reason Max_Load_Date 0 ...
python|python-3.x|pandas|dataframe
0
351,622
70,549,144
plot and draw curves in python matplotlib without ignoring first and last Nan values from the graph figure
<p>I have csv format file like the below table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">depth</th> <th style="text-align: center;">x1</th> <th style="text-align: right;">x2</th> <th style="text-align: right;">x3</th> </tr> </thead> <tbody> <tr> <td style="te...
<p>You need to <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.sharey.html" rel="nofollow noreferrer">share the y axis with the other y axis</a>:</p> <pre><code>fig, axs = plt.subplots(1, 3, figsize=(15, 12), dpi=100, tight_layout=True, gridspec_kw={'wspace': 0}) axs[0].plot(df.x1, df.depth, '-o...
python|pandas|matplotlib
1
351,623
70,695,645
How to display Rows based on number of Days (From Dates) in Python Pandas
<p>I have a Dataframe which looks like below after some coding. Now, I want to display only those rows where &quot;Name&quot; is repeating 3 or more days.</p> <p>Sample Data Frame:</p> <p><a href="https://i.stack.imgur.com/q4u2D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q4u2D.png" alt="Sample D...
<p>Welcome u2k to Stackoverflow.</p> <p>You could try:</p> <pre><code>name_count = df.Name.value_counts() df[df.Name.isin(name_count.index[name_count.gt(2)])] </code></pre> <hr /> <p><strong>Output:</strong></p> <pre><code> Name Account 0 Ryan 1 1 Ryan 2 2 Ryan 3 3 Ryan 4 </code></pre> <hr /> ...
python|pandas|dataframe|datetime|timedelta
0
351,624
70,629,095
How do I store different arrays from an array in a list?
<p>I have a problem where I cant store different arrays in a list. I've got an array <code>displacement = [[0],[0],[0],[1],[5.5],[-7],[0],[0],[0]]</code> and I want to break it into <em>n</em> arrays with six rows and one column and then store the different arrays in a list.</p> <p>I tried this:</p> <pre><code> elem...
<p>It seems like you want to partition 'displacement' into 'element_count' elements of 'num_columns' (6 in your case) columns. Such that you populate each element in order from your 'displacement' array. (I assumed that if you want more elements with more columns than 'displacement' allows, you just butt up against the...
python|arrays|list|numpy|append
0
351,625
70,570,790
How to filter pandas dataframe to select list of column
<p>I have a dataframe with 100 columns and I want to select list of variables</p> <pre><code>ID A B C 0 day1 day10 Δday day1 day10 Δday day1 day10 Δday 1 1 1.0 2.0 1.0 1.5 2.5 1.0 3.0 2.0 -1.0 2 2 3.0 5.0 2.0 1.0 2.5 1.5 ...
<p>Try <code>slice(None)</code> to select any column at first level:</p> <pre><code>&gt;&gt;&gt; df.loc[:, (slice(None), 'Δday')] A B C Δday Δday Δday 0 1.0 1.0 -1.0 1 2.0 1.5 2.0 2 1.0 1.4 0.5 </code></pre> <p>To know more: <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced...
python|pandas|dataframe|pandas-groupby
1
351,626
70,707,996
matplotlib: horizontal labels as style
<p>Is there a parameter to force horizontal labels <strong>in an mplstyle file? and/or using rcParams</strong>?</p> <p>I'm currently using <code>ax.xaxis.set_tick_params(rotation=0)</code> at plot construction. I'd like a permanent style or setting. Thanks!</p> <p>Default look (with <code>x_compat=True</code> in a pand...
<p>Use parameter <code>rot</code> from <code>df.plot</code></p> <pre><code>df.plot(ax=ax, x='Date', x_compat=True, rot=0) </code></pre>
pandas|matplotlib
1
351,627
70,534,732
datetime index in plotting doesn't work. why?
<p>I want to plot one month of data [one data per hour. the dataset is over one year]. why is this code not working?</p> <pre><code>df_pv[&quot;Zeit&quot;] = pd.to_datetime(df_pv[&quot;Zeit&quot;]) df_pv[&quot;Zeit&quot;].min(), df_pv[&quot;Zeit&quot;].max() [Out] (Timestamp('2020-01-01 01:00:00'), Timestamp('2020-12-3...
<p>convert Zeit to datatime using pd.To_DateTime()</p> <pre><code>df_pv=pd.DataFrame() df_pv[&quot;Zeit&quot;] = pd.date_range(pd.Timestamp('2020-01-01 01:00:00'), pd.Timestamp('2020-12-31 00:00:00')) df_pv.set_index(&quot;Zeit&quot;, inplace=True) df_pv['y']=np.random.randn(len(df_pv)) df_pv.plot() </code></pre>
python|pandas|datetime|timestamp
0
351,628
70,599,172
Turn group of points into single pixel
<p>I have a b&amp;w image with 4 groups of points, and I need to transform each group into a single point.</p> <p>My idea was to find remove points by distance, so if a pixel is maybe 20px away from the other, I would turn remove one and keep the other, and repeat the process until I only got 4 pixels, but it doesn't s...
<p>Your idea is not so far from a workable solution. You can craft a simple algorithm that works as follows:</p> <ul> <li><p>scan the image in raster order until you meet a white pixel,</p> </li> <li><p>from this pixel, erase the whole connected component by seed-filling,</p> </li> <li><p>restore the initial pixel and ...
python|numpy|opencv|image-processing|computer-vision
2
351,629
43,007,467
Setting the shape of a tensor as the shape of another tensor
<p>I'm trying to run this piece of code:</p> <pre><code>def somefunc(x, rows, n_hidden): vectors = tf.contrib.layers.embed_sequence(nodes, vocab_size=vocab_size, embed_dim=n_hidden) batch_size = tf.shape(vectors)[0] state = tf.zeros([batch_size, rows, n_hidden]) bias = tf.Variable(tf.constant(0.1, shap...
<p>The <code>shape</code> argument of the <a href="https://www.tensorflow.org/api_docs/python/tf/constant" rel="nofollow noreferrer"><code>tf.constant()</code></a> op expects a <strong>static</strong> shape, so you can't use a <code>tf.Tensor</code> as part of the argument.</p> <p>Fortunately there is another op that ...
tensorflow
2
351,630
43,008,903
Does a column have only dates or also datetimes in pandas?
<p>I'm trying to write a function to assess whether a column in a pandas DataFrame has only dates or also datetimes, in order to decide whether to create a date or timestamp column in an external database.</p> <p>All dates in a DataFrame are stored as the same type, but date-only values would have no time component</p...
<p>I'd check to see if the <code>datetime</code> column is equal to its <code>date</code> component`</p> <p>Consider the dataframe <code>df</code></p> <pre><code>df = pd.DataFrame(dict( Date=pd.to_datetime( ['2017-03-01', '2017-03-01 00:00:00', '2017-03-01 00:00:01', ...
pandas|numpy
1
351,631
42,973,621
How to keep track of the label in supervised learning?
<p>I have 144 images named "Good_id" and "Bad_id".</p> <p>Now I have read all the images and extracted 13 features from them and stored in the numpy array of shape (144,13).</p> <p>What I don't understand is how do I tell the classifier( I am going to use svm for this ) that images in the array are from classes Good ...
<p>Save the classes into a separate array <code>y</code>, encoding "Good_id" as 1 and "Bad_id" as 0 (in the same order as they appear in your (144,13) array). Then when you use SVM you pass both numpy arrays, in the following way:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; X = np.array([[-1, -1], [-2,...
python|numpy|machine-learning|svm
2
351,632
42,743,167
how to fetch a value from a dataFrame cell to fill in value at another location?
<p>I have the following DataFrame:</p> <pre><code>ID | Parent ID | Direction 1 | 0 | North 2 | 1 | South 3 | 1 | West 4 | 0 | East </code></pre> <p>I want to write a function that will change the direction for all rows that have a non-zero 'Parent ID' to the Direction of the corre...
<p>You can try this:</p> <pre><code>to_replace = df['Parent ID'] != 0 df.loc[to_replace, 'Direction'] = df['Parent ID'][to_replace].map(df.set_index("ID").Direction) df </code></pre> <p><a href="https://i.stack.imgur.com/GMTYB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GMTYB.png" alt="ente...
python|pandas
1
351,633
42,865,972
dropping rows where date aligns with max value of another column in pandas
<p>I have a <code>DataFrame</code> named <code>au</code> from which I want to drop the rows where <code>date</code> aligns with observations where <code>bal==bal.max()</code>. For example, if <code>bal==bal.max()</code> is associated with <code>2009-08-01</code>, then I want to drop all other observations for which <co...
<p>Using <code>idxmax</code> and @jezrael's setup</p> <p><strong><em>setup</em></strong></p> <pre><code>au = pd.DataFrame({'bal':[1,2,3,4], 'date':['2009-08-01','2009-08-01','2009-08-02', '2009-08-02'], 'C':[7,8,9,1]}) </code></pre> <p><strong><em>solution</em></strong> </p> <...
python|pandas
3
351,634
42,708,031
Filtering a numpy array using another array of labels
<p>Given two numpy arrays, i.e:</p> <pre><code>images.shape: (60000, 784) # An array containing 60000 images labels.shape: (60000, 10) # An array of labels for each image </code></pre> <p>Each row of <code>labels</code> contains a <code>1</code> at a particular index to indicate the class of the related example in <...
<p>One way would be to convert your label array to bool and use it for indexing:</p> <pre><code>classes = [] blabels = labels.astype(bool) for i in range(10): classes.append(images[blabels[:, i], :]) </code></pre> <p>Or as a one-liner using list comprehension:</p> <pre><code>classes = [images[l.astype(bool), :] ...
python|arrays|numpy|filter
1
351,635
42,594,070
create dataframe from dataset loop func
<p>Hey I have problem creating dataframe from the boston dataset (can be found here: <a href="https://archive.ics.uci.edu/ml/datasets/Housing" rel="nofollow noreferrer">https://archive.ics.uci.edu/ml/datasets/Housing</a>)</p> <p>So this is my code:</p> <pre><code>data1 = DataFrame(data= np.c_[boston['data'], boston['...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_fwf.html" rel="nofollow noreferrer"><code>read_fwf</code></a>:</p> <pre><code>cols = ['col1','col2','col3','col4','col5','col6','col7', 'col8','col9','col10','col11','col12','col13','col14'] url = 'https://archive.ic...
python|pandas|dataframe
0
351,636
42,791,793
Pandas: convert series of time stamps keeping the YYYY-MM-DD format only
<p>Say you want to create a series of time stamps in the form <code>YYYY-MM-DD</code> from <code>1990-1-1</code> to <code>1991-12-31</code> with <code>pandas</code>:</p> <pre><code>import pandas import datetime start = datetime.date(1990, 1, 1) end = datetime.date(1991, 12, 31) s = pandas.Series(pandas.date_range(sta...
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>.dt.strftime</code></a> to output your dates in your desired string format:</p> <pre><code>In [114]: s.dt.strftime('%Y-%m-%d').head() Out[114]: 0 1990-01-01 1 1990-01-02 2 199...
python|date|pandas|datetime
3
351,637
42,735,183
Pandas: using dict (including operators) to return column subset from dataframe
<p>Let's say I got a data frame with columns <code>a, b, c, d, e</code> and a dictionary <code>{"A": "a", "B": "b", "E": "e"}</code></p> <p>a) How do I use this dictionary to return a new data frame (same index) with only those 3 columns (renamed to cap letters)?</p> <p>b) Alternatively, is there a way to drop any co...
<p>You could use <code>eval</code>-- not the Python function of the same name, but the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eval.html#pandas.DataFrame.eval" rel="nofollow noreferrer">DataFrame method</a>.</p> <pre><code>In [50]: df = pd.DataFrame(np.arange(15).reshape((3,5)),...
python|pandas|calculated-columns
4
351,638
42,628,577
Fastest way to cast all dataframe columns to float - pandas astype slow
<p>Is there a faster way to cast all columns of a pandas dataframe to a single type? This seems particularly slow:</p> <pre><code>df = df.apply(lambda x: x.astype(np.float64), axis=1) </code></pre> <p>I suspect there's not much I can do about it because of the memory allocation overhead of <code>numpy.ndarray.astype<...
<p>No need for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer"><code>apply</code></a>, just use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="noreferrer"><code>DataFrame.astype</code></a> directly. </p> <pr...
python|performance|pandas|numpy|dataframe
21
351,639
42,687,637
How to create and empty scatter plot with date on the x axis - Python, Pandas?
<p>I have a dataframe that looks like this:</p> <pre><code>date number_of_books ... (additional columns) 1997/06/01 23:15 3 1999/02/19 14:56 5 1999/10/22 18:20 7 2001/11/04 19:13 19 ... ... 2014/04/30 02:14 134 </code></pre> <p>My goal is to c...
<p>You could create a column in your <code>pd.DataFrame</code> to store the color information, and pass the arguments to each data point with the <code>scatter</code> plot function.</p> <p>See for example:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt # your dataframe df = pd.DataFrame({"date": ...
python-3.x|pandas|datetime|matplotlib|scatter
0
351,640
42,950,161
Python Numpy calculation without looping
<p>So I need to transform the following line </p> <pre><code>np.mean([-y[i] * X[i] * (1 - 1 / (1 + np.exp( - np.dot(X[i],w) * y[i]))) for i in range(X.shape[0])], axis = 0) </code></pre> <p>where <code>y.shape = (N,)</code>, <code>X.shape = (N,M)</code>, <code>w.shape = (M,)</code> and the output's shape has to be ...
<p>Here's one vectorized approach making use of the efficient <code>matrix-multiplication</code> with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow noreferrer"><code>np.dot</code></a> -</p> <pre><code>n = y.shape[0] exp_val = (1 - 1 / (1 + np.exp(-np.dot(X,w)*y))) out = -(...
python|performance|numpy|vectorization
1
351,641
42,615,702
What's a more efficient way to merge rows from DataFrames row-by-row with conditions?
<p>I'm joining two tables with data from two systems. A simple Pandas <strong>merge</strong> between two df won't honor more complex rules (unless I'm using it wrong, don't understand the process merge is implementing--very possible).</p> <p>I've cobbled together a <strong>toy solution</strong> that lets me unpack two...
<p>df3=df1.join(df2) does not do what you want?</p>
pandas|join|dataframe
0
351,642
42,693,387
Read url as pandas dataframe with column names (python3)
<p>I have read several questions regarding this topic, but nothing seems to work for me. </p> <p>I want to retrieve the data from this page "<a href="http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/heart.dat" rel="nofollow noreferrer">http://archive.ics.uci.edu/ml/machine-learning-databases/stat...
<p>The link you provided was missing a hyphen. I've corrected that in my answer. Basically you need to decode the <code>s</code> string into <code>utf-8</code>, then split it on <code>\n</code> to get each row and then split each row on white space to get each value separately. This will give you a nested list represen...
python|pandas|url
1
351,643
42,703,575
How do I separate a time stamp into separate columns with pandas?
<p>I would like to separate my timestamp into different columns, as I would like to sort my data by year. My time stamp looks like this: </p> <pre><code> 12/08/2011 11:04:13 AM </code></pre> <p>Sample of data:</p> <pre><code>BusinessName DBAName LegalOwner NameLast NameFirst ISSDTTM NEW GARDEN RESTAURA...
<p>For starters, the format you are passing to strptime, '%Y %m %d %H' doesn't match the date/time string you gave as an example. Also, your datetime is only in one column, why are you passing [1,2,3,4] in the parse_dates argument?</p> <p>Assuming the contents of your CSV are in a file called foo.csv (no header) and c...
python|pandas
0
351,644
42,970,106
ModuleNotFoundError: No module named 'tensorflow'
<p>When I'm importing TensorFlow with Spyder as so:</p> <pre><code>import tensorflow as tf </code></pre> <p>I then face the following error:</p> <blockquote> <p><strong>ModuleNotFoundError: No module named 'tensorflow'</strong></p> </blockquote> <p>How can I overcome this issue?</p>
<p>Since you plan to use tensforflow with Anaconda, you need to install it through Anaconda. It is advisable to do this as follows: </p> <ol> <li><code>C:&gt; conda create -n tensorflow</code></li> <li><code>C:&gt; activate tensorflow</code></li> <li><code>C:&gt; pip install --ignore-installed --upgrade https://stor...
python|tensorflow|jupyter|spyder
7
351,645
42,980,205
pandas agg for datetime returns incorrect result
<p>groupby.agg() return incorrect result(or at lease very misleading) for datatime series. Here is the code snippet (Pandas version : 0.19): </p> <pre><code>In [4]: df = pd.DataFrame({'A':[1,2,3,4],'B':pd.to_datetime("2017-01-01")}) In [5]: df Out[5]: A B 0 1 2017-01-01 1 2 2017-01-01 2 3 2017-01-01...
<pre><code>df.groupby("A")['B'].agg('nunique') </code></pre>
python|pandas
1
351,646
42,951,315
Represent negative timedelta in most basic form
<p>If I create a negative <code>Timedelta</code> for e.g. 0.5 hours, the internal representation looks as follow:</p> <pre><code>In [2]: pd.Timedelta('-0.5h') Out[2]: Timedelta('-1 days +23:30:00') </code></pre> <p>How can I get back a (<code>str</code>) representation of this <code>Timedelta</code> in the form <code...
<p>I can't add comment to you so adding it here. Don't know if this helps but I think you can use python humanize.</p> <pre><code>import humanize as hm hm.naturaltime((pd.Timedelta('-0.5h'))) </code></pre> <p>Out:</p> <pre><code>'30 minutes from now' </code></pre>
pandas|timedelta|python-datetime
1
351,647
42,804,573
TypeError: cannot do slice indexing on <class 'pandas.indexes.numeric.Int64Index'> with these indexers [(2,)] of <class 'tuple'>
<p>I've a user defined function as follows:-</p> <pre><code>def genre(option,option_type,*limit): option_based = rank_data.loc[rank_data[option] == option_type] top_option_based = option_based[:limit] print(top_option_based) top_option_based.to_csv('top_option_based.csv') return(top_option_based))...
<p>Consider the dataframe <code>rank_data</code></p> <pre><code>rank_data = pd.DataFrame(dict( genre=['Crime'] * 4 + ['Romance'] * 4 )) print(rank_data) genre 0 Crime 1 Crime 2 Crime 3 Crime 4 Romance 5 Romance 6 Romance 7 Romance </code></pre> <p>I'm going to assume you wanted to g...
python|python-3.x|pandas|slice|argument-unpacking
1
351,648
42,890,970
Pythonic way to convert a numpy array into another array with column indices
<p>So, what I want to do, given this input:</p> <pre><code>a=np.array([[5, 1, 10], [2, 3, 4]]) </code></pre> <p>convert into another np array:</p> <pre><code>[[(5, 0), (1, 1), (10, 2)], [(2, 0), (3, 1), (4, 2)]] </code></pre> <p>What's the pythonic way to do this?</p> <p>EDIT: I was using 1 indexing but 0 indexing...
<p>First your <code>a</code> expression is missing []</p> <pre><code>In [231]: a=np.array([[5, 1, 10], [2, 3, 4]]) # add extra [] In [232]: a Out[232]: array([[ 5, 1, 10], [ 2, 3, 4]]) </code></pre> <p>A list comprehension is the easiest way to produce the shown list</p> <pre><code>In [233]: [[(n,i+1) fo...
python|numpy
4
351,649
42,740,483
Convert array of integers into dictionary of indices
<p>I have a (large) integer array like</p> <pre><code>materials = [0, 0, 47, 0, 2, 2, 47] # ... </code></pre> <p>with few unique entries and I'd like to convert it into a dictionary of indices, i.e.,</p> <pre><code>d = { 0: [0, 1, 3], 2: [4, 5], 47: [2, 6], } </code></pre> <p>What's the most ef...
<p>no need for <code>numpy</code>, those are standard python structures, dict comprehension does that very well for your problem:</p> <pre><code>materials = [0, 0, 47, 0, 2, 2, 47] d = {v : [i for i,x in enumerate(materials) if x==v] for v in set(materials)} print(d) </code></pre> <p>result:</p> <pre><code>{0: [0,...
python|arrays|numpy
4
351,650
27,231,783
How to groupby an index as well as a column in pandas
<p>Let's say I have a simple dataframe which has an index of a datetime and three columns - one being a value and one being an aggregating indicator and the last being a unique identifier. The index is not unique across the dataframe, as it is duplicated over multiple instances of the indicator. ie it looks like this:<...
<p>You can do it like this:</p> <pre><code>&gt;&gt;&gt; df.reset_index().groupby(['index','aggregating indicator'])['val'].sum().reset_index() index aggregating indicator val 0 1-Jan set_a 4 1 1-Jan set_b 5 2 2-Jan set_a 6 3 2-Jan set_b ...
python|pandas|aggregate
2
351,651
27,174,771
Convert an numpy array with header to float
<p>I wanted to use the function <code>.astype(float)</code> to convert an array named Defocus_Array to float. But I got this error.</p> <pre><code>&gt;&gt;&gt; Defocus_Array.astype(float) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: could not convert string to float:...
<pre><code>Defocus_Array = np.array(('123.3', '0', 'defocus')) Defocus_Array.astype(float) # ValueError: could not convert string to float: defocus Defocus_Array[2] = 'nan' Defocus_Array.astype(float) # array([ 123.3, 0. , nan]) </code></pre> <p>Or, more generally:</p> <pre><code>Defocus_Array[Defocus_Array ...
python|arrays|numpy
1
351,652
27,191,310
install numpy and matplotlib of python2.7 numpy on window7 64 system
<p>I installed python 2.7 in the window 7 64-bit system, it works.However, when I install the numpy and matplotlib , the setup can not find the path, the version of matplotlib is 'matplotlib-1.4.2.win-amd64-py2.7.exe' it showed the error'Python version 2.7 required, which was not found in the regestry'.</p> <p>I have ...
<p>Alles, </p> <p>I think I did resolved the problems! </p> <p>The most tricky issue is </p> <p>when installing some Python Windows modules lies in: you have 64-bit Python, but a 32-bit installer of new modules.</p> <p>64-bit Python installer write to: HKLM|HKCU\SOFTWARE\</p> <p>while 32-bit installer looks at : H...
python|python-2.7|numpy|matplotlib
0
351,653
27,241,253
print the unique values in every column in a pandas dataframe
<p>I have a dataframe (df) and want to print the unique values from each column in the dataframe.</p> <p>I need to substitute the variable (i) [column name] into the print statement</p> <pre><code>column_list = df.columns.values.tolist() for column_name in column_list: print(df."[column_name]".unique() </code></p...
<p>It can be written more concisely like this:</p> <pre><code>for col in df: print(df[col].unique()) </code></pre> <p>Generally, you can access a column of the DataFrame through <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics" rel="noreferrer">indexing</a> using the <code>[]</code> opera...
python|for-loop|pandas
108
351,654
27,004,908
What actually happens when broadcasting a NumPy array
<p>I was playing around with NumPy and I've written simple function</p> <pre><code>&gt; def euclid_dist(x, y): ... return sqrt((x-y).transpose().dot(x-y)) </code></pre> <p>But now when I try</p> <pre><code>&gt; x = arange(1,4).reshape(3,1) &gt; y = array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]).transpose() &gt; z ...
<p>As I understand your question, you are trying to do a column-wise parallel dot product. In other words, for a matrix of vectors <code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code>, you want to take this:</p> <pre><code>[[a1, b1, c1, d1], [a2, b2, c2, d2], [a3, b3, c3, d3]] </code></pre> <p>To this...
python|numpy
2
351,655
14,549,696
Mipmap of image in numpy?
<p>I'm checking with you if there is a neat numpy solution to resizing down a 2D numpy array (which is an image) using bilinear filtering?</p> <p>More specifically, my array has the shape (width, height, 4) (as in a rgba image). The downscaling is also only done on "even" steps: i.e. from (w, h, 4) to (w/2, h/2, 4) to...
<p>I don't think there is any specific solution in numpy, but you should be able to implement it efficiently without leaving the comfort of python. Correct me if I'm wrong, but when the size of the image is divisible by 2, a bilinear filter is basically the same as averaging 4 pixels of the original image to get 1 pixe...
python|numpy
3
351,656
14,916,407
How do I stack vectors of different lengths in NumPy?
<p>How do I stack column-wise <code>n</code> vectors of shape <code>(x,)</code> where x could be any number?</p> <p>For example, </p> <pre><code>from numpy import * a = ones((3,)) b = ones((2,)) c = vstack((a,b)) # &lt;-- gives an error c = vstack((a[:,newaxis],b[:,newaxis])) #&lt;-- also gives an error </code></pre...
<p>Short answer: you can't. NumPy does not support jagged arrays natively.</p> <p>Long answer:</p> <pre><code>&gt;&gt;&gt; a = ones((3,)) &gt;&gt;&gt; b = ones((2,)) &gt;&gt;&gt; c = array([a, b]) &gt;&gt;&gt; c array([[ 1. 1. 1.], [ 1. 1.]], dtype=object) </code></pre> <p>gives an array that <em>may or may not</...
python|numpy
41
351,657
25,196,595
Memory optimization when selecting from a pandas dataframe
<p>I have a rather large pandas dataframe (1.7G) from which I am selecting some columns to do some computaton (find maximum value of the three selected columns). It seems that this operation is memory intensive. I am trying to find a way to avoid this memory overhead.</p> <p>For the purpose to this question, I a simpl...
<p>Pandas returns copies for most operations. Certain selection operations can return a <em>view</em>, in that the memory may not be copied and is an underlying numpy view. This is in general controlled by numpy. A taking operation like you are doing, (e.g. a non-consecutive) slice, will never give a view.</p> <p>Howe...
python|pandas
1
351,658
25,273,415
How to plot a PMF of a sample?
<p>Is there any function or library that would help me to plot a probability mass function of a sample the same way there is for plotting the probability density function of a sample ?</p> <p>For instance, using pandas, plotting a PDF is as simple as calling:</p> <pre><code>sample.plot(kind="density") </code></pre> ...
<p>If <code>ts</code> is a series, you may obtain PMF of the sample by:</p> <pre><code>&gt;&gt;&gt; pmf = ts.value_counts().sort_index() / len(ts) </code></pre> <p>and plot it by:</p> <pre><code>&gt;&gt;&gt; pmf.plot(kind='bar') </code></pre> <hr> <p>numpy only solution can be done using <a href="http://docs.scipy...
python|matplotlib|plot|pandas|scipy
15
351,659
25,065,697
Store to HDF, can't store frequency
<p>I have dataframe that has a custom frequency index, like so,</p> <pre><code>holidays = CustomBusinessDay(holidays=[ pnd.Timestamp(d) for d in pnd.Series.from_csv(f).values]) timestamps = pnd.date_range(s, e, normalize=False, freq = holidays) df = pnd.DataFrame(columns= ['a','b'], index= timestamps) </code></pre> <...
<p>Jeff's answer is correct. I was able to use format='table' and not get the error "can't set attribute 'freq' in node"</p>
python|pandas
0
351,660
25,274,270
How can I convert each Pandas Data Frame row into an object including the column values as the attributes?
<p>Suppose I have a DataFrame including following columns &quot;NAME&quot;, &quot;SURNAME&quot;, &quot;AGE&quot; and I would like to create one object for each row, including those column values as its variables.</p> <pre><code>person = ConvertRow2Object(frame.iloc[0,:]) print person.NAME //outputs Gary </code></pre> <...
<p>You can convert the whole thing to a numpy recarray, then each record in the array is attributed:</p> <pre><code>people = frame.to_records() person = people[0] print person.NAME // ... </code></pre> <p>Using a namedtuple also seems to work:</p> <pre><code>from collections import namedtuple Person = namedtuple('P...
python|pandas
14
351,661
25,168,058
Python pandas module openpxyl version issue
<p>My installed version of the python(2.7) module pandas (0.14.0) will not import. The message I receive is this:</p> <p>UserWarning: Installed openpyxl is not supported at this time. Use >=1.6.1 and &lt;2.0.0.</p> <p>Here's the problem - I already have openpyxl version 1.8.6 installed so I can't figure out what the ...
<p>The best thing would be to remove the version of openpyxl you installed and let Pandas take care.</p>
python|pandas|openpyxl|versions
0
351,662
25,071,554
How to feed sqlite query data to Pandas scatter_matrix
<p>I am successfully pulling data from a Fitbit sqlite db using Python sqlite3 as follows. I want to create Pandas scatter_matrix on the data. </p> <p>My code that successfully gets data is:</p> <pre><code>import pandas.io.sql as psql import sqlite3 as lite from pandas.tools.plotting import scatter_matrix con = lit...
<p>Looks like the pandas.io.sql read_sql has some additional parameters to get column headers. I changed the read_sql statement from</p> <pre><code>fitbit_data_psql = psql.read_sql(sql, con) </code></pre> <p>to </p> <pre><code>fitbit_data_psql = psql.read_sql(sql, con, index_col=None, coerce_float=True) </code></pre...
python|pandas
0
351,663
25,201,143
numpy.ndarray vs pandas.DataFrame
<p>I need to make a strategic decision about choice of the basis for data structure holding statistical data frames in my program.</p> <p>I store hundreds of thousands of records in one big table. Each field would be of a different type, including short strings. I'd perform multiple regression analysis and manipulati...
<p><code>pandas.DataFrame</code> is awesome, and interacts very well with much of numpy. Much of the <code>DataFrame</code> is written in Cython and is quite optimized. I suspect the ease of use and the richness of the Pandas API will greatly outweigh any potential benefit you could obtain by rolling your own interface...
python|python-3.x|numpy|pandas
25
351,664
30,311,211
Pandas groupby to find percent True and False
<p>I have a column of sites: ['Canada', 'USA', 'China' ....]</p> <p>Each site occurs many times in the SITE column and next to each instance is a true or false value.</p> <pre><code>INDEX | VALUE | SITE 0 | True | Canada 1 | False | Canada 2 | True | USA 3 | True | USA </code></pre> <p>And it goe...
<p>Something like this:</p> <pre><code>In [13]: g = df.groupby('SITE')['VALUE'].mean() In [14]: g[g &gt; 0.1] Out[14]: SITE Canada 0.5 USA 1.0 </code></pre>
python|python-2.7|pandas
14
351,665
30,562,678
python pandas get first available datapoint of a year / calculate YTD return
<p>I need to calculate the year-to-date relative return of a given dataset. I usually caculate the cumulative relative return with this simple function:</p> <pre><code>def RelPerf(price): RelPerf = (price/price[0]) return RelPerf </code></pre> <p>The problem ist that I need to set instead of "price[0]" the ...
<p>Use df for dataframe</p> <p>Group the data with TimeGrouper to get things grouped by year <code>GroupedDat = df.groupby(pd.TimeGrouper('A'))</code></p> <p>Create a new column with YTD data of adjusted close, using a transformation lambda function applied to our group data.</p> <p><code>df["YTD"] = GroupedDat['CLO...
python|pandas
0
351,666
30,670,121
Python u-law issues: unknown format: 7
<p>I'm trying to compare two large sets of wav files to remove duplicates. The issue is that one set is PCM, the other has been u-law'd. When I try to read in PCM wav, no problem, but the u-law files give the following error:</p> <pre><code>&gt;&gt;&gt; wav = wave.open("C:\\soundfiles\\Olympus Recordings\\1019.wav")...
<p>From <a href="https://docs.python.org/3/library/wave.html" rel="nofollow">the documentation</a> (emphasis mine):</p> <blockquote> <p>The <code>wave</code> module provides a convenient interface to the WAV sound format. <strong>It does not support compression/decompression</strong>, but it does support mono/stereo...
python|numpy|format|fft|wav
2
351,667
30,386,437
How does numpy.linalg.eig decide on order in which eigenvalues are returned?
<p>When I use <code>numpy.linalg.eig</code> like</p> <pre><code>eValues, eVectors = numpy.linalg.eig(someMatrix) </code></pre> <p>the eValues returned are almost in descending order.</p> <p>How does numpy.linalg.eig decide on order in which eigenvalues are returned?</p>
<p>Numpy makes no guarantees about that -</p> <p>from the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html" rel="nofollow">docstring</a>:</p> <pre class="lang-html prettyprint-override"><code>Returns ------- w : (..., M) array The eigenvalues, each repeated according to its multi...
python|numpy|linear-algebra|eigenvalue
3
351,668
30,507,442
Pandas: add dataframes to dataframe - match on index and column value
<p>I am trying to add pandas dataframes to another dataframe with different lengths such that the values in the result are aligned with both the (time)index and a key value from a column that is present in all dataframes. </p> <p>Say I want to combine df1,df2 and df3 and merge on index and column 'id':</p> <pre><code...
<p>If your DataFrames look like this:</p> <pre><code>import datetime as DT import numpy as np import pandas as pd df1 = pd.DataFrame({'id':[1,2,1,2], 'value1':[13,14,15,16]}, index=pd.DatetimeIndex(['2015-5-1', '2015-5-1', '2015-5-2', '2015-5-2'])) df2 = pd.DataFrame({'id':[1,1], 'value2':[4,5]}, index=pd.DatetimeInd...
python|pandas|merge
1
351,669
30,607,817
Pandas: How do I check for value match between columns in same dataframe?
<p>I am a complete coding novice and have been experimenting with Pandas. This is my first post. Thank you in advance for your help!</p> <p>I would like to remove any rows where cat1 does not match either dog1 or dog2. It does not have to match both, just one or the other. </p> <pre><code> cat1 dog1 dog2 0 re...
<p>This is really simple:</p> <pre><code>df.query('cat1 == dog1 or cat1 == dog2') </code></pre>
python|pandas
2
351,670
30,294,633
Applying zscore function for every row in selected columns of Pandas data frame
<p>With the following code:</p> <pre><code>import pandas as pd from sklearn.preprocessing import scale df = pd.DataFrame({"Probe":["1430378_at","1439896_at","1439896_at"], "Gene":["2900011G08Rik","Trappc5","Limk2"], "A.x1":[0.0767, 0.4383, 0.7866], "A.x2":[0...
<p>With Pandas it's often a good idea to try and use <code>apply</code> together with an anonymous function to perform your calculation on every row. Does this work for you?:</p> <pre><code> df.iloc[:,2:5] = df.filter(regex = 'A.x').apply( lambda V: scale(V,axis=0,with_mean=True, with_std=True,copy=Fals...
python|pandas
1
351,671
30,411,203
incorrect mean from PANDAS dataframe
<p>So here's an interesting thing:</p> <p>Using python 2.7:</p> <p>I've got a dataframe of about 5,100 entries, each with a number (melting point) in a column titled 'Tm'. Using the code:</p> <pre><code>self.sort_df[['Tm']].mean(axis=0) </code></pre> <p>I get a mean of:</p> <pre><code>Tm 92.969204 dtype: float6...
<p>A more readable syntax would be : </p> <pre><code>sort_df['Tm'].mean() </code></pre> <p>Try to do a <code>sort_df['Tm'].value_counts()</code> or <code>sort_df['Tm'].max()</code> to see what values are present. Some unexpected values must have crept up.</p> <p>The <code>.mean</code> function gives accurate result ...
python|python-2.7|pandas
1
351,672
30,455,638
How to bin all subsets of a python list into n bins
<p>I have a list:</p> <pre><code>a = range(2) </code></pre> <p>and I am trying to get the list's contents binned into n(=3) bins, in all possible ways, giving (order not important):</p> <pre><code>[[[],[0],[1]], [[],[1],[0]], [[],[0,1],[]], [[],[],[0,1]], [[0],[1],[]], [[0],[],[1]], [[1],[0],[]], [[1],[],[0]], [[0,1...
<p>Assuming I understand your aim (not sure what you might want to happen in cases of duplicate elements, namely whether you want to consider them distinct or not), you could use <code>itertools.product</code>:</p> <pre><code>import itertools def everywhere(seq, width): for locs in itertools.product(range(width),...
python|numpy|combinations|sympy|itertools
4
351,673
30,669,391
Custom reading CSV files (Keyword accesible / custom structure)
<p>I am trying to do the following: I downloaded a csv file containing my banking transactions of the last 180 days. I want to readin this csv file and then do some plots with the data. For that I setup a program that reads the csv file und makes the data avaible through keywords. e.g. in the csv file there is a column...
<p>Repeating your array generation without the extra code:</p> <pre><code>In [230]: dt=np.dtype([('date', 'S15'), ('value', '&lt;f8')]) In [231]: data=np.recarray((2,),dtype=dt) In [232]: type(data['date']) Out[232]: numpy.core.records.recarray In [233]: type(data['value']) Out[233]: numpy.ndarray </code></pre> <p>...
python|csv|numpy|matplotlib
0
351,674
30,675,679
Python returns instance instead of array
<p>The structure of my program is simple. I have two <code>.py</code> files, say <code>file1.py</code> and <code>file2.py</code>. <code>file1</code> is UI, <code>file2</code> is calculations. When a button is pressed, <code>file1</code> sends the user input to <code>file2</code> and <code>file2</code> does calculations...
<p>Since <code>Calculations</code> is a class, this line invokes the implicit constructor:</p> <pre><code>self.myPlotData = file2.Calculations(*user info*) </code></pre> <p>And you should know that the result of a constructor is an instance of the class. Which is exactly why you are getting that <code>type</code> inf...
python|numpy|matplotlib|plot|instance
0
351,675
30,384,908
Python keras neural network (Theano) package returns an error about data dimensions
<p>I have this code:</p> <pre><code>import numpy as np from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.optimizers import SGD from sklearn import datasets import theano iris = datasets.load_iris() X = iris.data[:,0:3] # we only take the first two features. Y = i...
<p>You specified the wrong output dimensions for your internal layers. See for instance this example from the Keras documentation:</p> <pre><code>model = Sequential() model.add(Dense(20, 64, init='uniform')) model.add(Activation('tanh')) model.add(Dropout(0.5)) model.add(Dense(64, 64, init='uniform')) model.add(Activa...
python|numpy|canopy|theano|keras
7
351,676
30,597,260
Merging a dataframe with a Series
<p>A co-worker of mine is trying to combine a matrix and a Series and is trying to see if there is a native pandas way to do so instead of using a loop.</p> <p>Example if I had a dataframe that consisted of</p> <pre><code>1, 2, 3 4, 5, 6 7, 8, 9 </code></pre> <p>and a Series with values</p> <pre><code>13, 14, 15 </...
<p>You can do this with merge. If you want the full Cartesian product, you can do the following:</p> <pre><code>import pandas as pd df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]]) df['key'] = 0 ser = pd.DataFrame({'data': [13,14,15], 'key': [0] * 3}) result = pd.merge(df, ser, on = 'key').drop('key', axis = 1) </code>...
python|pandas|merge|dataframe|series
2
351,677
30,298,144
datetime format change when save to csv file python
<p>I have a dataframe like this:</p> <pre><code>In [67]: call_df.head() Out[67]: timestamp types 1 2014-06-30 07:00:55 Call_O 2 2014-06-30 07:00:05 Call_O 3 2014-06-30 06:54:55 Call_O 501 2014-06-30 11:24:01 Call_O </code></pre> <p>When I saved that dataframe to csv file, the format of datetime is change as w...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html#pandas.DataFrame.to_csv" rel="noreferrer"><code>to_csv</code></a> accepts a <code>date_format</code> param, so please try this:</p> <pre><code>call_df.to_csv('D:/Call.csv', date_format='%Y-%m-%d %H:%M:%S') </code></pre> <p>...
python|pandas
14
351,678
30,284,478
Rollaxis error from numpy cross product in Python
<p>I have been trying to determine the source of my error for this simple script which takes a numpy.array as input and produces a new lattice from the dataset</p> <pre><code>def reciprocalLat(lattice): for i,a in enumerate(lattice): print a b[i]=numpy.cross(a[(i+1)%3],a[(i+2)%3],axis=0) #/numpy.dot(a[...
<p>With the newer version of <code>np.cross</code> (which uses rollaxis instead of swap), I can produce this error with:</p> <pre><code>In [663]: np_cross.cross(lat[0,0],lat[0,1],axis=0) --------------------------------------------------------------------------- ValueError Traceback (mos...
python|numpy|cross-product|vectormath
2
351,679
30,400,740
matlab read h5 file produced with pandas
<p>I have a csv file and I have transformed it in an h5 file with pandas:</p> <pre><code>data = pd.read_csv('file.csv') data.to_hdf('file.h5', 'table') </code></pre> <p>Now I would like to read it with matlab. </p> <p>How can I do that?</p> <p>I have tried </p> <pre><code>data = h5read('file.h5','/g4/lat'); </code...
<p>You need to export with <code>format='table'</code>, see docs <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#external-compatibility" rel="nofollow">here</a>.</p> <p>This is can be read by various <code>R</code> packages and should be ok in matlab, as this is plain vanilla <code>HDF5</code>, which some...
matlab|pandas|hdf
1
351,680
30,424,161
Write filenames to csv with Pandas and Regex
<p>How do I write a list of filenames to a column in a csv file, using Pandas? I also want to Regex to keep only a part of the filename.</p> <p>With the csv module, I have done like this:</p> <pre><code>import os import re import csv with open("file.csv","w") as write_csv: fieldnames = ["col1", "col2"] wr_he...
<p>Pandas dataframe can take a list as a constructor. The real question is where do you do the regex work. Here, I use the pandas string method <code>extract</code> which returns the captured group for each row.</p> <pre><code>pd.Series(os.listdir(directory)).str.extract(regex).to_csv(filename) </code></pre> <p>See <...
python|regex|python-2.7|pandas
2
351,681
26,584,465
Pandas Dataframe index from nested values in dictionary
<p>I am creating a pandas dataframe from historical weather data downloaded from weather underground.</p> <pre><code>import json import requests import pandas as pd import numpy as np import datetime from dateutil.parser import parse address = "http://api.wunderground.com/api/7036740167876b59/history_20060405/q/CA/San...
<p>Since the <em>dtype</em> held in <code>pretty</code> is just object, you can simply grab them to a list and get indexed. Not sure if this is what you want:</p> <pre><code># by the way, `r.json` should be without ()` wu_data = r.json df = pd.DataFrame.from_dict(wu_data["history"]["observations"]) # just index using...
python|dictionary|pandas
1
351,682
26,907,305
Pandas DataFrame insert column based on values in lists
<p>This may be a simple question. But I have wasted lot of time without figuring out what is happening here. I want to categorize HTTP requests in a web log file based on the resource extensions. Following is what I have tried.</p> <pre><code>imgstr = ['.png','.gif','.jpeg','.jpg'] docstr = [ '.pdf','.ppt','.doc'...
<p>I'd probably use regular expressions for this.</p> <pre><code>import pandas as pd import re def categoriser(x): if re.search('(.png|.gif|.jpeg|.jpg)', x): return 'A' elif re.search('(.pdf|.ppt|.doc)', x): return 'B' elif 'favicon.ico'in x: return 'C' elif 'robots.txt'in x: return 'D' elif 'GET / H...
python|pandas|dataframe
0
351,683
26,600,759
extra numbers showing up on my axes when i do multiple subplots in matplotlib
<p>hi folks first python question here!</p> <p>so big picture, i have a panel with 4 dataframes in it. i wanted a function that just plots the panel in 4 subplots, with a tiny bit of data processing on it..</p> <p>When i try to set up subplots i get weird numbers on both axes of my subplots 2 and higher. I dont know ...
<p>The problem is that your <code>plt.subplots(2,2)</code> call adds four AxesSubplot objects to the figure and the <code>fig.add_subplot()</code> calls each add one more*. You're plotting data to this second set of axes, which is why the rogue tick labels span zero to one. That's the default graph when you don't plot...
python|matplotlib|pandas
2
351,684
26,596,101
Converting long integers to strings in pandas (to avoid scientific notation)
<p>I want the following records (currently displaying as 3.200000e+18 but actually (hopefully) each a different long integer), created using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.excel.read_excel.html" rel="noreferrer">pd.read_excel()</a>, to be interpreted differently:</p> <pre><cod...
<p>Convert your column values with <code>NaN</code> into 0 then typcast that column as integer to do so.</p> <pre><code>df[['class_parent_ref']] = df[['class_parent_ref']].fillna(value = 0) df['class_parent_ref'] = df['class_parent_ref'].astype(int) </code></pre> <p>Or in reading your file, specify <code>keep_default...
python|pandas|long-integer
2
351,685
39,272,470
Average Time difference in pandas
<p>I am trying to calculate the average time difference, in hours/minutes/seconds, iterating on a field - in my example, for each different ip address. Moreover, a column containing the count of each ip row.</p> <p>My dataframe looks like:</p> <pre><code>date ipAddress 2016-08-08 00:39:00 98.249.24...
<p>See <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-different-functions-to-dataframe-columns" rel="noreferrer">applying different functions to dataframe columns</a>:</p> <pre><code>(df.groupby('ipAddress') .date .agg({'count': 'count', 'avg_time_diff': lambda group: group....
python|datetime|pandas
6
351,686
39,302,666
how to add column by using other column's conditions
<p>I have a dataframe.</p> <pre><code>df=pd.DataFrame({'month':np.arange(1,8)}) </code></pre> <p>So,I would like to add column by using 'month' columns</p> <pre><code>if 'month'=1,2,3 the elements = 'term1' 'month'=4,5 the elements = 'term2' 'month'=6,7 the elements = 'term3' </code></pre> <p>I wou...
<p>Use <code>numpy.where</code> and <code>Series.isin()</code> method could be one of the options to do it:</p> <pre><code>import numpy as np import pandas as pd df["term"] = np.where(df.month.isin([1,2,3]), "term1", \ np.where(df.month.isin([4,5]), "term2", "term3")) df # month term #0 1 te...
python|pandas
1
351,687
39,131,620
using a DataFrame with columns as named arguments to str.format()
<p>I have a DataFrame like:</p> <pre><code>import pandas as pd df = pd.DataFrame({'author':["Melville","Hemingway","Faulkner"], 'title':["Moby Dick","The Sun Also Rises","The Sound and the Fury"], 'subject':["whaling","bullfighting","a messed-up family"] }) </co...
<pre><code>&gt;&gt;&gt; ["Some guy {author} wrote a book called {title} that uses " "{subject} as a metaphor for the human condition.".format(**x._asdict()) for x in df.itertuples(index=False)] ['Some guy Melville wrote a book called Moby Dick that uses whaling as a metaphor for the human condition.', 'Some g...
python|pandas|string-formatting
3
351,688
39,390,616
Melding several columns by unique value
<p>I have a dataset with a lot of columns. The data is structured like this:</p> <pre><code>id Artist 1 Artist 2 Artist 3 1 Red hot 2 Wiz Red hot 3 Red hot Wiz Bronson 4 Bronson Bruce Red hot 5 Wiz Bronson 6 Red Hot </code></pre> <p>And I need it to ...
<p>I think you can use:</p> <pre><code>#if column `id` is not index, first set it to index df.set_index('id', inplace=True) #create multiindex from columns df.columns = df.columns.str.split(expand=True) print (df) Artist 1 2 3 id 1 Red hot ...
python|excel|pandas
0
351,689
39,262,647
Tensorflow sum tensor from before and after queue
<p>What would happen with this: <a href="https://i.stack.imgur.com/jPy6s.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jPy6s.jpg" alt="enter image description here"></a></p> <p>What I want is that (out1, out2) to the summation is from the same input. However, as Queue2 is continuously doing enqueu...
<p>The easiest way to make this work is to enqueue <code>out1</code> into <code>queue2</code> alongside the result of <code>op1(out1)</code>. Here's a rough example of how it would look, using two <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#FIFOQueue" rel="nofollow"><code>tf.FIFOQueue...
tensorflow
1
351,690
39,104,928
Pandas, map two dataframes, count based on condition
<p>I have written some code to map the ids of two dataframes and if a condition matches then create a count in a specified column in the existing dataframe, I am looking for a more efficient way of calculating it. </p> <p><strong>Sample Data</strong></p> <pre><code>import numpy as np import pandas as pd d = {'ID' : p...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p> <pre><code>print (pd.crosstab(df1.ID, df1.Tag)) ...
python|pandas|dataframe
2
351,691
39,207,890
Efficient way to make numpy object arrays intern strings
<p>Consider numpy arrays of the <code>object</code> dtype. I can shove anything I want in there.</p> <p>A common use case for me is to put strings in them. However, for very large arrays, this <em>may</em> use up a lot of memory, depending on how the array is constructed. For example, if you assign a long string (e.g....
<p>Here's one way to do it, using a dictionary whose values are equal to its keys:</p> <pre><code>seen = {} for idx, string in enumerate(file): arr[idx] = seen.setdefault(string, string) </code></pre>
python|numpy
2
351,692
39,384,539
How to read data in chunks in Python dataframe?
<p>I want to read the file f in chunks to a dataframe. Here is part of a code that I used.</p> <pre><code>for i in range(0, maxline, chunksize): df = pandas.read_csv(f,sep=',', nrows=chunksize, skiprows=i) df.to_sql(member, engine, if_exists='append',index= False, index_label=None, chunksize=chunksize) </code></pre> ...
<p>I think it is better to use the parameter <code>chunksize</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer"><code>read_csv</code></a>. Also, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>conc...
python|csv|pandas|dataframe|chunks
5
351,693
38,969,267
python pandas selecting columns from a dataframe via a list of column names
<p>I have a dataframe with a lot of columns in it. Now I want to select only certain columns. I have saved all the names of the columns that I want to select into a Python list and now I want to filter my dataframe according to this list. </p> <p>I've been trying to do:</p> <pre><code>df_new = df[[list]] </code></pre...
<p>You can remove one <code>[]</code>:</p> <pre><code>df_new = df[list] </code></pre> <p>Also better is use other name as <code>list</code>, e.g. <code>L</code>:</p> <pre><code>df_new = df[L] </code></pre> <p>It look like working, I try only simplify it:</p> <pre><code>L = [] for x in df.columns: if not "_" i...
python|pandas|dataframe
40
351,694
39,093,727
Tensorflow: Dequeue and then enqueue
<p>I have a queue (called <code>queue_A</code>) and populate 100 elements inside. If I would like to do the following 2 things:</p> <ol> <li>Dequeue 1 element from <code>queue_A</code>, do some processing on it and enqueue the result into another queue (<code>queue_B</code>). The enqueuing op is called <code>op_B</cod...
<p>The code in your example has two types of "queue runner":</p> <ol> <li>One that runs <code>op_A</code>: it dequeues an element from <code>queue_A</code>, and enqueues it back to <code>queue_B</code>.</li> <li>Another that runs <code>op_B</code>: it dequeues an element from <code>queue_A</code>, processes it via <co...
tensorflow
3
351,695
39,355,717
Having issue summarising python dataframe to one line per record
<p>I've got a dataframe in the form:</p> <pre><code>df = pd.DataFrame({'id':['a', 'a', 'a', 'b','b'],'var':[1,2,3,5,9]}) </code></pre> <p>and I'm trying to reshape it so that there is one line per 'id' and the values 'var' are displayed across in one line, so 'a' would have 1,2,3 ... 'b' would have '5,9'</p> <p>I've...
<p>You must supply the correct arguments, like:</p> <pre><code>pd.crosstab(index=df['id'], columns=df['var']) var 1 2 3 5 9 id a 1 1 1 0 0 b 0 0 0 1 1 </code></pre>
python|pandas|dataframe|pivot-table
3
351,696
38,965,667
Pandas: take whichever column is not NaN
<p>I am working with a fairly messy data set that has been individual csv files with slightly different names. It would be too onerous to rename columns in the csv file, partly because I am still discovering all the variations, so I am looking to determine, for a set of columns, in a given row, which field is not NaN a...
<p>For a dataframe with an arbitrary number of columns, you can back fill the rows (<code>.bfill(axis=1)</code>) and take the first column (<code>.iloc[:, 0]</code>):</p> <pre><code>df = pd.DataFrame({ 'A': [15, None, None, None, 12], 'B': [None, 11, 99, None, 14], 'C': [10, None, 10, 10, 10]}) df['D'] = ...
python|pandas
6
351,697
39,051,676
Expanding each element in a (2-by-2) matrix to a (3-by-2) block
<p>I want to expand each element in a (2-by-2) matrix to a (3-by-2) block, using Python 3 --- with professional and elegant codes. Since I don't know the python codes, I will just describe the following in maths</p> <pre><code>X = # X is an 2-by-2 matrix. 1, 2 3, 4 d = (3,2) # d is the s...
<p>If you are okay with using <a href="http://www.numpy.org/" rel="nofollow"><code>NumPy module</code></a> with Python, you can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.kron.html" rel="nofollow"><code>numpy.kron</code></a> -</p> <pre><code>np.kron(X,np.ones((3,2),dtype=int)) </code...
matlab|python-3.x|numpy|matrix
3
351,698
39,116,088
TypeError in Countvectorizer scikit-learn: Expected string or buffer
<p>I am trying to solve a classification problem. when I feed the text to CountVectorizer it gives error: </p> <blockquote> <p>expected string or buffer. </p> </blockquote> <p>Is anything wrong with my dataset as it contains message mixture of number and word even special character is also in message.</p> <p>Sampl...
<p>You need convert column <code>message</code> to <code>string</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>, because in data are some numeric values:</p> <pre><code>df = pd.read_excel('training_data.xlsx') df['message'] = df...
python-2.7|pandas|dataframe|scikit-learn|text-classification
1
351,699
39,028,903
Transforming column dataframe pandas into sequence
<p>I have data and convert into dataframe</p> <pre><code>d = [ (1,70399,0.988375133622), (1,33919,0.981573492596), (1,62461,0.981426807114), (579,1,0.983018778374), (745,1,0.995580488899), (834,1,0.980942505189) ] df = pd.DataFrame(d, columns=['source', 'target', 'weight']) &gt;&gt;&gt; df source tar...
<p>You can use:</p> <pre><code>#remember original values source_old = df.source.copy() df.source = (df.source.diff() != 0).cumsum() - 1 #series for maping ser = pd.Series(df.source.values, index=source_old).drop_duplicates() print (ser) source 1 0 579 1 745 2 834 3 dtype: int32 #map where values exist...
python|pandas
0