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
349,900
54,934,655
python aggregation of two time-series
<p>I have two pandas time-series dataframes and I want to aggregate the values against one time series based on the intervals of the other one. Let me show by example. The first time series is as follows:</p> <pre><code> date value 0 2016-03-21 10 1 2016-03-25 10 2 2016-04-10 10 3 2016-05-0...
<p>You can bin the data in df1 based on bins in df2 dates,</p> <pre><code>bins = pd.date_range(df2.date.min(), df2.date.max() + pd.DateOffset(10), freq = '10D') labels = df2.date df1.groupby(pd.cut(df1.date, bins = bins, right = False, labels = labels)).value.sum().reset_index() date value 0 2016-03-21 ...
python|pandas|time-series|aggregation
6
349,901
54,909,322
Mismatching Conda and Pycharm
<p>I'm new in python and I'm confused about mismatching Conda packages list and Pycharm. In a project I need to install pytorch. Installing with pycharm lead to some error and when I install it through conda, It does not appear in pycharm. Both list is the same env. </p> <p>Thanks in advance.</p> <p>pycharm list <a ...
<p>PyCharm shows you the list of installed packages with <code>pip</code>, while <code>conda list</code> shows both <code>pip</code> and <code>conda</code>. Meanwhile, you can switch between <code>pip</code> and <code>conda</code> with a dedicated button in PyCharm:</p> <p><a href="https://i.stack.imgur.com/1VDgg.png"...
python|pycharm|anaconda|pytorch
2
349,902
54,702,212
Keras: rescale=1./255 vs preprocessing_function=preprocess_input - which one to use?
<h2>Background</h2> <p>I find quite a lot of code examples where people are preprocessing their image-data with either using <code>rescale=1./255</code> or they are using they <code>preprocessing_function</code> setting it to the <code>preprocess_input</code> of the respective model they are using within the ImageData...
<p>I had similar questions, and after running the small experiments below, I think you need to always use <code>preprocess_input</code> when using pre trained models, and use rescale when training from scratch.</p> <p>Obviously when you directly used a pre trained model for inference, you have to use <code>preprocess_...
python|tensorflow|keras
11
349,903
54,861,056
Do all objects have a __qualname__ attribute?
<p>I was doing some introspection on pandas objects when I encountered an error for <code>pandas.core.indexing._iLocIndexer</code>.</p> <p>The <a href="https://docs.python.org/3/library/stdtypes.html#definition.__qualname__" rel="nofollow noreferrer">docs</a> say:</p> <blockquote> <p><code>definition.__qualname__</...
<p>According to <a href="https://www.python.org/dev/peps/pep-3155/" rel="nofollow noreferrer">PEP3155</a> <code>__qualname__</code> was introduced on <code>class</code> and <code>function</code> objects.</p> <p>Now, we need to remember that in Python <em>everything</em> is an object. Functions are objects. Classes are ...
python|pandas|introspection
1
349,904
54,980,992
How do I make sure my Keras/tensorflow code uses my MacBook Pro's AMD graphics card
<p>I am running some Keras/tensorflow code in python on my MacBook Pro with Radeon Pro 560X 4096 MB and Intel UHD Graphics 630 1536 MB. What do I have to do to use the graphics cards in running the neural network code?</p>
<p>If you are running Keras, then you can use PlaidML as a backend: <a href="https://github.com/plaidml/plaidml" rel="nofollow noreferrer">https://github.com/plaidml/plaidml</a></p> <p>Installation is as easy as:</p> <pre><code>virtualenv plaidml source plaidml/bin/activate pip install plaidml-keras plaidbench </code...
python|tensorflow|keras|neural-network|gpu
3
349,905
54,931,538
Join DataFrames by a matching key
<p>I'm trying to join two DataFrames that has a matching key. Currently, I've tried with all three possible methods: df.merge, df.join, df.concat but with no luck.</p> <pre><code>#DataFrame 1: # Timestamp PageId LoadDuration # 01/01/2019 1 10 # 01/01/2019 2 20 # 01/01/2019 3 30 #DataFrame 2: # T...
<p>Try </p> <pre><code> pd.merge(df1,df2 , on = 'PageId' , how = 'inner') </code></pre>
python|pandas|numpy
2
349,906
54,867,308
Image Recognition/Labeling using TensorFlow.js
<p>We are using TensorFlow.js to create and train a custom model. We use tf.browser.fromPixels() function to convert an image into tensor. We want to create a custom and train a custom model. In terms to achieve this we are created two different web pages (i.e: 1st page is for Create custom mode and train it with image...
<p>A saved model does not contain the label name. A saved model contains the topology of the model and the weights of the architecture. </p> <p>After loading a saved model, one can predict the confidence for each given class of the last layer. From that prediction, one can only tell if the 1st class is the most likely...
javascript|machine-learning|image-recognition|tensorflow.js
0
349,907
54,973,175
retrieving values in one row of dataframes based on value in other
<p>I have mutiple DataFrames, each containing a row called 'location' and another row called 'value' (both make up the index). for example, suppose i have the following 2:</p> <pre><code>df1 = pd.DataFrame(np.array([[-4,2,5],['nyc','sf','chi']]), columns=['col1','col2','col3'], index=['value','location']) df2 = pd.Da...
<p>I would recommend <code>set_index</code> and <code>concat</code>:</p> <pre><code>(pd.concat([df.T.set_index('location')['value'] for df in [df1, df2]], axis=1) .T .reset_index(drop=True)) location nyc sf chi 0 -4 2 5 1 5 0 -3 </code></pre>
python|pandas|dataframe
3
349,908
54,698,146
What's the difference between Numpy's Structured arrays vs xarray (xray)?
<p>What's the difference between <a href="https://docs.scipy.org/doc/numpy-1.16.1/user/basics.rec.html" rel="nofollow noreferrer">Numpy Structured Arrays named fields</a> vs <a href="http://xarray.pydata.org/en/stable/" rel="nofollow noreferrer">xarray</a> (xray) N-D labeled arrays ?</p>
<p>From <a href="https://numpy.org/doc/stable/user/basics.rec.html#:%7E:text=Structured%20datatypes%20are,behavior%20in%20comparison." rel="nofollow noreferrer">the numpy docs on structured arrays</a>:</p> <p>&quot;Structured datatypes [i.e. structured numpy arrays] are designed to be able to mimic ‘structs’ in the C l...
python|numpy|multidimensional-array|python-xarray
0
349,909
54,838,422
How to use np.arwhere with multiple conditions?
<p>I want to pick indices of 1,2,3,12 and 13 with np.argwhere or np.where.In both cases following code is not working. Is there any way to do this using these two commands or should I use it twice instead of using &amp; operator? </p> <pre><code>`a= np.array([1,2,3,4,10,12,13]) b = np.argwhere((a&lt;4) &amp; (a&gt;10)...
<pre><code>In [31]: a= np.array([1,2,3,4,10,12,13]) In [32]: a Out[32]: array([ 1, 2, 3, 4, 10, 12, 13]) </code></pre> <p>The 2 conditions individually:</p> <pre><code>In [33]: a&lt;4 ...
python|numpy|numpy-ndarray
6
349,910
54,714,665
Make every n-th slice of a 3-d numpy array consecutive
<h2>Statement</h2> <p>Let's say we have some 3-dimesional numpy array, <code>A</code>, which has shape <code>(X, Y, Z)</code>. I want to create a new array <code>B</code>, which will also have shape <code>(X, Y, Z)</code>.</p> <p>We desire that the first n slices (<code>:n</code>) of <code>B</code> along the zero-th ...
<p>I think this does what you want:</p> <pre><code>import numpy as np # Create array A with shape (15, 3, 3) a = np.array([i * np.eye(3) for i in range(1, 6)]) A = np.tile(a, (3, 1, 1)) B = np.swapaxes(A.reshape(3, 5, 3, 3), 0, 1) B = B.reshape(-1, 3, 3) print(B) # [[[1. 0. 0.] # [0. 1. 0.] # [0. 0. 1.]] # # [[...
python|arrays|python-3.x|numpy
1
349,911
54,914,218
How to convert string to datetime, ignoring time information?
<p>In Python3 and pandas I have a dataframe with a column of strings representing dates - "DataFim" column</p> <pre><code>df_lotacoes.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 52725 entries, 0 to 52724 Data columns (total 5 columns): DataFim 48854 non-null object DataInicio 5272...
<p>Extract date part using str.extract and convert to datetime,</p> <pre><code>df['DataFim'] = pd.to_datetime(df['DataFim'].str.extract('(.*)T')[0], format = '%Y-%m-%d') DataFim 0 2018-11-05 1 2008-08-28 2 2002-08-08 3 2007-03-14 4 2005-05-06 </code></pre> <p>Option 2: You can also use str.split</p> <...
python|pandas|datetime
3
349,912
54,811,221
Multiplying the matrix via its transpose using numpy
<p>I am trying to multiply X by its transpose:</p> <p><a href="https://i.stack.imgur.com/gp7Ou.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gp7Ou.png" alt="enter image description here"></a></p> <p>I am bit puzzled by the fact that <code>X</code> is an <code>np.array</code> of <code>list</code>'...
<p>o turn a list of list on python into array and to be able to use arithmetic calculations on it after you can use :</p> <pre><code>import numpy as np A = [[638, 331, 327, 30.3], [331,589,384,560], #0.049 [327,384,560,4.81], [3.03,0.049,4.81,1.46]] X = np.array([np.array(a) for a in A]) </code></pre> ...
python|numpy
1
349,913
54,794,867
How to feed LSTM when training data is in multiple csv files of time series of different length?
<p>I am running an LSTM to classify medical recordings for each patient. That's being said, for each patient (an observation) I have one CSV file. The whole dataset is multiple CSV files, each one of them is DataFrame of time series. <strong><em>This is not that obvious cuz there is one small difference between feeding...
<p>Since your data points have variable sequence lengths, you can't easily train your network all at once. Instead, you must train in mini batches of size 1 or fix your sequence length, although the latter probably doesn't make sense based on the data you're dealing with.</p> <p>Take a look at the Keras function <a hr...
python|tensorflow|keras|time-series|lstm
2
349,914
54,708,188
Appending a pandas dataframe with new data
<p>I'm trying to build a DataFrame of stock data, I can get all the data I need, but can only get 1000 data points at a time. So what I want to do is save the initial 1000 data points in a csv file, and then run my program again every now and again, and any new data, I want to append to the old DataFrame. So it needs t...
<p>I believe you need working with <code>DatetimeIndex</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>, not with <code>merge</code> by <code>date</code> column:</p> <pre><code>coins = ['ADABTC'] dfs = [] for coin in coins:...
pandas|dataframe|append
4
349,915
54,891,915
ValueError: could not broadcast input array from shape (3) into shape (2)
<pre><code> def_dictionary = defaultdict(lambda: np.array([np.array([-1, 1]), np.array([-1, 1])])) def_dictionary[tuple([3,5])][1] = np.concatenate((def_dictionary[tuple([3, 5])][1], np.array([6]))) </code></pre> <p>How should I append an integer to <code>def_dictionary[tuple([3,5])][1]</code> array? I tried np.appen...
<p>It's not possible to change shape of an element of an array. Hence I had to get rid of array of arrays. I workaround this by creating defaultdic with defaultdic in it:</p> <pre><code>def_dictionary = defaultdict(lambda: defaultdict(lambda: np.array([-1, 1]))) </code></pre>
python|numpy|numpy-ndarray|defaultdict
0
349,916
55,037,188
Trying to concat two dataframes on top of each other but having some troubles with index values and length mismatch
<p>I have two dataframes that I want to concatenate on top of each other. The DFs look like:</p> <p>DF1 (3 columns, many rows in multiples of 3 duplicates)</p> <pre><code> col1 col2 col3 0 A1 A2 A3 0 A1 A2 A3 0 A1 A2 A3 1 A4 A5 A6 1 A4 A5 A6 1 A4 A5 A...
<p>Idea is create same columns values in each DataFrame:</p> <pre><code>df1 = DF1.reset_index(drop=True).T df2 = DF2.copy() df2.columns = np.arange(len(df2.columns)) df = pd.concat([df1, df2], ignore_index=True) print (df) 0 1 2 3 4 5 0 A1 A1 A1 A4 A4 A4 1 A2 A2 A2 A5 A5 A5 2 A3 A3 ...
python|pandas
2
349,917
54,977,130
Convert DataFrame from numeric to string with mapping
<p>Convert Dataframe from string to numeric (as IDs) with mapping so that I can map numeric values back to string after my Machine Learning job (which requires numeric values for training)</p> <p>I have 2 columns in my data frame:-</p> <ol> <li><code>Repository Name</code>(String that is needed to be converted)</li> ...
<pre><code>def get_metadata(df, key, val): #create a new column with index df['index'] = df.index if key == "Repository Name": return {str(row[key]): row[val] for _, row in df.iterrows()} else: return {row[key]: row[val] for _, row in df.iterrows()} emb2idx = get_metadata(dataframe, "i...
python|pandas|dataframe|lambda
0
349,918
54,864,607
Using functions on every row to return a new data frame
<p>I have a big data frame with over 1000 rows. I am able to find the most similar rows to a certain index using cosine similarity and weight them accordingly. So my similar_rows data frame looks like this...</p> <p>eg. similar_rows(60):</p> <pre><code> A B C Weight 0 5 6 7 0.2 1 8 3 2 0.3 2 ...
<p>Look at the <code>apply</code> function from <code>pandas.DataFrame</code> : </p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html#pandas-dataframe-apply" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.htm...
python|pandas|function
2
349,919
55,011,881
Pivoting a One-Hot-Encode Dataframe
<p>I have a pandas dataframe that looks like this:</p> <pre><code>genres.head() </code></pre> <pre> Drama Comedy Action Crime Romance Thriller Adventure Horror Mystery Fantasy ... History Music War Documentary Sport Musical Western Film-Noir News number_of_genres tconst ...
<p>Maybe I'm missing something but doesn't this work for you?</p> <pre><code>agg = df.groupby('number_of_genres').agg('sum').T agg['totals'] = agg.sum(axis=1) </code></pre> <p>Edit: Solution via <code>pivot_table</code></p> <pre><code>agg = df.pivot_table(columns='number_of_genres', aggfunc='sum') agg['total'] = agg...
python|python-3.x|pandas|pivot|pivot-table
1
349,920
54,736,489
Matplotlib histogram does not show details of distribution
<p>I have some data and I would like to look at its distribution. But I don't know why when I use this code, the histogram does not really show what is going on within the data and it shows a very general picture. I want to have a more granular histogram.</p> <pre><code>data['feature'].plot(kind='hist') </code></pre> ...
<p><code>data['feature'].plot(kind='hist', bins=100)</code></p> <p>This would group histogram into 100 bins. If you need even higher granularity you can naturally use higher number.</p> <hr> <p>Your data seems very left-skewed. You can force 100 bins with equal number of member, using <code>pd.qcut</code> as <code>b...
python|pandas|dataframe|matplotlib|histogram
1
349,921
55,021,503
Adding multiple dictionaries into a single Dataframe pandas
<p>I have a set of python dictionaries that I have obtained by means of a for loop. I am trying to have these added to Pandas Dataframe. </p> <p>Output for a variable called <code>output</code></p> <pre><code>{'name':'Kevin','age':21} {'name':'Steve','age':31} {'name':'Mark','age':11} </code></pre> <p>I am trying to...
<p>You can append each dictionary to list and last call <code>DataFrame</code> constructor:</p> <pre><code>out = [] for file in allFiles: tree = ET.parse(file) root = tree.getroot() result = f(root, result) out.append(result) df = pd.DataFrame(out) </code></pre>
pandas
3
349,922
54,777,026
A way to map one array onto another in numpy?
<p>I have a 2-d array and a 1-d array, shown below. What I'd like to do is to fill the blank spaces in the 2-d array with the product of the 2-d and 1-d array - probably simplest to demonstrate below:</p> <pre><code>all_holdings = np.array([[1, 0, 0, 2, 0], [2, 0, 0, 1, 0]]).astype('float64') ...
<pre><code>In [76]: all_holdings = np.array([[1, 0, 0, 2, 0], ...: [2, 0, 0, 1, 0]]).astype('float64') ...: sub_holdings = np.array([0.2, 0.3, 0.5]) </code></pre> <p>With one level of iteration:</p> <pre><code>In [77]: idx = np.where(all_holdings[0,:]=...
python|numpy|array-broadcasting
1
349,923
55,098,679
installing numpy Raspberry Pi
<p>I have this problem when i install numpy on Raspberry Pi ( Python 3.6.6 without anaconda):</p> <pre class="lang-none prettyprint-override"><code>pi@raspberrypi:~/Desktop$ sudo pip3 install numpy pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting nump...
<p>From the previous answer, after following sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev, I got six errors saying E: Unable to locate package libreadline-gplv2-dev E: Unable to locate package libncursesw5-dev E: Unable to locate package l...
python|numpy|pip
0
349,924
49,551,271
Efficient way to transform array into encoding for ordinal regression
<p>I have this array</p> <pre><code>import numpy as np array = np.array([2, 3, 4]) </code></pre> <p>And I would like to map that to</p> <pre><code>[array([ 1., 1., 0., 0., 0.]), array([ 1., 1., 1., 0., 0.]), array([ 1., 1., 1., 1., 0.])] </code></pre> <p>This is the best solution I've found so far</p> ...
<p>Leverage <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> with greater-than <code>outer-comparison</code> of input array against the range of <code>array_len</code> values -</p> <pre><code>In [14]: array Out[14]: array([2, 3, 4])...
python|arrays|numpy
5
349,925
49,465,527
How to specify multiple elements using pandas.Series.isin
<p>I have a working code that I am trying to reduce</p> <pre><code>df['Criteria'] = (df['Alpha'] == 3) | (df['Alpha'] == 4) </code></pre> <p>I tried with error the below (TypeError: isin() takes 2 positional arguments but 3 were given)</p> <pre><code>df['Criteria'] = df['Alpha'].isin(3,4) </code></pre> <p>I took r...
<p>You are close, need <code>list</code>,<code>tuple</code>, <code>array</code> or <code>set</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow noreferrer"><code>isin</code></a>:</p> <blockquote> <p><strong>Series.isin(values)</strong></p> <p><strong>values</...
python|pandas|dataframe
2
349,926
49,407,565
Pandas sorting based on two paired columns
<p>I have two columns, "before" and "after". We'll just call them <code>Bf</code> and <code>Af</code> here. Based on many other attached columns, they have been ranked as follows:</p> <pre><code>Bf Af 3 5 0 2 1 4 5 3 2 0 4 1 </code></pre> <p>Now, the way they need to be sorted is</p> <pre><code>Bf Af 0...
<p>IIUC</p> <pre><code>df.reindex(pd.DataFrame(np.sort(df.values,1)).sort_values([0,1]).index) Out[444]: Bf Af 1 0 2 4 2 0 2 1 4 5 4 1 0 3 5 3 5 3 </code></pre>
python|pandas|sorting
2
349,927
49,661,049
Python PANDAS: Multi-Column Pivot and Level Swapping
<p>I have an initial dataframe with the following format:</p> <pre><code>store_id,product,sale_ind,total_sold,percentage_sold 1,thing1,sale,30,46.2 1,thing2,no_sale,20,30.7 1,thing3,sale,15,23.1 2,thing4,sale,10,16.7 2,thing3,sale,20,33.3 2,thing2,sale,30,50.0 3,thing3,no_sale,20,50.0 3,thing2,sale,15,37.5 3,thing1,no...
<p>You need <code>pivot_table</code> for multi-columns pivot:</p> <pre><code>df.pivot_table( index=['store_id'], columns=['product', 'sale_ind'], values=['total_sold', 'percentage_sold'] ) </code></pre> <p><a href="https://i.stack.imgur.com/oIqH6.png" rel="nofollow noreferrer"><img src="https://i.stack....
python|pandas|numpy|pandas-groupby
2
349,928
49,766,456
How can I specify row order when I use dask.dataframe
<p>I have two dataframe with same shape.<br> I tried to convert to dask dataframe specifying same <code>n_partition=50</code>.<br> However, how each dataframe split into partition seems different as shown below image.<br> Does anyone know how I can specify how dataframe should be separated? </p> <p><a href="https://i...
<p>Here is a guess: the index values appear to be sorted, but one would be numerical and one lexicographical; i.e., I suspect that your dataframe <code>mrt_dask</code> has an index containing strings, not numbers. If this is so, then calling <code>astype</code> before passing it to dask should solve your issue, or perh...
python|pandas|dask
0
349,929
49,540,279
Having trouble moving a row to the top of the dataframe
<p>I've got 280 CSV files and for each of them I need to create a row that contains the sum of all its numeric values.This is simple but my problem is that the sumation needs to be in the first row. </p> <p>I've been using this code to create the summation row in the file</p> <pre><code>df = pd.read_csv(file_path,sep...
<p>Consider the sample data frame <code>df</code></p> <pre><code>df = pd.DataFrame(np. arange(16).reshape(4, 4), columns=list('ABCD')) df A B C D 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 3 12 13 14 15 </code></pre> <hr> <h3>Use combination of <code>iloc</code> and <code>argsort</code></h3...
python|pandas|numpy|dataframe
1
349,930
49,681,623
Create new variable for grouped data using python
<p>I have a data frame like this:</p> <pre><code>d = {'name': ['john', 'john', 'john', 'Tim', 'Tim', 'Tim','Bob', 'Bob'], 'Prod': ['101', '102', '101', '501', '505', '301', '302', '302'],'Qty': ['5', '4', '1', '3', '5', '4', '1', '3']} df = pandas.DataFrame(data= d) </code></pre> <p><a href="https://i.stack.imgur.com...
<p>You can using <code>cumcount</code> </p> <pre><code>s=df.groupby(['Prod','name']).cumcount().add(1) df['counter']=s.mask(s.gt(1),0) df Out[1417]: Prod Qty name counter 0 101 5 john 1 1 102 4 john 1 2 101 1 john 0 3 501 3 Tim 1 4 505 5 Tim 1 5 301 4 ...
python-3.x|pandas
3
349,931
49,413,005
Replace multiple substrings in a Pandas series with a value
<p>All,</p> <p>To replace one string in one particular column I have done this and it worked fine:</p> <pre><code>dataUS['sec_type'].str.strip().str.replace(&quot;LOCAL&quot;,&quot;CORP&quot;) </code></pre> <p>I would like now to replace multiple strings with one string say replace <code>[&quot;LOCAL&quot;, &quot;FOREI...
<p>You can perform this task by forming a |-separated string. This works because <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="noreferrer"><code>pd.Series.str.replace</code></a> accepts regex:</p> <blockquote> <p>Replace occurrences of pattern/regex in the Serie...
python|string|pandas|python-2.7|series
28
349,932
49,541,718
Tick labels only displayed in one subplot
<p>Need to display custom shared x-axis tick labels on both subplots, using two datasets with different dates.</p> <pre><code>from pandas import DataFrame, date_range, Timedelta import numpy as np from matplotlib import pyplot as plt import matplotlib.dates as mdates #Dataset 1 rng1 = date_range(start='01-01-2015', p...
<p>This seemed to work for me, just following the <a href="https://matplotlib.org/examples/pylab_examples/shared_axis_demo.html" rel="nofollow noreferrer">shared_axis_demo</a></p> <pre><code>fig = plt.figure() ax1 = plt.subplot(211) _ = plt.plot(y1) plt.setp(ax1.get_xticklabels(), visible=True) ax2 = plt.subplot(212...
python-3.x|pandas|matplotlib
1
349,933
49,610,295
Python: fill column based on first charakter of another columns content
<p>I have a pandas dataframe looking like this:</p> <pre><code>+-----+------+ | No | type | +-----+------+ | 123 | C01 | | 123 | C02 | | 123 | T01 | | 345 | C01 | | 345 | H12 | | 345 | H22 | +-----+------+ </code></pre> <p>and a numpy array like this:</p> <pre><code>arr = [Car, Tree, House] </code></pre> <p>...
<p>Full example:</p> <pre><code>import pandas as pd data = '''\ No type 123 C01 123 C02 123 T01 345 C01 345 H12 345 H22''' df = pd.read_csv(pd.compat.StringIO(data),sep='\s+') arr = ['Car', 'Tree', 'House'] d = {x[0]:x for x in arr} # Create a map df['category'] = df['type'].str[0].map(d) # App...
python|pandas|numpy|dataframe
3
349,934
49,759,856
How to display the values count on the bar chart
<p>Can I please get some help on how I can include the counts on my bar chart. Thank you.</p> <pre><code>sns.countplot(data['target']) plt.plot(0, label ="0 = No") plt.plot(1, label ="1 = Yes") plt.xlabel("Target") plt.ylabel("count") plt.title("Target vrs count") plt.legend() plt.show() </code></pre> <p><a href="htt...
<p>You can use <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.text.html" rel="noreferrer"><code>matplotlib.text</code></a>:</p> <pre><code>from matplotlib import pyplot as plt data = pd.DataFrame({'target': [1, 1, 1, 0, 0]}) sns.countplot(data.target); for v in [0, 1]: plt.text(v, (data.target == v)...
pandas|matplotlib|scikit-learn
5
349,935
49,702,465
Pandas reindex turning all non-index columns to NaN
<p>I have a csv file of weather station data which has non continuous timestamps:</p> <pre><code>logstamp temp rh snow wind gust wind_dir 2018-01-26 21:00:00 -10.120 63.93 207.1 4.018 9.806 173.900 2018-01-26 22:00:00 -9.750 58.54...
<p>I think you need to call <a href="https://pandas.pydata.org/pandas-docs/stable/missing_data.html#missing-data-interpolate" rel="nofollow noreferrer"><code>interpolate</code></a>. For your example dataframe:</p> <pre><code># This is the same as what you had index = pd.date_range(ts1.index.min(),ts1.index.max(), freq...
python|python-3.x|pandas
1
349,936
49,593,797
Using sklearn's LabelEncoder on a column of a dataframe
<p>If I have a dataframe, say df, and if </p> <pre><code>df["levels"] = pd.Series(["low", "low", "med", "low", "med", "high"]) </code></pre> <p>Is there a way to change this to be:</p> <pre><code>df["levels"] = pd.Series([0,0,1,0,1,2]) </code></pre> <p>I've tried using preprocessing.LabelEncoder() to transform this...
<p>I'm not sure how you used <code>sklearn</code> to encode your column of strings, since that was not included in the original post. However, you can used the <code>LabelEncoder()</code> following the steps below</p> <pre><code>from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit(df.levels.uniqu...
python|pandas|scikit-learn|data-mining
1
349,937
49,652,693
how to read text from excel file in python pandas?
<p>I am working on a excel file with large text data. 2 columns have lot of text data. Like descriptions, job duties. </p> <p>When i import my file in python df=pd.read_excel("form1.xlsx"). It shows the columns with text data as NaN. </p> <p>How do I import all the text in the columns ? I want to do analysis on job t...
<p>Try converting the file from .xlsx to .CSV I had the same problem with text columns so i tried converting to CSV (Comma Delimited) and it worked. Not very helpful, but worth a try.</p>
excel|python-3.x|pandas|import
1
349,938
49,700,913
Error when using pd.to_datetime
<p>So, i'm trying to convert a unix column of dates to a more legible time expression. In order to achieve that i use the command </p> <pre><code>`df1["Date"]=pd.to_datetime(df1["Date"],origin='unix')` </code></pre> <p>how ever it returns the dates with the following structure.</p> <pre><code>1970-01-01 00:00:01.521...
<p>Use the <code>unit</code> argument<br> <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer">Documentation</a></p> <pre><code>ud = '1521673397;1521673200;1521672938'.split(';') pd.to_datetime(ud, unit='s') DatetimeIndex(['2018-03-21 23:03:17', '2018-03-2...
python|pandas
2
349,939
49,565,780
Tensorflow session in a class in python?
<p>I want to use tensorflow gradients for a computation of other quantities later on. I need to numerically compute the objective function and gradients as functions in a class (This class then is used in the remaining suite). However, I am getting error for the below code:</p> <pre><code>import tensorflow as tf class...
<p>Basically, 'self' tells which variables and methods belongs to a class. So you have to tell that (x, func, diff_func and sess) belong to the MyClass. So modify the code as below:</p> <pre><code>import tensorflow as tf class MyClass: def __init__(self): self.x = tf.Variable(tf.zeros(2)) self.fu...
python|class|session|tensorflow
5
349,940
49,394,188
Parameters for fitted distribution
<p>When searching for the best-fit distribution for my dataset, the result was the Exponentially Modified Normal distribution with the following parameters: </p> <pre><code>K=10.84, loc=154.35, scale=73.82 </code></pre> <p>Scipy gives us a way to analyze the mean of the distribution by:</p> <pre><code> fitted_mean...
<p>For the exponentially modified normal distribution, the location parameter is <em>not</em> the same as the mean. This is true for many distributions.</p> <p>Take a look at the <a href="https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution" rel="nofollow noreferrer">wikipedia page for the expon...
python|numpy|scipy|statistics|pymc3
3
349,941
49,389,167
Series indicating third weekday in a month
<p>I would like to create a pandas Series that indicates whether a certain date - which is supposed to be the index of the Series - is a third friday in a month.</p> <p>My idea is to create the Series first with zeroes as values and then changing those zeroes to ones where the index is a third friday in a month. This ...
<p>Use non loop faster solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.weekday.html" rel="nofollow noreferrer"><code>weekday</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.day.html" rel="nofollow noreferrer"><code>day<...
python-3.x|pandas|numpy
1
349,942
49,384,682
How to iterate 1d NumPy array with index and value
<p>For python <code>dict</code>, I could use <code>iteritems()</code> to loop through key and value at the same time. But I cannot find such functionality for NumPy array. I have to manually track <code>idx</code> like this:</p> <pre><code>idx = 0 for j in theta: some_function(idx,j,theta) idx += 1 </code></pre...
<p>There are a few alternatives. The below assumes you are iterating over a 1d NumPy array.</p> <h3>Iterate with <a href="https://docs.python.org/3/library/functions.html#func-range" rel="noreferrer"><code>range</code></a></h3> <pre><code>for j in range(theta.shape[0]): # or range(len(theta)) some_function(j, the...
python|arrays|numpy|indexing|iterator
53
349,943
49,501,509
How to read data from excel from a particular column in python
<p>I have an excel sheet and I am reading the excel sheet using pandas in python.</p> <p>Now I want to read the excel file based on a column, if the column has some value then do not read that row, if the column is empty than read that and store the values in a list.</p> <p>Here is a screenshot</p> <p><a href="https...
<p>This is possible for csv files. There you could do</p> <pre><code>iter_csv = pandas.read_csv('file.csv', iterator=True, chunksize=100000) df = pd.concat([chunk[chunk['UniqueIdentifier'] == 'True'] for chunk in iter_csv]) </code></pre> <p>But <code>pd.read_excel</code> does not offer to return an iterator object, m...
python|excel|pandas
0
349,944
49,711,567
Pandas Categorical masking
<p>I have what I believe is a simple question but I can't find what I'm looking for in the docs.</p> <p>I have a dataframe with a <code>Categorical</code> column called <code>mycol</code> with categories <code>a</code> and <code>b</code> and would like to be mask a subset of the dataframe as follows:</p> <p><code>df...
<pre><code>df_a = df[df["mycol"]=='a'] </code></pre> <p>I believe this should work, unless by 'mask' you mean you want to actually zero out the values that don't have a</p>
python|pandas|numpy|dataframe
1
349,945
49,385,147
How to stop variables from being updated?
<p>After training a neural network in Tensorflow, how do you stop it from updating weights and biases to test their current values? From what I know, you can inspect them with <code>inspect_checkpoint.print_tensors_in_checkpoint_file</code>, but what it gives you as an output is nothing to calculate with. I already tri...
<p>An update operation (e.g. the call to <code>optimize</code>) is done only if you run the corresponding operation. If you want to have access to the value of a variable without updating it, don't run the update operation (for example the <code>train_op</code> or a <code>tf.assign</code>), and only evaluate the variab...
python|tensorflow|machine-learning|neural-network
1
349,946
49,602,222
Efficiently adding rows to a dataframe
<p>I have a dataset containing historical pricing data for certain number of client IDs. Essentially, it is a spreadsheet with two columns as primary keys (id, p_date): <a href="https://i.stack.imgur.com/2DzqC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2DzqC.png" alt="enter image description her...
<p>Luckily this can be done very simply:</p> <pre><code>df = df.pivot(index='id', columns='p_date') </code></pre> <p>This will reshape the df using hierarchical indexing for the columns. To flatten the hierarchy levels into just one, you can use the solution found <a href="https://stackoverflow.com/questions/14507794...
python-3.x|performance|pandas|dataframe
1
349,947
49,418,248
Plot the x-axis as a date
<p>I am trying to perform some analysis on data. I got csv file and I convert it into pandas dataframe. the data looks like this. Its has several columns, but I am trying to draw x-axis as date column. . </p> <p>the pandas dataframe looks like this </p> <pre><code>print (df.head(10) cus-id date valu...
<h3>Set the index as a <code>datetime dtype</code></h3> <p>If you set the index to the datetime series by converting the dates with <code>pd.to_datetime(...)</code>, matplotlib will handle the x axis for you.</p> <p>Here is a minimal example of how you might deal with this visualization.</p> <p>Plot directly with <code...
python|pandas|numpy|matplotlib
8
349,948
49,373,363
Python/Pandas - df.duplicated() MemoryError: cannot allocate memory for array
<p>I am getting a <code>MemoryError: cannot allocate memory for array</code> when using <code>df.duplicated()</code> to check for duplicates in a data frame in Python 3.6.4. </p> <p>The df has about 150,000 rows and 208 columns and there are no issues with loading the data into a df (using chunks per below).</p> <pre...
<p>The issue here was use of Python 32-bit instead of 64-bit. Thanks to abrnert for helping resolve this.</p>
python|python-3.x|pandas|memory
0
349,949
27,996,070
Generate condition for selecting rows in pandas.DataFrame
<p>For the dataframe df, I am selecting the rows that have True values either in column 'a' or 'b'.</p> <pre><code>&gt;&gt;&gt; df Out[127]: a b 0 False False 1 True True 2 True False &gt;&gt;&gt; con = (df['a'] == True) | (df['b'] == True) &gt;&gt;&gt; con Out[129]: 0 False 1 True 2 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow"><code>DataFrame.any</code></a>:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.random.choice([True]+[False]*5, size=(6,5)), columns=list("abcde")) &gt;&gt;&gt; df a b c d ...
python|python-2.7|pandas
3
349,950
28,336,882
How do I take a column of pandas data based on a scalar condition AND a column comparison?
<p>Here's a starting DataFrame:</p> <pre><code>ipdb&gt; df[["line_amount","modifiedAmount"]] line_amount modifiedAmount 0 30.00 1 2.88 2.88 2 199.20 199.2 3 -105.00 -104 4 150.00 150 5 75.00 6 -450.00 ...
<p>you can use <code>apply</code> column-wise on the whole dataframe.</p> <pre><code>import pandas as pd import numpy as np </code></pre> <p>Create some dummy data and put it in a dataframe. I used np.nan instead of "".</p> <pre><code>df =pd.DataFrame( { 'lineAmount':[30.00,2.88,199.20,-105.00,150.00,75.00,-450.00,1...
python|pandas
0
349,951
27,934,169
Lua: Dimensions of a table
<p>This seems like a really easy, "google it for me" kind of question but I can't seem to get an answer to it. How do I find the dimensions of a table in Lua using a command similar to Numpy's <code>.shape</code> method? E.g. <code>blah = '2 x 3 table'; blah.lua_equivalent_of_shape = {2,3}</code></p>
<p>Tables in Lua are sets of key-value pairs and do not have dimensions.</p> <p>You can implement 2d-arrays with Lua tables. In this case, the dimension is given by <code>#t x #t[1]</code>, as in the example below:</p> <pre><code>t={ {11,12,13}, {21,22,23}, } print(#t,#t[1]) </code></pre>
numpy|lua|lua-table
2
349,952
28,190,383
Rolling a function on a data frame
<p>I have the following data frame <code>C</code>.</p> <pre><code>&gt;&gt;&gt; C a b c 2011-01-01 0 0 NaN 2011-01-02 41 12 NaN 2011-01-03 82 24 NaN 2011-01-04 123 36 NaN 2011-01-05 164 48 NaN 2011-01-06 205 60 2 2011-01-07 246 72 4 2011-01-08 287 84 6 2011-01-09 3...
<p>You could use <code>pd.rolling_apply</code>:</p> <pre><code>import numpy as np import pandas as pd df = pd.read_table('data', sep='\s+') def foo(x, df): window = df.iloc[x] # print(window) c = df.ix[int(x[-1]), 'c'] dvals = window['a'] + window['b']*c return bar(dvals) def bar(dvals): # pr...
python|pandas|dataframe|apply
8
349,953
27,929,780
How to increase pixel math speed using NumPy
<p>I'm looking for help on how to increase the speed of this calculation. What I'm trying to do is access each pixel and do some math on it, then create a new image with the new pixel calculations. I'm running this through a few thousands of small images which takes 1hr+. Any help would be appreciated, thanks.</p> <p...
<p>Remove the double <code>for-loop</code>. The key to speed with NumPy is to operate on the whole array at once:</p> <pre><code>image = cv2.imread('image.png') height, width, depth = image.shape image = image.astype('float') B, G, R = image[:, :, 0], image[:, :, 1], image[:, :, 2] num = R - B den = R + B image =...
python|performance|opencv|numpy
4
349,954
28,102,834
Separate Day and Time (h)
<p>I'm reading from a csv where a column contains both time and date. I'm looking to separarte time (hour) from the day but have not been able to. This is my code</p> <pre><code>dat = pd.read_csv('30day.csv') time = dat['Event_Time'] date_time=pd.to_datetime(time) </code></pre> <p>Which produces</p> <pre><code>0 ...
<p>try this :</p> <pre><code>date = date_time.apply(lambda x: x.date()) print date 0 2014-12-23 1 2014-12-23 2 2014-12-23 3 2014-12-23 4 2014-12-23 hours = date_time.apply(lambda x: x.hour) print hours 0 6 1 6 2 6 3 6 4 6 </code></pre>
date|time|pandas|ipython-notebook
1
349,955
28,132,147
Can numpy einsum() perform a cross-product between segments of a trajectory
<p>I perform the cross product of contiguous segments of a trajectory (xy coordinates) using the following script:</p> <pre><code>In [129]: def func1(xy, s): size = xy.shape[0]-2*s out = np.zeros(size) for i in range(size): p1, p2 = xy[i], xy[i+s] #segment 1 p3, p4 = xy[i+s], xy[i+2*s] ...
<p><code>einsum</code> computes sums of products only, but you could shoehorn the cross-product into a sum of products by reversing the columns of <code>tmp2</code> and changing the sign of the first column:</p> <pre><code>def func3(xy, s): size = xy.shape[0]-2*s tmp1 = xy[0:size] - xy[s:size+s] tmp2 = xy[...
python|numpy
1
349,956
27,974,746
Python 2.7: looping over 1D fibers in a multidimensional Numpy array
<p>I am looking for a way to loop over <code>1D</code> fibers (row, column, and multi-dimensional equivalents) along any dimension in a 3+-dimensional array. </p> <p>In a <code>2D</code> array this is fairly trivial since the fibers are rows and columns, so just saying <code>for row in A</code> gets the job done. But ...
<p>I think you might be looking for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html" rel="nofollow"><code>numpy.apply_along_axis</code></a></p> <pre><code>In [10]: def my_func(x): ...: return x**2 + x In [11]: np.apply_along_axis(my_func, 2, A) Out[11]: array([[[ 0, ...
arrays|python-2.7|numpy|multidimensional-array|iteration
2
349,957
73,324,711
Change string index to datetime using chained function
<p>For the following dataframe:</p> <pre><code>import pandas as pd import datetime import io data = &quot;&quot;&quot;value &quot;2015-09-25 00:46&quot; 71.925000 &quot;2015-09-25 00:47&quot; 71.625000 &quot;2015-09-25 00:48&quot; 71.333333 &quot;2015-09-25 00:49&quot; 64.571429 &quot;2015-09-25 ...
<p>Worked this out after posting. I used <code>set_index</code></p> <pre><code>def tweak_frame(_df): return (df.assign(new_col=1) .set_index(pd.to_datetime(_df.index))) tweak_frame(df).index </code></pre> <p>Returns:</p> <pre><code>DatetimeIndex(['2015-09-25 00:46:00', '2015-09-25 00:47:00', '2015-...
python|pandas
0
349,958
73,240,435
Python pandas create a new row by combining a variable and a list of variables for each row and appending
<p>I have a list of data frames that look like this called <code>date_group</code>. I have 117 such frames, one for each day.</p> <p><code>date_group[0]</code> looks like this.</p> <pre><code> x1 x2 x3 prob x5 date 0 1.0 1.0 20.0 0.05 90.0 2021-12-23 1 1.0 2.0 20.0 0.60 90.0 ...
<p>here is one way to do it</p> <p>concatenate all the DFs together, and then use pivot to create the desired table. here, i named the first dataframe as DF, second as DF2 and combine these into df3</p> <pre><code># create a list of all the DFs df_list = [df.reset_index(), df2.reset_index() ] df3...
python|arrays|pandas|dataframe|concatenation
1
349,959
73,297,985
How can I create a for loop that filters a master dataframe for a specific state in a list?
<p>I have a sample dataframe of sales:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>product_category</th> <th>state</th> <th>total_revenue</th> </tr> </thead> <tbody> <tr> <td>macbook</td> <td>New York</td> <td>2799</td> </tr> <tr> <td>macbook</td> <td>California</td> <td>3200</td> </tr>...
<p>This will give you a list of dataframes containing only a unique state:</p> <pre><code>df_list = [df[df.state == unique_state] for unique_state in df.state.unique()] </code></pre>
python|pandas|for-loop
0
349,960
73,287,949
Unable to get the groupby column of same numeric column
<p>Below is the dataframe</p> <pre><code>df = pd.DataFrame({'Cust_Pincode':[487551,487551,639207,452001,484661,484661], 'REGIONAL_GROUPING':['WEST I','WEST II','TN II','WEST I','WEST I','WEST II'], 'C_LATITUDE':[22.89831,23.74881,10.72208,22.69875,23.88280,23.88280], ...
<p>You can try this solution</p> <pre><code>df = df.groupby(['Cust_Pincode']).filter(lambda x: len(x) &gt; 1) print(df.groupby(['Cust_Pincode', 'REGIONAL_GROUPING']).first()) </code></pre>
python|python-3.x|pandas|dataframe|group-by
1
349,961
73,332,654
Python Map function deletes all data in column
<p>I have a Pandas DataFrame with several columns. One of these ('Code') is object-type but has missing data (NaN). Other data can be numbers or letters. For the missing data, I want to do a map / set_index function in order to fill in the data. Here is my code:</p> <pre><code>for row in df['Code']: if pd.isnull(ro...
<p>Instead all your code loop use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a>:</p> <pre><code>df['Code']= df['Code'].fillna(df['account'].map(df_2.set_index('AccountID')['AccountCode'])) </code></pre>
python|pandas|dataframe|map-function
3
349,962
73,483,426
Filter by string column as a substring of another string
<p>I am trying to filter a dataframe by a string column. I would like the filter to return all rows where this string column is a substring of another string. Any searching I do for this problem leads to results about the converse - filtering a dataframe where a string columns contains a substring.</p> <p>In other word...
<pre><code>df[df[&quot;string_column&quot;].apply(lambda x: x in &quot;some_string&quot;)] </code></pre>
python|pandas
1
349,963
73,346,173
Pandas Dataframes Remove rows by unique count of values
<p>I want to remove rows where specific columns unique value counts is less than some value.</p> <p>Dataframe looks like that:</p> <pre><code> class reason bank_fees cash_advance community food_and_drink ... recreation service shops tax transfer travel 0 0 a...
<p>You can try to get the index of value counts where value is below <code>5</code> and use <code>isin</code> to filter out these value</p> <pre class="lang-py prettyprint-override"><code>out = df[~df['reason'].isin(df['reason'].value_counts().lt(5).pipe(lambda s: s[s].index))] </code></pre> <p>To elaborate each step u...
python|pandas|dataframe
2
349,964
73,502,171
transform event based data into time series data with pandas using groupby and reindex
<p>We want to transform event-based data into multiple time series.</p> <p>As an example we use pandas to plot some graphics of the changes in salary per employee in a company over time. An event of a change in salary is a entry in a table with a date, a name and the new salary.</p> <pre><code> employee sala...
<p>This should work. If your index is already a datetime index, then you do not need the <code>.rename(pd.to_datetime)</code> part</p> <pre><code>(df.rename(pd.to_datetime) .set_index('employee',append = True) .unstack() .asfreq('D') .ffill() .fillna(0)) </code></pre> <p>Output:</p> <pre><code> salary ...
python|pandas|dataframe|group-by
2
349,965
73,481,505
Replace the value in arrray by another aarray
<p>I have a mask array: <code>[0,0,0,0,1,1,0,0,1,1,0,1,0]</code>. <br /> And a values array: <code>[3,4,5,6,7]</code> <br /> Which is the best way that I can replace all value 1 in mask array into the values array?<br /> Expected result: <code>[0,0,0,0,3,4,0,0,5,6,0,7,0]</code><br /> I am working with large array.</p>
<p>Assuming <a href="/questions/tagged/numpy" class="post-tag" title="show questions tagged &#39;numpy&#39;" rel="tag" aria-labelledby="numpy-container">numpy</a>, and a values length equal to the number of 1s.</p> <p>Use boolean indexing:</p> <pre><code>mask = np.array([0,0,0,0,1,1,0,0,1,1,0,1,0]) values = [3,4,5,6,7]...
python|python-3.x|numpy
2
349,966
73,450,215
How to make a new column with different values using "AND" in pandas?
<p>I have a dataframe,containing values of name and verified columns, i want to see if the conditions meet and it generates a new column with different valuess based on the condition, For eg:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Verified</th> </tr> </thead> <tbody> ...
<p>You were close. Once you correct the structure of your conditional statement, you could do something like map, or use numpy where</p> <pre><code>df['Identity'] = ((df['Name'].eq('Mary')) &amp; (df['Verified'].eq('No'))).map({True:'Human',False:'Bot'}) </code></pre> <p>Or using numpy <code>where</code></p> <pre><cod...
python|pandas|dataframe
0
349,967
73,418,321
Python: string not splitting correctly at "|||" substring
<p>I have a column in Pandas DataFrame that stores long strings, in which different chunks of information are separated by a &quot;|||&quot;. This is an example:</p> <pre><code>&quot;intermediation|&quot;mechanical turk&quot;|precarious &quot;public policy&quot; ||| intermediation|&quot;mechanical turk&quot;|precarious...
<p>You need to escape <code>|</code>:</p> <pre><code>df['query_ids'].str.split('\|\|\|', n=5, expand=True) </code></pre> <p>or to pass <code>regex=False</code>:</p> <pre><code>df['query_ids'].str.split('|||', n=5, expand=True, regex=False) </code></pre>
python|pandas|dataframe
3
349,968
73,472,164
VarianceThreshold() not returning expected output
<p>I'm on the stage of cleaning categorical variables from my data. More specifically, I'm now removing quasi-constant categorical variables.</p> <p>I've searched and found that <code>VarianceThreshold()</code> from <code>sklearn.feature_selection</code> can do the job. However, I've got unexpected results. My piece of...
<p>The variance in this particular case would be <code>(1.91^2 * 0.94 + 1^2 * 0.03) - (1.91 * 0.94 + 1 * 0.03)^2 = 0.1419 &gt; 0.1</code></p> <p>Looks like you'll need a bit higher threshold.</p>
python|pandas|scikit-learn
1
349,969
73,213,399
Rsquared linear regression for stock market (SP500)
<p>I have programmed a small program to calculate the linear r square of a company through yfinance. This works perfectly</p> <pre><code>import numpy as np import pandas as pd #Para calcular r square from sklearn.metrics import r2_score import yfinance as yf import datetime import matplotlib.pyplot as plt ## To use st...
<p>With some modification to your code to calculate the r-squared :</p> <pre><code>import pandas as pd import numpy as np import yfinance as yf stock='NVCR' ko_df = yf.download(stock, period=&quot;5y&quot;, interval=&quot;1d&quot;, auto_adjust=False, prepost=False) adj_close_df = yf.download(stock, period=&quot;5y&qu...
python|numpy|scikit-learn|statsmodels
0
349,970
73,359,368
Replace values based on column to built cluster
<p>Is it possible to replace values in many columns. My goal is to replace all values based on the columns to create something like a cluster.</p> <p>There is a matrix looking like this with like 1000 columns</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <t...
<p>If you just need to fill in the required cells, then the solution is as follows:</p> <p>First, data is read from the file from the column names, another column is created, which is converted into indexes. Two arrays are created for indexing by indices and columns (the result is placed in a tuple, because without it ...
python|pandas|matrix|cluster-computing
0
349,971
73,420,498
Python pandas 'correct' syntax for slicing an entire column's/series values
<p>Given:</p> <pre class="lang-py prettyprint-override"><code>pandas.Series([[1,2],[3,4]]) 0 [1, 2] 1 [3, 4] dtype: object </code></pre> <p>Using <code>str</code> namespace of Dataframe/Series its possible to get a slice of the values (rather than of the dataframe) just like <a href="https://docs.python.org/3/lib...
<p>You can try:</p> <p><code> pandas.Series([[1,2],[3,4]]).map(lambda x:x[1:2])</code></p> <p>which tells pandas to slice each element with it's native syntax</p>
python|pandas|dataframe|syntax|slice
2
349,972
73,382,163
Filtering out rows based on other rows using pandas
<p>I have a dataframe that looks like this:</p> <pre><code>dict = {'companyId': {0: 198236, 1: 198236, 2: 900814, 3: 153421, 4: 153421, 5: 337815}, 'region': {0: 'Europe', 1: 'Europe', 2: 'Asia-Pacific', 3: 'North America', 4: 'North America', 5:'Africa'}, 'value': {0: 560, 1: 771, 2: 964, 3: 217, 4: 433, 5: 680}, '...
<p>You can check with <code>argsort</code> then <code>drop_duplicates</code></p> <pre><code>out = df.iloc[df.type.ne('actual').argsort()].drop_duplicates('companyId') Out[925]: companyId region value type 0 198236 Europe 560 actual 2 900814 Asia-Pacific 964 actual 4 1...
python|pandas|numpy
8
349,973
73,351,273
Creating 3D plot with pyplot - ValueError: shape mismatch: objects cannot be broadcast to a single shape
<p>I have a problem generating the chart. I want to create a 3d chart. I don't know where I made a mistake adding variables.</p> <p>This is my code:</p> <pre><code>d = 0.2 i_min = 1 / d i_max = pipe.max_slope(d=d) # float value slope = ctrl.Antecedent(np.arange(i_min, i_max + 1, 1), 'slope') v_min = 0 v_max = 5 veloci...
<p>It's trying to turn the 3 input arrays into compatible ones, <code>s, v, pred_val</code>.</p> <p>They come from these lines:</p> <pre><code>s = np.arange(i_min, i_max + 1, 1) v = np.arange(v_min, v_max + 0.1, 0.1) s, v = np.meshgrid(s, v) pred_val: np.ndarray = np.zeros(shape=(len(v), len(s))) </code></pre> <p>As a...
python|numpy|matplotlib|skfuzzy
0
349,974
73,393,235
Polars - How to compute rolling ewm grouped by column?
<p>What's the right way to perform a groupby + rolling aggregate operation in polars? For some reason performing an <code>ewm_mean</code> over a rolling groupby gives me the list of all the ewm's rolling by time. For example take the dataframe below:</p> <pre><code>shape: (10, 3) ┌─────────────────────┬────────┬───────...
<p>You were close. Since <code>ewm_mean</code> produces an estimate for each observation in each window, you simply need to specify that you want the <code>last</code> calculated value in each rolling window.</p> <pre class="lang-py prettyprint-override"><code>( portfolios .groupby_rolling(&quot;ts&quot;, by=&...
python|pandas|python-polars
2
349,975
73,200,378
TypeError: float() argument must be a string or a number, not 'NAType'
<p>I have a column in my dataframe that contains nan values and int values. The original dType was float64, but I was trying to change it to int6, and change nan values to np.nan. now I get this error: TypeError: float() argument must be a string or a number, not 'NAType' when trying to run imputation on it. In the fol...
<p>Use</p> <pre class="lang-py prettyprint-override"><code>df['age'] = df['age'].astype(dtype='Int64') </code></pre> <p>with extension datatype <code>Int64</code> (with a capitalized <code>I</code>) rather than the default <code>dtype</code> which is <code>int64</code> (lower case <code>i</code>). The latter throws an ...
python|pandas|null|dtype
2
349,976
73,483,917
Transform sequential 2d array to time-windowed dataset
<p>I have a 2d dataframe:</p> <pre><code> C1. C2. C3 0. 2. 3. 6 1. 8. 2. 1 2. 8. 6. 2 3. 4. 9. 0 4. 6. 7. 1 5. 2. 3. 0 </code></pre> <p>I want it to be a 3d data with &lt;num_windows, window_size, num_features&gt;</p> <p>So if window size is 5, the shape of the 3d data will be ...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.sliding_window_view.html" rel="nofollow noreferrer"><code>sliding_window_view</code></a>:</p> <pre><code>num_windows = 2 window_size = 5 num_features = 3 np.lib.stride_tricks.sliding_window_view(df, (window_size, num_featu...
pandas|dataframe|lstm|numpy-ndarray|data-munging
0
349,977
73,436,781
How do I write a user defined function to count the first name in the NAME and exactly match the score with respect to first name in the score column?
<p>Input:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Name</th> <th style="text-align: right;">Score</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Sam, Josh</td> <td style="text-align: right;">0</td> </tr> <tr> <td style="text-align: left;">Sam...
<p>You want to first go through names and then sum all the scores. First map the split function across names column</p> <pre><code>dataframe[&quot;Name&quot;] = dataframe[&quot;Name&quot;].map(lambda x: x.split(&quot;,&quot;)[0]) </code></pre> <p>then you group by name and sum all the Scores</p> <pre><code>dataframe = ...
python|pandas|dataframe
0
349,978
73,186,939
Selecting DataFrame values based on column of indices in list
<p>I created a code that gets values of df based on list of indices in another column:</p> <pre><code>import numpy as np import pandas as pd d = {'myvalues': [11, 13, 0, -1, 10, 14], 'neighbours': [[1,2],[0,2,3],[0,1,3],[1,2,4],[3,5],[4]]} df = pd.DataFrame(data=d) df['neighboring_idxs'] = df['neighbours']+pd.Series(...
<p>I don't know if it's faster but you can try to explode your list of list:</p> <pre><code>df['neighboring_myvalues'] = ( df.explode('neighboring_idxs').reset_index() .assign(vals=lambda x: df.loc[x['neighboring_idxs'], 'myvalues'].tolist()) .groupby('index')['vals'].agg(list) ) </code></pre> <p>Output...
python|pandas|dataframe|numpy
0
349,979
73,490,896
Check if value of dataframe is existing in list
<p>I am trying to <strong>split a pandas Dataframe into two, based on the value in the column &quot;country&quot;</strong>.</p> <p>If the value exists in the following list (EU-COUNTRY-CODES), the row should be added to a dataframe called &quot;EU&quot;, if it does not exist in the list I want to add the row to another...
<p>try this:</p> <pre><code>data[data[&quot;country&quot;].isin( eu-country-codes)==False] </code></pre>
python|pandas|dataframe
1
349,980
73,266,394
how to use separator on dataset loaded from sklearn?
<p>I know how to use separator (sep =&quot;&quot;) when importing the dataset using pd.read_csv</p> <p>but I don't know what to use to implement the separator on a dataset loaded from sklearn itself, like the digits dataset i used below where i want to implement the \n separator.</p> <p>code:</p> <pre><code>from sklear...
<p>If you look at carefully, you'll see that <code>load_digits</code> is a dictionary. You can reach its elements by</p> <pre><code>df.keys() </code></pre> <p>which returns</p> <pre><code>dict_keys(['data', 'target', 'frame', 'feature_names', 'target_names', 'images', 'DESCR']) </code></pre> <p>So, if you want to get t...
python|pandas|scikit-learn
0
349,981
73,312,603
Pandas: get rows with consecutive column values and add a couter row
<p>I need to go through a large pd and select consecutive rows with similar values in a column. i.e. in the pd below and selecting column x:</p> <pre><code>col row x y 1 1 1 1 2 2 2 2 6 3 3 8 9 2 3 4 5 3 3 9 4 9 4 4 5 5 5 1 3 7 5 2 6 6 6 6 </code></pre> <p>The res...
<p>IIUC, use boolean indexing using a mask of the consecutive values:</p> <pre><code>m = df['x'].eq(df['x'].shift()) df[m|m.shift(-1, fill_value=False)] </code></pre> <p>Output:</p> <pre><code> col row x y 2 6 3 3 8 3 9 2 3 4 4 5 3 3 9 6 5 5 5 1 7 3 7 5 2 </code></pre>
python|pandas|dataframe
0
349,982
73,486,822
Comparing 2 CSV files with Domain and IP. Rows are in different order. Reading Row 1 File X compare with all Rows in File Y
<p>so i've looked online at a far exmaples but they all seem to assume the data is in order. So Row 1 in Both files has the same information.</p> <p>In my case Row 1 File X has an IP and DNS. The idea is to check if this IP address can be found in any of the rows in File Y.</p> <p>Ideally I'd get a list of IP addresses...
<p><strong>Try this:</strong></p> <pre><code>df_file1.loc[~df_file1.ip.isin(df_file2.ip)] </code></pre>
python|pandas|csv|sorting
0
349,983
73,251,219
Unexpected behaviour while outputting file in python
<p>I have the following code:</p> <pre><code>import csv import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) for x in range(10, 11): df.to_csv(&quot;file_%x.csv&quot; % x, index=False) </code></pre> <p>Instead of returning <code>file_10.csv</code>...
<p>The old <code>%</code>-style <a href="https://docs.python.org/3/library/string.html" rel="nofollow noreferrer">string formatting</a> uses largely C-derived directives. <code>%x</code> instructs the formatter to print the number in hexadecimal, so 10 <em>is</em> <code>a</code>. Use <code>%s</code> to stringify in the...
python|pandas
4
349,984
73,440,790
Splitting a dataframe column into two separate data frames using pandas
<p>i am using python to code in jupyter notebook.</p> <p>Im trying to use pandas to split a column of dataframe (called &quot;PostTypeId' into two separate dataframes, based on the columns value - one dataframe is to be called Questions and has the column value of 1, and the second dataframe is to be called Answers tha...
<p>you can do it by:</p> <pre><code>Questions=pd.DataFrame(PostTypeId[PostTypeId.col_name==1]) Answers=pd.DataFrame(PostTypeId[PostTypeId.col_name==2]) </code></pre> <p>when creating the function, use the filter values as the argument</p>
python|pandas|dataframe
0
349,985
73,215,537
TypeError: Sequential.add() got an unexpected keyword argument 'padding'
<p>I'm trying to build a model for image classification, but when I run the code, this error shows: <code>TypeError: Sequential.add() got an unexpected keyword argument 'padding'</code> this is the model:</p> <pre><code>model.add(Conv2D(32, (3,3), 1, activation='relu', input_shape=(256,256,3), padding='same', kernel_re...
<pre><code>model.add(Conv2D(32, (3,3), 1, activation='relu', input_shape=(256,256,3), padding='same', kernel_regularizer=regularizers.l2(0.01))) model.add(Conv2D(64, (3,3), 1, activation='relu'), padding='same', kernel_regularizer=regularizers.l2(0.01)) </code></pre> <p>In the first call, because of the arrangement of...
python|tensorflow|keras
0
349,986
73,450,038
Adding an index in Pandas Dataframe
<p>I have this dataframe in Pandas:</p> <pre><code>id animal 0 dog 0 cat 1 goat 1 cow 1 sheep 1 pig 2 lion 2 tiger 2 bear </code></pre> <p>I want to add a column as follows. I don't know what you call it but basically it's an index for each unique id.</p> <pre><code>id animal ix 0 do...
<p>Group by <code>id</code> and use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a></p> <pre><code>df['ix'] = df.groupby('id').cumcount() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df id animal ix...
python|python-3.x|pandas|dataframe
1
349,987
73,438,167
Python - Finding average of a column in a CSV given a value in another column (data from a specific year in a file with multiple years)?
<p>The CSV files used in this code are air quality sensor data files. They record particle concentrations each hour over multiple years in some cases. There is about 100 CSV files I am using. I have already figured out how to look through each file and average a variable regardless of the year, but I am having trouble ...
<p>Imagine this is your <strong>table</strong> :</p> <p><a href="https://i.stack.imgur.com/jEriz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jEriz.png" alt="enter image description here" /></a></p> <br /> <br /> <p>I tried to give you the idea on :</p> <p><strong>how to do something on a column ...
python|pandas|csv
0
349,988
73,445,358
create new df3 with max values from df1 and corresponding values (same position) from df2
<p>I would like to create a new <strong>df3</strong> based on</p> <p><strong>1)</strong> finding the max value in each column of <strong>df1</strong> and</p> <p><strong>2)</strong> then appending a row with the corresponding values from <strong>df2</strong> (same position of <strong>df1</strong>)</p> <p><strong>Input:<...
<p>You can try:</p> <pre><code>df3 = pd.DataFrame([df1.max().tolist(), [df2.at[row, col] for row, col in zip(df1.idxmax(), df1.columns)]]) </code></pre> <p>Output:</p> <pre><code> 0 1 0 7.00 15.000 1 0.45 0.115 </code></pre>
python|pandas
1
349,989
73,428,428
Efficient way to apply several functions to Pandas DataFrame returning several columns
<p>I have a large datasource in which I am trying to enrich the data by creating some calculated columns.</p> <p>The data source is close to 4 Million rows and I am pulling the data in chunks of 100,000</p> <pre><code>for field in fields: operation_start = time.time() print(f&quot;Operation {y+1}&quot;) chunk[...
<p>You can process the file as a stream without building a <code>DataFrame</code>. There's <code>Table</code> helper in convtools library (<a href="https://convtools.readthedocs.io/en/latest/tables.html" rel="nofollow noreferrer">table docs</a> | <a href="https://github.com/westandskif/convtools" rel="nofollow noreferr...
python|pandas
1
349,990
73,487,352
Can Pandas to_excel support hyperlink style now?
<p>I can't find an answer (or one I know how to implement) when it comes to using the excel &quot;hyperlink&quot; style for a column when exporting using pd.to_excel.</p> <p>I can find plenty of (OLD) answers on using xlsxwriter or openpyxl. But none using the current pandas functionality.</p> <p>I think it might be po...
<p>Here is one way to do it using xlsxwriter as the Excel engine:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'ID': [1, 2], 'link':['=HYPERLINK(&quot;http://www.python.org&quot;, &quot;some website&quot;)', '=HYPERLINK(&quot;h...
python|pandas|xlsx
2
349,991
73,466,656
How to add a custom layer after a densevariational layer?
<p>I have made a small bayesian neural network with few dense variational layers.</p> <pre><code>import numpy as np from sklearn.model_selection import train_test_split from tqdm.notebook import tqdm import tensorflow_probability as tfp import tensorflow as tf from tensorflow.keras.layers import Input from tens...
<p>You should stick to one data type when doing your calculations and it should be fine. Here is an example, but I cannot verify that the logic is correct (that is up to you):</p> <pre><code>import tensorflow as tf import tensorflow_probability as tfp tfk = tf.keras tfkl = tf.keras.layers tfd = tfp.distributions tfpl ...
python|tensorflow|keras|deep-learning|tensorflow-probability
2
349,992
73,359,999
Count non-nan-values in 3d numpy array
<p>I have a list of N 2d numpy arrays, all of the same size Mx3, all of which represent a single sample of M coordinates. Sometimes the value of a coordinate can be np.nan.</p> <p>I (think I) know how to compute the average and standard deviation over these coordinate samples, namely as follows (i.e. stack them and com...
<p>You can make a mask array and just sum 0s and 1s, where 0 either means a real value or nan value.</p> <p>Basically, let us assume you have a 3D array with some random nan-values and let us count the number of nans along some axis (in your case the axis 0):</p> <pre><code>#!/usr/bin/env ipython # --------------------...
python|numpy
1
349,993
73,359,855
Implementing Custom Min_MAX_Pooling Layer in Tensorflow
<p>Hi i am trying to implement coustom min max plooing layer in tensorflow using lambda layers to reduce noise in time series data. Here is the function that dose the min max pooling</p> <pre><code>def min_max_pooling(sequence, window=5): output = tf.constant([],dtype='float64') max_ = tf.Variable(0,dtype = 'f...
<p>Apart from the fact that usually TF uses float32 in my experience, as float 64 is double the memory, and usually the additional precision/big numbers are not useful, your problem is that you are not considering that TF uses batches of data</p> <p>In other words, your layer will receive a batch of sequences, not a si...
python|tensorflow|keras|deep-learning|max-pooling
1
349,994
73,420,669
how to extract database column in json format into multiple columns in dataframe
<p>I have a database column that's been converted to a Pandas dataframe and it looks like below . My actual data has much more columns and rows with different <code>key: value</code> pair.</p> <pre><code>df[&quot;Records&quot;] {&quot;ID&quot;:&quot;1&quot;,&quot;ID_1&quot;:&quot;40309&quot;,&quot;type&quot;:&quot;typ...
<p>not entirely sure I understand the question but if youre just trying to take your data out of index, just use</p> <p><code>df1.reset_index(drop=False)</code></p> <p>or if youre trying to convert rows to columns you could use <code>df1.transpose()</code></p>
python|pandas
0
349,995
73,312,456
Keras can't save model with CuDNNLSTM as SavedModel
<p>I have recently encountered a problem with Keras. My model looks like:</p> <pre><code>inputs = Input(shape=(max_sequence_len,)) # Embedding layer embedding = Embedding( input_length=max_sequence_len, input_dim=len(word_idx), output_dim=100, weights=[embedding_matrix], trainab...
<p>Don't use <code>CuDNNLSTM</code>, just use <code>LSTM</code> (which is newer) with default parameters, it will automatically use CuDNN, assuming you have CuDNN properly installed. <code>CuDNNLSTM</code> is for Tensorflow &lt;=2.0.</p> <pre><code>heart = Bidirectional(LSTM(256))(embedding) </code></pre> <p>You might ...
python|tensorflow|keras
0
349,996
73,425,325
Custom aggregation of pandas dataframe
<p>I have below dataframe</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'A' : [1,2,3], 'B' : ['X', 'Y', 'Z'], 'C' : ['XX', 'YY', 'ZZ'], 'D' : [1,1,1]}) df2 = pd.DataFrame({'A' : [1+1,2+1,3+1], 'B' : ['X', 'Y', 'Z'], 'C' : ['XX', 'YY', 'ZZ'], 'D' : [2,2,2]}) df3 = pd.DataFrame({'A' : [1+3,2+3,3+3], 'B' : ['X', ...
<p>To get the desired output you could do something like this:</p> <pre class="lang-py prettyprint-override"><code>#lambda also possible but this looks a bit cleaner def weights(grp): val1,val2,val3 = grp return 0.4*val1 + 0.5*val2 + 0.5*val3 # the aggregations on B and D are just examples. You can change that...
python|pandas|aggregate
1
349,997
73,336,953
Iterate over custom date time index in pandas?
<p>I have a large dataframe with a timestamp index. I converted this index using <code>.to_pydatetime()</code>. I am trying to iterate over this index in invervals of 3 minutes, however though the dataframe has over 2,000 rows, my iteration stops at 53. Code below:</p> <pre><code># create Time column out of index for c...
<p>You can try using pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferrer">resample</a>. First convert the column with datetime using <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_date...
python|pandas|loops|datetime
1
349,998
73,490,158
Looping through CSV files, performing a function, and concatenating DataFrame objects
<p>I am attempting to loop through multiple CSVs, find the mean of multiple variable columns (6 to be specific) within the CSV, which in turn will output a single row of results (6,1) in dimensions, and append that to a dataframe object, for all .csv files in the folder.</p> <p>I am quite new to programming, and the fi...
<p>Would this work:</p> <pre><code>from pathlib import Path folder = r&quot;C:\Users\A\Desktop\Analysis\Field result\Height&quot; dfs = [] for file in Path(folder).glob(&quot;*.csv&quot;): print(file.name) dfs.append(pd.read_csv(file).iloc[:, 3:9].mean().to_frame().T) df = pd.concat(dfs, ignore_index=True) </c...
python|pandas|database|dataframe|csv
0
349,999
34,991,666
How to convert a particular dtype object column's field into column of data frame in pandas
<p>I'm trying to convert object type column <code>page_view_count</code> fields into column of data frame.</p> <p>I have a dataframe :</p> <pre><code> _id page_view_count 568a8c25cac4991645c287ac {u'main-rating': 2, u'detailed-rating2': 1, u'detailed-rating': 2} 568cd22e9e8...
<p>You can create new dataframe from column <code>page_view_count</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a> column <code>_id</code>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_...
python|mongodb|pandas|dataframe
1