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
374,900
70,107,223
TensorFlow ValueError: Input 0 of layer sequential is incompatible with the layer
<p>When I run the last part of the code below I get the following error:</p> <pre><code>ValueError: Input 0 of layer sequential_1 is incompatible with the layer: expected axis -1 of input shape to have value 28 but received input with shape (None, 30, 30) </code></pre> <pre><code>import pandas as pd ...
<p><strong>Working sample code</strong></p> <pre><code>import pandas as pd import numpy as np from tensorflow import keras from tensorflow.keras.layers import Conv1D, MaxPooling1D, Dense, Dropout, Flatten, GRU, SimpleRNN, LSTM, Bidirectional, Activation, TimeDistributed from tensorflow.keras impo...
python|tensorflow
0
374,901
70,042,492
Pandas: Multiple indices in a dataframe: drop some, keep others
<p>My data has the following structure:</p> <pre><code>&gt;&gt;&gt; df.head() value Date FIPS_state Date 2001-01-01 1 2001-03-31 6.4621 2 2001-03-31 11.3259 4 2001-03-31 6.3467 5 2001-03-31 6.0...
<p>You can do it by removing the the first <code>Date</code> column from the index (or any <code>Date</code> column - there just shouldn't be duplicate column names):</p> <pre class="lang-py prettyprint-override"><code>df.index = df.index.droplevel(0) </code></pre> <p>Then reset the index:</p> <pre class="lang-py prett...
python|pandas|pandas-groupby|multi-index
1
374,902
70,064,499
How does Python interpret a half 'empty' tuple (x,)?
<p>I came across this code fragment and can't understand what is happening here.</p> <pre><code>X = np.linspace(-5,5,50) Y = np.linspace(-5,5,50) X, Y = np.meshgrid(X,Y) pos = np.empty(X.shape+(2,)) </code></pre> <p>Why is <code>(2,)</code> necessary here and how does Python interpret half empty tuples like that in...
<p><code>(2,)</code> is literal for tuple with one element. You need that in</p> <pre><code>pos = np.empty(X.shape+(2,)) </code></pre> <p>as <code>X.shape</code> is <code>tuple</code> and <code>+</code> denotes concatenating tuples in <code>python</code>, in this particular example you are adding another dimension befo...
python|numpy|tuples
2
374,903
70,223,893
Conv layer, No gradients provided for any variable
<p>I try to train mnist dataset but I got an error like this:</p> <pre><code> No gradients provided for any variable: ['module_wrapper/conv2d/kernel:0', 'module_wrapper/conv2d/bias:0', 'module_wrapper_2/conv2d_1/kernel:0', 'module_wrapper_2/conv2d_1/bias:0', 'module_wrapper_5/dense/kernel:0', 'module_wrapper_5/dense/...
<p>Here is a working example based on your code but with the MNIST dataset, and just in case you didn't know, you should either use a softmax function on your output layer or set the <code>from_logits</code> parameter of your loss function to <code>True</code>, but <strong>not</strong> both.</p> <pre class="lang-py pre...
python|tensorflow|keras|deep-learning|tensorflow2.0
1
374,904
56,151,618
conditional forward fill within groupby
<p>I have a data frame for patients and their visits to the clinic. Patients may take a drug at some visits, and only the initial dose is recorded, or when the dose is changed. If the dose doesn't change at the next visit, what's recorded is "drug ongoing? Yes. Dose changed? No". What I need to get is the exact dose fo...
<p>In your case , filter before <code>ffill</code> </p> <pre><code>s=df.loc[(df['drug_ongoing'].eq(1)&amp;df['drug_dose_changed'].eq(0))|df.visit_number.eq(df.groupby('patient_id').visit_number.transform('first'))].groupby('patient_id').dose.ffill() df.dose.fillna(s,inplace=True) df Out[38]: patient_id visit_numbe...
python|pandas|dataframe|pandas-groupby|missing-data
4
374,905
56,329,451
Use pandas to plot highest correlations
<p>I have been plotting correlations via heatmaps with the following code. However, there are too many variables. Is it possible to plot the highest correlations ( over .5 and -.5) on a graph?</p> <pre><code>plt.rcParams['figure.figsize'] = [80,80] corr3 = datasetcm.corr() fig = plt.figure() ax = fig.add_subplot(111...
<p>Filter your correlation matrix on the treshold of 0.5 before plotting. This will return <code>0</code> for the correlations lower than <code>0.5</code>.</p> <p>Then we can use color mapping to show the rows with 0 as <code>not correlated</code> </p> <pre><code>corr3 = datasetcm.corr() corr3 = corr3 [corr3 &gt; 0.5...
pandas|correlation
1
374,906
56,202,832
I assign list of values to a new column and getting the warning SettingWithCopyWarning:
<p>I have a data frame that has the month and date for 2015. I calculate the Year to Date value into a list. I assign this list to a new column in the data frame but get a warning SettingWithCopyWarning. How do I get around it and some explanation why is this happening. Thanking you all in advance.</p> <pre><code>prin...
<p>You get this warning often when trying to set values on a copy of a dataframe. The only place in your code where this could happen is </p> <pre><code>dfabovemax['YtoDt'] = list(ytodt2) </code></pre> <p>This means that in all likelihood, dfabovemax is the result of another dataframe. In python, the dfabovemax is st...
python|pandas
0
374,907
56,071,559
Pandas conditional map/fill/replace
<pre><code>d1=pd.DataFrame({'x':['a','b','c','c'],'y':[-1,-2,-3,0]}) d2=pd.DataFrame({'x':['d','c','a','b'],'y':[0.1,0.2,0.3,0.4]}) </code></pre> <p>I want to replace <code>d1.y</code> where y&lt;0 with the correspondent <code>y</code> in d2. It's something like vlookup in Excel. The core problem is replace y accordin...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> with condition:</p> <pre><code>s = d2.set_index('x')['y'] d1.loc[d1.y &lt; 0, 'y'] = d1['x'].map(s) print (d1) x y 0 a 0.3 1 b 0.4 2 c 0.2 3 c 0.0 </cod...
python|pandas
3
374,908
56,436,632
Improve performance of rewriting timestamps in parquet files
<p>Due to some limitations of the consumer of my data, I need to "rewrite" some parquet files to convert timestamps that are in nanosecond precision to timestamps that are in millisecond precision.</p> <p>I have implemented this and it works but I am not completely satisfied with it.</p> <pre class="lang-py prettypri...
<p>You could try rewriting all columns at once. Maybe this would reduce some memory copies in pandas, thus speeding up the process if you have many columns:</p> <pre><code>df_datetimes = df.select_dtypes(include="datetime64[ns]") df[df_datetimes.columns] = df_datetimes.astype("datetime64[ms]") </code></pre>
python|pandas|amazon-s3|parquet|pyarrow
1
374,909
56,175,937
Write Multiple Dynamic DataFrames to Excel Workbook
<p>I am looking for help in filtering different dataframes to export to worksheets. Here is a sample dataframe.</p> <pre><code>import pandas as pd import numpy as np np.random.seed(1111) df = pd.DataFrame({ 'Category':np.random.choice( ['Group A','Group B','Group C','Group D'], 10000), 'Sub-Category':np.random.choice...
<p>How about just running</p> <pre><code>for c in df.Category.unique(): with pd.ExcelWriter(f"/Users/constantino/Desktop/{c}.xlsx") as writer: for i, d in enumerate([df1, df2, df3]): d.loc[c].to_excel(writer, sheet_name=f"df{i+1}") </code></pre>
python|excel|pandas
0
374,910
56,359,069
Reorder only a part of a pandas DataFrame
<p><strong>Context</strong></p> <p>I have a pandas-DataFrame with a structure analogous to something like the table on the left:</p> <pre><code> + Category + Content + Layer + Category + Content + Layer Index | | | Index | | | ----------------...
<p>You can do this in two steps:</p> <ol> <li>Filter rows by condition, for example by creating a boolean <code>mask</code></li> <li>Directly address the underlying numpy-arrays via <code>.loc</code> (in order to prevent the alignment of index values)</li> </ol> <blockquote> <p><code>.loc</code>: Access a group of ...
python|pandas|sorting|dataframe
4
374,911
56,193,488
Python3 Panda's Holiday fails to NOT find dates in arbitrary periods in the past
<p>Made my own definition of MLK Day Holiday that adheres not to when the holiday was first observed, but by when it was first observed by the NYSE. The NYSE first observed MLK day in January of 1998.</p> <p>When asking the Holiday for the days in which the holiday occurred between dates, it works fine for the most p...
<p>ANSWER: Inside of the <code>Holiday</code> class, the <code>dates()</code> method is used to gather the list of valid holidays within a requested date range. In order to insure that this occurs properly, the implementation gathers all holidays from one year before to one year after the requested date range via the ...
python|pandas|calendar|timestamp
0
374,912
56,167,463
Changing the optimizer in the tensorflow object detection
<p>How to change the optimiser for the configuration</p> <p>for example the following is a confgi for ssd_coco_mobilenetv2</p> <pre><code>train_config: { batch_size: 4 optimizer { rms_prop_optimizer: { learning_rate: { exponential_decay_learning_rate { initial_learning_rate: 0.0001...
<p>Here is the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/protos/optimizer.proto" rel="noreferrer">proto</a> file that corresponds to the optimizer. According to the proto file, you can choose among three different optimizers, e.g. </p> <ol> <li><p>rms_prop_optimizer </p></li> ...
python|tensorflow|object-detection|object-detection-api
5
374,913
56,148,611
When converting .dat into csv my code change the output values
<p>I have a .dat file and I am trying to convert it into a csv one. I have found a piece of code that "somehow" solved my problem. The thing is: such code gave me a messed up output file as a result. In other words: it changed my values!!!!</p> <p>Someone can help me with that? I am a total beginner at this.</p> <p>T...
<p>.dat files are not much readable using file io operations you can use asammdf module to read the .dat file.use pip install asammdf</p>
python|pandas
0
374,914
56,351,867
How to find mean of quantitative variable from categorical variable in a dataframe?
<p>Let's say I have the following data frame in pandas:</p> <pre><code>data = {'State':['CA', 'CA', 'CA', 'CA', 'NY', 'NY', 'TX'], 'Cost':[20, 30, 40, 50, 60, 70, 70]} test = pd.DataFrame(data) print(test.head(7)) </code></pre> <p>which would be the following</p> <pre><code> State Cost 0 CA 20 1 C...
<p>Use <code>groupby</code> and <code>mean</code>:</p> <pre><code>print(test.groupby('State').mean()) </code></pre> <p>Which outputs:</p> <pre><code> Cost State CA 35 NY 65 TX 70 </code></pre> <p>If you want a cleaner <code>DataFrame</code>:</p> <pre><code>print(test.groupby('State', ...
python|pandas
1
374,915
56,344,556
Image segmentation with edgeTPU
<p>I´m new here, so please be kind and teach me if I did not provide all the information you need :)</p> <p>I would like to compare Edge TPU with other edge device such as Myriad. I would like to select one object detection model and one image segmentation model. Considering the following link which shows supported op...
<p>Here you can find all supported layers for edgetpu: <a href="https://coral.ai/docs/edgetpu/models-intro/#supported-operations" rel="nofollow noreferrer">https://coral.ai/docs/edgetpu/models-intro/#supported-operations</a>.</p> <p>And for Conv2D it says &quot;Must use the same dilation in x and y dimensions.&quot;. S...
python-3.x|tensorflow-lite
0
374,916
56,430,955
Keras multi-gpu: specifying explicit GPU ids
<p>From looking at the file <code>keras/utils/multi_gpu_utils.py</code> in tensorflow GitHub repository, I could see that given that you specified that you want to use <code>x</code> GPUs, it will automatically allocate the GPU IDs from <code>range(x)</code>, i.e., <code>0, 1, 2, ..., x - 1</code>.</p> <p>I need to us...
<p>In python you can use </p> <pre><code>import os os.environ["CUDA_VISIBLE_DEVICES"]="0,1" </code></pre> <p>Or set <code>CUDA_VISIBLE_DEVICES=0,1</code> in bash before starting python script</p> <p>You can also refer to my answer <a href="https://stackoverflow.com/questions/40069883/how-to-set-specific-gpu-in-tenso...
tensorflow|keras|multi-gpu
1
374,917
56,295,471
Merge 2 dataframes with similar time indexes
<p>I have 2 dataframes, <code>ts1</code> and <code>ts2</code>. The data structure looks like this:</p> <pre><code> Date Close 0 2004-08-05 0.0 1 2004-08-06 -155.0 2 2004-08-09 -140.0 3 2004-08-10 -2.0 4 2004-08-11 -24.0 </code></pre> <p>Both have a <code>Date</code> and <code>Close</code> column....
<p>Pass how='inner' to the merge function. This will tell the merge function to do an inner join which will only keep keys found in both Data Frames.</p> <pre><code>ts_merged=ts1.merge( ts2, on='Date', how='inner', suffixes=('_TS1','_TS2') ) </code></pre>
python|pandas
1
374,918
56,273,406
how to get the desire rows by condition in DataFrame
<p>I have the DataFrame with index is the post_code and its value as medicines name and proportion. How can I just get 1 medicine name for each post_code alphabetically (some post_codes may have multiple 'bnf_name' with the same rate for the maximum. In this case, take the alphabetically first 'bnf_name')</p> <pre><co...
<p>You probably first want to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer">sort_values</a> by <em>both</em> index <code>post_code</code> and column <code>bnf</code> and then use <a href="https://pandas.pydata.org/pandas-docs/stable/refe...
python-3.x|pandas
-1
374,919
56,361,514
Divide data into bins with inf Python
<p>I'm having a problem with qcut function in python. My upper bounds and lower bounds are -Inf and Inf, but when I apply qcut with these bounds, Python return this error "cannot convert float infinity to integer".</p> <p>My friends told me that I should change the Inf into 1e100 (a very large number represents ) so q...
<p>You actually need <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.cut.html" rel="nofollow noreferrer">pd.cut</a>. It's because you're binning/labeling your data based on ranges:</p> <pre><code>a1 = [-np.inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7] cut_range = [-np.inf, 27.0, 33.0, 40.0,...
python-3.x|pandas|intervals
3
374,920
56,194,723
Write pandas data to a CSV file if column sums are greater than a specified value
<p>I have a CSV file whose columns are frequency counts of words, and whose rows are time periods. I want to sum for each column the total frequencies. Then I want to write to a CSV file for sums greater than or equal to 30, the column and row values, thus dropping columns whose sums are less than 30.</p> <p>Just le...
<p>It's easiest to do this in two steps:</p> <p><strong>1. Filter the DataFrame to just the columns you want to save</strong></p> <pre><code>df_to_save = df.loc[:, (df.sum(axis=0, skipna=True) &gt;= 30)] </code></pre> <p><code>.loc</code> is for picking rows/columns based either on labels or conditions; the syntax i...
pandas
2
374,921
56,109,392
Pandas/Numpy shift rows into column based on existence
<p>I have a dataframe like so:</p> <pre><code>col_a | col b 0 1 0 2 0 3 1 1 1 2 </code></pre> <p>I want to convert it to:</p> <pre><code>col_a | 1 | 2 | 3 0 1 1 1 1 1 1 0 </code></pre> <p>Unfortunately, most questions/answers revolving around this topic simply ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>get_dummies</code></a> with creating first column to <code>index</code>, last use <code>max</code> per index for return only <code>1/0</code> values in output:</p> <pre><code>df = pd.get_d...
python|pandas|numpy|scikit-learn
3
374,922
56,407,739
Is there a way to save time by not calculating unnecessary sums?
<h2>The objective</h2> <p>Given a 2-dimensional array <code>A</code>, I have to keep adding +1 to the value of the first row in each column until the sums of the columns equal to the same value, for example 28.</p> <h2>My solution</h2> <p>It is probably not the best of solutions, but considering the point I'd like t...
<p>Since you're only changing the first row, you don't need to recalculate the sum of the columns on each iteration. In fact, since the only change is adding 1 to some elements on the first row you don't need to iterate at all.</p> <pre><code>A = np.arange(20).reshape(2, 10) s = A.sum(0) d = max(s) - s A[0] += d &gt...
python|python-3.x|performance|numpy|numpy-ndarray
2
374,923
56,185,015
When trying to slice a pandas dataframe it raises "ValueError('Lengths must match to compare')"
<p>I have a huge pandas dataframe called df with the columns "Features","k","r2. The last two columns all contain numbers and the first row contains strings of lists(e.g "[Preop SC, Preop CC]").<br> I would like to slice the dataframe into smaller dataframes. One dataframe for every "Features"-"k" combination, using ne...
<p>Transforming the lists to string using the .apply method allows you to use .groupby:</p> <pre><code>df["Features"]=df.Features.apply(str) summary=df.groupby("Features").mean() print(summary) </code></pre>
python|pandas|scikit-learn|pandas-groupby|grid-search
0
374,924
56,368,717
Select and add column values from another dataframe based on if the index exists in both
<p>I have two dataframes, let's call them <code>A</code> and <code>B</code>, with the same indexes (person IDs), but some IDs might be in A and not B, and vice versa. Additionally, the IDs are Non-Unique in <code>B</code>, while unique in dataframe <code>A</code>, so I want to </p> <p>I want to check <code>B</code> to...
<p>I think* you're going to be able to do this with a <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#transformation" rel="nofollow noreferrer">groupby transform</a>:</p> <pre><code>df[label_name] = df.groupby("person_id").transform("max") </code></pre> <p>* It's a little hard to read pr...
python|pandas|dataframe
0
374,925
56,042,320
Split multiple content into multiple lines
<p>I have a column of data, it mostly has only one value, but some are multi-valued data connected with commas, and some missing values. I want to split multivalued data connected with commas into multiple lines.</p> <p>I found a good solution in this (<a href="https://stackoverflow.com/a/50731254/10446425">Split cell...
<p>Try adding <code>astype(str)</code>:</p> <pre><code>df_new = (df.set_index(['id']).astype(str) .stack() .str.split(',', expand=True) .stack() .unstack(-2) .reset_index(-1, drop=True) .reset_index() ) </code></pre>
python|pandas
0
374,926
56,063,831
how to decode colnames pandas dataframe with python?
<p>I imported a data frame in python with pandas. But I have column names with strange encoding.</p> <pre><code>colnames = ['Price \xe2\x82\xac', 'x-rate \xe2\x82\xac/$'] </code></pre> <p>Can you help me to decode these column names?</p>
<p>Try the following:</p> <pre><code>colnames = [i.encode('raw_unicode_escape').decode('utf-8') for i in colnames] </code></pre> <p>Yields:</p> <pre><code>['Price €', 'x-rate €/$'] </code></pre> <p>Per @piRSquared's comment, you can do this with <code>pandas</code> using:</p> <pre><code>df.rename(columns=lambda x:...
python|pandas|dataframe
5
374,927
56,076,878
How to access data of previous rows in pandas dataframe?
<p>I am trying to access the previous (or further back) row to use as a value in a new column. Have tried several approaches with enumerate, iterrows and iloc but end up with the same problem, they use the last value. The following code is used:</p> <pre><code>df = pd.DataFrame({'values':(50.033,50.025,49.979,49.954,4...
<p>Do not use <code>apply</code>, but instead use vectorized <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a>, which is faster and more readable:</p> <pre><code>df['b'] = np.where(df['a'].abs().between(0, 0.009, inclusive=True), df['val...
python|pandas|dataframe
0
374,928
56,410,498
sort_value working on Name column but not Number column in dataframe
<p>When try to sort my dataframe by the column "Number" i get the error code</p> <blockquote> <p>1708 # Check for duplicates</p> <p>KeyError: 'Number'</p> </blockquote> <p>the dataframe looks something like this</p> <pre><code>Number Name City Sex 3 Jay A M 1 Marry A F 5 John B M </code></pre> <p>...
<p>I try to make a DataFrame like yours and sort it &amp; it works to sort by <code>Number</code> column:</p> <pre><code>df=pd.DataFrame({'Number':[3,1,5], 'Name':['Jay','Marry','John'], 'City':['A','A','B'], 'Sex':['M','F','M']}) print(df) print(df.Number.dtype) df=df.s...
python|pandas|columnsorting
1
374,929
56,105,450
Python Pandas - find all unique combinations of rows of a DataFrame without repeating values in the columns
<p>I have a dataframe that looks similar to this</p> <pre><code>df = pd.DataFrame({'A': {0: 1, 1: 1, 2: 1, 3: 10, 4: 10, 5: 10, 6: 13, 7: 13, 8: 13}, 'B': {0: 17, 1: 20, 2: 25, 3: 17, 4: 20, 5: 25, 6: 17, 7: 20, 8: 25}, 'distance': {0: 304.0, 1: 326.0, 2: 426.0, 3: 124.0, 4: 146.0, 5: 246.0, 6: 69.0, 7...
<p>I think you may need using <code>permutations</code> from <code>itertools</code>, then we just need look up the df after <code>pivot</code> </p> <pre><code>l=list(itertools.permutations([0,1,2])) s=df.pivot(*df.columns) list_of_df=[pd.DataFrame({'A':s.index, 'B':s.columns.values[list(x)], ...
python|pandas
3
374,930
56,108,214
ValueError: Input contains NaN, infinity or.....('float32')
<p>Trying to figure out why I keep getting the message listed as the headline of this question. I think I already cleaned data, removing NaN's. Can anyone help me out?</p> <p>Looking into a dataset with 11K lines, I am trying to make the code train data to predict level of students dropping out. Using an ordinary Wind...
<p>As said, your dataset <code>X_train</code> or <code>y</code> must contain <code>nan</code>s. Check again to see where that comes from. It typically comes from division by 0 or math functions domain error like log of negative values.</p> <p>Something else you're gonna run in after :</p> <p>You're using <code>test =...
python|sklearn-pandas
0
374,931
56,031,922
Save Multiple Dataframes on excel workbook then Upload to AWS S3 Bucket
<p>Good afternoon everyone, </p> <p>I am trying to save multiple dataframes to an excel workbook on different sheets. Then upload that workbook to an Amazon S3 bucket. the code below works 99% of the way but the writer.save() cannot find my excel file on my S3 Bucket. Please assist if you know a way around this. thank...
<p>s3 is not a standard file system that you can read and write with frameworks (such as Pandas) that are not aware of the data location different interface.</p> <p>The simplest way is to write it locally to the file system of the notebook instance and then run <code>aws s3 cp</code> to upload it to s3. </p>
python|excel|pandas|amazon-s3|amazon-sagemaker
0
374,932
56,260,111
Filling pandas dataframe with foreign key
<p>I have 3 tables: master, summary, controller.</p> <p>master contains the columns: asset_id(unique), controller_name</p> <p>controller contains the columns: controller_id which is a primary key generated based on unique controller_names</p> <p>summary contains the columns: asset_id(primary key) and controller_id(e...
<p>You can use pandas merge and select the columns of interest</p> <pre><code>summary = master.merge( controller, on='controller_name', how='left' )[['asset_id','controller_id']] </code></pre>
python|pandas|sqlalchemy
1
374,933
56,325,181
Pyinstaller executable fails importing torchvision
<p>This is my <strong>main.py</strong>:</p> <pre class="lang-py prettyprint-override"><code>import torchvision input("Press key") </code></pre> <p>It runs correctly in the command line: <code>python main.py</code></p> <p>I need an executable for windows. So I did : <code>pyinstaller main.py</code></p> <p>But when I...
<p>Downgrade <strong>torchvision</strong> to the previous version fix the error.</p> <pre><code>pip uninstall torchvision pip install torchvision==0.2.2.post3 </code></pre>
python|pytorch|pyinstaller|torchvision
3
374,934
56,040,964
How to compare 2 dataframes and generate new dataframe
<p>I have 2 similar dataframes that I would like to compare each row of the 1st dataframe with the 2nd based on condition. The dataframe looks like this:</p> <p><a href="https://i.stack.imgur.com/c3otw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c3otw.png" alt="Dataframe"></a></p> <p>Based on t...
<p>Here is an easy workaround. </p> <pre><code># Import pandas library import pandas as pd # One dataframe data = [['foo', 10], ['bar', 15], ['foobar', 14]] df = pd.DataFrame(data, columns = ['Name', 'Age']) # Another similar dataframe but foo age is 13 this time data = [['foo', 13], ['bar', 15], ['foobar', 14]...
python|pandas|loops
0
374,935
56,366,831
How to do index and match like in Pandas
<p>I am trying to use index and match like function in Pandas. I am new to this. What I would like to do is</p> <ol> <li><p>index string or multiple strings and change the corresponding price</p></li> <li><p>index the string without regardless of uppercase and lowercase letters (a lot of the names of the fruits are in...
<p>you can convert to lower case</p> <pre><code>&gt;&gt;&gt; d_f.loc[d_f['Fruits'].str.lower().str.contains('apple'), 'Price'] = 275 &gt;&gt;&gt; d_f Fruits Price 0 apple from us 275 1 Apple from US 275 2 Mango from Canada 15 3 Orange from Mexico 16 4 Orange from C...
python|pandas
0
374,936
56,178,766
Extract numbers from "dd.dd AAA dd.dd BBB" or "AAA dd.dd BBB dd.dd"
<p>I am trying to extract two values from arbitrary text, formatted in variable ways. The two values are different, and I want to distinguish them based on a nearby sring, lets say "DDT" and "EEG". Here are some examples of how the strings can be formatted.</p> <pre><code>This contains 42.121% DDT and 2.1% EEG Now wi...
<p>You could try the following, at least for these cases:</p> <p>1/ work out which is first EEG or DDT:</p> <pre><code>In [11]: s.str.extract("(DDT|EEG)") Out[11]: 0 0 DDT 1 DDT 2 DDT 3 EEG 4 EEG </code></pre> <p>2/ pull out all the numbers:</p> <pre><code>In [12]: s.str.extract("(\d+\.?\d*|N/A).*?(\d+\.?...
python|regex|pandas|regex-negation|regex-lookarounds
0
374,937
56,087,907
Is there a way to use map function or for loop for melting? I need to melt 5 dataframes with same line of code
<p>I have 6 dataframes with me called <code>open_price</code>, <code>closed_price</code>, <code>volume</code>, <code>adj_open_price</code>, <code>high_price</code> and <code>low_price</code></p> <p>And each dataframe has values like this</p> <p><a href="https://i.stack.imgur.com/G5wmX.png" rel="nofollow noreferrer">T...
<p>Try like this:</p> <p>Put dataframes in a list then apply pd.melt with map.</p> <pre><code>dfs = [df1, df2] result=list(map(lambda df:pd.melt(...), dfs)) df_1, df_2 = result </code></pre> <p>So in your case this would be:</p> <pre><code>dataframess = [open_price, low_price] openn=pd.melt(df, value_vars=['GOO...
python|pandas
0
374,938
56,099,141
Numpy broadcasting - using a variable value
<p><strong>EDIT:</strong></p> <p>As my question was badly formulated, I decided to rewrite it.</p> <p>Does numpy allow to create an array with a function, without using Python's standard list comprehension ?</p> <p>With list comprehension I could have:</p> <pre><code>array = np.array([f(i) for i in range(100)]) </c...
<p>You can add two arrays together like this:</p> <p><a href="https://stackoverflow.com/questions/40955903/simple-adding-two-arrays-using-numpy-in-python">Simple adding two arrays using numpy in python?</a></p> <p>This assumes your "variable by index" is just another array. </p>
python|numpy|vectorization
0
374,939
56,274,699
One-line piece of script to read a single row in a file as numpy.array
<p>Simple question, I have a file with N entries and M values. I need a one-line piece of script to read the first or any single row of the file as numpy.array.</p>
<pre><code>A=np.loadtxt('file_name',skiprows = N,max_rows =1) #for rows B=np.loadtxt('file_name',usecols=M) #for colomns </code></pre>
python|python-2.7|numpy|readfile
1
374,940
56,433,990
rounding big floating point numbers
<p>I'm implementing Jacobian algorithm to find eigenvalue of a given matrix.My problem is with float numbers like 1.2335604410291751e+216.I can not round them.</p> <p>I tried np.around and round functions but they didnt work.</p>
<p>If what you want is to only round <em>m</em> of a number in standard form (m × bⁿ) you can do it like this, for m, b, and n the number, the base, and the exponent, respectively:</p> <pre><code>import math def round_(m, d, b = 10): n = math.floor(math.log(abs(m), b),) return float(round(m * (b ** (d - n)))...
python|numpy|rounding
0
374,941
56,331,296
How do I make Tkinter drawing lines from an x interval and a y NumPy array?
<p>I have two sources of data to be plotted as X and Y coordinates on a continuous Tkinter line. The x data is generated from a constant like say 1.3. So each x value has to be + 1.3 greater than the last - for example 3.9, 5.2, 6.5 and so on. The y values are held in a numpy array. I need to create a line on a canvas ...
<p>You can simply call <code>Canvas.create_line(...)</code> with the array of points created from your two sources of data as below:</p> <pre><code>from tkinter import * import numpy.random root = Tk() canvas = Canvas(root, bg='white', width=1600, height=800) canvas.pack(fill=BOTH, expand=1) y_array = numpy.random....
python|arrays|numpy|tkinter|line
0
374,942
56,292,555
Delete rows preceeding and following a row containing NaN in Python?
<p>I am trying to clean experimental data using python with numpy and pandas. Some of my measurements are implausible. I want to remove these measurements and the 2 preceeding and 2 following measurements from the same sample. I am trying to find an elegant way to achieve this without using a for loop as my dataframes ...
<p>We can make mark all indices which are two places before or after the <code>NaN</code>, then replace their values with <code>NaN</code> as well:</p> <pre><code># Get indices of NaN's idxnull = df[df['Measurement'].isnull()].index a = [range(x+2) if x==0 else range(x-2, x) if x==idxnull.max() else range(x-2, x+2) f...
python|pandas|numpy|dataframe
3
374,943
56,215,105
Wrong when I use tensorflow and keras together?
<h1>This is the code where I mix tensorflow with keras.</h1> <pre><code>def dense_block(x, nb_layers, nb_filter, growth_rate, bottleneck=False, dropout_rate=None, weight_decay=1e-4, grow_nb_filters=True, return_concat_list=False): ''' Build a dense_block where the output of each conv_block is fed...
<p>you cannot usually mix separate keras install with tensorflow use the one provided within tensoflow,<p> try replacing keras as follows <code>from tensorflow import keras as K</code> </p> <a href="https://www.tensorflow.org/api_docs/python/tf/keras" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/pytho...
tensorflow|keras
0
374,944
56,332,802
Autoeconders Keras with Variable Inputs
<p>I have a keras code implementing an autoencoder like that:</p> <pre><code>ENCODING_DIM = 5 # input placeholder input_img = tf.keras.layers.Input(shape=(320,)) # this is the encoded representation of the input encoded = tf.keras.layers.Dense(35, activation='relu')(input_img) encoded = tf.keras.layers.Dense(20, act...
<p>Dense layer will create, in your case, 35 neurons where each will be connected to each input feature (out of 320). It will initialize the matrix of weight of size 35x320, for example. There is no way to initialize such a matrix when input size is not known, at least when it comes to dense layers. You will have to pa...
python|tensorflow|keras|autoencoder
0
374,945
56,218,003
Pandas dataframe : Operation per batch of rows
<p>I have a pandas DataFrame <code>df</code> for which I want to compute some statistics per batch of rows. </p> <p>For example, let's say that I have a <code>batch_size = 200000</code>. </p> <p>For each batch of <code>batch_size</code> rows I would like to have the number of unique values for a column <code>ID</code...
<p>See <a href="https://stackoverflow.com/questions/33367142/split-dataframe-into-relatively-even-chunks-according-to-length/33368088">this post</a> for the splitting process, then you could do this to get number of unique 'ID'</p> <pre><code>df = pd.DataFrame({'ID' : [1, 1, 2, 2, 2, 3, 3, 3, 3]}) batch_size = 3 resul...
python|pandas|performance|batch-processing
5
374,946
56,414,847
Concatenating Pandas DataFrames Doubling Rows
<p>I am trying to concat() two DataFrames in pandas. One of the dataframes are just some columns I have taken from the other dataframe and transformed, so at no point do I resort them. But when I try to concatenate them I get an error saying they can't be concatenated together and so they are concatenated almost diagon...
<p>may be there is a different index label, try using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer">reset_index()</a> in each dataframe before concatenating:</p> <p>Example i have this 2 dataframes with different index name and try to <...
python-3.x|pandas|dataframe|scikit-learn
1
374,947
56,082,364
Finding a specific value in csv files Python
<p>I have a column of values, which are part of a dataframe df. </p> <pre><code>Value 6.868061881 6.5903628020000005 6.472865833999999 6.427754219 6.40081742 6.336348032 6.277545389 6.250755132 </code></pre> <p>These values have been put together from several CSV files. Now I'm trying to backtrack and find the origi...
<p>Assuming <code>dirs</code> is a list of file paths to CSV files:</p> <pre><code>csv_dfs = {file: pd.read_csv(file) for file in dirs} csv_df = pd.concat(csv_dfs) </code></pre> <p>If you're just looking in the <code>'Values'</code> column, this is pretty straightforward:</p> <pre><code>print csv_df[csv_df['Values']...
python|pandas|csv
3
374,948
56,263,418
Iterating over columns and comparing each row value of that column to another column's value in Pandas
<p>I am trying to iterate through a range of 3 columns (named 0 ,1, 2). in each iteration of that column I want to compare each row-wise value to another column called Flag (row-wise comparison for equality) in the same frame. I then want to return the matching field.</p> <p>I want to check if the values match.</p> <...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> in combination with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>eq</code></a> than...
python-3.x|pandas|for-loop|while-loop|multiple-columns
3
374,949
56,112,796
Split a list with different number of elements into separate columns in a dataframe
<p>I am extracting results from SQL Queries into my Pandas data frame. The results are either 'Min and Max' or Min, Max, and Average'. </p> <p><a href="https://i.stack.imgur.com/4qqPO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4qqPO.png" alt="Min Max Data frame"></a></p> <p>I want to split the...
<p>In your DF above, I've changed the dates to strings in a list. A vectorized solution is provided by tolist(). </p> <pre><code>pd.concat([df['SQL_Query'],pd.DataFrame(df.Results.values.tolist(), columns=['Min', 'Max', 'Avg'])], axis=1) SQL_Query Min Max Avg 0 ...
pandas|list
0
374,950
56,256,480
How do I avoid my piece of python code from aggressively rounding off values to 1 decimal place
<p>I am trying to create a new column in my pandas dataframe that is the result of a basic mathematical equation performed on other columns in the dataset. The problem now is that the values captured in the column are extremely rounded up and does not represent the true values.</p> <p>2.5364 should not be rounded off ...
<p>You have not defined the first_part variable in your code, so I am going to assume it is some subset of dataframe columns, e.g:</p> <pre><code>first_part=['course1', 'course2', 'course3'] </code></pre> <p>All of the numbers in your dataframe are integer multiples of 3, therefore when you sum up any of them and div...
python|pandas|dataframe
1
374,951
56,160,379
How to use np.where in another np.where (conext: ray tracing)
<p>The question is: how to use two np.where in the same statement, like this (oversimplified):</p> <pre><code>np.where((ndarr1==ndarr2),np.where((ndarr1+ndarr2==ndarr3),True,False),False) </code></pre> <p>To avoid computing second conditional statement if the first is not reached.</p> <p>My first objective is to fin...
<p>Here's how I used masked arrays to answer this problem:</p> <pre><code> loTrue= np.where((s1!=s2),False,True) s3=ma.masked_array(np.sign(dot(np.cross(r0r1, r0t0), r0t1)),mask=loTrue) s4=ma.masked_array(np.sign(dot(np.cross(r0r1, r0t1), r0t2)),mask=loTrue) s5=ma.masked_array(np.sign(dot(np.cross(r0r1,...
python-3.x|numpy|optimization|geometry
0
374,952
56,123,378
Finding the logits with respect to labels Tensorflow Python
<p>I have the label array and logits array as: </p> <pre><code>label = [1,1,0,1,-1,-1,1,0,-1,0,-1,-1,0,0,0,1,1,1,-1,1] logits = [0.2,0.3,0.4,0.1,-1.4,-2,0.4,0.5,-0.231,1.9,1.4,-1.456,0.12,-0.45,0.5,0.3,0.4,0.2,1.2,12] </code></pre> <p>Using Tensorflow, I want to get the values from label and logits where: </p> <bl...
<p>You can use <code>tf.boolean_mask</code>.</p> <pre><code>import tensorflow as tf label = tf.constant([1,1,0,1,-1,-1,1,0,-1,0,-1,-1,0,0,0,1,1,1,-1,1],dtype=tf.float32) logits = tf.constant([0.2,0.3,0.4,0.1,-1.4,-2,0.4,0.5,-0.231,1.9,1.4,-1.456,0.12,-0.45,0.5,0.3,0.4,0.2,1.2,12],dtype=tf.float32) # label&gt;0 label...
python|tensorflow
1
374,953
56,296,355
Perform one-hot encoding on pandas dataframe on multiple column types
<p>So I have a pandas dataframe where certain columns have values of type list and a mix of columns of non-numeric and numeric data.</p> <p>Example data</p> <pre><code> dst_address dst_enforcement fwd_count ... 1 1.2.3.4 [Any,core] 8 2 3.4.5.6 [] 9 3 6.7.8.9 [Any] ...
<p>I use 3 steps as follows:</p> <pre><code>df['dst_enforcement'] = df.dst_enforcement.apply(lambda x: x if x else ['empty']) dm1 = pd.get_dummies(df[df.columns.difference(['dst_enforcement'])], prefix='', prefix_sep='') dm2 = df.dst_enforcement.str.join('-').str.get_dummies('-') pd.concat([dm1, dm2], axis=1) Out[122...
python|pandas|one-hot-encoding|data-processing
2
374,954
56,370,060
How to extract a value from a Pandas data frame from a reference in the frame, then "walk up" the frame to another specified value?
<p>I have the following toy data set:</p> <pre><code>import pandas as pd from StringIO import StringIO # read the data df = pd.read_csv(StringIO(""" Date Return 1/28/2009 -0.825148 1/29/2009 -0.859997 1/30/2009 0.000000 2/2/2009 -0.909546 2/3/2009 0.000000 2/4/2009 -...
<p>Filter your dataframe for all rows less than the minimum value in Return and also Return equals zero, than show the last value. </p> <pre><code>df.loc[(df.index &lt; df.Return.idxmin()) &amp; (df['Return'] == 0), "Date"].tail(1) </code></pre>
python|pandas
2
374,955
56,063,686
Considerations of model definitions when moving from Tensorflow to PyTorch
<p>I've just recently switched to PyTorch after getting frustrated in debugging tf and understand that it is equivalent to coding in numpy almost completely. My question is what are the permitted python aspects we can use in a PyTorch model (to be put completely on GPU) eg. if-else has to be implemented as follows in t...
<p>In pytorch, the code can be written like the way normal python code is written.</p> <p><strong>CPU</strong></p> <pre><code>import torch a = torch.FloatTensor([1,2,3,4,5]) b = torch.FloatTensor([6,7,8,9,10]) cond = torch.randn(5) for ci in cond: if ci &gt; 0: print(torch.add(a, 1)) else: pr...
python|tensorflow|pytorch
1
374,956
55,881,160
Confused by pandas dtype conversion to np.float16 value 2053 becomes 2052
<p>I was trying to reduce memory consumption by downcasting float data types.</p> <p>I checked the range of <code>np.float16</code>:</p> <pre><code>np.finfo(np.float16) finfo(resolution=0.001, min=-6.55040e+04, max=6.55040e+04, dtype=float16) </code></pre> <p>This shows <code>-6.55040e+04 &lt; 2053 &lt; 6.55040e+04<...
<p>It's not about <code>min</code> or <code>max</code>, which determine the lowest and highest values a <code>float16</code> can take respectively, but <code>resolution</code>, or the least difference between two values before they are considered identical.</p> <p><code>finfo</code> shows that the resolution of <code>...
python|pandas|numpy
3
374,957
55,582,218
Change the value of an item given a flag
<p>I have a data frame which holds bets placed on horses, with each row being a new bet. Each bet has multiple attributes including location, the name of the horse, winnings/losses etc. The problem is those bet winnings are given in a positive integer and a flag attribute is provided to say whether it is a win or a los...
<p>Use <code>groupby</code>, <code>sum</code>, and then unstack the result:</p> <pre><code>df.groupby(['Year', 'Won/Lost'])['Amount'].sum().unstack(-1).add_prefix('total_') Won/Lost total_lost total_won Year 2016 115.0 584.81 2017 5.0 69.31 </code></pre>
python|pandas|dataframe
4
374,958
55,881,784
Keras: custom loss causes "You must feed a value for placeholder tensor"
<p>I'm trying to build a variational autoencoder in Keras following the <a href="https://github.com/keras-team/keras/blob/master/examples/variational_autoencoder.py" rel="nofollow noreferrer">example</a> in the Keras repository. Here's my setup:</p> <pre><code>from keras.layers import Dense, Input, merge, concatenate,...
<p>Ah, I got this worked out once my variables were scoped properly:</p> <pre><code>from keras.layers import Dense, Input, merge, concatenate, Dense, LSTM, Lambda, Flatten, Reshape from keras import backend as K from keras.models import Model from keras.losses import mse import numpy as np class VAE: def __init__(...
python|tensorflow|keras
1
374,959
55,609,810
How to add new row which copy's some columns, but assigns new values in other columns
<p>I have a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({'VisitorID': [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000], 'EpochTime': [1554888560, 1554888560, 1554888560, 1554888560, 1554888560, 1521333510, 1521333510, 1521333510], 'HitTime': [1400, 5340, 7034,...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>DataFrame.drop_duplicates</code></a> for improve performance a bit:</p> <pre><code>d = {'HitTime':0,'HitNumber':0,'PagePath':'Home'} df_first = df.drop_duplicates(['V...
python|pandas|group-by
2
374,960
55,916,235
What's the difference between multi-(single outputs) NN vs single-(multi targets) NN?
<p>I'm working on this following autoregressive problem with Keras/TF :</p> <p>Inputs : </p> <p><strong><em>m</strong> examples x <strong>10</strong> timesteps (sequence length) x <strong>7</strong> features</em></p> <p>(With each value being a real value)</p> <p>Outputs : </p> <p><strong><em>m</strong> examples x...
<p>It does not make a difference most of the time. If your output layers are dense ones, each of them will have a n*1 weight matrix. If you have a single output layer the weight has the shape n*4 instead. Generally one big output layer is faster, as one big matrix multiplication often faster than multiple small ones.</...
python|tensorflow|machine-learning|keras|deep-learning
0
374,961
55,943,967
check if a columns contains any str from list
<p>I try to use any() to check if the column contains any string from the list and make a new column with the corresponding results</p> <pre><code>df_data = pd.DataFrame({'A':[2,1,3], 'animals': ['cat, frog', 'kitten, fish', 'frog2, fish']}) cats = ['kitten', 'cat'] df_data['cats'] = df_data.apply(lambda row: True if ...
<p>With pandas you should try your best not using for loop or apply , I am using <code>DataFrame</code> constructor with <code>isin</code> and <code>any</code> </p> <pre><code>df_data['cats']=pd.DataFrame(df_data.animals.str.split(', ').tolist()).isin(cats).any(1) df_data A animals cats 0 2 cat, frog ...
python|pandas|dataframe
1
374,962
55,740,358
How to train model using TFSlim library?
<p>I'm reading Object Detection API source code and I wonder how to use TFSlim to train model?</p> <p>More specifically, when we use Tensorflow to train the model, we use something like this:</p> <pre><code>parameters = model(X_train, Y_train, X_test, Y_test) # Returns: parameters -- parameters learnt by the model. ...
<p>The <code>train</code> function does not return a value because it modifies the actual parameters of the model. The function does that by running the <code>train_tensor</code> which is: "A <code>Tensor</code> that, when executed, will apply the gradients and return the loss value." as written in the <a href="https:/...
python|tensorflow|machine-learning|deep-learning|computer-vision
0
374,963
55,726,480
ValueError: cannot reindex from a duplicate axis when making DataFrame from dictionary
<p>I have a dictionary with a similar format as the dictionary below:</p> <pre><code>{'ID': Unnamed: 0 2019-04-17 06:54:24 {'a': 6.75, 'b': 7.4} 2019-04-17 07:04:24 {'a': 6.75, 'b': 7.4} 2019-04-17 07:13:24 {'a': 6.75, 'b': 7.4} dtype: object, 'ID2': Unnamed: 0 2019-04-17 06:54:44 {'a': 6.35, 'b': 7.0...
<p>Use dictionary comprehension with <code>DataFrame</code> constructor and <code>concat</code>:</p> <pre><code>df = pd.concat({k: pd.DataFrame(v.squeeze().values.tolist(), index=v.index) for k, v in d.items()}) print (df) a b ID 2019-04-17 06:54:24 6.75 7.40 201...
python|pandas
0
374,964
55,737,227
Report a column values corresponding to 1st non-zero and last zero values from another column
<p>I have a dataframe as shown below. I would like to scan through 'Krg' column and find the row that corresponds to the last zero value in this column and to report 'Sg' from this row (0.03). Additionally, I would like to report 'Sg' corresponding to 1st non-zero value of 'Krg' (0.04).</p> <p>I could achieve that usi...
<p>We can simplify this by using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Series.eq</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ne.html" rel="nofollow noreferrer"><code>Series.ne</code>...
python|pandas|dataframe
0
374,965
55,656,114
Pandas cumprod with reset indicated by second column
<p>I need to calculate cumulative products that reset with some frequency indicated by a new value in a column <code>Wgt</code>.</p> <p>For example, in the DataFrame produced by:</p> <pre><code>df = pd.DataFrame(np.random.lognormal(0, 0.01, 27), pd.date_range('2019-01-06', '2019-02-01'), columns=['Chg']) df['Wgt'] = ...
<p>Using <code>np.where</code> with <code>cumprod</code></p> <pre><code>s=df.loc[df.Wgt.isnull(),'Chg'].groupby(df.Wgt.notna().cumsum()).cumprod() np.where(df.Wgt.notna(),df.Wgt,s*df.Wgt.ffill()) Out[531]: array([0.861546 , 0.87790934, 0.89323852, 0.89662211, 0.90926986, 0.90541273, 0.89550571, 0.602225 , 0....
python|pandas|dataframe
2
374,966
55,639,151
Mixing datasets in set ratio
<p>In tensorlfow dataset, how do I mix 2 datasets, taking 75% of the set from my original data and 25% from the augmented data?</p> <pre><code>d = tf.data.Dataset.list_files("raw_data/")\ .flat_map(tf.data.TFRecordDataset) ad = tf.data.Dataset.list_files("augmented_data/")\ .flat_map(tf.data.TFRecordDataset) <...
<p>The problem is you can't use <code>len()</code> on a dataset object, so it's sometimes hard to know exact number of examples until you iterate a full epoch. But you can approximate this with <code>take</code> and <code>skip</code> methods.</p> <pre><code>train_dataset = dataset.take(number_examples_for_train) test_...
tensorflow|tensorflow-datasets|tensorflow-estimator
1
374,967
55,752,970
How datasets are structured in TensorFlow?
<p>In my first TensorFlow project, I have a big dataset (1M elements) which contains 8 categories of elements, with each category, has a different number of elements of course. I want to split the big dataset into 10 exclusive small datasets, with each of them having approximately 1/10 of each category. (This is for 10...
<p>Split your <strong>whole datasets</strong> into Training, Testing and Validation categories. As you have 1M data, you can split like this: 60% training, 20% testing and 20% validation. Splitting of datasets is completely up to you and your requirements. But normally maximum data is used for training the model. Next,...
tensorflow|dataset
0
374,968
55,588,122
How to calculate the relative vectors from a list of points, from one point to every other point
<p>I have a list of points in <code>(x,y)</code> pairs, which represents the positions of a list of agents. For example, given 3 agents, there are 3 pairs of points, which I store as follows:</p> <pre><code>points = np.array([[x1, y1], [x2, y2], [x3, y3]]) </code></pre> <p>I woul...
<p><strong>Approach #1</strong></p> <p>With <code>a</code> the input array, you can do -</p> <pre><code>d = (a-a[:,None,:]) valid_mask = ~np.eye(len(a),dtype=bool) out = d[valid_mask] </code></pre> <p>Basically, we are extending <code>a</code> to <code>3D</code> such that first axis is made <code>outer-broadcastable</c...
python|arrays|numpy
2
374,969
55,938,112
Describe a Dataframe on PySpark
<p>I have a fairly large Parquet file which I am loading using</p> <pre><code>file = spark.read.parquet('hdfs/directory/test.parquet') </code></pre> <p>Now I want to get some statistics (similar to pandas <code>describe()</code> function). What I've tried to do was:</p> <pre><code>file_pd = file.toPandas() file_pd.d...
<p>What are the stats you need? Spark has a similar feature</p> <pre><code>file.summary().show() </code></pre> <pre><code>+-------+----+ |summary|test| +-------+----+ | count| 3| | mean| 2.0| | stddev| 1.0| | min| 1| | 25%| 1| | 50%| 2| | 75%| 3| | max| 3| +-------+----+ </code></pre>
python|pandas|apache-spark|pyspark
17
374,970
55,863,619
How to convert tensorflow placerholder variable to numpy array?
<p>I would like to use scipy interpolation function in the tensorflow code.</p> <p>Here is the example snippet similar to my situation.</p> <pre><code>import tensorflow as tf from scipy import interpolate def interpolate1D(Xval,Fval,inp): Xval = np.array(Xval) Fval = np.array(Fval) f = interpolate.inter...
<p>You could use <a href="https://www.tensorflow.org/api_docs/python/tf/py_func" rel="nofollow noreferrer"><code>tf.py_func</code></a> to use the SciPy function inside your graph, but a better option would be to implement the interpolation in TensorFlow. There is no function in the library that does this out of the box...
python|numpy|tensorflow
2
374,971
55,590,814
Cuda compute capability 3.0. The minimum required Cuda capability is 3.7
<p>I have python 3.5, gpu: Quadro K1000M, CUDA 9.0 and I want toinstall tensorflow on gpu. The installation was done successfully, but when I check it, it gives me the warning and my python code works with CPU version in spite of I didn't install CPU version. The warning is:</p> <pre><code> Cuda compute capability...
<blockquote> <p>Cuda compute capability 3.0. The minimum required Cuda capability is 3.7</p> </blockquote> <p>Your GPU is too old, the bare minimum according to the <a href="https://en.wikipedia.org/wiki/CUDA" rel="nofollow noreferrer">list of GPU models on Wikipedia's CUDA page</a> is a Tesla K80. If you want touse...
python|tensorflow|gpu
1
374,972
55,984,986
Python: Evaluate Arithmetic String Within Pandas Dataframe Column
<p>To preface this, I'm a python newbie. I'm working on a script to automate a reporting process for website downtime each month. I've successfully built a script that scrapes our monitoring site with Beautifulsoup and pulls the data into a pandas dataframe. The "Duration" column of the dataframe lists downtime and ...
<p>(Updated answer to reflect new information.)</p> <pre><code># Sample data: ddict = { 'Record': [1, 2, 3, 4], 'Duration': ['1 Hour 5 Minutes', '2 Hours 1 Minute', '2 Hours 45 Minutes', '7 Minutes'] } df = pd.DataFrame(ddict) ### Replace plurals in 'Du...
python|pandas|dataframe
0
374,973
55,754,477
Nearest neighbor matching in Pandas
<p>Given two DataFrames (t1, t2), both with a column 'x', how would I append a column to t1 with the ID of t2 whose 'x' value is the nearest to the 'x' value in t1?</p> <pre><code>t1: id x 1 1.49 2 2.35 t2: id x 3 2.36 4 1.5 output: id id2 1 4 2 3 </code></pre> <p>I can do this by creating a new Data...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html#pandas.merge_asof" rel="nofollow noreferrer"><code>merge_asof</code></a></p> <pre><code>df = pd.merge_asof(df1.sort_values('x'), df2.sort_values('x'), on='x', di...
python|pandas
5
374,974
55,674,799
"No such table" error while loading the .db file in python
<p>I'm trying to read the .db file in python code, whereas i getting "no table found an" error. But i could see the table when I import it onto MYSQL DB.</p> <pre><code>import sqlite3; import pandas as pd; con=None def getConnection(): databaseFile="test.db" global con if con == None: con=sqlite3...
<p>Assume you're trying to read data from <strong>SQLite</strong> database file, here is a simpler way to do it.</p> <pre><code>import sqlite3 import pandas as pd con = sqlite3.connect("test.db") with con: df = pd.read_sql("select * from Movie", con) print(df) </code></pre>
python-3.x|pandas|sqlite
0
374,975
55,903,895
Pick random entry from two ragged tensors
<p>How do I pick random entries from two ragged tensors? For example,</p> <pre><code>c = tf.ragged.constant([[1, 2, 3], [4, 5]]) v = tf.ragged.constant([[10., 20., 30.], [40., 50.]]) r = tf.random.uniform([1, 1], maxval=2, dtype=tf.int32) with tf.Session() as sess: print(sess.run([tf.gather_nd(c, r), tf.gather_n...
<p>Here is an example based on the values you've given: (I am using TF 1.13)</p> <pre><code>import tensorflow as tf tf.enable_eager_execution() # you can use a normal Session, but this is to show intermediate output c = tf.ragged.constant([[1, 2, 3], [4, 5]]) v = tf.ragged.constant([[10., 20., 30.], [40., 50.]]) r =...
python|tensorflow|ragged
1
374,976
55,720,396
How to use mutiple arithmetic functions in multiple columns in pandas dataframe
<p>I have a pandas dataframe and three lists as follows.</p> <pre><code>list1 = ['n3', 'n5', 'n7'] list2 = ['n1', 'n2', 'n4', 'n11', 'n12'] list3 = ['n6', 'n8', 'n9', 'n10'] item n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 item1 1 6 7 8 9 1 6 8 8 9 9 5 item2 1 6 7 6 9 1 8 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.abs.html" rel="nofollow noreferrer"><code>DataFrame.abs</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rdiv.html" rel="nofollow noreferrer"><code>DataFrame.rdiv</code></a> for d...
pandas
3
374,977
55,972,789
Difference between two dataframe and drop those that's not present in both
<p>State column exists in both of my dataframes, and I'm trying to drop the state that doesn't appear in both.</p> <p>I've tried:</p> <pre><code>for s in df1_2016.state if s not in df_2016.state: print(s) </code></pre> <p>Doesn't work.</p> <p>I planned to drop it by</p> <pre><code>df1_2016.state.drop('Alabama') ...
<p>Assuming a couple of dataframes like so:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({ 'state' : ['A','B','C','D'], 'values' : [1,2,3,4] }) df2 = pd.DataFrame({ 'state' : ['A','C','E','F'], 'values' : [5,6,7,8] }) df3 = df1[df1['state'].isin(df2['state'])] </code></pre> <p>df3 will contain the data in d...
python|pandas
0
374,978
55,935,692
How to make second maximum values as new column in pandas?
<p>I have the following dataframe. </p> <pre><code>import pandas as pd import numpy as np d = { 'ID':[1,2,3,4,5], 'Price1':[5,9,4,3,9], 'Price2':[9,10,13,14,18], 'Price3':[5,9,4,3,9], 'Price4':[9,10,13,14,18], 'Price5':[5,9,4,3,9], 'Price6':[np.nan,10,13,14,18], 'Price7':[np.nan,9,4,3,...
<p>one way to do this</p> <pre><code>df['Second_Max'] = df.drop(['ID','Type'], axis=1).fillna(0).apply(lambda x: (sorted(list(set(x)), reverse=True))[1], axis=1) </code></pre> <p>or</p> <pre><code>df['Second_Max'] = df.filter(like='Price').fillna(0).apply(lambda x: (sorted(list(set(x)), reverse=True))[1], axis=1) <...
pandas
3
374,979
55,672,269
How to access elements of Collections Counter stored as column in dataframe to be used in CountVectorizer
<p>One of the columns in the dataframe is in the following format</p> <pre><code>Row 1 : Counter({'First': 3, 'record': 2}) Row 2 : Counter({'Second': 2, 'record': 1}). </code></pre> <p>I want to create a new column which has the following value:</p> <pre><code>Row 1 : First First First record record Row 2 : Seco...
<p>I was able to solve the question myself by the following code. It is very much related to regex.</p> <pre><code>def transform_word_count(text): words = re.findall(r'\'(.+?)\'',text) n = re.findall(r"[0-9]",text) result = [] for i in range(len(words)): for j in range(int(n[i])): r...
python|pandas|collections
1
374,980
56,008,742
How can I read multiple csv files from a single directory and graph them separately in Python?
<p>I want to read csv files from a directory and plot them and be able to click the arrow button to step through a plot and look at a different plot. I want to specify which column and be able to title it as well as I have in the code below as well.</p> <p>I am able to read the csv file and plot a single plot with spe...
<p>You just need to add a <code>for</code> loop over all the files and use <code>glob</code> to collect them.</p> <p>For example,</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import glob cols_in = [1, 3] col_name = ['Time (s), Band (mb)'] # Select all CSV files on Desktop files = glob.glob("/...
python|pandas|csv|matplotlib|glob
1
374,981
56,000,679
Pandas CSV dataframes
<p>I have a dataframe like this :</p> <pre><code>+---+-------+------+-------+-------+ | id| prop1 | prop2| prop3|prop4 | +---+-------+------+-------+-------+ | 1| value1|value2| value3| null| | 2|value11| null|value13|value14| +---+-------+------+-------+-------+ I want to get this in python: +-------+--------...
<p>It seems you need unpivot of your dataframe so use melt for unpivot</p> <pre><code>pd.melt(df,id_vars=['id'],value_vars=['prop1', 'prop2','prop3','prop4']) </code></pre>
python|pandas|dataframe
0
374,982
55,665,599
Pandas - Merging two dataframes by index ID
<p>I have 2 Dataframes as below:</p> <p><strong>Dataframe1:</strong></p> <pre><code> 6 count store_1 10 store_2 23 store_3 53 </code></pre> <p><strong>Dataframe2:</strong></p> <pre><code>store_name location store_1 location_a store_2 location_b </code></pre> <p>I am trying to join the above tw...
<p>Left merge on indexes would work for you.</p> <pre><code>data = {'6': ['store1', 'store2', 'store3'], 'count': [10, 23, 53]} df1 = pd.DataFrame(data).set_index('6') df1 </code></pre> <p><a href="https://i.stack.imgur.com/ES7M6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ES7M6.png" alt="enter...
python|pandas
2
374,983
55,893,523
Bar plot from pivot table with grand total and percentage per group aggregation
<p>Here's the challenge: make a dataframe from the shipwreck.csv file. From this dataframe, build a pivot table that shows the average fares for males/females in each class, and the number of surviving males/females in each class. The row index should be the class values. Use margins to include averages for all males,...
<p>Here's what you can do:</p> <pre><code>df = pd.read_csv('shipwreck.csv', usecols=['survived', 'sex', 'class']) df_piv = pd.pivot_table(df, index='class', columns='sex', aggfunc=lambda x: 100*x.sum()/x.count(), # % per group ...
python|pandas|matplotlib
3
374,984
55,926,039
selecting different columns each row
<p>I have a dataframe which has 500K rows and 7 columns for days and include start and end day.</p> <p>I search a value(like equal 0) in range(startDay, endDay)</p> <p>Such as, for id_1, startDay=1, and endDay=7, so, I should seek a value D1 to D7 columns.</p> <p>For id_2, startDay=4, and endDay=7, so, I should seek...
<p>You can create boolean array to check in each row which 'Dx' column(s) are above 'startDay' and below 'endDay' and the value is equal to 0. For the first two conditions, you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html#numpy.ufunc.outer" rel="nofollow noreferrer"><code...
python-3.x|pandas|numpy
1
374,985
55,610,891
numpy.load from io.BytesIO stream
<p>I have numpy arrays saved in Azure Blob Storage, and I'm loading them to a stream like this:</p> <pre><code>stream = io.BytesIO() store.get_blob_to_stream(container, 'cat.npy', stream) </code></pre> <p>I know from <code>stream.getvalue()</code> that the stream contains the metadata to reconstruct the array. This i...
<p>I tried to use several ways to realize your needs.</p> <p>Here is my sample codes.</p> <pre><code>from azure.storage.blob.baseblobservice import BaseBlobService import numpy as np account_name = '&lt;your account name&gt;' account_key = '&lt;your account key&gt;' container_name = '&lt;your container name&gt;' blo...
python|numpy|azure-storage
4
374,986
55,625,121
Where are the filter image data in this TensorFlow example?
<p>I'm trying to consume this tutorial by Google to use TensorFlow Estimator to train and recognise images: <a href="https://www.tensorflow.org/tutorials/estimators/cnn" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/estimators/cnn</a></p> <p>The data I can see in the tutorial are: <strong>train_data, ...
<p>The filters are the weight matrices of the <code>Conv2d</code> layers used in the model, and are not pre-loaded images like the "butt curve" you gave in the example. If this were the case, we would need to provide the CNN with all possible types of shapes, curves, colours, and hope that any unseen data we feed the m...
tensorflow|machine-learning|artificial-intelligence|conv-neural-network|sample
1
374,987
55,705,910
reformatting a sequential data file into a data frame using pandas
<p>I have an input file, now converted to a <code>pandas.dataframe</code>. The records/rows are in a sequence which contain related data of the form</p> <pre><code> survey, a, b, c section, 1, 2, 3 observation, a, b, c values, 1, 2, 3 values, 4, 5, 6 observation, d, e, f values, 7, 8, 9 ...
<p>You could do it without using <code>Pandas</code> </p> <pre><code>s = '''survey, a, b, c section, 1, 2, 3 observation, a, b, c values, 1, 2, 3 values, 4, 5, 6 observation, d, e, f values, 7, 8, 9 section, 4, 5, 6''' list_s = s.strip().split('\n') list_s = [x.strip() for x in list...
python|pandas|sequential
0
374,988
55,947,360
How to provide encoding while reading multiple files?
<p>I'm reading multiple csv files in from a folder. While reading multiple files I receive <code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 21: invalid start byte</code> </p> <p>When I try to read file one-by-one I provide encoding of type - <code>"ISO-8859-1"</code> in <code>pandas.read_csv(...
<p>Try adding <code>errors='ignore'</code>, then everything works, but you will lose couple of characters.</p> <pre><code>with open(path, encoding="utf8", errors='ignore') as f: </code></pre>
python|pandas
0
374,989
64,958,746
Calculating {z,w} from {x,y} given 200 samples of f(x, y) = (z,w)
<p>What would be the best way to calculate <code>(z,w)</code> from a <code>(x,y)</code> given that we have 200 samples of <code>f(x,y) = (z,w)</code>?</p>
<p>You want a 2D interpolation function such as <a href="https://scipython.com/book/chapter-8-scipy/examples/scipyinterpolateinterp2d/" rel="nofollow noreferrer"><strong><code>scipy.interpolate.interp2d</code></strong></a></p> <p>Like in the linked example use <code>Z=f(x,y)</code> and set the interpolation type to <co...
numpy|math
1
374,990
64,627,602
Combining three similar Pandas datasets, keeping original values
<p>So I have three similar data sets given by the lines below:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df1 = pd.DataFrame({'Name': ['Michael', 'Samantha', 'Jimmy'], 'Gender': ['M', 'F', 'M'], 'Mon': [0,1,2], 'Tue': [0,3,5], 'Wed': [0,5,3]}) df2 = pd.DataFrame({'Name': ['Michael', 'Samant...
<p>Let us do <code>concat</code> then <code>groupby</code></p> <pre><code>df = pd.concat([df1,df2,df3]).set_index(['Name','Gender']).groupby(level=[0,1]).agg(list).reset_index() Out[20]: Name Gender Mon Tue Wed 0 Jimmy M [2, 4, 0] [5, 5, 5] [3, 5, 6] 1 Michael M [0, 1, 5...
python|pandas|dataframe
1
374,991
64,921,756
Merge a list containing numpy and numbers to one numpy array
<p>I have the following list I want to turn into one numpy. What is the best and most effective way to do this?</p> <pre><code>[[array([1, 2, 3]), 1], [array([1, 2, 3]), 2], [array([1, 2, 3]), 4], [array([4, 4, 4]), 3]] </code></pre> <p>Expected result:</p> <pre><code>[[1, 2, 3, 1], [1, 2, 3, 2], [1, 2, 3, 4], [4, 4...
<p>You can use this</p> <pre><code>test = [[np.array([1, 2, 3]), 1], [np.array([1, 2, 3]), 2], [np.array([1, 2, 3]), 4], [np.array([4, 4, 4]), 3]] np.apply_along_axis(lambda x:np.hstack((x[0],[x[1]])),axis=1,arr=test) </code></pre>
python|numpy
2
374,992
64,740,758
How to aggregate data based on two columns?
<p><a href="https://i.stack.imgur.com/5LzUw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5LzUw.png" alt="enter image description here" /></a></p> <p>i have table as shown above where there are two columns(Gender and year). i want to convert this into following format as shown below. any help on ho...
<p>You can do:</p> <pre><code>df = pd.DataFrame({'Gender': ['m', 'm', 'm', 'm', 'f'], 'year': [2011, 2013, 2011, 2011, 2012]}) pd.crosstab(df['year'], df['Gender']) Gender f m year 2011 0 3 2012 1 0 2013 0 1 </code></pre> <p>To reverse the gender column, it will be:</p> <pr...
python|pandas|data-science
2
374,993
64,986,643
Pivot output isn't as expected
<p>I have data which is already summed and grouped in a dataframe named <code>df</code>:</p> <pre><code>| id | segment | region | points | |----|---------|----------|--------| | 90 | Gold | APAC | 21 | | 90 | Silver | EMEA | 34 | | 90 | Bronze | AMERICAS | 564 | | 90 | Gold | EMEA | 393...
<p>Solution with double <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join</co...
python-3.x|pandas|pivot|pivot-table|transpose
1
374,994
64,981,900
Reassignment of weights in tensorflow 2/keras
<p>I'm currently testing some modified versions of dropout in Keras and one of them involves adjusting the weights during the training of a customized dense layer. I however have not been able to run it without error yet. I suspect is has something to do with eager execution but I'm not sure.</p> <pre><code>class Linea...
<p><code>self.w</code> has to be <code>tensorflow.Variable</code>. However after multiplication in <code>call()</code> it becomes <code>tensorflow.Tensor</code>. Just find another way to do the same thing in <code>call()</code> Try this code:</p> <pre><code> def call(self, inputs, training=False): prob = 0.0...
python|tensorflow|keras|neural-network|tensorflow2.0
1
374,995
64,911,096
How do I move a particular row up in a Pandas dataframe?
<p>Given the following dataframe:</p> <pre><code>df_test = pd.DataFrame( [['18-24', 334725], ['25-44', 698261], ['45-64', 273087], ['65+', 15035],['&lt;18', 80841]], columns=['age_group', 'total_arrests'] ) </code></pre> <p><a href="https://i.stack.imgur.com/XzP62.png" rel="nofollow noreferrer"><img src="https:...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.argsort.html" rel="nofollow noreferrer"><code>Series.argsort</code></a> with compare column for not equal for indices and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="no...
python|pandas|dataframe
1
374,996
64,830,512
weird behavior of numpy when it calculates a vector and matrix multiplication
<p>I have the following weird behavior of <code>numpy</code> where numpy can't multiply a <code>(n,n)</code> matrix with <code>(n,)</code> matrix and convert the later to <code>(1,n)</code> matrix. I tried different examples and it worked fine. <code>u</code> and <code>s</code> were obtained from <code>svd</code> funct...
<p>Look at what <code>svd</code> produces for a <code>matrix</code> versus <code>array</code>:</p> <pre><code>In [24]: np.linalg.svd(np.matrix(np.eye(3))) Out[24]: (matrix([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]), array([1., 1., 1.]), matrix([[1., 0., 0.], [0., 1., 0.], [0., 0....
python|numpy
1
374,997
65,023,572
Combining Pandas startswith and rstrip
<p>I'm trying to compare two strings, each containing an array of ints, to see if one is the start of the other. These are both columns in a pandas DataFrame. Here's the problem reduced to a simple example.</p> <p>Here's the data:</p> <pre class="lang-python prettyprint-override"><code>data = {'pred1': ['[0, 1, 2, 3]',...
<p>You should use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply</code></a> instead:</p> <pre><code>In [3793]: df.apply(lambda x: x['pred1'].startswith(x['pred2'].rstrip(']')), axis=1) Out[3793]: 0 True 1 False dtype: boo...
python|pandas
2
374,998
64,646,197
Watch-your-step model with StellarGraph is not working on a GPU
<p>I am trying to train a large graph-embedding using WatchYourStep algorithm using StellarGraph.</p> <p>For some reason, the model is only trained on a CPU a<strong>nd not utilizing the GPUs</strong>.<br /> using:</p> <ul> <li>TensorFlow-gpu 2.3.1</li> <li>having 2 GPUs , cuda 10.1</li> <li>running inside an nvidia-do...
<p>I just followed this instructions : <a href="https://github.com/stellargraph/stellargraph/issues/546" rel="nofollow noreferrer">https://github.com/stellargraph/stellargraph/issues/546</a>.</p> <p>It worked for me.</p> <p>Basically you have to edit the file setup.py from stellargraph github and remove the tensorflow ...
python|docker|tensorflow|gpu|stellargraph
0
374,999
64,775,560
Indexing list of tensors
<p>I have two identical lists of tensors (with different sizes) except that for the first one all of the tensors are assigned to the cuda device. For example:</p> <pre><code>list1=[torch.tensor([0,1,2]).cuda(),torch.tensor([3,4,5,6]).cuda(),torch.tensor([7,8]).cuda()] &gt;&gt;&gt; list1 [tensor([0, 1, 2], device='cuda:...
<p><code>np.array</code> trys to convert each of the elements of a list into a numpy array. This is only supported for CPU tensors. The short answer is you can explicitly instruct numpy to create an array with <code>dtype=object</code> to make the CPU case works. To understand what exactly is happening lets take a clos...
python|numpy|pytorch
1