Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
13,900
37,106,640
Python. BigData. Need to extract Web-Browser and OS users' preferences from cells. Best-performance method?
<p>So. We have a clean dataframe that was made of messy <a href="https://drive.google.com/open?id=0BxWmwAIo1D_nUUpqTU5TdDlaUHc" rel="nofollow noreferrer">TSV file</a> like that (special thanks to @unutbu): <a href="https://i.stack.imgur.com/gkKlz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gkKlz....
<p>this works, but it's pretty slow:</p> <pre><code>df = pd.DataFrame({'user_agent':['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36']}) # create 10.000 rows DF: df = pd.concat([df] * 10**4) def parse_ua_series(ua): p = user_agents.parse(ua) retu...
python|pandas|data-analysis|bigdata
1
13,901
36,836,521
In pandas dataframe handling object data type
<p>I'm tearing my hair out a bit with this one. I've imported two csv's into pandas dataframes both have a column called SiteReference i want to use pd.merge to join dataframes using SiteReference as a key.</p> <p>Initial merged failed as pd.read took different interpretations of the SiteReference values, in one insta...
<p>Following the discussion in the comments, if you want to format floats as integer strings, you can use this:</p> <pre><code>df['SiteReference'] = df['SiteReference'].map('{:,.0f}'.format) </code></pre> <p>This should handle null values gracefully.</p>
python|csv|pandas
0
13,902
73,332,482
Is there a pandas function to add in value of a column based on the other dataframe?
<p>I would like to add a column to a pandas dataframe based on the value from another dataframe. Here is table 1 and table 2. I would like to update the duration for table 1 based on the value from table 2. Eg, row 1 in Table 1 is Potato, so the duration should be updated to 30 based on value from table 2.</p> <p>Table...
<p>Just use merge method:</p> <pre><code>df = df1.merge(df2, on='Crops', how='left') </code></pre> <p>Before doing that I suggest to drop the duration column in the first dataframe (df1).</p> <p>The parameter 'on' defines on which column you want to merge (also called 'key') and how='left' it returns a dataframe with t...
python|pandas
2
13,903
73,364,934
pandas function to check if there exist non-NA values for the same ids?
<p>Assume I have a dataset that contains around 100 000 rows and 50 columns. I have information about the sellers and their products. The part of the dataset will look somehow like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">seller_id</th> <th style="text...
<p>You can do this using pandas for example:</p> <pre><code>import pandas as pd # Read the data into DataFrame which is basically a two dimensional array df = pd.read_csv(&quot;you_csv_file.csv&quot;) # Print if there are null values print(df.isna().sum()) </code></pre>
python|pandas|missing-data|data-preprocessing
0
13,904
73,489,827
How to fill the nan's at the end of every column with 0's in pandas python?
<p>I want to forward fill my dataframe with a custom value - like 0. But pandas dosent allow to ffill with custom value. It only takes the last available value in every column and fills the nan values at the end with it. So was wondering if there was a better way to do this in python.</p> <pre><code>df = nan 1 2 n...
<p>You can use boolean indexing:</p> <pre><code>m1 = df.notna() m2 = m1.cummax() out = df.mask(m2&amp;~m1, 0) </code></pre> <p>output:</p> <pre><code> 0 1 2 3 0 NaN 1.0 2 NaN 1 1.0 4.0 5 2.0 2 0.0 6.0 7 0.0 3 0.0 0.0 8 0.0 4 0.0 0.0 8 0.0 </code></pre> <p>If you have intermediate NaN and...
python|pandas|dataframe
1
13,905
73,211,461
I have str which includes a date that I'm trying to extract
<p>I have a string which is similar to this</p> <blockquote> <p>02032021..........SW01SW05..........</p> </blockquote> <p>I have already extracted everything I need from it except for the date which is the first block of digits. the dates are between Jan 21 and YTD.</p> <p>I used this code to get only the digits <code>...
<p>Here's an example of how you can handle those digits, with a mock &quot;date&quot; string. You'll have to separate the date from the string you provided to make this work, probably with slicing as you have already done.</p> <p>Code:</p> <pre><code>from datetime import datetime example_date = &quot;02032021&quot; pr...
python|pandas|dataframe
0
13,906
35,134,507
Python pandas: How to group by and count unique values based on multiple columns?
<p>I have datafarme df:</p> <pre><code>id name number 1 sam 76 2 sam 8 2 peter 8 4 jack 2 </code></pre> <p>I would like to group by on 'id' column and count the number of unique values based on the pair of (name,number)?</p> <pre><code>id count(name-number) 1 1 2 2 4 1 </code></pre> <p>I have...
<p>You can just combine two <code>groupby</code>s to get the desired result. </p> <pre><code>import pandas df = pandas.DataFrame({"id": [1, 2, 2, 4], "name": ["sam", "sam", "peter", "jack"], "number": [8, 8, 8, 2]}) group = df.groupby(['id','name','number']).size().groupby(level=0).size() </code></pre> <p>The first <...
python|pandas|group-by|unique
8
13,907
34,994,832
Expected and predicted arrays ending up to be the same in scikit learn random forest model
<pre><code>data = df_train.as_matrix(columns=train_vars) # All columns aside from 'output' target = df_train.as_matrix(columns=['output']).ravel() # Get training and testing splits splits = cross_validation.train_test_split(data, target, test_size=0.2) data_train, data_test, target_train, target_test = splits # Fit ...
<p>Kudos for questioning too good results! </p> <p>Each feature (column) in the data contains only a small amount of distinct values. If I counted correctly, there are <strong>only 14 uniquely different rows</strong>.</p> <p>This has two implications:</p> <ol> <li><p>You are very likely to be overfitting because you...
python|numpy|pandas|scikit-learn|random-forest
1
13,908
35,310,652
shortcut for filling missing dates
<p>I have the following example:</p> <pre><code>import numpy as np import pandas as pd idx1 = pd.period_range('2015-01-01', freq='10T', periods=1000) idx2 = pd.period_range('2016-01-01', freq='10T', periods=1000) df1 = pd.DataFrame(np.random.randn(1000), index=idx1, columns=['A']) df2 = pd.DataF...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a>:</p> <pre><code>df_total = df_concat.resample('10T') print df_total[df_total.isnull()] A 2015-01-01 00:00:00 NaN 2015-01-01 00:10:00 NaN ...
python|pandas|time-series|missing-data
1
13,909
67,304,148
What is the most efficient/fastest way to add new rows of data to a DataFrame in Python
<p>The program creates some random products and then creates orders by randomly choosing a product. Right now every order only has one item; a future version will randomize the number of line items per order.</p> <p>I've never used Python or Pandas before and I wanted to make sure that my approach is the most efficient...
<p>For an <em>efficient</em> answer:</p> <p>My suggestion dives a bit into <a href="https://en.wikipedia.org/wiki/Database_normalization" rel="nofollow noreferrer">rules for normalization for databases</a>. The general idea of these rules is to reduce data redundancy (Why enter the same data more than once?). That said...
python|pandas
0
13,910
67,283,018
Saving/Storing pymatgen Structures
<p>I'm currently dealing with a material science dataset having various information.</p> <p>In particular, I have a column 'Structure' with several <code>pymatgen.core.Structure</code> objects.</p> <p>I would like to save/store this dataset as <code>.csv</code> file or something similar but the problem is that after ha...
<p>pymatgen.core.structure object can be stored with only some sort of fixed format, for example, cif, vasp, xyz... so maybe you, first, need to store your structure information to cif or vasp. and open it and preprocess to make it &quot;csv&quot; form with python command.(hint : using python string-related command).</...
python|pandas|dataframe|encoding|pymatgen
2
13,911
67,269,103
NumPy: how to calculate variance along each row of a 2D array using np.var and by hand (i.e., not using np.var; calculating each term explicitly)?
<p>I am using Python to import data from large files. There are three columns corresponding to x, y, z data. Each row represents a time at which the data were collected. For example:</p> <pre><code>importedData = [[1, 2, 3], &lt;--This row: x, y, and z data at time 0. [4, 5, 6], [7, ...
<p>Well you could do something like this to make things more explicit:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np importedData = np.arange(1,10).reshape(3,3) # Get means for each row means = [row.mean() for row in importedData] # Calculate squared errors squared_errors = [(row-mean)**2 f...
python-3.x|numpy|loops|statistics|variance
2
13,912
34,836,341
matplotlib adjusting colorbar
<p>I have a 2D data set with values between 0.5 and 2. I want to show it with <code>imshow</code> and <code>seismic</code> color map but I need the value 1 to match the white color. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = np.random.random((100,100))*2 data[data&lt;0.5]=0.5 plt.imshow(...
<p>use <code>ColorBar.set_clim()</code>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = np.random.random((100,100))*2 data[data&lt;0.5]=0.5 plt.imshow(data,cmap='seismic', vmin=0.5, vmax=2) c = plt.colorbar() c.set_clim(0, 2) </code></pre> <p>the output:</p> <p><a href="https://i.stack.imgu...
python|numpy|matplotlib
2
13,913
34,537,068
Python/numpy: Most efficient way to sum n elements of an array, so that each output element is the sum of the previous n input elements?
<p>I want to write a function that takes a flattened array as input and returns an array of equal length containing the sums of the previous n elements from the input array, with the initial <code>n - 1</code> elements of the output array set to <code>NaN</code>.</p> <p>For example if the array has ten <code>elements ...
<p>You can make use of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html" rel="nofollow"><code>np.cumsum</code></a>, and take the difference of the <code>cumsum</code>ed array and a shifted version of it:</p> <pre><code>n = 3 arr = np.array([2, 4, 3, 7, 6, 1, 9, 4, 6, 5]) sum_arr = arr.cu...
python|arrays|algorithm|performance|numpy
9
13,914
34,666,751
Numpy Array with different types of features for sci-kitLearn dataset API in Python
<p>I am trying to perform machine learning using sci-kitLearn on a dataset parsed from a json file. To use the dataset API in sci-kitLearn I need a Numpy array of shape (n_samples * n_features).</p> <p>I have this data encoded as a nested Python list where the list is size 'X' (some large amount of samples) and each e...
<p>If you have a list of lists you can convert this to a <code>numpy</code> array with <code>np.array(combined_list)</code>. This will be in the shape where the length of the outer list is in the first dimension (down), e.g. </p> <pre><code>&gt;&gt;&gt; a = np.array([[1,2,3],[1,2,3]]) &gt;&gt;&gt; a.shape (2, 3) </co...
python|arrays|numpy|dataset|scikit-learn
0
13,915
60,332,221
ModuleNotFoundError: No module named 'validate_email'
<p>I am trying to execute the following code in <code>python pandas</code>. </p> <pre><code>from email_validator import validate_email from pandas import DataFrame, read_csv import pandas as pd file =r'sampe.csv' df=pd.read_csv(file,usecols =['name','email','phone']) print(df) </code></pre> <p>But it gives <code>Modu...
<p>try installing email validator using this:</p> <pre><code>conda install -c conda-forge email_validator </code></pre> <p>make sure you are using correct <code>conda</code> environment</p>
python|pandas
3
13,916
59,988,979
Pivot pandas dataframe from from wide to long
<p>I'm not sure if this data is properly in a wide format, but what I want to do is the following: </p> <p>Convert from the shape of <code>d1</code> to the shape <code>d2</code></p> <pre class="lang-py prettyprint-override"><code>In [26]: d1 = pd.DataFrame({'where':['x','y'], ...: 'p1':[3,7], ...: 'p2':[11,12...
<p>No, it can't be done with a pivot table. You are not pivoting values within the dataframe.</p> <p>You would use pivot to return d2 to d1. For example below shows d1 becoming d2 (as initially requested) and then we can use pivot_table to then return d2 back to d1.</p> <pre><code>d1.melt(id_vars='where') where va...
python|pandas|dataframe
2
13,917
60,206,786
1D Convolutional Neural Network
<p>I need to test CNN on EEG data, and I have heard that 1D-CNN is useful for real-time application. I have 5 test subjects with data from 3 sessions each. Each file contain signal from 56 electrodes/channels (56, 260).</p> <p>I am struggling to find how to set up the CNN and how to input data should be transformed. ...
<p>So, for a Keras convolution, you should keep it this way: <code>(examples, time_steps, features)</code>.</p> <p>Where:</p> <ul> <li>examples (usually called samples, but not to be confused with your sensor samples) - they are the number of examples you have for your model: 15 </li> <li>time_steps: the continuo...
tensorflow|machine-learning|keras|neural-network|conv-neural-network
0
13,918
65,181,543
Problems with .to_timedelta
<p>I am attempting to following the steps in <a href="https://stackoverflow.com/questions/38355816/pandas-add-timedelta-column-to-datetime-column-vectorized">Pandas: add timedelta column to datetime column (vectorized)</a> to add a time delta column to my dataframe by converting a'pandas._libs.tslibs.timestamps.Timesta...
<p>If need times from datetimes convert to timedeltas convert datetimes to format <code>HH:MM:SS</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a>:</p> <pre><code>df['td'] = pd.to_timedelta(pd.to_dat...
python|pandas|timestamp|timedelta
1
13,919
64,030,892
Why isn't my db table showing up on Apache Superset?
<p>I'm trying to mess around with this csv I have on Apache Superset. I created an sqlite database and tried to upload the csv via superset and was getting no return in the table section. So instead, I created the table through python, reloaded and still see no tables in superset in my nav database.</p> <p>here's my co...
<p>Modify the superset configuration file(config.py) to enable SQLite by setting.</p> <pre><code>PREVENT_UNSAFE_DB_CONNECTIONS = False </code></pre>
python|pandas|sqlite|apache-superset
1
13,920
64,149,100
Two list compare in Pandas
<p>I have two list, first one with names only and second one with names and values corresponding to names. What I am trying to achieve is to find in second list all names that presented in first list with its values in second one. I tried this way, but missing the corresponding numbers</p> <pre><code>matches = [] for i...
<p>if it has names and values corresponding to names - it is not a list, but dict or pd.DataFrame</p> <p>for pd.DataFrame:</p> <pre><code>matches = list2[list2.name.isin (list1)] </code></pre> <p>for dict:</p> <pre><code>matches = {} for i, v in dict2.items(): if i in list1: matches[i] = v </code></pre> <p>o...
python|pandas
0
13,921
63,931,488
Pandas Dataframe groupby aggregate functions and difference between max and min of a column on the fly
<pre><code>import pandas as pd df = {'a': ['xxx', 'xxx','xxx','yyy','yyy','yyy'], 'start': [10000, 10500, 11000, 12000, 13000, 14000] } df = pd.DataFrame(data=df) df_new = df.groupby(&quot;a&quot;,as_index=True).agg( ProcessiveGroupLength=pd.NamedAgg(column='start', aggfunc=&quot;count&quot;), ...
<p>Your solution should be changed by lambda function, but I think if many groups or/and large DataFrame this should be slowier like first solution.</p> <p>Reason is optimalized functions <code>max</code> and <code>min</code> and also vectorized subtraction of <code>Series</code>. In another words if not used lambda fu...
pandas|dataframe|pandas-groupby|aggregate-functions
7
13,922
63,809,778
How to align 3 dataframes with some threshold in python?
<p>I have some x &amp; y columns in a dataframe such as below:</p> <pre><code> X-1 X-1_y X-2 X-2_y X-3 X-3_y 0 411.726266 1387.29 437.404307 3755.08 437.273585 3360.85 1 437.692665 677.39 448.557534 1460.70 448.760155 981.45 2 448.596937 2276.35 481.550490 0.00 ...
<p>You can do the following:</p> <p>First we want to make a flat list of all the values:</p> <pre><code>x=list(df[&quot;X-1&quot;])+list(df[&quot;X-2&quot;])+list(df[&quot;X-3&quot;]) items=[[row[&quot;X-1&quot;]]+[row[&quot;X-2&quot;]]+[row[&quot;X-3&quot;]] for index,row in df.iterrows()] flat_list = [item for sub...
python|pandas|dataframe|data-science
1
13,923
46,939,140
Different ways to install numpy, scipy, and matplotlib on macOS via homebrew
<p>Today I decided to install python and the scipy stack manually, instead of using Anaconda (or Canopy) as I had previously done. I use homebrew on my mac and have python2 and python3 (2.7 and 3.6) installed via homebrew. But reading through the documentation, there are multiple ways to install the scipy stack and I w...
<p>Your analysis seems correct: variants 1 and 3 will install numpy/scipy from the python package index (PyPI) and will use pre-built wheels (if available for your platform, which they most likely are). Variant 2 installs the brew formula.</p> <p>As mentioned by @Evhz, the conda packages for numpy and scipy use the In...
python|numpy|matplotlib|scipy|homebrew
0
13,924
46,944,747
how to select nth element of array in a tuple?
<p>I have a tuple like this:</p> <blockquote> <p>(array([0, 0, 0]), array([0, 1, 2]))</p> </blockquote> <p>I would like to select the first element of each array in this tuple and want to achieve this result: [0,0] or [0,1] or [0,2]</p> <p>How can I do this?</p> <p>Actually, this tuple is obtained from a function in nu...
<p>Is this what you want ? </p> <pre><code>list(zip(tp[0],tp[1])) Out[689]: [(0, 0), (0, 1), (0, 2)] </code></pre> <p>Data input </p> <pre><code>tp=(np.array([0, 0, 0]), np.array([0, 1, 2])) </code></pre> <p>If you want to list of list </p> <pre><code>l=list(zip(tp[0],tp[1])) list(map(list, l)) Out[691]: [[0, 0], ...
python|numpy
0
13,925
38,755,143
How to add a number to an index range of a pandas array
<p>In pandas, how can I operate on a subset of rows in a column, selected by index?</p> <p>In particular, how can I add 1.0 to column y here, only where the date is greater than 2016-08-04?</p> <pre><code>&gt;&gt;&gt; pandas.DataFrame( ... index=[datetime.date.today(), datetime.date.today() + datetime.timedelta(1)], ...
<p>If you convert the index to a DateTimeIndex it becomes easier:</p> <pre><code>df.index = pd.to_datetime(df.index) df.loc[df.index &gt; '2016-08-04', 'y'] += 1 df Out: x y 2016-08-04 1.2 234 2016-08-05 3.3 433 </code></pre>
python|pandas
3
13,926
38,618,141
advanced aggregation pandas python
<p>If I have a simple table, such as:</p> <pre><code>index location col1 col2 col3 col4 1 a TRUE yes 1 4 2 a FALSE null 2 6 3 b TRUE null 6 3 4 b TRUE no 3 4 5 b F...
<p>Use <code>groupby</code> and <code>agg</code></p> <pre><code>funcs = dict( col1=dict(Trump=lambda x: x.any()), col3='sum', col4=dict(Avg='mean') ) df.groupby('location').agg(funcs) </code></pre> <p><a href="https://i.stack.imgur.com/BEA5T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur....
python|pandas|dataframe|group-by|pandas-groupby
6
13,927
38,724,286
Captcha recognizing with convnet, how to define loss function
<p>I have small research project where I try to decode some captcha images. I use convnet implemented in Tensorflow 0.9, based on MNIST example (<a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/convolutional_network.py" rel="nofollow noreferrer">https://github.com/ayme...
<p>The real problem was that my network get stuck, the network output was constant for any input.</p> <p>When I have changed loss function to <code>loss = tf.nn.sigmoid_cross_entropy_with_logits(pred,y)</code> and normalize input, then the net start to learn the patterns. </p> <p>Standarization (substract mean and d...
python|neural-network|tensorflow|captcha|conv-neural-network
1
13,928
62,898,716
Parsing JSON into pandas dataframe in Python 3
<p>I've been some trouble getting JSON code into a pandas dataframe in python. This is what my JSON code looks like:</p> <pre><code> { &quot;results&quot;: [ { &quot;events&quot;: [ { &quot;id&quot;: 132, &quot;name&quot;: &quot;rob&quot...
<p>You can try to use the <a href="https://docs.python.org/3/library/json.html" rel="nofollow noreferrer">json</a> module from the standard library to parse the json data, then <a href="https://stackoverflow.com/questions/20638006/convert-list-of-dictionaries-to-a-pandas-dataframe">converting the list of dicts to a Dat...
python|json|pandas|dataframe
1
13,929
62,980,450
What is the best way to replace the format of data in a large dataset?
<p>I am just starting out with data science, so apologies if this is a bone question with a simple answer, but I have been scanning google for hours and have tried multiple solutions to no avail.</p> <p>Basically, my dataset has automatically adjusted some values such as 3-5 to 03-May. I am not able to simply change th...
<p><code>df[['tumor-size', 'inv-nodes']] = df[['tumor-size', 'inv-nodes']].astype(str)</code></p> <p>That line of code saved the day.</p>
python|pandas|replace|data-science|data-cleaning
0
13,930
63,083,439
PyTorch Average Accuracy after each epoch
<p>I am trying to calculate the accuracy of the model after the end of each epoch. After each epoch I would like to calculate the accuracy over the previous epoch. The model only seems to print the same value as the mean test error.</p> <pre class="lang-py prettyprint-override"><code>model.eval() for images, paths in ...
<p><strong>IF</strong> your model is a classifier, calculating accuracy follows:</p> <pre><code>acc = (pred.max(dim=1) == target).float().mean() </code></pre> <p>Where:</p> <pre><code>pred.shape = (batch_size, n_classes) target.shape = (batch_size) </code></pre> <p>A similar question was asked recently: <a href="https...
python|python-3.x|deep-learning|pytorch
0
13,931
67,778,168
Pandas Python (CSV) - Accessing data from tables and using that data -
<p>I have three csv files - Supply, Demand and Hotelling.</p> <p>I want to go to supply table, sum values in a given column where team_belong = &quot;someteamname&quot;, and then write this summed up value into Hotelling file against the same team.</p> <p>I am completely new to python. I want to be able to go into supp...
<pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv(&quot;supplytable.csv&quot;) df[df[team_column]==team_name][column_name].sum() </code></pre> <p>I suggest you to go through some online course on tutorial on pandas because this is the basics of pandas.</p>
python|pandas|dataframe|csv
0
13,932
67,877,688
Why flatten() is not working in co-lab whereas it worked in kaggle-notebook posted by other user?
<p>I am working on a project for pneumonia detection. I have looked over kaggle for notebooks on the same. there was a user who stacked two pretrained model densenet169 and mobilenet. I copies whole kaggle notebook from the user where he didn't get any error, but when I ran it in google colab I get this error in this p...
<p>You have mixed up your imports a bit.</p> <p>Here is a fixed version of your code</p> <pre><code>from tensorflow.keras.layers import concatenate from tensorflow.keras.layers import Input, GlobalAveragePooling2D, Flatten, BatchNormalization, Dense, Dropout from tensorflow.keras.applications import MobileNetV2, DenseN...
tensorflow|machine-learning|keras|google-colaboratory|tensor
0
13,933
67,979,281
Python date.today() not working with pandas pdr.get_data_yahoo)
<p>I am trying to use Yahoo's pandas stock reader library. I currently have the following code:</p> <pre><code>today=str(date.today()) print(today) print(type(today)) start_date= '2020-01-01' end_date = '2021-06-14' stockData = pdr.get_data_yahoo(stock,start=start_date,end=today) </code></pre> <p>I get '2021-14-06' an...
<p>UPDATE: it's because the stock market is closed on weekends so there was no data for those dates :(</p>
python-3.x|pandas|datetime|yahoo-finance|pandas-datareader
0
13,934
67,813,794
How to work with a Dataframe with a column/series of dtype object and having different +z values
<p>Hi I have a dataframe with one of its column called 'Formatted Date' having objects like <code>2006-04-01 00:00:00.000 +0200</code>. I am trying to convert it to datetime and and I used</p> <pre><code>format='%Y-%m-%d %H:%M:%S.%f %z' </code></pre> <p>It does not work since the +z value is not the same for all. How...
<p>Parse to datetime with keyword <code>utc=True</code>. If you don't know the origin time zone of the data, I'd suggest to continue working with UTC here. However if you know the time zone, you can <code>tz_convert</code> to it, e.g.</p> <pre><code>import pandas as pd df = pd.DataFrame({'Formatted Date': [&quot;2006-...
python|pandas|datetime|datetime-format
0
13,935
67,728,275
How to obtain link inside of a DIV nested in a TD with BeautifulSoup
<p><em><strong>Problem:</strong></em> &quot;Easy&quot; way (<code>pd.read_html()</code>) of obtaining table information with Pandas isn't working for my use case.</p> <p>It's only pulling what I believe is the label text, and it's got this newb confuzzled. What I need is at least the link <em>(to pdf)</em> text.</p> <p...
<p>Ok, with the help and guidance of QHarr in the <a href="https://stackoverflow.com/questions/67728275/how-to-obtain-link-inside-of-a-div-nested-in-a-td-with-beautifulsoup#comment119946917_67728275">comments</a> of the original question, I was able to come up with a solution. As with anything coding related, I am sure...
python|pandas|web-scraping|beautifulsoup
1
13,936
41,412,335
tf.nn.softmax_cross_entropy_with_logits() error: logits and labels must be same size
<p>I am new to TensorFlow and am trying to write an algorithm to classify images in the CIFAR-10 dataset. I am getting this error:</p> <pre><code>InvalidArgumentError (see above for traceback): logits and labels must be same size: logits_size=[10000,10] labels_size=[1,10000] [[Node: SoftmaxCrossEntropyWithLogits ...
<p>The <a href="https://www.tensorflow.org/api_docs/python/nn/classification#softmax_cross_entropy_with_logits" rel="nofollow noreferrer"><code>tf.nn.softmax_cross_entropy_with_logits(logits, labels)</code></a> op expects its <code>logits</code> and <code>labels</code> arguments to be tensors with the same shape. Furth...
python|tensorflow
2
13,937
41,507,187
Write pandas DataFrame to HDF in memory buffer
<p>I want to get a dataframe as hdf in memory. The code below results in "AttributeError: '_io.BytesIO' object has no attribute 'put'". I am using python 3.5 and pandas 0.17</p> <pre><code>import pandas as pd import numpy as np import io df = pd.DataFrame(np.arange(8).reshape(-1, 2), columns=['a', 'b']) buf = io.By...
<p>Your first argument to df.to_hdf() has to be a "path (string) or HDFStore object" not an io stream. Documentation: <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.to_hdf.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.D...
python|pandas|hdf
2
13,938
61,603,407
Reshaping data with dates as column values
<p>I am trying to reshape data using pandas and have been having a hard time getting it into the right format. Roughly, the data look like this*:</p> <pre><code>df = pd.DataFrame({'PRODUCT':['1','2'], 'DESIGN_START':[pd.Timestamp('2020-01-05'),pd.Timestamp('2020-01-17')], 'DESIGN_COMPLETE':[pd.Time...
<p>MELT IT!!!</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'PRODUCT':['1','2'], 'DESIGN_START':[pd.Timestamp('2020-01-05'),pd.Timestamp('2020-01-17')], 'DESIGN_COMPLETE':[pd.Timestamp('2020-01-22'),pd.Timestamp('2020-03-04')], 'PRODUCTION_START':[pd.Timestamp('2020-02-07')...
python|pandas|pivot|reshape|group-summaries
2
13,939
61,351,283
Multiple columns to single column pandas
<p>convert header to one column and multiple columns to another column in Pandas DF:</p> <p>DF:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns =["2000","2001","2002" ]) df.index = pd.Index(["A","B","C"],name = "random") df </code></pre> <p>OP:</p> <pre><code> 2000 2001 2002...
<pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns =["2000","2001","2002" ]) df.index = pd.Index(["A","B","C"],name = "random") df=pd.melt(df, value_vars=["2000","2001","2002" ]) print(df) # output variable value 0 2000 5 1 2000 1 2 ...
python|pandas|numpy
1
13,940
68,844,166
Formating phone number in Pandas
<p>Im working on a Database that contains phone numbers, trying to add another column which says which country each number is from. I've tried many diffrent versions, and this is the current one. I keep getting this error :</p> <pre><code>Traceback (most recent call last): File &quot;***PycharmProjects/DataTools/data...
<p>I just created a dummy data and works just fine until your for loop.</p> <p>I suggest simply create a new column</p> <pre><code>df['new_phone'] = df[['phonenumber', 'country']].agg('+'.join, axis=1) </code></pre>
python|pandas|phone-number
0
13,941
68,696,183
Pandas: Iterate through columns index/labels and group the ones that starts with the same strings
<p>I want to group the column index/labels that starts with the same str, but I'cant use str.startswith() because it would be a very long list if I'd have to write every single prefix and than group.</p> <p>So I want to iterate through every column's prefix (in format Q[0-9]) and group all similar ones together.</p> <p...
<ol> <li>To select the columns that start with regex pattern <code>Q[0-9]</code>, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>df.filter()</code></a> with <code>regex=</code> parameter, as follows:</li> </ol> <pre><code>df2...
python|pandas|dataframe|group-by|multiple-columns
1
13,942
68,468,523
Concatenate multiple pieces of an image to a single image using python
<p>I have 15 images (from 1 to 15). I would like to stitch these images together so that it forms one single image. What I tried so far?</p> <pre><code>import numpy as np import PIL from PIL import Image import os filenames = [os.path.abspath(os.path.join(directory, p)) for p in os.listdir(directory) if p.endswith(('jp...
<p>I tried the same approach as Dr. Prof. Patrick and made more universal function. Number of images can be less than rows * cols in this version.</p> <pre><code>#!/usr/bin/env python3 import numpy as np from imageio import imread, imwrite from pathlib import Path import math def tile_images(images, cols=None, bg_val=...
python|image|numpy|python-imaging-library|image-stitching
1
13,943
68,766,629
Retrieving latest DEX Trades of a specified token address on BSCScan
<p>I'm trying to get the list of DEX Trades from BSCScan. I don't think they have an API endpoint for this, so I tried using webscraping using selenium to retrieve the information.</p> <pre><code>import pandas as pd from selenium import webdriver from selenium.webdriver.common.keys import Keys import time PATH = 'C:/U...
<p>There are total of 6 columns, you can use Selenium to scrape the data.</p> <p>See below, sample code and then we can use pandas to write into <code>.csv</code> file:</p> <pre><code>PATH = 'C:/Users/XX/Downloads/chromedriver_win32/chromedriver.exe' driver = webdriver.Chrome(PATH) driver.maximize_window() driver.impl...
python|pandas|selenium|cryptocurrency|bscscan
0
13,944
36,379,796
Extract values array using indices
<p>I need to extract certain values from a multidimensional array that are not subsequent.</p> <pre><code>import numpy as np A = np.array([[[ 0., 4., 0. ], [ 0.19230769, 4.03846154, 0. ], [-0.4, 4.8, 0. ], [ 2., ...
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">"advanced indexing"</a>:</p> <pre><code>In [99]: A[[0,1,2], [2,1,1], :] Out[99]: array([[-0.4 , 4.8 , 0. ], [ 2.11538462, 4.42307692, 0. ], [ 3.1730769...
python|arrays|numpy|indices
2
13,945
36,673,447
python pandas conditional sum on dataframe which is grouped on multiple columns
<p>To illustrate my problem I have an example dataframe</p> <pre><code>df = pd.DataFrame({'key1': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1], 'key2': ['a', 'b', 'b', 'c', 'a', 'a', 'a', 'b', 'b', 'c'], 'key3': [10, 5, 15, 10, 5, 10, 20, 10, 20, 5], 'zdata': [2, 4, 2,...
<p>I think better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.mean.html" rel="nofollow"><code>mean</code></a> as <code>agg</cod...
python|pandas|dataframe
3
13,946
36,242,735
Combination of values in pandas data frame
<p>This is my pandas dataframe:</p> <pre><code> Item Support_Count 0 BREAD 4 1 MILK 4 2 DIAPER 4 3 BEER 3 </code></pre> <p>How will i generate all possible unique combinations of 2 and 3 set of items from the 1st column 'Item'. </...
<p>You can use the <code>itertools</code> library:</p> <pre><code>import itertools list(itertools.combinations(df['Item'], 2)) [('BREAD', 'MILK'), ('BREAD', 'DIAPER'), ('BREAD', 'BEER'), ('MILK', 'DIAPER'), ('MILK', 'BEER'), ('DIAPER', 'BEER')] list(itertools.combinations(df['Item'], 3)) [('BREAD', 'MILK', 'DI...
python|python-3.x|pandas|dataframe
20
13,947
53,262,097
Creating plot from CSV with matplotlib fails
<p>I'm trying to plot from csv using pandas but the image that I get it is blank any help.</p> <pre><code>def graph(request): fig = matplotlib.figure.Figure() ax = fig.add_subplot(111) data_df = pd.read_csv(r"C:\Users\csvdata.csv") data_df = pd.DataFrame(data_df) data_df.plot(ax=ax) canvas = F...
<p>Of course we cannot know the content of the csv file and hence cannot know if it's read in correctly. But suppose it is, the problem would be that you are using pyplot to save a figure which has not been registered with pyplot. </p> <p>You can either use pyplot as</p> <pre><code>fig = plt.figure() ax = fig.add_sub...
python|pandas|matplotlib
1
13,948
53,092,924
Python Groupby with Boolean Mask
<p>I have a pandas dataframe with the following general format:</p> <pre><code>id,atr1,atr2,orig_date,fix_date 1,bolt,l,2000-01-01,nan 1,screw,l,2000-01-01,nan 1,stem,l,2000-01-01,nan 2,stem,l,2000-01-01,nan 2,screw,l,2000-01-01,nan 2,stem,l,2001-01-01,2001-01-01 3,bolt,r,2000-01-01,nan 3,stem,r,2000-01-01,nan 3,bolt,...
<p>I think this should work:</p> <pre><code>df['failed_part_ind'] = df.apply(lambda row: 1 if ((row['id'] == row['id']) &amp; (row['atr1'] == row['atr1']) &amp; (row['atr2'] == row['atr2']) &amp; ...
python|pandas|pandas-groupby
1
13,949
65,620,186
ExponentialDecay learning rate schedule with 'staircase=True' changes the training behavior even before it should become effective
<p>When adding an <a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/schedules/ExponentialDecay" rel="nofollow noreferrer"><code>ExponentialDecay</code></a> learning rate schedule to my <a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam" rel="nofollow noreferrer"><code>Ada...
<p>When using <code>ExponentialDecay</code>, what you're basically doing is to make a decayed learning rate like:</p> <pre class="lang-py prettyprint-override"><code>def decayed_learning_rate(step): return initial_learning_rate * decay_rate ^ (step / decay_steps) </code></pre> <p>When you set <code>staircase=True</co...
python|tensorflow|machine-learning|keras
7
13,950
65,716,315
Create a new column based on two others and conditionals
<p>I have a two column data frame of the form:</p> <pre><code> Death HEALTH 0 other 0.0 1 other 1.0 2 vascular 0.0 3 other 0.0 4 other 0.0 5 vascular 0.0 6 NaN 0.0 7 NaN 0.0 8 NaN 0.0 9 vascular 1.0 </code></pre> <p>I would like to cr...
<p>You can create conditions for <code>No</code> and <code>Yes</code> and for all another values are created original value in <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a>:</p> <pre><code>m1 = df['Death'].eq('other') | (df['Death']....
python|arrays|pandas
0
13,951
65,761,375
Display another column where the conditions are determined in other columns
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>address</th> <th>latitude</th> <th>longitude</th> </tr> </thead> <tbody> <tr> <td>Tokyo</td> <td>124.4423</td> <td>95.223</td> </tr> <tr> <td>Budapest</td> <td>156.2442</td> <td>78.112</td> </tr> <tr> <td>Perth</td> <td>124.9234</td> <td>20.490</t...
<p>You can use Pandas filtering:</p> <pre><code>df[(df.latitude=='156.2442') &amp; (df.longitude == '78.112')]['address'] </code></pre>
python|pandas|dataframe
1
13,952
65,620,552
In GCP python cloud function, dataframe is putting ' ' in the end while reading csv file
<p><a href="https://i.stack.imgur.com/iorYM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iorYM.png" alt="Image is of csv file I'm using for testing" /></a>In GCP, my python cloud function is adding ' ' as last row while reading csv file in to JSON format through pandas data frame. ex:-</p> <pre><c...
<p>I was able to fix the issue by explicitly putting version pandas==1.1.3 in requirements.txt. Since my earlier requirements.txt didn't have any version mentioned, it was actually fetching the latest version of pandas which is 1.3.0 right now. This latest version is actually adding ' ' in the end of row while readin...
python|pandas|dataframe|google-cloud-platform|google-cloud-functions
0
13,953
65,487,863
Is there a way to read bulk `yaml` files into a pandas `dataframe` more efficiently(faster) in Python
<p>I would like to read several <code>yaml</code> files from a directory into pandas <code>dataframe</code> and concatenate them into one big DataFrame. The directory consists of <strong>7470</strong> files.</p> <pre><code>%%time import pandas as pd import glob path = r'../input/cricsheet-a-retrosheet-for-cricket/all'...
<p><a href="https://docs.dask.org/en/latest/" rel="nofollow noreferrer">Dask</a> is a great package if you want to avoid getting into the details of parallel computing. It's really designed for distributed computing on machines with many CPUs but I find the syntax is convenient even if you're just using it for multi-t...
python|pandas|dataframe|yaml|runtime
1
13,954
21,347,873
Pandas dataframe get next (trading) day in dataframe
<p>I have a date given that may or may not be a trading day, and I have a pandas dataframe indexed by trading days that has returns of each trading day.</p> <p>This is my date</p> <pre><code>dt_query = datetime.datetime(2006, 12, 31, 16) </code></pre> <p>And I want to do something like this (returns is a pandas data...
<p>This might not be the most the elegant solution but it works. </p> <p>Here's the idea: from any date dt_query, within a number of calender days (say 10), there must be trading days, and your next trading day is just the first among them. So you can find all days in returns within dt_query and dt_query + timedelta(d...
python|pandas|time-series
2
13,955
20,970,483
Convert numbers to strings when reading an excel spreadsheet into a pandas DataFrame
<p>I'm reading some excel spreadsheets (xlsx format) into pandas using <code>read_excel</code>, which generally works great. The problem I have is that when a column contains numbers, pandas converts these to float64 type, and I would like them to be treated as strings. After reading them in, I can convert the column t...
<p>I solve it with round, if you do round(number,5) in most case you will not lose data and you will get zero in the case of 8.027770e+14</p>
python|excel|pandas
0
13,956
63,368,345
How to speed up pandas saving data frame to csv?
<p>Is there any way to speed up the saving process. I have a data frame containing a mere 600,000 rows, and my program got stuck saving the file for ~8 hours before I just quit the program out of frustration. Pandas will successfully save a data frame of 50,000 rows in just 45 seconds, but for some reason this somewhat...
<p>You might also try the feather or parquet formats. Rationale: speed to save and reload files, and compression (for parquet).</p> <pre><code>df.to_feather('test.feather') df.to_parquet('test.hd5') </code></pre> <p>Docs are here:</p> <ul> <li><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#...
python|pandas|performance|csv
0
13,957
63,368,983
print "EXTERNSHEET(b7-):" pandas
<p>I was trying to run as ussually my library &quot;pandas&quot; but then I faced a mistake</p> <pre><code>import pandas as pd DF_temp = pd.read_excel(&quot;example.xlsx&quot;) </code></pre> <p>Output</p> <pre><code> File &quot;/opt/anaconda3/lib/python3.7/site-packages/xlrd/__init__.py&quot;, line 1187 print &q...
<p>Had the same issue and used suggested fix python3 -m pip install --upgrade xlrd Worked for me even though I received some warning.</p> <pre><code>Defaulting to user installation because normal site-packages is not writeable Collecting xlrd Downloading xlrd-1.2.0-py2.py3-none-any.whl (103 kB) |████████████████...
python|pandas|xlrd
10
13,958
21,803,256
Error: Setting an array element with a sequence. Python / Numpy
<p>I'm receiving this error when trying to assign an array to another array specific position. I was doing this before creating simple lists and doing such assignment. But Numpy is faster than simple lists and I was trying to use it now.</p> <p>The problem is cause I have a 2D array that stores some data and, in my co...
<p>The trouble is that matrix_b is defaulting to a float dtype. On my machine, checking</p> <pre><code>matrix_b.dtype </code></pre> <p>returns <code>dtype('float64')</code>. To create a numpy array that can hold anything, you can manually set dtype to object, which will allow you to place a matrix inside of it:</p>...
python|arrays|numpy
21
13,959
53,649,371
In Tensorflow, what is the difference between Session.partial_run and Session.run?
<p>I always thought that <code>Session.run</code> required all placeholders in the graph to be fed, while <code>Session.partial_run</code> only the ones specified through <code>Session.partial_run_setup</code>, but looking further that is not the case. </p> <p>So how exactly do the two methods differentiate? What are ...
<p>With <a href="https://www.tensorflow.org/api_docs/python/tf/Session#run" rel="nofollow noreferrer"><code>tf.Session.run</code></a>, you usually give some inputs and expected outputs, and TensorFlow runs the operations in the graph to compute and return those outputs. If you later want to get some other output, even ...
session|tensorflow
4
13,960
53,485,631
Dictionary with Panda Dataframe as value
<p>Here is below the output of the object dic when I print it:</p> <pre><code>{'Stock': Price date 2018-11-23 150 2018-11-26 153} </code></pre> <p>By printing dic['Stock'] I end up with:</p> <pre><code> Price date 2018-11-23 150 2018-11-26 153 </code></pre> <...
<pre><code>dic['Stock'].reset_index().values.tolist() #[['2018-11-23', 150], ['2018-11-26', 153]] </code></pre>
python|python-3.x|pandas|numpy
1
13,961
53,487,627
stop groupby from making 2 combination same pair in python dataframe
<p>I am working on IPL dataset from Kaggle (<a href="https://www.kaggle.com/manasgarg/ipl" rel="noreferrer">https://www.kaggle.com/manasgarg/ipl</a>). I want to sum up the runs made by two people as pair and I have prepared my data. When I am trying a GROUPBY on the dataframe columns (batsman and non_striker) it is mak...
<p>You can sort the batsman and non_striker and then group the data</p> <pre><code>df[['batsman', 'non_striker']] = df[['batsman', 'non_striker']].apply(sorted, axis=1) df.groupby(['batsman', 'non_striker']).batsman_runs.sum().nlargest(10) </code></pre> <p>Edit: You can also use numpy for sorting the columns, which ...
python|pandas
4
13,962
53,781,507
pandas - efficiently computing minutely returns as columns on intraday data
<p>I have a DataFrame that looks like such:</p> <pre><code> closingDate Time Last 0 1997-09-09 2018-12-13 00:00:00 1000 1 1997-09-09 2018-12-13 00:01:00 1002 2 1997-09-09 2018-12-13 00:02:00 1001 3 1997-09-09 2018-12-13 00:03:00 1005 </code></pre> <p>I ...
<p>You can do this with some aggregation and shifting your time series that should result in more efficient calculations.</p> <p>First aggregate your data by <code>closingDate</code>.</p> <pre><code>g = df.groupby("closingDate") </code></pre> <p>Next you can shift your data to offset by a day.</p> <pre><code>shifte...
python|pandas
1
13,963
17,170,230
assertion error with np.load following numpy.savez
<p>I have 5 numpy arrays <code>a,b,c,d</code> and <code>e</code> all defined as:</p> <pre><code>array([1, 2, 3, 4, 5, 6, 7, 8, 9]) </code></pre> <p>I am saving these arrays like so:</p> <pre><code>np.savez_compressed('tmp/test',a=a,b=b,c=c,d=d,e=e) </code></pre> <p>This results in a file, <code>test.npz</code> bein...
<p>Cannot reproduce your problem neither on Linux or Mac (Python 2.7, numpy 1.6.1/1.7.1)</p> <p>But, I've noticed you using relative path for saving file <code>tmp/test.npz</code>. Is that intentional? In my recollection recent versions of Windows have some special treatment for a new files applications trying to crea...
python|file-io|numpy
1
13,964
12,297,759
Reindex time-stamped data with date_range
<p>I have a <code>pandas.Series</code> of time-stamped data - basically a sequence of events:</p> <pre><code>0 2012-09-05 19:28:52 1 2012-09-05 19:28:52 2 2012-09-05 19:44:37 3 2012-09-05 19:44:37 4 2012-09-05 20:04:53 5 2012-09-05 20:04:53 6 2012-09-05 20:12:59 7 2012-09-05 20:...
<p>If you would use the timestamps of the events as index of the series instead of the data, resample can do this. In the example below, the index of series s are the timestamps and data is the event_id, basically the index of your series.</p> <pre><code>In [47]: s Out[47]: event_id timestamp 201...
python|time-series|pandas|data-analysis
2
13,965
12,269,834
Is there any numpy autocorrellation function with standardized output?
<p>I followed the advice of defining the autocorrelation function in another post:</p> <pre><code>def autocorr(x): result = np.correlate(x, x, mode = 'full') maxcorr = np.argmax(result) #print 'maximum = ', result[maxcorr] result = result / result[maxcorr] # &lt;=== normalization return result...
<p>So your problem with your initial attempt is that you did not subtract the average from your signal. The following code should work:</p> <pre><code>timeseries = (your data here) mean = np.mean(timeseries) timeseries -= np.mean(timeseries) autocorr_f = np.correlate(timeseries, timeseries, mode='full') temp = autoco...
python|numpy|statistics|correlation|autocorrelation
6
13,966
71,972,865
how to eliminate duplicate rows in column A keeping the maximum value in B in python
<p>I'm working with data from an excel file like this.</p> <pre><code>A B 2001-05-01 12:30 10 2001-05-01 12:30 20 2001-05-05 11:50 30 2001-05-05 11:50 40 2002-03-22 14:12 10 </code></pre> <p>I'm using this line of code to eliminate the duplicates keeping the maximum</p> <p><code>df_clean=df_r...
<p>If I can assume that your index is just a <code>RangeIndex</code> then I think what you are looking for is:</p> <pre><code>df_clean=df_raw.sort_values('A', ascending=False).drop_duplicates('B', ignore_index=True) </code></pre> <p>and not <code>sort_index()</code></p>
python|pandas
0
13,967
71,831,578
Multi input problem Keras. Expected to see 2 array(s), but instead got the following list of 1 arrays
<p>I have a model that takes two inputs of the same shape <code>(batch_size,512,512,1)</code>, and predict two masks each of shape <code>(batch_size,512,512,1)</code>.</p> <pre><code>dataset_input = tf.data.Dataset.zip((dataset_img_A, dataset_img_B)) dataset_output = tf.data.Dataset.zip((seg_A, seg_B)) dataset = tf.dat...
<p>SOLVED: Turns out it was an issue with the data augmentation step where tensors where concatenated inputs. Lesson learnt</p>
python|arrays|tensorflow|keras
0
13,968
19,120,480
Chose the farthest k points from given n points
<p>I have a set S of <em>n</em> points in dimension <em>d</em> for which I can calculate all pairwise distances if need be. I need to select <em>k</em> points in this set so that the sum of their pairwise distances is maximal. In other, slightly more mathematical words, I want p1, ..., pk in S such that sum(i,j &lt; k)...
<p>How about this greedy algorithm:</p> <ol> <li>add to the solution the 2 points with the greatest distance between them in S</li> <li>until you reach a solution of size k, add to the solution the point for which the sum of distances from it to all the points already in the solution is the greatest.</li> </ol> <p>Le...
python|algorithm|numpy|geometry
6
13,969
21,938,533
Pandas dynamic column creation
<p>I am attempting to dynamically create a new column based on the values of another column. Say I have the following dataframe</p> <p>A|B<br> 11|1<br> 22|0<br> 33|1<br> 44|1<br> 55|0<br></p> <p>I want to create a new column. If the value of column B is 1, insert 'Y' else insert 'N'. The resulting dataframe should lo...
<p>Avoid chained indexing by using <code>loc</code>. There are some subtleties with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">returning a view versus a copy</a> in pandas that are related to <code>numpy</code></p> <pre><code>df['C'] = 'N' df.loc[df.B =...
pandas
3
13,970
22,000,967
need pandas DataFrame.resample() to honor sub-period series start datetime
<p>I'm using the pandas DataFrame.resample() function to downsample 1 minute-frequency time series data to 15min-frequency. The original data consists of multiple time series aligned to the same minute-frequency where each series is a list of tuples, each tuple is defined to be <code>(&lt;offset from start time&gt;, &...
<p>Try using <code>base</code>, <code>loffset</code> and/or switching the label to <code>left</code> (this uses a different random seed that you).</p> <pre><code>In [17]: df.resample('15min', how='sum', label='right') Out[17]: values 2014-02-24 01:15:00+00:00 10 2014-02-24 01:30:00+00:...
python|pandas
1
13,971
8,485,107
Type of slice impacts mutability of numpy array
<p>I create netCDF files using python. When I try to assign values (data) to parts (or slices) of variables, depending on what is the "type" of slice, I can or I cannot assign the values. </p> <p>I don't know why. Any <strong><em>help to understand why that is</em></strong> would be appreciated. </p> <p>E.g.: </p>...
<p>Your example code seems to work on my machine, but I think you might be having a problem because you're using multiple index on the left side of your assignment. <code>A[0, :, ::-1][...] = something</code> where <code>A</code> is an array is weird, and even though it seems to work on my machine, I would try and avoi...
python|arrays|numpy|slice|netcdf
2
13,972
55,493,237
How to check a type of column values in pandas DataFrame
<p>I can check column types using <code>df.dtypes</code>, where <code>df</code> is pandas DataFrame. However, my question is a bit different. I have the following DataFrame:</p> <pre><code>col1 col2 0 &lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&gt; 1 &lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&...
<p>Try with:</p> <pre><code>df_viz['col3']=(df_viz.col2.transform(lambda x: np.where(x==pd._libs.tslibs.timestamps.Timestamp,'Yes','No'))) </code></pre>
python|pandas
2
13,973
55,440,224
Extra quote marks being added to String field in dataframe
<p>I'm trying to do some text processing on entries in a tsv file so I loaded it in as a dataframe and I'm trying to add a quotation mark at the beginning of a certain entry in the dataframe. So the code I'm using to do this is as follows </p> <pre class="lang-py prettyprint-override"><code>episode_info.loc[i, 'word']...
<p>Okay I printed out the entries in question to terminal and it looks like it was printing out the correct thing. I guess when I viewed it in Sublime, which is what I was using, the quotation marks were being formatted weirdly. Apologies for the unnecessary question.</p>
pandas|dataframe
0
13,974
55,576,133
TensorFlow 2.0 dataset.__iter__() is only supported when eager execution is enabled
<p>I'm using the following custom training code in TensorFlow 2:</p> <pre><code>def parse_function(filename, filename2): image = read_image(fn) def ret1(): return image, read_image(fn2), 0 def ret2(): return image, preprocess(image), 1 return tf.case({tf.less(tf.random.uniform([1])[0], tf.constant(0.5)...
<p>I fixed it by enabling eager execution after importing tensorflow:</p> <pre><code>import tensorflow as tf tf.enable_eager_execution() </code></pre> <p>Reference: <a href="https://www.tensorflow.org/guide/eager" rel="noreferrer">Tensorflow</a></p>
python|tensorflow|tensorflow-datasets|tensorflow2.0
18
13,975
56,866,639
Is it possible to share a Tensorflow model among Gunicorn workers?
<p>I need to put in production a Tensorflow model with a simple APIs endpoint. The model should be shared among processes/workers/threads in order to not waste too many resources in terms of memory. </p> <p>I already tried with multiple gunicorn workers setting the --preload option and loading the model before the def...
<p>The issue is that the Tensorflow runtime and global state is not fork safe. See this thread: <a href="https://github.com/tensorflow/tensorflow/issues/5448" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/5448</a> or this one: <a href="https://github.com/tensorflow/tensorflow/issues/51832" r...
api|tensorflow|keras|webserver|production
0
13,976
56,619,521
replace a cell in dataframe following a regex in dataframe Pandas
<p>I have this dataframe , and I want to replace any cell that contains an alphabetic character with an empty value . </p> <pre><code>df = pd.DataFrame(dict(A = pd.Series(['AB5 La2','-1','8577Y--00']), B = pd.Series(['2\nDate','-45.00','-']))) df.replace(['.*[a-zA-Z].*'], [''], regex=True , inplace=True) df </code>...
<pre><code>\s Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v]. </code></pre> <p><a href="https://docs.python.org/3/howto/regex.html" rel="nofollow noreferrer">https://docs.python.org/3/howto/regex.html</a></p> <pre><code>In [44]: df = pd.DataFrame(dict(A = pd.Series(['AB5 La2','-1','85...
python|regex|pandas|dataframe|replace
1
13,977
56,695,774
My timestamp strings have "-05:00" at the end, what does it mean and how do I handle it?
<p>My csv file has a different format TIMESTAMP. Screenshot of the file is given below: </p> <pre><code>2015-01-01 00:00:00-05:00 2015-01-01 00:01:00-05:00 2015-01-01 00:02:00-05:00 2015-01-01 00:03:00-05:00 2015-01-01 00:04:00-05:00 2015-01-01 00:05:00-05:00 2015-01-01 00:06:00-05:00 </code></pre> <p>My code is give...
<p>Your datetimes are timezone aware (the "-05:00" indicates you are 5 hours behind UTC, for example). What you'd want to do is load your TIMESTAMP column, then use <code>tz_localize</code> to convert it to a naive timestamp (no timezone information).</p> <pre><code>df = pd.read_csv('example.csv', usecols=['TIMESTAMP'...
python|pandas|dataframe|datetime
4
13,978
56,602,596
Converting a series of floats to int - some NaNs in list are causing an error 'cannot convert float NaN to integer'. How to skip NaNs?
<p>I have a very large column of phone numbers in a pandas dataframe, and they're in float format: <code>3.52831E+11</code>. There are also NaNs present.</p> <p>I am trying to convert the numbers to int and it's throwing an error that NaNs can't be converted to int. Fair enough. But I can't seem to get around this. </...
<p>From pandas 0.24+, we have the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html#nullable-integer-data-type" rel="nofollow noreferrer">Nullable Integer Type</a>. The first step is to convert your strings (objects) to float, then to nullable int:</p> <pre><code>df.astype('float').astyp...
python|pandas
1
13,979
26,322,352
Python Pandas:Need help making a chart with 2 line plots from a single pandas dataframe
<p>so I have automobile fuel economy data and I just want to chart the average overall mpg of Honda vs Toyota. I can do this by making a dataframe containing just Honda data and then creating a dataframe containing just Toyota data. Then plot the 2 data sets. But I was wondering if I can make the same chart from a sing...
<p>The problem seems to be that when you created 'honda_toyota_average' it became a Series object in which the 'make' column cannot be accessed. Presumably the plot function is therefore also unable to make use of it. </p> <p>If instead you use the pivot_table method on the dataframe you can easily create a honda and ...
python|pandas
0
13,980
67,095,821
Multiple Linear Regression with TensorFlow
<p>I'm trying to perform a Multiple Linear Regression with TensorFlow and confront the results with <code>statsmodels</code> library.</p> <p>I generated two random variables <code>X1</code> and <code>X2</code> (so that anyone can reproduce it) that will explain the Y variable. The <code>X2</code> variable is completely...
<p>The key issues with your code are the following:</p> <ol> <li>While it is necessary to add a column of ones to the features matrix <code>x_data</code> before running the regression with statsmodels, this is not necessary when running the regression with tensorflow. This means that you are passing 3 features to tenso...
python|tensorflow|keras|linear-regression
1
13,981
67,153,803
Displaying the complete dataframe in Pandas
<p>I have a Pandas dataframe in Google Colab that displays a Query ID, a Brand ID and the Brand Name. It's a pretty hefty amount of lines (193k lines approx.) and I think that that amount of lines is responsible for the following:</p> <p><a href="https://i.stack.imgur.com/0qg4H.png" rel="nofollow noreferrer"><img src="...
<p>The option you're looking for is <code>pandas.set_option('display.max_rows', None)</code>.</p>
python|pandas|dataframe
1
13,982
66,784,459
SAS set datasets to Python
<p>I have 2 sas datasets and I'm using SET statement to combine both of them into a new one by a key column. Here is how the data looks (note: '.' is a missing or null value)</p> <pre><code>data1 data2 ID X Y ID X Z 01 12 11 01 . 4 02 15 . 03 17 6 03 18 . data combine; set data1 d...
<h3><code>concat</code></h3> <pre><code>pd.concat([data1, data2], ignore_index=True).sort_values('ID') ID X Y Z 0 01 12.0 11.0 NaN 2 01 NaN NaN 4.0 1 02 15.0 NaN NaN 3 03 17.0 NaN 6.0 4 03 18.0 NaN NaN </code></pre> <hr /> <h3><code>append</code></h3> <pre><code>data1.append(data...
pandas|merge|concatenation
3
13,983
66,769,854
Keras ValueError: Shapes (None, 365) and (None, 1) are incompatible, Image Dataset from Directory
<p>I'm attempting to train a network on the <a href="http://places2.csail.mit.edu/" rel="nofollow noreferrer">Places2</a> dataset and have arranged all the classes into subfolders. When the training and validation datasets are loaded via:</p> <pre class="lang-py prettyprint-override"><code>from tensorflow.keras.preproc...
<p>well after a few hours of head scratching I figured it out! All you have to do is in model.compile change metrics=['Accuracy'] to metrics=['accuracy']. I went back to an old network I built a few years back that used sparse_categorical_crossentropy and went through it line by line.</p>
python|tensorflow|machine-learning|keras|deep-learning
1
13,984
66,874,396
How to convert dynamic nested json into csv?
<p>I have some dynamically generated nested json that I want to convert to a CSV file using python. I am trying to use pandas for this. My question is - is there a way to use this and flatten the json data to put in the csv without knowing the json keys that need flattened in advance? An example of my data is this:</p>...
<p>If using pandas doesn't work for you, here's the more canonical Python way of doing it.</p> <p>You're trying to write out a CSV file, and that implicitly means you must write out a header containing all the keys.</p> <p>The constraint that you don't know the keys in advance means you can't do this in a single pass.<...
python|json|pandas|csv
0
13,985
67,039,217
Flatten and merge arrays and then split them back
<p>Suppose that I have 3 matrces w2,w3 and w4 with shapes <code>(5,5)</code> <code>(5,5)</code> and <code>(5,1)</code></p> <p>Is there any efficient way to create a flatten array of those 3 matrices with shape <code>(55,1)</code> or <code>(55,)</code> (do some calculations) and then split this new array back to 3 matri...
<p>The function <code>flatten</code> performs a copy and <code>append</code> creates a new Numpy array while <code>reshape</code> does not.</p> <p>You can use <code>np.concatenate</code> followed by <code>np.array_split</code> with some <code>reshape</code>. Here is how:</p> <pre class="lang-py prettyprint-override"><c...
python-3.x|numpy|flatten
2
13,986
67,154,146
What are the possible causes of this df.drop() behavior in Pandas?
<p>I have a Pandas dataframe <code>df</code> of which <code>df2</code> is a subset. When I try to drop rows in <code>df</code> based on the index values of <code>df2</code>, I get some funny math as below. What might be causing such behavior? Am I completely misunderstanding how <code>.index</code> works?</p> <pre><c...
<p>Based on the numbering system, it looks like there are multiple records with the <a href="https://stackoverflow.com/a/41209697/7287543">same index</a>. If that's the case, dropping, for example, <code>106</code> because it is in <code>df2</code> may result in multiple records being dropped from <code>df</code>. Chec...
python|pandas|dataframe
2
13,987
66,913,586
How to convert Dataframe containing float and nan values to datetime python?
<p>I have a dataframe float column as:</p> <pre><code>data = {'mydate': [23131.0,23131.0,np.nan,22677.0,22554.0,np.nan,23131.0]} df = pd.DataFrame(data,columns=['mydate']) mydate 0 23131.0 1 23131.0 2 NaN 3 22677.0 4 ...
<p>To convert a float to datetime and ignore np.nan values, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime with errors='coerce'</code></a></p> <pre><code>import pandas as pd import numpy as np data = {'mydate': [231...
python|pandas|datetime
2
13,988
66,773,619
I would like to find consecutive numbers in column A and column B in python (pandas)
<p>I would like to find consecutive numbers in column A and Column B in python, Column A should be ascending but Column B is descending. I am attaching an example file.</p> <p>Input file</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>nucleotide</th> <th>Pos_A</th> <th>Pos_B</th> <th></th> ...
<p>Do it one by one then <code>groupby</code> with <code>ngroup</code></p> <pre><code>s1 = df.Pos_A.diff().le(0).cumsum() s2 = df.Pos_B.diff().ge(0).cumsum() df['out'] = df.groupby([s1,s2]).ngroup()+1 Out[452]: 0 1 1 2 2 2 3 3 4 3 5 3 6 4 7 4 8 4 9 4 10 5 11 5 12 5 13 ...
python-3.x|pandas
2
13,989
47,265,369
Numpy error: operands could not be broadcast together with shapes 1
<p>I am a python beginner. I have an error message "ValueError: operands could not be broadcast together with shapes".</p> <p>Here is my data:</p> <pre><code>import numpy as np spent = np.array([ 10, 10, 13, 12, 109, 17, 31, 1, 39, 41, 45, 41, 71, 161, 39, 115, 5, 51, 58, 334, 165, 10...
<p>IIUC you don't need the mask on <code>spent</code> per se like you've done:</p> <pre><code>In[16]: a=(spent&gt;100) &amp; (visit&gt;10) a Out[16]: array([False, False, False, False, True, False, False, False, False, False, False, False, False, True, False, True, False, False, False, True, True,...
python|numpy
3
13,990
47,298,022
Fixing date labels when plotting bar chart of resampled Pandas time series data in Matplotlib
<p>Using the command <code>monthly[monthly.columns[:3]].resample('Q').sum()</code> in pandas, I create a DataFrame that looks like this: </p> <pre><code>DateIndex C1 C2 C3 2012-09-30 94 139 181 2012-12-31 111 236 162 2013-03-31 113 321 259 2013-06-30 96 238 219 </code></pre> <p>I can then plot those num...
<pre><code>y = monthly[monthly.columns[:3]].resample('Q').sum() fig, ax = plt.subplots(figsize=(12,5)) y.plot(ax=ax,kind='bar',stacked=True) ax.xaxis.set_ticklabels(y.index.to_period('Q')) </code></pre>
python|pandas|matplotlib
1
13,991
11,199,437
issue with pandas and semilog for boxplot
<p>I have a <code>pandas</code> <code>dataframe</code> that has columns: </p> <p>'video' and 'link' of click values </p> <p>with an index of datetime. For some reason, when I use semilogy and boxplot with the video series, I get the error</p> <pre><code>ValueError: Data has no positive values, and therefore can not ...
<p><strong>Note: I'm unable to upload images due to some issue with imgur. I'll try again later.</strong> </p> <p>Take advantage of pandas matplotlib helper / wrappers by calling pd.DataFrame.boxplot(). I believe this will take care of the NaN values for you. It will also put both Series in the same plot so you can ea...
matplotlib|pandas
1
13,992
68,168,914
How to export pyreadstat’s metadata container to json
<p>I read a sav file using this code:</p> <p><code>df_file, meta_data = pyreadstat.read_sav(‘path’)</code></p> <p>It returns <code>df_file</code> as pandas DataFrame but returns <code>meta_data</code> as <code>metadata_container object</code>. I need to share <code>meta_data</code> object to a colleague who is not prog...
<p>Not perfect but it's a first step, you can use <code>meta.__dict__</code></p> <pre><code>import json df, meta = pyreadstat.read_sav('path') json.dump(meta.__dict__, open(&quot;metadata.json&quot;, &quot;w&quot;), indent=4) </code></pre>
python|pandas|spss
0
13,993
59,374,555
Generate sequence of negative numbers
<p>I have the following dataframe:</p> <pre><code> userId firstName lastName gender level 61 -1 Not Provided Not Provided Not Provided paid 100 -1 Not Provided Not Provided Not Provided free </code></pre> <p>Both <code>userId</code> are <code>-1</code> because I executed the...
<p>If want replace only empty strings use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> for mask of this values and then add array with length by sum of <code>True</code>s in boolean mask:</p> <pre><cod...
python|pandas
3
13,994
59,402,551
Is there a way to get the top k values per row of a numpy array (Python)?
<p>Given a numpy array of the form below:</p> <pre><code>x = [[4.,3.,2.,1.,8.],[1.2,3.1,0.,9.2,5.5],[0.2,7.0,4.4,0.2,1.3]] </code></pre> <p>is there a way to retain the top-3 values in each row and set others to zero in python (without an explicit loop). The result in the case of the example above would be </p> <pre...
<p>Here is a fully vectorized code without third party outside <code>numpy</code>. It is using numpy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html" rel="nofollow noreferrer">argpartition</a> to efficiently find the k-th values. See for instance <a href="https://stackoverflow.co...
python|python-3.x|python-2.7|numpy|loops
2
13,995
59,356,075
Pandas - Extract text between two strings
<p>I have a Dataframe whose column has data in the below format:</p> <pre><code>--- - !ruby/hash:Control::Keys name: sample1 value: 101 </code></pre> <p>I am trying to extract just the name and values and store them as new column. I tried </p> <pre><code>df['col'].str.extract(r'name:(\w+)value') </code></pre> <...
<p>You can try</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df['names'] = df.col.str.extract(r'(?&lt;=name:)\s+(\w+)') &gt;&gt;&gt; df['values'] = df.col.str.extract(r'(?&lt;=value:)\s+(\w+)') &gt;&gt;&gt; df col names values 0 ---\n- !ruby/hash:...
pandas
1
13,996
59,123,562
Replacing question marks with np.nan
<p>I am trying to replace question marks in my data set with np.nan:</p> <p>I tried using the following code: </p> <pre><code>df['Workclass'] = [row if row!='?' else np.nan for row in df['Workclass']] </code></pre> <p>And this: </p> <pre><code>df['Workclass'] = df['Workclass'].map(lambda x: np.nan if x=="?" else x...
<p>Try this:</p> <pre><code>df['Workclass'].apply(lambda x: np.nan if x == '?' else x) </code></pre> <p>and if that works:</p> <pre><code>df['Workclass'] = df['Workclass'].apply(lambda x: np.nan if x == '?' else x) </code></pre> <p>if your looking for '?' anywhere in a string you can use this:</p> <pre><code>df[...
python|pandas|replace|null
2
13,997
59,262,647
Convert String object to datetime in python
<p>I have a object column as 27/11 as day and month. When I convert it into datetime I am getting 1900-11-27. But I need only 27-11 as a datetime column. Can you help me with this?</p>
<pre><code>my_dict = {'date': ['27/11', '14/03', '19/06']} df = pd.DataFrame(my_dict) df['date'] = pd.to_datetime(df['date'], format='%d/%M').dt.strftime('%M/%d') </code></pre> <p>Output:</p> <pre><code> date 0 11/27 1 03/14 2 06/19 </code></pre> <p>Or just change the strftime format to get what you want: <cod...
python|python-3.x|pandas
0
13,998
14,095,463
How to make a Datetimeindex not be the index in a dataframe
<p>I'd like to have access to the special methods provided by the Datetimeindex class such as month, day, etc. However I can't seem to make a series in a dataframe be a Datetimeindex without making it the dataframe's index. Take the following example:</p> <pre><code>dates Out[119]: Dates 0 1/1/2012 1 ...
<p>Update: in 0.15 you will have access to a dt attribute for datetimelike methods:</p> <pre><code>dates.Dates.dt.month </code></pre> <hr> <p>Old post (do use Wes' solution and not this):</p> <p>Here's one (slow!) workaround to do it using <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame...
python|pandas
2
13,999
45,229,177
multiple boxplots by date in index
<p>My dataframe </p> <pre><code>index Dates Hours_played 0 2014-11-06 11 1 2014-12-06 4 2 2015-09-06 5 3 2015-97-06 5 </code></pre> <p>Then, I set Dates as index:</p> <pre><code> Hours_played Dates 2014-11-06 11 2014-12-06 4 2015-09-06 5 2015-97-06 ...
<p>A simple solution will be grouping by year first and then making boxplot:</p> <pre><code>import io import matplotlib.pyplot as plt import pandas as pd # Re-create your sample data s = """Dates,Hours_played 2014-11-06,11 2014-12-06,4 2015-09-06,5 2015-07-06,5""" df = pd.read_table(io.StringIO(s), sep=',', index_co...
python|pandas|matplotlib
2