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
362,600
28,735,609
Cryptic warning pops up when doing pandas assignment with loc and iloc
<p>There is a statement in my code that goes:</p> <pre><code>df.loc[i] = [df.iloc[0][0], i, np.nan] </code></pre> <p>where <code>i</code> is an iteration variable that I used in the <code>for</code> loop that this statement is residing in,<code>np</code> is my imported numpy module, and <code>df</code> is a DataFrame...
<p>Without seeing how you are doing this, if you just want to set the 'Cycles' column then the following would work without raising any warning:</p> <pre><code>In [344]: for i in range(len(df)): df.loc[i,'cycles'] = np.nan df Out[344]: build_number name cycles 0 390 adpcm NaN 1 390 ...
python|pandas|numpy|pandas-loc
0
362,601
28,828,973
Pandas get the index of an element in a map function
<p>I am using pandas to analyse existing ssh sessions to different nodes, for that I have parsed the ssh daemon log and I have a DataFrame that contains the following columns:</p> <ul> <li>Node: the name of the node where the connection was established</li> <li>Session: the ID of the session</li> <li>Start: timestamp ...
<pre><code>def count(df): count_sessions = lambda t: df[(df.Start&lt;t) &amp; (df.Finish&gt;t)].shape[0] df['OpenSessions'] = df['Start'].map(count_sessions) return df print sessions.groupby('Node').apply(count) </code></pre> <p>The output is:</p> <pre><code> Node Session Start ...
python|pandas
1
362,602
28,615,636
Python pandas - trying to a dict of df's into a panel (or loop the df items into a panel)
<p>I have stock data in a dataframe with column headings like AAPL, AAPL_ma, MSFT, MSFT_ma -- and would like to somehow get the data into a panel with items = stock symbols (so AAPL item would include AAPL and AAPL_ma). </p> <p>I am new to pandas and am struggling to come up with a coherent plan. I can't figure out if...
<p>Your easiest way to the promised land would be to create a multi index dictionary with keys being tuples like (aapl, aapl) and (aapl,aapl_ma) and then doing a pandas.Dataframe() on the dictionary. <a href="http://pandas.pydata.org/pandas-docs/dev/advanced.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev...
python|pandas|split|dataframe|multi-index
1
362,603
51,095,085
How to merge month and year columns to get single mm-yyyy column?
<p>I have a df like this:</p> <pre><code>Sr. lwd_month lwd_year 1 3 2015 2 6 2018 3. 9 2017 4. NaN NaN 5. 5 2015 </code></pre> <p>How can I merge this two columns to get dataframe like below?:</p> <pre><code>Sr. lwd_month lwd_Year MonthYear 1 3 201...
<p>Why not just this:</p> <pre><code>df['MonthYear'] = pd.to_datetime(df[['Year', 'Month']].assign(Day=1)).dt.strftime('%m-%Y') print(df) </code></pre> <p>Output:</p> <pre><code> Sr. Month Year MonthYear 0 1.0 3.0 2015.0 03-2015 1 2.0 6.0 2018.0 06-2018 2 3.0 9.0 2017.0 09-2017 3 4.0 N...
python|pandas|datetime
2
362,604
50,961,821
setting two different multiple regression layers
<p>I'm now working on a small project, but I don't know how I should build the model. </p> <p>So, the number of inputs is 27, outputs is 163. </p> <p>I need to find weights and biases by training, and I am done with this by using 5 layers including relu and dropout.</p> <p>When I see a cost graph about training loss...
<p>You may incorporate a uniformity constraint into your loss function during training.</p> <pre><code>def my_loss(labels, predictions): lambda_ = 0.01 return tf.losses.mean_squared_error(labels, predictions) + \ lambda_ * uniformity(labels) / uniformity(predictions) </code></pre>
python|tensorflow
0
362,605
50,701,990
Changing only one row to column in Python
<p>So the data frame is</p> <pre><code>computer status count A on 45 off 44 B on 34 off 32 rmt_off 12 C on 23 off 23 rmt_off 2 </code></pre> <p>I performed</p> <pre><code>df.set_index('status').T </code></p...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> if <code>MultiIndex</code> one column <code>DataFrame</code>:</p> <pre><code>print (df.index) MultiIndex(levels=[['A', 'B', 'C'], ['off', 'on', 'rmt_off']], la...
python-3.x|pandas|group-by
3
362,606
51,011,470
row selection and loc masking and slicing in one command
<p>I'd like to be able to make rows selection and masking and slicing in one command.<br> Currently I use two steps. </p> <pre><code>df Out[126]: A B C D 2018-06-24 -2.198394 0.224622 0.990230 0.390609 2018-06-25 0.644388 -1.196015 1.859241 0.444789 2018-06-26 0.7088...
<p>No it is not possible, need create boolean mask for check index values like in <a href="http://pandas.pydata.org/pandas-docs/stable/cookbook.html#dataframes" rel="nofollow noreferrer">cookbook</a>.</p> <p>I think your solution is nice, but if need one line solution need new condition with comparing numpy array crea...
python|pandas
1
362,607
50,877,663
Memory efficient way to store bool and NaN values in pandas
<p>I am working with quite a large dataset (over 4 GB), which I imported in <code>pandas</code>. Quite some columns in this dataset are simple True/False indicators, and naturally the most memory-efficient way to store these would be using a <code>bool</code> dtype for this column. However, the column also contains som...
<p>Use dtype: <a href="https://docs.scipy.org/doc/numpy/user/basics.types.html" rel="noreferrer"><code>int8</code></a></p> <pre><code>1 = True 0 = False -1 = NaN </code></pre> <p>This is 4 times better than <code>float32</code> and 8 times better than <code>float64</code></p>
python|python-3.x|pandas|memory|nan
8
362,608
50,862,909
pandas: get the highest values in an entire dataframe, and row/col values?
<p>I have a pandas dataframe, of sales by department by year:</p> <pre><code> department 2001 2002 2003 ... Food 1300 1444 1573 ... Music 1370 1244 1173 ... </code></pre> <p>I want to find the 10 highest values across the whole dataset, and see the department and year ...
<p>You could use something like this (simple case of 3-largest here):</p> <pre><code>&gt;&gt;&gt; df.stack().sort_values(ascending=False).nlargest(3) sports 2002 72 music 2001 67 sports 2001 54 dtype: int64 </code></pre> <p>To create this example:</p> <pre><code>import pandas as pd import numpy as np n...
python|pandas
2
362,609
51,054,958
Load multiple DNN models in tensorflow and use them multiple times
<p>I have checkpoints of two models of Inception-v3 (.data,.index,.meta files)</p> <p>I want to load them both into memory in the beginning of the program and use them simultaneously in a while loop.</p> <pre><code>load model1 load model2 while True : predict output from model1 predict output from model2 </co...
<p>Here is the following code I used to solve this.</p> <pre><code>turn_graph = tf.Graph() posn_graph = tf.Graph() with turn_graph.as_default(): from models import inception_v3 as googlenet turn_model = googlenet(227,227,3,1.0e-3,output=4) turn_model.load('turn_model_01') with posn_graph.as_default(): ...
python|tensorflow|machine-learning|deep-learning
0
362,610
51,093,678
How to train model with two kids functions for object detection?
<p>I'm trying to implement the model described by Professor Andrew Ng for <a href="https://youtu.be/cz-ttO-cKNk" rel="nofollow noreferrer">object detection</a> (explanation starts at 10:00).</p> <p>He describes the first element of the output vector as the probability that an object was detected, followed by the coord...
<blockquote> <p>How do I implement this conditional loss in tensorflow?</p> </blockquote> <p>You can convert the loss function to:</p> <pre class="lang-py prettyprint-override"><code>Error = mask[0]*(y^[0]-y[0])**2 + mask[1]*(y^[1]-y[1])**2 ... mask[n]*(y^[n]-y[n])**2), where mask = [1, 1,...1] for y[0] = 1 and [...
tensorflow|machine-learning|conv-neural-network|object-detection
1
362,611
50,912,255
Change axis for pandas replace ffill
<p>Suppose I have a dataframe that looks like:</p> <pre><code>df = 0 1 2 0 1.0 2.0 3.0 1 4.0 5.0 NaN 2 6.0 NaN NaN </code></pre> <p>Then it is possible to use <code>df.fillna(method='ffill', axis=1)</code> to obtain:</p> <pre><code> 0 1 2 0 1.0 2.0 3.0 1 4.0 5.0 5.0 2 6.0...
<p>Use <code>mask</code> and <code>ffill</code></p> <pre><code>df.mask(df.eq(-1)).ffill(axis=1) 0 1 2 0 1.0 2.0 3.0 1 4.0 5.0 5.0 2 6.0 6.0 6.0 </code></pre>
python|pandas|dataframe|fillna
5
362,612
51,007,852
Pandas method to apply a function on the entire DataFrame
<p>I have created a function where I need to pass data frame I get shape and return me df.head() </p> <pre><code> def shape_of_df(df): tup = df.shape print('Shape of df is Rows :{0[0]},column:{0[1]}'.format(tup)) return df.head() </code></pre> <p>Now when I call function with items.apply(s...
<p>The first line of the docs explains that <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> will "Apply a function along an axis of the DataFrame" (i.e., along the rows or along the columns). </p> <p>You want to app...
python|pandas|function|dataframe|apply
3
362,613
50,889,192
input and filter must have the same depth: 32 vs 16 when using MKL and channels first format
<p>I compiled tensorflow from source with MKL in order to accelerate my DNN learning progress. And I have a ResNet model which is copy from <a href="https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10_estimator" rel="nofollow noreferrer">tensorflow/models</a>. The dataset is CIFAR-10. When I run th...
<p>No need to transpose the data for changing the dataformat. You can pass the data format as channels first or channels last as argument</p> <p>For example, python cifar10_main.py --data-dir=${PWD}/cifar-10-data --data-format=channels_first --job-dir=/tmp/cifar10</p>
python|tensorflow
1
362,614
50,821,660
Data augmentation using python function with tf.Dataset API
<p>I'm looking for dynamically read images and apply data augmentation for my image segmentation problem. From what I've looked so far the best way would be the <code>tf.Dataset</code> API with <code>.map</code> function.</p> <p>However, from the examples I've seen I think I'd have to adapt all my functions to tensorf...
<p>py_func is limited by the python GIL, so you won't get much parallelism there. Your best bet is to write your data augmentation in tensorflow proper (or to precompute it and serialize it to disk).</p> <p>If you do want to write it in tensorflow you can try to use tf.contrib.autograph to convert simple python ifs an...
python|tensorflow|deep-learning|dataset|tensorflow-datasets
1
362,615
50,899,901
plotting a vbar_stack using a dataframe
<p>I'm struggling to get a stacked vbar working.</p> <p>With python/pandas and bokeh I want to plot several statistics about the players of a football team. The dataframe is nicely filled, the values are a string where they should be an <code>int</code> where it should be a numeric value.</p> <p>I used the sample of ...
<p>When using categorical ranges, you have to tell <code>figure</code> what the categories for the axis are and what order you want them to show up, e.g. provide <code>x_range</code> something like:</p> <pre><code># specify all the factors for the x-axis by passing x_range p = figure(..., x_range=sorted(df.naam.unique...
python|pandas|bokeh
0
362,616
50,911,316
Plotting an excel sheet using python and matplotlib?
<p>I currently have an excel file that is in this format:</p> <pre><code>PS PSX1 PSX2 PSX3 PSX4 I P V I P V I P V I P V States Idle # # # # # # # # # # # # Data=Addr(R) # # # # # # # # # ...
<p>Use pandas to clean your data. Depending on your data this can be achieved in different ways. You can use pandas built-in functions:</p> <pre><code>your_dataframe_here.dropna(inplace=True) </code></pre> <p>This will delete all NaN values, however, this is not an optimal approach. You should rather replace the NaN...
python|pandas|matplotlib
1
362,617
51,033,792
How to interpret a ML training output
<p>I'm a beginner in Machine Learning and I'm learning through working on Kaggle competitions. I've started off with the famous Titanic survival problem and through trial-error/getting help from others, I am able to train my data but my question is: How do I make sense of the output and proceed to the next stage?</p>...
<p>You now compare your <code>val_predictions</code> with <code>val_y</code> and see how many you got right! </p> <p>You used <code>train_x, train_y</code> to find the pattern, you fit it on <code>val_x</code> and now you want to see how good your model is! </p> <p>There are multiple ways to go about this! You can ch...
python|pandas|numpy|machine-learning|scikit-learn
2
362,618
50,912,407
pandas read_csv for a gziped file is not infering numeric columns types
<p>When I read a CSV file using:</p> <pre><code>train_data= pd.read_csv("train.pk", header=True, encoding='Latin-1') </code></pre> <p>I get all columns types inferred quite accurately. For example <code>IDs</code> with any length are inferred <code>int64</code>.</p> <p>Now doing the same, with a gziped file, pandas ...
<p>I cannot replicate your issue. However, downcasting need not be a manual process. You can select integer columns via <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>pd.DataFrame.select_dtypes</code></a>:</p> <pre><code>df = pd.Data...
python|pandas|dataframe
1
362,619
50,940,768
Tensorflow: TypeError: Expected binary or unicode string, got <tf.Tensor 'Placeholder:0' shape=<unknown> dtype=string>
<p>Here is the code:</p> <pre><code>filename = tf.placeholder(tf.string) image_raw_data = tf.gfile.FastGFile(filename, "rb").read() image = tf.image.decode_jpeg(image_raw_data) with tf.Session() as sess: sess.run(image, feed_dict={filename: "4.jpg"}) </code></pre> <p>Here is the error:</p> <pre><code>Traceback ...
<p>The function expects a string or byte string not a tensor or placeholder. What you are looking for is tf.io.readfile()... Here is an example with a dataset, but it can be used as the replacement in your code to tf.gfile</p> <pre><code>#placeholder for list of filenames filenames = tf.placeholder(tf.string) # Using...
python|tensorflow
1
362,620
50,976,898
how to merge data frames with same format in python
<p>Looked at other similar questions, but none has the use case I have. I have multiple files with the same format and no header </p> <pre><code>file1 id, value 1, 100 2, 150 ... file2 10, 500 11, 510 .... </code></pre> <p>I would like to "merge" them to have</p> <pre><code>id, value 1, 100 2, 150 ... 10, 500 11,...
<p><code>concat</code> should also work for you. <a href="https://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/merging.html</a></p> <p>You should also name each column upon import...</p> <p><code>pd.read_csv(work_dir+'/'+file_name, header=No...
python|pandas
0
362,621
51,073,350
CSV Text Read/Write into new file based on keywords
<p>I am trying to extract certain words, I have defined as keywords by reading a single column in one file and creating a new column with these words (if present)... </p> <p>So far, I have:</p> <pre><code>import pandas as pd keywords= {"these", "are", "my", "keywords", "defined"} df = pd.read_csv("this_is_my_file....
<p>This is the solution, if i understood your question correctly:</p> <pre><code>import pandas as pd keywords = ['a', 'b'] df = pd.DataFrame() df['keywords'] = ['1', 'a', 'd', 'b'] df['contents'] = ['foo','foo','foo','foo',] filtered_df = df[df['keywords'].isin(keywords)] </code></pre> <p>In the last line we use df...
python|python-3.x|pandas
0
362,622
50,737,973
tensorflow : Analysing images gives Cannot feed value of shape (1296000,) for Tensor 'Placeholder:0', which has shape '(?, 1296000)'
<p>I am using tensorflow to build a multilayer_perceptron network, based on the example given by <a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3_NeuralNetworks/neural_network_raw.ipynb" rel="nofollow noreferrer">Google</a></p> <p>The point is to train images to recognize specific...
<p>You're feeding a single element with shape <code>(1296000)</code>, that's a 1-D tensor. Your placeholder, (at in general every tensorflow input) instead, want's a batch of elements.</p> <p>Hence you have to feed your network a <code>(batch_size, X)</code> tensor. If you want to feed one element at a time, you can u...
python|tensorflow
1
362,623
50,921,058
Python - Finding most occurring words in a CSV row
<p>I want to find the most occurring substring in a CSV row either by itself, or by using a list of keywords for lookup. </p> <p>I've found a way to find out the top 5 most occurring words in each row of a CSV file using Python using the below responses, but, that doesn't solve my purpose. It gives me results like - ...
<p>Let, <code>my_values = ['A', 'B', 'C', 'A', 'Z', 'Z' ,'X' , 'A' ,'X','H','D' ,'A','S', 'A', 'Z']</code> is your list of words which is to sort.</p> <p>Now take a list which will store information of occurrences of every words.</p> <pre><code>count_dict={} </code></pre> <p>Populate the dictionary with appr...
python|python-2.7|pandas|csv|numpy
0
362,624
50,964,051
Convergence issues in a3c
<p>I've built an A3C implementation in keras using this as referance: <a href="https://jaromiru.com/2017/03/26/lets-make-an-a3c-implementation/" rel="nofollow noreferrer">https://jaromiru.com/2017/03/26/lets-make-an-a3c-implementation/</a> And I'm using custom environment, where an agent has a choise of purchasing some...
<p>Too large changes to the current policy is the main cause of instability of A3C algorithm. There are methods to stabilize it, e.g. <a href="https://arxiv.org/abs/1502.05477" rel="nofollow noreferrer">TRPO</a> or <a href="https://arxiv.org/abs/1707.06347" rel="nofollow noreferrer">PPO</a>. I'd suggest you to look at ...
python-3.x|tensorflow|keras|reinforcement-learning
1
362,625
50,745,849
Specifying a DirichletMultinomial in tensorflow probability
<p>This is probably quite basic, but I can't figure it out -- I have a 100x5 matrix <code>y</code> that is generated from a Dirichlet-Multinomial and I want to infer the parameters gamma using tensorflow probability. Below is the model I implemented (for simplicity I'm assuming that gamma is the same for all 5 classes ...
<p>As hinted in my comment, the fix here is to use <code>sample_shape=[100,]</code> instead of <code>sample_shape=[100, 5]</code>. We have 3 notions of shape in the TF Distributions library (which Edward wraps): sample shape, batch shape, and event shape.</p> <p>The event shape describes the shape of a single draw fro...
python|python-3.x|tensorflow-probability
1
362,626
50,885,024
Get Latitude/Longitude Python Pandas
<p>I'm learning python and am currently trying to parse out the longitude and latitude from a "Location" column and assign them to the 'lat' and 'lon' columns. I currently have the following code:</p> <pre><code>def getlatlong(cell): dd['lat'] = cell.split('\n')[2].split(',')[0][1:] dd['lon'] = cell.split('\n'...
<p>Please see my approach below. It is based on creating a DataFrame with <code>lat</code> and <code>lon</code> columns and then adding it to the existing dataframe.</p> <pre><code>def getlatlong(x): return pd.Series([x.split('\n')[2].split(',')[0][1:], x.split('\n')[2].split(',')[1][1:-1]],...
python|pandas|dataframe|apply
2
362,627
51,106,297
Reindex DataFrame Columns by Label Series
<p>I have a Series of Labels</p> <pre><code>pd.Series(['L1', 'L2', 'L3'], ['A', 'B', 'A']) </code></pre> <p>and a dataframe</p> <pre><code>pd.DataFrame([[1,2], [3,4]], ['I1', 'I2'], ['A', 'B']) </code></pre> <p>I'd like to have a dataframe with columns <code>['L1', 'L2', 'L3']</code> with the column data from 'A', ...
<p>Since you mention <code>reindex</code></p> <pre><code>#s=pd.Series(['L1', 'L2', 'L3'], ['A', 'B', 'A']) #df=pd.DataFrame([[1,2], [3,4]], ['I1', 'I2'], ['A', 'B']) df.reindex(s.index,axis=1).rename(columns=s.to_dict()) Out[598]: L3 L2 L3 I1 1 2 1 I2 3 4 3 </code></pre>
python|pandas|dataframe|indexing|reindex
2
362,628
51,092,889
Receiving HTTP Error 403: Forbidden CSV download
<p>I am trying to access a csv programmatically at the following url: <a href="http://www.cmegroup.com/CmeWS/exp/voiProductDetailsViewExport.ctl?media=xls&amp;tradeDate=20180627&amp;reportType=F&amp;productId=425" rel="nofollow noreferrer">http://www.cmegroup.com/CmeWS/exp/voiProductDetailsViewExport.ctl?media=xls&amp;...
<p>There are two things wrong with your code: </p> <ol> <li><p>You are passing a response object to pandas, </p> <p><code>data_sheet = pd.read_csv(sheet_url)</code> when your actual csv data is in <code>sheet_url.content</code></p></li> <li><p>pandas cannot read <code>csv</code> from <code>string</code>, <code>pd.rea...
python|pandas|csv|python-requests
6
362,629
51,089,965
Plotting: `S=sum(1/x*x for x in range (1,n))` vs. `n`
<p>Equation</p> <p><img src="https://i.stack.imgur.com/VomsV.png" alt=""></p> <p>For n=10,</p> <pre><code>S=sum(1.0 / (x * x) for x in range(1, 11)) </code></pre> <p>For n=100,</p> <pre><code>S=sum(1.0 / (x * x) for x in range(1, 101)) </code></pre> <p>For n=1000,</p> <pre><code>S=sum(1.0 / (x * x) for x in rang...
<p>You could use an aggregation function for the series. In the case of a sum-series the numpy functions <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html#numpy-ufunc-accumulate" rel="nofollow noreferrer"><code>np.add.accumulate</code></a> or <a href="https://docs.scipy.org/doc/n...
python|numpy
3
362,630
50,930,655
Select same length of subarrays by evenly spacing in numpy
<p>I'm new to python and stackoverflow and I'm working on a project that deal with manually created arrays with different length. </p> <pre><code>path = '/home/Documents/Noise' files = glob.glob(path + '/*.txt') data_noise = [] for file in files: df = pd.read_csv(file, delimiter=',', header=None) df = df.value...
<p>It's not numpy, but in general Python this should work.</p> <pre><code>distance = 100 / m sub_list = df[0::distance] </code></pre> <p>Provided you add some checks and possibly rounding.</p>
python|arrays|numpy
0
362,631
51,032,764
Improve performance when creating a new column using another column as a lookup table
<p>I have a main dataframe with 4 columns representing 4 colors and 3 rows representing 3 types of materials. The values in this frame are either 1 or 0, where 1's indicate POSITIVE, and 0 NEGATIVE. I have another very long dataframe with multiple columns, including a column for COLOR and another column for MATERIAL. F...
<p>You can use <code>merge</code> after using <code>stack</code> and <code>reset_index</code> on <code>lookup_table</code>. First create df_stack:</p> <pre><code>df_stack = (lookup_table.stack().reset_index() .rename(columns={'level_0':'Color','level_1':'Material',0:'FAVOR'})) print (df_stack.head(15)) ...
python|python-2.7|pandas|dataframe
0
362,632
50,771,636
How to initialize variables in an LSTM?
<p>I'm having difficulty when I try to run this LSTM model in TensorFlow. I'm relatively new to the library, so forgive me.</p> <pre><code>from tensorflow.contrib import ffmpeg, rnn import tensorflow as tf import os import time # hyperparameters learning_rate = 0.01 total_iterations = 100 layer_width = 5 network_dept...
<p>The reason of the error is that you defined the <code>init_op</code> before defining your variables (i.e. before calling <code>stacked_lstm</code> and <code>tf.nn.dynamic_rnn</code>. This means that the variables you defined after having called <code>init_op</code> won't be initialised.</p> <p>You should do someth...
python|python-3.x|tensorflow
0
362,633
50,785,226
Extracting values from last dimension of 3D numpy array
<p>I'm trying to extract from a 3D matrix of values a 2d matrix were the last dimension has values from the last dimension of the 3d matrix. For example if P of dimensions [2,2,3] = </p> <p><code>[ [[5, 1, 5], [9, 9, 4]], [[0, 9, 8], [8, 6, 8]] ]</code> </p> <p>what is the index matrix in order to get the out m...
<p>I am assuming there's an indexing array to index into the last axis. Let's call it <code>idx</code>. For the given sample with the given text in the question, it would be -</p> <pre><code>idx = np.array([[1,0],[0,2]]) </code></pre> <p>Specifically, this was extracted from the quoted text :</p> <blockquote> <p>1...
python|numpy|indexing
3
362,634
50,946,534
Conditional elementwise sum in numpy
<p>I have found a solution to cumsum the previous numbers if they are negative:</p> <pre><code>def func(x): for i, value in enumerate(x): if i == len(x)-1: break if value &lt; 0: x[i+1] += value x = x.clip(min=0) return x data = np.array([-3, 4, -2, -2, 6]) print(fu...
<p>You can use a binarized array of your data. Once you defined your threshold, binarize it with <code>np.where</code>:</p> <pre class="lang-py prettyprint-override"><code>data = np.array([-3, 4, -2, -2, 6]) binarized = np.where(data&gt;0, 1, 0) # array([0, 1, 0, 0, 1]) </code></pre> <p>The <code>np.where</code> func...
python|numpy
0
362,635
50,825,501
How to combine two dataframes from bank accounts
<p>I have two dataframes which contain transactions from two bank accounts. I would just like to combine them into one dataframe. However this is not working well for me. The dataframes are called <code>df</code> and <code>JLcard</code> and here is some information</p> <pre><code>df.shape (1405, 3) JLcard.shape (96,...
<p>You can try <code>pd.merge(f,JLcard,left_index=True, right_index=True)</code></p>
python|pandas|dataframe
0
362,636
50,870,437
Multiclass Text Classification of Wikipedia Articles
<p>I have a collection of Wikipedia dumps. I need to <strong>classify</strong> them in a list of categories that I have. The categories are like, Sports, Law, Music, Movie, etc. There are around <strong>300</strong> categories. I extracted the descriptions from the articles, and the category list of the articles. </p> ...
<p>Stackoverflow is not a place to ask for readily available code.</p> <p>I can, however, point you in a general direction, which should be enough information to get you to some tutorials doing similar (enough) topics.<br/> Your problem can certainly be approached in several different ways. As your bag-of-words (which...
python|tensorflow|neural-network|deep-learning|text-classification
1
362,637
51,064,269
sciklearn Linear Regression (Final Prediciton always 0)
<p>I'm trying to do simple linear regression using this small<a href="https://i.stack.imgur.com/2dPdx.png" rel="nofollow noreferrer"> Dataset (Screenshot)</a>.</p> <p>The dataset is records divided into small time blocks of 4 years each (Except for the 2nd to the last time block of 2016-2018). </p> <p>What I'm trying...
<p>Based on your data, I think this is what you ask for [Edit: see updated version below]:</p> <pre><code>import pandas as pd from sklearn.linear_model import LinearRegression df = pd.DataFrame( {'Country:':['Brunei','Cambodia','Indonesia','Laos', 'Malaysia','Myanmar','Philippines','Singa...
python|pandas|scikit-learn|regression|linear-regression
0
362,638
51,013,319
How to generate random sampling in python . with integers. with sum and size given
<p>Is there a direct function or any another way in python where I can generate random integers for my given size and I want to specify sum of those numbers as well. </p> <p>For example. I want to generate 7 numbers whose sum is 341. </p> <p>Can I also specify mean for this. Like 7 numbers with mean 49 and sum 341. (...
<p>I found this code would probably do decent job:</p> <pre><code>_sum = 341 n = 7 Argentina = np.random.multinomial(_sum, np.ones(n)/n, size=1)[0] print (Argentina) [44 46 42 52 53 50 54] </code></pre>
python|numpy|random
0
362,639
20,470,459
How do you allow for text qualifiers using numpy genfromtxt
<p>I am currently trying to import some comma delimited text data into an array using the numpy library in Python. I am using the following code:</p> <pre><code>data = np.genfromtxt(fname, delimiter=',') </code></pre> <p>I get the following error: </p> <blockquote> <p>Line #2 (got 12 columns instead of 11)</p> </b...
<p>Numpy arrays are not well-suited for categorical data like you have here. You may be better off using <a href="http://pandas.pydata.org" rel="nofollow"><code>pandas</code></a>:</p> <pre><code>import pandas data = pandas.read_csv(fname) </code></pre>
python|arrays|csv|numpy|genfromtxt
1
362,640
20,725,584
Update 2D numpy array values
<p>Is there a more efficient way to update the values of a multidimensional numpy array?<br> For example, I have a loop</p> <pre><code> for i in np.arange(5): for j in np.arange(5): if (i + j) % 2 == 0: v[i,j] = v[i,j] + v[i, j + 1] </code></pre> <p>I was ...
<p>Basically you are doing this:</p> <p><img src="https://i.stack.imgur.com/D28oi.png" alt="enter image description here"></p> <p>You can do this in two lines using slice indexing:</p> <pre><code>v[0:5:2,0:5:2] += v[0:5:2,1:6:2] # even rows v[1:5:2,1:5:2] += v[1:5:2,2:6:2] # odd rows </code></pre>
python|arrays|function|numpy
5
362,641
20,383,647
Pandas selecting by label sometimes return Series, sometimes returns DataFrame
<p>In Pandas, when I select a label that only has one entry in the index I get back a Series, but when I select an entry that has more then one entry I get back a data frame.</p> <p>Why is that? Is there a way to ensure I always get back a data frame?</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.DataF...
<p>Granted that the behavior is inconsistent, but I think it's easy to imagine cases where this is convenient. Anyway, to get a DataFrame every time, just pass a list to <code>loc</code>. There are other ways, but in my opinion this is the cleanest.</p> <pre><code>In [2]: type(df.loc[[3]]) Out[2]: pandas.core.frame.Da...
python|pandas|dataframe|slice|series
144
362,642
20,681,972
different results for PCA, truncated_svd and svds on numpy and sklearn
<p>In sklearn an numpy there are different ways to compute the first principal component. I obtain a different results for each method. Why?</p> <pre><code>import matplotlib.pyplot as pl from sklearn import decomposition import scipy as sp import sklearn.preprocessing import numpy as np import sklearn as sk def gen_d...
<p>Because the methods PCA, SVD, and truncated SVD are not the same. PCA calls SVD, but it also centers data before. Truncated SVD truncates the vectors. <code>svds</code> is a different method from <code>svd</code> as it is sparse.</p>
python|numpy|machine-learning|scikit-learn|svd
2
362,643
20,710,479
Column type inference for heterogeneous vector of ints and floats [pandas]
<p>I am computing some article metrics for many different wikipedia pages, like article length and references per section. The type of these metrics is either int or float. I have stored them in a dict of dicts, and am not trying to get them into pandas to create some histograms and statistics. When I try to populate t...
<p>You sure can cast to float with <code>convert_objects</code>:</p> <pre><code>&gt;&gt;&gt; df = df.convert_objects(convert_numeric=True) &gt;&gt;&gt; df[:2] qid lang metric val 0 Q774 fr informativeness 1.350078 1 Q774 fr referencerate 0.002627 &gt;&gt;&gt; df.dtypes qi...
python|pandas
2
362,644
20,716,437
python pandas library installation
<p>I tried installing pandas library for python when when u typed </p> <p>location > <strong>python setup.py install</strong></p> <p>this came up </p> <blockquote> <p>warning: no files found matching 'TODO.rst'</p> <p>warning: no files found matching 'setupegg.py'</p> <p>no previously-included directorie...
<p>easy answer since you are on Windows is just install the entire <a href="http://continuum.io/downloads" rel="nofollow">Anaconda</a> distribution (free)</p>
python|python-3.x|pandas
1
362,645
20,374,170
numpy ndarray uninitialized values interesting
<p>When I create a numpy ndarray,</p> <pre><code>c = np.ndarray((4, 5)) </code></pre> <p>I get:</p> <pre><code>c = array([[ 6.58119589e-295, nan, 2.10077583e-312, 1.08646184e-311, 2.84381388e-308], [ 1.93933443e-309, 1.20154015e-306, 2.90571629e-298, -7.52450413e-266, 3.000295...
<p>Numpy allocates needed memory for your array according to it's type (np.float by default). If not initialized, the result you see is tranlation of garbage in allocated memory. Not all possible byte combinations can be converted to float, hence <code>NaN</code>, i.e. <code>Not a Number</code>.</p> <p><strong>Update<...
python|numpy|initialization
1
362,646
20,440,232
Append numpy ndarrays with different dimensions in loop
<p>I need to append the arrays created in each loop so that I get a single ndarray at the end. The code structure is like this:</p> <pre><code>for...: . . . for...: list1 = array([some_math_here]) list2.append(list1) #each loop creats a list, converting it to array() give...
<p>No, you can't create a <code>n*4</code> 2d <code>array</code> if <code>n</code> for each column is different:</p> <pre><code>&gt;&gt;&gt; np.vstack((np.arange(10),np.arange(1,11),np.arange(2,12))) array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [ 2, 3, 4, ...
python|arrays|numpy|append|multidimensional-array
3
362,647
33,113,600
Can't read csv data from gzip-compressed file which stores name of archived file with Pandas
<p>I am trying to read csv data from gzip archive file which also stores name of the archived data file. The problem is that pandas.read_csv() picks the name of the archived file and returns it as very first data entry in returned DataFrame. How can I skip the name of the archived file? I looked at all available option...
<p>Use tarfile again:</p> <pre><code>fh = tarfile.open('ones.tar.gz', 'r:gz') f = fh.extractfile('numpy_ones.dat') df = pd.read_csv(f, delim_whitespace=True, header=None) </code></pre>
python|csv|pandas
2
362,648
33,384,734
Is there any more pythonic way to do the following repetitive code
<p>I have more than 20 columns where I need to run following rule:</p> <pre><code>df['LAND1'] = df['LAND1'].str.replace('\W+', '') df['LAND1'] = df['LAND1'].str.lower().astype(str) df['SEA1'] = df['SEA1'].str.replace('\W+', '') df['SEA1'] = df['SEA1'].str.lower().astype(str) df['OCEAN1'] = df['OCEAN1'].str.replace('\W...
<p>You can create a list of column names and then iterate through them and apply your logic for them. Example -</p> <pre><code>columns = ['LAND1','SEA1','OCEAN1','CITY1',...] for col in columns: df[col] = (df[col].str.replace('\W+', '') .str.lower().astype(str)) </code></pre> <p>Demo -</p> ...
python|python-2.7|pandas
4
362,649
33,513,987
Adding numpy zero array and masked array
<p>I have foll.. 2 numpy arrays:</p> <pre><code>arr_a = numpy.zeros(shape=(3, 3)) </code></pre> <p><code>arr_b</code> is second numpy array, but it is masked with mask value of <code>-9999.0</code></p> <p>if I do:</p> <pre><code>arr_a += arr_b </code></pre> <p>then the resulting <code>arr_a</code> does not retain ...
<p>I'm assuming that <code>arr_b</code> is an instance of <code>numpy.ma.array</code>. In such a case the semantics of numpy mean that <code>arr_a += arr_b</code> is adding the array <strong>in-place</strong>. Thus, it certainly cannot alter its type from a <code>numpy.array</code> to a <code>numpy.ma.array</code>.</...
python|numpy|mask
3
362,650
33,490,816
Adding horizontal and vertical lines and colorbar to seaborn jointplot
<p>I would like to use <em>kernel density estimate</em> of <code>seaborn</code>. </p> <p><strong>First</strong> I would like to add a colorbor for the main plot.</p> <p><strong>Second</strong> I would like to add horizontal line to the joint probability distribution to show the 68%, 98% confidence levels and another ...
<ol> <li><p>Not easily possible (although the density values are not particularly interpretable anyway).</p></li> <li><p>These are matplotlib objects, you can add any additional plot elements you want to them.</p></li> <li><p><code>stat_func=None</code>, as is shown <a href="http://stanford.edu/~mwaskom/software/seabor...
python|numpy|matplotlib|scipy|seaborn
1
362,651
33,443,121
Group Daily Data by Week for Python Dataframe
<p>So I have a Python dataframe that is sorted by month and then by day, </p> <pre><code>In [4]: result_GB_daily_average Out[4]: NREL Avert Month Day 1 1 14.718417 37.250000 2 40.381167 45.250000 3 42.512646 40.666667 4 12.166896 31.583333 5 14.583208...
<p>I assume by weeks you don't mean actual calendar week!!! Here is my proposed solution:</p> <pre><code>#First add a dummy column result_GB_daily_average['count'] = 1 #Then calculate a cumulative sum and divide it by 7 result_GB_daily_average['Week'] = result_GB_daily_average['count'].cumsum() / 7.0 #Then Round the...
python|pandas|dataframe
1
362,652
33,285,769
Pandas dataframe - deltas of data with same ids
<p>I have a dataframe that looks like this:</p> <pre><code> type unique_id val 0 X 1 11 1 X 2 12 2 Y 1 20 3 Y 2 30 </code></pre> <p>The desired output is</p> <pre><code> type unique_id val delta 0 X 1 11 9 1 X 2 12 18 2 Y ...
<p>Assuming the unique_id is in fact unique for the give type, you can group on it based on the data filtered for type <code>Y</code>.</p> <pre><code>gb = df[df.type == 'Y'].groupby('unique_id').first() &gt;&gt;&gt; gb type val unique_id 1 Y 20 2 Y 30 </code></pre> <p>Yo...
python|pandas|dataframe
1
362,653
33,350,575
How to generate time series from a series of ordered numbers in Python's pandas
<p>I am using DataFrame in pandas to analyse data. A sample:</p> <pre><code>data[:5] time qlen means vars 1 1.153281 1 0.000000 0.000000 2 5.279293 1 0.333333 0.222222 3 12.285338 1 0.400000 0.240000 4 16.407872 1 0.428571 0.244898 5 23.184910 1 0.444444 0.2...
<p>If you want the times as a <code>timedelta</code> (i.e. dateless) type, use the <code>to_timedelta</code> conversion function, specifying the unit.</p> <pre><code>In [11]: pd.to_timedelta(df['time'], unit='s') Out[11]: 1 00:00:01.153281 2 00:00:05.279293 3 00:00:12.285338 4 00:00:16.407872 5 00:00:23.184...
python|pandas
0
362,654
33,442,728
import multiple csv from folder into a dataframe in python
<p>I was trying to import 15 different csv into a data frame. Installed pyserial and it still shows "cannot import name serial" Also tried to </p> <pre><code>"try: import serial # Python2 except ImportError: from serial3 import * # Python3" </code></pre> <p>and still not able to run it. Here is my code:</...
<p>replace this</p> <pre><code>from serial import serial </code></pre> <p>to:</p> <pre><code>from serial import Serial ^ Capital S </code></pre> <p>you also need to do this</p> <pre><code> pd.read.csv(file_, index_col=None) ^ pd.read_csv(file_, index_col=N...
python|csv|pandas|pyserial
0
362,655
33,271,702
Pandas: Index of last non equal row
<p>I have a pandas data frame <code>F</code> with a sorted index <code>I</code>. I am interested in knowing about the last change in one of the columns, let's say <code>A</code>. In particular, I want to construct a series with the same index as <code>F</code>, namely <code>I</code>, whose value at <code>i</code> is <c...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow"><code>np.argmax</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.argmax.html" rel="nofollow"><code>pd.Series.argmax</code></a> on Boolean data can help you find the first (or in t...
python|pandas|indexing|dataframe
0
362,656
33,442,796
Fast way to convert strings into lists of ints in a Pandas column?
<p>I'm trying to compute the Hamming distance between all strings in a column in a large dataframe. I have over 100,000 rows in this column so with all pairwise combinations, which is 10x10^9 comparisons. These strings are short DNA sequences. I would like to quickly convert every string in the column to a list of inte...
<p>Since Hamming distance doesn't care about magnitude differences, I can get about a 40-60% speedup just replacing <code>df.apply(lambda x: np.array([mapping[char] for char in x]))</code> with <code>df.apply(lambda x: map(ord, x))</code> on made-up datasets.</p>
python|numpy|pandas|scipy
2
362,657
33,374,140
What does newArray = myNumpyArray[:,0] mean?
<p>Not too familiar with Python and need to translate some code. Here is the gist of what I am having a problem with:</p> <pre><code>import numpy myNumpyArray = numpy.array([1,2,3,4]) newArray = myNumpyArray[:,0] </code></pre> <p>I don't know what <code>myNumpyArray[:,0]</code> means and get compile error <code>Index...
<pre><code>myNumpyArray[:,0] </code></pre> <p>means the first column of myNumpyArray, since your array is 1-Dimensional, this doesn't work.</p>
python|numpy
1
362,658
33,357,085
Efficient way to multiply/add/devide each element of a list with each element of another list in Python
<p>I want to multiply each element of a list with each element of another list.</p> <pre><code>lst1 = [1, 2, 1, 2] lst2 = [2, 2, 2] lst3 = [] for item in lst1: for i in lst2: rs = i * item lst3.append(rs) </code></pre> <p>This would work, but this is very inefficient in large dataset and can tak...
<p>Numpy is the way to go, specifically <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.outer.html" rel="nofollow">numpy.outer</a>, which returns the product of each element as a matrix. Using .flatten() compresses it into 1d. </p> <pre><code>import numpy lst1 = numpy.array([1, 2, 1, 2]) lst2 = nump...
python|numpy|data-structures
3
362,659
33,480,695
Ignore duplicate rows while adding to database with Blaze's Odo
<p>How can I ignore duplicate rows while storing a dataframe in a postgres DB with Blaze's <a href="http://odo.pydata.org/en/latest/" rel="nofollow">Odo</a>?</p> <p>For example, I store the first 3 rows like this:</p> <pre><code>&gt;&gt;&gt; odo(df[:3], 'postgresql:///my_db::my_table') </code></pre> <p><strong><code...
<p>The data model for <code>odo</code> only supports appending, not merging. You'll need to either remove duplicates before passing it through <code>odo</code>, or use the database to remove the duplicates. Try adding an auto-increment field, and set it as the primary key. This will fix your <code>IntegrityError</code>...
postgresql|pandas|psycopg2|blaze
1
362,660
33,442,434
Parse log file with python pandas
<h1>Problem 1</h1> <p>I am trying to read and parse a log file from a simulation. Ideally I would like to do this with pandas but I am having issues. The file in question is called <code>log</code> and a sample is contained below. Now I try to do</p> <pre><code> import pandas as pd import numpy as np impo...
<p>To answer your second question. This may help, althought the regular expression could be nicer. </p> <pre><code>line1 = 'smoothSolver: Solving for Ux, Initial residual = 0.999999999388, Final residual = 0.00692443749034, No Iterations 2' line2 = 'smoothSolver: Solving for Uy, Initial residual = 0.999999994742, Fi...
python|parsing|pandas
1
362,661
9,303,728
Matplotlib yaxis range display using absolute values rather than offset values?
<p>I have the following range of numpy data (deltas of usec timestamps):</p> <pre><code>array([ 4.312, 4.317, 4.316, 4.32 , 4.316, 4.316, 4.319, 4.317, 4.317, 4.316, 4.318, 4.316, 4.318, 4.316, 4.318, 4.317, 4.317, 4.317, 4.316, 4.317, 4.318, 4.316, 4.318, 4.316, 4.318, 4.316, 4.317,...
<p>set useOffset to False: </p> <pre><code>ax = plt.gca() ax.ticklabel_format(useOffset=False) </code></pre>
python|numpy|matplotlib
46
362,662
5,965,667
Memory error in np.hstack()
<p>I am trying to execute this code:</p> <pre><code>for i in Fil: for k in DatArr: a = np.zeros(0) for j in Bui: a = np.hstack([a,DatDifCor[k][i,j]]) DatDifPlt[k].update({i:a}) </code></pre> <p>But it gives me this error:</p> <pre><code>Traceback (most recent call ...
<p>A <code>MemoryError</code> always means that an attempt to allocate memory failed. Trying to create an array bigger than the maximum array size results in a <code>ValueError</code>:</p> <pre><code>&gt;&gt;&gt; a = numpy.arange(500000000) &gt;&gt;&gt; numpy.hstack((a, a)) Traceback (most recent call last): File "...
python|numpy|memory-management|out-of-memory
2
362,663
5,779,754
Sort on multiple NumPy arrays
<p>I am creating a 2 dimensional numpy array that contains stock returns. I want to sum the return every 2 days, and if the sum is in the top two, I will set every element in a similar shaped array to True.</p> <p>For example, returns below is the daily returns for four different stocks.</p> <p><code> returns=np.arr...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html" rel="nofollow"><code>numpy.lexsort()</code></a> to get the indices that sort your arrays using <code>prices</code> as primary key and <code>names</code> as secondary key. Applying advanced indexing using these indices yield...
python|numpy
1
362,664
5,838,994
Fourier Series from Discrete Fourier Transform
<p>I'm trying to recreate a function from a discrete fourier transform. In Matlab it would be done like this:</p> <pre><code>function [y] = Fourier(dft,x) n = length(dft); y = cos(pi*(x+1)'*(0:n-1))*real(dft)+sin(pi*(x+1)'*(0:n-1))*imag(dft) end </code></pre> <p>My attempt in Python is falling flat because I don't kn...
<p>You were running two nested loops instead of one. Try this:</p> <pre><code>y = ([(dft[nn].real)*np.cos(np.pi*x*nn) + (dft[nn].imag)*np.cos(np.pi*x*nn) for nn in range(0,n)]) </code></pre>
python|numpy
5
362,665
5,642,203
Efficient vector selection in numpy
<p>Is there an efficient numpy mechanism to generate an array of values from a 2D array given a list of indexes into that array?</p> <p>Specifically, I have a list of 2D coordinates that represent interesting values in a 2D <code>numpy</code> array. I calculate those coordinates as follows:</p> <pre><code>nonzeroVal...
<p>Yes, of course, you can get the values as </p> <pre><code>nonZeroData = array2d[nonzeroValidIndices] </code></pre> <p>if map is a new dict, you could do</p> <pre><code>map = dict(zip(nonzeroValidCoordinates,nonZeroData)) </code></pre> <p>If it is an existing dict,</p> <pre><code>map.update(zip(nonzeroValidCoord...
python|numpy
2
362,666
5,795,268
Unable to load DLL python module in PyCharm. Works fine in IPython
<p>When I use the IPython included with Enthought Python Distribution, I can import the pyvision package just fine. However, when I try to import pyvision inside of PyCharm 1.2.1, I get the following errors</p> <pre><code> File "C:\Python27\lib\site-packages\pyvision\__init__.py", line 146, in &lt;module&gt; from...
<p>I had the same problem. I'm using Winpython32 and trying to <code>import win32com</code>. Worked everywhere (I tried) except in PyCharm. <code>sys.path</code> and <code>os.environ['PYTHONPATH']</code> had some extra entries inside Pycharm, but nothing is missing compared to when run elsewhere.</p> <p>The solution w...
python|import|numpy|ipython|pycharm
4
362,667
66,660,909
Add a new column to a dataframe in which each row adopts a different value based on the title of the dataframe it came from
<p>So i have a list of multiple dataframes, and I concadenated them in one big dataframe. Now I want to add a column to this last big dataframe, but I want the values of this column to change depending on the name of the dataframe each row belongs to in the first place. This is an example:</p> <pre><code>list_of_df = [...
<p>one way:</p> <pre class="lang-py prettyprint-override"><code>import itertools as it big_df[&quot;new_column&quot;] = list(it.chain.from_iterable([f&quot;{j}&quot;.zfill(2)]*len(df) for j, df in enumerate(list_of_df, start=1))) </code></pre> <p>This gets the length ...
python|pandas
1
362,668
66,652,641
How to handle correctly sparse features to avoid poor performance of classification neural network?
<p>I'm trying to understand how sparse neural networks work. I have a very sparse data of about 40k rows for two classes. The dataset looks like this:</p> <pre><code> RA0 RA1 RA2 RA3 RA4 RA5 RA6 RA7 RA8 RA9 RB0 RB1 RB2 RB3 RB4 RB5 RB6 RB7 RB8 RB9 50 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0....
<p>The use of <code>sparse_categorical_crossentropy</code> is wrong here; the sparsity in <code>sparse_categorical_crossentropy</code> refers to the <em>label representation</em>, and not to the features. Since you are using one-hot encoded labels:</p> <pre><code>y_train2 = to_categorical(y_train) y_test2 = to_categori...
python-3.x|tensorflow|keras|neural-network|sparse-matrix
1
362,669
66,539,577
Aggregate series from DataFrame based on specific conditions
<p>I have the following data structure:</p> <pre><code> sls srx stx hostname m @timestamp 0 1 21.1 389.2 A dev 2021-03-05 05:00:00.112965476+00:00 1 0 0.0 352.4 A dev 2021-03-05 05:00:00.263778044+00:00 2 0 0.0 351.5 A dev 2...
<p>perhaps you're lookig for <code>groupby</code>? <code>df.groupby(by=[&quot;sls&quot;]).sum()</code></p> <p>group by docs: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Data...
python|pandas
0
362,670
66,580,503
pandas check conditions inside a subset to obtain values
<p>The following data set has containers with specific items that have a specific priority.</p> <pre><code>container item_No Priority 1 123 A 1 124 B 1 142 D 2 516 C 2 142 D 3 516 C 3 124 B 3 123 A </code></...
<p>First convert column for ordered categoricals with specify order and then aggregate <code>min</code>:</p> <pre><code>df['Priority'] = pd.Categorical(df['Priority'], ordered=True, categories=['A','B','C','D']) df = df.groupby('container', as_index=False)['Priority'].min() print (df) container Priority 0 ...
python|pandas
0
362,671
66,497,600
drop records from a df that are not in another df using python
<p>I've a sample datafram1</p> <pre><code>date username cities 2021-03-01 K John New york 2021-03-01 K John LA 2021-03-02 Ken Miles Florida 2021-03-02 Ken Miles LA </code></pre> <p>dataframe2 contains</p> <pre><code>date username planne...
<p>you could use <code>Index.isin</code> with the columns you are interested in and then boolean index:</p> <pre><code>cols = ['date','username'] idx1 = pd.MultiIndex.from_frame(df1[cols]) idx2 = pd.MultiIndex.from_frame(df2[cols]) out = df2[idx2.isin(idx1)] </code></pre> <hr /> <pre><code> date username planne...
python|pandas
2
362,672
66,516,856
Beautiful Soup and Pandas extract number
<p>I have this structure:</p> <pre><code>&lt;tr id=&quot;table3620_0_5&quot; class=&quot;l1&quot;&gt; &lt;td class=&quot;r&quot;&gt; North America&lt;/td&gt; &lt;td x:num=&quot;02/12/20&quot;&gt;02/12/20&lt;/td&gt; &lt;td x:num=&quot;&quot; class=&quot;r&quot;&gt;5553226&lt;/td...
<p>You can try <code>beautifulsoup</code></p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup import re s = &quot;&quot;&quot;&lt;tr id=&quot;table3620_0_5&quot; class=&quot;l1&quot;&gt; &lt;td class=&quot;r&quot;&gt; North America&lt;/td&gt; &lt;td x:num=&qu...
python|pandas|beautifulsoup
2
362,673
66,608,087
Concatenate 1st Column values with column headers in Pandas to get a tall and skinny format tabel
<p>I want to concatenate 1st column values with column headers to get a tall and skinny format table using pandas. for example- the input is</p> <pre><code>Freq Low High B1 19 22 B2 20 23 </code></pre> <p>the expected output I am looking for is</p> <pre><code>Freq value B1_Low ...
<p>You could use <code>melt</code> then concat the frequency and variable column that result.</p> <pre><code>df = df.melt(id_vars='Freq') df['Freq'] = df['Freq'].str.cat(df['variable'], sep='_') print(df[['Freq','value']]) </code></pre> <p>Output</p> <pre><code> Freq value 0 B1_Low 19 1 B2_Low 20 2 B...
python|pandas|dataframe|numpy|combinations
1
362,674
66,572,210
Create Correlation Matrix by rows: Pandas
<p>I want to create a correlation matrix by rows. Here's how my df looks like:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'],index = [&quot;doc1&quot;, &quot;doc2&quot;, &quot;doc3&quot;]) #Output a b...
<p><code>DataFrame.corr()</code> finds the correlation between pairs of <strong>columns</strong>. If you want rows, transpose first. (I modified your data slightly so everything isn't perfectly correlated)</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.array([[1, 2, 8], [4, 5, 6], [5, 8, 9]]...
python|pandas|numpy
0
362,675
66,568,876
Generate count column in dataframe based on multiple criteria pandas
<p>I have a dataframe like this:</p> <pre><code>Location Action House1 Quote House2 Offer House3 Quote House2 Quote House2 Quote House3 Offer </code></pre> <p>I want to add two columns, one that shows the count of quotes to any given house, and one that shows the count of offers to any given house.<...
<p>You can do a <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>pd.crosstab</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> back on <code>Location<...
python|pandas|dataframe|count
5
362,676
66,755,882
Scraping a table (CSS build) from online store with Python Scrapy Pandas
<p>I try to get a clean table from a online store - the section with &quot;Technische Daten&quot; - <a href="https://www.coolblue.de/produkt/863600/aeg-l6fb64470.html#product-specifications" rel="nofollow noreferrer">https://www.coolblue.de/produkt/863600/aeg-l6fb64470.html#product-specifications</a></p> <p>The CSS sel...
<p>You need loop through each spec item within the table. Here's how you can achieve it</p> <pre><code>data = {} for spec in response.css('section.js-specifications-section dl'): key = ''.join(spec.css('dt ::text').extract()).strip() val = ''.join(spec.css('dd ::text').extract()).strip() data[key] = val pri...
python|css|pandas|scrapy|screen-scraping
1
362,677
66,409,025
Pandas series to row of dataframe using loc but some columns are missing
<p>I want to add a series to a row of a dataframe but not every column is in the dataframe. How can I change the code:</p> <pre><code>df = pd.DataFrame(index=[0,1,2], columns = ['A', 'B']) series = pd.Series(data=[5,3], index=['B', 'C']) df.loc[0] = series print(df) Output: A B 0 NaN 5 1 NaN NaN 2 NaN ...
<p>Not very elegant, but you can do it in a for loop:</p> <pre><code>for c in series.index: df.loc[0, c] = series[c] df A B C 0 NaN 5 3.0 1 NaN NaN NaN 2 NaN NaN NaN </code></pre> <p>Another way is to add null columns to df before assigning to series:</p> <pre><code>df.reindex(columns=df.colu...
python|pandas
1
362,678
66,428,080
Create a DataFrame from a dictionary with partially same values
<p>I'm using a function to create a dictionary with keys and values. Some values are unique and others don't. Actually I want to use all unique values as index and keys as column names, if the key:value pair exists, fill an &quot;x&quot; in this cell.</p> <p>Pseudo-Code:</p> <pre><code>def some_function(): dict = c...
<p>Trick is to create a dictionary with keys as tuples of <code>(i, j)</code> where <code>i</code> values will end up in the index and <code>j</code> values will end up in the columns. <code>pd.Series</code> constructor will make a <code>pd.MultiIndex</code> from the tuples with <code>i</code> in the first level and <...
pandas|dictionary
1
362,679
66,480,216
Using ipysheet, how do I adjust the column width for an index column?
<p>I am trying to work through the simple ipysheet example below and have not been able to find a way to increase the column width associated with the date index in the resulting sheet in a Jupyter Notebook</p> <pre><code>import ipysheet as ip import pandas as pd dates = pd.date_range('20130101', periods=6) df =...
<p>I'm having the same problem, and don't see anything in the code that indicates this is possible.</p> <p>You can see in the <a href="https://ipysheet.readthedocs.io/en/latest/_modules/ipysheet/sheet.html#Sheet" rel="nofollow noreferrer">ipysheet code</a> that Sheet extends <a href="https://github.com/jupyter-widgets/...
pandas|jupyter-notebook
0
362,680
66,678,007
pd.crosstab() inside a for loop
<p>Suppose I have the following dataframes:</p> <pre><code>df1 = pd.DataFrame({'col1':['x','y','z','x','x'],'col2':['n1','n2',np.nan,'n3','n2']}) df2 = pd.DataFrame({'col1':['x','y','z','x','x'],'col2':['m1','m2',np.nan,'m3','m2']}) df3 = pd.DataFrame({'col1':['x','y','z','x','x'],'col2':['o1','o2',np.nan,'o3','o2']}) ...
<p>You are thinking to much:</p> <pre><code>crosstab_list = [] for i in df_list: crosstab_list.append(pd.crosstab(i['col1'], i['col2'].isna())) </code></pre>
python|pandas|for-loop
1
362,681
66,639,642
Group-by then row shift in each group
<p>I have dataset that can be grouped with following:</p> <pre><code> df.groupby(df.batch.str[:7]) </code></pre> <p>different group sizes are</p> <pre><code>df.groupby(df.batch.str[:7]).size().unique() array([1, 2, 3, 4, 5, 6, 7]) </code></pre> <p>lets say I will take any group with size 4 arranged with time column ...
<p>We can try use <code>sorted</code> with <code>key</code> in this situation you do not need worry about how many <code>NaN</code> in the top</p> <pre><code>df['new'] = df.groupby(df.col1.str[:7])['col2'].apply(lambda x : sorted(x, key=pd.isnull) ).explode().values df Out[145]: col1 col2 time new 0 rt_2345 ...
python|pandas|group-by
1
362,682
66,642,108
Bloomberg API xbbg wrapper for Python - Getting Portfolio Data
<p>I am trying to extract data from Bloomberg PRTU, at a specific point in time.</p> <p>The following works for the current portfolio:</p> <pre><code>from xbbg import blp, pipeline blp.bds('U1234567-8 Client', flds='Portfolio_Data', use_port=True) </code></pre> <p>I need to extract data at a specific point in time. The...
<p>Figured out an answer using the following syntax:</p> <pre><code>blp.bds('A20065594-121 Client', flds='Portfolio_Data', use_port=True, Reference_Date = '20210301') </code></pre>
python|pandas|bloomberg
3
362,683
66,705,579
Jupyter environment error, loading different tensorflow version than installed
<p>I am using ubuntu 20.04. I created a new environment.</p> <p>conda create -n tfgpu python=3.8 conda activate tfgpu pip install tensorflow-gpu==2.3 jupyter notebook</p> <p>Then I open a previously created .ipynb file and I try to import tensorflow. import tensorflow as tf tf.<strong>version</strong></p> <p>version is...
<p>I missed installing jupyter notebook. I do not yet understand what was happening, but my mistake was that. The problem is resolved.</p>
python|tensorflow|jupyter-notebook|version
0
362,684
66,512,527
count entries from each group using pandas.dataframe.groupby.count
<p>Note: I apologize for missing the quote which was an unintentional typo. It is corrected below. Thanks Beny for pointing out the typo.</p> <p>I was trying to count the number of entries in each of group after applying groupby to a column, but got something unexplainable. Please help. Below is my code</p> <pre><code>...
<p>You should do double quote</p> <pre><code>df.groupby('id').size() Out[106]: id 1 1 2 1 3 1 366 4 dtype: int64 </code></pre> <p>When pass id , it is id of object not the <code>id</code> in your dataframe</p> <p>More like</p> <pre><code>df.id.value_counts() Out[107]: 366 4 3 1 2 1 1 ...
pandas|pandas-groupby
1
362,685
66,595,177
understanding final layer of output for classification problem BCELoss vs CrossEntropyLoss
<p>I'm making a binary image classifier. I'm just using a pretrained model to start and change the last fully connected layer to predict between 2 classes, which I'm told requires the last layer to be the number of features and then the number of classes.</p> <pre><code> model = models.resnet18(pretrained=True, prog...
<p>Its because ,if using BCE , the last layer should have only single neuron i.e</p> <pre><code>model = models.resnet18(pretrained=True, progress=True) num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 1) </code></pre> <p>And when using CE,</p> <pre><code>model = models.resnet18(pretrained=True, progress=T...
pytorch
0
362,686
66,605,996
How to sort values in a Multi-index while keeping the index structure
<p>I'd like to sort data of a multi-index dataframe, while keeping higher level indexes the same.</p> <p>Here is the data sample:</p> <pre class="lang-py prettyprint-override"><code>data = { 'Column 1': [1., 2., 3., 4.,34,2,5,6], 'Index1 Title': [ &quot;Apples&quot;, &quot;Apples&quot;, &quot;Puppies&qu...
<p><code>sort_values</code> accepts index names, so you can do:</p> <pre><code>df.sort_values(['Index1 Title', 'Column 1'], ascending=[True, False]) </code></pre> <p>output:</p> <pre><code> Column 1 Index1 Title index2 Title Apples Outside 2.0 Inside ...
python|pandas|multi-index
4
362,687
66,428,845
Using EFS with AWS Lambda (memory issue)
<p>I have a question regarding the usage of EFS as and additional memory location for lambda. I am using python along with pandas to perform some tests on my files. And it works great if the files are not that large, but if the files exceed 2-3 GB lambda dies because of the memory limitation (using both max memory and ...
<p>As far as I know <code>pandas</code> requires the whole file to fit into memory. In principle you can fit larger files into memory in Lambda, since you can now configure Lambda functions with up to 10GB of RAM.</p> <p>That's doesn't translate to you being able to read a 10GB file from S3 and create a dataframe out o...
python|pandas|amazon-web-services|aws-lambda|amazon-efs
1
362,688
66,602,892
Tetris remove completed line and shift all the remaining block
<p>For now the code i'm using is this one:</p> <pre><code> self.board = numpy.delete(self.board, row, 0) new_row = [0 for _ in range(configuration.config[&quot;cols&quot;])] self.board = numpy.vstack([new_row, self.board]) </code></pre> <p>The code corretly remove the row(an index) in question from <code>sel...
<p>It isn't clear exactly what you're trying to achieve. For what it's worth, the way you have it currently is how the &quot;real&quot; Tetris works. Blocks are left floating.</p> <p>If you want pieces to fall, how to you want it to work?</p> <p>Only pieces on the row immediately above? This would leave strange voids i...
python|numpy|matrix
1
362,689
66,360,012
How to plot multiple sine waves/ summation of waves in python
<pre><code>import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft, fftfreq, ifft #Varibles A = 1 f = 10 t = 1/f nss = 10 fs = nss*f ts = 1/fs cycles = 1 #CREATING SINE WAVE t1 = np.arange(0,cycles*t+ts,ts) x = A*np.sin(2*np.pi*f*t1) #PLOTTING SINE WAVE plt.figure(1) plt.subplot(2,2,1) plt.plo...
<p>Not sure if this is what you're looking for, but you can use a for loop. Here, the loop represents <code>cycle=1,2,3,4,...,9,10</code>, but you can change it to modify whatever variables you want:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt from numpy.fft i...
python|numpy|fft
0
362,690
66,625,389
AttributeError: 'list' object has no attribute 'size' Hugging-Face transformers
<p>I am trying to use Huggingface to transform stuff from English to Hindi. This is the code snippet</p> <pre><code>from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained(&quot;Helsinki-NLP/opus-mt-en-hi&quot;) model = AutoModelForSeq2SeqLM.from_pretrained(&quot;Helsin...
<p>The model requires pytorch tensors and not a python list. Simply add <code>return_tensors='pt'</code> to <a href="https://huggingface.co/transformers/model_doc/marian.html?highlight=prepare_seq#transformers.MarianTokenizer.prepare_seq2seq_batch" rel="noreferrer">prepare_seq2seq</a>:</p> <pre class="lang-py prettypri...
python-3.x|nlp|huggingface-transformers
9
362,691
66,623,858
not in pandas dataframe
<p>I have 2 dataframe : <code>code_ifc</code> and <code>demo_df</code></p> <p>I would like to create <code>demo_ER_df</code> that contains all rows from</p> <pre><code>demo_df that does not contain all rows from `code_ifc` dataframe . </code></pre> <p>I try with this code , but i found that it does not delete rows fr...
<p>Suppose that df1 is</p> <pre><code> V1 V2 V3 0 aaa 34 67 1 aaa 34 4545 2 bbb 23 342344 3 bbb 56 776 4 ccc 878 754 5 ccc 454 66 6 ddd 78768 46 7 ddd 56 646 </code></pre> <p>and</p> <p>df2 is</p> <pre><code> V1 V2 V3 0 aaa 34 ...
python|pandas
0
362,692
66,666,532
How do I make a field dynamically populated using a loop based on other fields in python?
<p>My data field names consists of letter number combinations that looks something like this.</p> <pre><code>A1 | A2 | A3 | A4 | B1 | B2 | B3 | B4 | C1 | C2 | C3 | C4 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 </code></pre> <p>There will always be t...
<p>One option is to store the result in a dictionary rather than a data frame</p> <pre><code>import pandas as pd dat=pd.DataFrame({&quot;A1&quot;:[0,0], &quot;A2&quot;:[0,1], &quot;A3&quot;:[0,0], &quot;A4&quot;:[1,0], &quot;B1&quot;:[1,0], &quot;B2...
python|pandas|dataframe
0
362,693
66,406,011
Pandas:Find newly added data
<p>I have two dumps of data , the old dump and the new dump.</p> <p>Old dump goes like:- <a href="https://i.stack.imgur.com/F8TuX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F8TuX.png" alt="enter image description here" /></a></p> <p>New Dump is the changed data or the newly added data. My goal i...
<p>I am not sure, if you are looking for an answer only to the code that you have provided, but another approach could be to use the pandas <code>compare</code> API to get the difference between the dataframes. I am showing an example below taken from their <a href="https://pandas.pydata.org/pandas-docs/stable/referenc...
python-3.x|pandas|data-processing
0
362,694
66,639,722
Why does HuggingFace's Bart Summarizer replicate the given input text?
<p>I am trying to summarize the input text using Bart's pretrained summarization pipeline. However, I am noticing that the generated summary is exactly the same as the text that I am feeding the model to summarize upon. I also tried fine-tuning the model on the text-summary pairs(human-generated summaries), but for new...
<p>I've been having the same issue with the bart_base model from facebook. I tried a couple other models, and I've found that Sam Shleifer's DistilBART model does really well at summarizing news articles. If you want to try it out :</p> <pre><code>model = BartForConditionalGeneration.from_pretrained(&quot;sshleifer/dis...
python|deep-learning|nlp|huggingface-transformers|summarization
0
362,695
66,511,989
Count to first column and sum to the rest of the columns pandas groupby
<p>I have a pandas DataFrame <code>df</code> with 290 columns.</p> <p>Is there a way to make the <code>.groupby</code> operation concerning the following rules:</p> <ol> <li>sum operation for the 2st column.</li> <li>count operation to 3nd column.</li> <li>mean operation to all other columns</li> </ol> <p>I know that I...
<p>Let's use a dictionary:</p> <pre><code>import pandas as pd import numpy as np df=pd.DataFrame(np.arange(100).reshape(10,-1), columns=[*'ABCDEFGHIJ']) # Defined the first three columns aggdict={'A':'sum', 'B':'sum', 'C':'count'} # Use for loop to added to dictoary the rest of the columns. Creat...
python|pandas|dataframe|group-by
1
362,696
66,610,575
Pytorch showing the error: 'NoneType' object has no attribute 'zero_'
<p>I am using Python 3.8 and VSCode.</p> <p>I tried to create a basic Neural Network without activations and biases but because of the error, I'm not able to update the gradients of the weights.</p> <p>Matrix Details:</p> <p>Layer Shape: (1, No. of Neurons)</p> <p>Weight Layer Shape: (No. of Neurons in the previous lay...
<p>Your model doesn't have any trainable parameters for the grad to be calculated. Use torch's Parameter. See this <a href="https://discuss.pytorch.org/t/how-could-i-create-a-module-with-learnable-parameters/28115" rel="nofollow noreferrer">link</a> for creating a module with learnable parameters.</p> <pre><code> torc...
machine-learning|neural-network|pytorch
1
362,697
66,398,942
How do I round off a 'Float' object?
<p>I am trying to return the percentage rounded to one decimal place from a database using pandas.</p> <p>my code consists of:</p> <pre class="lang-py prettyprint-override"><code>df.loc[((df['education-num'] &lt; 13)|(df['education'] == 'Prof-school')) &amp; (df['salary'] == '&gt;50K')].shape[0] / df.loc[(df['education...
<p><a href="https://docs.python.org/3/library/functions.html#round" rel="nofollow noreferrer"><code>round()</code></a> is a global function, not a method of <code>float</code>.</p> <pre><code>print(round(17.3713601914639, 1)) </code></pre> <p>If you really want to round <strong>up only</strong>, use <a href="https://do...
python|pandas|dataframe|rounding
2
362,698
66,515,107
Pandas casting to category still results in different datatypes when plotting with Seaborn
<p>I am trying to cast a column to a category as the 2 data sets I am reading in do not have the same datatype for the column I am interested in. They do contain the same set of possible values (1, 2, 3, 4, 5).</p> <pre><code>df1 = pd.read_csv (r'set1.csv', decimal=&quot;,&quot;) df2 = pd.read_csv (r'set2.csv', decimal...
<p>see Initially your <code>df1['score']</code> is of type <code>object(string)</code> and <code>df2['score']</code> is of type <code>int</code></p> <p>so when you change <code>df1['score'] = df1['score'].astype('category')</code> it converts into <code>category</code> but initial values in this <code>category</code> a...
python|python-3.x|pandas|seaborn
0
362,699
66,521,273
requests_html: How to structure code to include sub-pages?
<p>How to structure my code to include pagination sometimes from within a running loop. I am not using <code>def</code>, yet. Maybe that's the answer. But after looking for several days I'm stuck. I'm looking for a high level answer.</p> <p>Here is my basic structure:</p> <pre><code>import requests_html from requests_h...
<p>So I figured out a solution that meets my needs. It might not be Pythonic. It allows me to control the depth of search at the city level. I added an input for the number (depth) of sub-pages to loop through (default is 1) at the city level. I added an additional for loop <em>for page in pages</em> and nested my main...
python|python-3.x|pandas|python-requests-html
0