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
353,600
58,061,309
Delete rows based on the quantity of the last row in the same group
<p>I have a table like this</p> <pre><code>+---------+------------------+------+------+---------+ | Name | Task | Team | Date | Month | +---------+------------------+------+------+---------+ | John | Market study | A | 1 | Month 1 | +---------+------------------+------+------+---------+ |...
<p>Try this using <strong>groupby</strong> and <strong>filter</strong> method in pandas:</p> <pre><code>df.groupby('Month').filter(lambda g:(g['Date']&gt;1).any()) </code></pre>
python|dataframe|pandas-groupby
2
353,601
58,101,445
Keras functional API and TensorFlow Hub
<p>I'm trying to use a <a href="https://tfhub.dev/google/universal-sentence-encoder-multilingual-large/1" rel="noreferrer">Universal Sentence Encoder</a> from TF Hub as a keras layer in a functional way. I would like to use <code>hub.KerasLayer</code> with Keras Functional API, but i'm not sure how to achieve that, so ...
<p>Try This</p> <pre><code>sentence_encoding_layer = hub.KerasLayer(&quot;https://tfhub.dev/google/universal-sentence-encoder/4&quot;, trainable=False, input_shape = [], dtype = tf.string, ...
python|tensorflow|keras
3
353,602
57,875,796
Using values in 3 columns, create a new column that takes values from one of the 3
<p>I have a dataframe with 3 columns <code>candle</code>,<code>point</code> and <code>time</code>. If the candle in <code>candle</code> gets to the point,<code>b</code>,create a new column that contains the time at which candle got to the point</p> <p>I tried doing this</p> <pre><code>df = pd.DataFrame({'candle':[23...
<p>This does it:</p> <pre><code>df = pd.DataFrame({'candle':[23,22,25,23,22,23,25,25,22],'point':['a','a','a','b','b','c','b','c','a'],'time':['2019-07-05 12:22:22','2019-07-10 12:22:22','2019-07-15 12:22:22','2019-07-20 12:22:22','2019-07-25 12:22:22','2019-07-30 12:22:22','2019-07-35 12:22:22','2019-07-40 12:22:22',...
python|pandas
5
353,603
58,130,950
How to round the Timestamp to the nearest seconds?
<p>Pls help me to round this Timestamp to seconds I have the Dataframe Index is the series of the timestamp as below. How to round Index to the nearest second?</p> <pre><code>Timestamp('2019-06-16 07:53:32.961000') </code></pre> <p>Expected result</p> <pre><code>Timestamp('2019-06-16 07:53:33') </code></pre>
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.round.html" rel="nofollow noreferrer"><code>Timestamp.round</code></a>:</p> <pre><code>pd.Timestamp('2019-06-16 07:53:32.961000').round('s') # Timestamp('2019-06-16 07:53:33') </code></pre>
python|pandas
2
353,604
58,045,853
Python get previous day of week (Thursday in my example) from pandas date column
<p>I have a pandas date column and I want to return the date for the previous Thursday (could be any day of week). I use pd.offsets.Week but I do not get the expected result when the year changes and the Week starts over. Here is my dataframe as 'd':</p> <p><code>raw date Thursday week_start 0 2019-01-03 2018-12-27...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.weekday.html" rel="nofollow noreferrer"><code>Series.dt.weekday</co...
python|pandas
1
353,605
58,094,601
How to join files using string contains function in python?
<p>I have two data frames that look like this:</p> <p>df1</p> <pre><code>cleaned_transaction_data MR PRICE FNB WHK NANDOS MR PRICE CHECKERS WERNH PICK'N PAY FNB EAT-SUM-MOR-MEAT LUDERI SPAR SWAKOPMUND FNB LEGIT SWAKOP SHOPRITE KFC </code></pre> <p>df2</p> <pre><code>merchant_name description_merchant CHECKER...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>Series.str.extract</code></a> for get first values from <code>df2['merchant_name']</code> joined by <code>|</code> for regex <code>OR</code> and <code>\b\b</code> for words boundarie...
python|python-3.x|pandas
1
353,606
57,938,666
Join Count to the original DataFrame in pandas
<p>Give Data Frame as</p> <pre><code>import pandas as pd lst = ['Yes', 'No', 'Maybe', 'Yes', 'No', 'Maybe', 'Yes'] lst2 = [11, 22, 33, 44, 55, 66, 77] df = pd.DataFrame(list(zip(lst, lst2)), columns =['Name', 'val']) </code></pre> <p>I used to below to get GroupBy Count</p> <pre><code>countData=df...
<p>You can use <code>transform</code>:</p> <pre><code>df['countData'] = df.groupby("Name")["Name"].transform(lambda x: x.count()) </code></pre> <p>df:</p> <pre><code> Name val countData 0 Yes 11 3 1 No 22 2 2 Maybe 33 2 3 Yes 44 3 4 No 55 2 5 Maybe 66 2 6 Yes 77 3...
python|pandas
3
353,607
58,153,068
Pandas joining strings in a column according to consecutive values in another
<p>I have two cols in a DataFrame col1 and col2 and I need to generate result column. Every FD has few correlated MS that are supposed to be populated in the result column as shown in the fig</p> <p><a href="https://i.stack.imgur.com/EUZhS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EUZhS.png" a...
<p>You can use <code>GroupBy.agg</code>, join your strings and assign it back to the "FD" rows:</p> <pre><code>grp = (df.assign(col3=(df['col1'] == 'FD').cumsum()) .query("col1 == 'MS'") .groupby('col3')['col2'].agg('|'.join)) df.loc[df['col1'] == 'FD', 'result'] = grp.values # grp.to_numpy(); pandas...
python|pandas
3
353,608
57,761,189
pivot_table is not giving expected results
<p>df:</p> <pre><code>id flag year amt 1 'Y' 2016 100 1 'Y' 2017 200 1 'Y' 2018 100 2 NaN 2016 100 2 'Y' 2017 200 </code></pre> <p>I am pivoting on <code>year</code> and <code>amt</code>.</p> <p><strong>Expected output:</strong></p> <pre><code>id flag 2016 2017 2018 1 'Y' 100.0 200.0 100.0 ...
<p>You could use <code>set_index/unstack</code>:</p> <pre><code>In [51]: df.set_index(['id','flag','year'])['amt'].unstack('year').reset_index() Out[51]: year id flag 2016 2017 2018 0 1 Y 100.0 200.0 100.0 1 2 NaN 100.0 NaN NaN 2 2 Y NaN 200.0 NaN </code></pre> <p><a hre...
python|pandas
1
353,609
58,078,651
How to count no of rows in a data frame whose values divisible by 3 or 5?
<p>I have a data frame with two columns:</p> <pre><code> ones zeros 0 6 13 1 8 7 2 11 7 3 8 5 4 11 5 5 10 6 6 11 6 7 7 4 8 9 4 9 4 6 10 7 5 11 6 7 12 9 10 13 14 3 14 7 7 15 7 7 16 9 7 17 7 10 18 9 5 19 12 7 20 4 8 21 6 4 22 11 5 23 9 7 24 3 ...
<p>Compare modulo <code>5</code> and <code>3</code> with <code>0</code> and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="noreferrer"><code>boolean indexing</code></a> with <code>|</code> for bitwise <code>OR</code>:</p> <pre><code>df = df[(df['ones'] % ...
python|pandas|dataframe|data-analysis
7
353,610
58,099,499
How to return a subset of the DataFrame’s columns based on the column dtypes in Spark Scala
<p>I need to divide my dataset into different subsets based on the data types.</p> <p>In Pandas we can do it by df.select_dtypes, I want to implement this in Spark Scala. Can anyone please help.</p> <p>For example, below is my dataset: <a href="https://i.stack.imgur.com/mcx3n.png" rel="nofollow noreferrer">Dataset</a...
<p>There is this function <code>dtypes</code> which can help, like:</p> <pre class="lang-scala prettyprint-override"><code>import org.apache.spark.sql.functions._ //df is the DataFrame containing the input data df.dtypes.groupBy(_._2).map { case (k, v) =&gt; (k, df.select(v.map { x =&gt; col(x._1) }: _*)) } // Retu...
python|pandas|scala|apache-spark
2
353,611
58,024,644
How to have Python find files in a subfolder without hard-coding path names?
<p>I use Git VC for my Python codes, mostly scripts with scientific calculations. To parse raw data (which are also part of the repository) into Python variables, I do:</p> <pre><code>import numpy as np t_x_q_obs = np.genfromtxt('MeasuredAlgebrProductionRate_30min_18h.csv', delimiter=';') </code></pre> <p>Meanwhile, ...
<p>You could improve your code by using paths relative to your main python file like this:</p> <pre><code>import os base_path = os.path.dirname(os.path.abspath(__file__)) my_file = os.path.join(base_path, 'my_data_file.csv') # now my_file is referring to a path relative to your python script </code></pre>
python|git|numpy|filepath
1
353,612
58,076,154
Python unittest assert 2 dataframe
<p>I am working on a writing unittest for PySpark. Below is the actual function.</p> <pre><code>def get_some_timestamp(self, final_set): final_set.createOrReplaceTempView("session_data") session_df = self.spark.sql("""SELECT \ id,\ date(sent_at) as date_without_t...
<p>It seems having same datatype does not help. If we are comparing anything other than <code>String</code>, Datatype has to match exactly. So in my case, it was <code>date</code></p> <p>The way I resolved is as follows:-</p> <pre><code> expected_output_pandas_df = pd.DataFrame( { 'id':['1234','4567','123...
python|pandas|unit-testing|pyspark
1
353,613
57,986,086
tensorflow 1.13 how to use tf.searchsort safe?
<p>With code </p> <pre><code>tf.searchsorted(input, input2) </code></pre> <p>I got <strong>first error</strong></p> <blockquote> <p>InvalidArgumentError (see above for traceback): Reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero</p> </blockquote> <p...
<p>Although it is not explicitly stated, it is implied that <a href="https://www.tensorflow.org/api_docs/python/tf/searchsorted" rel="nofollow noreferrer"><code>tf.searchsorted</code></a> does not work with an empty sequence in the first parameter.</p> <p>You can however use <a href="https://www.tensorflow.org/api_doc...
python|tensorflow
1
353,614
57,916,603
Best way to bin (into categorical values), based on multiple columns
<p>I need to bin using values from two columns into another column. </p> <p>Supposed the following is my pandas df:</p> <pre><code>data = {'material':['Matl_A', 'Matl_B', 'Matl_B', 'Matl_A'], 'strength':[10, 20, 30, 100] df = pd.DataFrame(data) </code></pre> <p>So my df is:</p> <pre><code> material st...
<p>Use <code>np.select</code></p> <pre><code>a = df.material.eq('Matl_A') b = df.material.eq('Matl_B') df['grade'] = np.select([a &amp; df.strength.between(5,10), a &amp; df.strength.between(11,20), b &amp; df.strength.between(10,50), b &amp; ...
python|python-3.x|pandas|dataframe
2
353,615
57,800,651
write multiple pandas dataframe to the same txt file
<p>I'm writing a summary and I need to write multiple <code>pandas</code> data frames to the same <em>txt</em> file. <code>.to_csv</code> method can only write one data frame to a file, so I tried the following code:</p> <pre><code>f = open('summary.txt', 'w') f.write(str(df1)) f.write(str(df2)) f.write(str(df3)) f.cl...
<p>Try the following code:</p> <pre><code>with open('summary.txt', 'w') as f: f.write(df1.to_string()) f.write(df2.to_string()) f.write(df3.to_string()) </code></pre>
pandas
0
353,616
57,882,479
subset df by masking between specific rows
<p>I'm trying to subset a pandas <code>df</code> by removing rows that fall between specific values. The problem is these values can be at different rows so I can't select fixed rows. </p> <p>Specifically, I want to remove rows that fall between <code>ABC xxx</code> and the integer <code>5</code>. These values could f...
<pre><code>a = df.index[df['Val'].str.contains('ABC')==True][0] b = df.index[df['Val']==5][0]+1 c = np.array(range (a,b)) bad_df = df.index.isin(c) df[~bad_df] </code></pre> <p><strong>Output</strong></p> <pre><code> Val 0 None 8 X 9 1 10 2 </code></pre> <p>If there are more than one 'ABC' and 5, then you ...
pandas|dataframe|subset|mask
1
353,617
58,139,544
Python: Calculate 5-year rolling CAGR of values that need to be grouped from a dataframe
<p>I have a dataframe with historical market caps for which I need to compute their 5-year compound annual growth rates (CAGRs). However, the dataframe has hundreds of companies with 20 years of values each, so I need to be able to isolate each company's data to compute their CAGRs. How do I go about doing this? </p> ...
<p>Setting up a toy example:</p> <pre><code>import numpy as np import pandas as pd idx_level_0 = np.repeat([&quot;company1&quot;, &quot;company2&quot;, &quot;company3&quot;], 5) idx_level_1 = np.tile([2015, 2016, 2017, 2018, 2019], 3) values = np.random.randint(low=1, high=100, size=15) df = pd.DataFrame({&quot;value...
python|pandas|pandas-groupby|apply|rolling-computation
2
353,618
57,862,426
Plot the ratio of the standard deviation to the mean over bandwidth
<p>I wanted to reveal hard to see correlation in data via computing the ratio of the standard deviation to the mean over the given bandwidth. The window would be shifted one frequency bin to the right, and the ratio is computed again, and so on. I thought it is possible with ready function from Matplotlib or scipy libr...
<h1>Solution</h1> <p>What you are trying to calculate is a <em><strong>rolling version</strong></em> of <strong>Relative Standard Deviation</strong> (RSD), which is also known as <strong>Coefficient of Variation</strong> (CV). See <a href="https://en.wikipedia.org/wiki/Coefficient_of_variation" rel="nofollow noreferrer...
python|numpy|matplotlib|scipy|statistics
3
353,619
57,829,545
Is there a way to find the indices of an entire row of numbers in a 2D array in Python?
<p>For a 2D array, is there a command in Python like the "find" command in MATLAB? </p> <p>How do I find the location of the row [ 0.5795946 , 0.24307856, 0.56676058, 0.08502582] in a numpy array </p> <pre><code>A = array([[ 0.57383254, 0.10132767, 0.86211639, 0.35402222], [ 0.20238346, 0.93204519, 0.8...
<p>To find the index of the element in the array</p> <pre><code>import numpy as np A = np.array([[ 0.57383254, 0.10132767, 0.86211639, 0.35402222], [ 0.20238346, 0.93204519, 0.84563318, 0.68373515], [ 0.5795946 , 0.24307856, 0.56676058, 0.08502582], [ 0.27188428, 0.0630682 , 0.9762359 ,...
python|numpy|multidimensional-array
0
353,620
57,777,829
How to calculate the expanding mean of all the columns across the DataFrame and add to DataFrame
<p>I am trying to calculate the means of all previous rows for each column of the DataFrame and add the calculated mean column to the DataFrame. </p> <p>I am using a set of nba games data that contains 20+ features (columns) that I am trying to calculate the means for. Example of the dataset is below. (Note. "...." re...
<blockquote> <p>I am trying to calculate the means of all previous rows for each column of the DataFrame </p> </blockquote> <p>To get all of the columns, you can do:</p> <pre><code>df_means = df.join(df.cumsum()/ df.applymap(lambda x:1).cumsum(), r_suffix = "_mean") </code></...
python|pandas
0
353,621
57,850,257
How to get consecutive number of shots played instead of a standard cumulative sum?
<p>I have a <em>dataset</em> with details of shots played by each user in the game. It is a <em>dataset</em> of snooker so one player pots the ball and he carries on until he misses and so on. I need to calculate the highest number of <strong>continuous shots</strong> played by the player in the game. </p> <p>Here's ...
<p>You can do this:</p> <pre><code>df['Streak'] =df['Player ID'].groupby((df['Player ID'] != df['Player ID'].shift()).cumsum()).cumcount() + 1 df.head() Game_id Player ID Streak 0 5d6576aab80c990500e3ce5a 2ff211 1 1 5d6576aab80c990500e3ce5a 2ff250 1 2 5d6576aab80c990500e3ce5...
python|pandas|dataset
1
353,622
57,761,003
List of arrays without brackets
<p>Given a list of arrays in this format:</p> <pre><code>[array([[63371.29484043], [65000. ], [51114.1118643 ], [39000. ], [61549.2893635 ], [58204.43242583]]), array([[28750. ], [19166.90102574], [19667.19108884], [17250. ]]), array([[32188.01786071], [3...
<p>Try to understand the nature of the object before worrying too much about display details. Display follows from the list's structure. Pay special attention to <code>len</code> (for a list) and <code>shape</code> (for an array).</p> <pre><code>In [119]: alist=[np.array([[63371.29484043], ...: [65000. ...
python-3.x|list|numpy|numpy-ndarray
1
353,623
57,732,809
How read multiple .txt files with some missing headers and unwanted columns
<p>I am trying to read about 2000 .txt files which do not all have the same columns. I want to select only the common headers across all files and save these to a csv file to be uploaded into a MySQL database. I need help parsing these files to select only the columns I need. I only need the following columns: code, st...
<p>You can modify your regex to only match the lines that contain either of your columns names-</p> <pre><code>obj = re.compile(r'\b(code|startDate|startTime|endDate|endTime|s|number)\b') with open('words.txt', 'r') as reader: for line in reader: match = obj.findall(line) datalist.append(match) </code...
python|pandas|csv
0
353,624
57,953,688
Pandas loc and apply changes to dataframe problem .. getting error ValueError: cannot reindex from a duplicate axis
<p>I am trying to add a new column to my dataframe .. pseudo this is what I want to do. </p> <p>If value in plcg column does not equal 1, then do an equation to other columns and add the result to a new column... Probably not explained very well .. Currently this is the code I have.</p> <pre><code>formula = (df['Marg...
<p>Thanks to user anky_91 for providing an alternative to get around the index issue.</p> <pre><code>df['real_time']=np.where(df['Plcg'] != '1',formula,df['real_time']) </code></pre>
python|pandas
1
353,625
58,026,531
Trying to compare 2 excel files via python and pandas
<p>Background: I have 2 files, with few matching columns and there is a common column between them for comparison.</p> <p>Example:</p> <pre><code>Table 1 , about 10K rows | col1 | col2 | col3 | |------|------|------| | adam | key1 | def | | mike | key2 | efg | </code></pre> <pre><code>Table 2 , about 5k rows | col...
<p>IIUC, use <code>pandas.DataFrame.update</code>:</p> <p>Given:</p> <pre><code># df1 col1 col2 col3 0 adam key1 def 1 mike key2 efg # df2 col1 col2 col3 col4 0 adam key1 def abc 1 mike key2 cdf new_df = df1.set_index('col1') new_df.update(df2.set_index('col1')) new_df.reset_index(inplace=...
python|excel|pandas
0
353,626
57,897,700
Are there rules for the interaction between numpy reshape() and transpose()?
<p>I've put this question in quite a bit of context, to hopefully make it easier to understand, but feel free to skip down to the actual question.</p> <hr> <h2>Context</h2> <p>Here is the work I was doing which sparked this question:</p> <p>I'm working with an API to access some tabular data, which is effectively a...
<p>I'm not going to try to go through all your cases (for now), but here's an illustration of how reshape, transpose, and order interact:</p> <pre><code>In [176]: x = np.arange(12) In [177]: x.strides, x.shape ...
python|arrays|numpy|multidimensional-array
2
353,627
58,140,508
urlopen error [Errno 11001] getaddrinfo failed for a local drive
<p>I am trying to run a code in spyder and it throws error </p> <pre><code>" return self.do_open(http.client.HTTPConnection, req) File "C:\Users\name\AppData\Local\Continuum\Anaconda3-5.2.0\lib\urllib\request.py", line 1320, in do_open raise URLError(err) URLError: &lt;urlopen error [Errno 11001] getaddrin...
<p><code>pd.read_csv</code> is interpreting the filename as a URL, not a local path. </p> <p>You can open the file yourself, and pass the file object.</p> <pre><code>with open(os.path.join(root, fname)) as f: df = pd.read_csv(f) </code></pre>
python|pandas|urlopen|fancyurlopener
0
353,628
58,133,899
Highlight cell on condition
<p>I'm trying to highlight all cells that are before the current date. However I am highlighting all cells instead of just the old dates. </p> <pre><code>import pandas as pd from datetime import datetime #get file df = pd.read_excel(r'C:\Users\cc-621.xlsx') df # sort the data by date df['Date'] = pd.to_datetime(d...
<p>Idea is create new DataFrame filled by styles by condition with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply.html" rel="nofollow noreferrer"><code>Styler.apply</code></a>, for set rows by conditions is used <a href="https://docs.scipy.org/doc/numpy/reference...
python|pandas|jupyter
3
353,629
58,097,320
Create subclass of dataframe with multiple inheritance
<p>Hi I would like to subclass a pandas dataframe but the subclass of the dataframe will also inherit from a custom class of my own. I want to do this because I would like to make multiple subclassed dataframes, as well as other subclasses (that are not dataframes) that will share properties and methods of this base cl...
<p>You stated in the comment section <code>I've read that</code>. However, you did not. That's the source of the problem. Since <code>that</code> describes the steps to subclass pandas dataframe including ways to define original properties.</p> <p>Consider the followig modification of your code. The key part is <code>...
python|pandas|dataframe
1
353,630
57,958,641
Is there a faster way on reading, writing and saving excel files?
<p>I am new to Python. Currently I need to count the number of duplicates, delete the duplicate ones and update the duplicates occasions into a new column. Below is my code:</p> <pre><code>import pandas as pd from openpyxl import load_workbook filepath = '/Users/jordanliu/Desktop/test/testA.xlsx' data = load_workboo...
<pre class="lang-py prettyprint-override"><code>for x in range(sku.max_row): duplicate_count = 0 for i in range(x): if sku.cell(row =i + 2, column = 1).value == sku.cell(row = x + 2, column = 1).value: duplicate_count = duplicate_column[i] + 1 sku.cell(row =i+2, column = 1).val...
python|excel|pandas|multiprocessing|openpyxl
0
353,631
57,804,585
column is not getting dropped
<p>Why column A is not getting dropped in train,valid,test data frames?</p> <pre><code>import pandas as pd train = pd.DataFrame({'A': [0, 1, 2, 3, 4],'B': [5, 6, 7, 8, 9],'C': ['a', 'b', 'c', 'd', 'e']}) test = pd.DataFrame({'A': [0, 1, 2, 3, 4],'B': [5, 6, 7, 8, 9],'C': ['a', 'b', 'c', 'd', 'e']}) valid = pd.DataF...
<p>You can use <code>inplace=True</code> parameter, because <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>DataFrame.drop</code></a> function working also <code>inplace</code>:</p> <pre><code>for df in [train,valid,test]: df.drop(['A']...
python|pandas
3
353,632
57,876,043
Select multiple values from pandas dataframe
<p>I have the following dataframe:</p> <pre><code>PIC Label EncodedPixels pic1 fish True pic1 flower True pic1 gravel False pic1 sugar False pic2 fish True pic2 flower True </code></pre> <p>What i want to do is this:</p> <p>for every EQUAL value in PIC, count the labels that coexist (being the t...
<p>I believe this is what you're asking for:</p> <pre><code>df &gt;&gt;&gt; PIC Label EncodedPixels 0 pic1 fish True 1 pic1 flower True 2 pic1 gravel False 3 pic1 sugar False 4 pic2 fish True 5 pic2 flower True helper_df = df.groupby(['PIC', 'Label'...
python|pandas|dataframe|data-science
-1
353,633
57,773,199
Datetime dtype is Object not Datetime
<p>I'm trying to mean groupby a timestamp. First I've had to convert the time (string) that I've got into a datetime. After converting it datetime I've noticed that despite giving the specific format that pandas adds a date, I don't need a date. I'm working to remove this and keep only time object but I've not be succe...
<p>seems <code>groupby</code> doesn't recognize <code>timedelta64</code> as a numeric type. There are several workarounds, either with <code>numeric_only=False</code> or working with <code>total_seconds</code>.</p> <pre><code>import pandas as pd #df = pd.read_clipboard(header=None) #df[1] = pd.to_timedelta(df[1]) df...
python|pandas|datetime|pandas-groupby|python-datetime
2
353,634
58,134,704
Split a 3D numpy array into smaller 3D arrays
<p>I have a 3D np.array</p> <pre class="lang-py prettyprint-override"><code>arr = np.array([ [ [0, 205, 25], [210, 150, 30], [0, 0, 0], [1, 2, 3], [4, 5, 6], [7, 8, 9] ], [ [0, 255, 0], [255, 40, 0], [0, 0, 200], [7, 8, 9], [10, 11, 12], [120, 51, 58] ], [ [0, 0, 30], [...
<p>You can reshape and transpose it</p> <pre><code>arr.reshape(3, 3, 3, 2, 3).transpose(2, 0, 1, 3, 4) # array([[[[[ 0, 205, 25], # [210, 150, 30]], # # [[ 0, 255, 0], # [255, 40, 0]], # # [[ 0, 0, 30], # [ 0, 40, 0]]], # # # [[[ 0, 205, 25...
python|arrays|numpy
2
353,635
58,002,531
Disable Tensorflow/Numpy Deprecation Warning Messages
<p>Running my Python 3.7.4 app that uses <code>tensorflow</code> v1.14.0 causes a large list of deprecation warnings to appear. The following code clears up most of it.</p> <pre><code>try: from tensorflow.python.util import module_wrapper as deprecation except ImportError: from tensorflow.python.util import de...
<p>You can ignore all "FutureWarning" warnings by putting the following code at the beginning of your scripts (<a href="https://machinelearningmastery.com/how-to-fix-futurewarning-messages-in-scikit-learn/" rel="noreferrer">source</a>):</p> <pre><code>from warnings import simplefilter simplefilter(action='ignore', ca...
python|python-3.x|tensorflow
9
353,636
58,012,316
Voting Classifier causing casting Numpy Type Error
<p>I'm experimenting with several sklearn classifiers in a Voting Classifier for ensembling. </p> <p>To test, I have a dataframe with set of columns that represent tool skills (a numerical value from 0 to 10 representing how much the person knows about the skill) and a "Fit to Job" column that is the class variable. E...
<pre><code>df = pd.DataFrame(columns=["Python", "Scikit-learn", "Pandas", "Fit to Job"], data=np.random.randint(1, 10,size=(400,4))) class LinearRegressionInt(LinearRegression): def predict(self,X): predictions = self._decision_function(X) return np.asarray(predictions, dtype=np.int64).ravel()...
python|pandas|numpy|machine-learning|scikit-learn
1
353,637
34,403,993
Python: Writing and printing to CSV a dataframe
<p>I have a vector of dates of size 10 and type numpy.ndarray. I also have an array of temperatures at each hour of size 10x24.</p> <p>I want to print the dates in column A and the corresponding temperature in columns B through Y for rows 1 though 10 in a csv file.</p> <p>My arrays look as following:</p> <pre><code>...
<p>It's not working because you trying to assign dataframe to column. You could construct pandas dataframe with your <code>TemperatureArray</code> and then add <code>Dates</code> column:</p> <pre><code>TempDay = pd.DataFrame(TemperatureArray) TempDay['Dates'] = AllDays TempDay.to_csv('C:\MyFile.csv') </code></pre>
python|pandas|dataframe
2
353,638
34,235,546
How to return the index of numpy ndarray based on search?
<p>I have a numpy 2D array, </p> <pre><code>import numpy as np array1 = array([[ 1, 2, 1, 1], [ 2, 2, 2, 1], [ 1, 1, 1, 1], [1, 3, 1, 1], [1, 1, 1, 1]]) </code></pre> <p>I would like to find the element '3' and know its location. So, I could try </p> <pre><code>condition = array1 == 3 </code><...
<p>You can also use <code>where</code>, returning a tuple of coordinate:</p> <pre><code>In [34]: np.where(array1==3) Out[34]: (array([3]), array([1])) </code></pre>
python|search|numpy|indexing
1
353,639
34,213,362
How to delete rows using a key word from columns in Pandas
<p>How we can delete the whole row taking a keyword in any column of that row? I have 250 such rows and 28 columns and I want to delete all rows having "income" as a key string in any column from a data frame using pandas </p>
<p>Say for instance you wanted to drop any row that had 'c' in a column</p> <pre><code>In [5]: import pandas as pd In [7]: data = [['a', 'b'], ['a', 'c'], ['c', 'd']] df = pd.DataFrame(data, columns=['col1', 'col2']) In [9]: df Out[9]: col1 col2 0 a b 1 a c 2 c d In [10]: df.loc[~(df == '...
python-3.x|pandas|row|dataframe|multiple-columns
2
353,640
34,110,032
Only length-1 arrays can be converted to Python scalars with log
<pre><code>from numpy import * from pylab import * from scipy import * from scipy.signal import * from scipy.stats import * testimg = imread('path') hist = hist(testimg.flatten(), 256, range=[0.0,1.0])[0] hist = hist + 0.000001 prob = hist/sum(hist) entropia = -1.0*sum(prob*log(prob))#here is error print 'E...
<p>This is an example of why you should never use <code>from module import *</code>. You lose sight of where functions come from. When you use multiple <code>from module import *</code> calls, one module's namespace may clobber another module's namespace. Indeed, based on the error message, that appears to be what is h...
python|python-2.7|numpy|scipy
4
353,641
34,207,409
Formatting of DateTimeIndex in plot pandas
<p>I'm having trouble deciphering the documentation for changing tick frequency and date formatting with pandas.</p> <p>For example:</p> <pre><code>import numpy as np import pandas as pd import pandas.io.data as web import matplotlib as mpl %matplotlib inline mpl.style.use('ggplot') mpl.rcParams['figure.figsize'] = ...
<p>If you use the <code>plot</code> method in <code>pandas</code>, the <code>set_major_locator</code> and <code>set_major_formatter</code> methods of <code>matplotlib</code> is likely to <a href="https://stackoverflow.com/questions/24665990/time-series-plotting-inconsistencies-in-pandas/24690145#24690145">fail</a>. It...
date|numpy|pandas|matplotlib|format
2
353,642
34,129,949
Pandas pivot table fixing value columns
<p>I get a dataframe like below daily,</p> <pre><code> type subtype count 0 A 1 25 1 A 2 36 2 B 1 12 3 B 2 10 4 C 1 40 </code></pre> <p>I pivot it and write in db among otherthings,</p> <pre><code>newdf = df.pivot_table('count', 'type', 'subtyp...
<p>I think you couldn't get your expected dataframe directly from <code>pivot_table</code> you'll need to add your column manually. But you could do it with for loop instead of manually:</p> <pre><code>list_to_fill = [2,'else'] for col_name in list_to_fill: if col_name not in new_df.columns: new_df[col_nam...
python|pandas
0
353,643
34,356,682
Clustering results print with details in python
<p>I just try to print my clustering results in python (2D array Numpy). But I can't find any solution about printing results.</p> <p>I draw my dendrogram but I need results for example:</p> <p>Cluster 1:</p> <p>Cluster 2:</p> <p>Cluster 3:</p> <p>My code is:</p> <pre><code>from matplotlib import pyplot as plt fr...
<p>If you read the documentation at</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/cluster.hierarchy.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/cluster.hierarchy.html</a></p> <p>You will notice the first method there:</p> <blockquote> <p>fcluster(Z, t[, criterion, depth, R, monocrit]...
python|numpy|scipy|cluster-analysis|hierarchical-clustering
0
353,644
34,116,024
Find nearest neighbour in a more pythonic way
<p>A is a point, and P is a list of points. I want to find which point P[i] is the closest to A, i.e. I want to find <code>P[i_0]</code> with:</p> <pre><code>i_0 = argmin_i || A - P[i]||^2 </code></pre> <p>I do it this way:</p> <pre><code>import numpy as np # P is a list of 4 points P = [np.array([-1, 0, 7, 3]), np...
<p>A more Pythonic way of implementing the same algorithm you're using is to replace your loop with a call to <code>min</code> with a <code>key</code> function:</p> <pre><code>closest = min(P, key=lambda p: sum((p - A)**2)) </code></pre> <p>Note that I'm using <code>**</code> for exponentiation (<code>^</code> is the...
python|numpy|nearest-neighbor
3
353,645
34,403,299
Equivalent of matlabs interp2 spline in scipy/numpy
<p>I am currently converting our matlab code base to python 3.5 with scipy/numpy.</p> <p>The line i am currently struggling with contains the <a href="http://de.mathworks.com/help/matlab/ref/interp2.html?refresh=true#inputarg_method" rel="nofollow">interp2 function with spline</a> as the method. I generally am able to...
<p>I suggest <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.splrep.html#scipy.interpolate.splrep" rel="nofollow">splrep</a> . <code>scipy.interpolate.splrep(x,y,k=3,task=-1)</code> seems to do the same job. <code>interp2d</code> is a wrapper with less parameters. </p>
python|matlab|numpy|scipy
1
353,646
34,050,071
TensorFlow random_shuffle_queue is closed and has insufficient elements
<p>I'm reading batch of images by getting idea <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/how_tos/reading_data/fully_connected_reader.py">here</a> from tfrecords(converted by <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/how_tos/reading_data/convert_t...
<p>I had a similar problem. Digging around the web, it turned out that if you use some <code>num_epochs</code> argument, you have to initialize all the <code>local</code> variables, so your code should end up looking like:</p> <pre><code>with tf.Session() as sess: sess.run(tf.local_variables_initializer()) ses...
python|tensorflow
13
353,647
36,924,613
Scipy Stats rv_continuous without normalization constant
<p>I want to draw random deviates from a distribution where I don't know the normalizing constant. The distribution is the conjugate prior of the gamma likelihood with unknown shape and scale=1. The pdf is given on wikipedia here <a href="https://en.wikipedia.org/wiki/Conjugate_prior#Table_of_conjugate_distributions" ...
<p>Doing the normalization integral numerically (<code>scipy.integrate.quad</code>) is always an option.</p>
python|numpy|scipy|bayesian
1
353,648
37,041,327
Numpy: modify array elements at certain positions
<p>I have an array a:</p> <pre><code>array([[[[14, 59, 18, 92], [91, 38, 58, 23], [33, 52, 93, 68], [19, 21, 50, 77]], [[90, 37, 22, 55], [56, 54, 10, 16], [83, 20, 36, 3], [84, 87, 85, 81]]], [[[ 0, 45, 72, 5], [49, 46, 94, 53], [34, 51, 75, 8], [27, 79, 35, 15...
<p>That's quite easy if you interpret your <code>b</code> as boolean mask:</p> <pre><code>b_mask = b.astype(bool) d = a.copy() d[b_mask] = a[b_mask] + c.ravel() d </code></pre> <p>giving me</p> <pre><code>array([[[[ 14, 59, 18, 92], [ 92, 38, 58, 23], [ 33, 54, 96, 68], [ 19, 21,...
python|arrays|numpy|conv-neural-network
4
353,649
37,117,798
TensorFlow missing CPU Op for FFT (InvalidArgumentError: No OpKernel was registered to support Op 'FFT' with these attrs)
<p>I am new to tensorflow and want to create a graph which performs fft on real data, similar to numpys rfft function:</p> <pre><code>def rfftOp(_in, name='rfft', graph=tf.get_default_graph()): with graph.as_default(): with tf.device('/cpu:0'): with tf.name_scope(name): cast...
<p>You are forcing TensorFlow to try to run the FFT operation on CPU by calling <code>with tf.device('/cpu:0')</code>. However the FFT operations are currently only implemented for GPU, which is why you end up with an error message.</p> <p>If you have a GPU available you can simply remove the call to tf.device(). Tens...
python|tensorflow
2
353,650
37,033,497
Any way to create a column of tuples from a column of floats in pandas?
<p>I'm given a list of tuples of the following form:</p> <pre><code>ls = [(14, 6, 1.5), (14, 7, 1.5), (14, 8, 1.5), (14, 9, 1.5), (14, 10, 1.5), (14, 11, 1.5), (14, 12, 1.5), ..., (14, 13, 1.5), (14, 14, 1.5), (14, 15, 1.5)] </code></pre> <p>There is a pandas DataFrame with one of the columns <code>data['ind']</code>...
<p>I would first create a <code>Series</code> from your list of tuples:</p> <pre><code>LS = pd.Series(ls) </code></pre> <p>and then call <code>map</code>:</p> <pre><code>data['ls'] = data['ind'].map(LS) </code></pre> <p>Using a sample of your list:</p> <pre><code>ls = [(14, 6, 1.5), (14, 7, 1.5), (14, 8, 1.5), (14...
python|pandas|dataframe|data-processing
2
353,651
36,956,849
Indexing using a tensor
<p>I'm trying to use a Targmax tensor to index a tensor.</p> <p>In numpy you can do the following indexing:</p> <pre><code>mat = np.random.uniform(size = 3*10*10).reshape((3,10,10)) indices = [np.array([0,0,1,2]),np.array([1,1,2,3]), np.array([1,3,0,3])] mat[indices] </code></pre> <p>Is there an equivalent operation...
<pre><code>x = tf.constant([[1,2],[3,4]]) sess = tf.Session() sess.run(tf.gather_nd(x,[[0,0],[1,1]])) </code></pre> <p>Out</p> <pre><code>array([1, 4], dtype=int32) </code></pre>
tensorflow
1
353,652
36,898,646
Python Pandas read_csv not importing correctly
<p>I have a <code>.xls</code> file that looks similar to this...</p> <pre><code>Value of Construction Put in Place... (Millions of Dollars....) Blank Row Date Total_Construction Total Residential Total Nonresidential...Columns Dec-15 1,116,570 435,454 681,217 Nov-15 1,115,966 432,295...
<p>Don't use <code>read_csv</code> to import an xls file. Use <code>read_excel</code>. See <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html</a></p>
python|pandas
5
353,653
36,977,103
Python Pandas, Resampling only specific hours
<p>my pandas version is 0.18 and I have a minute data that looks as follows:</p> <pre><code>Time 2009-01-30 09:30:00 85.11 100.11 2009-01-30 09:39:00 84.93 100.05 2009-01-30 09:40:00 84.90 100.00 2009-01-30 09:45:00 84.91 99.94 2009-01-30 09:48:00 84.81 99.90 2009-01-30 09:55:...
<p>The <code>base</code> argument is applied to midnight, so in your case the sampling starts from 00:30 and adds 78 min increments from there. I see two options.</p> <p><strong>Option 1</strong>:</p> <p>Figure out what the <code>base</code> applied to midnight should be in order to reach 9:30 (in this case <code>24<...
python|pandas
5
353,654
36,941,819
How to use column index when merging?
<p>I would like to merge two csv files and I want to merge them on the first column of the first csv file. Both of the files will have the same column name, but the name is unknown. I do not want to specify a column name for on = ... </p> <p>What I have:</p> <pre><code>compare = csv1.merge(csv2, on = csv1[csv1.column...
<p>Not clear what you're trying to do because it looks like you are trying to merge on a specific column, and on indexes. If you want to merge on a specific column, you want "<code>on</code>" to accept a string, not a pandas series. So change <code>on = csv1[csv1.columns[0]]</code> to <code>on = csv1.columns[0]</code> ...
python-2.7|csv|pandas|indexing|merge
2
353,655
36,764,553
Report with Pivot Tables like in Excel using Python
<p>I have data </p> <pre><code>ID,"address","used_at","active_seconds","pageviews" 0a1d796327284ebb443f71d85cb37db9,"vk.com",2016-01-29 22:10:52,3804,115 0a1d796327284ebb443f71d85cb37db9,"2gis.ru",2016-01-29 22:48:52,214,24 0a1d796327284ebb443f71d85cb37db9,"yandex.ru",2016-01-29 22:14:30,4,2 0a1d796327284ebb443f71d85c...
<p>The following code creates a sum of <code>active_seconds</code> per <code>ID</code> and <code>week</code>.</p> <p>First, producing some sample data similar to yours:</p> <pre><code>df = pd.DataFrame() ids = [''.join([random.choice(string.ascii_lowercase + string.digits) for _ in range(16)]) for i in range(10)] add...
python|excel|numpy|pandas
0
353,656
36,727,837
Python Modify data of existing .xlsx file
<p>I have some code here in python which created a .xlsx file using openpyxl.</p> <p>However, when i tried to modify the file, the new data will register into the file but previous data is gone. I heard of using deepcopy or (.copy.copy) to copy the data of the file but how can i paste the data copied plus my current e...
<p>I've run into this problem several times, and haven't been able to solve it using pure python; however, you can use the following code to call a VBA macro from a Python script, which can be used to modify your existing excel file. </p> <p>This has allowed me to come up with creative ways to streamline work so that ...
excel|python-2.7|pandas|openpyxl|xlutils
0
353,657
55,119,103
Convert two different dataframes to one json file using pandas
<p>My first dataframe <code>df_gammask</code> looks like that: </p> <pre><code> distance breakEvenDistance min max 0 2.1178 2.0934 NaN 0.000955 1 2.0309 2.1473 0.000955 0.001041 2 1.9801 1.7794 0.001041 0.001124 3 1.9282 2.1473 0.001124 0.001199 4 1.8518 1.5885 0.001199 0.00...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>DataFrame.to_dict</code></a> in nested dictionary comprehension for remove missing values, then create <code>dictionary</code> and convert to <code>json</code>:</p> <pre><code>import...
python|json|pandas
5
353,658
54,840,080
Get values from a smaller DataFrame with a specified step
<p>Supposing I have the two <code>DataFrames</code> shown below:</p> <pre><code>dd = pd.DataFrame([1,0, 3, 0, 5]) 0 0 1 1 0 2 3 3 0 4 5 </code></pre> <p>and</p> <pre><code>df = pd.DataFrame([2,4]) 0 0 2 1 4 </code></pre> <p>How can I broadcast the values of <code>df</code> into <code>dd</code> with <...
<p>Another solution:</p> <pre><code>dd = pd.DataFrame([1, 0, 3, 0, 5]) df = pd.DataFrame([2, 4]) dd.iloc[1::2] = df.values dd # Out: 0 0 1 1 2 2 3...
python|pandas|dataframe
2
353,659
54,810,680
Problem when processing from CSV to CSV with a row count
<p>I am trying to process a CSV file into a new CSV file with only columns of interest and remove rows with unfit values of -1. Unfortunately I get unexpected results, as it automatically includes column 0 (old ID) into the new CSV file without explicitly asking the script to do it (as it is not defined in cols = [..])...
<p>I solved the problem via simple line after the data drop:</p> <pre><code>data.reset_index(drop=True, inplace=True) </code></pre>
python|pandas|csv
0
353,660
55,062,454
Create New Column with Multiple Matches
<p><strong>Sample DF:</strong></p> <p>I have a df with columns like <code>Zone</code> , <code>New_Zone</code>, <code>Country</code>, <code>New_Region</code> &amp; <code>Currency</code></p> <p><code>Currency</code> column has values like <code>EUR</code>, <code>AUD</code>, <code>BLR</code>,<code>RUB</code></p> <p><code>...
<p>Create each conditions for separate rows for readable code, chain by <code>|</code> or <code>&amp;</code> for bitwise <code>OR</code> or <code>AND</code> to final mask and pass to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</...
python|pandas
2
353,661
55,101,168
Pandas: create new columns intelligently
<p>This is a very general question, I'm asking for solutions to look into for the following situations:</p> <p>I often find myself creating an extra column in a dataframe, and I want to use something like:</p> <pre><code>df['new_col'] = df['old_col_1']+df['old_col_2'] </code></pre> <p>But unless the operation is inc...
<p>I think principe <code>df['new_col'] = df['old_col_1']+df['old_col_2']</code> is good, because vectorized.</p> <p>It depends of data, how handle it. E.g. here is possible convert columns to strings and apply <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow no...
python-3.x|pandas
5
353,662
54,965,169
pandas : How to get groups of each n rows after row matching query?
<p>Let's say I have this pandas dataframe:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'x': np.random.randint(-10, 10, size=100), 'y': np.random.randint(-10, 10, size=100)}) </code></pre> <p>And I have any query that selects rows, e.g.</p> <pre><code>query = (df['x'] &...
<p>I think you can do this using <code>cumsum</code>, <code>groupby</code> and <code>head</code>:</p> <p>Try this, where k=2 use head(3), current record plus two:</p> <pre><code>df.groupby(query.cumsum()).head(3) </code></pre> <p>and to generalize try this</p> <pre><code>k=2 df.groupby(query.cumsum()).head(k+1) </c...
python|pandas|numpy|pandas-groupby
1
353,663
54,851,490
Lambda over dataframe rows interacting with columns
<p>I am trying to apply this to my dataframe: For each row:</p> <ul> <li>if row['colA']=='NONE' then row['colA']=row['colX']</li> <li>elif row['colA']!='NONE' &amp; row['colB']=='NONE' then row['colB']=row['colX']</li> </ul> <p>and so on. I am trying to do this with a lambda function so that:</p> <pre><code>datafram...
<p>May be something like(<em>its better to always post some sample data to test</em>):</p> <pre><code>df=df.replace('NONE',np.nan) df['colA']=df['colA'].fillna(df['colX']) df['colB']=np.where(df['colA'].notnull()&amp;df['colB'].isnull(),df['colB'].fillna(df['colX']),df['colB']) #alternative for above line-&gt; #df.loc...
python|pandas|lambda
1
353,664
54,841,346
Modify DataFrame column values based on condition
<p>I am trying to modify the formatting of the strings of a Datframe column according to a condition.</p> <p>Here is an example of the file</p> <p><a href="https://i.stack.imgur.com/qgYk0.jpg" rel="nofollow noreferrer">The DataFrame</a></p> <p>Now, as you might see, the object column values either start with http or...
<p>So it looks like you have many of the right pieces here, you mentioned boolean indexing which is what you can use to select and update certain rows, for example I'll do this on a dummy DataFrame:</p> <pre><code>df = pd.DataFrame({"a":["http://akjsdhka", "Helloall", "http://asdffa", "Bignames", "nonetodohere"]}) </c...
python|pandas
0
353,665
54,839,473
Pandas DataFrame multplication with missing values
<p>I have 2 dataframes </p> <pre><code> Value Location Time Hawai 2000 1.764052 2002 0.400157 Torino 2000 0.978738 2002 2.240893 Paris 2000 1.867558 2002 -0.977278 2000 2002 Country Unit Location US USD Hawai ...
<p>I think better here is use missing values instead <code>..</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> with <code>errors='coerce'</code>, so divide working very nice:</p> <pre><code>df2 = pd.DataFrame({'Countr...
python|pandas|dataframe
2
353,666
54,915,550
exclude dates greater than 500 years old in pandas dataframe
<p>I have a dataframe containing a column with dates. Some of the dates are missing (empty) and a few dates are in the year 1500.</p> <p>I want to get only those rows where either the date is within the last 10 years or is missing. </p> <p>Since Pandas has an time range of 584 years, I do this to avoid raising an err...
<p>Then just add the conditions</p> <pre><code>con1=(pd.to_datetime(df['date'], errors = 'coerce') &gt;= ar.utcnow().shift(days=-3650).date()) con2=pd.to_datetime(df['date'], errors = 'coerce').isnull() df.loc[con1|con2] </code></pre>
python|pandas
2
353,667
54,807,335
Visualizing executable byte stream to a image file, why it is rotated 45 degrees?
<p>I'm trying to visualize malware executables for testing visual classification approach. Using Microsoft Malware Classification Challange <a href="https://www.kaggle.com/c/malware-classification/data" rel="nofollow noreferrer">dataset</a> .bytes files I have input such:</p> <pre><code>00401000 56 8D 44 24 08 50 8B F...
<p>I think the line:</p> <pre><code>image_buffer[i,j] = b_data[i+j] </code></pre> <p>needs to be:</p> <pre><code>image_buffer[i,j] = b_data[(i*width)+j] </code></pre> <hr> <p>I don't have your data to test with, nor the <code>import</code> statements which you didn't share for some reason, but I suspect the whole ...
python|numpy|python-imageio
2
353,668
55,138,516
Replace **NULL** values in Pandas dataframe
<p>I'm pulling my hair out here. I need to replace <strong>null</strong> values in a pandas dataframe column. These are specifically null values not NaN values.</p> <p>I've tried:</p> <pre><code>trainData['Embarked'].replace(trainData['Embarked'].isnull, embarkedMost, regex=True) trainData['Embarked'].replace('', em...
<p>Nevermind everyone</p> <p>Solved with:</p> <pre><code>trainData['Embarked'] = trainData['Embarked'].fillna(embarkedMost) </code></pre> <p>I think I may have opened a csv in a different directory</p>
python|pandas|dataframe|missing-data
1
353,669
54,845,617
subset a dataframe in Python with more than one query
<p>What is the shortest way to subset a dataframe with multiple columns and find the number of rows that matches a query. </p> <p>Is there an easier way to re-write the following piece of code.</p> <p>The goal is to find the number of students who got the grades for all quarters and the ones who missed just the 4th q...
<p>Your first line can be shorted tremendously, since the condition is always the same, and the column names follow a pattern:</p> <pre><code>df.filter(like='6th-Grade-Q').eq('Y').all(1).sum() </code></pre> <p>If there are other columns that begin with <code>'6th-Grade-Q'</code> than those 4, don't use filter and spe...
python|python-3.x|pandas|dataframe
2
353,670
55,033,823
I need advice on how to compact this dataframe
<p>Below is my dataframe, I believe I need to use groupby or pivot but haven't gotten anything to work correctly.</p> <pre><code> LOGIN MANAGER 7 8 9 10 11 UNITS HOURS UPH 0 joeblow MSmith 1 21 1 47.01 1 joeblow MSmith 0.25 ...
<p>First Create your columns <code>dict</code> with functions </p> <pre><code>d={'7':'first','8':'first','9':'first','10':'first','11':'first','UNITS':'sum','HOURS':'sum','UPH':'mean'} </code></pre> <p>Then do with <code>agg</code> </p> <pre><code>yourdf=df.groupby(['LOGIN','MANAGER']).agg(d) </code></pre>
python-3.x|pandas|pandas-groupby
2
353,671
54,798,562
Reading JSON into Python / Pandas - getting JSONDecodeError
<p>I have data that has a few columns in json, but I need to convert each column to multiple columns within a Pandas dataframe (so each new column is a key, and each row will be the value associated with it for that row).&nbsp;</p> <p>I created this function:</p> <pre><code>def convert_json_columns(df): cat_df = ...
<p>Not sure if it's the cause of the JSON issue but you can easily replace double quotes with singles in pandas like so:</p> <p><code>df["column name"] = df["column name"].str.replace('"', "'")</code></p>
python|json|python-3.x|pandas|dictionary
0
353,672
55,085,660
RuntimeError: Only tuples, lists and Variables supported as JIT inputs, but got NoneType
<p>My code is </p> <pre><code>a=torch.randn(1,80,100,requires_grad=True) torch.onnx.export(waveglow,a, "waveglow.onnx") </code></pre> <p>I am trying to export a PyTorch model to ONNX format so i can use it in TensorRT. while testing my model in PyTorch the input tensor dimension is (1,80,x) where x varies depending o...
<p>Given that you have NoneType, perhaps you could check if there is an actual input, because the fact is, you actually got <code>None</code>. </p> <p>Also, any reason to not use Variable? Variable converts your inputs to a tensor that can be accepted as an input for <code>torch.onnx.export</code>.</p>
pytorch|onnx
2
353,673
55,138,926
Annotations in xml convert to json?
<p>Im using <strong>MASK RCNN</strong> keras and tensorflow and I would like to know if someone has been able to train using a xml annotation file, or if someone has converted xml to json. Can someone show me an example how to use the load_() function if I change my xml file to json?</p> <p>I made some annotations wit...
<p>You need to create your own script to convert from XML to JSON, or simply delete the <code>load_mask()</code> function.</p>
python|tensorflow|machine-learning|keras|computer-vision
1
353,674
54,732,779
Pandas: Simple Analysis of growth (comparatively) and with Fillna
<p>Below is the basic data I'm provided with every month. There are many department related files I get and the job gets very monotonous and repetitive.</p> <pre><code>Month,year,sales, January,2017,34400, February,2017,35530, March,2017,34920, April,2017,35950, May,2017,36230, June,2017,36820, July,2017...
<p>AFAIU this should work for you:</p> <pre><code># Get difference from previous as True / False df['P/L'] = df.sales &gt; df.sales.shift() # Add column counting 'streaks' of P or L df['streak'] = df['P/L'].groupby(df['P/L'].ne(df['P/L'].shift()).cumsum()).cumcount() # map True/False to string of Profit/Loss df['P/L']...
python|pandas|dataframe|comparison
2
353,675
54,755,406
Converting directories of images to tfrecords using built-in inception script
<p>I am trying to convert my data (images) into tfrecords. I was led to this built-in script via Stackoverflow but I can't seem to get it working right.</p> <p><a href="https://github.com/tensorflow/models/blob/f87a58cd96d45de73c9a8330a06b2ab56749a7fa/research/inception/inception/data/build_image_data.py" rel="nofollo...
<p>Did you verify both train and validation directory has correctly labeled data?<br> Labels should match with the labels file as well.<br> It's better to remove white space from the path. At times it also make bugs. ;) </p>
python|python-3.x|tensorflow
0
353,676
55,049,392
filter on a pandas dataframe column which contains frozenset of strings
<p>I've a result dataframe which I've obtained like this (ref <a href="http://rasbt.github.io/mlxtend/user_guide/frequent_patterns/apriori/" rel="nofollow noreferrer">http://rasbt.github.io/mlxtend/user_guide/frequent_patterns/apriori/</a>)</p> <pre><code>dataset = [['Milk', 'Onion', 'Nutmeg', 'Kidney Beans', 'Eggs', ...
<p>a classic solution:</p> <pre><code>fname = 'eggs' file_result_df = file_result_df[file_result_df['itemsets'].astype(str).str.lower().str.contains(fname)] </code></pre> <p>output:</p> <pre><code> support itemsets length 0 0.8 (Eggs) 1.0 5 0.8 (E...
python|pandas|dataframe|frozenset
2
353,677
55,033,122
Counting continues occurrence of a value in a column
<p>I have a data frame like this:</p> <pre><code>index value ---- ----- 1 A 2 A 3 A 4 A 5 B 6 B 7 A 8 B 9 C 10 C </code></pre> <p>I want to add a column to count continues occurrence of my value, like this:</p> <pre><code>index val...
<p>It is just too boring to using <code>shift</code> and <code>cumsum</code> , let us try <code>itertools</code> </p> <pre><code>import itertools df['New']=list(itertools.chain(*[list(range(len(list(y))))for _,y in itertools.groupby(df.value)])) df Out[596]: index value New 0 1 A 0 1 2 A ...
python|pandas|dataframe
3
353,678
54,984,345
After Pytorch Upgrade , my model is giving almost random output
<p>I trained, tested and still using a model in "Pytorch 0.4.1". It was, and is still working fine (output is what it should be) if I use pitch 0.4.1. But as i upgrade to version 1.0.1, every time, I try to evaluate same input image, I get different output (Its a regression).</p> <p>I tried to see what has been change...
<p>It was because of drop out layer. Model.eval disables the dropout layer. Pretty simple. But Now in Pytorh upgrade, if Dropout is not defined specifically in model <strong>init</strong> function, it will not get disable during eval. Atleast this was reason for my case. </p>
python|machine-learning|pytorch|torchvision
0
353,679
54,921,594
Get access to numpy with a dictionary lookup style but remain numpy array operations
<p>I want to construct a class inheriting from the numpy.ndarray, so that it can do normal operations as a numpy array(+, -, *, /,...). The only thing I want to change is that the way we access the items in our Data. For example:</p> <pre><code>import numpy as np from PIL import Image class Data(np.ndarray): """ ...
<p>You are going to want to override the __getitem__ method. Here is another question which may provide some intuition: <a href="https://stackoverflow.com/questions/43627405/understanding-getitem-method">Understanding __getitem__ method</a>. </p> <p>Link to the docs: <a href="https://docs.python.org/3/reference/datamo...
python|numpy
0
353,680
54,949,810
Using Pandas join to fill in columns
<p>I have two DataFrames that roughly look like</p> <pre><code>(ID) (Category) (Value1) (Value2) 111 1 5 7 112 1 3 8 113 2 6 9 114 3 2 6 </code></pre> <p>and</p> <pre><code>(Category) (Value1 Average for Category) (Value2 Average for ...
<p>You are simply looking for a <code>join</code>, in pandas we use <code>pd.merge</code> for that like the following:</p> <pre><code>df3 = pd.merge(df1, df2, on='Category') ID Category Value1 Value2 Value 1 Average Value 2 Average 0 111 1 5 7 4 5 1 112 1 3 ...
python|pandas
0
353,681
54,933,895
Break numpy arrays into subarrays according to their signs
<p>Suppose I have a numpy array</p> <pre><code>a = numpy.array( [-1, -2, 3, 3, -4, -4, 9, 9, 10, -1, -3] ). </code></pre> <p>I would like to break the array into subarrays according to the rule: the first subarray starts with a[0] and ends before it changes sign. We continue the process at where the last operation e...
<p>Here's one compact way to produce list of those subarrays as output -</p> <pre><code>In [170]: a Out[170]: array([-1, -2, 3, 3, -4, -4, 9, 9, 10, -1, -3]) In [171]: np.split(a,np.flatnonzero(np.diff(a&gt;0))+1) Out[171]: [array([-1, -2]), array([3, 3]), array([-4, -4]), array([ 9, 9, 10]), array([-1, -3]...
python|numpy
3
353,682
54,988,772
Write multiple column names for pandas group by agg
<p>I want to make a group by in pandas and calculating the sum and average for multiple different columns. Below is an example.</p> <pre><code> grouped =df.groupby(['id']).agg({ 'column1': ['sum','avg'], 'column2': ['sum','avg'], 'column3': ['sum','avg'], ...
<p>You could do something like this:</p> <pre><code>df[cols_list].groupby(['id']).agg([np.mean, np.std]) </code></pre> <p>Where <code>cols_list</code> is the list of your columns of interest plus your <code>id</code>, so it still can group: <code>['id','column1',...,'column8']</code> in your example.</p>
python|pandas
2
353,683
54,876,182
Sample from a 2d probability numpy array?
<p>Say that I have an 2d array <code>ar</code> like this: </p> <pre><code>0.9, 0.1, 0.3 0.4, 0.5, 0.1 0.5, 0.8, 0.5 </code></pre> <p>And I want to sample from [1, 0] according to this probability array. </p> <pre class="lang-py prettyprint-override"><code>rdchoice = lambda x: numpy.random.choice([1, 0], p=[x, 1-x]) ...
<p>You should be able to do this like so:</p> <pre><code>&gt;&gt;&gt; p = np.array([[0.9, 0.1, 0.3], [0.4, 0.5, 0.1], [0.5, 0.8, 0.5]]) &gt;&gt;&gt; (np.random.rand(*p.shape) &lt; p).astype(int) </code></pre>
python|numpy|random
4
353,684
55,045,843
Make pandas raise on divide by zero instead of inf
<p>I would like to have pandas raise an exception when dividing by zero as in:</p> <pre><code>d = {'col1': [2., 0.], 'col2': [4., 0.]} df = pd.DataFrame(data=d) 2/df </code></pre> <p>Instead of the current result:</p> <pre><code>0 1.000000 1 inf Name: col1, dtype: float64 </code></pre> <p>Any suggestions...
<p>It's far from ideal, but one potential option is to interpret the elements of your dataframe as Python objects rather than the more optimized <code>numpy</code> or <code>pandas</code> dtypes that it typically uses:</p> <pre><code>In [37]: d = {'col1': [2., 0.], 'col2': [4., 0.]} ...: df = pd.DataFrame(data=d) ...
pandas
1
353,685
55,049,461
How do i plot k-mean clustering from pandas?
<p>I am trying to cluster data from product sales of various companies. Note that I mapped any strings in my columns to numerical values so i could use k-means clustering. I have the following code where i am doing k-means on my data</p> <pre><code>FeaturesDf=FeaturesDf[['company_value','Date_value','product_value']] ...
<p>Same thing as you did, but you can call <code>plot.scatter</code> on the DataFrame itself:</p> <pre><code>import pandas as pd import numpy as np from sklearn.cluster import KMeans n = 1000 d = pd.DataFrame({ 'x': np.random.randint(0,100,n), 'y': np.random.randint(0,100,n), }) m = KMeans(5) m.fi...
python|pandas|data-science|k-means
9
353,686
55,062,375
tensorflow api 2.0 tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn
<p>I am trying to use tensorflow estimator using tensorflow api 2.</p> <pre><code>import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({'A': np.array([100, 105.4, 108.3, 111.1, 113, 114.7]), 'B': np.array([11, 11.8, 12.3, 12.8, 13.1,13.6])...
<p>This completes without error. But I haven't tested. Just installed tensorflow 2.0 alpha.</p> <p>Please check the <a href="https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/estimators/linear.ipynb" rel="nofollow noreferrer">docs</a> for further help.</p> <pre><code>import tensorflow as tf import p...
python-3.x|tensorflow|tensorflow-estimator|tensorflow2.0
1
353,687
54,988,498
Strange tensorflow issue: dropped ranks
<p>I am uncertain what is happening here. I have been reading about this error and I interpret it as an error related to image reshape. For some reason, the last 3 ranks are missing. The data set has each image that are non-normalized in width and height. The images are supposed to be a square after processing, which i...
<p>img = skimage.transform.resize(img, (img_height, img_width), mode='reflect') for some reason is not appropriately resizing the images. Resizing the images outside of python and not using this line of code resolved the problem of dropped ranks. </p>
python|tensorflow|machine-learning|keras|computer-vision
0
353,688
54,857,888
How can I create thousands of variables rather than using DataFrame (too slow)?
<h3>Question </h3> <p>How can I create thousands of variables rather than using DataFrame? Updating elements with </p> <pre><code>df1.loc[a,b] = df1.loc[a,b] + update_term </code></pre> <p>is so slow!!!</p> <h3>Current situation </h3> <ol> <li>I have 2500 days' historical prices of 445 U.S. companies in a datafram...
<p>It turns out that using dictionary is much faster than using DataFrame for storing variables, as John Zwinck suggested. Thank you!</p>
python|python-3.x|pandas
0
353,689
54,908,612
Rasa Core TypeError (chatbot)
<p>I have an issue with RasaStack core : when I train the dialog data with this command : </p> <pre><code>python -m rasa_core.train -d domain.yml -s data\stories.md -o models\current\dialogue -c config.yml </code></pre> <p>I have this Exception TypeError : </p> <pre><code> q, r = gen_linalg_ops.qr(a, full_matrice...
<p>Please consider updating to the stable Rasa version <code>1.x</code>, e.g. by doing <code>pip install rasa</code>, where this bug is fixed.</p>
python|tensorflow|chatbot|rasa-core
0
353,690
54,737,891
Convert the last non-zero value to 0 for each row in a pandas DataFrame
<p>I'm trying to modify my data frame in a way that the last variable of a label encoded feature is converted to 0. For example, I have this data frame, top row being the labels and the first column as the index:</p> <pre><code>df 1 2 3 4 5 6 7 8 9 10 0 0 1 0 0 0 0 0 0 1 1 1 0 0 0 1 0 0 0...
<p>You can use <code>cumsum</code> to build a boolean mask, and set to zero. </p> <pre><code>v = df.cumsum(axis=1) df[v.lt(v.max(axis=1), axis=0)].fillna(0, downcast='infer') 1 2 3 4 5 6 7 8 9 10 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 </code></pr...
python|pandas|dataframe
1
353,691
54,815,519
Pandas – lowest value in last x columns
<p>I have a pandas dataframe in Python. I like to find minimum value in the last 10 columns in each lines.</p> <p>I tried this:</p> <blockquote> <p>df['min_value'] = df.min(axis=1)</p> <p>1, 3, 56, 7, ,23 ,46, 234, 23, 45, 123, 23, 64, 27, 12, 78 ==&gt; 1</p> <p>4, 5, 6, 73, ,82 ,66, 24, 243, 345, 12, 22, 46, 7, 21, 8...
<p>you can use</p> <pre><code>df = df.assign(min_value=df.iloc[:, -10:].values.min(1)) # column name: min_value </code></pre>
python|pandas
0
353,692
54,701,792
How to convert .wav files into a Pandas DataFrame in order to feed it to a neural network?
<p>I'm trying to feed .wav files to a neural network in order to train it to detect what's being said. So I have around 10 000 .wav files and the transcription of the audio, but when I try to feed the CSV file to the neural network I get this error : <code>ValueError: setting an array element with a sequence.</code></p...
<p>Looks like you already solved this, but here are a couple of other items that it looks like haven't been mentioned. First, wave is a Python utility that was included in my Py3.6 install. </p> <p><a href="https://docs.python.org/3/library/wave.html" rel="nofollow noreferrer">https://docs.python.org/3/library/wave.ht...
python|pandas|list|wav
1
353,693
54,905,790
Error when converting from spark dataframe with dates to pandas dataframe
<p>I have a spark dataframe with this schema:</p> <pre><code>root |-- product_id: integer (nullable = true) |-- stock: integer (nullable = true) |-- start_date: date (nullable = true) |-- end_date: date (nullable = true) </code></pre> <p>When trying to pass it to a <code>pandas_udf</code> or convert to a pandas d...
<p>Looks like a bug. Have the same issue with pyarrow==0.12.1 and pyarrow==0.12.0. Casting spark dataframe column to TIMESTAMP works for me.</p> <pre><code>spark.sql('SELECT CAST(date_column as TIMESTAMP) FROM foo') </code></pre> <p>Also rolling back to pyarrow==0.11.0 solves the issue. (my python is 3.7.1 and pandas...
pandas|apache-spark|dataframe|pyspark
7
353,694
54,840,612
PyTorch why does the forward function run multiple times and can I change the input shape?
<pre><code>import torch import torch.nn as nn import torchvision.datasets as dsets from skimage import transform import torchvision.transforms as transforms from torch.autograd import Variable import pandas as pd; import numpy as np; from torch.utils.data import Dataset, DataLoader import statistics import random imp...
<p>You are calling <code>forward</code> twice in <code>run</code>:</p> <ol> <li>Once for the training data</li> <li>Once for the validation data</li> </ol> <p>However, you do <em>not</em> appear to have applied the following transformation to your validation data:</p> <p><code>images = images.resize_((100,616))</cod...
python|python-3.x|pytorch|mnist
2
353,695
54,733,869
How to get the Rank of current row compared to previous rows
<p>How to get the Rank of current row compared to previous rows </p> <p>I have a dataframe like:</p> <pre><code>Instru Price Volume ABCD 1000 100258 ABCD 1000 100252 ABCD 1000 100168 ABCD 1000 100390 ABCD 1000 100470 ABCD 1000 100420 </code></pre> <p>I want to get the rank of current row compared t...
<p>Use <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.searchsorted.html" rel="noreferrer">np.searchsorted</a> after a <em>cumulative sort</em>:</p> <pre><code>df['Rank'] = np.array([i - np.searchsorted(sorted(df.Volume[:i]), v) for i, v in enumerate(df.Volume)]) + 1 print(df) </code></pre> ...
python|python-3.x|pandas|dataframe
5
353,696
54,926,465
while find Max of two pandas element of current and previous getting error 'list' object has no attribute 'max'
<p>Sadly I get this error when I try to do <code>max()</code> tried with multiple <code>[] ()</code> combination and the error keeps on coming .</p> <p>Looks like this is minor issue and easily solvable. Before posting it here referred some of the existing posts still could not figure out the way.</p> <p>Any help muc...
<p>Need function <a href="https://docs.python.org/3/library/functions.html#max" rel="nofollow noreferrer"><code>max</code></a> function working with iterables in python:</p> <pre><code>for i in range(1, len(df)): if(df[source].iat[i] &gt; df[trail].iat[i - 1]) and (df[source].iat[i-1] &gt; df[trail].iat[i-1]):...
python-3.x|pandas|dataframe|max
1
353,697
55,057,635
Find pattern in time series graph with pandas
<p>I would like to find a pattern in a pandas data frame.The real problem looks like this picture:</p> <p><a href="https://i.stack.imgur.com/YvOQQ.jpg" rel="nofollow noreferrer">I would like to find the blue pattern in the graph.</a></p> <p>My idea was:</p> <ol> <li>Make a pattern model of what I'm looking for</li> ...
<p>Well, I fixed your dataframe creation, also function definition, but not sure about the output if it's what you are expecting:</p> <pre><code>import numpy as np import pandas as pd from pandas import Series from pandas import DataFrame from sklearn.metrics.pairwise import euclidean_distances from sklearn.metrics.pa...
python|pandas|data-analysis
0
353,698
54,852,185
How can I keep the forms of the arrays when I use numpy concatenate or numpy append
<p>I had 3 lists and made them into ndarray.</p> <pre><code>o_a = [1,2,3,4,5] o_b = [2,4,6,8,10] o_c = [11,22,33,44,55] np_a = np.array(o_a) np_b = np.array(o_b) np_c = np.array(o_c) print(np_a) print(np_b) print(np_c) [1 2 3 4 5] [ 2 4 6 8 10] [11 22 33 44 55] </code></pre> <p>when I use vstack to jo...
<p><strong>Using <code>numpy.concatenate()</code> or <code>numpy.append()</code>:</strong></p> <pre><code>np.concatenate((np_a[None,:],np_b[None,:]), axis=0) </code></pre> <p>or</p> <pre><code>np.append(np_a[None,:],np_b[None,:], axis=0) </code></pre> <p>Output (in either case):</p> <pre><code>array([[ 1, 2, 3, ...
python|numpy|concatenation|numpy-ndarray
0
353,699
54,738,156
Splitting and copying csv fields in pandas
<p>I have a csv file for eg </p> <p>ID,Name,products</p> <p>101,Tesco,Apple;Banana;Oranges</p> <p>102,Lidl,Juice;Yogurt</p> <p>103,Aldi,Fruits;vegetables;rice</p> <p>Using the pandas library I want to split these into a new csv such that for the products column there is only one value for every field</p> <p>The f...
<p>We can: </p> <p>1) Split the items in each row with delimiter ";". Then we get one column for each item.</p> <p>2) We then unstack the columns to get them as rows, and then remove the index level that is added based on the previous column values.</p> <p>3) Name this pd.Series and join on the main df.</p> <pre><c...
python|pandas|csv|data-analysis
2