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
6,000
48,257,800
Data filtering code in Pandas taking lot of time to run
<p>I am executing the below code in Python. Its taking some time run. Is there something i am doing wrong. </p> <p>Is there a better a way to do the same.</p> <pre><code>y= list(word) words = y similar = [[item[0] for item in model.wv.most_similar(word) if item[1] &gt; 0.7] for word in words] similarity_matrix = pd....
<p>It is not possible to determine what is going on in the following line as there is not enough data provided (I do not know what <code>model</code> is):</p> <pre><code>similar = [[item[0] for item in model.wv.most_similar(word) if item[1] &gt; 0.7] for word in words] </code></pre> <p>The second line below does not ...
python-3.x|pandas
0
6,001
48,316,370
get indexes with condition
<p>How do I find a position(index) of all entries of search_value?</p> <pre><code>import pandas as pd import numpy as np search_value=8 lst=[5, 8, 2, 7, 8, 8, 2, 4] df=pd.DataFrame(lst) df["is_search_value"]=np.where(df[0]==search_value, True, False) print(df.head(20)) </code></pre> <p>Output:</p> <pre><code> 0 i...
<p>You can use enumerate in a conditional list comprehension to get the index locations.</p> <pre><code>my_list = [5, 8, 2, 7, 8, 8, 2, 4] search_value = 8 &gt;&gt;&gt; [i for i, n in enumerate(my_list) if n == search_value] [1, 4, 5] </code></pre> <p>If the search value is not in the list, then an empty list will be...
python|python-3.x|pandas|numpy
3
6,002
48,668,706
How do I convert an Armadillo matrix to cube?
<p>I'm trying to recreate the following Python numpy code:</p> <pre><code>num_rows, num_cols = data.shape N = 4 data = data.reshape(N, num_rows/N, num_cols) </code></pre> <p>in C++ using Armadillo matrices and cubes? How can this be done most efficiently. I dont think the resize/reshape operations are supported direc...
<p>The <em>fastest</em> way to construct such a cube is to use one of the <a href="http://arma.sourceforge.net/docs.html#Cube" rel="nofollow noreferrer">advanced constructors</a>. These allow you to directly create a new object from an arbitrary section of memory, even without copying any of the data. This is closest i...
python|c++|numpy|armadillo
2
6,003
48,787,340
seed=1, TensorFlor- Xavier_initializer
<p>What does seed=1 is doing in the following code:</p> <p>W3 = tf.get_variable("W3", [L3, L2], initializer = tf.contrib.layers.xavier_initializer(seed=1))</p>
<p>It's to define the random seed. By this means, the weight values are always initialized by the same values. From Wiki: A random seed is a number (or vector) used to initialize a pseudo-random number generator.</p>
python|tensorflow
0
6,004
48,663,207
Colaboratory install Tensorflow Object Detection Api
<p>I succesfully executed in Google Colaboratory a notebook of training model and image recognition in Tensorflow. Now I want to start a new notebook with <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Object Detection Api</a>. When I execute my code I get...
<p>Here is an example notebook that shows the installation and configuration of the TensorFlow object detection API:</p> <p><a href="https://colab.research.google.com/drive/1kHEQK2uk35xXZ_bzMUgLkoysJIWwznYr" rel="noreferrer">https://colab.research.google.com/drive/1kHEQK2uk35xXZ_bzMUgLkoysJIWwznYr</a></p> <p>The depa...
tensorflow|object-detection|google-colaboratory
5
6,005
48,711,082
Empty values in pandas -- most memory-efficient way to filter out empty values for some columns but keep empty values for one column?
<p>Using Python, I have a large file (millions of rows) that I am reading in with Pandas using pd.read_csv. My goal is to minimize the amount of memory I use as much as possible.</p> <p>Out of about 15 columns in the file, I only want to keep 6 columns. Of those 6 columns, I have different needs for the empty rows.</p...
<p>I would advise you use <a href="http://dask.pydata.org/en/latest/dataframe.html" rel="nofollow noreferrer"><code>dask.dataframe</code></a>. Syntax is pandas-like, but it deals with chunking and optimal memory management. Only when you need the result in memory should you translate the dataframe back to <code>pandas<...
python|pandas|numpy|filter|nan
0
6,006
48,474,699
Marker size/alpha scaling with window size/zoom in plot/scatter
<p>When exploring data sets with many points on an xy chart, I can adjust the alpha and/or marker size to give a good quick visual impression of where the points are most densely clustered. However when I zoom in or make the window bigger, the a different alpha and/or marker size is needed to give the same visual impr...
<p>You can achieve what you want with <code>matplotlib</code> event handling. You have to catch zoom and resize events separately. It's a bit tricky to account for both at the same time, but not impossible. Below is an example with two subplots, a line plot on the left and a scatter plot on the right. Both zooming (fac...
pandas|matplotlib
6
6,007
48,738,112
Pandas MultiIndex Merge
<p>Suppose I have two dataframes as follows:</p> <pre><code>import pandas as pd index = pd.MultiIndex.from_tuples([('one', '1993-02-02'), ('one', '1994-02-03'), ('two', '1995-02-18'), ('two', '1996-03-01')]) s = pd.DataFrame(np.arange(1.0, 5.0), index=index) s.rename(columns = {0 : 'test1'}, inplace = True) s.inde...
<p>You can <code>reset_index</code>, then it will make the index merge to df merge (which is much more easy )</p> <pre><code>s.reset_index().assign(key=s.index.get_level_values(1).str[:4]).merge(d.reset_index().assign(key=d.index.get_level_values(1).str[:4]),on=['name','key'],how='left').set_index(['name','date_x']).d...
pandas|dataframe|concat|multi-index
1
6,008
48,521,360
Pandas - fill NaN based on the previous value of another cell
<p>I have some stocks data in a dataframe that I'm resampling, which results in some NaN values. Here's a section of the raw feed:</p> <pre><code>In [34]: feeddf Out[34]: open high low close volume date 2017-12-03 07:00:00 14.46 14.46 14.46 14.46 25000 2017-12-03 07:01:00 14.46 14....
<p>First forward fill last column <code>close</code> and then <code>bfill</code> by columns:</p> <pre><code>print (df) open high low close date 2017-12-03 07:00:00 14.46 14.46 14.46 14.81 2017-12-03 07:03:00 NaN NaN NaN NaN 2017-12-...
python|pandas
4
6,009
51,843,514
Filling Null values with respective mean
<p>I have a dataset as follow - </p> <pre><code>alldata.loc[:,["Age","Pclass"]].head(10) Out[24]: Age Pclass 0 22.0 3 1 38.0 1 2 26.0 3 3 35.0 1 4 35.0 3 5 NaN 3 6 54.0 1 7 2.0 3 8 27.0 3 9 14.0 2 </code></pre> <p>Now I want to fill all the...
<p>You can use</p> <p><strong>1]</strong> <code>transform</code> and lambda function</p> <pre><code>In [41]: df.groupby('Pclass')['Age'].transform(lambda x: x.fillna(x.mean())) Out[41]: 0 22.0 1 38.0 2 26.0 3 35.0 4 35.0 5 22.4 6 54.0 7 2.0 8 27.0 9 14.0 Name: Age, dtype: float64 </code...
python|pandas|kaggle
3
6,010
41,925,157
LogisticRegression: Unknown label type: 'continuous' using sklearn in python
<p>I have the following code to test some of most popular ML algorithms of sklearn python library:</p> <pre><code>import numpy as np from sklearn import metrics, svm from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from skl...
<p>You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to <code>int</code> it will be accepted as input (although it will be questionable if that's the right way to do it). </p> <p>It would be better to convert your training scores by using scikit's <a href=...
python|numpy|scikit-learn
119
6,011
41,864,014
Setting pandas multiple rows with enlargement
<p>According to the <code>pandas</code> documentation, it should be possible to append-non-existent rows a <code>DataFrame</code> using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#setting-with-enlargement" rel="nofollow noreferrer">setting with enlargment</a>, but while <em>retrieving</em> multip...
<p>Per your edit, you can assign with overlap and enlargement by using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html#pandas.DataFrame.reindex" rel="nofollow noreferrer"><code>reindex</code></a> on the union of your two indexes, followed by <code>loc</code>:</p> <pre><code...
python|python-3.x|pandas|dataframe
1
6,012
64,458,509
Looping through Numpy array and slicing
<p>I am working on a certain task which uses numpy. I have the following array:</p> <pre><code>A = array([[1, 2], [3, 4], [5, 6], [7, 8]]) </code></pre> <p>And I have another variable called B which is of shape (10, 10). What I want to do is basically loop through the array A and do the following:</p> <pre><code>B[1,2]...
<p>You don't need a loop</p> <p>Setting up an example</p> <pre><code>A = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) B = np.arange(100).reshape(10,10) B </code></pre> <p>Out:</p> <pre><code>[[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39]...
arrays|python-3.x|numpy
0
6,013
64,454,928
Time Diff on vertical dataframe in Python
<p>I have a dataframe, df that looks like this</p> <pre><code> Date Value 10/1/2019 5 10/2/2019 10 10/3/2019 15 10/4/2019 20 10/5/2019 25 10/6/2019 30 10/7/2019 35 </code></pre> <p>I would like to calculate the delta for a period of 7 ...
<p>Let us try <code>shift</code></p> <pre><code>s = df.set_index('Date')['Value'] df['New'] = s.shift(freq = '-6 D').reindex(s.index).values df['DIFF'] = df['New'] - df['Value'] df Out[39]: Date Value New DIFF 0 2019-10-01 5 35.0 30.0 1 2019-10-02 10 NaN NaN 2 2019-10-03 15 NaN NaN 3...
python|pandas|numpy
1
6,014
64,393,028
Select different columns in different rows according to another pandas Series
<p>I have a pandas Series which contains the column names that I need to collect data from:</p> <pre><code>1 col1 3 col4 4 col3 5 col5 6 col5 </code></pre> <p>And the dataframe that contains data looks like:</p> <pre><code> col1 col2 col3 col4 col5 1 data1 data2 ...
<p>This is <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.lookup.html" rel="nofollow noreferrer"><code>lookup</code></a>:</p> <pre><code>print (df2.lookup(df2.index, df1)) ['data1' 'data9' 'data13' 'data20' 'data25'] </code></pre>
python|pandas|dataframe|logic|data-science
1
6,015
64,406,280
Select rows in a dataframe based on a condition spanning several dates
<p>I'm working with the dataframe below. I would like to apply a filter that will create a new dataframe of the filtered result set. The filtered dataset should result in a True condition if the first and last day of a three day rolling lookback window are less or equal to 0.5, <strong>the middle value should be exclud...
<p>I made use of the fact that the source DataFrame contains <strong>consecutive</strong> dates in <strong>descending</strong> order.</p> <p>So instead of the rolling window, <em>shift</em> can be used to get <em>LSTPX</em> from the row 2 positions down from the current row:</p> <pre><code>result = df[(df.LSTPX &lt;= 0...
python|pandas
2
6,016
64,310,087
how to return only the True values?
<p>I'm checking if a word is in the object in a dataframe series. Like this:</p> <pre><code>indicators['Indicator Name'].str.contains('population') </code></pre> <p>But when I run this command, my result is all values as true or false. How can I print only the true values and show all of them? Since the dataframe is hu...
<p>Use lambda expresion:</p> <pre><code>indicators[lambda x: x['Indicator Name'].str.contains('population')] </code></pre>
python|pandas|string|contains
0
6,017
64,472,837
my model does not perform python and tensorflow process, keras
<pre><code>import sys import os import tensorflow import keras from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras import optimizers from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dropout, Flatten, Dense, Activation from tensorflow.keras.layers i...
<p>Your steps per epoch is too large for your current dataset size, try lowering it.</p>
python|tensorflow|keras|deep-learning|conv-neural-network
0
6,018
47,621,187
pandas - aggregating on contents of dataframe
<p>I have a pandas dataframe which looks like this:</p> <pre><code> Lane PropA PropB PropC Sample NameA R1 PASS FAIL WARN NameB R2 FAIL FAIL PASS NameC R1 WARN PASS PASS NameD R2 PASS PASS WARN </code></pre> <p>I have as a goal to produce a bar plot that for each P...
<p>First filter only necessary columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>drop</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</cod...
python|pandas
1
6,019
49,239,478
How to get a single value from model.predict() results
<p>I am trying to use a neural network to predict actions for a car simulator game that runs in another file. I need to get the value predicted for an action to pass into the game but i am struggling to do this. After calling model.predict i have attempted to access the value as if from an array but this returns an out...
<p>You're feeding your network a list of 8 elements, when it expected an iterable of 8-dimensional samples. Practically:</p> <pre><code>&gt;&gt;&gt; a = [currentLane, offRoad, collision, lane1, lane2, lane3, reward, a_action] &gt;&gt;&gt; a = np.array(a) # convert to a numpy array &gt;&gt;&gt; a = np.expand_dims(a, 0)...
python|tensorflow|machine-learning|neural-network|keras
2
6,020
48,987,956
pandas multi-column merge on index
<p>hello i'm newbie in pandas</p> <p>for example, datas of cryptocurrency are as below</p> <p><strong>BTC</strong></p> <pre><code>time(index) open high low close value 0 1 4 1 2 1 1 2 5 2 3 2 </code></pre> <p><strong>ETH</strong></p> <pre><code>time(index) open high ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with parameter <code>keys</code> for first level of <code>MultiIndex</code>:</p> <pre><code>df = pd.concat([df1, df2], keys=('BTC','ETH'), axis=1) print (df) BTC ...
pandas|merge
2
6,021
48,977,206
Index Error when using list comprehension on column in Pandas Dataframe
<p>I have a DataFrame with a column like this: <code> Data Science Score 0 303231.0 1 238632.0 2 209423.0 3 207254.0 4 206395.0</code></p> <p>I am trying to split the elements in the series from the end after the character that corresponds to their index+1.</p> <p>If I use <code>print()</code> wi...
<p>If I correctly understand you want to convert the value in the cell to an int of length 5.</p> <p>What about:</p> <pre><code>df['rounded_score'] = df['Data Science Score'].apply(lambda x: int(x / 10.0)) </code></pre> <p>this approach should easier than coverting to string and split.</p>
python-3.x|pandas|dataframe|list-comprehension
0
6,022
58,620,033
Extract column value based on another column, reading multiple files
<p>I will like to extract out the values based on another on Name,Grade,School,Class. For example if I were to find Name and Grade, I would like to go through column 0 and find the value in the next few column, but the value is scattered(to be extracted) around the next column. Same goes for School and Class. </p> <p>...
<p>I think here is possible use:</p> <pre><code>for file in files: df = pd.read_csv(file,header=0) #filter out first column and reshape - removed NaNs, convert to 1 column df df = df.iloc[1:].stack().reset_index(drop=True).to_frame('data') #compare by : m = df['data'].str.endswith(':', na=False) ...
python|pandas|dataframe
1
6,023
58,848,252
Python: loading data from file csv insert whole data in .db and operate on tables
<p>I'm learning currently a python language. Here is my question i converted .txt file to .csv then want to insert to table to database file. I have a problem with iteriation on the bottom im pasting results. How can i iterate with it? Im struggle with that few days so don't really know how to solve the problem.</p> <...
<p>You could simplify the operation using sqlalchemy</p> <pre><code>from sqlalchemy import create_engine # sqlite://&lt;nohostname&gt;/&lt;path&gt; # where &lt;path&gt; is relative: engine = create_engine('sqlite:///artists.db') df.to_sql('tabela', con = engine, if_exists = 'append', chunksize=1000) </code></pre> <p>...
python|pandas|sqlite
0
6,024
58,853,468
How do I customize the colours in the bars using custom number set in matplotlib?
<p>I am trying to add colors to the bar according to the integer value, lets say the values are 1 to 20, 1 will be the lightest and 20 will be the darkest, but none of the colors can be the same, so far I am at using an incorrect <code>colorbar</code> method:</p> <pre><code>import pandas as pd import numpy as np impor...
<p>I just realized using <code>plt.barh</code> and <code>colormaps</code> provide better plots, use:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'values': [0, 0, 0, 0, 0, 17, 16, 16, 15, 15, 15, 14, 13, 13, 13]}) df = df.sort_values(by='values').reset_index(drop=True) s = df[...
python|pandas|matplotlib|plot|colorbar
5
6,025
70,196,691
How to split a value in a dataframe if the value contains a digit?
<p>I have a dataframe which looks like below (in reality much bigger):</p> <pre><code>df = pd.DataFrame([ [-0.531, '30 mg', 0], [1.49, '70 kg', 1], [-1.3826, 'food delivery', 2], [0.814, '80 degrees', ' '], [-0.22, ' ', 4], [-1.11, '70 grams', ' '], ], columns='Power Value Stage'...
<p>You have multiple problems in your code. You can't simply use if-else in a function call. You are applying pandas string methods, which return a whole Series / DataFrame containing the split lists. That means you can't simply use bracket indexing like <code>[-1]</code>. Look at the output of <code>df['Value'].str.sp...
python|pandas|dataframe
1
6,026
56,090,087
Operation on data frame to transform rows into separate columns
<p>I have a data-frame containing following structure</p> <pre><code> **Email MAC** email_1@mail.com AA:AA:AA:AA:A1 email_1@mail.com AA:AA:AA:AA:A5 email_1@mail.com PP:PP:PP:PP:P5 email_1@mail.com PP:PP:PP:PP:P6 email_2@mail.com AA:AA:AA:...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for counter column, filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow nor...
python|python-3.x|numpy|dataframe
0
6,027
56,226,621
How to extract data/labels back from TensorFlow dataset
<p>there are plenty of examples how to create and use TensorFlow datasets, e.g.</p> <pre><code>dataset = tf.data.Dataset.from_tensor_slices((images, labels)) </code></pre> <p>My question is how to get back the data/labels from the TF dataset in numpy form? In other words want would be reverse operation of the line ab...
<p>In case your <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="noreferrer"><code>tf.data.Dataset</code></a> is batched, the following code will retrieve all the y labels:</p> <pre><code>y = np.concatenate([y for x, y in ds], axis=0) </code></pre> <p>Quick explanation: [y for x, y in ds] is kn...
tensorflow|tensorflow-datasets
56
6,028
55,708,136
Does loc/iloc return a reference or a copy?
<p>I am experiencing some problems while using .loc / .iloc as part of a loop. This is a simplified version of my code:</p> <pre class="lang-py prettyprint-override"><code> INDEX=['0', '1', '2', '3', '4'] COLUMNS=['A','B','C'] df=pd.DataFrame(index=INDEX, columns=COLUMNS) i=0 while i&lt;1000: for row in INDEX: ...
<p>I <strong>think</strong> both <code>loc</code> and <code>iloc</code> (didn't test <code>iloc</code>) will <strong>point</strong> to a specific index of the dataframe. They do not make copies of the row. </p> <p>You can use the <code>copy()</code> method on the row to solve your problem.</p> <pre><code>import panda...
python|pandas|dataframe
4
6,029
64,694,572
Python how to apply per-column mean on Series of series
<p>I have a series with 800 elements. Each element - is a series with n elementes , <code>800 &lt; n &lt;= 1200</code>, so the longest series <code>len</code> is 1200. I want to have a single vector with 1200 elements, each element value - is the mean of this position for all series. So if:</p> <pre><code>s = ([1,2,3,4...
<p>Create <code>DataFrame</code> by constructor and use <code>mean</code>:</p> <pre><code>s = pd.Series(([1,2,3,4,5,6,1], [1,3,9,6], [4,4])) out = pd.DataFrame(s.tolist()).mean().tolist() print (out) [2.0, 3.0, 6.0, 5.0, 5.0, 6.0, 1.0] </code></pre>
python|pandas|numpy|dataframe|series
0
6,030
64,925,753
Python looping over folders and its subfolders to read CSV is getting file names but on read_csv it is returning file not found
<p>I am trying to loop over folders and subfolder to access and read CSV files before transforming them into JSON. Here is the code I am working on:</p> <pre><code>cursor = conn.cursor() try: # Specify the folder containing needed files folderPath = 'C:\\Users\\myUser\\Desktop\\toUpload' # Or using input() ...
<p>Before reading the csv file, you should compose the whole path to the file, otherwise, pandas won't be able to read that file.</p> <pre class="lang-py prettyprint-override"><code>import os # ... path = os.path.join(folderPath, countries, sectors, file) data = pd.read_csv(path) </code></pre> <p>Also instead of using...
python|pandas
1
6,031
64,618,725
Which month has the highest cumulative sum in multiindex pandas
<p>I have this <code>MultiIndex</code> pandas dataframe:</p> <pre><code> chamber_temp month day 1 1 0.000000 2 0.005977 3 0.001439 4 -0.000119 5 0.000514 ... 12 27 0.001799 28 0.002346 29 -0.001815 30 0.001102 3...
<p>You can leverage on <code>level</code> parameter in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.sum.html" rel="nofollow noreferrer"><code>Series.sum</code></a> when there's <code>MultiIndex</code> to avoid <code>groupby</code> in such cases.</p> <pre><code>df['champer_temp'].sum...
python|python-3.x|pandas|multi-index
2
6,032
64,886,170
How to extract a nested dictionary from a STRING column in Python Pandas Dataframe?
<p>There's a table where one data point of its column <code>event</code> looks like this:</p> <p>THE 'event IS A STRING COLUMN!</p> <pre><code>df['event'] RETURNS: &quot;{'eventData': {'type': 'page', 'name': &quot;WHAT'S UP&quot;}, 'eventId': '1003', 'deviceType': 'kk', 'pageUrl': '/chick 2/whats sup', 'version': '1.0...
<p>I've finally fot the answer from another post: <a href="https://stackoverflow.com/questions/51359783/python-flatten-multilevel-nested-json">Python flatten multilevel/nested JSON</a></p> <p>How to use: json_col = pd.DataFrame([flatten_json(x) for x in df['json_column']])</p> <pre><code>def flatten_json(nested_json, e...
python|regex|pandas|dataframe|python-re
0
6,033
64,914,930
Finding duplicate row pairs irrespective of column order
<p>I have a pandas data frame and I am looking for a simple way to identify rows where the values are the same (duplicate), <strong>irrespective of the order of the columns.</strong></p> <p>For example:</p> <pre><code>df = pd.DataFrame([[1, 3], [4, 2], [3, 1], [2, 3], [2, 4], [1, 3]], columns=[&quot;a&quot;, &quot;b&qu...
<p>You could do this using <a href="https://numpy.org/doc/stable/reference/generated/numpy.sort.html" rel="nofollow noreferrer"><code>np.sort</code></a> on <code>axis=1</code>, then <code>groupby</code></p> <pre><code>u = pd.DataFrame(np.sort(df,axis=1),index=df.index) [tuple(g.index) for _,g in u[u.duplicated(keep=Fal...
python|pandas|duplicates
1
6,034
39,887,598
How do I delete rows I don't need in dataframe pandas?
<p>I want to delete a certain row where both the ZIPCODE and AV_LAND values would be deleted. For instance, I want to delete row 1 and 2. How would I do that? In addition, I want to reset the index once I delete all the rows I don't need.</p> <pre><code>ZIPCODE AV_LAND 0 02108 2653506 1 02109 5559661 2 02110...
<p>You can use drop:</p> <pre><code>df.drop([1, 2]).reset_index(drop=True) Out: ZIPCODE AV_LAND 0 02108 2653506 1 02134 4333212 </code></pre> <p>This is not an inplace operation so if you want to change the original DataFrame you need to assign it back: <code>df = df.drop([1, 2]).reset_index(drop=True...
pandas|dataframe
1
6,035
69,363,602
Pivoting without numerical aggregation/ a numerical column
<p>I have a dataframe that looks like this</p> <pre><code>d = {'Name': ['Sally', 'Sally', 'Sally', 'James', 'James', 'James'], 'Sports': ['Tennis', 'Track &amp; field', 'Dance', 'Dance', 'MMA', 'Crosscountry']} df = pd.DataFrame(data=d) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> ...
<p>You can do that, either with <code>.pivot()</code> if your column / index names are unique, or with <code>.pivot_table()</code> by providing an aggregation function that works on strings too, e.g. <code>'first'</code>.</p> <pre><code>&gt;&gt;&gt; df['Sport_num'] = 'Sport ' + df.groupby('Name').cumcount().astype(str)...
python|pandas|pivot-table|reshape|melt
2
6,036
69,538,626
How to transform a time series into a two-column dataframe showing the count for each element of the time series, using Python
<p>I have data in a file that takes the form of a list of array: each line correspond to an array of integers, with the first element of each array (it is a time series) corresponding to an index. Here is an example :</p> <pre><code>1 101 103 238 156 48 78 2 238 420 156 103 26 3 220 103 154 48 101 238 156 26 420 4 26 5...
<pre><code>import pandas as pd array1 = [1, 101, 103, 238, 156, 48, 78] array2 = [2, 238, 420, 156, 103, 26] array3 = [3, 220, 103, 154, 48, 101, 238, 156, 26, 420] array4 = [4, 26, 54, 43, 103, 156, 238, 48] pd.Series(list(array1 + array2 + array3 + array4)).value_counts() </code></pre>
python|pandas|dataframe|numpy|time-series
0
6,037
66,320,198
Keras fit with generator function always execute in the main thread
<p>How can I make Keras Models <code>fit</code> method execute a generator in the main thread? From the docs, it looks like that setting workers=0 would execute the code in the main thread.</p> <blockquote> <p>workers Integer. Used for generator or keras.utils.Sequence input only. Maximum number of processes to spin ...
<p>It seems like @Ena was on the right track. The following code runs each iteration of the generator on the main thread. <code>workers</code> must be set to 1. If it is set to 0, then the iterations are not on the main thread.</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import threading...
python|tensorflow|keras
2
6,038
66,063,918
How to delete cells and cut rows find by " ̶i̶s̶i̶n̶(̶)̶ " df.mask()?
<p>I have dataframe with random cells, for example &quot;boss&quot;. How can I delete the cells &quot;boss&quot; and all right cells in the same row using df.isin()?</p> <pre><code>x=[] for i in range (5): x.append(&quot;boss&quot;) df=pd.DataFrame(np.diagflat(x) ) 0 1 2 3 4 0 boss ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a> with mask:</p> <pre><code>df = df.mask(df.eq('boss').cumsum(axis=1).ne(0)) print (df) 0 1 2 3 4 0 NaN NaN NaN NaN NaN 1 NaN NaN Na...
python|pandas|dataframe
1
6,039
52,633,582
(Dask) How to distribute expensive resource needed for computation?
<p>What is the best way to distribute a task across a dataset that uses a relatively expensive-to-create resource or object for the computation.</p> <pre><code># in pandas df = pd.read_csv(...) foo = Foo() # expensive initialization. result = df.apply(lambda x: foo.do(x)) # in dask? # is it possible to scatter the fo...
<pre><code>foo = dask.delayed(Foo)() # create your expensive thing on the workers instead of locally def do(row, foo): return foo.do(row) df.apply(do, foo=foo) # include it as an explicit argument, not a closure within a lambda </code></pre>
pandas|dask|python-3.7|dask-distributed
1
6,040
52,508,359
multi label classification confusion matrix have wrong number of labels
<p>i am feeding in y_test and y_pred to a confusion matrix. My data is for multi label classification so the row values are one hot encodings.</p> <p>my data has 30 labels but after feeding into the confusion matrix, the output only has 11 rows and cols which is confusing me. I thought i should have a 30X30. </p> <p>...
<p>I think you are not quit clear the definition of <code>confusion_matrix</code> </p> <pre><code>y_true = [2, 0, 2, 2, 0, 1] y_pred = [0, 0, 2, 2, 0, 2] confusion_matrix(y_true, y_pred) array([[2, 0, 0], [0, 0, 1], [1, 0, 2]]) </code></pre> <p>Which in data frame is </p> <pre><code>pd.DataFrame(confus...
python|pandas|numpy|confusion-matrix|multilabel-classification
1
6,041
46,382,820
Creating a tensor variable with a dynamic shape
<p>I am a newbie to tensorflow. I have a tensor <code>score</code> and I am trying to create a tensor variable with the shape <code>score.shape[0]</code>.</p> <pre><code>score = tf.constant(np.array([[10, 0, -5], [4, 3, 0], [-3, 0, 11]]), dtype=tf.float32) v = tf.Variable(tf.zeros(tf.shape(score)[0])) </code></pre> ...
<p>You can just use <code>score.shape[0]</code> to get the first dimension of the <code>score</code> tensor:</p> <pre><code>sess = tf.InteractiveSession() score = tf.constant(np.array([[10, 0, -5], [4, 3, 0], [-3, 0, 11]]),dtype=tf.float32) v = tf.Variable(tf.zeros(score.shape[0])) tf.global_variables_initializer().r...
python|tensorflow
0
6,042
46,305,622
Why does numpy array comparison return boolean array?
<p>Why does:</p> <pre><code>[3] == np.arange(10) </code></pre> <p>return:</p> <pre><code>([False, False, False, True, False, False, False, False, False, False], dtype=bool) </code></pre> <p>Instead of simply <code>False</code>?</p>
<p>Why does <code>np.arange(10)+3</code> return an array? The comparison <code>[3] == np.arange(10)</code> is treating the arguments in the same way, element by element (with broadcasting as needed). </p> <p>If it can't broadcast and do element wise comparison it does return a False or an error.</p> <pre><code>In [...
python|numpy|multidimensional-array
1
6,043
46,284,172
Pandas sequentially apply function using output of previous value
<p>I want to compute the "carryover" of a series. This computes a value for each row and then adds it to the previously computed value (for the previous row). </p> <p>How do I do this in pandas?</p> <pre><code>decay = 0.5 test = pd.DataFrame(np.random.randint(1,10,12),columns = ['val']) test val 0 4 1 5 2 7...
<p>Consider a vectorized version with <code>cumsum()</code> where you cumulatively sum (val * decay) with the very first <em>val</em>. </p> <p>However, you then need to subtract the very first (val * decay) since <code>cumsum()</code> includes it:</p> <pre><code>test['loop_decay'] = (test.ix[0,'val']) + (test['val']*...
python|pandas|apply
2
6,044
58,227,796
Plotly Scatter Points on Maps - Removing Longitude and Latitude from text
<p>I am following this example very closely to experiment with plotting scatter points on maps and this is working perfectly: <a href="https://plot.ly/python/scatter-plots-on-maps/" rel="nofollow noreferrer">https://plot.ly/python/scatter-plots-on-maps/</a></p> <p>However, when you hover over each scatter point you wi...
<p>You should be able to set <code>hoverinfo="text"</code> to achieve this. Here is the relevant documentation page: <a href="https://plot.ly/python/hover-text-and-formatting/" rel="nofollow noreferrer">https://plot.ly/python/hover-text-and-formatting/</a></p>
python|pandas|plot|geolocation|plotly
4
6,045
69,040,070
How can I reconstruct original matrix from SVD components with following shapes?
<p>I am trying to reconstruct the following matrix of shape (256 x 256 x 2) with SVD components as</p> <pre><code>U.shape = (256, 256, 256) s.shape = (256, 2) vh.shape = (256, 2, 2) </code></pre> <p>I have already tried methods from documentation of numpy and scipy to reconstruct the original matrix but failed multiple...
<p>From <strong>np.linalg.svd</strong>'s documentation:</p> <blockquote> <p>&quot;... If <code>a</code> has more than two dimensions, then broadcasting rules apply, as explained in :ref:<code>routines.linalg-broadcasting</code>. This means that SVD is working in &quot;stacked&quot; mode: it iterates over all indices of...
numpy|scipy|numpy-ndarray|svd
1
6,046
68,894,007
Apply multiple filter on column using tuple
<pre><code>data = [['A',23], ['D',50], ['C',32], ['D',21], ['D',24], ['B',20], ['C',68], ['A',52], ['A',41],[ 'D',44], ['B',29], ['B',70], ['B',33], ['C',56], ['A',72]] df = pd.DataFrame(data, columns = ['group', 'age']) </code></pre> <p>I would like to filter down to rows where <code>age</code> is equal to, or betwe...
<pre class="lang-py prettyprint-override"><code>df['range'] = df['group'].map({v:k for k, v in group_mask.items()}) df['in_range'] = (df['range'].str[0] &lt;= df['age']) &amp; (df['age'] &lt;= df['range'].str[1]) #filtered df = df[df['in_range']] df.drop(columns=['range', 'in_range'], inplace=True) # group age ...
python|pandas|dataframe|filter|tuples
0
6,047
68,920,781
Extracting the data from pandas dataframe
<p>I have a pandas dataframe having data in each row like below</p> <pre><code>Joel Thompson / Tracy K. Smith&lt;/h2&gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt;New work (World Premiere–New York Philharmonic Commission) </code></pre> <p>How would I filter this so I can get results to work with like this:</p> <pre><code...
<p>You should try to use the split function for string variables. You can do this this way :</p> <pre><code>#Get your row in a string variable text text = &quot;Joel Thompson / Tracy K. Smith&lt;/h2&gt;&lt;/div&gt;&lt;div&gt;&lt;p&gt;New work (World Premiere–New York Philharmonic Commission)&quot; #Extracting the name...
python-3.x|pandas
0
6,048
69,178,181
Use string literal instead of header name in Pandas csv file manipulation
<p>Python 3.9.5/Pandas 1.1.3</p> <p>I use the following code to create a nested dictionary object from a csv file with headers:</p> <pre><code>import pandas as pd import json import os csv = &quot;/Users/me/file.csv&quot; csv_file = pd.read_csv(csv, sep=&quot;,&quot;, header=0, index_col=False) csv_file['org'] = csv_f...
<p>You could just build it <em>by hand</em>:</p> <pre><code>csv_file['org'] = csv_file['location'].apply(lambda x: {'location': x, 'type': 'foo'}) </code></pre>
python|pandas
1
6,049
69,217,935
Insert a row into a dataframe based on values in another dataframe
<p>I want to insert a row into a dataframe based on values in another dataframe. I have attempted to reproduce my problem in a simple way. I have two dataframes df1 and df2.</p> <pre><code>data = [['apple', 'apples'], ['orange', 'oranges'], ['banana', 'bananas'], ['kiwi', 'kiwis']] df1 = pd.DataFrame(data, columns= ['f...
<p>Let's do:</p> <pre><code># get labels from df2 _df = pd.merge(df1, df2, how='left', on='fruit') # drop the old fruit column and rename fruits to fruit _df = _df.drop('fruit', axis=1) _df = _df.rename({'fruits': 'fruit'}, axis=1) # concat the 2 dataframes together df2 = pd.concat([df2, _df]) </code></pre>
python|pandas|dataframe|nested-loops
1
6,050
44,520,286
Merge dataframe resulting in Series
<p>I working with the Texas Hospital Discharge Dataset and I am trying to determine the top 100 most frequent Principal Surgery Procedures over a period of 4 years.</p> <p>Do to this I need to go through each quarter of each year and count the procedures, but when I try to merge different quarters the result is a Seri...
<p>the merge will indeed return a dataframe, but in your code you are summing on axis=1 (all values in one row) after merging which then gives you a series (since the values from all columns are summed together in one final column).</p> <p>Hope that helps.</p>
python|pandas
1
6,051
44,482,722
Why tensorflow constant is feedable true
<p>I am learning tensorflow</p> <pre><code>import tensorflow as tf print(tf.VERSION) a = tf.placeholder(tf.float32, shape=[3]) b = tf.constant([2, 2, 2], tf.float32) c = a + b with tf.Session() as sess: print(tf.get_default_graph().is_feedable(b)) print(sess.run(c, feed_dict={a: [3, 2, 3]})) </code></pre> <p...
<p>Because in TF you can also <a href="https://www.tensorflow.org/programmers_guide/reading_data" rel="nofollow noreferrer">feed values in constants and variables</a>:</p> <blockquote> <p>While you can replace any Tensor with feed data, including variables and constants, the best practice is to use a tf.placeholder ...
python|tensorflow
2
6,052
71,717,202
Filtering in Python
<p>I have rather a simple question but couldn't find an answer for it. I have an array as following:</p> <pre><code>sample = np.random.uniform(0,1,1000) </code></pre> <p>and I would like to filter values between 0.1 and 0.13 plus values above 0.9.</p> <pre><code>filter1 = sample[((sample &gt; 0.1) &amp; (sample &lt;0.1...
<p>You are currently filtering for numbers that are above 0.1, below 0.13, and above 0.9; a number must meet all three criteria to meet your requirements.</p> <p>To fix this, change your second ampersand to a pipe, such that the filtering reads &quot;(numbers above 0.1 and below 0.13), or above 0.9&quot;:</p> <pre clas...
python|arrays|python-3.x|numpy
4
6,053
42,258,758
How to delete the rows with pattern
<p>I have a DataFrame as below. I want to delete rows which has RegionName containing [edit]. I appreciate any help.</p> <pre><code> State RegionName1 0 Alabama Alabama[edit] 1 Alabama Auburn 2 Alabama Florence 3 Alabama Jacksonville 4 Alabama Livingston 9 Alaska Alaska[edit] 10 Alaska Fairbanks 11...
<p>you can use <code>.str.endswith()</code> method:</p> <pre><code>In [165]: df = df.loc[~df.RegionName1.str.endswith('[edit]')] In [166]: df Out[166]: State RegionName1 1 Alabama Auburn 2 Alabama Florence 3 Alabama Jacksonville 4 Alabama Livingston 6 Alaska Fairbanks 8 ...
python|pandas
1
6,054
69,852,627
Compare 2 pandas.DataFrames, get differences and print only rows that changed from the first one
<p>I have 2 dataframes which I am comparing with below snippet:</p> <pre><code>df3 = pandas.concat([df1, df2]).drop_duplicates(keep=False) </code></pre> <p>It works fine, it compares both and as an output I got rows that are different form both of them.</p> <p>What I would like to achieve is to compare 2 dataframes to ...
<p>I would use <code>~isin()</code>:</p> <pre><code>df.set_index(list(df.columns), inplace=True) df2.set_index(list(df2.columns), inplace=True) df[~df.index.isin(df2.index)].reset_index() </code></pre>
python|pandas
1
6,055
69,955,550
Keras model with fasttext word embedding
<p>I am trying to learn a language model to predict the last word of a sentence given all the previous words using keras. I would like to embed my inputs using a learned fasttext embedding model.</p> <p>I managed to preprocess my text data and embed the using fasttext. My training data is comprised of sentences of 40 t...
<p>If you really want to use the word vectors from <code>Fasttext</code>, you will have to incorporate them into your model using a weight matrix and <code>Embedding</code> layer. The goal of the embedding layer is to map each integer sequence representing a sentence to its corresponding 300-dimensional vector represen...
python|tensorflow|keras|fasttext|language-model
2
6,056
43,077,893
Pandas.to_csv gives error 'ascii' codec can't encode character u'\u2013' in position 8: ordinal not in range(128)
<p>I am trying to save a panda dataframe to csv and it fails with error: </p> <pre><code>df.to_csv(location, sep='|', index=False, header=True) </code></pre> <p>'ascii' codec can't encode character u'\u2013' in position 8: ordinal not in range(128)</p> <p>I have pandas version as: </p> <pre><code>&gt;&gt;&gt; impor...
<p>from <a href="https://github.com/pandas-dev/pandas/blob/v0.18.1/pandas/core/frame.py" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/blob/v0.18.1/pandas/core/frame.py</a> we find :</p> <pre><code>formatter = fmt.CSVFormatter(self, path_or_buf, line_terminator ...
python|pandas
1
6,057
43,172,357
regarding the ValueError: If `inputs` don't all have same shape and dtype or the shape
<p>There is a program that defines the loss function as follows:</p> <pre><code>def loss(hypes, decoded_logits, labels): """Calculate the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor ...
<p>As a work around, you can replace this line with:</p> <pre><code>temp = tf.get_collection('losses') if temp == []: temp = [0] weight_loss = tf.add_n(temp, name='total_loss') </code></pre> <p>As adding a zero value won't affect the final result but will be effective to run the software... what ...
tensorflow
0
6,058
43,457,890
Multiprocessing with GPU in keras
<p>I need to compute multiple deep models in parallel and average their results. My job runs forever after finishing computation with <code>GPU 0</code>.</p> <pre><code>def model_train(self, params): from nn_arch import nn_models X, y, gpu_no = params print("GPU NO ", gpu_no) with tf.device('/gpu:' + s...
<p>Before compiling the model in keras. Add this line</p> <p>model = make_parallel(model, 2)</p> <p>where 2 is the number of GPUs available.</p> <p>The make_parallel function is available in this file. Just import the file in your code and your code will be executed on multiple GPUs.</p> <p><a href="https://github....
tensorflow|keras
4
6,059
43,334,937
How to build tensorflow native for android using clang toolchain?
<p>Based on this <a href="https://github.com/bazelbuild/bazel/issues/817" rel="nofollow noreferrer">bazel using clang</a> , need to add command line option for setting android compiler option. How does this translate to <code>*.bzl</code> files, crosstool files in tensorflow?</p>
<p>Bazel 0.4.5 and later support Android NDK clang via the <code>--android_compiler=clang3.8</code> build flag. Note that in NDK13, clang is the default (previous was gcc) so this flag is only needed for NDK12 and prior. No bzl or crosstool files necessary (although android_ndk_repository is actually generating a cross...
android|tensorflow|bazel
0
6,060
50,321,673
Slicing a Data frame by checking consecutive elements
<p>I have a DF indexed by time and one of its columns (with 2 variables) is like [x,x,y,y,x,x,x,y,y,y,y,x]. I want to slice this DF so Ill get this column without same consecutive variables- in this example :[x,y,x,y,x] and every variable was the first in his subsequence.</p> <p>Still trying to figure it out...</...
<p>Assuming you have df like below </p> <pre><code>df=pd.DataFrame(['x','x','y','y','x','x','x','y','y','y','y','x']) </code></pre> <p>We using <code>shift</code> to find the next is equal to the current or not </p> <pre><code>df[df[0].shift()!=df[0]] Out[142]: 0 0 x 2 y 4 x 7 y 11 x </code></pre>
python|pandas|dataframe
2
6,061
50,397,321
tensorflow Invalid symbol
<p>I am using seq2seq to train a language model on some english words not found in the dictionary. But when I train the model on a phonetic dictionary I get these warnings, then the model wont recognize the words after training because it cant recognize these letters.</p> <pre><code>WARNING:tensorflow:Invalid symbol:A...
<p>So I am gonna go ahead and answer my own question if someone needs help, The problem was that I needed to add the missing letters to vocab.g2p. Edit: added CAPITAL LETTERS to vocab.g2p</p>
python|tensorflow|speech-recognition|cmusphinx
0
6,062
50,442,156
Loading a model from tensorflow SavedModel onto mutliple GPUs
<p>Let's say someone hands me a TF SavedModel and I would like to replicate this model on the 4 GPUs I have on my machine so I can run inference in parallel on batches of data. Are there any good examples of how to do this? </p> <p>I can load a saved model in this way:</p> <pre><code>def load_model(self, saved_model_...
<p>There is no support for this use case in TensorFlow at the moment. Unfortunately, "replicating the inference function" based only on the SavedModel (which is basically the computation graph with some metadata), is a fairly complex (and brittle, if implemented) graph transformation problem.</p> <p>If you don't have ...
tensorflow|multi-gpu
1
6,063
45,552,856
prediction of MNIST hand-written digit classifier
<p>I am new to Deep Learning and am using Keras to learn it. I followed instructions at this <a href="http://machinelearningmastery.com/handwritten-digit-recognition-using-convolutional-neural-networks-python-keras/" rel="nofollow noreferrer">link</a> to build a handwritten digit recognition classifier using MNIST data...
<p>To my knowledge, you will need to turn this into a 28x28 grayscale image in order to work with this in Python. That's the same shape and scheme as the images that were used to train MNIST, and the tensors are all expecting 784 (28 * 28)-sized items, each with a value between 0-255 in their tensors as input.</p> <p...
python|tensorflow|keras|mnist|handwriting-recognition
1
6,064
62,667,466
make columns rows python
<p>hello i have the following code:</p> <pre><code>for j in range(8): b=fran[fran.Año.isin([2020]) &amp; fran.Channel.isin(['CANAL 5'])&amp;fran.Week.isin([j])] c=b[['hour','number']] print(c) </code></pre> <p>I get the output:</p> <pre><code> ...
<p>Change your code to</p> <pre><code>l=[] for j in range(8): b=fran[fran.Año.isin([2020]) &amp; fran.Channel.isin(['CANAL 5'])&amp;fran.Week.isin([j])] l.append(b[['hour','number']].set_index('hour').rename(columns={'number' : 'number' + str(j)})) </co...
python|pandas
1
6,065
62,844,757
Linspace on a matrix
<p>I'd like to do something like linspace, but where I specify the corners of the matrix.</p> <p>For example:</p> <pre><code>[[-60 -2] [140 6]] </code></pre> <p>I'd like to fill out a larger matrix:</p> <pre><code>[[-60 -31 -2] [40 21 4] [140 73 6]] </code></pre>
<p>I figured out a solution:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy.interpolate import griddata def interpolate(corners, n): grid_x, grid_y = np.mgrid[0:n:1, 0:n:1] points = [[0, 0], [0, n-1], [n-1, 0], [n-1, n-1]] return griddata(points, corners, (grid_x, grid_y...
python|numpy
1
6,066
62,719,982
multiply pandas column with a number in python
<p>I am trying to multiply the price column with integers but it is not happening.</p> <pre><code>for index,row in df.iterrows(): a=row['price'] row['price'] = a[1:] b = row['price'].split(' ')[1] </code></pre> <p>So I want to multiply by 100000 where price has 'L' in it and by 10000000 where price has 'Cr'...
<p>IIUC, you can try with <code>series.str.extract</code> with <code>series.map</code> and multiplication:</p> <pre><code>d = {&quot;L&quot;:100000,&quot;Cr&quot;:10000000} pat = '|'.join(d.keys()) mapped = df['price'].str.extract('('+pat+')',expand=False).map(d) df['price'] = pd.to_numeric(df['price'].str.replace(pat,...
python|pandas|string|numpy|dataframe
2
6,067
54,629,993
Python - Replace NA's on Joins not working
<p>I am trying to fill the values of a NA with some default text values.</p> <p>Here is my df1</p> <pre><code>data = [['Alex','10'],['Bob','12'],['Clarke','13']] df1 = pd.DataFrame(data,columns=['Id','Age']) </code></pre> <p>Here is my df2</p> <pre><code>data = [['Alex','10'],['Clarke','13']] df2 = pd.DataFrame(dat...
<p>If need replace all missing values after <code>concat</code> by list of <code>DataFrame</code> with creating index by <code>Id</code> use:</p> <pre><code>dfs = [df1, df2, df3] df4 = pd.concat([x.set_index('Id') for x in dfs], axis=1).fillna('IDNP') print (df4) Age Age Age Alex 10 10 10 Bob 1...
python|pandas
1
6,068
54,255,345
Pandas highlighting excel columns with conditions using a function
<p>I have a pandas data-frame (Pre_Final_DataFrame) that I am writing to excel. </p> <p>I need to highlight a row in Excel if that corresponding row has a "No Match" word on any of the column that starts with 'Result_'.</p> <p>So, I decided to go for an array to understand which one needed to be highlighted.</p> <p>...
<p>We can use the <code>StyleFrame</code> package for reading it into an excel sheet.</p> <pre><code>import pandas as pd from StyleFrame import StyleFrame, Styler df = pd.read_excel("Your Excel Sheet") sf = StyleFrame(df) style = Styler(bg_color='yellow') for col in df: sf.apply_style_by_indexes(sf[sf[col]== '...
python|pandas
6
6,069
54,639,512
Trouble setting x_tick value with python scatter plot
<p>I have a pandas dataframe <code>avg_temp</code> with 2 columns. I Want to so a scatter plot of these two columns and with the x_ticks being the index values.</p> <pre><code>High_Avg Low_Avg 2014 28.516129032258064 9.419354838709678 2015 32.193548387096776 16.516129032258064 2016 35.32258064516129 18...
<p>Try:</p> <pre><code>df.plot(style=['o','rx']) _ = plt.xticks(df.index) </code></pre> <p>OR</p> <pre><code>ax = df.plot(style=['o','rx']) _ = ax.set_xticks(df.index) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/NvWmn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NvWmn.p...
python|pandas|matplotlib
0
6,070
73,719,911
Create chronology column in pandas DataFrame
<p>I have a dataframe characterized by two essential columns: <em>name</em> and <em>timestamp</em>.</p> <pre><code> df = pd.DataFrame({'name':['tom','tom','tom','bert','bert','sam'], \ 'timestamp':[15,13,14,23,22,14]}) </code></pre> <p>I would like to create a third column <em>chronology</em> that c...
<p>The function <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.rank.html" rel="nofollow noreferrer">GroupBy.rank()</a>, does exactly what you need. From the documentation:</p> <blockquote> <p><em>GroupBy.rank(method='average', ascending=True, na_option='keep', pct=False, axis=0)</em> ...
python|pandas|dataframe
1
6,071
73,783,623
How to make multiple columns in one column in pandas for the data appended from a list
<p>I am scraping data from yahoo finance all data scraping is working fine. But when I want to store the appended list into an indexable dataframe it returns a blank dataframe however, when I store the data in a non-indexable dataframe it store the data.</p> <p>When I print temp I can see the data even if I convert tem...
<p>try this:</p> <ol> <li>create function to return one dataframe per ticker:</li> </ol> <pre><code>def f(ticker): url = 'https://finance.yahoo.com/quote/'+ticker+'/financials?p='+ticker page = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Ge...
python|pandas|dataframe
0
6,072
73,533,196
Replace A Column Value by Most Frequent Value In Group
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'student': list('AAABBBCCCC'), 'city': ['LA', 'LA', 'NY', 'DC', 'NY', 'NY', 'SF', 'SF', 'LA', 'SF'], 'score': [75, 27, 31, 22, 43, 20, 26, 40, 33, 20]}) print(df) student city score 0 A LA 75 1 ...
<p>You can get the most frequent value with <code>mode</code>, which is a bit faster than <code>value_counts</code>. Then you can use <code>groupby().transform()</code> to broadcast the values to all the rows:</p> <pre><code># lambda x: x.value_counts().index[0] would also work df['city'] = df.groupby('student')['city'...
python|pandas|dataframe|group-by
1
6,073
71,171,188
Pandas sum column data based on summation points
<p>Based on a given dataframe e.g</p> <pre><code> x y 0 1 2 1 2 4 2 3 6 3 4 8 4 5 10 5 6 12 6 7 14 </code></pre> <p>I would like to calculate the sum of the in between values based on given summation points e.g</p> <pre><code> x 0...
<p>IIUC, create a custom group and <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>groupby</code>+<code>agg</code></a>.</p> <p>Note that I used a simple list for the x points, if you have a dataframe <code>df_ref</code>...
python|pandas
1
6,074
71,230,991
Formatting output of series in python pandas
<p>Here is my DataFrame. This is a representation of an 8-hour day, and the many different combinations of schedules. The time is in 24hr time. Input:</p> <pre><code>solutions = problem.getSolutions() pd.options.display.max_columns = None df = pd.DataFrame(solutions) </code></pre> <p>Output:</p> <pre><code> WorkHr1 W...
<p>You can reverse it by passing its index as data and data as index to a Series constructor:</p> <pre><code>out = pd.Series(s.index, index=s).sort_index() </code></pre> <p>Output:</p> <pre><code>9 FreeHour 10 Lunch 11 WorkOut 12 Cleaning 13 WorkHr1 14 WorkHr2 15 WorkHr3 16 WorkHr4 dtyp...
python|pandas
2
6,075
52,214,217
Remove all columns matching a value in Numpy
<p>Let's suppose I have a matrix with a number of binary values:</p> <pre><code>matrix([[1., 1., 1., 0., 0.], [0., 0., 1., 1., 1.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]]) </code></pre> <p>Using <strong>np.sum(M, 0)</strong> produces:</p> <pre><code>matrix([[1., 1., 2., 2., 2.]]) </code></pre> <p>H...
<p>Easier to have an array here:</p> <pre><code>M = M.A </code></pre> <p>Now using simple slicing:</p> <pre><code>M[:, np.sum(M, 0)!=1] </code></pre> <p></p> <pre><code>array([[1., 0., 0.], [1., 1., 1.], [0., 1., 0.], [0., 0., 1.]]) </code></pre>
python|numpy|matrix
2
6,076
52,201,644
Regressor Neural Network built with Keras only ever predicts one value
<p>I'm trying to build a NN with Keras and Tensorflow to predict the final chart position of a song, given a set of 5 features. </p> <p>After playing around with it for a few days I realised that although my MAE was getting lower, this was because the model had just learned to predict the mean value of my training set...
<p>So I am pretty sure that your normalization is the issue: You are not normalizing <em>by feature</em> (as is the de-fact industry standard), but <em>across all data</em>. That means, if you have two different features that have very different orders of magnitude/ranges (in your case, compare <code>timeinchart</code>...
python|tensorflow|machine-learning|neural-network|keras
1
6,077
60,495,864
How to handle repeated input for a Keras layer?
<p>I have a Keras model which has two input layers. </p> <ol> <li>a tweet of shape <code>(20,300)</code>.</li> <li>five other tweets of shape <code>(5,20,300)</code>. however this input is same for all training examples.</li> </ol> <p>In other word, for each training step, there will be a different tweet (first input...
<p>Create a tensor with that constant input:</p> <pre><code>fixed_tweets = keras.backend.constant(the_tweets_as_numpy) </code></pre> <p>Use a regular input and a <code>tensor</code> input: </p> <pre><code>input1 = Input((20,300)) input2 = Input(tensor=fixed_tweets) </code></pre> <p>Go have fun!!</p> <p>You will...
python|tensorflow|keras|deep-learning|keras-layer
0
6,078
59,844,745
Adding Future Dates to DataFrame
<p>How do I add future dates to a data frame? This datetime delta only adds deltas to adjacent columns.</p> <pre><code>import pandas as pd from datetime import timedelta df = pd.DataFrame({ 'date': ['2001-02-01','2001-02-02','2001-02-03', '2001-02-04'], 'Monthly Value': [100, 200, 300, 400] }) df["future_date...
<p>You can do the following:</p> <pre><code># set to timestamp df['date'] = pd.to_datetime(df['date']) # create a future date df ftr = (df['date'] + pd.Timedelta(4, unit='days')).to_frame() ftr['Monthly Value'] = None # join the future data df1 = pd.concat([df, ftr], ignore_index=True) date Monthly Value 0...
python|pandas|datetime
2
6,079
59,786,922
How to best coerce a list of numpy arrays into a pandas dataframe column?
<p>I have a list (posterior_list) of 18,000 <code>numpy arrays</code> with length 82,868. I have a dataframe (y_test) with shape <code>(82,868, 1)</code>. The arrays are posterior predicted values. I would like to append each array inside that list as a column onto the dataframe (y_test) with the end result having s...
<p>You can try</p> <pre><code>y_test.join(pd.DataFrame(posterior_list,columns=y_test.index).T) </code></pre>
python|pandas|numpy
1
6,080
61,919,647
Runtime error when optimising Theta in Logistic Regression using fmin_bfgs
<pre><code>#Get libraries import scipy.optimize as opt import numpy as np import pandas import matplotlib.pyplot as plt def plotData(): plt.scatter(X[y==1,0],X[y==1,1], marker='+', c='black',label="Admitted") plt.scatter(X[y==0,0],X[y==0,1], marker='.', c='y', label="Not Admitted") plt.xlabel("Exam 1 Sco...
<p>The first RuntimeWarning gave me the clue that I needed. My sigmoid function was returning 0 for very low values of z. To fix the problem I set the lower and upper bounds manually in the sigmoid function.</p>
python|python-3.x|numpy|scipy-optimize
0
6,081
61,975,181
Random generation of uniformly distributed points within given boundries in 3D space(cuboid) with Python
<p><img src="https://i.stack.imgur.com/nLgqQ.png" alt="3D space"></p> <p>I am trying to generate 2000 random points in 3D cuboid space within given boundaries in python. How would one go about it?</p>
<pre class="lang-py prettyprint-override"><code>import random xrange = (-1000.0, 1000.0) yrange = (-1000.0, 1000.0) zrange = (-1000.0, 1000.0) points = [] [ points.append((random.uniform(*xrange), random.uniform(*yrange), random.uniform(*zrange))) for i in range(2000) ] print(points) </code></pre>
python|numpy|random|neural-network|cluster-computing
2
6,082
61,935,672
Converting dictionary into two-column panda dataframe
<p>I have a dictionary in python called <code>word_counts</code> consisting of key words and values which represent the frequency in which they appear in a given text:</p> <pre><code>word_counts = {'the':2, 'cat':2, 'sat':1, 'with':1, 'other':1} </code></pre> <p>I now need to make this into a pandas DataFrame with tw...
<p>you can create a dataframe from a dictonary:</p> <pre><code>df=pd.DataFrame({"word":list(word_counts.keys()) , "count": list(word_counts.values())}) </code></pre>
python|pandas|dataframe|dictionary
0
6,083
57,785,386
How to convert a column form object to float?
<p>I have a csv whose columns include the results of some mathematic calculations. When I read the csv, the datatype of these columns is object. The content of the columns are numbers like this "9,180693865" (or 0)</p> <p>Now I tried the following to change the datatype:</p> <pre><code>df["column"].astype('float64') ...
<p>Replace the <code>,</code> by a <code>.</code> using <code>str.replace</code> to fix this:</p> <pre><code>df["column"] = Erzeugung.solar_prediction.str.replace(',', '.').astype("float64") </code></pre>
python|pandas
0
6,084
54,980,385
Tensorflow dataset generator inverted colors
<p>I have a problem with TF dataset generator. I do not why, but when I get picture from dataset by running it through session, it returns Tensors where colors are inverted. I tried to changed BGR to RGB, but this is not the problem. It is partially solved by inverting the image array (img = 1 - img ), but I would like...
<p>Ok so the solution was </p> <p>imgplot = plt.imshow(out/255)</p>
python|tensorflow|tensorflow-datasets
0
6,085
49,724,954
How are PyTorch's tensors implemented?
<p>I am building my own Tensor class in Rust, and I am trying to make it like PyTorch's implementation. </p> <p><em>What is the most efficient way to store tensors programmatically, but, specifically, in a strongly typed language like Rust?</em> <em>Are there any resources that provide good insights into how this is d...
<h2>Contiguous array</h2> <p>The commonly used way to store such data is in a single array that is laid out as a single, contiguous block within memory. More concretely, a 3x3x3 tensor would be stored simply as a single array of 27 values, one after the other. </p> <p>The only place where the dimensions are used is t...
python|python-3.x|rust|pytorch|tensor
6
6,086
49,673,059
How to control X's and Y's when interplolating with pandas
<p>I want to use spline interpolation so I can fill some nulls, but I can not find a way to specify X's and Y's for Pandas. It automatically select the index to be the X's and fill nulls for all columns that have nulls respectively. Any ideas of how to make it work? or do I need to use SciPy?</p> <p>I tried somthing l...
<p>Pandas interpolation doesn't allow you to simultaneously specify x, y, and metho. For greater control over interpolation, you might want to use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d" rel="nofollow noreferrer"><code>scipy.interp1d</cod...
python|python-2.7|pandas|scipy|interpolation
1
6,087
49,503,565
make a numpy array with shape and offset argument in another style
<p>I wanted to access my array both as a 3-element entity (3d position) and individual element (each of x,y,z coordinate). After some researching, I ended up doing the following.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arr = np.zeros(5, dtype={'pos': (('&lt;f8', (3,)), 0), ...
<p>In reference to the docs page, <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/arrays.dtypes.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.14.0/reference/arrays.dtypes.html</a></p> <p>you are using the fields dictionary form, with <code>(data-type, offset)</code> value</p> <pre><cod...
python|arrays|numpy
2
6,088
73,521,449
How do I adjust the dates of a column in pandas according to a threshhold?
<p>I have a data frame with a datetime column like so:</p> <pre><code> dates 0 2017-09-19 1 2017-08-28 2 2017-07-13 </code></pre> <p>I want to know if there is a way to adjust the dates with this condition:</p> <ol> <li>If the day of the date is before 15, then change the date to the end of last month.</li> <li>If the...
<p>Easy with <a href="https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.tseries.offsets.MonthEnd.html" rel="nofollow noreferrer"><code>MonthEnd</code></a></p> <p>Let's set up the data:</p> <pre><code>dates = pd.Series({0: '2017-09-19', 1: '2017-08-28', 2: '2017-07-13'}) dates = pd.to_datetime(dates) </code...
python|pandas|dataframe
2
6,089
73,184,848
Rearrange a 5D tensor in PyTorch
<p>I have a 5D tensor in the shape of <code>(N,C,T,H,W)</code>. I want to rearrange it using PyTorch to the form of <code>(N,T,HW,C)</code>. How can I do that?</p>
<p>Naturally you can reshape the last two dimensions of your tensor by flattening your tensor from <code>dim=-2</code>, this will produce a shape of <code>(N,C,T,HW)</code>:</p> <pre><code>&gt;&gt;&gt; x.flatten(-2) </code></pre> <p>Then you can permute the dimensions around:</p> <pre><code>&gt;&gt;&gt; x.flatten(-2).p...
python|pytorch
2
6,090
73,431,883
Expand selected keys in a json pandas column
<p>I have this sample dataset:</p> <pre class="lang-py prettyprint-override"><code>the_df = pd.DataFrame( {'id':['AM','AN','AP'], 'target':[130,60,180], 'moves':[[{'date':'2022-08-01','amount':285.0,'name':'Cookie'}, {'name':'Rush','amount':10,'date':'2022-08-02','type':'song'}], ...
<p>Here are the steps you could follow</p> <p>(1) define df</p> <pre><code>df = pd.DataFrame( {'id':['AM','AN','AP'], 'target':[130,60,180], 'moves':[[{'date':'2022-08-01','amount':285.0,'name':'Cookie'}, {'name':'Rush','amount':10,'date':'2022-08-02','type':'song'}], [{'amoun...
python|pandas
2
6,091
73,296,742
How can I use count list value in dataframe
<p>I have a dataframe looks like this</p> <pre><code>df = pd.DataFrame({'id': ['T01', 'T01', 'T01', 'T02', 'T02', 'T03', 'T03'], 'event_list': [(['a', 'b']), (['a', 'c']), (['a', 'b', 'c']), (['a']), ...
<p>Making use of pandas' newer functions we can combine <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer">explode</a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer">pd.NamedAgg</a> recreating yo...
python|pandas|list
2
6,092
67,544,547
Python: Pandas Dataframe MultiIndex select data based on Index values gives empty result
<p>I have a pandas dataframe that has multiple index (latitude, longitude, and time) with the data being windspeed. I want to select based on one latitude, longitude location. When I try this, it returns an empty result. What am I doing wrong here?</p> <p>Here is part of my original dataframe:</p> <p><a href="https://i...
<p>Actually you are facing this problem because the column <strong>'latitude','longitude'</strong> and <strong>'time'</strong> are of type string so to resolve it:</p> <pre><code>df=df.reset_index() </code></pre> <p>Now use <code>astype()</code> method and <code>to_datetime()</code> method:</p> <pre><code>df[['latitude...
python|pandas|dataframe|multi-index
1
6,093
60,162,118
How to get nth max correlation coefficient and its index by using numpy?
<p>I compute correlation coefficient like this (its just example):</p> <pre><code>a = np.array([[1, 2, 3], [4, 7, 9], [8, 7, 5]]) corr = np.corrcoef(a) </code></pre> <p>The result is a correlation matrix.</p> <p>The question is how to get 1st, 2nd (or nth) largest coefficient?</p> <p>And its index? like ...
<p>Let's say you have a NumPy array and you computed the correlation coefficient like this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.array([[1, 2, 3], [4, 7, 9], [8, 7, 5]]) corr = np.corrcoef(a) </code></pre> <p>Now flatten the array, take the unique coefficients and ...
python|numpy
2
6,094
60,140,342
Summing particular rows in a particular column
<p>I have following data where I want to add only "Total" column yearly(12 rows at once). How to do it with <code>pandas</code> ? <a href="https://i.stack.imgur.com/OtLB4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OtLB4.jpg" alt="enter image description here"></a></p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.year.html" rel="nofollow noreferrer"><code>Series.dt...
python|pandas|csv
2
6,095
60,169,065
my picture won't resize tf.image.resize_with_padding tensorflow
<p>my original image is 600*600 px I want to resize it to be 300*300 px</p> <p><strong>Resize code</strong></p> <pre><code>import tensorflow as tf import numpy as np from tensorflow.keras.preprocessing.image import array_to_img from tensorflow_core.python.keras.layers.image_preprocessing import ResizeMethod def res...
<p>Tensorflow operations are <strong>not in place</strong>. You need to assign the result of the resize operation as follows:</p> <pre><code>image = tf.image.resize_with_pad( image, h, w, method=ResizeMethod.BILINEAR ) </code></pre>
python|python-3.x|image|tensorflow|image-processing
2
6,096
60,281,248
How can I check what value is assigned to what label while using sklearns' LabelEncoder()?
<p>I am transforming categorical data to numeric values for machine learning purposes.</p> <p>To give an example, the buying price (= "buying" variable) of a car is categorized in: "vhigh, high, med, low". To transform it into numeric values, I used:</p> <pre><code>le = preprocessing.LabelEncoder() buying = le.fit_tr...
<p>You can create an extra column in your dataframe to map the values:</p> <pre><code>mapping_df = data[['buying']].copy() #Create an extra dataframe which will be used to address only the encoded values mapping_df['buying_encoded'] = le.fit_transform(data['buying'].values) #Using values is faster than using list </co...
python|pandas|machine-learning|scikit-learn|one-hot-encoding
3
6,097
60,111,700
How to BEST extract information from multiple dataframes based on a series of if\else conditions and matching values? (Guidance needed!))
<p>So I have three Dataframes, X, Y and Events. df_X has X Co-ordinates, df_Y has Y Co-ordinates and Events_df has a list of events that has happened (The Data is Basketball related). You'll see how they link together by looking below:</p> <pre><code>df_Event: Seconds Passed Event Type Player 1.0 ...
<p>Solution to the question needs a systematic approach which would affect significantly if understaning of problem changes. Since in the asked question, the output dataframe has excluded event type 'Touch' and has only compared Passes and Receiving; therefore, I have adopted the approach to reach at such output.</p> ...
python|pandas|dataframe|where-clause
2
6,098
65,085,586
Pandas code to get the count of each values
<p>Here I'm sharing a sample data(I'm dealing with Big Data), the &quot;counts&quot; value varies from 1 to 3000+,, sometimes more than that..</p> <p>Sample data looks like :</p> <pre><code> ID counts 41 44 17 16 19 52 6 17 30...
<p>Use <code>Counter</code> for get counts of values splitted by space in list comprehension:</p> <pre><code>from collections import Counter L = [{int(k): v for k, v in Counter(x.split()).items()} for x in df['ID']] df1 = pd.DataFrame(L, index=df.index).fillna(0).astype(int).sort_index(axis=1) df = df.join(df1) print ...
python|python-3.x|pandas|dataframe|count
1
6,099
65,366,859
Changing values of duplicates in pandas
<p>I have a dataframe of stock prices. There is possibility of duplicates and hence while performing merge functions data goes haywire. What i want is whenever there are duplicates in any column, i want to increment it with small amounts.</p> <p>Eg.Table</p> <pre><code>|Date| High| low| |:--|:---:|---:| |1-12-2020| 515...
<p>A solution is this. Your dataframe is ddf</p> <pre><code> Date High low 0 1-12-2020 515 505 1 2-12-2020 525 515 2 3-12-2020 515 510 3 4-12-2020 530 505 </code></pre> <p>and doing this</p> <pre><code>mask = ddf['High'].duplicated(keep=False) ddf.loc[mask, 'High'] += ddf.groupby('High').cumcou...
python|pandas
1