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
370,300
73,066,603
Dictionary/Records to Dataframe
<p>How do I convert the dictionary to df?</p> <pre><code>data = {'records': [{'centre_contact_no': 1578}, {'centre_contact_no': 7517}, {'centre_contact_no': 3590} ] } </code></pre> <p>I have tried:</p> <pre><code>data = pd.DataFrame.from_records(data) </...
<p>Do you simply want:</p> <pre><code>df = pd.DataFrame(data['records']) </code></pre> <p>output:</p> <pre><code> centre_contact_no 0 1578 1 7517 2 3590 </code></pre> <p>Or with a MultiIndex:</p> <pre><code>df = pd.concat({k: pd.DataFrame(v) for k,v in data.items()}, axis=1) ...
python|pandas|dataframe
1
370,301
73,093,893
Pandas compute all combinations between two columns just once
<p><strong>Disclaimer this is a simplified example, in the real case I need to compute a heavy cost function avoiding repetition a + b == b + a counts as duplicated</strong></p> <p>I have a dataframe with a string column, in this example I simply add them up:</p> <pre><code>import pandas as pd data = pd.DataFrame({'peo...
<p>A more Pythonic method is using the <code>itertools.combinations_with_replacement</code> generator:</p> <pre><code>from itertools import combinations_with_replacement d = pd.DataFrame({ 'combinations': [ ''.join(c) for c in \ combinations_with_replacement(data['people'], 2) ] }) print(d) </code><...
python|pandas
0
370,302
73,151,382
How to interperet the 'num_layers' line when using Keras Tuner
<p>I'm reading an article about tuning hyperparameters in keras tuner. It includes code to build a model that has this code:</p> <pre><code>def build_model(hp): &quot;&quot;&quot; Builds model and sets up hyperparameter space to search. Parameters ---------- hp : HyperParameter object C...
<p>If you see the <a href="https://keras.io/api/keras_tuner/hyperparameters/#int-method" rel="nofollow noreferrer">docs</a>, the 2 and 6 are referring to the min and max values respectively. Also note:</p> <blockquote> <p>[...] max_value is included in the possible values this parameter can take on</p> </blockquote> <p...
python|tensorflow|keras|neural-network|keras-tuner
1
370,303
72,964,383
regex to find word that starts with c and ends with o
<p>I am trying to write some code to find sentence that has any word that has a letter c followed by a another letter and ends in o. e.g. cxo, ceo, cfo Aplogies should have mentioned that it can only have one letter in the middle of c and o</p> <p>I've tried</p> <pre><code>(&quot;c.o&quot;) </code></pre> <p>but this do...
<p>If your goal is to find any 3-letter word starting with C and ending with O, you can insert a <strong>word boundary</strong> <code>\b</code> before and after your match like so: <code>/\bc\wo\b/</code>. The presence of <code>\b</code> will prevent partial matches like <code>echo</code> from matching your regex, but ...
python|pandas|regex
1
370,304
73,090,447
ValueError in model.fit keras and user code
<p>I'm learning deep-learning python using keras and tensorflow. I am using efficientnetb0 from imagenet dataset. I had divided the training and testing sets and performed one hot encoding. I have 17 folders or classifications of images.</p> <pre><code>effnet = EfficientNetB0(weights='imagenet',include_top=False,input_...
<p><strong>I fixed the error!</strong></p> <p>I just changed dense layer to 18 and deleted dropout layer. I don't know why. I will determine if it is because of the dense layer or the dropout layer. Maybe dropout helps the model not to overfit. Maybe it was the dense layer's error.</p>
python|tensorflow|keras|deep-learning
0
370,305
72,946,441
AttributeError: module 'tensorflow._api.v2.train' has no attribute 'get_or_create_global_step'
<p>I have this line of code as part of a function:</p> <pre><code>global_step = tf.train.get_or_create_global_step() </code></pre> <p>An this is the error I'm getting:</p> <pre><code>AttributeError Traceback (most recent call last) &lt;ipython-input-17-e0d01fc93072&gt; in &lt;module&gt;() ...
<p>From what i gathered in <a href="https://github.com/tensorflow/tensorflow/blob/v2.8.1/tensorflow/python/training/training_util.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/v2.8.1/tensorflow/python/training/training_util.py</a>, and <a href="https://github.com/tensorflow/tensorflow/comm...
python|tensorflow|machine-learning|keras|deep-learning
1
370,306
73,027,309
Z-Score computation of a Pandas' DataFrame returns differing classes
<p>I am trying to calculate the Z-Score of a Pandas' DataFrame, using <a href="https://docs.scipy.org/doc/scipy-1.5.4/reference/generated/scipy.stats.zscore.html#scipy.stats.zscore" rel="nofollow noreferrer">scipy's zscore</a> method. Though while successful, I am getting different types returned, depending on which ho...
<p>If we look at the source code of scipy's <code>zscore</code> in version <a href="https://github.com/scipy/scipy/blob/19acfed431060aafaa963f7e530c95e70cd4b85c/scipy/stats/stats.py#L2430" rel="nofollow noreferrer">v1.5.4</a> (such as on Host 1), we can see that the passed input gets converted to a numpy array using <c...
python|pandas|numpy|scipy
2
370,307
72,897,387
Getting basic stats from Np.array within a for loop in python
<p>I don't have a lot of python experience and I'm trying something rather complicated for me, so excuse my messy code. I have a few arrays that were generated with <code>rasterio </code> from raster layers (tif), and ultimately I want to get some basic statistics from each raster layer and append it to a data frame. ...
<p>Considering you have a dict of images:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd vmin, vmax = 0, 255 C, H, W = 2, 64, 64 images_names = [&quot;HH&quot;, &quot;VV&quot;, &quot;VH&quot;, &quot;HV&quot;] images = { im_name: np.random.randint(vmin, vmax, size=(C, H,...
python|pandas|numpy|gdal|rasterio
1
370,308
73,024,921
Flatten list of dicts
<p>I have a pandas dataframe (sample) as follows</p> <pre><code>df = pd.DataFrame({'Country':['India', 'China', 'Nepal'], 'Habitat':[[{'city1':'Ind1','city2':'Ind2'},{'town1':'IndT1','town2':'IndT2'}], [{'city1':'Chi1','city2':'Chi2'},{'town1':'ChiT1','town2':'ChiT2'}], ...
<p>Let us use <code>ChainMap</code> to merge the list of dictionaries in each row, then create a new dataframe and <code>join</code> back with original dataframe</p> <pre><code>from itertools import starmap from collections import ChainMap h = pd.DataFrame(starmap(ChainMap, df['Habitat']), df.index) df.join(h.add_pref...
python|pandas
5
370,309
72,972,301
How can combine or merge all worksheets within an Excel file into one worksheet using python?
<p>I'm trying to merge all worksheet tabs of each excel file within a provided file path into one worksheet. For Example if there's 5 Excel files with multiple amounts worksheet tabs, each Excel file now only contains one merged worksheet tab. I would like to append each of these merged worksheet tabs to a created outp...
<p>If you want to do what is said in the title, you could do this solely with pandas, as <code>pd.read_excel(path_input, sheet_name=None)</code> can read all worksheets of a workbook in one pass:</p> <pre><code>import pandas as pd path_input = r&quot;test.xlsx&quot; path_save = r&quot;finished.xlsx&quot; df_lst = pd....
python|excel|pandas|openpyxl|xlwings
1
370,310
72,901,014
Import dlopen error when trying to Use tensorflow-text package
<p>I recently installed the <code>tensorflow-text</code> package from source with .whl file.</p> <p>I used the command</p> <pre><code>pip install /Users/michaelscoleri/Downloads/tensorflow_text-2.8.2-cp39-cp39-macosx_11_0_arm64.whl </code></pre> <p>to download the package.</p> <p>When importing the packages I get this ...
<p>To avoid this error, Please install <code>tensorflow-text</code> and <code>tf-models-official</code> using below code and restart the kernel(runtime) before executing the above code:</p> <pre><code>!pip install tensorflow-text !pip install tf-models-official </code></pre>
python|tensorflow|conda
0
370,311
73,013,149
How can I speed up reading from socket for non-constant size data structures? Python
<p>I need to communicate with the game (I can't change its code) over a TCP connection. The developers have provided code that can be used to do this. But I came to the conclusion that this python code is too slow, because data structures are read one primitive at a time:</p> <pre><code>bool &lt;- socket_stream.read(1)...
<p>Reading data item per item (from 1 to 8 bytes) is not efficient in Python. You should decode them in a packed way. This is often but not always possible. For example, if you read a string with a prefixed size, then you must read the size in the first place and if the string is zero-terminated then it starts to be tr...
python|numpy|performance|sockets|struct
2
370,312
73,052,216
The display by Bokeh of the geographical map is not the one expected. Why is this?
<p>Importation</p> <pre><code>import pandas as pd import numpy as np </code></pre> <p>Importation for figures</p> <pre><code>from bokeh.plotting import figure, output_notebook, show Display precision in relation with the jupyter cell. output_notebook() </code></pre> <p>Load data</p> <pre><code>df = pd.read_csv(&quot;l...
<p>I reordered your script and I hope that this solves some error. Please check out if this works, because it is working for me.</p> <pre><code>from io import StringIO import pandas as pd import numpy as np from bokeh.tile_providers import get_provider from bokeh.models import ColumnDataSource, LabelSet from bokeh.pl...
python|pandas|bokeh
1
370,313
73,088,340
How to fill NA values with applying condition?
<p>I am trying to replace null values with 0 by applying certain conditions. Here is the code to generate the dataset.</p> <pre><code>data = {'month': ['2022-01-01', '2022-02-01', '2022-03-01', '2022-01-01', '2022-02-01', '2022-03-01', '2022-04-01', '2022-05-01', '2022-06-01', '2022-07-01', '2022-08-01'], 'Date1': ['20...
<p>you can use where the condition</p> <pre><code>import numpy as np import pandas as pd data = {'month': ['2022-01-01', '2022-02-01', '2022-03-01', '2022-01-01', '2022-02-01', '2022-03-01', '2022-04-01', '2022-05-01', '2022-06-01', '2022-07-01', '2022-08-01'], 'Date1': ['2022-01-01', '2022-01-01', '2022-01-01', '2022...
python|pandas|dataframe|imputation|data-science-experience
0
370,314
73,064,668
change dictionary to dictionary series
<p>I have a column</p> <pre><code>index data 1 {'data': '123'} 2 {'data': '123'} 3 {&quot;data&quot;: &quot;123&quot;} </code></pre> <p>I need to change data column to</p> <pre><code>index data 1 {'data': '123'} 2 {'data': '123'} 3 {'data': '123'} </code></pre> <p>The difference is line with index 3 T...
<p>Use list comprehension with <code>if-else</code> for convert strings to dictionaries:</p> <pre><code>import ast df = pd.DataFrame({'data':[{'data': '123'}, {'data': '123'}, '{&quot;data&quot;:&quot;123&quot;}']}) df['data'] = [ast.literal_eval(x) if isinstance(x, str) else x for x in df.data] print (df) ...
python|pandas
1
370,315
73,021,694
Counting values in data frame rows against another df to see how many values are higher
<p>I have two data frames</p> <ul> <li>df2022fl One is a list of 24 rows</li> <li>df One is one row of values</li> </ul> <p>1759 columns in each df.</p> <p>I want to reference every row in dataframe with 24 rows too count how many columns are above the corresponding column in the one row df.</p> <p>I used the code belo...
<p>Compare both the dataframe using</p> <pre><code>df2022fl.ge(df.iloc[0]).sum() </code></pre> <p>This gives us the number of values in df2022fl which is greater than the value in df</p> <p><strong>Output :</strong></p> <pre><code>id 24 table_position 20 performance_r...
python|pandas|dataframe
0
370,316
10,857,924
Remove NaN/NULL columns in a Pandas dataframe?
<p>I have a <code>dataFrame</code> in pandas and several of the columns have all null values. Is there a built in function which will let me remove those columns?</p>
<p>Yes, <code>dropna</code>. See <a href="http://pandas.pydata.org/pandas-docs/stable/missing_data.html">http://pandas.pydata.org/pandas-docs/stable/missing_data.html</a> and the <code>DataFrame.dropna</code> docstring:</p> <pre><code>Definition: DataFrame.dropna(self, axis=0, how='any', thresh=None, subset=None) Docs...
python|pandas|dataframe|nan
118
370,317
70,674,732
How to Get Sum of column value, after groupby another column in Pandas?
<p>I have a Pandas data frame, as shown below, with multiple columns and would like to get the total of column, 'Score' after grouby 'Region','Team'.</p> <p>input: <a href="https://i.stack.imgur.com/K7j5e.png" rel="nofollow noreferrer">input</a></p> <p><strong>Code</strong>:</p> <pre><code>import pandas as pd df=pd.re...
<p>This gives your expected output :</p> <pre><code>df2 = df.groupby(['Team','Region']).sum() df2.rename(columns = {'Score' : 'New Score'}, inplace = True) df2.reset_index() </code></pre>
python|pandas
0
370,318
70,596,758
pandas.concat function doesnt work correctly with my def, how can I improve that?
<p>I have pandas Series as name of; a,b,c,....m I want to concate with</p> <pre><code>newage = pd.DataFrame([]) newage = pd.concat((newage,a),axis=0,ignore_index=False,sort=True) # This way doesn't have any problem, I can take fully filled series, bun If I try this def defage = pd.DataFrame([]) listofage = [a,b,c,d,e...
<pre><code>listofage = [a,b,c,d,e,f,g,h,j,k,l,m] def agefill (listofage): defage = pd.DataFrame([]) for i in listofage: defage = pd.concat((defage,i),axis=0,ignore_index=False,sort=True) return defage print(agefill (listofage)) train_data[&quot;defage&quot;] = agefill (list...
python|pandas
0
370,319
70,455,085
Using a function to create a string from numbers
<p>I am trying to create a function in python that returns the top 10 IDs, by a given column, as a string that will be the value of a new column. For example, if the top 10 ids are [1,2,3,4,5,6,7,8,9,10], the output should be &quot;1 2 3 4 5 6 7 8 9 10&quot;. When I apply the function I have, it just returns blank valu...
<p>One way to form a string from an array of numbers is to use <code>astype</code> to convert them to individual strings:</p> <pre><code>In [206]: x = np.arange(5) In [207]: x.astype('U5') Out[207]: array(['0', '1', '2', '3', '4'], dtype='&lt;U5') </code></pre> <p>Then use <code>join</code> to concatenate them with wha...
python|pandas|function|numpy
0
370,320
70,608,841
Send variable to Dash with call back in Python
<p>is it possible to have a single app.callback running on different matrix inputs? update_figure_matrix is a function that return a figure based on input dataframe, I would like to call this function multi[ule time with different dataframe (matrix), but I don't know how.</p> <pre><code>@app.callback(Output('tabel-mat...
<p>There are two possible approaches:</p> <ol> <li>include an additional input to your callback in order to specify which df you want to use:</li> </ol> <pre><code>matrices = {1: matrix1, 2: matrix2} @app.callback(Output('table-matrix', 'figure'), [Input('radioitems', 'value'), Input('checklist', 'value...
python|pandas|plotly-dash
1
370,321
70,600,793
Exact matching string with "==" operator between Str and a list of strings
<p>I have this example df:</p> <pre><code>df6 = pd.DataFrame({ 'answer1': ['Lo', 'New York', 'Toronto'], 'answer2': ['London', 'New', 'Paris'], 'answer3': ['CA', 'CA', 'CA'], 'correct': [['London'], ['New York'], ['Toronto']] ...
<p>Strip correct of corner brackets , check existence in df and then conditionally copy over the columns</p> <pre><code> df6['answer'] =df6.isin(df6['correct'].str[0].to_list()).agg(lambda s: s.index[s].values, axis=1) df6 answer1 answer2 answer3 correct answer 0 Lo London CA [London] [...
python|python-3.x|pandas|string|list
1
370,322
70,645,284
Matching datetime column in pandas with another datetime column and return index
<p>I have two DataFrames - df1 and df2. Both of them contain a datetime column, say date1 and date2. I want to match each value of date1 column to date2 and store the index in a new column. I am trying the following code:</p> <pre class="lang-py prettyprint-override"><code>df1['location'] = df2.loc[df1['date1'] == df2[...
<p>Try to setup a <a href="https://stackoverflow.com/help/minimal-reproducible-example">MRE</a>:</p> <pre><code>df1 = pd.DataFrame({'date1': pd.date_range('2022-1-1', periods=5, freq='D')}) df2 = pd.DataFrame({'date2': pd.date_range('2022-1-3', periods=4, freq='D')}) # df1 # date1 # 0 2022-01-01 # 1 2022-01-02 ...
python|pandas|dataframe|datetime|indexing
0
370,323
70,591,107
Databricks spark permission denied (Errno 13) on local disk during ETL
<p>We have a custom ETL pipeline running as a python module on a Databricks cluster. At one point in this ETL pipeline we have to create a spark dataframe from multiple pandas dataframes. We do this with:</p> <pre><code>full_data = pd.concat( [self.drift_data.null_proportions, self.drift...
<p>Upgrade your databricks runtime to be version 7.5+, in which databricks creates per notebook home directory on the high concurrency clusters, and you'll not have the permission issue.</p> <p>Refer <a href="https://github.com/Azure/azure-sdk-for-python/issues/9809" rel="nofollow noreferrer">this</a> for more details....
python|pandas|pyspark|permissions|databricks
0
370,324
70,650,545
Pandas .agg() convert to list but skip nans
<p>How do I consolidate/reduce a DataFrame so that it merges rows by custom column 'id' and puts values into a list if they are not Nan. So far I came up with this but it doesn't remove Nans:</p> <pre><code>x: pd.DataFrame = df_chunk.groupby('id', dropna=True).agg(lambda x: list(x)) for row in x.itertuples(): print...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dropna.html" rel="nofollow noreferrer"><code>Series.dropna</code></a> for remove <code>NaN</code>s and <code>None</code>s:</p> <pre><code>df_chunk.groupby('id').agg(lambda x: list(x.dropna())) </code></pre>
python-3.x|pandas|dataframe|aggregate|nan
4
370,325
70,464,158
Pandas df.replace with regex group
<p>I have a column with strings such as: <code>Posted: 1 day ago</code>, <code>Posted: 2 days ago</code>. I want to convert this column to a column of dates, i.e.: <code>datetime.date(2021, 12, 22)</code>, <code>datetime.date(2021, 12, 21)</code>.</p> <p>I tried using regex groups combined with <code>df.replace()</code...
<p>You can't use <code>date - timedelta</code>, but you can use <code>datetime - timedelta</code>:</p> <pre><code>from datetime import datetime, timedelta df['Date'] = datetime.datetime.today() - df.Date.str.extract('Posted: (\d+) days? ago')[0].astype(int).apply(timedelta) </code></pre> <p>Output:</p> <pre><code>&gt;...
python|pandas|datetime
2
370,326
70,722,763
LSTM layer value error: dimension must be equal
<p>I am trying to create a very simple 2 layer LSTM model for sequential prediction. The input data shape is 2D. I want to pad my input but I wasn't sure how to do it, so I manually padded my input data. That is why the pad_inputs is commented out. However, when I run this model I get an error saying:</p> <pre><code>Va...
<p>Problem with <code>l1 = LSTM(...)</code>. LSTM takes specific input dimension, it takes either inputs or mask_inputs. As the error says expected dimension 45 and 400 but given dimension[?,45] and [?, 400]</p> <p><strong>Find the below working sample code</strong></p> <pre><code>import tensorflow as tf n_out = 24 sam...
python|tensorflow|keras|lstm
0
370,327
70,650,810
Skipping na values while reading a csv or excel file
<p>I am reading a csv file which has three columns. I will be using first two columns as multiindex and the third column will be a column value in the dataframe.</p> <p>Raw CSV sample:</p> <pre><code>index1,index2,value a1,b1,20 a1,b2,10 a1,b3,40 a2,b1,10 a2,b2, a2,b3,30 a2,b4,40 </code></pre> <p>Now while reading the ...
<p><strong>Update</strong></p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('data.csv').dropna() for idx, row in df.pivot_table('value', 'index1', 'index2', aggfunc='sum').iterrows(): row.dropna().plot.bar(title=idx) plt.show() </code></pre> <p><a href="https://i.stack.imgur...
python-3.x|pandas|dataframe
0
370,328
70,457,785
How to save a pandas dataframe as excel table to SharePoint using Python
<p>I am trying to save a pandas dataframe as an excel table to a sharepoint site. I have two separate blocks of code which achieve the below.(thanks for Stackoverflow community)</p> <ol> <li>A script which can save a pandas df as excel table using ExcelWriter on local storage.</li> <li>A Script which can save a local f...
<p>Given that you have your data in a <code>df</code> the following code will write to sharepoint using the <a href="https://pypi.org/project/O365/" rel="nofollow noreferrer">O365</a> library.</p> <pre class="lang-py prettyprint-override"><code>from io import BytesIO from tempfile import gettempdir from O365 import Ac...
python|excel|pandas|sharepoint
0
370,329
70,725,243
Concatenate dataframes for Seaborn hue (adding key)
<p>I'd like to make this code more elegant and reduced. I have three data frames that need to be combined to use Seaborn hue. I need to add a key for the hue itself.</p> <p>This is what I have come up with, but I feel there must be a more elegant and efficient way</p> <pre><code>df = pd.DataFrame({ 'A' : range(3), 'B' ...
<p>IIUC, you want to repeat n times <code>df</code> and add n labels (n=3 here).</p> <p>You have several options.</p> <h4>concat + <a href="https://numpy.org/doc/stable/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>np.repeat</code></a></h4> <p>concatenate the input n times, and add the repeated...
python|pandas
1
370,330
70,448,469
Remove consecutive duplicates while keeping the max value
<p>I am trying to remove consecutive duplicates from column X while keeping the entry with the max value based on column Y, unfortunately with no success. The data frame is as follow:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>idx</th> <th>X</th> <th>Y</th> </tr> </thead> <tbody> <tr> ...
<p>You need to apply an <a href="https://stackoverflow.com/questions/32683492/make-pandas-groupby-act-similarly-to-itertools-groupby">itertools-style-groupby</a> and then <a href="https://stackoverflow.com/questions/15705630/get-the-rows-which-have-the-max-value-in-groups-using-groupby">keep the rows where Y is maximal...
python|pandas
3
370,331
70,420,155
How to predict actual future values after testing the trained LSTM model?
<p>I have trained my stock price prediction model by splitting the dataset into train &amp; test. I have also tested the predictions by comparing the valid data with the predicted data, and the model works fine. But I want to predict <em><strong>actual</strong></em> future values.</p> <p>What do I need to change in my ...
<p>Below is an example of how you could implement <a href="https://stackoverflow.com/a/69787683/11989081">this approach</a> for your model:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np from datetime import date from nsepy import get_history from keras.models import Sequenti...
python|tensorflow|machine-learning|keras|lstm
2
370,332
70,384,906
How to get the sum of values from one column with the conditional of another column
<p>For the sample data shown in the below image:</p> <p><a href="https://i.stack.imgur.com/j0XRx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j0XRx.png" alt="enter image description here" /></a></p> <p>How can I get the number of similar items that occur within one column, with the conditional the...
<p>Assuming your data is loaded into a pandas dataframe, you can use:</p> <pre><code># Sample data labels = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;a, b, c&quot;, &quot;b, c&quot;] df = pd.DataFrame({ &quot;customer_id&quot;: [0, 1]*10, &quot;category&quot;: [labels[np.random.randint(0,len(labels ))...
python|pandas|list|dataframe|for-loop
0
370,333
70,430,999
Flatten a Dataframe that is pivoted
<p>I have the following code that is taking a single column and pivoting it into multiple columns. There are blanks in my result that I am trying to remove but I am running into issues with the wrong values being applied to rows.</p> <pre><code>task_df = task_df.pivot(index=pivot_cols, columns='Field')['Value'].reset_i...
<p>This is basically merging all rows having the same name or id together. You can do it with this:</p> <pre><code>mergers = {'ID': 'first', 'Color': 'sum', 'Class': 'sum'} task_df = task_df.groupby('Name', as_index=False).aggregate(mergers).reindex(columns=task_df.columns).sort_values(by=['ID']) </code></pre>
python|pandas|dataframe
0
370,334
70,709,160
Reading labelimg (bounding box) files into pandas dataframe
<p>Hey all couldn't find a good answer to this but I made a little method that worked for me. hope it helps if anyone else is looking. Its a bit hacky but will serve.</p>
<pre><code>``` import pandas as pd import xml.etree.ElementTree as ET test_xml = '/Users/cole/PycharmProjects/Birds/VisualizeConvsTest/Robin.xml' tree = ET.parse(test_xml) root = tree.getroot() labelimg_params = {} #takes an empty dict and adds in the params as we recursively go through the xml file def find_childr...
python|pandas|xml|dataframe|labelimg
0
370,335
70,513,701
Apply conditional statement to specific rows in Python
<p>I have a dataset where I would like a certain statement to only be applied to specific rows in my dataset. I would like this to only be applied to rows that contain [type] == 'aa', and apply second statement for rows that contain [type] == 'bb'</p> <p><strong>Data</strong></p> <pre><code>location type mig1 ...
<pre><code>#Coerce dates to datetime df1=df1.set_index(['location','type']).apply(lambda x: pd.to_datetime(x,format='%d/%m/%Y')) #Set non dates as index, slice level two and impose the datetifference df1.loc[ ( slice(None), 'aa' ), : ]=df1.loc[ ( slice(None), 'aa' ), : ]-pd.to_timedelta(5, unit='d') ...
python|pandas|function|numpy|input
1
370,336
70,410,143
How to calculate revenue by month between years in python?
<p>The columns in the below dataset will represent:</p> <p>A: Date contract opened;</p> <p>B: Date contract stops;</p> <p>C: Unique account ID against which contract associated (can have multiple contracts live against one ID)</p> <p>D: Monthly revenue for contract period - for simplicity, assume revenue generated from...
<p>Maybe you want something like this?</p> <pre><code>date_range = (df['date'] &gt;= &quot;2013-01-01&quot;) &amp; (df['date'] &lt;= &quot;2014-12-31&quot;) df[date_range].groupby(df['date'].dt.strftime('%B')).agg( MRR=('MRR', 'sum'), Contracts=('date', 'count'), Accounts=('Unique Account Field', 'nunique')...
python|python-3.x|pandas|dataframe
1
370,337
70,540,427
Python: How to convert matrix to ASCII string?
<p>I wanna ask about how to convert matrix to string then convert to text?<br /> For example I have matrices from image and have range from 0 - 255:</p> <pre><code>[[224 65 90] [62 125 33] [75 40 94]] </code></pre> <p>I want the output is convert all matrix value to ASCII text with string type like this:</p> <block...
<p>Here is a way to do what you asked:</p> <pre><code>import numpy as np m=np.array([[224, 65, 90], [62 ,125 ,33], [75 ,40 ,94]]) print(''.join(map(chr,m.flatten()))) </code></pre> <p>Updated based on rioV8's comment - no need for a list after <code>join</code>.</p> <p><strong>Output</strong>:</p> <pre><code>Out[34]: '...
python|numpy|image-processing|python-imaging-library
2
370,338
70,660,781
Converting Multi-level columns to single level in Pandas
<p>I have a multi level columns:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Item</th> <th>CBP</th> <th></th> <th>SAC</th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td>Qty</td> <td>Date</td> <td>Qty</td> <td>Date</td> </tr> <tr> <td>Item A</td> <td>20</td> <td>2/10/2021</td> <td>...
<p>Assuming all are columns:</p> <pre><code>idx = pd.MultiIndex.from_arrays([['Item', 'CBP', 'CBP', 'SAC', 'SAC'], [None, 'Qty', 'Date', 'Qty', 'Date']]) df = pd.DataFrame([['Item A', 20, '2/10/2021', 32, '3/12/2022']], columns=idx) </code></pre> <p>You can set the Item columns aside as index and <cod...
python|pandas
0
370,339
70,653,364
model.predict () return an array instead of a number/label
<p>I am trying to used a trained model to predict <code>model.predict(data)</code> a new testing data for classification. However, instead of a number/label, the program returns an array. How to modify my training code to get the output correctly? Thank you. Here is my code.</p> <pre><code>def make_model(input_shape): ...
<p>Your model is performing as expected. Your last layer is calculated using softmax, and produces an array with probabilities of how &quot;sure&quot; it is of being each label.</p> <p>If you want to get the actual predicted label, you can use <code>argmax</code>, along with the correct dimension, which returns the ind...
python|tensorflow|conv-neural-network
1
370,340
70,392,891
How to append to each column of empty pandas data frame different size of lists in a loop?
<p>Hi guys this is getting frustrating.! After long hours of online browsing. I can not find a single source that can help here. How to append to each column of empty pandas data frame different size of lists? For instance, I have these three variables:</p> <pre><code>var1 = ['BBCL15', 'KL12TT', 'TMAA03', '1523FR'] var...
<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; cols = ['col1', 'col2', 'col3'] &gt;&gt;&gt; df = pd.DataFrame(columns=cols) &gt;&gt;&gt; max_len = max([len(var1), len(var2), len(var3)]) &gt;&gt;&gt; for col, var in zip(cols, [var1, var2, var3]): ... df[col] = var+([None]*(max_len - len(var))) &gt;&gt;...
python|pandas|list|dataframe
1
370,341
70,565,690
Get license link from Github with specific commit hash
<p>I have a table (as a Pandas DF) of (mostly) github repos, for which I need to automatically extract the LICENSE link. However, it is a requirement that the link does not just simply go to the /blob/master/ but actually points to a specific commit as the master link might be updated at some point. I assembled a Pytho...
<p>Ok, I found a way to get the unique SHA-hash of the current commit. I believe that should always link to the license file of that point in time.</p> <p>Using the python git library, i simply run the ls_remote git command and return the HEAD sha</p> <pre><code>def lsremote_HEAD(url): g = git.cmd.Git() HEAD_sh...
python|pandas|github|github-api
0
370,342
70,475,752
Creating your own dataset in tensorflow
<p>I am faced with the task of classifying sound by spectrograms. I have a solution to this problem in one way (I will convert all audio recordings into spectrograms -&gt; save them as pictures and train a neural network for this), but I want to go the simpler way, that is, not save pictures, but immediately convert au...
<p>If you read the <a href="https://www.tensorflow.org/tutorials/audio/simple_audio#convert_waveforms_to_spectrograms" rel="nofollow noreferrer">documentation</a> there are code patterns.</p> <p>This is not tested but if you load the index from another data structure which has mapped the files to the indexes then this ...
python|tensorflow|pytorch|conv-neural-network
0
370,343
70,437,946
keep only ids that have all three values of the column Mode
<p>I have a pandas dataframe with multiple columns, which looks like the following:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Index</th> <th style="text-align: center;">ID</th> <th style="text-align: center;">Year</th> <th style="text-align: center;">Code</th...
<p>You can try</p> <pre><code>out = df.groupby('ID').filter(lambda x : pd.Series([1,2,3]).isin(x['Mode']).all()) Out[9]: Index ID Year Code Type Mode 0 0 100 2018 ABC 1 1 1 1 100 2019 DEF 2 2 2 2 100 2019 GHI 3 3 </code></pre>
python|pandas
2
370,344
70,422,150
Getting the max value from a list of columns by their index in Pandas
<p>I have a dataframe with a variety of columns, but the key part of data I am looking to extract is in columns which are named using datetime values which hold a floating point number for currency.</p> <p>I am basically just looking to find the max value of any column that is of a date value (i.e. 2021-01-15 00:00:00)...
<p>You can find the 'date' columns using a list comprehension which will return the columns that contain <code>/</code>. Then you can use <code>max(axis=1)</code> to create the column which will show the highest value per row, of your date like columns:</p> <pre><code>date_cols = [c for c in list(df) if '/' in c] df['m...
python|pandas
1
370,345
70,664,177
Better way to plot Gender count using Python
<p>I am making a graph to plot Gender count for the time series data that look like following data. Each row represent hourly data of each respective patient.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">HR</th> <th style="text-align: center;">SBP</th> <th sty...
<p>I have a working example for selecting the unique IDS, it looks ugly so there is probably a better way, but it works...</p> <pre><code>import pandas as pd # example of data: data = {'gender': [0, 0, 1, 1, 1, 1, 0, 0], 'id': [1, 1, 2, 2, 3, 3, 4, 4]} df = pd.DataFrame(data) # get all unique ids: ids = set(df.id) # Go...
python|pandas|matplotlib|plot|seaborn
0
370,346
70,540,134
How to make conditional judgments on several columns in pandas?
<p>I have a dataframe:</p> <p><a href="https://i.stack.imgur.com/ilYZg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ilYZg.png" alt="enter image description here" /></a></p> <p>I want to calculate the number of devices sold to hospitals by sales people.</p> <p>There are several scenarios:</p> <ol> ...
<p>IIUC use:</p> <pre><code>#test all rows with at least one non NaN, Nat, None values m = df[['Signing time', 'Arrival time']].notna().any(axis=1) #get sums per Hospitals of Trues df['Number of equipment'] = df.assign(m = m).groupby(['Hospital'])['m'].transform('sum') #remove duplicates per both columns df = df.drop...
python|pandas
1
370,347
70,589,601
Creating a dictionary from a csv file. I am taking the csv file as an input in an api endpoint in fastapi (file: UploadFile = File(...))
<p>I basically want to take a CSV file as input, and return a dictionary as a response. Since the default fastapi UploadFile module returns a spooled temp file, which i can't use as an input to pandas.read_csv(), what i am trying to do is write the contents of the uploaded file to another file buffer, and than use read...
<p>I resolved the issue, instead of writing data to a new file, we can indeed encode the data to UTF-8 instead of reading bytes.</p> <p>Using the default CSV module, we can pass the file after decoding it:</p> <pre><code>iterator = csv.reader(codecs.iterdecode(data.file, 'utf-8'), delimiter=',') </code></pre> <p>This &...
python|pandas|csv|fastapi
0
370,348
70,389,549
Assign lables for previous n days based on condition
<p>Hi i have problem with calculating/labelling the dates previous 11 days (irrespective of repeated or missing).<br /> I need to assaign lables in &quot;Day_mark&quot; column for previous 11 days(or n days dynamically) lables when i found '1' in column 'day'<br /> Below is my dataset and required column is 'Day_mark'<...
<p>First create groups column by shift mask with compare <code>1</code>, change order by <code>iloc</code> and add cumulative sum and then remove duplicates by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>DataFrame.drop_duplica...
python|pandas|python-datetime
2
370,349
70,712,915
How do I optimise numpy.packbits with numba?
<p>I'm trying to optimise <code>numpy.packbits</code>:</p> <pre><code>import numpy as np from numba import njit, prange @njit(parallel=True) def _numba_pack(arr, div, su): for i in prange(div): s = 0 for j in range(i*8, i*8+8): s = 2*s + arr[j] su[i] = s def numba_packb...
<p>There are several issue with the Numba implementation. One of them is that parallel loops <strong>breaks the constant propagation optimization in LLVM-Lite</strong> (the JIT-compiler used by Numba). This cause critical information like array strides not to be propagated resulting in a slow scalar implementation inst...
python|numpy|numba|bit-packing
2
370,350
42,898,678
Pandas - Counting the number of days for group by
<p>I want to count the number of days after grouping by 2 columns:</p> <pre><code>groups = df.groupby([df.col1,df.col2]) </code></pre> <p>Now i want to count the number of days relevant for each group:</p> <pre><code>result = groups['date_time'].dt.date.nunique() </code></pre> <p>I'm using something similar when I ...
<p>You need another variation of <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#dataframe-column-selection-in-groupby" rel="nofollow noreferrer"><code>groupby</code></a> - define column first:</p> <pre><code>df['date_time'].dt.date.groupby([df.col1,df.col2]).nunique() </code></pre> <hr> <pre><code...
python|date|pandas|group-by
3
370,351
42,955,576
How to concatenate large dataset into dataframe pandas
<p>So I am working with a fairly substantial CSV dataset that has couple hundred megabytes. I have managed to read in the data in chunks (~100 rows). How do i then elegantly convert those chunks into a dataframe and apply the describe function to it? Thank you</p>
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> of <code>TextFileReader</code> object what is output of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"...
python|pandas
2
370,352
43,017,597
Comparing values within the same dataframe column
<p>Is there anyway to compare values within the same column of a pandas DataFrame?</p> <p>The task at hand is something like this:</p> <pre><code>import pandas as pd data = pd.DataFrame({"A": [0,-5,2,3,-3,-4,-4,-2,-1,5,6,7,3,-1]}); </code></pre> <p>I need to find the maximum time (in indices) consecutive +/- values ...
<p>Here's a NumPy approach that computes the max interval lengths for the positive and negative values -</p> <pre><code>def max_interval_lens(arr): # Store mask of positive values pos_mask = arr&gt;=0 # Get indices of shifts idx = np.r_[0,np.flatnonzero(pos_mask[1:] != pos_mask[:-1])+1, arr.size] ...
python|pandas|numpy
2
370,353
42,919,436
Keras getting output of intermidate layers
<pre><code>## what my model looks like # defining the model archictecture model = Sequential() # 1st conv layer model.add(Conv2D(32, (5, 5), activation='relu', input_shape=x_ip_shape)) # 1st max pool model.add(MaxPooling2D(pool_size=(2, 2))) # 2nd conv layer model.add(Conv2D(64, (7, 7), activation='relu')) # 2nd max p...
<p>The <code>get_3rd_layer_output</code> is a Theano function. You do not need to make many modifications in it. </p> <p><code>model.layers[0].input</code> will stay as it is if you want the output (of any layer) given input of the first layer in the network. In other words, if you want output of some layer given 4th ...
tensorflow|neural-network|keras|conv-neural-network
4
370,354
43,021,762
Matplotlib how to change figsize for matshow
<p>How to change figsize for <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.matshow" rel="noreferrer">matshow()</a> in jupyter notebook?</p> <p>For example this code change figure size</p> <pre><code>%matplotlib inline import matplotlib.pyplot as plt import pandas as pd d = pd.DataFrame({'one' ...
<p>By default, <code>plt.matshow()</code> produces its own figure, so in combination with <code>plt.figure()</code> two figures will be created and the one that hosts the matshow plot is not the one that has the figsize set.</p> <p>There are two options:</p> <ol> <li><p>Use the <code>fignum</code> argument</p> <pre>...
python|pandas|matplotlib
49
370,355
43,008,892
How to aggregate a boolean field with null values with pandas?
<p>I'm working with pandas for the first time and I'm having some issues with aggregation. I have a dataframe with three calculated fields added by an apply statement like this:</p> <pre><code>dataset['calculated_field'] = dataset.apply( lambda row: calculation_function( row['field1'], row['field2'...
<p>Convert them to numeric columns. The <code>None</code> will become <code>NaN</code>, <code>True</code>s become <code>1</code>, and <code>False</code>s become <code>0</code>. A convenient way to convert the whole dataframe is to use <code>pd.to_numeric</code> with the <code>errors</code> parameter set to <code>igno...
python|pandas|aggregate
4
370,356
42,978,704
what happens when I modify a pandas dataframe in the following way
<p>trying to understand this behavior (why it happens; and if it was intentional, then what was the motivation for it to be done this way)</p> <p>So I create a dataframe</p> <pre><code>np.random.seed(0) df = pd.DataFrame(np.random.random((4,2))) 0 1 0 0.548814 0.715189 1 0.602763 0.544883 2 0...
<p>Because it added <code>third</code> as an attribute, you should stop accessing columns as an attribute and always use <code>df['third']</code> to avoid ambiguous behaviour.</p> <p>You should get into the habit of always accessing and assigning columns using <code>df[col_name]</code>, this is to avoid problems like<...
python|pandas
6
370,357
42,597,701
how to find libstdc++.so.6: that contain GLIBCXX_3.4.19 for RHEL 6?
<p>I work with a Linuxs server:</p> <pre><code>&gt; cat /etc/redhat-release Red Hat Enterprise Linux Server release 6.7 (Santiago) </code></pre> <p>(from wikipedia: <em><strong>Red Hat Enterprise Linux 6</strong></em> was forked from <em><strong>Fedora 12</strong></em></p> <pre><code>6.7, also termed Update 7, 22 July ...
<p>Updated steps (because it seems the file has been moved):</p> <pre><code>curl -O http://ftp.de.debian.org/debian/pool/main/g/gcc-4.7/libstdc++6-4.7-dbg_4.7.2-5_i386.deb tar -x libstdc++6-4.7-dbg_4.7.2-5_i386.deb &amp;&amp; tar xvf data.tar.gz mkdir backup cp /usr/lib/libstdc++.so* backup/ cp ./usr/lib/i386-linux-gnu...
linux|tensorflow|libstdc++|rhel6
3
370,358
43,027,876
String formatting for Python datetimes with (slightly) wonky timezones using Pandas
<p>I am having trouble parsing timestamps for my data using Pandas.</p> <p>An example of the datetime format that I am trying to parse looks like <code>2012-05-02 01:00:00-05:00</code>. From the Pandas docs I was driven to the relevant <a href="https://docs.python.org/3.6/library/datetime.html#strftime-and-strptime-b...
<p>You can cook up a function to convert your date string format. Then it can be applied to the column to convert to datetimes. This function can return timezone <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow noreferrer">aware or naive timestamps</a>.</p> <p><strong>Code:</strong></p> <pre>...
python|pandas|datetime
4
370,359
42,663,005
How to upsample without filling the gaps in the datetime
<p>Given the following 1 hour dataframe:</p> <pre><code> column1 datetime 2016-08-09 19:00:00 1 2016-08-09 20:00:00 2 2016-08-10 06:00:00 3 2016-08-10 07:00:00 4 </code></pre> <p>When I try to up-sample the data to a 10 min timeframe using this method: </p> <pre><cod...
<p>You need to have a good definition of what a gap is. Assuming in your example that the interval is a constant 1 hour, anything longer will be a gap. </p> <p>Given the above assumption, first reindexing to an hourly interval, and then resampling to 10Min will do the job.</p> <pre><code>idx = pd.DatetimeIndex(start=...
python|pandas
2
370,360
42,920,363
How to expand one column in Pandas to many columns?
<p>As the title, I have one column (series) in pandas, and each row of it is a list like <code>[0,1,2,3,4,5]</code>. Each list has 6 numbers. I want to change this column into 6 columns, for example, the <code>[0,1,2,3,4,5]</code> will become 6 columns, with <code>0</code> is the first column, <code>1</code> is the sec...
<p>Not as fast as @jezrael's solution. But elegant :-)</p> <p><code>apply</code> with <code>pd.Series</code></p> <pre><code>df.a.apply(pd.Series) 0 1 2 3 4 5 0 0 1 2 3 4 5 1 0 1 2 3 4 5 </code></pre> <p>or</p> <pre><code>df.a.apply(pd.Series, index=list('abcdef')) a b c d e f 0 0 1 ...
python|pandas|scikit-learn|bigdata
9
370,361
42,661,528
Pandas: get average over certain rows and return as a dataframe
<p>I have a df like this</p> <p><a href="https://i.stack.imgur.com/V4BoF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V4BoF.png" alt="enter image description here"></a></p> <p>It contains <code>speed</code> and <code>dir</code> at different date's hour minute. For example, the first row records ...
<p>What you are getting is a multi-index dataframe. you can try </p> <pre><code>df.groupby(['date', 'Hr'])['speed'].mean().reset_index() </code></pre> <p>If you want mean for rest of the data, try</p> <pre><code>df.groupby(['date', 'Hr'])['speed', 'dir_max', 'speed_max'].mean().reset_index() </code></pre> <p>EDIT: ...
python|pandas
1
370,362
42,965,230
Distributed training of tf.learn Estimators?
<p>I want to train a Convolutional Neural Network on MNIST in a distributed way, using Tensorflow high-level apis. I tried to specify a cluster configuration, and pass it to an Estimator (code below). </p> <p>I am getting the following error <strong>Parameter to MergeFrom() must be instance of same class: expected t...
<p>If u want to run a distributed estimator in TF, there is an instance:</p> <pre><code>from tensorflow.contrib.learn.python.learn import learn_runner from tensorflow.contrib.learn.python.learn.estimators import run_config ... learn_runner.run( experiment_fn=create_experiment_fn(config), output_dir=output_dir) <...
python|machine-learning|tensorflow|computer-vision|distributed-computing
1
370,363
42,680,299
Is there a way to calculate the slope for each successive point in two data frames, store all the values for slope and then plot it?
<pre><code>df = pd.read_csv('data.csv') v = df['Gate V'] i1 = df['Drain I.1'] Drain V Gate V Drain I 0 0.01 -5.00 3.270000e-14 1 0.01 -4.85 1.740000e-14 2 0.01 -4.70 2.620000e-14 3 0.01 -4.55 6.270000e-14 ...
<p>The slope as you calculate it in your loop is just the ratio of the successive diffs in the two columns:</p> <pre><code>deltas = df.diff().drop(0) slope = deltas['Drain I'] / deltas['Gate V'] </code></pre> <p>The <code>.drop(0)</code> will remove the first row of the diffs, which will be all NaNs to preserve the o...
python|python-3.x|pandas|numpy|matplotlib
2
370,364
42,683,039
pandas, apply function and lambda
<p>In the following pandas code, why is <code>df</code> not need in the arguments?</p> <pre><code>df.groupby('Category').apply(lambda df,a,b: sum(df[a] * df[b]), 'Weight (oz.)', 'Quantity') </code></pre>
<p>The first parameter is passed implicitly to a function in the apply call. Therefore, it does not appear in the args again. You could actually rewrite the anonymous function in the apply to </p> <pre><code> df.groupby('Category').apply(lambda x: sum(x["Weight (oz.)"] * x["Quantity"])) </code></pre> <p>without using...
python|pandas|dataframe
1
370,365
42,603,407
How to compile Tensor Flow with SSE and AVX instructions on Windows?
<p>With the latest version of Tensor Flow now on windows, I am trying to get everything working as efficiently as possible. However, even when compiling from source, I still can't seem to figure out how to enable the SSE and AVX instructions.</p> <p>The default process: <a href="https://github.com/tensorflow/tensorflow...
<p>Well, I tried to fix that, but I am not sure if it really worked.</p> <p>In <code>CMakeLists.txt</code> you will find the following statements:</p> <pre><code>if (tensorflow_OPTIMIZE_FOR_NATIVE_ARCH) include(CheckCXXCompilerFlag) CHECK_CXX_COMPILER_FLAG("-march=native" COMPILER_OPT_ARCH_NATIVE_SUPPORTED) </cod...
c++|windows|msbuild|tensorflow
6
370,366
42,965,670
InceptionV4 and V2 giving low accuracy on "flower dataset" than InceptionV1
<p>I am using the following code to train flower dataset on InceptionV1. This code is provided <a href="https://github.com/tensorflow/models/blob/master/slim/slim_walkthrough.ipynb" rel="nofollow noreferrer">Here</a></p> <pre><code>import os from datasets import flowers from nets import inception from preprocessing i...
<p>There are many things that may go wrong when fine-tuning a fairly large convolutional network like Inception V3. Here are some pointers you could look into to improve your model:</p> <ul> <li>The training code you've posted above excludes the <code>InceptionV1/Logits</code> and <code>InceptionV1/AuxLogits</code> fr...
python|machine-learning|tensorflow|tf-slim
1
370,367
42,771,110
Fastest way to left-cycle a numpy array (like pop, push for a queue)
<p>With numpy arrays, I want to perform this operation:</p> <ul> <li>move <code>x[1],...,x[n-1]</code> to <code>x[0],...,x[n-2]</code> (left shift),</li> <li>write a new value in the last index: <code>x[n-1] = newvalue</code>.</li> </ul> <p>This is similar to a <code>pop()</code>, <code>push(newvalue)</code> for a fi...
<p>After some experiments, it is clear that:</p> <ul> <li>copying is required,</li> <li>and the fastest and simplest way to do that, for <code>nparray</code> (numpy arrays) is a slicing and copying.</li> </ul> <p>So the solution is: <code>x[:-1] = x[1:]; x[-1] = newvalue</code>.</p> <p>Here is a small benchmark:</p>...
python|arrays|performance|numpy|optimization
17
370,368
43,026,647
How can I count the number of rows that are not zero in a certain range in python?
<p>I have a pandas Series that consists of numbers either 0 or 1.</p> <pre><code>2016-01-01 0 2016-01-02 1 2016-01-03 1 2016-01-04 0 2016-01-05 1 2016-01-06 1 2016-01-08 1 ... </code></pre> <p>I want to make a dataframe using this Series, adding another series that provides information on how man...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>rolling</code></a> for this which creates a sized <em>window</em> and iterates over your given column while applying an aggregation like sum.</p> <p>First create some dummy data:...
python|pandas
3
370,369
42,957,868
Efficient repeated numpy.where
<p>I have a code in which I want to check whether pairs of coordinates fall into certain rectangles. However, there are many rectangles and i am not sure how to generalize the following code to many rectangles. I only can do it using <code>eval</code> in a loop but that is quite ugly.</p> <p>Here is a code which check...
<p>matplotlib has a built-in routine <code>contains_point</code> for checking if a point is contained in a polygon object which is quite fast.</p> <pre><code>from matplotlib.patches import Rectangle rec1 = Rectangle((0, 0), 100, 100) rec1.contains_point((1, 1)) # True rec1.contains_point((101, 101)) # False </code></...
python|pandas|numpy|where|computational-geometry
2
370,370
27,206,168
Create a MultiIndexed DataFrame from a DataFrame with dict values
<p>I have a Python Pandas DataFrame like this</p> <pre><code>df = pd.DataFrame({'o': [{'ask':1, 'bid':2},{'ask':3, 'bid':4}], 'h': [{'ask':5, 'bid':6},{'ask':7, 'bid':8}]}) h o 0 {u'ask': 5, u'bid': 6} {u'ask': 1, u'bid': 2} 1 {u'ask': 7, u'bid': 8} {u'ask': 3, u'bid'...
<p>one possibility:</p> <pre><code>&gt;&gt;&gt; df h o 0 {'bid': 6, 'ask': 5} {'bid': 2, 'ask': 1} 1 {'bid': 8, 'ask': 7} {'bid': 4, 'ask': 3} &gt;&gt;&gt; d = df.to_dict() &gt;&gt;&gt; pd.concat(list(map(pd.DataFrame, d.values())), keys=list(d.keys())).T h o ...
python|pandas
0
370,371
26,975,769
Modify a particular row/column of a NumPy array
<p>How do I modify particular a row or column of a NumPy array?</p> <p>For example I have a NumPy array as follows:</p> <pre><code>P = array([[1, 2, 3], [4, 5, 6]]) </code></pre> <p>How do I change the elements of first row, <code>[1, 2, 3]</code>, to <code>[7, 8, 9]</code> so that the <code>P</code> will...
<p>Rows and columns of NumPy arrays can be selected or modified using the square-bracket indexing notation in Python.</p> <p>To select a <em>row</em> in a 2D array, use <code>P[i]</code>. For example, <code>P[0]</code> will return the first row of <code>P</code>. </p> <p>To select a <em>column</em>, use <code>P[:, i]...
python|arrays|numpy
61
370,372
27,219,828
Convert Pandas Dataframe to specific json format
<p>I have been looking at different methods to export pandas dataframes into json files but I am not sure how to include other string 'constants' into the JSON.</p> <p>The purpose is to spit out a JSON file that can be read by chart.js.</p> <p>The format of the pandas dataframe for the example is:</p> <pre><code>df ...
<p>I recommend using a templating library like <a href="http://www.makotemplates.org/" rel="nofollow">mako</a> or <a href="http://jinja.pocoo.org/" rel="nofollow">jinja</a>. Here's a quick mako file that contains your JSON, but references a <code>DataFrame</code> argument <code>df</code> which mako will pass to it when...
python|json|pandas
2
370,373
27,024,451
Get value of a Pandas GroupBy Object
<pre><code>group.Units[group['Channel'].map(lambda x: x.startswith('F'))] </code></pre> <p>gives me a Series</p> <pre><code>0 4 </code></pre> <p>How can I get only the value from this GrupBy Object? I.e.:</p> <pre><code>4 </code></pre>
<pre><code>group.Units[group['Channel'].map(lambda x: x.startswith('F'))].values[0] </code></pre>
pandas
0
370,374
27,054,593
Writing DataFrame to CSV with add header name for row names in Pandas
<p>I have the following Data frame:</p> <pre><code>In [18]: import pandas as pd In [32]: df = pd.DataFrame.from_items([("A\tbar", [1, 2, 3]), ("B\tfoo" , [4, 5, 6])],orient='index', columns=['one', 'two', 'three']) In [33]: df Out[35]: one two three A\tbar 1 2 3 B\tfoo 4 5 6 In [34]: df....
<p>Thanks to BrenBarn for <code>index=False</code></p> <pre><code>df = pd.DataFrame.from_items([("A\tbar", [1, 2, 3]), ("B\tfoo" , [4, 5, 6])],orient='index', columns=['one', 'two', 'three']) df['col_a'] = df.index lista = [item.split('\t')[0] for item in df['col_a']] listb = [item.split('\t')[1] for item in df['col_a...
python|pandas
1
370,375
26,982,467
Split items in a series
<p>I have a series that looks like this;</p> <pre><code>Name: TOR, Length: 162, dtype: object, ['TOR'], 0 [W, 9-7] 1 [W, 5-1] 2 [W, 8-2] 3 [L, 1-2] 4 [L, 2-6] 5 [W, 2-1] </code></pre> <p>etc.,</p> <p>The data comes from a pandas data frame where each team has a column with the above d...
<h3>Update</h3> <p>As OP has changed the requirements, I have updated this answer to have a more straight forward approach.</p> <p>Here is a working solution, probably not the best, but for one-off it does the work. Rather than converting the Series to workable DataFrame, you should tackle the source and read into Da...
python|pandas
1
370,376
14,466,713
Element-wise matrix operation returns zero (due to integer division)
<p>I'm plotting a 3D surface in Python. Here muy1 and muy2 are two matrices created by meshgrid:</p> <pre><code>[[-5. -4.75 -4.5 ..., 4.25 4.5 4.75] [-5. -4.75 -4.5 ..., 4.25 4.5 4.75] [-5. -4.75 -4.5 ..., 4.25 4.5 4.75] ..., [-5. -4.75 -4.5 ..., 4.25 4.5 4.75] [-5. -4.75 -4.5 ...,...
<p><code>temp</code> is zero because it starts with <code>1/2</code>, which is integer division (resulting in zero). Use <code>1./2</code> or <code>0.5</code> in both places to prevent that.</p> <pre><code>temp=1./2*(1-muy1)**2-1./2*(1-muy2)**2 </code></pre>
python|matrix|numpy|matplotlib|plot
3
370,377
14,766,155
Pandas AssertionError: Must be mixed type DataFrame
<p>I'm still having issues with Pandas importing data and it has been giving me headaches. I have some previous posts. Anyway my lastest attempt at a simple CSV file resulted in an "AssertionError: Must be mixed type DataFrame" in frame.py. In that example I could import a CSV file I made if I only imported columns ...
<p>I also get this assertion in Wing. </p> <p>There is a check box on the upper left corner of the "Exceptions" tab in Wing labeled "Ignore this exception location", I checked that off and Wing stopped bugging me about it.</p>
csv|import|pandas
0
370,378
14,638,606
What numerical optimizers can operate with only gradients, and no explicit value of the objective?
<p>I have an optimization problem that involves minimizing a function whose gradient I know, but the actual value of objective function at any point is unknown.</p> <p>I'd like to optimize the function using BFGS, but all of the BFGS implementations I've found seem to require knowledge of the value of the objective, e...
<p>I believe you've reduced the problem to a one of finding roots. You could use one of the <a href="http://docs.scipy.org/doc/scipy/reference/optimize.nonlin.html#module-scipy.optimize.nonlin" rel="nofollow">root finders in scipy</a>, then you simply have to check to see if that point is a minimum, maximum or inflecti...
r|optimization|numpy|numerical-methods|numerics
3
370,379
14,572,933
Contours around scipy labeled regions in a 2D grid
<p>I'm trying to find the bounding polygons of all of the wholes in a 2D grid with a large no-data value (1e6). I've got the listing of holes working using scipy's label. Without dipping into gdal's polygonalize, is there an easy way to generate the bounding polygons? I see that there is matplotlib.pylab.contour, bu...
<p>Thanks to Joe Kington for pointing me to Scikit Image.</p> <pre><code>from skimage import measure contours = measure.find_contours(labels, 1) contours[-1] array([[ 2686.99905927, 1054. ], [ 2686. , 1053.00094073], [ 2685.00094073, 1054. ], [ 2686. , 1054.9990592...
numpy|scipy|gis
5
370,380
14,639,496
How to create a numpy array of arbitrary length strings?
<p>I'm a complete rookie to Python, but it seems like a given string is able to be (effectively) arbitrary length. i.e. you can take a <code>string str</code> and keeping adding to it: <code>str += "some stuff..."</code>. Is there a way to make an array of such strings?</p> <p>When I try this, each element only stor...
<p>You can do so by creating an array of <code>dtype=object</code>. If you try to assign a long string to a normal numpy array, it truncates the string:</p> <pre><code>&gt;&gt;&gt; a = numpy.array(['apples', 'foobar', 'cowboy']) &gt;&gt;&gt; a[2] = 'bananas' &gt;&gt;&gt; a array(['apples', 'foobar', 'banana'], ...
python|arrays|string|numpy
143
370,381
25,287,557
DataFrameGroupBy object Column Name
<p>I have a DataFrameGroupBy object (i.e. it's not a dataframe but a grouped by dataframe) that has duplicate column name. How do I change one of the duplicate column name. ( use of .rename has been unsuccessful)</p> <p>Since there are two column names with the same 'label' how do I keep one of the column name intact ...
<p>Why not just calculate the column before you group?</p> <pre><code>df['PriceSquared'] = df['Price'] * 2 dfg = df.groupby(['Sector', 'Price', 'PriceSquared']) </code></pre> <p>EDIT: As far as I'm aware, the two ways to rename a series are:</p> <pre><code>s = df.Price * 2 s.name = 'PriceSquared' </code></pre> <p>o...
python|pandas|rename|dataframe
2
370,382
25,250,784
Pandas Dataframe Series To List - Suppress Float Scientific Notation
<p>I have a Pandas DataFrame with a float column that I convert to a list, then convert to a string, and then write to a text file for another use. </p> <p>For example:</p> <pre><code>df=pd.DataFrame([[0.0068149439999999999, 0.90550613999999996], [7.5699999999999997e-05, 0.48159182100000003], [0.009679478,...
<p>(just realized I'm late with an answer but I'll leave this an an alternate answer if you want finer control over the output format) Just replace the TextToWrite line with:</p> <p><code>TextToWrite = 'ColumnA = ' + ' %12.7f'*4 % tuple( df['ColumnA'].tolist() )</code></p> <p>to get this:</p> <p><code>ColumnA = ...
python|pandas
0
370,383
25,406,691
could not read ascii file
<p>I have a text file looks like below, I could not read the last column. How to know the delimiter?</p> <pre><code>data = np.genfromtxt(f,usecols=(5),delimiter=' ',dtype=float) print data </code></pre> <p>text file called f:</p> <pre><code> 22219355 02/21/2003 10:24:31.843 -65.033577 65.429672 25.193 ...
<p>Try with <code>delimiter=None</code></p> <p>By default, genfromtxt assumes delimiter=None, meaning that the line is split along white spaces (including tabs), and this probably suits your needs</p>
python|numpy
3
370,384
25,273,180
dataframe boolean selection along columns instead of row
<p>Suppose I have the following dataframe:</p> <pre><code> a b c d 0 0.049531 0.408824 0.975756 0.658347 1 0.981644 0.520834 0.258911 0.639664 2 0.641042 0.534873 0.806442 0.066625 3 0.764057 0.063252 0.256748 0.045850 </code></pre> <p>and I want only the subset of co...
<p>How about this?</p> <pre><code>df.loc[:, df.iloc[0, :] &gt; 0.5] </code></pre>
python|pandas
7
370,385
25,060,103
Determine sum of numpy array while excluding certain values
<p>I would like to determine the sum of a two dimensional <code>numpy</code> array. However, elements with a certain value I want to exclude from this summation. What is the most efficient way to do this?</p> <p>For example, here I initialize a two dimensional <code>numpy</code> array of 1s and replace several of them...
<p>Use numpy's capability of <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html" rel="noreferrer">indexing with boolean arrays</a>. In the below example <code>data_set!=2</code> evaluates to a boolean array which is <code>True</code> whenever the element is not 2 (and has the correct shape). So <code>da...
python|arrays|numpy|sum
12
370,386
25,029,583
is there any quick function to do looking-back calculating in pandas dataframe?
<p>I wanna implement a calculate method like <strong>a simple scenario</strong>: </p> <blockquote> <p>value computed as the sum of daily data during the previous N days (set N = 3 in the following example)</p> </blockquote> <p>Dataframe df: (df.index is 'date') </p> <pre><code>date value 20140718 1 201407...
<p>Since you want the sum of the previous three excluding the current one, you can use <code>rolling_apply</code> over the a window of four and sum up all but the last value.</p> <pre><code>new = rolling_apply(df, 4, lambda x:sum(x[:-1]), min_periods=4) </code></pre> <p>This is the same as shifting afterwards with a...
python|pandas
0
370,387
25,047,818
Aggregating unbalanced panel to time series using pandas
<p>I have an unbalanced panel that I'm trying to aggregate up to a regular, weekly time series. The panel looks as follows:</p> <pre><code>Group Date value A 1/1/2000 5 A 1/17/2000 10 B 1/9/2000 3 B 1/23/2000 7 C 1/22/2000 20 </code></pre> <p>To...
<p>Assume <code>df</code> is your second dataframe with weeks, you can try the following:</p> <pre><code>df.groupby('week').sum()['value'] </code></pre> <p>The documentation of <code>groupby()</code> and its application is <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">here</a>. It'...
python|pandas
1
370,388
25,247,373
Need nose >= 0.10.0 error while attempting to install Theano on Ubuntu
<p>Overall I've had a hell of a time getting Theano to work, I've gotten to the stage where I <em>think</em> everything in stalled correctly. Running:</p> <pre><code> sudo apt-get install python-numpy python-scipy python-dev python-pip python-nose g++ libopenblas-dev git </code></pre> <p>and the console tells me t...
<p>If you use <code>Anaconda</code> simply try this whet your <code>conda</code> environment is activated:</p> <pre><code>conda install nose </code></pre> <p>I had the same issue and <code>conda install</code> works without any <code>pip</code>!</p>
ubuntu|numpy|nose|theano
1
370,389
30,655,891
How to handle large files in python?
<p>I am new in python. I have asked another question <a href="https://stackoverflow.com/questions/30654895/how-to-arrange-three-lists-in-such-a-way-that-the-sum-of-corresponding-elements">How to arrange three lists in such a way that the sum of corresponding elements if greater then appear first?</a> Now the problem is...
<p>If you're going to use numpy, then I suggest using <code>ndarray</code>s, rather than lists. You can use <code>loadtxt</code> since you don't have to handle missing data. I assume it'll be faster.</p> <pre><code>a = np.loadtxt('file.txt', usecols=(0, 1, 2)) </code></pre> <p><code>a</code> is now a two-dimensional ...
arrays|list|file|python-3.x|numpy
1
370,390
30,644,179
downsampling data using timestamp information
<p>I have an array of some arbitrary data <code>x</code> and associated timestamps <code>t</code> that correspond to the data in <code>x</code> (they are the same length <code>N</code>).</p> <p>I want to downsample my data <code>x</code> to a smaller length <code>M &lt; N</code>, such that the new data is roughly equa...
<p>I'd suggest using <code>pandas</code>, specifically the <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a> function:</p> <blockquote> <p>Convenience method for frequency conversion and resampling of regular time-series data.</p> </b...
python|numpy|time-series
1
370,391
30,701,068
Python Pandas Boolean Dataframe Where Dataframe Equals False - Returns 0 instead of False?
<p>If I have a <code>Dataframe</code> with <code>True</code>/<code>False</code> values only like this:</p> <pre><code>df_mask = pd.DataFrame({'AAA': [True] * 4, 'BBB': [False]*4, 'CCC': [True, False, True, False]}); print(df_mask) AAA BBB CCC 0 True False ...
<p>Not entirely sure why, but if you're looking for a quick fix to convert it back to bools you can do the following:</p> <pre><code>&gt;&gt;&gt; df_bool = df_mask.where(df_mask == False).astype(bool) &gt;&gt;&gt; df_bool AAA BBB CCC 0 True False True 1 True False False 2 True False True 3 True ...
python|pandas|boolean|where|dataframe
1
370,392
30,439,552
Match a large number of keywords in each line of a large file (>3 million lines; ~4 GB size)
<p>I have a large(>3 million rows; ~4 GB size) csv file with following columns:</p> <p>post_category, post_content, post_date</p> <p>The column 'post_content' is of particular interest to me, and contains medical-domain text of the following form:</p> <p>"Extracorporeal shock wave lithotripsy (ESWL) is commonly used...
<p>I would cut down the number of rows to search by running grep for "Pancrea" first:</p> <pre><code>grep -i pancrea filename.csv | awk -F: '{ print $2 }' &gt; smaller.csv </code></pre>
python|regex|pandas|multiprocessing
0
370,393
30,522,982
List with many dictionaries VS dictionary with few lists?
<p>I am doing some exercises with datasets like so:</p> <p><strong>List with many dictionaries</strong></p> <pre><code>users = [ {"id": 0, "name": "Ashley"}, {"id": 1, "name": "Ben"}, {"id": 2, "name": "Conrad"}, {"id": 3, "name": "Doug"}, {"id": 4, "name": "Evin"}, {"id": 5, "name": "Florian"...
<p>This relates to <a href="https://en.wikipedia.org/wiki/Column-oriented_DBMS">column oriented databases</a> versus row oriented. Your first example is a row oriented data structure, and the second is column oriented. In the particular case of Python, the first could be made notably more efficient using <a href="https...
python|pandas|dataset
29
370,394
30,292,966
count cumulative number of rows since a condition is et in a Pandas DataFrame
<p>I have a pandas DF that has two columns, Day, and Data, reading from a csv file. </p> <p><img src="https://i.stack.imgur.com/WtzTu.png" alt="enter image description here"></p> <p>After reading, I add 3 columns "Days with condition 0", 1, and 2. For example, for the columns 'Days with condition 2' I do this:</p> ...
<p>Starting with your two original columns</p> <pre><code> Day Data 0 1 1 1 2 0 2 3 0 3 4 0 4 5 0 5 6 0 6 7 1 7 8 0 8 9 2 9 10 0 10 11 0 11 12 1 12 13 0 13 14 0 14 15 0 15 16 1 16 17 0 17 18 ...
python|pandas
2
370,395
30,642,356
how to drop dataframe in pandas?
<p>Tips are there for dropping column and rows depending on some condition. But I want to drop the whole dataframe created in pandas. like in R : rm(dataframe) or in SQL: drop table </p> <p>This will help to release the ram utilization.</p>
<p>Generally creating a new object and binding it to a variable will allow the deletion of any object the variable previously referred to. <code>del</code>, mentioned in @EdChum's comment, removes both the variable and any object it referred to.</p> <p>This is an over-simplification, but it will serve.</p>
python|pandas|dataframe
5
370,396
30,418,072
How to initialize 2D numpy array
<p><strong>Note:</strong> I found the answer and answered my own question, but I have to wait 2 days to accept my answer.</p> <hr> <p>How do I initialize a numpy array of size 800 by 800 with other values besides zero? :</p> <pre><code>array = numpy.zeros((800, 800)) </code></pre> <p>I am looking for a solution lik...
<p>You can use fill method to init the array.</p> <pre><code>x = np.empty(shape=(800,800)) x.fill(1) </code></pre>
python|numpy
7
370,397
30,386,328
Efficiently select random non-zero column from each row of sparse matrix in scipy
<p>I'm trying to efficiently select a random non-zero column index for each row of a large sparse SciPy matrix. I can't seem to figure out a vectorized way of doing it, so I'm resorting to a very slow Python loop:</p> <pre><code>random_columns = np.zeros((sparse_matrix.shape[0])) for i,row in enumerate(sparse_matrix):...
<p>Have you looked at the underlying data representation for this, and other sparse formats? </p> <p>For example, for small matrix</p> <pre><code>In [257]: M = sparse.rand(10,10,.1,format='csr') In [258]: M Out[258]: &lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 10 stored elements in Com...
python|numpy|scipy
2
370,398
26,901,111
Extracting hours from a csv with pandas
<p>I have a csv that looks like this</p> <pre><code>time,result 1308959819,1 1379259923,2 1318632821,3 1375216682,2 1335930758,4 </code></pre> <p>times are in unix format. I want to extract the hours from such times and groupby the file with respect to such values.</p> <p>I tried</p> <pre><code>times = pd.to_dateti...
<p>You're getting that error because Series and DataFrames don't have <code>hour</code> attributes. You can access the information you want using the <code>.dt</code> convenience accessor (docs <a href="http://pandas.pydata.org/pandas-docs/version/0.15.0/api.html#datetimelike-properties" rel="nofollow">here</a>):</p> ...
python|time|pandas
1
370,399
26,571,373
Subdividing NumPy array into Regular Grid
<p>import numpy as np</p> <p>I have a rectangle with the following coordinates:</p> <pre><code>ulx,uly = (110, 60) ##uppper left lon, upper left lat urx,ury = (120, 60) ##uppper right lon, upper right lat lrx, lry = (120, 50) ##lower right lon, lower right lat llx, lly = (110, 50) ##lower left lon, lower left lat </c...
<p>For this you can use <code>np.meshgrid</code>:</p> <pre><code>import numpy as np lats = np.linspace(50, 60, 11) lons = np.linspace(110, 120, 11) xx, yy = np.meshgrid(lats, lons) </code></pre> <p>At this point <code>xx</code> and <code>yy</code> are 2x2 matrices with the corner coordinates of the grid tiles. If y...
python|numpy
2