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
15,100
59,440,800
converting 1 x 1 x 33 tensor to 1 x 1 x 34 while maintaining values and leaving the 34th index 0
<p>I have a tensor of 0 and and one 1 in a 1 by 1 by 33 tensor and I want all the indexes that are 1 to stay one, but be in a 1 by 1 by 34 tensor. What's the standard practice for this? Apparently using "reshape is bad" for this.</p>
<p>You can use <a href="https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.pad" rel="nofollow noreferrer"><code>pad</code></a> to pad either the beginning or end of a tensor with zeros.</p> <p>For example</p> <pre><code>import torch.nn.functional as F x = F.pad(x, (0, 1)) </code></pre> <p>will pa...
pytorch
1
15,101
59,096,992
Efficiency: Check if value in Pandas DataFrame has changed with an specific threshold outside an interval of measurement
<p>I have a column which a sensor recorded. <br> This Data has some noise on it, so the values are not exactly the same for each point of time while nothing was detected.<br> I want to split that recorded DataFrame into new DataFrames only containing the "interesting" Data (with values bigger than a certain threshold o...
<p>Here's a solution which is generalisable and tries to catch edge cases:</p> <pre><code># all rows where B &gt; 5 mask1 = df['B'].gt(5) # all rows where Bt-1 &gt; 5 &amp; Bt+1 &gt; 5 mask2 = df['B'].shift().gt(5) &amp; df['B'].shift(-1).gt(5) # all rows where mask1 OR mask2 is True mask3 = (mask1 | mask2) # turn ...
python|pandas|dataframe
1
15,102
59,308,829
Assign a label to each element of an array in Python
<p>Hi So basically I got 2 arrays. For the sake of simplicity the following:</p> <pre><code>array_notepad = [] array_images = [] </code></pre> <p>Some magic happens and they are populated, i.e. data is loaded, for <code>array_notepad</code> data is read from a notepad file whilst <code>array_images</code> is populate...
<p>Your question isn't entirely clear on what your expected output should be. You mention 'label' - to me it sounds like you're describing key-value pairs i.e. a dictionary.</p> <p>In which case you should be able to use the <code>zip</code> function as described in this question: <a href="https://stackoverflow.com/qu...
python|arrays|tensorflow|neural-network|conv-neural-network
0
15,103
14,217,581
python pandas csv exporting
<p>I've problem exporting a dataframe to CSV file. </p> <p>Data types are String and Float64 values like this:</p> <pre><code>In [19]: segmenti_t0 Out[19]: SEGM1 SEGM2 AD P.S. 8.3 SCREMATO 0.6 CRE STD 1.2 FUN INTERO 0.0 P.S. 2.0 SCREMATO 0.0 NORM ...
<p>You should use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="noreferrer"><code>to_excel</code></a> DataFrame method:</p> <pre><code># first convert Series to DataFrame df_segmenti_t0 = DataFrame(segmenti_t0) # save as excel spreadsheet df_segmenti_t0.to_exc...
python|csv|pandas|export
6
15,104
45,255,236
How is pandas groupby method actually working?
<p>So I was trying to understand pandas.dataFrame.groupby() function and I came across this example on the documentation:</p> <pre><code> In [1]: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', ...: 'foo', 'bar', 'foo', 'foo'], ...: 'B' : ['one', 'one', 'two'...
<p>When you use just</p> <pre><code>df.groupby('A') </code></pre> <p>You get a <a href="https://github.com/pandas-dev/pandas/blob/v0.20.3/pandas/core/groupby.py#L1632-L1657" rel="nofollow noreferrer"><code>GroupBy</code> object</a>. You haven't applied any function to it at that point. Under the hood, while this de...
python|pandas|dataframe
16
15,105
44,996,628
Transpose factorplot in seaborn
<p>Following my <a href="https://stackoverflow.com/questions/44975337/side-by-side-boxplots-with-pandas">previous question</a> how to draw several box plots, now I am wondering how transpose the factor plot and instead of having 1x5 pictures</p> <p><a href="https://i.stack.imgur.com/MhZ6X.png" rel="nofollow noreferrer...
<p>For a seaborn boxplot you need to use the <code>row</code> argument to supply the quantity to map along the rows, instead of the <code>col</code> argument.</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt titanic = sns.load_dataset("titanic") g = sns.factorplot(y="age", x="embark_town", ...
python|pandas|seaborn
1
15,106
45,271,924
Error converting to Pandas Datetime to include only the time
<p>I have made a new column in my dataframe that's the difference between two other <code>datetime64</code> columns, with precision to the seconds. The other two columns have been created using the following format:</p> <pre><code>df = df.col1.values.astype('datetime64[s]') df = df.col2.values.astype9('datetime64[s]'...
<p>So after you do this step:</p> <p><code>df['final'] = df.col3 - df.col2</code> which gives</p> <p>00:19:14 1<br> 00:19:21 2<br> 00:19:54 3<br> 00:20:01 4<br> 00:19:54 5<br> 00:20:01 6</p> <p><code>df['final'] = pd.to_datetime(df['final'])</code></p> <pre><code>df['final'] </code></pre> <p>1970-01-01 00:19:14 1...
python|pandas|datetime
1
15,107
57,101,061
Creating new pandas from other dataframe based on conditions
<p>To start with - I'm a total beginner with Pandas, so descriptive help would be very appreciated.</p> <p>I have one dataframe, called df_persons. This dataframe contains 2 columns, one "age" and one "gender". The ages spans from 0 - 100 yrs.</p> <p>My main goal is to create a pie chart, showing amount of people who...
<p>You can always try conditional selection, you were really close in your first statement. So you have two dataframes: df_test &amp; df_persons. We want to slice df_persons for your age groups and place them in df_test. To be sure you're not simply creating a variable that points to df_persons, you'll see that I add ....
python|pandas
0
15,108
57,000,785
Removing special characters while retaining alpha numeric words
<p>I'm in the middle of cleaning a data set that has this:</p> <p>[IN]</p> <pre><code>my_Series = pd.Series(["-","ASD", "711-AUG-M4G","Air G2G", "Karsh"]) my_Series.str.replace("[^a-zA-Z]+", " ") </code></pre> <p>[OUT]</p> <pre><code>0 1 ASD 2 AUG M G 3 Air G G 4 Karsh </code></pre...
<p>Try with <code>apply</code> to achieve your ideal output. </p> <pre><code>&gt;&gt;&gt; my_Series = pd.Series(["-","ASD", "711-AUG-M4G","Air G2G", "Karsh"]) </code></pre> <hr> <p><strong>Output:</strong></p> <pre><code>&gt;&gt;&gt; my_Series.apply(lambda x: " ".join(['' if word.isdigit() else word for word in x.r...
regex|python-3.x|pandas
2
15,109
35,374,995
Create multiple dataframe using for loop in python 2.7
<p>I have a list of locations </p> <pre><code>["HOME", "Office", "SHOPPING"] </code></pre> <p>and a pandas data frame "DF"</p> <pre><code>Start_Location End_Location Date OFFICE HOME 3-Apr-15 OFFICE HOME 3-Apr-15 HOME SHOPPING 3-Apr-15 HOME SHOPPIN...
<p>I got the answer which I was looking for </p> <pre><code>import pandas as pd gbl = globals() for i in locations: gbl['df_'+i] = df[df.Start_Location==i] </code></pre> <p>This will create 3 data frames df_HOME, df_office and df_SHOPPING</p> <p>Thanks,</p>
python|pandas
5
15,110
28,447,567
Python terminates process with exit code -1073741819
<p>I am trying to read a csv file (~190MB in size) into a pandas dataframe, but I am getting this error. I am running the Pycharm IDE from JetBrains</p> <pre><code>Process finished with exit code -1073741819 (0xC0000005) </code></pre> <p>The code I am trying to run is below:</p> <pre><code>from pandas import DataFra...
<p>I figured out what the issue was. There were values in the CSV like that were not being properly read by the parser. I changed the code from </p> <pre><code>frame.from_csv('c:/Nitin/692/Python/CSV/21LIVvTOT_user_geo_Reply.csv', header=True) </code></pre> <p>to </p> <pre><code>data = pandas.read_csv('c:/Nitin/692...
python|pandas|csv|utf
3
15,111
50,907,049
How to make np.where more efficient with triangular matrices?
<p>I got this code where distance is a lower triangular matrix defined as this: </p> <pre><code>distance = np.tril(scipy.spatial.distance.cdist(points, points)) def make_them_touch(distance): """ Return the every distance where two points touched each other. See example below. """ thresholds = np.un...
<p><strong>UPDATE1:</strong> here is a snippet for an <em>upper</em> triangular distance matrix (it shouldn't really matter as the distance matrix is always symmetric):</p> <pre><code>from itertools import combinations res = {tup[0]:tup[1] for tup in zip(pdist(points), list(combinations(range(len(points)), 2)))} </co...
python|numpy|scipy|itertools
1
15,112
50,870,987
Looking for the presence of composite key in three DataFrames, and concatenating DataFrames accordingly
<p>This question was very hard to word..</p> <p>Here is some sample code for a reproducible example:</p> <pre><code>import numpy as np import pandas as pd df1 = pd.DataFrame([['a', 1, 10, 1], ['a', 2, 20, 1], ['b', 1, 4, 1], ['c', 1, 2, 1], ['e', 2, 10, 1]]) df2 = pd.DataFrame([['a', 1, 15, 2], ['a', 2, 20, 2], ...
<p>You can use <code>pd.merge</code> whilst using <code>how='outer'</code></p> <pre><code># Change column names and remove 'part' column df1 = df1.rename(columns={'price':'pricepart1'}).drop('part', axis=1) df2 = df2.rename(columns={'price':'pricepart2'}).drop('part', axis=1) df3 = df3.rename(columns={'price':'pricepa...
python|pandas|dataframe|join|merge
2
15,113
50,955,127
Determining input nodes when freezing Tensorflow graphs using tf.data.Datasets
<p>I'm using Tensorflow <code>tf.data.Dataset</code> API as my input pipeline as follows:</p> <pre><code>train_dataset = tf.data.Dataset.from_tensor_slices((trn_X,trn_y)) train_dataset = train_dataset.map(_trn_parse_function,num_parallel_calls=12) train_dataset = train_dataset.shuffle(buffer_size=1000).repeat(args.n...
<p>handle = tf.placeholder(tf.string, shape=[]) is your input, so the tensor is most likely 'Placeholder:0'.</p> <p>However it would make more sense to write: </p> <pre><code>handle = tf.placeholder(tf.string, shape=[], name="input_placeholder") </code></pre> <p>then you know for sure.</p>
python|tensorflow
0
15,114
20,763,012
Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?
<p>I have a Numpy array consisting of a list of lists, representing a two-dimensional array with row labels and column names as shown below:</p> <pre><code>data = array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]]) </code></pre> <p>I'd like the resulting DataFrame to have Row1 and Row2 as index values, and Col1, Co...
<p>You need to specify <code>data</code>, <code>index</code> and <code>columns</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame" rel="noreferrer"><code>DataFrame</code></a> constructor, as in:</p> <pre><code>&gt;&gt;&gt; pd.DataFrame(data=data[1:,1:], #...
python|pandas|numpy
398
15,115
66,341,335
getting NAN values from for loop [python pandas]
<p>I have a python dataframe with a column <code>CREATIVE_NAME</code> and I want to create a new column <code>CREATIVE_SIZE</code> by searching specific substrings and put them in the new column.</p> <pre><code> creative_size = [] for i in df['CREATIVE_NAME']: if search('320x480', i): creative_s...
<pre><code>import pandas as pd #### FOR TESTING #### test_data_dict = { 'CREATIVE_NAME':['320x480', '728x1024', '1000x1000'] } df = pd.DataFrame(data=test_data_dict) #### Define a set of all creative sizes you want to check against creative_sizes =('320x480','728x1024','320x50','728x90','300x250','80x80','1200x62...
python|pandas|loops|for-loop|na
0
15,116
66,339,567
Changing type of Data Frame cells without loop
<p>Sometimes, data is not in the format we wish it to be. Python offers ways to deal with this (such as int() and str()), but solutions for Data Frames are not trivial.</p> <p>For instance, let us generate a Data Frame of 5 datetime observations:</p> <pre><code>import pandas from datetime import datetime datelist = pd...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html" rel="nofollow noreferrer"><code>.dt</code> accessor</a> <em>for datetimelike properties of the Series values</em>:</p> <pre><code>df.A.dt.date # 0 2021-02-23 # 1 2021-02-24 # 2 2021-02-25 # 3 2021-02-2...
python|pandas|dataframe|datetime
2
15,117
66,412,293
how to obtain max and min for a datetime in a pandas df?
<p>I am exploring some data using pandas (I imported the dataset from excel using read_excel).</p> <p>One of my columns is a <strong>datetime</strong>... How can I select the 'max' and 'min' for this datetime column?</p> <p>This is the same question as here:</p> <p><a href="https://stackoverflow.com/questions/23178129/...
<p>just change your <strong>'creation_date'</strong> column from <code>object</code> to <code>datetime</code> dtype by:-</p> <pre><code>df['creation_date']=pd.to_datetime(df['creation_date']) </code></pre> <p>Now just calculate min and max dates value by:-</p> <pre><code>df['creation_date'].max() df['creation_date'].mi...
python|pandas
4
15,118
16,406,611
how to get particular part of DataFrame
<p>I have a pandas DataFrame "df" as below:</p> <pre><code> lat lon time ID 48202 42.5040 -70.5419 731800.5514 48202 42.4956 -70.5539 731801.6319 48202 42.4927 -70.5830 731802.7188 48202 42.5028 -70.6010 731802.8014 48202 42.5168 -70.5966 731803.8944 4...
<p>you should mask here!</p> <pre><code>df_masked = df[(df.time &lt;= t1) &amp; (df.time &gt;= t0)] </code></pre>
python|pandas
1
15,119
57,346,191
Tensorflow pad sequence feature column
<p>How to pad sequences in the feature column and also what is a <code>dimension</code> in the <code>feature_column</code>.</p> <p>I am using <code>Tensorflow 2.0</code> and implementing an example of text summarization. Pretty new to machine learning, deep learning, and TensorFlow.</p> <p>I came across <code>feature...
<p>Actually, this</p> <blockquote> <p>I am also confused as to what to use here, sequence_categorical_column_with_vocabulary_list or categorical_column_with_vocabulary_list.</p> </blockquote> <p>should be the first question, because it affects interpretation the one from the topic name.</p> <p>Also it is not e...
python|tensorflow|machine-learning|deep-learning|tensorflow2.0
10
15,120
57,457,631
Faster-RCNN Pytorch problem at prediction time with image dimensions
<p>I am finetuning Faster-RCNN using PyTorch according to this tutorial: <a href="https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html</a></p> <p>The results are pretty good but making predictions only work ...
<p><a href="https://pytorch.org/docs/stable/_modules/torchvision/models/detection/mask_rcnn.html" rel="nofollow noreferrer"><code>MaskRCNN</code></a> expects a list of tensors as 'input images' and a list of dictionaries as 'target' during training mode. This particular design choice is due to the fact that each image ...
python|pytorch|faster-rcnn
1
15,121
57,590,299
Can not replace values in pandas dataframe column with map
<p>I'm trying to replace a column in pandas data frame using a dictionary and the map method.I found a method without map but its very very ugly</p> <p>Here is my dictionary </p> <pre><code>{'A+': '97–100%', 'A': '93–96%', 'A−': '90–92%', 'B+': '87–89%', 'B': '83–86%', 'B−': '80–82%', 'C+': '77–79%', 'C': '73–...
<p>If get missing values in output it means key of dicionary not match with values of column. </p> <p>If problem with whitespaces in column use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.strip.html" rel="nofollow noreferrer"><code>Series.str.strip</code></a>:</p> <pre><code>d...
python-3.x|pandas|dataframe
2
15,122
57,662,483
Combining 2 arrays into a dictionary
<p>I have an array of strings (<code>a1</code>): <code>["a", "b", "c"]</code></p> <p>And another (<code>a2</code>) that looks like this:</p> <pre><code>["1,20,300", "2,10,300", "3,40,300", "1, 20, 300, 4000"] </code></pre> <p>The wanted end result is:</p> <pre><code>{"a": [1,2,3,1], "b": [20, 10, 40, 20], "c": [300...
<pre><code>from numpy import transpose a1 = ["a", "b", "c"] a2 = ["1,20,300", "2,10,300", "3,40,300"] a2t = transpose([e.split(",") for e in a2]) result = {a1[i] : list(a2t[i]) for i in range(len(a1))} =&gt; {'a': ['1', '2', '3'], 'b': ['20', '10', '40'], 'c': ['300', '300', '300']} </code></pre> <p>thx to Code-Ap...
python|pandas
2
15,123
57,605,610
replacing values in a df based on the values in another df if a coincidence exists in a column
<p>I have the following df1:</p> <pre><code> Id value 'so' 5 'fe' 6 'd1' 4 </code></pre> <p>Then I have a ref_df:</p> <pre><code> Id value 'so' 3 'fe' 3 'ju' 2 'd1' 1 </code></pre> <p>I want to check that if any of the Ids in ref_df appear in df1, then replace the value in df1 by the ref_df....
<p>try this,</p> <pre><code>df1['Value'] = df1['Id'].map(ref_df.set_index('Id')['Value']) </code></pre> <p>O/P:</p> <pre><code> Id Value 0 so 3 1 fe 3 2 dl 1 </code></pre>
python|pandas|dataframe
1
15,124
57,384,525
How to open a series of csv files, edit and re-save with a revised string variable in the filename
<p>I have a series of csv files that each have several columns. I want to open each file, delete some columns, rename the last column, and save the revised file under a new, similar name, and repeat this ~2500 times</p> <p>The basic open, edit, save aspects does work for a single, hardcoded filename (both old and ne...
<p>One of the reasons the dataframe is not getting updated because the statement where you are renaming the columns is not entirely correct. Here's how it should look like:</p> <pre><code>df = df.rename(columns = {'Close':symbol}) </code></pre> <p>You have to assign it back to the dataframe variable or do it place li...
python|pandas|csv|dataframe|filenames
0
15,125
24,337,499
Pandas rolling apply with variable window length
<p>I have a Series with values indexed by timestamps. These timestamps are irregularly spaced and I would like to calculate something like the rolling mean (say) over the last N seconds, where N is a constant. Unfortunately, resampling at regular intervals before calculating the rolling quantity is NOT an option - the ...
<p>You want to reset your index to an integer index and perform the rolling operation on a timestamp column.</p> <pre><code># generate some data data = pd.DataFrame(data={'vals':range(5), 'seed_ts': [np.datetime64('2017-04-13T09:00:00') for x in range(5)]}) data['random_offset'] = [np.timedelta64(randint(0, 5), 's') f...
python|pandas
3
15,126
43,770,635
Make a dataframe with grouped questions from three columns
<p>I have the following dataframe:</p> <pre><code> A B C I am motivated Agree 4 I am motivated Strongly Agree 5 I am motivated Disagree 6 I am open-minded Agree 4 I am open-minded Disagree 4 I a...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot_table.html" rel="noreferrer">DataFrame.pivot_table()</a> method:</p> <pre><code>In [250]: df.pivot_table(index='A', columns='B', values='C', aggfunc='sum', fill_value=0) Out[250]: B Agree Disagree Strongly Ag...
python|pandas|dataframe|pivot
5
15,127
43,660,458
multiply index value and column
<p>I have the following df :</p> <pre><code> A B C A      A    A*B    A*C B        A*B    B      B*C C       A*C    B*C      C </code></pre> <p>I have on ther side a dfs with the values: </p> <pre><code>df0:  A*B   3 A*C 4 B*C 2 df1: A  2  B 8 C 3 </code></pre> <p>Is there...
<p>It seeems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>replace</code></a>:</p> <pre><code>print (df0) a A*B 3 A*C 4 B*C 2 print (df1) b A 2 B 8 C 3 df1 = df.replace(df0['a']).replace(df1['b']) print (df1) A ...
python|pandas
1
15,128
43,595,652
Hows does sklearn PCA works on dataframes?
<p>I have the following dataframe:</p> <pre><code> A B C D 0 4 1 1 78 1 82 2 58 41 2 53 3 31 76 3 1 45 4 12 5 5 2 4 87 6 1 74 6 11 7 1 1 6 47 8 1 1 6 8...
<p>This is how you would do it using <code>PCA</code>, note I am also standardizing the values.</p> <pre><code>from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA vals = df.ix[:, :4].values vals_std = StandardScaler().fit_transform(vals) sklearn_pca = PCA(n_components = 'however m...
python|pandas|dataframe|scikit-learn|pca
0
15,129
73,103,484
Split text expanding rows in Pandas
<p>I have this dataset:</p> <pre class="lang-py prettyprint-override"><code>mydf = pd.DataFrame({'source':['a','b','a','b'], 'text':['November rain','Sweet child omine','Paradise City','Patience']}) mydf source text 0 a November rain 1 b Sweet child omine 2 a Paradise ...
<p><code>str.split(expand=True)</code> returns a dataframe, normally with more than one column, so you can't assign back to your original column:</p> <pre><code># output of `str.split(expand=True)` 0 1 2 0 November rain None 1 Sweet child omine 2 Paradise City None 3 Patience None...
python|pandas
2
15,130
10,678,682
Why does pygame.sndarray.make_sound seemingly quadruple the sound duration?
<p>The following code:</p> <pre><code>import pygame, numpy pygame.mixer.pre_init(frequency=96000,size=-16,channels=1) pygame.init() a = numpy.random.randn(96000) sound = pygame.sndarray.make_sound(a) print sound.get_length() </code></pre> <p>yields a print-out of 4.0, suggesting that the specified duration of 96000 s...
<p>The data going into make_sound isn't 16 bit integers, (as your pre_init() suggests they should be). Before calling make_sound() try...</p> <pre><code>a = a.astype(numpy.int16) </code></pre> <p>You might want to also make sure that you use a method of generating your random numbers that causes them to fall into th...
python|numpy|pygame|audio
4
15,131
70,632,384
pandas: text analysis: Transfer raw data to dataframe
<p>I need to read lines from a text file and extract the quoted person name and quoted text from each line.</p> <p>lines look similar to this:</p> <blockquote> <p>&quot;Am I ever!&quot;, Homer Simpson responded.</p> </blockquote> <blockquote> <p>Remarks:</p> <p>Hint: Use the returned object from the '<code>open</code>'...
<p>for loop in folder:</p> <pre><code># All files acc. mask ending with .txt print(glob.glob(&quot;C:\\MyFolder\\*.txt&quot;)) mylist=[ff for ff in glob.glob(&quot;C:\\MyFolder\\*.txt&quot;)] print(&quot;file_list:\n&quot;, mylist) for filepath in mylist: # do smth with each filepath </code></pre> <p>to collect ...
python|pandas|dataframe|nlp|python-re
0
15,132
70,395,583
Finding continuous sequences in Python using Numpy
<p>Given increasing list, my purpose is to return partition of the sequence into subsequences formed by sequential numbers. I want to do it with NumPy. Now, I wish to subtract each time the value of the first element in the relevant part of the list, and ask to the indices where the value in the index equals it's index...
<p>Let's pretend your numpy tag is not spurious and you have</p> <pre><code>a = np.array([10, 11, 12, 23, 30, 31, 32, 204]) </code></pre> <p>If you apply <code>np.diff</code>, you see</p> <pre><code>d = np.diff(a) # 1, 1, 11, 7, 1, 1, 172 </code></pre> <p>Clearly, anywhere that <code>d</code> is not <code>+/-1</code>,...
python|numpy
2
15,133
42,596,264
Element wise multiplication of each row
<p>I have two <code>DataFrame</code> objects which I want to apply an element-wise multiplication on each row onto:</p> <pre><code>df_prob_wc.shape # (3505, 13) df_prob_c.shape # (13, 1) </code></pre> <p>I thought I could do it with <code>DataFrame.apply()</code> </p> <pre><code>df_prob_wc.apply(lambda x: x.multi...
<p>It seems you need multiple by <code>Series</code> created with <code>df_prob_c</code> by <code>iloc</code>:</p> <pre><code>df_prob_wc = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9], 'D':[1,3,5], 'E':[5,3,6], 'F':[7...
pandas|dataframe|series|multiplication|elementwise-operations
1
15,134
42,800,444
When should we use the place_pruned_graph config?
<p>Question:As the title saied, I wander When should we use the config place_pruned_graph in GraphOptions. What's the purpose of this config?</p> <p>I'm not clear to the comment about this config:</p> <pre><code> // Only place the subgraphs that are run, rather than the entire graph. // // This is useful for int...
<p>The short answer? <strong>Never.</strong> The longer answer requires me to explain why this option exists at all.</p> <p>So why does TensorFlow include this convoluted configuration option and logic to handle it? It's a historical accident that came about when <code>tensorflow::DirectSession</code> and <code>tensor...
tensorflow
2
15,135
42,816,678
fsum for numpy.arrays, stable summation
<p>I have a number of multidimensional <code>numpy.array</code>s with small values that I need to add up with little numerical error. For <code>float</code>s, there is <a href="https://docs.python.org/3/library/math.html#math.fsum" rel="noreferrer"><code>math.fsum</code></a> (with its implementation <a href="https://gi...
<p>Alright then, I've implemented <a href="https://github.com/nschloe/accupy/" rel="noreferrer">accupy</a> which gives a few stable summation algorithms.</p> <p>Here's a quick and dirty implementation of <a href="https://en.wikipedia.org/wiki/Kahan_summation_algorithm" rel="noreferrer">Kahan summation</a> for numpy ar...
python|arrays|numpy
7
15,136
30,471,119
Using DataFrame#loc with arguments of trivially different types
<p>Let <code>df</code> be a <code>DataFrame</code> with an index of dtype <code>x</code>. Due to implicit type conversions, I end up having to call <code>df.loc(n)</code>, where <code>n</code> was implicitly converted from <code>x</code> to a trivially different type <code>y</code>. Most commonly this happens with <cod...
<p>You could explicitly recast when doing your <code>.loc</code>:</p> <pre><code>&gt;&gt;&gt; df.loc[df.loc[1].astype('int64')[0]] 0 1 1 2 Name: 1, dtype: float64 </code></pre> <p>Or, more generally:</p> <pre><code>df.loc[df.loc[2].astype(df[0].dtype)[0]] </code></pre>
python|pandas
1
15,137
30,547,149
Generate a numpy array from a python function
<p>I have what I thought would be a simple task in numpy, but I'm having trouble.</p> <p>I have a function which takes an index in the array and returns the value that belongs at that index. I would like to, efficiently, write the values into a numpy array.</p> <p>I have found <code>numpy.fromfunction</code>, but it ...
<p>I think the issue of integer wraparound is unrelated to numpy's vectorized <code>sin</code> implementation and even the use of python or C.</p> <p>If you use a 2-byte signed integer and try to generate an array of integer values ranging from 0 to above 32767, you will get a wrap-around error. The array will look li...
python|arrays|numpy
0
15,138
26,666,919
Add column in dataframe from list
<p>I have a dataframe with some columns like this:</p> <pre><code>A B C 0 4 5 6 7 7 6 5 </code></pre> <p>The <em>possible range of values in A are only from 0 to 7</em>. </p> <p>Also, I have a list of 8 elements like this:</p> <pre><code>List=[2,5,6,8,12,16,26,32] //There are only 8 elements in this list ...
<p>Just assign the list directly:</p> <pre><code>df['new_col'] = mylist </code></pre> <hr> <p><strong>Alternative</strong><br> Convert the list to a series or array and then assign:</p> <pre><code>se = pd.Series(mylist) df['new_col'] = se.values </code></pre> <p>or</p> <pre><code>df['new_col'] = np.array(mylist) ...
python|pandas|dataframe
393
15,139
38,976,800
Pandas apply function to groups of columns and indexing
<p>Given a dataframe <code>df</code> consisting of multiple columns:</p> <pre><code>Col1 Col2 Col3 Col4 Col5 Col6 4 2 5 3 4 1 8 3 9 7 4 5 1 3 6 7 4 7 </code></pre> <p>I want to apply a function <code>func</code> for a group ...
<p>You need remove first <code>:</code> in <code>iloc</code>, because working with <code>Series</code> in <code>apply</code>, not with <code>DataFrame</code>:</p> <pre><code>print (df.apply(lambda x: func(x.iloc[0:3]), axis=1)) </code></pre> <p>Test:</p> <pre><code>def func(x): return x.sum() print (df.apply(la...
python|pandas|indexing|dataframe|multiple-columns
3
15,140
39,283,605
Regarding the use of tf.train.shuffle_batch() to create batches
<p>In <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#shuffle_batch" rel="noreferrer">Tensorflow tutorial</a>, it gives the following example regarding <code>tf.train.shuffle_batch()</code>:</p> <pre><code># Creates batches of 32 images and 32 labels. image_batch, label_batch = tf.train....
<p>The <a href="https://www.tensorflow.org/api_docs/python/tf/train/shuffle_batch" rel="noreferrer"><code>tf.train.shuffle_batch()</code></a> function uses a <a href="https://www.tensorflow.org/api_docs/python/tf/RandomShuffleQueue" rel="noreferrer"><code>tf.RandomShuffleQueue</code></a> internally to accumulate batche...
tensorflow
25
15,141
39,172,575
Pandas concatenation of multiple dataframes returns null values
<p>I have a dataframe (<code>df</code>), that I break down into 4 new dfs (<code>media</code>, <code>client</code>, <code>code_type</code>, and <code>date</code>). <code>media</code> has one column of null values, while the other three are only 1-dim dfs, each consisting of nulls. After replacing the nulls in each data...
<p>Starting with this:</p> <pre><code> code_name media_type acq. revenue 0 RASH Radio 50.0 34004.0 1 100 NaN 10.0 1035.0 2 NEWS SiriusXM 61.0 3475.0 3 DR SiriusXM 53.0 4307.0 4 SPORTS SiriusXM 45.0 6503.0 5 DOUBL Podcast 13.0 4205.0 </code></pre> ...
python|pandas|concatenation
0
15,142
39,352,725
Append dataframes in pandas
<p>I have two dataframes in pandas (copy from Spyder Variable Explorer)</p> <p>df1</p> <pre><code>index 0 1 2 3 4 5 6 0 Loc 0.0 0.0 0.0 0.25 0.0 light 1 Loc 0.0 0.0 0.0 0.25 0.0 light 2 Loc 0.0 0.0 0.0 0.25 0.0 light 3 Loc 0.0 0.0 0.0 0.25 0.0 light </code></...
<p><strong>Disclaimer</strong>: I do not have 50 rep points to comment. So this answer is just a comment as <a href="https://stackoverflow.com/users/704848/edchum">EdChum</a> has given the correct answer.</p> <p>You should take a look at the documentation of the various types of concat, merge and join <a href="http://...
python|pandas|formatting
2
15,143
19,730,653
slicing on a perod index in pandas when slice start and end may be out of bounds
<p>Is the following behavior expected or a bug?</p> <p>I have a process where I need rows from Dataframe, but in the boudary conditons the simple rule ( all rows 5 days preceeding will generate selections partially or fully outside the index. I would like pandas to behave like python and always return a frame even if...
<p>This is as expected. The slicing on labels (start : end), only works if the labels exist. To get what I think you are after reindex for the entire period, select, then dropna. That said, the <em>loc</em> behavior of raising is correct, while the <em>[]</em> indexing should work (maybe a bug).</p> <pre><code>In [23]...
python|pandas|slice|period
1
15,144
13,143,052
Iterate two or more lists / numpy arrays... and compare each item with each other and avoid loops in python
<p>I am new to python and my problem is the following:</p> <p>I have defined a function <code>func(a,b)</code> that return a value, given two input values.</p> <p>Now I have my data stored in lists or numpy arrays <code>A,B</code>and would like to use <code>func</code> for every combination. (A and B have over one m...
<h1>First issue</h1> <p>You need to calculate the output of <code>f</code> for many pairs of values. The "standard" way to speed up this kind of loops (calculations) is to make your function <code>f</code> accept (NumPy) arrays as input, and do the calculation on the whole array at once (ie, no looping as seen from Py...
python|map|numpy|scipy
3
15,145
29,305,078
How to get last quarter and last year values
<p>I have a dataframe with data 'per quarters'. </p> <p>I would like to have the value of the previous quarter and the value 4 quarters before (1 year before) next to my quarter value. </p> <p>What is the best way to do it: </p> <ul> <li>Tranform into dates</li> <li>Play with the order of the data and the indexes? <...
<p>Use Shift.</p> <p><a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.shift.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.shift.html</a></p> <pre><code>import pandas as pd index = ['14Q1','14Q2','14Q3','14Q4','15Q1'] df = pd.DataFrame({'A':range(...
python|pandas
2
15,146
23,794,361
Install Python modules on Shared hosting virtualenv
<p>Experimenting with using python in a virtualenv on my shared hosting account. Based on <a href="http://wiki.dreamhost.com/Flask" rel="nofollow">this dreamhost tutorial</a> have installed pip and another module or two (echonest, remix), but trying to install numpy the long list of errors starts with <code>non-existin...
<p>Are you sure you're running <code>~/local/bin/python</code> when running setup.py?</p> <p>One virtualenv-specific thing you can do is <code>source ~/local/bin/activate</code>, which automatically sets your virtualenv to take preference over everything else in your path. It only works until you log out of your term...
python|numpy
1
15,147
22,817,533
Pip doesn’t know where numpy is installed
<p>Trying to uninstall <code>numpy</code>. I tried <code>pip uninstall numpy</code>. It tells me that it isn't installed. However, <code>numpy</code> is still installed at <code>/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy</code>.</p> <p>How can I make sure <code>pip</code> finds ...
<p>Make sure your pip is the right one for your NumPy install. Check the pip and python locations with:</p> <pre><code>$ which pip $ which python </code></pre> <p>… these should echo <code>/usr/bin/pip</code> and <code>/usr/bin/python</code>, respectively (since you are evidently on a Mac). Next, check which NumPy yo...
python|python-2.7|numpy|pip|python-packaging
5
15,148
22,636,499
Convert multi-channel PyAudio into NumPy array
<p>All the examples I can find are mono, with <code>CHANNELS = 1</code>. How do you read stereo or multichannel input using the callback method in PyAudio and convert it into a 2D NumPy array or multiple 1D arrays?</p> <p>For mono input, something like this works:</p> <pre><code>def callback(in_data, frame_count, ti...
<p>It appears to be interleaved sample-by-sample, with left channel first. With signal on left channel input and silence on right channel, I get:</p> <pre><code>result = [0.2776, -0.0002, 0.2732, -0.0002, 0.2688, -0.0001, 0.2643, -0.0003, 0.2599, ... </code></pre> <p>So to separate it out into a stereo stream, r...
python|numpy|pyaudio
18
15,149
15,134,442
Python, how to optimize this code
<p>I tried to optimize the code below but I cannot figure out how to improve computation speed. I tried Cthon but the performance is like in python.</p> <p>Is it possible to improve the performance without rewrite everything in C/C++?</p> <p>Thanks for any help</p> <pre><code>import numpy as np heightSequence = 400...
<p>By looking at the code it seems that you can get rid of the two outer loops completely, converting the code to a <em>vectorised</em> form. However, the <code>np.polyfit</code> call must then be replaced by some other expression, but the coefficients for a linear fit are easy to find, also in vectorised form. The las...
python|performance|numpy|cython
4
15,150
13,385,860
How can I remove extra whitespace from strings when parsing a csv file in Pandas?
<p>I have the following file named 'data.csv':</p> <pre><code> 1997,Ford,E350 1997, Ford , E350 1997,Ford,E350,"Super, luxurious truck" 1997,Ford,E350,"Super ""luxurious"" truck" 1997,Ford,E350," Super luxurious truck " "1997",Ford,E350 1997,Ford,E350 2000,Mercury,Cougar </code></pre> <...
<p>You could use converters:</p> <pre><code>import pandas as pd def strip(text): try: return text.strip() except AttributeError: return text def make_int(text): return int(text.strip('" ')) table = pd.read_table("data.csv", sep=r',', names=["Year", "Make", "Model", ...
python|parsing|pandas
60
15,151
29,618,613
Read all lines of csv file using .read_csv
<p>I am trying to read simple <code>csv</code> file using <code>pandas</code> but I can't figure out how to not "lose" the first row.</p> <p>For example:</p> <p><code>my_file.csv</code></p> <p>Looks like this:</p> <pre><code>45 34 77 </code></pre> <p>But when I try to to read it:</p> <pre><code>In [18]: import pa...
<p>Yeah, this is a bit of a UI problem. We should handle <code>False</code>; right now it thinks you want the header on row 0 (== False.) Use <code>None</code> instead:</p> <pre><code>&gt;&gt;&gt; df = pd.read_csv("my_file.csv", header=False) &gt;&gt;&gt; df 45 0 34 1 77 &gt;&gt;&gt; df = pd.read_csv("my_file.cs...
python|pandas
1
15,152
62,418,856
The differences between tf.nest.map_structure vs tf.map_fn in speed and in results
<p>My question may be summarized as follows:</p> <ol> <li><strong>Why does <code>tf.map_fn</code> generate slightly different results compared to <code>tf.nest.map_structure</code>?</strong></li> <li><strong>Why is <code>tf.map_fn</code> much slower than <code>tf.nest.map_structure</code>?</strong></li> <li><strong>To...
<h2><code>tf.map_fn(func, elems)</code>:</h2> <p>Maps over axis 0. For example:</p> <pre class="lang-py prettyprint-override"><code>tf.map_fn(lambda x: x*2, tf.constant([1, 2, 3])) # =&gt; [2, 4, 6] tf.map_fn(lambda x: x[0]*x[1], tf.constant([[1, 0], [2, 4], [3, 5]])) # =&gt; [0, 8, 15] </code></pre> <h2><code>tf.nest....
python|tensorflow
0
15,153
62,191,514
DataFrame create column and groupby from str.contain
<p>Example:</p> <p>Given a pd.DataFrame similar to :</p> <pre><code>In [37]: df_ex Out[37]: value AS1_TEMP 12 AS1_TENS 190 AS1_SPEED 2000 AS2_TEMP 24 AS2_TENS 200 AS2_SPEED 1750 AS3_TEMP 11 AS3_TENS 187 AS3_SPEED 1621 </code></pre> <p>I want a final df with new index/colum...
<p>One way is to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer">split</a> the index, and expand to True - this converts the index to a multiIndex; from there, you <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataF...
python|pandas|dataframe
4
15,154
62,315,715
Distinct users per time from duration and datetime using pandas python
<p>I have this dataset</p> <pre><code>created_at user_id duration (second) 2019-02-21 11:32:57.000 A 50 2019-02-21 11:32:57.000 B 100 2019-02-21 11:35:00.000 B 70 </code></pre> <p>My goal is to know distinct user_id per minute that still open our app. for exa...
<p>Use:</p> <pre><code># STEP 1: df['created_at'] = pd.to_datetime(df['created_at']) df['end_at'] = df['created_at'] + pd.to_timedelta(df['duration (second)'], unit='s') # STEP 2: df1 = df.melt(id_vars='user_id', value_vars=['created_at', 'end_at'], value_name='ts') # STEP 3: df1 = ( df1[['user_id', 'ts']].group...
python|pandas|datetime
1
15,155
51,470,991
create a tensor proto whose content is larger than 2GB
<p>I created a ndarray (W) which size is (2^22, 256), and I tried to use this array as my initialization of weight matirx using:</p> <pre><code>w = tf.Variable(tf.convert_to_tensor(W)) </code></pre> <p>then, the tensorflow raised a error: <em>ValueError: Cannot create a tensor proto whose content is larger than 2GB.<...
<p>Protobuf has a <a href="https://stackoverflow.com/a/34186672/7443104">hard limit of 2GB</a>. And 2^22*256 floats are 4GB. Your problem is, that you are going to embed the initial value into the graph-proto by</p> <pre><code>import tensorflow as tf import numpy as np w_init = np.random.randn(2**22, 256).astype(np.f...
python|tensorflow
9
15,156
51,231,852
Iterating over Torchtext.data.BucketIterator object throws AttributeError 'Field' object has no attribute 'vocab'
<p>When I try to look into a batch, by printing the next iteration of the <code>BucketIterator</code> object, the <code>AttributeError</code> is thrown. </p> <pre><code>tv_datafields=[("Tweet",TEXT), ("Anger",LABEL), ("Fear",LABEL), ("Joy",LABEL), ("Sadness",LABEL)] train, vld = data.TabularDataset.splits(path="./d...
<p>I am not sure about the specific error you are getting but, in this case, you can iterate over a batch by using the following code:</p> <pre><code>for i in train_iter: print i.Tweet print i.Anger print i.Fear print i.Joy print i.Sadness </code></pre> <p><code>i.Tweet</code> (also others) is a t...
python|iterator|pytorch|torchtext
1
15,157
51,311,953
What is dtype with more than one element in ndarray of numpy?
<pre><code> x = np.array([(1,2),(3,4)],dtype=[('a','&lt;i4'),('b','&lt;i4')]) </code></pre> <p>Why do we use the dtype with more than one elements in ndarray and how is it useful? How do we interpret this?</p>
<p>First of all, you should notice that this array would only have one dimension which is represented by the dtype </p> <pre><code>('a','&lt;i4'),('b','&lt;i4') </code></pre> <p>The way I like to think about this is that we are creating a dtype by concatenating other dtypes together. We treat each pair of tuples as a...
python|numpy
1
15,158
47,997,605
Simplest way to distribute Tensorflow training on premise?
<p>What is the simplest way to train tensorflow models (using Estimator API) distributed across a home network? Doesn't look like ml-engine <a href="https://cloud.google.com/sdk/gcloud/reference/beta/ml-engine/local/train" rel="nofollow noreferrer">local train</a> allows you to specify IPs.</p>
<p>Your best bet is to use something like Kubernetes. This is a work in progress, but I believe it does have support for distributed training as well -- <a href="https://github.com/tensorflow/k8s" rel="nofollow noreferrer">https://github.com/tensorflow/k8s</a>.</p> <p>Alternatively for more low-tech automation options...
tensorflow|machine-learning|kubernetes|distributed-computing|google-cloud-ml
2
15,159
48,587,133
How to only add common index pandas data frame?
<p>Suppose I have two data frame. I would like to add both values if there is a common index otherwise take the value. Let me illustrate this with an example</p> <pre><code>import pandas as pd In [118]: df1 = pd.DataFrame([1, 2, 3, 4], index=pd.date_range('2018-01-01', periods=4)) In [119]: df2 = pd.DataFrame(10*np....
<p>Combine with <code>fillna</code></p> <pre><code>df1.add(df2).fillna(df1) Out[581]: 0 2018-01-01 1.0 2018-01-02 12.0 2018-01-03 13.0 2018-01-04 4.0 </code></pre> <p>Ok, </p> <pre><code>pd.concat([df1,df2]).sum(level=0) Out[591]: 0 2018-01-01 1 2018-01-02 12 2018-01-03 3 201...
python-2.7|pandas
2
15,160
71,000,250
Import "tensorflow.keras" could not be resolved after upgrading to TensorFlow 2.8.0
<p>TensorFlow 2.8 was recently released and I installed it as soon as it was out. I really need it for support of higher NumPy versions and a few new features. However, after installing it in my conda environment with</p> <p><code>python3 -m pip install --upgrade tensorflow</code></p> <p>neither PyCharm nor VSCode can ...
<p>This is a bug in the current version of tensorflow, as discussed in <a href="https://github.com/tensorflow/tensorflow/issues/53144" rel="noreferrer">this issue</a>.</p> <p>You can work around it by either</p> <ol> <li>modifying the file <code>site-packages/tensorflow/__init__.py</code> as described in <a href="https...
python-3.x|tensorflow2.0
7
15,161
70,833,286
Python - Pandas crosstab() - formatting cell values?
<p>not sure if possible, but it would be good if I could apply a percentage format to cells resulting from <code>pd.crosstab()</code>, as I am using the <code>normalize='columns'</code> option.<br /> They are percentage results, so displaying as percentages would be nice.</p> <p>Can it be done?</p> <p>Or perhaps a diff...
<p>The <code>pd.crosstab()</code> gives you the right results.</p> <pre class="lang-py prettyprint-override"><code>foo = pd.Categorical(['a', 'b', 'a', 'a'], categories=['a', 'b', 'c']) bar = pd.Categorical(['d', 'e', 'e', 'd'], categories=['d', 'e', 'f']) result = pd.crosstab(foo, bar, normalize='columns') </code></pr...
python|pandas|format|crosstab
1
15,162
70,828,891
How to copy contents from a sheet of an excel workbook to another workbook without loosing the excel formatting using python
<p>I have an excel sheet with specific formatting done. I need to copy this sheet to another workbook(excel sheet) without loosing the formatting(colour combination, wrap texting, cell size etc.) using python</p>
<p>Copying just the data is easy enough&gt; Formatting &amp; styles are part of the workbook, to maintain these need to be copied as well. You don't say if the 'another workbook' is existing or you want to copy the sheet to a newly created workbook. If the later then making copies of the workbook with a new name is pro...
python|excel|pandas|openpyxl
0
15,163
70,856,063
Convert .xls files of multiple sheets to .xlsx
<p>I have a 97-2003 <code>.xls</code> excel file that I need to converted to a <code>.xlsx</code>. The operational sense is that I have a plethora of these I need to convert.</p> <p>My issue is that each <code>.xls</code> file has various sheets; both the number and sheet names change.</p> <p>I am trying to convert the...
<p>The following solution works and was inspired <a href="https://stackoverflow.com/questions/35707723/writing-multiple-pandas-dataframes-to-multiple-excel-worksheets">by this post</a> and <a href="https://stackoverflow.com/questions/53290765/convert-a-xlsx-file-with-multiple-sheets-to-multiple-xlsx-files">this post</a...
python|excel|pandas
1
15,164
70,816,746
Sine Function with an exponential amplitude with a plusminus in Python
<p>I want to graph this expression:</p> <p><img src="https://latex.codecogs.com/gif.image?%5Cdpi%7B110%7D%20%5Cinline%20V_R(t)=%20%5Cpm%2015000e%5E%7B-2500t%7Dsen(t)" alt="" /></p> <p>But i dont understand how to manage time and plusminus in the code.</p> <p>I need to get something like this (this image is a voltage gr...
<p>First of all, you have to define a <code>t</code> array with time values:</p> <pre><code>t = np.linspace(0, 0.01, N) </code></pre> <p>then you can compute <code>Vr</code> as a function of time. The expression you reported contains a ± so it is not a mathematical function: you have to define two different functions (...
python|numpy|matplotlib|math|plot
0
15,165
51,970,709
Create frame wih both single and multi-level columns and add data to it
<p>I have 2 dataframes like this</p> <pre><code>frame1=pd.DataFrame(columns=['A','B','C']) a=['d1','d2','d3'] b=['d4','d5'] tups=([('T1',x) for x in a]+ [('T2',x) for x in b]) cols=pd.MultiIndex.from_tuples(tups,names=['Trial','Data']) frame2=pd.DataFrame(columns=cols) </code></pre> <p>My goal is to have both Da...
<p>You want to add a level to <code>frame1</code> with empty strings</p> <h2><code>pandas.MultiIndex.from_tuples</code></h2> <pre><code>idx = pd.MultiIndex.from_tuples([(c, '') for c in frame1]) f1 = frame1.set_axis(idx, axis=1, inplace=False) frame3 = pd.concat([f1, frame2], axis=1) frame3.reindex([0, 1]) A ...
python-3.x|pandas|multi-level
1
15,166
51,879,201
Concatenating Values to Dataframes
<p>Let's say I have a Pandas dataframe that looks like this:</p> <pre><code>df2 = pd.DataFrame(['Apple', 'orange', 'pear', 'apple'], columns=['A']) A 0 Apple 1 orange 2 pear 3 apple </code></pre> <p>Let's say I have this:</p> <pre><code>stuff = 'hello' </code></pre> <p>Is there a way to concatenat...
<p>Try:</p> <pre><code>df2[['A']] + ' - hello' </code></pre> <p>OR</p> <pre><code>stuff = hello df2[['A']] + ' - ' + stuff </code></pre> <p>Or as @piRSquared suggest using the <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow noreferrer">f-string</a> Python 3.6+ syntax:</p> <pre><code>df2 + f" - {s...
python|pandas
4
15,167
64,264,583
Custom Keras Metrics Class -> Metric at a certain recall value
<p>I am trying to build a metric that is comparable to the metrics.PrecisionAtRecall class. Therefore, I've tried to build a custom metric by extending the keras.metrics.Metric class.</p> <p>The original function is <em>WSS = (TN + FN)/N − 1 + TP/(TP + FN)</em> and this should be calculated at a certain recall value, f...
<p>If we follow the definition of the WSS@95 given by this paper :<a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1447545/" rel="nofollow noreferrer">Reducing Workload in Systematic Review Preparation Using Automated Citation Classification</a>, then we have</p> <blockquote> <p>For the present work, we have fixed...
tensorflow|keras|metrics
1
15,168
64,371,673
KeyError when using YOLOv3/Tensorflow detection
<p>Whenever the model I trained on my custom dataset detects a class in the image, I get this error output:</p> <pre><code>2020-10-14 19:47:45.924359: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'libcudart.so.10.1'; dlerror: libcudart.so.10.1: cannot open shared object...
<p>i think you missed something in your [pylession]code</p> <p>first you need to import..</p> <pre><code>from yolov3.yolov3 import Create_Yolov3 </code></pre> <p>and then ,</p> <pre><code>image_path = &quot;./IMAGES/[Your_images].jpg&quot; </code></pre> <p>and</p> <pre><code>yolo = Create_Yolov3(input_size=YOLO_INPUT...
python|tensorflow|object-detection|yolo
0
15,169
64,469,468
Iterate through dataframe to extract delta of a particular time period
<p>I have a file, df, that I wish to take the delta of every 7 day period and reflect the timestamp for that particular period</p> <p>df:</p> <pre><code>Date Value 10/15/2020 75 10/14/2020 70 10/13/2020 65 10/12/2020 60 10/11/2020 55 10/10/2020 50 10/9/2020 45 10/8/2020 40 10/7/2020 ...
<p>Don't iterate through the dataframe. You can use a <code>merge</code>:</p> <pre><code>(df.merge(df.assign(Date=df['Date'] - pd.to_timedelta('6D')), on='Date') .assign(Value = lambda x: x['Value_y']-x['Value_x']) [['Date','Value']] ) </code></pre> <p>Output:</p> <pre><code> Date Value 0 2020-1...
python|pandas|numpy|loops
2
15,170
48,936,094
Writing string to empty dataframe not working, but works in other dataframes, how to fix?
<p>I have created a dataframe on my local machine like so:</p> <pre><code>df1 = pd.DataFrame() </code></pre> <p>Next, I have added to columns to dataframe plus I want to assign a string to only one column. I am attempting to do this like so: </p> <pre><code>df1['DF_Name'] = 'test' df1['DF_Date'] = '' </code></pre> ...
<p>You need to add brackets, like:</p> <pre><code>df1 = pd.DataFrame() df1['DF_Name'] = ['test'] df1['DF_Date'] = [''] df1 </code></pre> <p>you can't assign a single value to a pd.Series. With the brackets, it's a list instead.</p>
python|pandas
1
15,171
48,899,255
delete all columns of a dimension except for a specific column
<p>I want to make a function which takes a n-dimensional array, the dimension and the column index, and it will return the (n-1)-dimensional array after removing all the other columns of that specific dimension.</p> <p>Here is the code I am using now</p> <pre><code>a = np.arange(6).reshape((2, 3)) # the n-dimensiona...
<pre><code>In [1]: arr = np.arange(6).reshape(2,3) In [2]: arr Out[2]: array([[0, 1, 2], [3, 4, 5]]) </code></pre> <p>Simple indexing:</p> <pre><code>In [3]: arr[:,0] Out[3]: array([0, 3]) </code></pre> <p>Or if you need to used the general <code>axis</code> parameter, try <code>take</code>:</p> <pre><code>...
python|numpy
2
15,172
48,967,362
Map dictionary values in Pandas
<p>I have a data frame (<code>df</code>) with the following:</p> <pre><code> var1 a 1 a 1 b 2 b 3 c 3 d 5 </code></pre> <p>And a dictionary: </p> <pre><code>dict_cat = { 'x' = ['a', 'b', 'c'], 'y' = 'd' } </code></pre> <p>And I want to create a new column called <code>cat</code> in which depending of the <co...
<p>You need swap keys with values to new <code>dict</code> and then use <code>map</code>:</p> <pre><code>print (df) var1 var2 0 a 1 1 a 1 2 b 2 3 b 3 4 c 3 5 d 5 dict_cat = {'x' : ['a', 'b', 'c'],'y' : 'd' } d = {k: oldk for oldk, oldv in dict_cat.items() for k in oldv} pr...
python|pandas
13
15,173
49,093,732
numpy.ndarray is object is not callable in my case
<p>I am a new user for python and I know there are a few discussions about this; however, I still cannot fix it.</p> <p>I execute my homework as the following code: </p> <p><a href="https://i.stack.imgur.com/cvWVm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cvWVm.png" alt="enter image descripti...
<p>Your ut variable is an array, try to change (line 69)</p> <pre><code>u = lambda t,x : ut(t) </code></pre> <p>to</p> <pre><code>u = lambda t,x : ut[t] </code></pre>
python|numpy
1
15,174
58,925,223
Sparse vectors for training data
<p>I have a training data like this:</p> <pre><code>x_train = np.random.randint(100, size=(1000, 25)) </code></pre> <p>where each row is a sample and thus we have 1000 samples.</p> <p>Now I need to have the training data such that for each of the sample/row there can be at max 3 non-zero elements out of 25.</p> <p>...
<p>I am assuming that you want to turn a majority of your data into zeros, except that 0 to 3 non-zero elements are retained (randomly) for each row. If this is the case, a possible way to do this is as follows.</p> <p>Code</p> <pre><code>import numpy as np max_ = 3 nrows = 1000 ncols = 25 np.random.seed(7) X = np....
python|numpy|tensorflow|machine-learning|pytorch
1
15,175
58,812,244
TensorFlow CondaVerificationError - Mixing Pip with Conda
<p>I'm running Anaconda 64 bit on Windows 10 and I've encountered a CondaVerificationError when I try installing TensorFlow 2.0 on one of my computers. I believe the error stems from mixing pip installations with conda installations for the same package. I originally installed then uninstalled TensorFlow with pip and t...
<p>Update:</p> <p>I reinstalled TensorFlow 2.0 with pip and even though it successfully installed, I was still facing issues when I tried to run my code. A file called cudart64_100.dll could not be located. I eventually managed to get my TF 2.0 code to run successfully by installing an older version of CUDA. I'm still...
python|windows|tensorflow|pip|conda
0
15,176
70,076,523
TypeError: unhashable type: 'list' when creating a new definition
<p>I'm creating a definition to calculate mean,sem and count for parameter 1, parameter 2 and the value. Each .mean(), .sem(), .count(), .groupby() all come from pandas library.</p> <pre><code>def mean_SEM_Count(para1,para2,value): mean=df.groupby([para1],[para2])[value].mean() SEM=df.groupby([para1],[para2])[v...
<p>There is necessary change:</p> <pre><code>df.groupby([para1],[para2]) </code></pre> <p>to:</p> <pre><code>df.groupby([para1,para2]) </code></pre> <p>Btw, here is possible use only <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>...
python|pandas|dataframe|typeerror|function-definition
1
15,177
56,420,867
Keras in TensorFlow cannot reinitialize a sequential model using config (KeyError: 'name')
<p>I build a sequential model as follows:</p> <pre><code>## build the model model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(32, activation='relu', batch_input_shape=(None, 8))) model.add(tf.keras.layers.Dense(32, activation='relu')) model.add(tf.keras.layers.Dense(1, activation=None)) </code></pre> <p>N...
<p>You have to use <code>model2 = tf.keras.Sequential.from_config(config)</code> with sequential models</p>
tensorflow|serialization|keras|tf.keras
3
15,178
56,187,689
Python Matlibplot DateFormat X Label Invisible
<p>I'm trying to plot the following csv data. The data is ticked at 1 minute interval:</p> <pre><code># cat futures-sample.txt | head 2019/05/16-09:15 27830 2031 2019/05/16-09:16 27815 995 2019/05/16-09:17 27829 961 2019/05/16-09:18 27848 663 2019/05/16-09:19 27873 869 2019/05/16-09:20 27847 854 2019/05/16-09:21 2782...
<p>Maybe your <code>Time</code> column is a string, you can use <code>parse_dates=['Time']</code> in your <code>read_csv</code>.</p> <pre><code>df = pd.read_csv('futures-sample.txt', names=['Time', 'HSIF', 'Volume'],parse_dates=['Time'] ,delim_whitespace=True) </code></pre>
python|pandas
0
15,179
56,423,435
How do I correct for errors in smoothing plotted data? (final data point is shifted)
<p>The final data point is shifted compared to the rest of the graph, included is a reference plot in green with no smoothing showing the intended final data point.</p> <p>I have tried smoothing the data using other methods such as scipy.</p> <pre><code>import tkinter import matplotlib.pyplot as plt import math as m ...
<p>Your box convolution function extends out of data range, so you see "edge effect". This is fundamental problem of convolution.</p> <p>You can get shortened output range <a href="https://www.numpy.org/devdocs/reference/generated/numpy.convolve.html" rel="nofollow noreferrer">with mode ‘valid’</a></p> <p>Also you ca...
python|numpy|matplotlib|math
1
15,180
55,699,769
How to groupby name and concat all reviews in python dataframe?
<pre><code>df = pd.read_csv('movie_lens') df1 = df.groupby([['name of movie','reviews']]) ##Groupby name of the movie and put all reviews for that movie into one row..# #name of movie.............reviews# #titanic...................good# #titanic...................bad# #titanic....................great# #superbad........
<p>You simply grouped by too many things. You want:</p> <pre><code>df1 = df.groupby(['name of movie'])['reviews'].apply(list) </code></pre> <p>Or, slightly simpler:</p> <pre><code>df1 = df.groupby('name of movie').reviews.apply(list) </code></pre> <p>Once you have a <code>list</code> of reviews, feel free to <code>...
python-3.x|dataframe|concatenation|pandas-groupby
1
15,181
55,921,900
How to output Pandas Data to JSON, with specific columns in an array
<p>I need to output some results from a Pandas dataframe to JSON, on a row by row basis. I've sorted out the export, that works fine, it's the fine details of making certain columns into an array. For example</p> <pre class="lang-py prettyprint-override"><code>Id customerId baseValue targetValue 1 Customer1 ...
<p>Have you tried:</p> <pre class="lang-py prettyprint-override"><code>df.to_json(orient="index") </code></pre>
json|python-3.x|pandas|dataframe
0
15,182
55,913,528
python pandas dataframe how to apply a function to each time period
<p>I have the following <code>dataframe</code>,</p> <pre><code>df = pd.DataFrame({'col1':range(9), 'col2': list(range(7)) + [np.nan] *2}, index = pd.date_range('1/1/2000', periods=9, freq='0.5S')) df Out[109]: col1 col2 2000-01-01 00:00:00.000 0 0.0 2000-01-01 00:00:00.500 1 ...
<p>Here is one way using <code>reindex</code> after dropna we reindex , then both of the columns become <code>NaN</code>, In this situation if we using <code>last</code> , we will not select any item from this row (correlated with your previous question )</p> <pre><code>df.dropna().reindex(df.index).resample('1s').las...
python|pandas|dataframe
0
15,183
64,899,106
How to extend Pandas base Styler template
<p>Hi so I'm working on writing a custom jinja template that inherits from <code>Pandas</code> base template.</p> <p>My default template looks as</p> <pre><code>{% extends &quot;html.tpl&quot; %} {% block table %} &lt;style type=&quot;text/css&quot; &gt; {% block default_table_styles %} #T_{{uuid}} th { ...
<p>So after a lot of reading I discovered the problem.</p> <p>Two things I learned, as I never worked with css/html before let alone jinja2 templates.</p> <p>If you look at the template that <code>Pandas</code> provides you'll see they have empty blocks such as <code>before_style</code> and <code>before_table</code> if...
pandas|jinja2|pandas-styles
1
15,184
40,029,777
Change Array of multi integer vectors to single value for each vector in Numpy
<p>I have an array below, which I want to make each row randomly have a single 1 or all zeros, but only the current 1 values can be converted to 0. I have a check below that was going to do this by seeing if there is a 1 in the row and if the summed value is greater or = to 0. I am hoping there is a simple approach to...
<p>You can randomly select per row the column you want to keep:</p> <pre><code>m, n = A.shape J = np.random.randint(n, size=m) </code></pre> <p>You can use these to create a new array:</p> <pre><code>I = np.arange(m) B = np.zeros_like(A) B[I,J] = A[I,J] </code></pre> <p>Or if you want to modify <code>A</code>, e.g....
python|numpy
0
15,185
40,006,169
Can this python function be vectorized?
<p>I have been working on this function that generates some parameters I need for a simulation code I am developing and have hit a wall with enhancing its performance.</p> <p>Profiling the code shows that this is the main bottleneck so any enhancements I can make to it however minor would be great.</p> <p>I wanted to...
<p>Here's a vectorized approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasted</code></a> summations -</p> <pre><code># Gather the elements sorted by the keys in (row,col) order of a dense # 2D array for both nn and nnn sidx0 = np.ravel_multi...
python|performance|python-2.7|numpy|vectorization
3
15,186
44,124,668
ValueError: Cannot feed value of shape (50,) for Tensor u'Placeholder_1:0', which has shape '(?, 10)'
<p>I'm a new guy in tensorflow,and I'm trying an experiment with my own .tfrecords files.Now I get something wrong in my code and I don't know what happend.Does anybody tell me how can I solve this problem </p> <pre><code>from color_1 import read_and_decode, get_batch, get_test_batch import cv2 import os import time ...
<p>Looks like <strong>label_batch</strong> on line 120 is has the value of the labels and not the 1-hot encodings. For example, it probably looks like a 1 dimensional array like this [1,3,4,0,6...] when instead it needs to be a 2 dimensional array of 1-hot encodings like this [ [0,1,0,0,0,0,0,0,0,0] , [0,0,0,1,0,0,0,0...
linux|tensorflow
1
15,187
41,207,014
How can I set index while converting dictionary to dataframe?
<p>I have a dictionary that looks like the below</p> <pre><code>defaultdict(list, {'Open': ['47.47', '47.46', '47.38', ...], 'Close': ['47.48', '47.45', '47.40', ...], 'Date': ['2016/11/22 07:00:00', '2016/11/22 06:59:00','2016/11/22 06:58:00', ...]}) </code></pre> <p>My purpose is to conver...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="noreferrer"><code>set_index</code></a>:</p> <pre><code>df = pd.DataFrame(dictionary, columns=['Date', 'Open', 'Close']) df = df.set_index('Date') print (df) Open Close Date ...
python|pandas|dictionary
37
15,188
40,784,315
Difference between scipy.leastsq and scipy.least_squares
<p>I was wondering what the difference between the two methods <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html" rel="noreferrer"><code>scipy.optimize.leastsq</code></a> and <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html" rel="nor...
<p>From the docs for <code>least_squares</code>, it would appear that <code>leastsq</code> is an older wrapper.</p> <blockquote> <p><strong>See also</strong></p> <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy.optimize.leastsq" rel="noreferrer">leastsq</a> &ems...
python|numpy|optimization|scipy|least-squares
5
15,189
53,941,162
Modifying values in a dataframe
<p>I am trying to iterate through the rows of a dataframe and modify some values as I iterate. The dataframe looks like this:</p> <pre><code> Time WindSpeed SkyCover Temp DewPt RH Press Precip 3 21:53 11 Light Snow -1.7 -6.1 72% 1003.1 0 4 20:53 N 11 Mostly Cloudy ...
<p>Use <code>apply</code>:</p> <pre><code>df.WindSpeed = df.WindSpeed.apply(lambda x: 1 if x == 'Calm' else re.findall(r'[0-9]+',x)[0]) </code></pre>
python|pandas|dataframe
3
15,190
54,159,160
Tensorflow error - the argument cell is not an rnn cell, property is missing, method is required, is not callable
<p>Im trying to train a text summarization model and I'm getting this error:</p> <blockquote> <p>The argument cell is not an RNN cell: 'output_size' property is missing, 'state_size' property is missing, either 'zero_state' or 'get_initial_state' method is required, is not callable.</p> </blockquote> <p>I'm not...
<p>After some time looking at this I decided to downgrade to Tf 1.11 and looks like that fixed everything. </p>
python|python-3.x|tensorflow
0
15,191
65,978,327
How can I store the index date (last row) from a panda dataframe in a variable?
<p>I have a panda dataframe with the following rows and columns:</p> <p><a href="https://i.stack.imgur.com/XtCXe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XtCXe.png" alt="enter image description here" /></a></p> <p>I need the date in the last row of the dataframe for plotting out a chart. How c...
<p>Your last index is</p> <pre><code>df1.index[-1] </code></pre> <p>You can store it in a variable.</p> <p>If you want to get let's say the Open of this last index, you can just type</p> <pre><code>df1.Open[-1] </code></pre> <p>If you want to use the variable and filter it (or if it's not the last index):</p> <pre><cod...
python|pandas|dataframe|indexing|time
1
15,192
66,199,637
How to get the count of dataframe rows at 75% or max
<p>The command below shows some details about the dataframe.</p> <pre><code>df.describe() </code></pre> <p>It gives details about <strong>count, mean, std, min, 25%, ...</strong></p> <p>Is there any way to get the count of rows in a dataframe at 75% or 25%?</p> <p>Thanks.</p>
<ul> <li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.quantile.html" rel="nofollow noreferrer"><code>pandas.Series.quantile</code></a> to determine the value for the given quantile of the selected column. <ul> <li><code>.quantile</code> has the benefit of being able to specify a...
pandas|dataframe
3
15,193
66,136,819
Subplot with Time Series Data
<p>Morning! I am trying to create two subplots (1 row and 2 columns). But am running into some issues.</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns fig = plt.figure(figsize=(25,10)) ax1 = fig.add data.Loc2.resample('W').mean().rolling(window=3).mean().plot() plt.title(&quot;Mean weekly windspee...
<p>I suggest using the object oriented API of matplotlib. This is what I would do:</p> <pre><code>fig, axes = plt.subplots(ncols=2, figsize=(25,10)) data.Loc2.resample('W').mean().rolling(window=3).mean().plot(ax=axes[0]) axes[0].set_title(&quot;Mean weekly windspeed at Loc2&quot;) data.Loc2.resample('M').mean().rolli...
python|pandas|matplotlib
0
15,194
52,811,935
With pytorch module,will computation graph be overrode when forward() was invoke multiple times before backward()?
<p>I found a line of code:</p> <pre><code>out_a, out_p, out_n = model(data_a), model(data_p), model(data_n) </code></pre> <p>in:<a href="https://github.com/liorshk/facenet_pytorch/blob/master/train_triplet.py" rel="nofollow noreferrer">https://github.com/liorshk/facenet_pytorch/blob/master/train_triplet.py</a></p...
<p>No, the graph is not over-ridden by different calls to forward. Every time you call forward, computations are added to the graph and hence gpu consumption increases.</p> <p>When you call <code>model.zero_grad()</code> graphs are cleared. </p>
pytorch
0
15,195
52,842,977
read csv to pandas retaining values as it is
<p>I am trying to read a csv and get it into a dataframe but I want to retain the values of columns. </p> <p>For eg. my first column has values like <code>001234</code>, <code>003462</code> in the csv file but the dataframe interprets it as <code>1234</code>, <code>3462</code>, etc. How do I retain the '00' at the fro...
<p>Try this:</p> <pre><code>df = pd.read_csv(file_path, dtype=str) </code></pre>
python|python-3.x|pandas
2
15,196
52,686,489
Equivalent 'spread' and 'gather' in R/tidyverse in python/pandas?
<p>for example. Data A:</p> <pre><code>y female male 1 2 3 4 5 6 </code></pre> <p>I want to 'gather' it to this:</p> <pre><code>y gender value 1 female 2 1 male 3 4 female 5 4 male 6 </code></pre> <p>It's easy in R. What about python pandas?</p>
<p>You should try melt , in the given data , the opposite(spread version is called cast), these melt and cast functions are very similar to R's reshape2:</p> <pre><code>import pandas as pd pd.melt(dt, id_vars="y") </code></pre> <p>Where dt is your input table</p> <p><strong>Output</strong>:</p> <pre><code>#y v...
python|pandas
10
15,197
46,360,690
Python, Pandas to remove rows with specific value in designated columns
<p>An Excel spreadsheet looked like below.</p> <p><a href="https://i.stack.imgur.com/6a1Zl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6a1Zl.jpg" alt="enter image description here"></a></p> <p>With Pandas, I want to remove the columns “Project C” and “Project E”, and all rows with value “XX” in...
<p>If your column names did not have whitespace, you could have done something along the lines of:</p> <pre><code>results1 = results1.query("ColumnName != 'XX'") </code></pre> <p>or alternatively inplace:</p> <pre><code>results1.query("ColumnName != 'XX'", inplace=True) </code></pre> <p>Alas, they do. Now you can e...
python|excel|pandas|dataframe
1
15,198
46,195,201
Pass additional parameter in call function of custom keras layer
<p>I created a custom keras layer with the purpose of manually changing activations of previous layer during inference. Following is basic layer that simply multiplies the activations with a number.</p> <pre><code>import numpy as np from keras import backend as K from keras.layers import Layer import tensorflow as tf ...
<p>You should work the same way the <a href="https://github.com/fchollet/keras/blob/master/keras/layers/merge.py" rel="nofollow noreferrer">Concatenate</a> layer does. (Search for <code>class Concatenate(_Merge):</code> in that link). </p> <p>These layers taking multiple inputs rely on the inputs (and the input shapes...
python|tensorflow|deep-learning|keras
3
15,199
58,565,246
How to replace exact matches from a list of strings with special characters python?
<p>I am removing all exact matches in my list_of_strings from a pandas dataframe column. I don't really understand the re.escape that is being used, however. I want to make sure this code will remove ALL matches no matter what type of character is present in my list_of_strings variable and in my dataframe column. Wh...
<p>In regex, some symbol have a meaning and trigger some functionality, when you want to explicitly match the symbol without triggering its function, you escape it.</p> <p>Now re.escape is simply a method to avoid escaping a list of character manually.</p> <p>instead of escaping (adding <code>\</code>) manually like ...
python|regex|pandas
1