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
13,100
71,441,818
Indexing with multiple keys
<pre><code> PageId VolumePred ConversionPred OSBrowser 955761 37200.0 27625.0 (11, 16) 955764 30157.0 21155.0 (11, 16) 955764 25258.0 17836.0 (11, 16) 1184903 35492.0 17768.0 (11, 16) 955764 24683.0 16965.0 (11, 16) 955764 8.0 0.0 ...
<p>You're really close; you just need to add an extra set of square brackets:</p> <pre><code>subdata.groupby(['PageId', 'OSBrowser'])[['ConversionPred', 'VolumePred']].agg('sum') </code></pre>
python|python-3.x|pandas|dataframe|pandas-groupby
1
13,101
71,282,712
How to create dataframe using two dataframe using pandas
<p>I have two dataframe 'df1' and 'df2'</p> <pre><code>df1= a b 1 such as 2 who I'm df2= a keyword 1 such 1 as 2 who 2 I'm </code></pre> <p>Based on this two dataframe I want to create following dataframe</p> <pre><code>resul...
<p>IIUC, just perform a replacement with <code>map</code>:</p> <pre><code>df2['a'] = df2['a'].map(df1.set_index('a')['b']) </code></pre>
python|pandas|dataframe
1
13,102
71,285,722
Read GoogleSheet with multiple sheets into pandas
<p>I want to read google sheet <em>with multiple sheets</em> into a (or several) pandas dataframe.</p> <p>I don't know the sheet names, or the number of sheets in advance.</p> <hr /> <p><a href="https://stackoverflow.com/questions/26521266/using-pandas-to-pd-read-excel-for-multiple-worksheets-of-the-same-workbook">The ...
<p>When your Spreadsheet is publicly shared, in your situation, how about the following sample script?</p> <h3>Sample script:</h3> <pre class="lang-py prettyprint-override"><code>import openpyxl import pandas as pd import requests from io import BytesIO spreadsheetId = &quot;###&quot; # Please set your Spreadsheet ID....
python|excel|pandas|google-sheets
0
13,103
71,412,409
Merging dictionaries by key
<p>I have a list of dictionaries. Each four with the same keys but different values.</p> <pre><code>[[{'Vanilla Shake': {'Calories': '505.3532687092'}}], [{'Vanilla Shake': {'Protein': '10.7838768505'}}], [{'Vanilla Shake': {'Carbohydrates': '83.7223214166'}}], [{'Vanilla Shake': {'Total Fat': '13.4791543506'}}], [...
<p>Assuming <code>l</code> the input list, you could do:</p> <pre><code>from itertools import chain df = (pd.concat(map(pd.DataFrame, chain.from_iterable(l))) .groupby(level=0).first() .T ) </code></pre> <p>or using a big dictionary comprehension, which should be faster:</p> <pre><code>df = (pd.S...
python|pandas|database
1
13,104
71,316,254
A more optimized solution to pandas apply row-wise
<p>I have this code that does some analysis on a DataFrame. <code>both_profitable</code> is <code>True</code> if and only if both <code>long_profitable</code> and <code>short_profitable</code> in that row are <code>True</code>. However, the DataFrame is quite large and using pandas <code>apply</code> on <code>axis=1</c...
<p>You should use <code>eq</code> method on the columns:</p> <pre><code>output[&quot;both_profitable&quot;] = output[&quot;long_profitable&quot;].eq(output[&quot;short_profitable&quot;]) </code></pre> <p>Or since both columns are boolean, you could use the bitwise <code>&amp;</code> operator:</p> <pre><code>output[&quo...
python|pandas|dataframe|optimization
1
13,105
71,214,513
Convert pandas dataframe from wide to long by two year columns
<p>There many answers, but still cannot resolve. I have a dataframe:</p> <pre><code>{'Author': {0: 111, 1: 222}, 'Journal17': {0: 2, 1: 4}, 'Journal18': {0: 1, 1: 7}, 'Journal19': {0: 0, 1: 3}, 'Journal20': {0: 0, 1: 0}, 'Var_one': {0: 0, 1: 2}, 'Var_two': {0: 0, 1: 2}, 'Score17': {0: 10.591, 1: 14.682}, 'Score18': {0:...
<p>Let's use <code>pd.wide_to_long</code>:</p> <pre><code>pd.wide_to_long(df, ['Journal','Score'], ['Author','Var_one', 'Var_two', 'Var3', 'Var4', 'Var5', 'Var6'], 'Year', sep='', suffix='\d+').reset_index() </code></pre> <p>Output:</p> <pr...
python|pandas
2
13,106
71,278,744
How to read json file without using python loop?
<p>I have a JSON file that I want to convert into DataFrame. Since the dataset is pretty large (~30 GB), I found that I need to set the chunksize as the limitation. The code is like this:</p> <pre><code>import pandas as pd pd.options.display.max_rows datas = pd.read_json('/Users/xxxxx/Downloads/Books.json', chunksize ...
<p>I don't think pandas is the way to go when reading giant json files.</p> <p>First you should check out if your file is actually in a valid JSON format (it is completely wrapped in one dictionary) or if it is a JSONL file (each row is one dictionary in JSON format but the rows are not connected).</p> <p>Because if yo...
python|pandas|dataframe
0
13,107
52,100,876
python convert 2d array to 1d array
<p>I am new to python and need to do the following thing:</p> <p>I've given an 1d array of vectors (so pretty much 2d).</p> <p>My task is to create an 1d array that contains the length of each vector.</p> <pre><code>array([[0. , 0. ], [1. , 0. ], [1. , 1. ], [1. , 0.75], [0.75, 1. ], [0.5 , 1....
<p>Using norm from <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html" rel="nofollow noreferrer">np.linalg.norm</a>:</p> <pre><code>import numpy as np a = np.array([[0., 0.], [1., 0.], [1., 1.], [1., 0.75], [0.75, 1.], ...
python|arrays|numpy
4
13,108
60,402,776
Calculate the subtraction of two columns in two dataframes by replacement
<p>I have <code>df1</code> which contains:</p> <pre><code>IDs values E21 32 DD12 82 K99 222 </code></pre> <p>And <code>df2</code> that contains:</p> <pre><code>IDs values GU1 87 K99 93 E21 48 </code></pre> <p>What I need is to check if the <code>ID</code> in <code>df2</code> exists in <code>df1</...
<pre><code># create new column in df2 with name 'new' df2['new'] = df2['values'] # loop on the values of 'IDs' column for i, element in enumerate(df2.IDs): # condition to check if an element exists in df1 if element in df1.IDs.values: df2['new'][i] = df1['values'][df1.index[df1.IDs == element][0]] - ...
python|pandas|subtraction
2
13,109
72,790,923
Pandas - column with nested None value, convert to empty string
<p>I have the following example list that I convert to a df:</p> <pre><code>new_list = [{'video_id': {'platform': 'facebook', 'id':'123'}, 'title': 'Scam Rapper', 'description': 'truthful', 'keywords':['x', 'B'], 'publish_date': '2022-06-15', 'publish_timestamp':'2022-06-15 23:30:02', 'publisher': {'creator_id': '2pal'...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply</code></a> with <a href="https://www.geeksforgeeks.org/python-dictionary-comprehension/" rel="nofollow noreferrer"><code>dict comprehension</code></a>:</p> <pre><code>In [1664]: video_items...
python-3.x|pandas
1
13,110
59,650,507
How can i compare values in pandas and change values
<p>I have some data frame, I have run this command:</p> <pre><code>share_df=df.iloc[:,60:61] </code></pre> <p>which make me a dataframe with one column with numbers, now I want to run for loop on this share_df to see if the value bigger than the median then set it to 1 else set it to 0 this is the dataframe:</p> <p...
<p>Don't write a for loop in Python, that would be slow.</p> <p>You can instead do</p> <pre><code>share_df["shares"] = (share_df["shares"] &gt; medianShareValue).astype(int) </code></pre>
pandas|dataframe
1
13,111
32,242,396
What is the most efficient way to replace NaNs in multiple columns based on a default value column?
<p>I have a DataFrame like</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame( { 'val1': [1,np.nan,3], 'val2': [np.nan,5,6], 'val3': [7,np.nan,8], 'default': [ 42,43,44 ] } ) </code></pre> <p>i.e.</p> <pre><code> default val1 val2 val3 0 42 1 NaN 7 1 43 NaN 5 ...
<p>Be sure to use double brackets to indicate <code>df[['default']]</code> is a DataFrame instead of a Series, otherwise your results won't match the expected output.</p> <pre><code>&gt;&gt;&gt; df.fillna(df[['default']].values) default val1 val2 val3 0 42 1 42 7 1 43 43 5 43 2 ...
python|pandas
3
13,112
32,150,192
IndexError for scientific Python code
<p>I have been working on some code that does integration, some manipulation, and then more integration. Here is the <a href="https://chat.stackoverflow.com/transcript/message/25087985#25087985">code</a> (thanks @JRichardSnape!). Basically this code solves a matrix equation, which is what <code>mesolve</code> does. It ...
<p>This reproduces your error:</p> <pre><code>In [34]: data = np.zeros((0,10)) In [35]: data Out[35]: array([], shape=(0, 10), dtype=float64) In [36]: data[0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt...
python|numpy|scipy|qutip
3
13,113
40,697,313
How to apply different functions to different columns on pandas dataframe
<p>I'd like to use groupby on pandas dataframe, but I want to get the mean of some columns and the sum for others. Let's say we have the following dataframe:</p> <pre><code>ID A B C 1 1 1 0 1 2 3 1 1 3 6 1 4 3 2 1 4 4 1 0 6 5 1 0 6 6 6 1 6 7 ...
<p>you can do it this way:</p> <p>Data:</p> <pre><code>In [127]: df = pd.DataFrame(np.random.randint(0,10, (7,6)), columns=list('ABCDEF')) ...: df['ID'] = np.random.choice([1,2], len(df)) ...: In [128]: df Out[128]: A B C D E F ID 0 7 7 2 2 3 0 1 1 8 4 1 3 6 8 1 2 4 7 7 2 8 4...
python|pandas|numpy|dataframe
7
13,114
61,823,128
Neatly use bias trick in deep learning
<p>I'm working on a simple example of how to use the bias trick in the forward pass of a neural network. I guess my code is correct so far, but is it really necessary to add an array of "1" manually to each activation, or is there a simpler way to do it?</p> <pre><code>import numpy as np def f(z): return 1/(1+np....
<p>How about rewriting <code>f</code> to account for that, something as the following will do the trick:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def f(z, final_activation=False): a = 1/(1+np.exp(-z)) return a if final_activation else np.r_[a, [[1]]] ###Define the network, use...
python|numpy|neural-network
1
13,115
61,987,403
:unsupported operand type(s) for -: 'str' and 'str'
<blockquote> <p>TypeError: unsupported operand type(s) for -: 'str' and 'str'</p> </blockquote> <p>face this typeerror msg when I ran the following code:</p> <pre><code>df_set= pd.read_excel("DATA_SVM.xlsx") print(df_set.columns) df1= df_set.drop([0]) df= df1.rename(columns={ 'MSCI World ':'Date', 'MSCI ...
<p>It looks like your Price column is formatted as strings. You first need to convert to a type for which subtraction is defined (e.g. float) </p> <pre><code>df['Price'] = df['Price'].apply(float) </code></pre>
python|pandas
2
13,116
61,639,243
Flattening MultiIndex pivot table in Python pandas
<p>Here's my pivot table column structure (multiindex):</p> <pre><code> col2 col3 col4 sales month month_1 month_2 month_3 </code></pre> <p>I would like to flatten it to:</p> <pre><code> col2 col3 col4 month_1 month_2 month_3 </code></pre> <p>If I do <code>pivot.columns = pivo...
<p>I think solution is remove <code>[]</code> around <code>[sales]</code> and <code>[months]</code> if pivoting only by one column <code>sales</code>.</p> <p>So code is:</p> <pre><code> pivot = (pd.pivot_table(df, index=['col2','col3','col4'], columns='month', ...
python|pandas|dataframe|pivot-table
5
13,117
61,715,271
How to find country with minimum and maximum happiness score from each region in a pandas dataframe?
<p>I have a pandas dataframe "df" having columns<code>[Country,Region,Happiness Score,Year]</code>. </p> <p>There are total <code>165</code> countries in df having data for <code>3 years(2015,2016,2017)</code>, therefore length of df is <code>165*3=495</code>. </p> <p>There are total <code>10</code> unique regions in...
<p>This will be close to what you are after - group by the region and find min and max:</p> <pre><code>mins = df.groupby('Region')['Happiness Score'].min() maxs = df.groupby('Region')['Happiness Score'].max() df2=pd.concat([mins,maxs],axis=1) df2.columns=(['Min Happiness Score','Max Happiness Score']) df2['Region']=mi...
python|pandas|dataframe|pandasql
1
13,118
58,031,136
Difference between subsequent columns in python dataframe
<p>In below dataframe, using pandas I would like to subtract values from subsequent years to get results like this:</p> <p>input:</p> <pre><code> 2000 2001 2002 2003 2004 Michael 10 12 15 8 3 John 7 5 6 12 25 Mitch 3 13 5 7 8 Jeff 1 0 11 6 9 Ron ...
<p>Try this. However, as @Quang Hoang put in the comments, it is much wasier to do with <code>df.diff(axis=1)</code>. It did not occur to me when I was putting this answer.</p> <pre><code>df.sub(df.shift(axis=1)) </code></pre> <p>In this code, we are basically shifting all columns one step in axis=1 (vertically) and ...
python|pandas|dataframe
0
13,119
57,747,913
Scipy linregress returns tuple when passed Pandas data
<p>Using Pandas, I'm reading in data from a CSV file and then trying to perform a linear regression on it, using linregress. I am able to extract and manipulate the data from the file but, when I go to use linregress, while it seems to run the regression, it returns a tuple and seems not to have slope, intercept, and o...
<p>Starting in SciPy version 0.16.0, <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html" rel="nofollow noreferrer"><code>linregress</code></a> returns a <a href="https://docs.python.org/3.7/library/collections.html#collections.namedtuple" rel="nofollow noreferrer"><code>namedtuple...
python|pandas|scipy
1
13,120
58,059,653
Convert data frame columns to rows
<p>I have a dataframe which looks like:</p> <pre><code>time feature_1 feature_2 feature_3 02.07.2019 00:00 0.1 0.1 0.7 02.07.2019 00:15 0.2 0.4 0.6 02.07.2019 00:30 0.3 0.5 0.7 </code></pre> <p>I want to convert it to </p> <pre><code>time ...
<p>Find the code below:</p> <pre><code>import pandas pd.melt(df,id_vars=['time'],value_vars=['feature_1','feature_2','feature_3']).sort_values('time') </code></pre>
python|pandas
3
13,121
57,871,450
async 'read_csv' of several data frames in pandas - why isn't it faster
<p>I want to create a code that reads several pandas data frames asynchronously, for example from a CSV file (or from a database)</p> <p>I wrote the following code, assuming that it should import the two data frames faster, however it seems to do it slower:</p> <pre><code>import timeit import pandas as pd import asy...
<p><code>pd.read_csv</code> isn't an async method, so I don't believe you're actually getting any parallelism out of this. You'd need to use an async file library like <a href="https://github.com/Tinche/aiofiles" rel="noreferrer"><code>aiofiles</code></a> to read the files into buffers asynchronously, then send those t...
python|pandas|async-await
6
13,122
34,365,564
Write data if it matches a criterion
<p>I have a datafile with 3000+ variables in it. Each row contains the data from one individual. Not all individuals have data for each variable. In other words the data file looks something like the following:</p> <pre><code>V1,V2,V3,V4,V5,V6 ID1, , , 4, 2, ID2,1, 2, , , ID3,1, , , , 3 </code></pre> <p>What...
<p>How about:</p> <pre><code>df_datafile = pd.read_csv('data.csv') for row, data in df_datafile.iterrows(): data.dropna().to_frame().transpose().to_csv('file_{}.csv'.format(row)) </code></pre> <p>You could probably skip the <code>fillna()</code> step if you later drop the <code>0</code> values again (that's why i...
python|csv|numpy|pandas
0
13,123
36,702,665
Is there a way for on-the-fly pre-processing (splitting) of elements with get_dummies()?
<p>I have been struggling with this one for a little while and I cannot figure it out.</p> <p>I have some data that I'm trying to prepare and in the course of that I have to turn some categorical part of the data to binaries, using dummies (I figured).</p> <p>The issue is that some of the entries in my raw data can i...
<p>Use <code>sep=','</code> in <code>get_dummies()</code></p> <pre><code>In [379]: df_sample['C'].str.get_dummies(sep=',') Out[379]: CAT1 CAT2 CAT3 0 1 0 0 1 0 1 0 2 0 0 1 3 1 1 0 4 0 0 1 </code></pre>
python|python-3.x|pandas
2
13,124
36,902,291
Insert Pandas Timestamp into Mongodb
<p>I'm trying to insert a Pandas DataFrame into Mongodb using PyMongo. </p> <pre><code>df.head() </code></pre> <p><a href="https://i.stack.imgur.com/zGFj5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zGFj5.png" alt="enter image description here"></a></p> <p>Because the index if the Pandas DataF...
<p>A solution would be that you turn index to <code>str</code> before attempting to store away in MongoDB, like this:</p> <pre><code>&gt;&gt; df.index = df.index.astype(str) &gt;&gt; db.testCollection.insert(df.T.to_dict()) </code></pre> <p>When reading the data out of db again later you can turn index to timestamp:<...
python|mongodb|pandas|pymongo
2
13,125
55,068,942
How to find the first & Last element in a Dataframe Column & Trim the value between those elements
<p>I have been working with coordinate Data. (Lat &amp; Long)</p> <p><strong>Background</strong></p> <pre><code>Act Df = Index Latitude Longitude 0 66.36031097267725 23.714807357485936 1 66.36030099322495 23.71479548193769 2 . . </code></pre> <pre><code>Flt Df = Index ...
<p>here my solution: ia m using the library geopy to calculate the distance.</p> <p>You could choose to calulate the distance in geodesic() or great_circle(), either the function distance = geodesic.<br> and you could change the metric <code>.km</code> to <code>.miles</code> or to <code>m</code> or to <code>ft</code> ...
python|python-3.x|pandas
1
13,126
49,391,652
Pandas: Drop row if second column is blank
<p>I am trying to use Python3 and Pandas to shape a dataframe.</p> <p>My current frame looks like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;style type="te...
<p>I think this answers your question. You can get the columns names and store it to a variable with:</p> <pre><code>x= df.columns.tolist()[0] </code></pre> <p>then:</p> <pre><code>df=df[df[x].isnull()==False] </code></pre>
python|pandas
0
13,127
28,111,323
How can I install the latest versions of NumPy/Scipy/Matplotlib/IPython/Pandas on Ubuntu
<p>Users <a href="https://stackoverflow.com/q/28101851/190597">sometimes need to know</a> how to install a newer version of Pandas than their OS package manager offers. Pandas requires NumPy, and works best with SciPy, Matplotlib and IPython.</p> <p>How can I install the latest versions of NumPy/Scipy/Matplotlib/IPyth...
<p>Using Ubuntu, here is how to install the entire NumPy/Scipy/Matplotlib/IPython/Pandas stack from Github in a virtualenv using Python2.7:</p> <p>Note: The instructions below install the latest <em>development</em> version of each package. If you wish to install the latest tagged version, then after <code>git clone</...
numpy|matplotlib|pandas|scipy|ipython
9
13,128
28,357,897
Speeding up analysis on arrays in numpy
<p>I have a python code, which imports 4 column txt file with numbers first three columns are x,y,z coordinate and fourth column is a density at that coordinate.</p> <p>below is the code that reads, converts to ndarray, Fourier transform that field, calculate the distance from origin (k=(0,0,0)) and a transformed coor...
<p>Numpy can typically do things hundreds of time faster than plain python, with very little extra effort (and sometimes will even automatically use multiple cores with no work from you). You just have to know the right ways to write your code. Just to name the first things I think of:</p> <ul> <li>Think about your ...
python|performance|numpy|multiprocessing|fft
11
13,129
73,437,604
Selecting only the rows where dataframe times that where hourly ends in HH:00:00, with 00:00 being minutes and seconds?
<p>I have a lot of data from a lot of different datasets with different time frames (hourly, every 5 minutes, and every minute). I decided to get all of the data on even times, and only want the data ending in YYYY:MM:DD HH:00:00 (I have decades of data on this).</p> <p>I have tried a few different methods to filter ou...
<p>Assuming you are working with <code>pd.Timestamp</code> values, you could do the following:</p> <pre><code>import pandas as pd df = pd.DataFrame([ pd.to_datetime('2022-04-06 11:00:00'), pd.to_datetime('2022-04-06 11:00:05') ], columns=['time_column']) idx1 = df['time_column'].dt.minute == 0 idx2 = df['time...
python|pandas|date|datetime
0
13,130
35,320,365
Using a GPU both as video card and GPGPU
<p>Where I work, we do a lot of numerical computations and we are considering buying workstations with NVIDIA video cards because of CUDA (to work with TensorFlow and Theano).</p> <p>My question is: should these computers come with another video card to handle the display and free the NVIDIA for the GPGPU?</p> <p>I w...
<p>Having been through this, I'll add my two cents.</p> <p>It is helpful to have a dedicated card for computations, but it is definitely not necessary.</p> <p>I have used a development workstation with a single high-end GPU for both display and compute. I have also used workstations with multiple GPUs, as well as he...
gpu|gpgpu|theano|tensorflow
15
13,131
34,904,465
Python Pandas filer columns by multiple string
<p>So I have a Python 2.7 Pandas data frame with lots of columns like:</p> <pre><code>['SiteName', 'SSP', 'PlatformClientCost', 'rawmachinecost', 'rawmachineprice', 'ClientBid' +... + 20 more] </code></pre> <p>And I would like to exclude all the columns contains either the word 'Platform' or 'Client' and below is my ...
<p>use the vectorised <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html#pandas.Series.str.contains" rel="nofollow"><code>str.contains</code></a>:</p> <pre><code>In [222]: df = pd.DataFrame(columns=['SiteName', 'SSP', 'IONumber', 'userkey', 'Imps', 'PlatformClientCost', 'raw...
python|pandas
2
13,132
31,003,229
Python dataframes count number of occurences in two columns
<p>Two dataframe columns:</p> <pre><code>data['IP'] data['domain'] 10.20.30.40 example.org 10.20.30.40 example.org 10.20.30.40 example.org 10.20.30.40 example.org 1.2.3.4 google.com 1.2.3.4 google.com 1.2.3.4 google.com 200.100.200.100 y...
<p>The following performs a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html#pandas.Series.groupby" rel="nofollow"><code>groupby</code></a> on 'domain' and then calls <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.value_counts.ht...
python|python-3.x|pandas|dataframe
3
13,133
67,600,662
Transform DataFrame into multidimensional TimeSeries?
<p>I have the following pandas DataFrame with &quot;periodic&quot; values over the column <code>'county'</code> as well as repeating values in <code>'reporting_period'</code> and <code>'date'</code>:</p> <pre class="lang-py prettyprint-override"><code>data = pd.DataFrame({'county': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: '...
<p>Easiest way to visualize the ts data as <code>multiindex</code> is to <code>set_index</code>. <code>reporting_period</code> can also be converted to <code>period type</code> but that depends on the requirement.<br /> If we want to apply any <code>aggregation, reduction</code> or any other <code>transformation</code>...
python|pandas|datetime|time-series
1
13,134
67,396,524
Create column in dataframe with TRUE if enough occurences of an id within a column
<p>I have a dataframe with id column, col1, col2. The id can appear several times.</p> <pre><code>id col1 col2 1 a b 1 c d 2 e f 3 g h 4 x y 4 x z 4 a z </code></pre> <p>I want to create a new column with:</p> <ul> <li>TRUE if id...
<p>With your shown samples, could you please try following. We can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer"...
python|pandas
1
13,135
60,113,549
How to Create/Add multiple charts in ChartSheet using openpyxl?
<p>There is option in excel sheet which allows user to export charts to chartsheet. Manually one can add any number of charts but while using openpyxl module I could only add one chart, when I try to add more than one chart its not showing up in the chartsheet, only thing i can see is my old graph which I just added at...
<p>I was just looking for some openpyxl solutions, their site lacks a lot of information if you compare it against xlswriter. The problem with xlswriter is that it can't open excel files, just create new ones.</p> <p>And even that this question is old, I would like to answer it in case anybody else comes looking for an...
python-3.x|pandas|openpyxl|xlsxwriter
0
13,136
60,013,547
using pandas, trying to get to a .describe in a for loop
<pre><code>cols = ['date_crawled', 'ad_created', 'last_seen'] for v in cols: autos[cols].value_counts(normalize=True, dropna=False).describe() </code></pre> <p>dataset = autos.</p> <p>want to do on each of the three columns:</p> <pre><code>{.value_counts(normalize=True, dropna=False).describe()} </code></pre> ...
<pre><code>cols = ['date_crawled', 'ad_created', 'last_seen'] [print (autos[v].value_counts(normalize=True, dropna=False).describe()) for v in cols] </code></pre> <p>Does this work for you?</p>
python|pandas|jupyter-lab
0
13,137
65,122,027
Using Pandas in Python on datasets too large for excel
<p>I had a quick application question on using pandas in python to analyze large excel sheets.</p> <p>For data that have millions of rows (beyond Excel's limit), how can we deal with analyzing them through pandas?</p> <p>I know excel lets you load data from a text file and have your excel spreadsheet &quot;create a con...
<p>I think getting files via small chunks can make the process efficient. Please look at this <a href="https://stackoverflow.com/questions/11622652/large-persistent-dataframe-in-pandas/12193309#12193309">link</a></p>
python|excel|pandas|sas
0
13,138
65,115,189
TypeError: nlargest() got an unexpected keyword argument 'columns'
<p>I am writing a python script to return the top 5 rows of a dataframe using the pandas <code>nlargest()</code> method. In its documentation seen <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nlargest.html" rel="nofollow noreferrer">here</a> , it states that it can take <code>col...
<p>After doing some more researching, I have discovered that the function <code>nlargest()</code> is different if you're calling it on a series or a dataframe. I have found what has caused this slight discrepancy.</p> <p>When the <code>else:</code> statement is run, the list <code>vehicles</code> is passed and put into...
python|pandas
0
13,139
49,793,349
How can I generate random numbers given I have probability of varous ranges specified in python
<p>I want to fill in the dummy data of attendance. I want that,for example, 60% students have attendance in the range of 70-100,25% in the range of 40-60 and 15% in the range of 0-40. How can I generate this using random numbers in Python. Is there any inbuilt function for this? I know that numpy.random.choice allows t...
<p>If you know the number N of students, you can take</p> <pre><code>N_ha = int(N * 0.6) # students with high attendance N_la = int(N * 0.15) # students with low attendance N_aa = N - ha - la # students with average attendance att_ha = np.random.random(N_ha) * 0.3 + 0.7 # this creates N_ha attendances in the half...
python-3.x|numpy|random|probability
0
13,140
49,869,142
How to aggregate data by historical time series values in python dataframe?
<p>I have a data frame like this,</p> <pre><code>import pandas as pd d = {'ID':["A","A","A","A","A","A","A","A","A","A","A","A"], 'date':["2017-01-01","2017-01-01","2017-01-01","2017-01-02","2017-01-02","2017-01-02","2017-01-03","2017-01-03", "2017-01-03","2017-01-04","2017-01-04","2017-01-04"], 't...
<p>IIUC, let's try this:</p> <pre><code>df.set_index(['ID','time','date'])['value']\ .unstack([0,1])\ .rolling(len(df),min_periods=1)\ .mean().shift(1).bfill()\ .unstack().rename('avg')\ .to_frame()\ .join(df.set_index(['ID','time','date']))\ .reset_index().sort_values(['ID','date','time']) </code></pre>...
python|pandas|numpy|dataframe
2
13,141
50,204,902
install pandas in python 3.7
<p>I can´t install pandas for python 3.7 windows 10 this is the message</p> <pre><code>C:\Users\PATRICIO\AppData\Local\Programs\Python\Python37\Scripts&gt;pip3 install pandas Collecting pandas Using cached https://files.pythonhosted.org/packages/08/01/803834bc8a4e708aedebb133095a88a4dad9f45bbaf5ad777d2bea543c7e/pand...
<p>Supported version list update as of 06 July 2018:</p> <blockquote> <p>Officially Python 2.7, 3.5, 3.6, and 3.7</p> </blockquote> <hr> <p>From the Current <a href="http://pandas.pydata.org/pandas-docs/stable/install.html#python-version-support" rel="nofollow noreferrer">DOCS</a>:</p> <h3>Python version support<...
python|python-3.x|pandas
3
13,142
50,029,027
Tensorflow different dropout configuration for one gradient update
<p>I am trying to implement the PI-Model for Semi-Supervised learning introduced in [1].</p> <p>To calculate the loss function, two forward passes through the network with the same data are needed, whereby in each forward pass the data is modified using stochastic augmentation. Additionally, dropout is used, and in e...
<p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/split" rel="nofollow noreferrer"><code>tf.split()</code></a> to split the batch into two halves, feed each half through a <a href="https://www.tensorflow.org/api_docs/python/tf/layers/dropout" rel="nofollow noreferrer"><code>tf.layers.dropout()</code...
python|tensorflow|keras
0
13,143
50,101,752
Optimizing groupby.apply with own function
<p>Let me start with a litle bit of context.</p> <p>I have <code>Spheres</code>, a large pandas DataFrame with positions and radius of multiple spheres during time.</p> <p>The spheres are grouped using a label. Multiple spheres can share the same label, and the same sphere can have multiple label through time.</p> <...
<p>Your dataframe is of mixed <code>dtype</code> and therefore I expect <code>group.values</code> to be expensive.</p> <p><a href="https://stackoverflow.com/a/41008334/2336654">See An Old Question Of Mine</a></p> <p>Instead, grab <code>x</code>, <code>y</code>, <code>z</code>, <code>r</code> directly from the datafra...
python|pandas
1
13,144
49,816,616
"import tensorflow as tf" fails on Windows 10 with gpu
<p>I've installed Python 3.6.5, and "pip3 install --upgrade tensorflow-gpu" succeeded. Then "import tensorflow as tf" gives the following error:</p> <pre><code> Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in &lt;mod...
<ol> <li>(Clean?) Install <a href="https://www.anaconda.com/download/" rel="nofollow noreferrer">Anaconda</a></li> <li>Using <em>Anaconda's Navigator</em>, create a new environment (I call it Tensorflow).</li> <li>In this new environment, search for and install Tensorflow gpu. (This will install package dependencies.)<...
python|tensorflow
0
13,145
49,820,329
Gfortran can't compile NumPy
<p>I'm working on a Raspberry-based project that needs SciPy, NumPy and scikit-learn. And we need to package our virtual environment in a .deb for distribution. For that, we use dh_virtualenv, which up until now has worked just fine.</p> <p>When I just install our requirements on the venv, like so:</p> <pre><code>myv...
<p>TL;DR: Use piwheels.</p> <p>I have suffered a lot trying to solve this and basically I had given up until I found piwheels.</p> <p>It's reasonably up to date, maybe youll get scipy 1.0.0 instead of 1.0.1 but really, who cares. It'll also substantially reduce the time it takes to package your venv.</p> <p>Simply o...
python|numpy|scipy|fortran|gfortran
1
13,146
63,953,285
Join two columns of dictionaries in Pandas
<p>I have a dataframe with two columns. Each column has a dictionnary, as such:</p> <pre><code>import pandas as pd df = pd.DataFrame([[{'a': 'one', 'b': 'two'}, {'c': 'three', 'd': 'four'}], [{'a': 'five', 'b': 'six'}, {'c': 'seven', 'd': 'eight'}]], columns=list('AB')) </code></pr...
<p>Here's one approach using <a href="https://python-reference.readthedocs.io/en/latest/docs/operators/dict_unpack.html" rel="nofollow noreferrer">dictionary unpacking</a>:</p> <pre><code>pd.Series(({**a,**b} for a,b in df.to_numpy().tolist()), name='A') 0 {'a': 'one', 'b': 'two', 'c': 'three', 'd': 'f... 1 {'a'...
python|pandas|dataframe|dictionary
1
13,147
63,758,361
How to sort multiple columns with different orders in pandas?
<p>How do I sort a data frame using multiple columns such that each column is sorted in different order? For example, the primary sort key is column 'A' in ascending order and secondary sort key is column 'B' in descending order.</p>
<p>The method <a href="https://techblog.bozho.net/tips-for-identifying-and-debugging-problems/" rel="nofollow noreferrer">df.sort_values</a> has a parameter <code>ascending</code> wich can be a boolean or a list of booleans.</p> <pre><code>df.sort_values(['A', 'B'], ascending=[True, False], inplace=True) </code></pre>
pandas
0
13,148
46,941,152
Calculating interest rates in numpy
<p>Hopefully this is a quick and easy question that is not a repeat. I am looking for a built in numpy function (though it could also be a part of another library) which, given an original loan amount, monthly payment amount, and number of payments, can calculate the interest rate. I see numpy has the following functio...
<p>You want <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.rate.html#numpy.rate" rel="nofollow noreferrer"><code>numpy.rate</code></a> from <a href="https://numpy.org/numpy-financial/" rel="nofollow noreferrer">numpy_financial</a>.</p> <p>An example usage: suppose I'm making 10 monthly payme...
python|numpy
9
13,149
62,954,034
Assigning "n" to the total number of words detected
<p>For a current project, I am planning to count the total number of words in a given Pandas DataFrame. The code below is based on SciKit-Learn and assigns a frequency to each word identified but requires to define the total quantity <code>n</code> of words considered.</p> <p>I am however looking to count the total num...
<p>If I understand your purpose correctly, the following return statement should do the job. You don't need to use <code>n</code> at all.</p> <p>Change this line</p> <pre><code>return words_freq[:n] </code></pre> <p>to this</p> <pre><code>return {'total_words': sum(frequency for word, frequency in words_freq)} </code><...
python|pandas|dataframe|nlp
1
13,150
67,799,160
Export rows from dataframe which contain special characters
<p>I have a data frame in which some rows contains special characters, i want to extract all rows which contains special characters in all columns.</p> <p>input:</p> <pre><code>**OWNERID ACCOUNT ID FIRST NAME LAST NAME MAILING COUNTRY** 3244323 gfdg9487589dffgjdskj adc FERRE France ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>DataFrame.select_dtypes</code></a> for select <code>object</code> columns (obviously strings) and test for punctation without spaces with regex in <a href="http://pandas.pydata....
python|pandas|dataframe
1
13,151
67,648,033
Mean squared logarithmic error using pytorch
<p>hello I'm new with <code>PyTorch</code> and i would like to use Mean squared logarithmic error as a loss function in my neural network for training my DQN agent but i can't find the MSLE in the <code>nn.functional</code> in <code>PyTorch</code> what the best way to implement it ?</p>
<p>well is not hard to do it the MSLE equation as the photo below shows <a href="https://i.stack.imgur.com/hGAAY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hGAAY.jpg" alt="enter image description here" /></a></p> <p>now, as some user on the PyTorch <a href="https://discuss.pytorch.org/t/rmsle-lo...
pytorch
2
13,152
67,640,297
Can i not call directly a function on pandas dataframe?
<p>I am new to learning pandas and have just learned python so my question may look silly. I created a function to change null values in a dataset. and i tried to call that function on few columns of my dataframe.</p> <pre><code>def impute_age(cols): age = cols[0] pclass = cols[1] if pd.isnull(Age): ...
<p>I'd use it like</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np def impute_age(age, pclass): if pd.isnull(age): if pclass == 1: return 37 elif pclass ==2: return 29 else: return 23 else: return age...
python|pandas|dataframe|numpy|data-science
0
13,153
68,013,864
Bin the pandas data frame horizontally with bins=0.2 (fraction), how should I go about it?
<p>I want to bin the data horizontally in a color-magnitude plane of stars. Here is how my data (red giant stars) look like: <a href="https://i.stack.imgur.com/gM1Mz.png" rel="nofollow noreferrer">RGB stars in my sample</a></p> <p>Now, I want to bin these stars in small bins (bins = 0.2 or 0.3) horizontally i.e. parall...
<p><code>bins</code> is specifying the number of bins that you want to use. Therefore it has to be an integer. Looking at your data, bins of size <code>0.2</code> would give about 15 bins. You can specify this in 2 ways:</p> <p>I’m starting with random values that somewhat look like your <code>f814w</code> series:</p> ...
python|pandas|statistics|binning
0
13,154
31,888,624
Calculating distances on grid
<p>I have a 10 x 10 grid of cells (as a numpy array). I also have a list of 3 points on that grid. For each cell on the grid, I need to find the closest of the three points. I can do this in series of nested loops in python (2.7) which works but is slow (especially if I upscale to larger grids) but I suspect there i...
<p>The simplest way I know of to calculate the distance between two points on a plane is using the Pythagorean theorem.</p> <p>That is, picture a right angle triangle where the hypotenuse goes between the two points and the base of the triangle is parallel to the x axis and the height is parallel to the y axis. We the...
python|python-2.7|numpy|grid|distance
0
13,155
41,230,512
How can I visualize a function value in 3d?
<p>Suppose I have some function, which maps 3 coordinates <code>(x,y,z)</code> to some real number.</p> <p>How can I visualize the function values on a surface like a sphere?</p> <p>Ideally, I would map the function's value to a color, and then color the sphere accordingly.</p> <p>Here is my code to generate a spher...
<p>The documentation for <code>surface_plot</code> lists the option <code>facecolors</code>. There is a example that alternates between two colors but you can pass any matplotlib color, including and array of RGB values.</p> <p>You need to do the mapping yourself from x, y, z to F(x, y, z) to "color", then convert F t...
python|numpy|matplotlib
1
13,156
27,471,459
Converting list to numpy array issues
<p>Using python xy's spyder code editor.</p> <p>When saving a list of pixel color values to a numpy array using np.asarray(list), it gives me an array with weird dimensions.</p> <p>The dimensions of the original image being read is (864,1089) (width,height) and is a JPEG image. When converting this list to a numpy a...
<p>Try to see what <code>pix[0,0]</code> contains for example:</p> <pre><code>&gt;&gt;&gt; img = Image.open('./edgewalker-cat.png') &gt;&gt;&gt; pix = img.load() &gt;&gt;&gt; pix &lt;PixelAccess object at 0x7f1afac932f0&gt; &gt;&gt;&gt; pix[0,0] (0, 0, 0) </code></pre> <p>Its tuple, size of 3, so the <code>pixels</co...
python-2.7|numpy
1
13,157
61,432,044
How to compute daily mean values for each column in pandas?
<p>I have a dataframe (df) with hourly reading of certain pollutants, from 2001 up to 2018. The df has the following info:</p> <pre><code> date O_3 NO_2 SO_2 PM10 PM25 CO 0 2001-01-01 01:00:00 7.86 67.120003 26.459999 32.349998 12.505127 0.45...
<p>Convert <code>date</code> column into a pandas <code>datetime</code> column. Then, group on the <code>year</code> and <code>day</code> part ignoring the <code>hour</code> part to get the <code>mean</code>:</p> <pre><code>In [663]: times = pd.to_datetime(df['date']) In [662]: df.groupby([times.dt.year, times.dt.day]...
python|pandas|dataframe|data-science
3
13,158
68,799,478
CSV data preprocess
<p>I have a .csv file like this format</p> <p><a href="https://i.stack.imgur.com/KVs1g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KVs1g.png" alt="enter image description here" /></a></p> <p>Then I want to convert it to</p> <p><a href="https://i.stack.imgur.com/J0hnf.png" rel="nofollow noreferrer...
<p>If you load it then you will have <code>DataFrame</code> like</p> <pre><code> Y M 1 2 3 0 2019 1 A E H 1 2020 2 B F I 2 2021 3 C G J </code></pre> <p>Set multi-index usinig <code>year</code> and <code>month</code></p> <pre><code>df = df.set_index(['Y','M']) </code></pre> <pre><code> 1 ...
python|pandas|csv
0
13,159
68,515,734
How do I delete columns that contain a zeros value in Pandas?
<p>I want to retain only non zero columns</p> <p>df:</p> <pre><code>Names Henry Adam Rachel Jug Jesscia Robert 54 0 0 6 5 Dan 22 31 0 0 55 </code></pre> <p>Expected output:</p> <pre><code>Names Henry Jesscia Robert 54 ...
<p>Try:</p> <pre><code>df.loc[:,~df.eq(0).any()] </code></pre> <p>OR</p> <p>as suggested by <a href="https://stackoverflow.com/users/7175713/sammywemmy"><code>@sammywemmy</code></a></p> <pre><code>df.loc[:, df.ne(0).all()] </code></pre> <p>Other possible solutions:</p> <pre><code>df.mask(df.eq(0)).dropna(axis=1) #OR df...
python|python-3.x|pandas|dataframe
5
13,160
68,492,551
How to calculate total running hours/ minutes/seconds of timestamps in a python pandas series?
<p>I have a Dataframe with start and stop times of a motor. My end goal is to calculate how many total minutes, hours or seconds my motor has been running. I've been able to calculate the elapsed time by subtracting stop from start time and put them in a new column ELAPSED_TIME. Now I'm having difficulties getting the ...
<p>If you're going to do further computation on datetimes/timedeltas it's best to leave them in the correct type until the end as <code>str</code> type data will not behave as desired:</p> <pre><code># Convert START and STOP to_datetime if not already df['START'] = pd.to_datetime(df['START']) df['STOP'] = pd.to_datetim...
python|pandas|datetime
1
13,161
68,786,004
How do I iterate through a DataFrame column to count the number of occurrences of a substring within a string?
<p>I have a pandas dataframe of scraped tweet information. It looks a bit like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>created_at</th> <th>full_tweet</th> </tr> </thead> <tbody> <tr> <td>2020-20-22</td> <td>&quot; All square in Austria. \n\n #UEL &quot;</td> </tr> <tr> <td>202...
<p>I don't know if this is what you are looking, but just what i see from your post and understood..</p> <p><strong>DataFrame:</strong></p> <pre><code>print(df) created_at full_tweet 0 2020-20-22 &quot; All square in Austria. \n\n #UEL &quot;. 1 2020-10-22 &quot...
python|pandas|string|dataframe|count
0
13,162
68,847,007
Numpy - create a summary df from array
<p>I have a 2d array of 20,10, values ranging from 0 to 12 (created from a dataframe).</p> <pre><code>arr = np.random.choice(np.arange(0, 13), size=(20,10)) array([[0, 9, 9, 7, 6, 2, 6, 4, 4, 3], [0, 2, 1, 7, 1, 0, 2, 6, 6, 2], [7, 3, 9, 8, 9, 7, 1, 10, 4, 2], [0, 7, 0, ...
<p>If you use a Counter from collections library you can solve it like this</p> <pre><code>import numpy as np from collections import Counter max_number = 12 np.random.choice(np.arange(0, max_number+1), size=(20,10)) index = np.array(list((i, i+1) for i in range(array.size-1))) counter = Counter(map(tuple, tuple(ar...
python|numpy
1
13,163
36,383,821
Pandas dataframe apply function to column strings based on other column value
<p>I would like to remove all instance of the string in col 'B' from col 'A', like so:</p> <pre><code>col A col B col C 1999 toyota camry camry 1999 toyota 2003 nissan pulsar pulsar 20013 nissan </code></pre> <p>How would I do this using pandas? If it was a fixed value (non-dependent o...
<p>Given a <code>DataFrame</code> of:</p> <pre><code>df = pd.DataFrame( { 'A': ['1999 toyota camry', '2003 nissan pulsar'], 'B': ['camry', 'pulsar'] } ) </code></pre> <p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html#pandas.DataFrame.apply" ...
python|pandas
9
13,164
36,291,437
Scrape a website with interactive buttons
<p>I am totally new into scraping a website. I am trying to download the tables from <a href="https://www.ssa.gov/oact/NOTES/as120/LifeTables_Tbl_7.html" rel="nofollow">https://www.ssa.gov/oact/NOTES/as120/LifeTables_Tbl_7.html</a></p> <p>The way we use the website is to select a year from the button and press "Go", ...
<p><code>https://www.ssa.gov/oact/NOTES/as120/LifeTables_Tbl_7_**1950**.html</code></p> <p><code>https://www.ssa.gov/oact/NOTES/as120/LifeTables_Tbl_7_**2030**.html</code></p> <p>Like you see the only thing that changes is the year. So when you go to scrape a website. you need to scrape <code>https://www.ssa.gov/oact...
python|pandas|web-scraping
1
13,165
36,491,612
Weird behavior when squaring elements in numpy array
<p>I have two numpy arrays of shape (1, 250000):</p> <pre><code>a = [[ 0 254 1 ..., 255 0 1]] b = [[ 1 0 252 ..., 0 255 255]] </code></pre> <p>I want to create a new numpy array whose elements are the square root of the sum of squares of elements in the arrays <code>a</code> and <code>b</code>, but I am n...
<p>Presumably your arrays <code>a</code> and <code>b</code> are arrays of unsigned 8 bit integers--you can check by inspecting the attribute <code>a.dtype</code>. When you square them, the data type is preserved, and the 8 bit values overflow, which means the values "wrap around" (i.e. the squared values are modulo 25...
python|arrays|numpy|sqrt
7
13,166
53,281,053
counting the values in multiple columns at once
<p>I have a dataframe,df as below</p> <pre><code>Index DateTimestamp a b c 0 2017-08-03 00:00:00 ta bc tt 1 2017-08-03 00:00:00 re 3 2017-08-03 00:00:00 cv ma 4...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>dt.floor</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>date</code></a> for remove times with <a hr...
python-3.x|pandas
1
13,167
53,298,352
Open csv file with Pandas and delete if has only 1 row
<p>I have a task to create a script to ssh to list of 10 cisco routers weekly and check for config changes and send notification. So i have in place the script that logs and run the command and send it to csv. I have modified so if there is not changes all I have in the csv will be for example: rtr0003# -which is the ...
<pre><code>import os import glob import csv files = glob.glob('*.csv') for file in files: with open(file,"r") as f: reader = csv.reader(f,delimiter = ",") data = list(reader) row_count = len(data) if row_count == 1: os.remove(file) </code></pre>
python|pandas|opencsv
1
13,168
65,900,198
Is there a C++ equivalent to np.frombuffer?
<p>I'm reading some data from a radar through a simple STM32 blue pill MCU. I have some code examples written i Python and Matlab and translating it into C++.</p> <p>One thing I can't get working correctly is the following bit. The Python code:</p> <pre><code>TDAT_Distance = np.frombuffer(com_obj.read(2), dtype=np.uint...
<p>If the read returns (a pointer to) bytes that are properly aligned and match the endianness of your system, you can <code>reinterpret_cast&lt;uint16_t *&gt;(com_obj.read(sizeof(uint16_t)));</code>.</p> <p>That might not be likely, so you can instead construct an <code>uint16_t</code> with the right value</p> <pre><c...
python|c++|arrays|numpy
0
13,169
65,719,501
Filtering based on two date columns in pandas
<p>I'm trying to filter out all rows that hold wage data that were earned before the end date of a training. So basically I only want wages with a wage period greater than or equal to the end date. When I run the python similar to below it is removing too many fields. I'm confused why this isn't working</p> <pre><code>...
<p>May be you should convert the date (eg. '10/1/2020') to datetime, or change the format of the date if the type is String (eg. '2020/10/1').</p> <p>Try this:</p> <pre><code>df['wage period'] = pd.to_datetime(df['wage period'], format='%m/%d/%Y') df['end date'] = pd.to_datetime(df['end date'], format='%m/%d/%Y') df = ...
python|pandas|datetime
1
13,170
21,352,129
matplotlib creating 2D arrays from 1D arrays - is there a nicer way?
<p>I am trying to visualise some 3d data I have using matplotlibs contour plots, surface plots and wireframe plots. </p> <p>my raw data is in the form of a numpy array with x,y and z each in their own column (e.g.):</p> <p>| xs | ys | zs |<br> |---|---|----|<br> | 1 | 1 | 3 |<br> | 2 | 1 | 4 |<br> | 3 | 1 | 2 |<b...
<p>If your data is like the one you gave in the example, you already have a mesh (you have a value of z for each pair (x,y)) and you only need to reshape the arrays:</p> <pre><code>cols = np.unique(xs).shape[0] X = xs.reshape(-1, cols) Y = ys.reshape(-1, cols) Z = zs.reshape(-1, cols) </code></pre>
python|arrays|numpy|matplotlib
3
13,171
63,353,328
remove words from table index
<p>I have a table index looks like that:</p> <pre><code>k__Bacteria;p__Spirochaetes k__Bacteria;p__Acidobacteria k__Bacteria;p__Actinobacteria k__Bacteria;p__Armatimonadetes ........... </code></pre> <p>I want to delete every word that come before the &quot;<em>&quot; ('k_Bacteria;p</em>') So that I have only the words...
<p>If need working with index values use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split</code></a> and select last values by indexing <code>[-1]</code>:</p> <pre><code>print (df) col k__Bacteria;p...
python|pandas
1
13,172
63,474,669
How does the model know what my data is labeled as?
<p>I have a piece of code here:. <br/> I want to know how the model knows how pictures are labeled. <br/></p> <p>I don't find any labeling function in the code and the dog-cat data directories are just full of images. I would like to solve the problem here so that I use this model for a different dataset. Just don't ...
<p>From the <a href="https://keras.io/api/preprocessing/image/" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p><strong>Arguments</strong></p> <p><strong>labels</strong>: Either &quot;inferred&quot; (labels are generated from the directory structure), or a list/tuple of integer labels of the same size ...
python|tensorflow|deep-learning
0
13,173
63,727,261
How to convert a Tensor with shape (None, 512) into a Tensor with shape (None, 12, 12, 512)
<p>I'm using Python 3.7.7., Tensorflow 2.1.0 and Functional Api to define an encoder with this summary:</p> <pre><code>Model: &quot;encoder&quot; _________________________________________________________________ Layer (type) Output Shape Param # ==========================================...
<p>You can use a Lambda layer:</p> <pre><code>import tensorflow as tf inputs = tf.random.uniform((100, 512),0, 1, dtype=tf.int32) layer = tf.keras.layers.Lambda(lambda x: tf.tile(tf.reshape(x, (100, 1, 1, 512)), (1, 12, 12, 1))) print(layer(inputs).shape) </code></pr...
python|tensorflow|keras
1
13,174
63,358,768
Why is there no pooler layer in huggingfaces' FlauBERT model?
<p>BERT model for Language Model and Sequence classification includes an extra projection layer between the last transformer and the classification layer (it contains a linear layer of size <code>hidden_dim x hidden_dim</code>, a dropout layer and a <code>tanh</code> activation). This was not described in the paper ori...
<p>Pooler is necessary for the next sentence classification task. This task has been removed from Flaubert training making Pooler an optional layer. HuggingFace commented that &quot;pooler's output is usually not a good summary of the semantic content of the input, you’re often better with averaging or pooling the sequ...
bert-language-model|huggingface-transformers
2
13,175
21,429,261
Array conversion using scikit-image: from integer to float
<p>I am facing some kind of problem when converting an integer image to a float image using scikit-image. </p> <p>This is an example (the image is a 2 pixel image):</p> <pre><code>from numpy import array,uint8; import skimage; rgb = array([array([[0,0,0],[0,0,5]])]) i1 = skimage.img_as_float(rgb)#rgb.dtype -&gt;dty...
<p><code>img_as_float()</code> is not just type conversion, it convert full unsigned integer range to [0, 1], full signed integer range to [-1, 1].</p> <ul> <li>i1, the dtype is int32, means convert [-2147483648, 2147483647] to [-1, 1]</li> <li>i2, the dtype is uint8, means convert [0, 255] to [0, 1]</li> <li>i3, beca...
numpy|type-conversion|scikit-image
4
13,176
29,853,322
find stretches of Trues in numpy array
<p>Is there a good way to find stretches of Trues in a numpy boolean array? If I have an array like:</p> <pre><code>x = numpy.array([True,True,False,True,True,False,False]) </code></pre> <p>Can I get an array of indices like:</p> <pre><code>starts = [0,3] ends = [1,4] </code></pre> <p>or any other appropriate way t...
<p>You can pad <code>x</code> with Falses (one at the beginning and one at the end), and use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html" rel="noreferrer">np.diff</a>. A "diff" of 1 means transition from False to True, and of -1 means transition from True to False.</p> <p>The conventio...
python|arrays|numpy|boolean
10
13,177
53,507,276
Filling NaN values based on values of row and column
<p>I have the following dummy dataframe:</p> <pre><code>City Longitude Latitude new mexico 1.94 2.34 berlin 2.44 5.33 london 1.1 2.44 new mexico nan nan tokyo 2.2 3.3 berlin nan nan new york 2.5 1.44 dakota ...
<p>You can sort by your <code>Longitude</code> and <code>Latitude</code> columns so that <code>NaN</code>s are at the bottom, then use <code>groupby</code> and <code>ffill</code>, finally re-sorting by your index:</p> <pre><code>df.sort_values(['Longitude', 'Latitude']).groupby('City').ffill().sort_index() C...
python|pandas
2
13,178
53,389,664
Python pandas data frame reshape
<p>The data shown below is an simplified example. The actual data frame is 3750 rows 2 columns data frame. I need to reshape the data frame into another structure.</p> <pre><code>A A2 0.1 1 0.4 2 0.6 3 B B2 0.8 1 0.7 2 0.9 3 C C2 0.3 1 0.6 2 0.8 3 </code></pre> <p>How can I reshape above...
<p>You can reshape your data and create a new dataframe:</p> <pre><code>cols = 6 rows = 4 df = pd.DataFrame(df.values.T.reshape(cols,rows).T) df.rename(columns=df.iloc[0]).drop(0) A B C A2 B2 C2 1 0.1 0.8 0.3 1 1 1 2 0.4 0.7 0.6 2 2 2 3 0.6 0.9 0.8 3 3 3 </code></pre>
python|pandas
2
13,179
53,518,331
Python/Pandas - confusion around ARIMA forecasting to get simple predictions
<p>Trying to wrap my head around how to implement an ARIMA model to produce (arguably) simple forecasts. Essentially what I'm looking to do is forecast this year's bookings up until the end of the year and export as a csv. Looking something like this:</p> <pre><code>date bookings 2017-01-01 438 2017-01-0...
<p>Here are some thoughts:</p> <ul> <li>Understanding the train/test subsets. Correct me if I'm wrong but the Train set is used to train the model and produce the 'predictions' data and then the Test is there to compare the predictions against the test?</li> </ul> <p>Yes that is correct. The idea is the same as any M...
python|pandas|forecasting|arima
2
13,180
20,078,794
DSP - get the amplitude of all the frequencies
<p>this question is related to : <a href="https://stackoverflow.com/questions/20057831/dsp-audio-processing-squart-or-log-to-leverage-fft">DSP : audio processing : squart or log to leverage fft?</a></p> <p>in which I was lost about the right algorithm to choose.</p> <p>Now,</p> <h1>Goal :</h1> <p>I want to get all the ...
<p>Mathematically Fourier Transform returns complex values as it is transform with the function <code>*exp(-i*omega*t)</code>. So the PC gives you spectrum as a complex number corresponding to the cosine and sine transforms. In order to get the amplitude you just need to take the absolute value: <code>np.abs(spectrum)<...
python|audio|numpy|signal-processing|fft
2
13,181
15,904,727
Python regex for following find and replace in string
<p>I am trying to load large text data with to numpy arrays. Numpy's loadtxt and genfromtxt didn't work for as , </p> <ul> <li>first, I need to remove the comment lines starting with delimiters <code>['#','!','C']</code></li> <li>second, there is a repeat pattern in data in forms of <code>n*value</code> where <code>n<...
<h2>Pythonic way</h2> <p>Use python's awesome functional features and list comprehension instead:</p> <pre><code>#!/usr/bin/env python lines = ['1 2 3*2.5 3 6 1*.3 8 \n', '! comment here\n', '1*1 2.0 2*2.1 3 6 0 8 \n'] #filter out comments lines = [line for line in lines if line.strip() != '' and line.strip()[0] n...
python|regex|numpy
1
13,182
15,598,867
extract value of a numeric array function in numpy
<p>If I define a function whit two array, for instance like this:</p> <pre><code>from numpy import * x = arange(-10,10,0.1) y = x**3 </code></pre> <p>How can I extract the value of y(5.05) interpolating the value of the two closer point y(5) and y(5.1)? Now if I want find that value, I use this method:</p> <pre><cod...
<p>There's a function for this in numpy/scipy..</p> <pre><code>import numpy as np np.interp(5.05, x, y) </code></pre>
python|numpy
4
13,183
18,805,426
HDFStore error appending - "Cannot serialize the column"
<p>I have a dataframe, df:</p> <pre><code> datetime bid ask bidvolume askvolume 0 2007-03-30 21:00:00.332000 1.9682 1.9678 4 0.8 </code></pre> <p>Trying to append this to a new datastore. The datastore does not exist so I use the following to create and append the...
<p><em>Please note: the following method <code>convert_objects()</code> is now deprecated and may not work</em> Call <code>DataFrame.convert_objects()</code>:</p> <pre><code>df = DataFrame(randn(10, 1), dtype=object).convert_objects() df.to_hdf('/tmp/blah.h5', 'df', append=True) </code></pre> <p>It might be worth che...
python|pandas
5
13,184
22,002,114
Hierarchical / Multi-index operations in Pandas
<p>Say I have a multi-index dataframe like the following:</p> <pre><code> A B C X Y bar one -0.007381 -0.365315 -0.024817 two -1.219794 0.370955 -0.795125 baz one 0.145578 1.428502 -0.408384 two -0.249321 -0.292967 -1...
<pre><code>In [87]: df.loc[df['A'].groupby(level='X').idxmax(), 'A'] Out[87]: X Y bar one -0.007381 baz four 0.210000 foo two 1.314373 qux one 0.716789 Name: A, dtype: float64 </code></pre> <hr> <p>To find the median <em>values</em>, you could use </p> <pre><code>df['A'].groupby(level='X').m...
python|pandas
3
13,185
55,235,212
model.summary() can't print output shape while using subclass model
<p>This is the two methods for creating a keras model, but the <code>output shapes</code> of the summary results of the two methods are different. Obviously, the former prints more information and makes it easier to check the correctness of the network.</p> <pre class="lang-py prettyprint-override"><code>import tensor...
<p>I have used this method to solve this problem, I don't know if there is an easier way.</p> <pre><code>class subclass(Model): def __init__(self): ... def call(self, x): ... def model(self): x = Input(shape=(24, 24, 3)) return Model(inputs=[x], outputs=self.call(x)) if ...
python|tensorflow|keras|tf.keras
29
13,186
55,247,739
how would I optimizing setting item in pandas
<p>Is it possible to optimize that </p> <pre><code>_df['side_diff'][_df['s'] == 0] = 0 </code></pre> <p>I have profiled the code, and this line takes a lot of time.</p> <pre><code>def diff_last_first(ser): try: return ser.iloc[-1] - ser.iloc[0] except AttributeError: return ser[-1] - ser[0] _...
<p>Use the below:</p> <pre><code>_df['side_diff']=np.where((_df['s'] == 0),0,_df['side_diff']) </code></pre>
python|pandas
1
13,187
55,360,354
Random Seed Chose Different Rows
<p>I was applying .sample with <code>random_state</code> set to a constant and after using <code>set_index</code> it started selecting different rows. A member dropped that was previously included in the subset. I'm unsure how seeding selects rows. Does it make sense or did something go wrong?</p> <p>Here is what was ...
<p>Applying .sort_index() after reading in the data and before performing .sample() corrected the issue. As long as the data remains the same, this will produce the same sample everytime.</p>
python|python-3.x|pandas|random-seed
0
13,188
56,533,453
split rows in a column and find the number of each word occurs, finding which one has the highest count using bar chart
<ul> <li>i have a dataframe</li> <li>i would like to split the string in each row, </li> <li>and find the number of each word appears, count all the words </li> <li>and make the bar chart for visualizing the highest one.</li> </ul> <p>The only thing i've done is to split the string from "[x|x|x]" into "[x,x,x]", but t...
<p>Not very elegant but this should do the work.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df_genres = pd.DataFrame({'genres': ["Action|Adventure|Science Fiction|Thriller", "Action|Adventure|Science Fiction|Thriller", "Adventure|Science Fiction|Thriller", "Action|Adventure|Science Fiction|Fan...
python|pandas
1
13,189
56,754,421
Solving a system of mass, spring, damper and Coulomb friction
<p>Consider the system below:</p> <pre> <img src="https://i.stack.imgur.com/CSKyf.png" width="500"> Fig.1 - Mass, spring, damper and Coulomb frction (image courtesy of <a href="https://commons.wikimedia.org/wiki/File:Mass-Spring-Damper.svg" rel="nofollow noreferrer">Wikimedia</a>). </pre> <p>with ...
<p>Writing the equations of such a system is not obvious. And solving it is also not easy.</p> <p>If the Python constraint can be released, I would suggest using <a href="https://www.openmodelica.org/" rel="nofollow noreferrer">OpenModelica</a> to solve this problem. In the modelica library of components, you have the ...
python|numpy|numerical-methods|ode
0
13,190
67,159,246
install tensorflow 2.3.1 with conda
<p>I recently switched my System to Ubuntu (20.04.2 LTS)</p> <p>I installed Anaconda and I want to work with spyder. now when I try to install tensorflow==2.3.1 (which I need to work with tensorflow-quantum) I get this message:</p> <p>~$ conda install tensorflow==2.3.1</p> <pre><code>Collecting package metadata (curren...
<p>I managed to get it to work, with using the base(root) environment. Unfortunately can I not get it working within my custom environment, no idea why.. I am going to stick with base then.</p>
tensorflow|ubuntu|anaconda
0
13,191
66,867,481
How Can I combine two columns is one dataframe?
<p>I have a dataset like this.</p> <pre><code>A B C A2 1 2 3 4 5 6 7 8 </code></pre> <p>and I want to combine A and A2.</p> <pre><code>A B C 1 2 3 5 6 7 4 8 </code></pre> <p>how can I combine two columns? Hope for help. Thank you.</p>
<p>I don't think it is possible directly. But you can do it with a few lines of code:</p> <pre><code>df = pd.DataFrame({'A':[1,5],'B':[2,6],'C':[3,7],'A2':[4,8]}) df_A2 = df[['A2']] df_A2.columns = ['A'] df = pd.concat([df.drop(['A2'],axis=1),df_A2]) </code></pre> <p>You will get this if you print <code>df</code>:</p>...
python|pandas|dataframe
3
13,192
66,984,809
How to check the version of NCCL
<p>I am remotely access High performance computing nodes. I am not sure about NVIDIA Collective Communications Library (NCCL) is installed in my directory or not? Is there a way to check the NCCL</p>
<p>You can try</p> <pre><code>locate nccl| grep &quot;libnccl.so&quot; | tail -n1 | sed -r 's/^.*\.so\.//' </code></pre> <p>or if you use PyTorch:</p> <pre><code>python -c &quot;import torch;print(torch.cuda.nccl.version())&quot; </code></pre> <p>Check it this link <a href="https://tech.amikelive.com/node-841/command-c...
python|tensorflow|nvidia|horovod
11
13,193
66,828,434
Convert monthly data to weekly data - Python
<p>I have a dataframe which looks like this:</p> <pre><code>ID Date Volume Sales 1 2020-02 10 4 1 2020-03 8 6 2 2019-12 6 8 2 2019-10 4 10 </code></pre> <p>Data here is monthly, and I would like to convert it to weekly.. dividing the volume and sales column by the number of weeks in t...
<p>From what I understand you can try creating an array of all weeks based on the <code>Date</code> column using <code>pd.offset</code>, then explode and <code>groupby+transform</code> to get count of each group for using it in division:</p> <pre><code>s = pd.to_datetime(df['Date']) u = (df.assign(Weeks=[pd.date_range(...
python|pandas|dataframe
1
13,194
66,970,017
I have been trying to qcut an array of values into 4 bins. I am getting the error below? How to solve this I am a beginner in Python
<p>Below is my array data: <code>wkx_old['Sales point'].values</code></p> <p>array([ 2, 2, 2, 4, 4, 3, 1, 4, 2, 1, 3, 4, 1, 1, 4, 7, 4, 1, 1, 2, 4, 3, 4, 3, 3, 2, 5, 2, 3, 2, 3, 4, 2, 10, 4, 4, 6, 3, 3, 1, 1, 2, 1, 3, 2, 4, 5, 2, 4, 3, 2, 3, 4, 3, 1, 1, 6, 3, 6, 5,...
<p><code>qcut</code> is not friendly with duplicated data and will throw an error when it sees a duplicate at splitting point. Imagine you do a <code>qcut</code> on <code>[1]*100</code>, what is the <code>50-th</code> percentile?</p> <p>You can try <code>rank(pct=True)</code> to calculate the actual percentile for the ...
python|pandas|bins
2
13,195
66,975,482
Coverting python list to smaller list or numpy array
<p>I have python lists which look like this:</p> <pre><code>[{'t': 1617632700048595399, 'y': 1617632700048396000, 'q': 1409807, 'i': '17243', 'x': 19, 's': 1, 'c': [37], 'p': 124.99, 'z': 3}, {'t': 1617632700057416219, 'y': 1617632700057000000, 'f': 1617632700057380078, 'q': 1409817, 'i': '5637...
<p>To save the data in CSV format, you can use <code>csv</code> module (<code>lst</code> is your list):</p> <pre><code>import csv with open(&quot;data.csv&quot;, &quot;w&quot;) as f_out: csvwriter = csv.writer( f_out, delimiter=&quot;,&quot;, quotechar='&quot;', quoting=csv.QUOTE_MINIMAL ) for item...
arrays|python-3.x|list|dataframe|numpy
1
13,196
68,302,777
What's the mean of tf.nn.softmax in cnn
<p>I've implemented a CNN for image classification using some tutoriels on the net, I found this function of softmax, and I didn't understand it</p> <pre><code>score = tf.nn.softmax(predictions[0]) </code></pre> <p>when I use it I found values that I didn't understand their meaning</p> <p>can anyone explain this functi...
<p>Well a softmax function is there to map your logits to a percentage, typically used in multi class classification problems, the percentage will sum up to be 1</p> <p>The function can be calculated as such</p> <pre><code>e.g [1. 0. 1.] -&gt; [0.3, 0.4, 0.3] softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axi...
tensorflow|conv-neural-network|prediction|softmax
0
13,197
68,279,166
Pandas outer join with no duplicates adds new rows
<p>I have 2 dataframes <code>preds</code> and <code>assets_to_remove</code>.</p> <p>This is how the dataframe <code>preds</code> looks:</p> <pre><code> asset_id asset_name 294771 493646671302244 queue_bar 294770 503848157271852 refactor_target 294769 786314528522899 submission_tray 2...
<p>Check datatype on asset_id on dataframes before the merge, is it int64 in both cases?</p> <p>This issue could be possible as before the merge you are comparing to numeric value 57412518735315968, if type in original dataframes is not int64, and instead is object, then your equality check will not be returning a matc...
python|pandas|dataframe|outer-join
1
13,198
68,201,188
I am trying to combine multiple rows into single rows in python/pandas
<p>I have three groups of rows right now and I am trying to combine those groups of rows into single rows. <a href="https://i.stack.imgur.com/ThDx7.png" rel="nofollow noreferrer">Current State of Data</a> (Image only shows two genes, but I promise there's a third)</p> <p>I have three separate genes, each having 61 NX v...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby()</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.mean.html" rel="nofollow noreferrer"><code>GroupBy.m...
python|pandas|dataframe
0
13,199
59,160,209
Pandas: filter dataframe by multiple conditions with column containing nan
<p>Connected to: <a href="https://stackoverflow.com/questions/59154836/pandas-add-column-with-index-of-matching-row-from-other-dataframe">Pandas: add column with index of matching row from other dataframe</a></p> <p>Matching multiple columns with corresponding columns from 2nd dataframe, and returning index of the mat...
<p>One workaround here is to simply use <code>fillna</code> to replace all <code>na</code> values with something like a <code>'NaN'</code> string.</p> <p>Simply use:</p> <pre><code>df1 = df1.fillna('NaN') df2 = df2.fillna('NaN') </code></pre> <p>Then use your existing code.</p>
python|pandas|dataframe
2