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
358,100
61,539,612
change a string into column with conditions in pandas
<p>I have a dataframe such as </p> <pre><code>Col1 Col2 G1 element.1:410022-411732(+):element_element G1 element.2:678-10098(-):element_element G1 element.4:6868-9899(-):element_element G1 element.1:789-1222(+):element_element G2 element.2:890-1220(-):element_element G3 element.1:12-678(+):element_element G3 element.1...
<p>A "pandasic" solution with vectorized operations:</p> <pre><code>import pandas as pd from io import StringIO data = StringIO("""Col1,Col2 G1,element.1:410022-411732(+):element_element G1,element.2:678-10098(-):element_element G1,element.4:6868-9899(-):element_element G1,element.1:789-1222(+):element_element G2,ele...
python|regex|pandas
0
358,101
61,503,398
change the shape of a kernel of a convolution layer in keras
<p>if i have a kernel size of 3X3, it will look at one pixel around the pixel it is focused on. for example, for the kernel:</p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>it will use 1-9 to produce a value at location 5 at the feature map. is there a way to make it so that it will produce a value at locati...
<p>Implementing your own layer where you manipulate the kernel and applying zero padding on left and top should achieve what you want:</p> <pre><code> 0 0 0 0 1 2 3 0 1 2 3 4 5 6 -&gt; 0 4 5 6 7 8 9 0 7 8 9 </code></pre> <p>And kernel will consider:</p> <pre><code>f f f ...
tensorflow|keras|deep-learning|conv-neural-network
1
358,102
61,309,832
How to calculate average of values of a column for a particular value in another column?
<p>I have a data frame that looks like this.</p> <p><a href="https://i.stack.imgur.com/3wotl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3wotl.png" alt="enter image description here"></a></p> <p>How can I get the average doc/duration for each window into another data frame? </p> <p>I need it i...
<p>Use <code>.groupby()</code> method and then compute the mean:</p> <pre><code>import pandas as pd df = pd.DataFrame({'10s_windows': [304, 374, 374, 374, 374, 3236, 3237, 3237, 3237], 'doc/duration': [0.1, 0.1, 0.2, 0.2, 0.12, 0.34, 0.32, 0.44, 0.2]}) new_df = df.groupby('10s_windows').mean() </code></pre> <p>Wh...
pandas|average|mean
1
358,103
61,246,278
Pandas : converting a period from an 'object' type to a 'period' type, to be able to make calculations
<p>I have just downloaded a basic file from NOAA (url : '<a href="https://www.ncdc.noaa.gov/cag/time-series/global/globe/land_ocean/p12/12/1880-2020.csv" rel="nofollow noreferrer">https://www.ncdc.noaa.gov/cag/time-series/global/globe/land_ocean/p12/12/1880-2020.csv</a>') and there is this 'Period' which is currently a...
<p>Use custom function, edited function from <a href="https://pandas.pydata.org/docs/user_guide/timeseries.html#representing-out-of-bounds-spans" rel="nofollow noreferrer">docs</a>:</p> <pre><code>df['Period']=df['Period'].apply(lambda x: pd.Period(year=x // 100, month=x % 100, freq='M')) print (df) Period Discr ...
python|pandas
0
358,104
61,506,961
Why do the keras loss functions reduce the dimensionality by one?
<p>When computing the loss between y_true and y_pred, the keras loss functions reduce the dimensionality by one. For example, when training a network on pairs of 64x64 greyscale images with batch size = 8, the shape of y_true and y_pred would be (8, 64, 64). The keras loss functions will produce a loss tensor with shap...
<p>I wondered the same thing. I believe, Keras assumes your data to have the following dimensions: [batch, W, H, n_classes] which means averaging over axis=-1 means averaging the loss over all different classes. However, in your case you do not have that dimension because you presumably do a binary classification in a ...
python|tensorflow|keras|loss-function
2
358,105
61,373,860
Is vectorization a hardware/framework specific feature or is it a good coding practice?
<p>I am trying to wrap my head around vectorization (for numerical computing), and I'm coming across seemingly contradictory explanations:</p> <ul> <li><p>My understanding is that it is a feature built into low-level libraries that takes advantage of parallel processing capabilities of a given processor to perform ope...
<p>Vectorization can mean different things in different contexts. In <code>numpy</code> we usually mean using the compiled numpy methods to work on whole arrays. In effect it means moving any loops out of interpreted Python and into compiled code. It's very specific to <code>numpy</code>.</p> <p>I came to <code>num...
python|performance|numpy|parallel-processing|vectorization
5
358,106
61,447,946
Pandas conditional column returning the opposite?
<p>I want to add a third column on a Pandas dataframe which is a conditional, using info from the second if the first is NaN, and from the first in any other cases.</p> <p>When i use the following code, it simply doesnt work. BUT, if i change the == to != it works (which didnt make any sense to me since its asking the...
<p><code>NaN</code> value a special constant, to validate if something is <code>NaN</code> you need to use <code>pandas.isnan</code> or <code>numpy.isnan()</code>. Another solutions is using <code>numpy.where()</code>:</p> <pre><code>import numpy as np result['Launch year (final)'] = np.where(np.isnan(result['Launch y...
python|pandas|dataframe|null|conditional-statements
0
358,107
61,415,344
Can't install geopandas with anaconda because of conflicts
<p>I'm a beginner and I try to follow a tutorial. So I install a anaconda and next step I should install geopandas but I get this messages:</p> <pre><code>conda install geopandas Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. Retrying with flexible solv...
<p>Maybe trivial for more experienced, but I still struggle with this. I got same when naively trying to install it using the base, if you're installing using the base (root) environment, you can't. (I don't know why.) You need to create your environment by clicking 'Environments' and in 'Create' on Anaconda Navigator ...
python|anaconda|conda|geopandas
5
358,108
61,607,656
Feeding integer CSV data to a Keras Dense first layer in sequential model
<p>The documentation for <a href="https://www.tensorflow.org/guide/data#consuming_csv_data" rel="nofollow noreferrer">CSV Datasets</a> stops short of showing how to use a CSV dataset for anything practical like using the data to train a neural network. Can anyone provide a straightforward example to demonstrate how to ...
<p><a href="https://stackoverflow.com/questions/37091899/how-to-actually-read-csv-data-in-tensorflow">This question</a> may provide some help... although the answers mostly relate to Tensorflow V1.x</p> <p>It is likely that CSV Datasets are not required for this task. The data size indicated will probably fit in memory...
tensorflow|keras|tensorflow-datasets
-1
358,109
61,532,569
How can i count special character like '?' for each column in my DataFrame in Pandas?
<p>This seems like an easy and simple task, however i'm looking for basic and comprehensive answer to count my missing values in data which they're coded like this '?' character. </p> <p>My Data: <a href="https://i.stack.imgur.com/hwc1p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hwc1p.png" alt=...
<p>You included the counter variable inside the loop, meaning that every loop you are resetting it to 0. All you have to do is move it outside the loop like this;</p> <pre><code>counter = 0 for i in data.columns: if data[i].dtype == '?' counter += 1 </code></pre>
python|pandas|special-characters
0
358,110
61,319,196
How to specify a row delimiter in pandas read_csv()?
<p>I would use a different row delimiter than <code>\n</code> with <code>pandas.read_csv()</code>. Does anyone know how to do that?</p> <p>In the documentation of <code>read_csv()</code>, I found nothing related, but in the <code>to_csv()</code> page, I found the parameter <code>line_terminator</code>.</p> <p>How may...
<p>Here is an Example:</p> <p>File: a.csv</p> <pre><code>hello,world:hell,worl:hel,wor:he,wo </code></pre> <pre><code>a = pd.read_csv('a.csv', lineterminator=':') print(a) </code></pre> <p>Output:</p> <pre><code> hello world 0 hell worl 1 hel wor 2 he wo </code></pre>
python|pandas
3
358,111
68,858,096
TF-Agents error: TypeError: The two structures do not match: Trajectory vs. Trajectory
<p>I am building a PPO agent side by side with the <a href="https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/1_dqn_tutorial.ipynb" rel="nofollow noreferrer">TF-Agents DQN tutorial</a>. The idea was checking the basics structures needed for a simple tf-agent to work, and adapting it ...
<p>I think the RandomTFPolicy is returning a Trajectory without <code>'policy_info': DictWrapper({'dist_params': DictWrapper({'logits': .})}),</code></p> <p>Maybe you should initialize it with <code>emit_log_probability=True</code> :</p> <pre class="lang-py prettyprint-override"><code>random_data_policy = random_tf_pol...
python|tensorflow|reinforcement-learning|tensorflow-agents
1
358,112
68,515,170
aggregating and counting in pandas
<p>for the following df</p> <pre><code>group participated A 1 A 1 B 0 A 0 B 1 A 1 B 0 B 0 </code></pre> <p>I want to count the total number of values in the participated column for each value in the group column (groupby-count) and then fi...
<p>You could follow the groupby with an aggregation as below:</p> <pre><code>grp_df = df.groupby('group', as_index=False).agg({'participated':['count','sum']}) grp_df.columns = ['group','tot_participated','1s'] grp_df.head() </code></pre> <p>The caveat to using .agg with multiple aggregation functions on the same colum...
python|pandas|group-by|count
1
358,113
68,513,190
scraping with BS4
<p>code generates empty file. Possibly missing correct div/tag entries(?). Trying to scrape multiple pages on one site.</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0...
<p>You have a trailing whitespace:</p> <p>Replace:</p> <pre><code>questions = soup.find_all('div', {'class': 'main grid '}) # &lt;- HERE &quot; '&quot; </code></pre> <p>By:</p> <pre><code>questions = soup.find_all('div', {'class': 'main grid'}) </code></pre> <p>Now you have another problem:</p> <pre><code>AttributeErr...
python|pandas
0
358,114
68,681,452
Update a df column based on three other columns values using a function
<p>Evening All,</p> <p>I would like to build a function (<code>Get_Trading_Book_Based_On_Other_Fields</code>) which updates a single column (<code>trading_book</code>) based on three columns inputs. My code:</p> <pre><code>def Get_Trading_Book_Based_On_Other_Fields(Ticker_Str, Code_Dtr, cust_cdr_display_name_Str): ...
<p>One solution is to use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html#numpy-select" rel="nofollow noreferrer"><code>np.select</code></a>:</p> <pre class="lang-py prettyprint-override"><code>mapping = { &quot;ACT&quot;: &quot;ZZZZGOVT&quot;, &quot;ACG&quot;: &quot;ZZZZGOVT&quot;, ...
python|pandas|dataframe|lambda
1
358,115
68,542,933
Assigning values to df col by col not working
<p>Trying to assign values in the following fashion:</p> <pre><code> cols = ['A', 'B', 'C'] df = pd.DataFrame(columns=cols) df['A'] = '1' df['B'] = '2' df['C'] = '3' </code></pre> <p>but <code>df</code> seems empty:</p> <pre><code> print(df.values) &gt;&gt;&gt; [] </code></pre> <p>What am I missin...
<p>One idea is specified index in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p> <pre><code>df = pd.DataFrame(columns=cols) df.loc[0, 'A'] = '1' df.loc[0, 'B'] = '2' df.loc[0, 'C'] = '3' print (df) A B C...
python|pandas
2
358,116
68,475,869
How to understand the index of np.array
<p>I am learning python numpy.array and am confused about how the index works. Let's see I have the following 3x4 2D array:</p> <pre><code>A = np.array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9,10,11,12]]) </code></pre> <p>If I want to extract the 1 from this array, I need to input the index of tha...
<p>In B, you are only giving one index for a 2 dimensional array which is <code>[0,0]</code>. So it will return the element in the first dimension of the index given (0 and 0 here).</p> <p>So, for the first index (which is 0) it will return the first element in the first dimension which is <code>[1,2,3,4]</code> and i...
arrays|numpy-ndarray
0
358,117
68,611,701
create a summary table with count values
<p>my df looks like</p> <pre><code>group value A 1 B 1 A 1 B 1 B 0 B 0 A 0 </code></pre> <p>I want to create a df</p> <pre><code>value 0 1 group A a b B c d </code></pre> <p>where a,b,c,d are the counts of 0s and 1s in groups A and B respect...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html#pandas-crosstab" rel="nofollow noreferrer"><code>pd.crosstab</code></a>:</p> <pre><code>pd.crosstab(df['group'], df['value']) </code></pre> <p>Output:</p> <pre><code>value 0 1 group A 1 2 B 2 2 </code></pre>
python|pandas|group-by|count|aggregate-functions
3
358,118
68,738,464
Pandas agg and listagg at the same time
<p>I want to <code>AGG</code> operations on column <code>B</code> and <code>C</code>, while using <code>LISTAGG</code> on column <code>D</code>.</p> <p>Currently I do <code>groupby</code> twice - once for <code>LISTAGG</code> and once for <code>AGG</code> - aftewards I join the two resulting dataframes.</p> <p>I was wo...
<p>Simply include 'D' column in the aggrigration:</p> <pre><code>df=df.groupby('A',as_index=False).agg({'B': 'sum', 'C': 'min','D':list}) </code></pre> <p>output of df:</p> <pre><code> A B C D 0 1 43 8 [x, y, y, z] 1 2 23 10 [w, v] 2 3 14 0 [k] </code></pre>
python|pandas
3
358,119
68,535,933
How to convert vertical pandas table of 2 columns to horizontal table based on common ID value in python
<pre><code>df1 = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two', 'two'], 'bar': ['A', 'B', 'C', 'A', 'B', 'C']}) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>foo</th> <th>bar</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>one</td> <td>A</...
<p>We can enumerate groups with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby cumcount</code></a> and use those as the pivot columns then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Da...
python|pandas|dataframe|pivot|transpose
6
358,120
68,791,821
ImportErrorWhenRunningHook: pyinstaller failed to import module _pyinstaller_hooks_0_pandas_io_formats_style required for module
<p>I want to create an .exe file and get this error: Failed to import module _Pyinstaller_hooks_0_pandas_io_formats_style required for module C:xxxxxx\site-packages\Pyinstaller\hooks\hook-pandas.io.format.style.py.</p> <p>I am not familiar with this subject at all and couldt find anything that could resolve the issue b...
<p>This happened when freezing pandas inside <code>conda</code> environment using <code>pyinstaller</code>.</p> <p>I had pandas installed using conda environment and also using pip like <code>pip install pandas</code>.</p> <p>I removed the pip version and installed using <strong>conda</strong>, and that worked!</p> <pr...
python|pandas|pyinstaller|hook|exe
0
358,121
68,637,628
Complex link between 2 dataframes
<p>I have 2 dataframes. One first is my reference</p> <pre><code>df_ref ID REF VALUE A 1 12 A 2 36 A 3 95 B 1 54 B 2 67 B 3 81 C 1 89 C 2 123 C 3 14 </code></pre> <p>And the second is my restricted :</p> <pre><code>df_restrict ID V1 V2 A 1 2 B 3 2 C 2 1 </cod...
<p>We can pivot <code>df_ref</code> to reshape, then set the index of <code>df_restrict</code> to <code>ID</code>, then transpose and replace the the values from the reshaped <code>df_ref</code></p> <pre><code>r = df_ref.pivot('REF', 'ID', 'VALUE') df_restrict.set_index('ID').T.replace(r).T </code></pre> <hr /> <pre><c...
python|python-3.x|pandas|dataframe
5
358,122
68,676,382
Fast updating MySQL Table based on NumPy Array
<p>Good morning everbody,</p> <p>I hope you are all well and that you are looking forward to a great weekend!</p> <p>I've a 2D numpy array containing 2 cols and approximatly 6000 rows [col1 = name = identifiert for where-clause ; col2 = value for column val]: <code>x = np.array([['a', '2'], ['b', '2'] , ['c', '1']])</c...
<p>This is what <code>executemany</code> is for:</p> <pre><code>cur.executemany( &quot;UPDATE test_table SET value=? WHERE Name=?&quot;, x ) </code></pre> <p>Now, that assumes &quot;value&quot; is first and &quot;name&quot; is second. You may need to rearrange your array columns to make that work.</p>
python|mysql|numpy|sql-update|mysql-python
1
358,123
68,498,651
Convert timestamp string to Timestamp('yyyy-mm-dd H:M:S+0000', tz='UTC')
<p>I have a timestamp string (end_time = '2021-07-22T14:00:00Z') and I need to convert it to a timestamp in this format: Timestamp('2021-07-22 14:00:00+0000', tz='UTC').</p> <p>This is my code to convert str to datetime, but the output is not what I really want to be:</p> <pre><code>end_time = '2021-07-22T14:00:00Z' en...
<p>You're almost done. All that remains is to run</p> <pre><code>end_time = pd.Timestamp(end_time, tz='UTC') </code></pre>
pandas|string|datetime|timestamp|strptime
1
358,124
68,461,204
Continual pre-training vs. Fine-tuning a language model with MLM
<p>I have some custom data I want to use to <em><strong>further pre-train</strong></em> the BERT model. I’ve tried the two following approaches so far:</p> <ol> <li>Starting with a pre-trained BERT checkpoint and continuing the pre-training with Masked Language Modeling (<code>MLM</code>) + Next Sentence Prediction (<c...
<p>The answer is a mere difference in the terminology used. When the model is trained on a large generic corpus, it is called 'pre-training'. When it is adapted to a particular task or dataset it is called as 'fine-tuning'.</p> <p>Technically speaking, in either cases ('pre-training' or 'fine-tuning'), there are update...
deep-learning|nlp|huggingface-transformers|bert-language-model|pre-trained-model
8
358,125
68,547,529
Handle batch size in custom data augmentation layer - tensorflow
<p>I have implemented this simple data augmentation layer, basically it rotates images by a specific angle (I know it can be done via ImageDataGenerator, but it is just to explain the problem).</p> <pre class="lang-py prettyprint-override"><code> class RandomRotation(tf.keras.layers.Layer): def __init__(sel...
<pre><code>tf.config.run_functions_eagerly(True) </code></pre> <p>as first row of the script solved the problem.</p>
tensorflow|layer|batchsize
0
358,126
68,532,510
Whats the purpose of torch.positive?
<p>From the <a href="https://pytorch.org/docs/stable/generated/torch.positive.html#torch.positive" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p><code>torch.positive(input)</code> → <code>Tensor</code></p> <p>Returns <code>input</code>. Throws a runtime error if input is a bool tensor.</p> </blockquo...
<p>It seems like pytorch added <code>pytorch.positive</code> <a href="https://github.com/pytorch/pytorch/pull/55891" rel="nofollow noreferrer">in parity with <code>numpy</code></a> which has a <a href="https://numpy.org/doc/stable/reference/generated/numpy.positive.html" rel="nofollow noreferrer">function of the same n...
python|pytorch
3
358,127
68,646,277
How to split string into two strings base on delimiter in a dataframe
<p>I have a dateframe that contains a list of file names, it looks like this below</p> <pre><code>fname ill_2_uctry.pdf ell_23_uctry.pdf fgy_4_uctry.pdf : : : hilll_234_uctry.pdf </code></pre> <p>I want to split the strings from the fname column into a new name, which should look like this below</p> <pre><code>fname ...
<p>Using <code>str.extract</code>:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;name&quot;] = df[&quot;fname&quot;].str.extract(r'^([^_]+_[^_]+)') </code></pre> <p><a href="https://regex101.com/r/CsvXNR/1" rel="nofollow noreferrer">Here is demo</a> showing that the regex logic is working correctly.</p>
python|pandas|split
2
358,128
68,613,694
Parse error when trying to remove time and change date format?
<p>I am trying to remove time and change format of my dates in my social media dataset so it is compatible with my stock data when I merge both datasets.</p> <p>This my social media dataset sample:</p> <pre><code>0 id created_at 1 1 7:51 PM ET Fri, 17 July 2020 2 2 7:33 PM ET Fri, 17 ...
<p>Split on <code>, </code> and keep the second part (the date) and convert it to a datetime with <code>pd.to_datetime</code>:</p> <pre><code>&gt;&gt;&gt; pd.to_datetime(df['created_at'].str.split(', ').str[1]) 1 2020-07-17 2 2020-07-17 4 2020-07-17 5 2020-07-17 3076 2017-12-26 3077 2018-09-20 3...
python|pandas|date|parsing|time
0
358,129
68,588,414
How to design a CNN in Keras for data of dimensions (2505,10)?
<p>I am designing a neural network for the classification of resting-state EEG signals. I have preprocessed my data such that each subject is characterized by a table consisting of 111 channels and their readings over 2505 timesteps. As a measure of dimensionality reduction, I clustered the 111 channels into the 10 lob...
<p>To have a Conv2D model your train data, in an image processing perspective, needs to be of 4 dimension (N_observatoion, nrows, ncolumns, nchannels). Therefore, you have to reshape your features accordingly as per your domain knowledge to make it meaningful:</p> <pre><code>X_train = np.array(X_train).reshape(253, 250...
python|pandas|tensorflow|keras|neural-network
0
358,130
68,838,858
Filtering on a pandas column which is the difference between 2 dates
<p>I have a pandas table which shows 2 dates and the duration between them:</p> <pre><code>| date1 | date2 | duration | +------------+------------+----------+ | 10/04/2018 | 15/05/2018 | 5 days | | 23/04/2018 | 28/04/2018 | 5 days | | 27/11/2018 | 28/11/2018 | 1 days | +------------+------------+-------...
<p>You can use <code>.dt.days</code> accessor on <code>timdelta</code> values to get number of days as integer value, then you can compare it against another number.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df.query('duration.dt.days &lt; 5') date1 date2 duration 2 2018-11-27 2018-11...
python|pandas
2
358,131
68,536,630
Is it possible to use a custom generator to train multi input architecture with keras tensorflow 2.0.0?
<p>With TF 2.0.0, I can train an architecture with one input, I can train an architecture with one input using a custom generator, and I can train an architecture with two inputs. But I can't train an architecture with two inputs using a custom generator.</p> <p>To keep it minimalist, here's a simple example, with no g...
<pre><code>from tensorflow.python.keras.utils.data_utils import Sequence class generator(Sequence): def __init__(self,filename,batch_size): data = pickle.load(open(filename,'rb')) self.X1 = data['X1'] self.X2 = data['X2'] self.y = data['y'] self.bs = batch_size def ...
python-3.x|keras|generator|tensorflow2.0
1
358,132
68,651,622
EarlyStopping not stop training
<p>As the title suggests I am training my IRV2 network using the following EarlyStopping definition:</p> <pre><code>callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, mode=&quot;auto&quot;) </code></pre> <p>However, the training doesn't stop when I get three equal values of val_loss:</p> <pre><...
<p>That happens because the loss is actually decreasing, but by a value that is very low. If you don't set the min_delta in the early stopping callback, the training will consider a negligible improvement as an actual improvement. You can solve the problem by simply adding min_delta argument=0.001:</p> <pre><code>tf.ke...
python|tensorflow|keras
2
358,133
68,869,810
Three pandas columns to nested dictionary
<p>I have a dataframe with 3 columns</p> <pre><code> c1 c2 c3 0 A C 1 1 A D 2 2 B E 3 3 B E 4 </code></pre> <p>I would like to turn it into a nested dictionary, so something like <code>{'A': {'C': [1], 'D': [2]}, 'B': {'E': [3,4]}</code></p> <p>How should I do this? Thanks!</p>
<p>Try with <code>groupby</code> and <code>to_dict</code>:</p> <pre><code>&gt;&gt;&gt; df.groupby('c1').apply(lambda x: pd.DataFrame(zip(x['c2'], x['c3'])).groupby(0)[1].apply(list).to_dict()).to_dict() {'A': {'C': [1], 'D': [2]}, 'B': {'E': [3, 4]}} &gt;&gt;&gt; </code></pre>
python|pandas
2
358,134
68,866,101
How can I fix this NotImplementedError in python class module while working in pytorch framework?
<p>Hello everyone I am working on CIFAR10 dataset using pytorch. I have developed a model which works absolutely fine but the main problem occurrs while runing the following code:</p> <pre><code>import time start_time=time.time() epochs=5 train_losses=[] test_losses=[] train_correct=[] test_correct=[] for i in range(...
<p>Your model class needs to implement a forward method. See <a href="https://pytorch.org/tutorials/beginner/examples_nn/two_layer_net_module.html" rel="nofollow noreferrer">the PyTorch Example on Subclassing</a> to see an example.</p>
class|pytorch|computer-vision|conv-neural-network|pytorch-dataloader
0
358,135
68,550,354
How do I find the indices of the row and the column for the maximum value in a Pandas dataframe?
<p>I have a large Pandas dataframe and I want to find out the column and row where the maximum value is (in the entire dataframe). Unfortunately, <code>df.idxmax()</code> only returns the index for the highest value per row/column, not for the entire dataframe. Is there a way to do this?</p>
<p>Using numpy, you can try:</p> <pre><code>import numpy as np &gt;&gt;&gt; np.unravel_index(np.argmax(df.values), df.shape) </code></pre>
python|pandas|dataframe
1
358,136
68,646,792
I need to convert a nested array of dictionary to new Dataframe in pandas python
<pre><code>My_dict = \ {0: '[{&quot;accountType&quot;: &quot;Consumer Loan&quot;, &quot;currentBalance&quot;: &quot;9,250&quot;, &quot;paymentHistory1&quot;: &quot;000 000 000 000 000 000 &quot;, &quot;dateofLastPayment&quot;: &quot;02/09/2017&quot;, &quot;ownershipIndicator&quot;: &quot;Individual&qu...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/version/1.1.3/reference/api/pandas.read_json.html" rel="nofollow noreferrer"><code>pandas.read_json</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pandas.concat</code></a>:</p> <...
python|json|pandas|dataframe|dictionary
1
358,137
68,868,162
Filter Pandas dataframe by column name on regex patterns using str.contains
<p>I want to find columns in a dataframe that match a string pattern. I specifically want to find two parts, firstly find a column that contains &quot;WORDABC&quot; and then I want to find the column that also is the &quot;1&quot; value of that column (i.e. &quot;WORDABC1&quot;). To do this I have been using the <a hre...
<p>Try <code>.filter</code> with <code>regex=</code> parameter:</p> <pre class="lang-py prettyprint-override"><code>print(df.filter(regex=r&quot;WORDABC9(?=[^\d]|$)&quot;)) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> WORDABC9N123 0 13 1 14 2 15 </co...
python|regex|pandas|dataframe
4
358,138
68,819,852
How to use trained model inside custom loss function in tensorflow?
<p>I am trying to use an already NN-based Trained model inside the custom loss function in tensorflow. But I am getting an error while using this custom loss function inside another model. Can someone help me to figure out what’s the mistake that I am doing while designing this custom loss function.</p> <p><strong>The ...
<p>You could try loading the model outside of the loss function and only passing the weights. To pass an extra argument to the custom loss function, you can wrap it inside another function like it is explained here: <a href="https://medium.com/@Bloomore/how-to-write-a-custom-loss-function-with-additional-arguments-in-k...
python|tensorflow|loss-function
0
358,139
68,818,695
Add column entry if certain date, Pandas
<p>I am using the dataframe below and am attempting to add a new column containing a Note depending on a few conditions.</p> <p>Condition 1: Spend = Y</p> <p>Condition 2: Ccy= Mgd Ccy</p> <p>Condition 3: If the date is today+1 add 'Note 1' to a notes column, if the date is today+2 add 'Note 2' to a notes column</p> <p>...
<p>You can try this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Amount': [1, 2, 3], 'Ccy': ['EUR', 'EUR', 'CHF'], 'Mgd Ccy': ['EUR', 'EUR', 'EUR'], 'Spend': ['Y', 'Y', 'Y'], 'Date':pd.date_range(&quot;2021-08-17&quot;, periods=3, freq=&quot;D&quot;)}) df = df[(df['Date'] == (pd.datetime....
python|pandas|date|datetime
0
358,140
68,557,907
How to move values to another column based on conditions of other columns?
<p>In my data set some of the data has been inputted into the wrong column. Specifically, some values for 'power' have ended up in the 'r' column and the only way to identify them is that 'theta', 'z' and 'power' are all NaN but 'r' has a numeric value. How do I identify these rows and then move these values from 'r' t...
<p>I think what you are looking for is the following:</p> <pre><code>m = ((df.theta.notnull()) | (df.z.notnull()) | (df.power.notnull())) df.power.where(m, df.r, inplace=True) df.r.where(m, None, inplace=True) </code></pre> <p>Like this you first create a series <code>m</code>, identifying all those lines where theta, ...
python|pandas|dataframe|data-cleaning
0
358,141
68,700,008
Difference between just reshaping and reshaping and getting transpose?
<p>I'm currently studying CS231 assignments and I've realized something confusing. When calculating gradients, when I first reshape x then get transpose I got the correct result.</p> <pre><code>x_r=x.reshape(x.shape[0],-1) dw= x_r.T.dot(dout) </code></pre> <p><a href="https://i.stack.imgur.com/ogFy1.png" rel="nofollow ...
<p>While both your approaches result in arrays of same shape, there will by a difference in the order of elements due to the way numpy reads / writes elements. By default, <code>reshape</code> uses a C-like index order, which means the elements are read / written with the last axis index changing fastest, back to the f...
python|numpy|machine-learning
3
358,142
68,569,896
0 Learnable parameters in Lstmcell pytorch
<p>[Does anyone know what could be the reason for 0 learnable parameters in lstm cells][1]</p>
<p>The reason this may be the case in your code is because you have freezed the params in your LSTM as their required grad is False.</p> <p>Or the params in your LSTM may not be calculating gradients as they could have been detached.</p> <p>Therefore there will be 0 learnable parameters in this case.</p> <p>Sarthak Jai...
pytorch|lstm
0
358,143
68,476,262
How to groupby and convert data to NaN values if there is at least 1 NaN value?
<p>I want to drop all rows for a specific <code>CODE</code> if there is at least one NaN value in <code>PPTOT</code> by <code>CODE</code>.</p> <p>This is my <code>df</code>:</p> <pre><code> CODE MONTH_DAY PPTOT 0 113250 01-01 8.4 1 113250 01-02 9.3 2 113250 01-03 NaN 3 ...
<p>Try:</p> <pre><code>&gt;&gt;&gt; df.loc[df['PPTOT'].notnull().groupby(df['CODE']).transform('all')] CODE MONTH_DAY PPTOT 16975 47E94706 12-27 5.0 16976 47E94706 12-28 10.2 16977 47E94706 12-29 0.2 16978 47E94706 12-30 0.3 16979 47E94706 12-31 2.0 </code></pre>
python|pandas
2
358,144
68,806,552
dealing with numpy array and dataframe columns
<p>I have the following dataframe:</p> <pre><code>dates,values 2014-10-01 00:00,10.606 2014-10-01 01:00,10.595 2014-10-01 02:00,10.583 2014-10-01 03:00,10.572 2014-10-01 04:00,10.56 2014-10-01 05:00,10.564 2014-10-01 06:00,10.65 2014-10-01 07:00,10.801 2014-10-01 08:00,10.977 2014-10-01 09:00,11.316 2014-10-01 10:00,11...
<p>use <code>loc</code>:</p> <pre><code>yy=dfr.loc[dfr.index.floor('D') == ' 2014-10-01 00:00:00','values'].to_numpy() </code></pre> <p>OR</p> <p>use <code>flatten()</code>:</p> <pre><code>yy=dfr[dfr.index.floor('D') == ' 2014-10-01 00:00:00'].to_numpy().flatten() #yy=dfr[dfr.index.floor('D') == ' 2014-10-01 00:00:0...
python|arrays|pandas|numpy
1
358,145
68,743,225
Is there a fast way to create a bool matrix from another matrix in python?
<p>i would like to know if there is a faster way, not O(n^2), to create a bool matrix out of an integer nxn-matrix.</p> <p>Example:</p> <p>given is the matrix:</p> <pre><code>matrix_int = [[-5,-8,6],[4,6,-9],[7,8,9]] </code></pre> <p>after transformation i want this:</p> <pre><code>matrix_bool = [[False,False,True],[Tr...
<pre><code>matrix_int = [[-5,-8,6],[4,6,-9],[7,8,9]] matrix_int = np.array(matrix_int) bool_mat = matrix_int &gt; 0 </code></pre> <p>result:</p> <pre><code>array([[False, False, True], [ True, True, False], [ True, True, True]]) </code></pre>
python|numpy
3
358,146
68,685,335
how do I compare these two tables?
<pre><code>import json from io import StringIO from bs4 import BeautifulSoup from requests_html import HTMLSession import time from selenium import webdriver import requests import pandas as pd import numpy as np url = 'https://www.benzinga.com/premarket/' tables = pd.read_html(url) df = tables[5] firstProductSet = df...
<p>If you just want the stocks that are common to both Series, you could use set <code>intersection</code>:</p> <pre><code>&gt;&gt;&gt; set(df1[&quot;Stock&quot;]).intersection(set(df2[0])) {'ANY', 'AUPH', 'GDYN', 'GRPN', 'HCI', 'SWCH', 'WPRT'} </code></pre>
python|pandas
0
358,147
68,868,795
How to correct words in panda dataframe?
<p>I am trying to correct the miss-spelling in the CSV file containing the sentences.</p> <p>input_csv:</p> <pre><code>id text 0 my telephon not working 1 I have mobil in my bag 2 car is expensiv </code></pre> <p>The code provided <a href="https://stackoverflow.com/questions/6702405/get-the-most-relevant-word-sp...
<p>Put your code in a function and then call it on each row using <code>apply</code>:</p> <pre><code>def word_suggest(word): d = enchant.Dict(&quot;en_US&quot;) if d.check(word): return word best_words = [] best_ratio = 0 a = set(d.suggest(word)) for b in a: tmp = difflib.Sequenc...
python|pandas
0
358,148
68,668,128
How to use groupby on multiple indexes and then use count aggregate function and then use one of the multiple indexes to get the sum of count?
<p>I have created a dataframe in python lets say:</p> <pre><code>testingdf = pd.DataFrame({'A':[1,2,1,2,1,2], 'B':[1,2,1,2,3,3], 'C':[9,8,7,6,5,6]}) </code></pre> <p>Now i want to get count of column 'C' according to 'A' and 'B' for that i am performing</p> <pre><code...
<p>you can use <code>sum()</code> method with <code>level</code> parameter after <code>groupby()</code>+<code>count()</code>:</p> <pre><code>out=testingdf.groupby(['A','B']).count().sum(level=0).reset_index() </code></pre> <p>OR</p> <p>other way is groupby twice:</p> <pre><code>out=testingdf.groupby(['A','B']).count()....
python|pandas|pandas-groupby
1
358,149
68,456,742
Pandas, how to create multiple sheet?
<p>I'd like to make several sheets with pandas.</p> <p>This is my test code</p> <pre><code>import pandas as pd number = [1, 2, 3, 4, 5] name = ['john', 'james', 'ken', 'jiny'] df = pd.DataFrame(number, columns=['number']) writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='test1_s...
<p>With your data, it would look like this.</p> <pre><code>import pandas as pd number = [1, 2, 3, 4, 5] name = ['john', 'james', 'ken', 'jiny'] df1 = pd.DataFrame(number, columns=['number']) df2 = pd.DataFrame(name, columns=['name']) # now write to excel with pd.ExcelWriter('text.xlsx', engine='xlsxwriter') as writer...
python|excel|pandas
1
358,150
68,661,736
How can I "concat" rows by same value in a column in Pandas?
<p>I would like to concat rows value in one row in a dataframe, given one column. Then I would like to receive an edited dataframe.</p> <p><strong>Input Data :</strong></p> <pre><code>ID F_Name L_Name Address SSN Phone 123 Sam Doe 123 12345 111-111-1111 123 Sam Doe 123 12345 222-222-2...
<p>try <code>groupby()</code>+<code>agg()</code>:</p> <pre><code>myschema=(df.groupby('ID',as_index=False) .agg(lambda x:list(set(x))[0] if len(set(x))==1 else list(set(x))).to_dict('r')) </code></pre> <p>OR</p> <p>If order is important then aggregrate <code>pd.unique()</code>:</p> <pre><code>myschema=(df.grou...
python|pandas|dataframe|pandas-groupby
1
358,151
68,562,438
Pandas merge near by entry
<p>Pandas merge_asof not meeting expectation....example below:</p> <pre><code>left = pd.DataFrame({'a': [5, 10], 'left_val': ['b', 'c']}) right = pd.DataFrame({'a': [3, 7], 'right_val': [6, 7]}) pd.merge_asof(left, right, on='a', direction='nearest') </code></pre> <p>This gives:</p> <pre><code> a left_val right...
<p>Use <code>pd.merge</code> with <code>how='cross'</code> to create all combinations from left and right dataframes and compute distance between <code>a</code> and <code>a_right</code>.</p> <pre><code>out = pd.merge(left, right, how='cross', suffixes=('', '_right')) out['dist'] = out['a'].sub(out['a_right']).abs() </c...
python|pandas
0
358,152
68,810,361
Print indexed values from .txt file
<p>I am a total beginner at Python and need to display certain indexes' values in a .txt file. I can display the index position of the values matching the defined criteria, but cannot print the indexed value itself.</p> <pre><code>np.where(sunspots &gt; 200) (array([ 352, 1055, 2380, 2494, 2501, 2504, 2505, 2506, 2507,...
<p>You can view indexes as well as values in multiple ways. I have listed a few below for your reference.</p> <pre><code>#created a sample list sunspots = np.array([10,20,200,230,240,100,210,300,250]) np.where(sunspots &gt; 200) # This will give the indices. </code></pre> <p>Now refer back to the original list of value...
python|arrays|numpy
2
358,153
68,714,674
select all below rows till we get next match in column pandas (issue resolved but couldn't delete question)
<p>i'm bit new to dataframe and i have a requirement as below. Here is my dataframe</p> <pre><code>ID type key xcolumn ycolumn 1 Title size 1223 hello 2 Attribute 10 177 hi 3 Attribute 11 431 ahssd 4 Attribute 12 134 dfejf 5 Title weight 34...
<p>I know a trick! It can help. You can create an new ID for the &quot;parents&quot; rows (i.e. where type == 'Title'). Then, you could use the fillna method on the DataFrame and specify the method forward ffill, so you will have the link with the &quot;child&quot; rows. My sample:</p> <pre><code>df = pd.DataFrame({'ty...
python|pandas
1
358,154
68,717,521
How to count the number of unique elements from two lists
<p>I have a pandas dataframe with hundreds of columns, and I need to know the number of unique elements in two columns. Here's a sample of the data:</p> <pre><code>df2 = pd.DataFrame(data={ 'colA_1': [&quot;12.456.&quot;, &quot;......7&quot;, &quot;..34..7&quot;], 'colA_2': [&quot;1......&quot;, &quot;1.....7&quot;, &q...
<p>You can use:</p> <pre><code>len(set(df2.filter(like='colA').sum().sum())) </code></pre> <p>output: 8</p> <p>This merges all the string of both columns for all rows and calculates the unique elements with <code>set</code></p> <h4>original answer</h4> <p>To calculate unicity, pandas/python hashes the objects. They nee...
python|pandas|list|dataframe
0
358,155
68,478,234
how Iterate each link to scrape all dataframe inside HTML?
<p>Im scraping a website thru a list of link, 442 links in total. In each of the link have Dataframe, by using pd.read_html() I manage to pull the dataframe. So I tried to loop all the link and scrape all the dataframe and joined them, but after I finished everything, I found out that, some of the link have different d...
<p>I had found some pattern in the links, so I I tried this and it is now working fine. Not 100% perfectly but it is working, 95%. Here's the code:</p> <pre><code>import pandas as pd import requests df=pd.read_csv(&quot;link.csv&quot;) # That google drive document links=df[&quot;0&quot;].values.tolist() for link in ...
python|pandas|dataframe|selenium|beautifulsoup
1
358,156
68,851,584
When does pandas read_csv read blank values as 'nan' string?
<h1>EDIT2 (SOLVED)</h1> <p>tl;dr Pandas is loading the blanks correctly as NaN. The issue is due to a function that processes the data.</p> <p>Data:</p> <pre><code>In: df Out: name column1 0 72944014961 NaN 1 81870301050 NaN 2 85266074963 NaN </code></pre> <p>It looks ok, but to make sure:...
<p>Solution: tell <code>read_csv</code> that string 'nan' is an NA value:</p> <pre><code>pandas.read_csv(..., na_values='nan') </code></pre> <p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html?highlight=na_values" rel="nofollow noreferrer"><code>na_values</code> arg</a> can b...
python|pandas
2
358,157
68,546,545
Removing a periodic noise signal from an output signal in python
<p>I currently have two periodic signals: an output signal shown in blue and a noise signal shown in green. Both of the curves shown have been shifted to arbitrary values, to clearly separate the curves. Given that both the noise and the output share a similar phase, what I would like to do is to scale the noise signal...
<p>Because I don't have your datasets it is difficult to show you with your actual data, but here are examples of how to compute the difference of two time series with different sampling rates.</p> <h2>resampling</h2> <p>This example is using <a href="https://pandas.pydata.org/pandas-docs/stable//reference/api/pandas.S...
python|pandas|numpy|matplotlib|signal-processing
1
358,158
36,551,457
Pandas: Date comparison with column addition based on values in rows
<p>I have a number of excel files that following a similar format:</p> <pre><code>|name| email| cat1| cat2| cat3 smith email 01JAN2016 01JAN2014 01JAN2015 </code></pre> <p>The first two columns contain strings (name and email addrs) while each of the following columns contain dates when each person completed each it...
<p>When you want to create a new column based on values of one or more other columns, you usually use one of the <code>apply</code> functions. When the function is of multiple columns, as is the case here, you use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow...
python|excel|date|pandas
3
358,159
36,580,973
Filtering dataframe based on elapsed time
<p>I have a dataframe indexed by a Timestamp column.</p> <pre><code>2011-5-5 12:11 (data...) 2011-5-5 12:12 (data...) 2011-5-5 12:13 (data...) 2011-5-5 12:14 (data...) 2011-5-5 12:15 (data...) 2011-5-5 12:26 (data...) 2011-5-5 12:27 ...
<p>try this:</p> <pre><code>In [36]: df[df.ts - df.ts.shift(1) &gt; pd.Timedelta('1min')] Out[36]: ts 5 2011-05-05 12:26:00 8 2011-05-05 12:36:00 </code></pre>
python|pandas|dataframe|filtering
5
358,160
36,369,291
X-Axis is not correctly spaced in Seaborn
<p>I have a multi-level indexed dataframe that I am trying to display in Seaborn. The plot is showing up fine, but the values of the x-axis are being treated as text labels instead of actual x-values. The snippet below shows how sample data is made and plotted:</p> <pre><code>&gt;&gt;&gt; import numpy, pandas, seaborn...
<p><code>factorplot</code> is treating your <code>[1, 10, 100, 1000]</code> as categories (or factors). Those are not numbers for seaborn - just labels. That's why they are spaced evenly (and internally it places those labels on a linear spaced scale from 0 to 3). The side effect from this is that it mimics the log-sca...
pandas|seaborn
4
358,161
36,653,443
Retaining NaN values after get_dummies in Pandas
<p>I have a dataframe 'df' like this -</p> <pre><code>Id v1 v2 0 A 0.23 1 B 0.65 2 NaN 0.87 </code></pre> <p>If I use</p> <pre><code>df1 = get_dummies(df) df1 </code></pre> <p>I get</p> <pre><code>Id v1_A v1_B v2 0 1 0 0.23 1 0 1 0.65 2 0 ...
<p>Method #1 would be to use <code>v1</code>'s nans directly, without loops:</p> <pre><code>&gt;&gt;&gt; df1 = pd.get_dummies(df) &gt;&gt;&gt; df1.loc[df.v1.isnull(), df1.columns.str.startswith("v1_")] = np.nan &gt;&gt;&gt; df1 Id v2 v1_A v1_B 0 0 0.23 1.0 0.0 1 1 0.65 0.0 1.0 2 2 0.87 NaN ...
python-3.x|pandas
11
358,162
36,530,521
python grouping similar categorical values
<p>My dataset has one column with a large number of unique values (object type). I believe some are insignificant (if they are spare) and so I am looking to group the levels if they are beneath a certain defined threshold. I converted the column into categorical values with the label encoder module, then I want to comb...
<p>This shall help you:</p> <pre><code>In [127]: df Out[127]: id bin new_bins 0 1 a a 1 2 a a 2 3 b o 3 4 c o 4 5 b o 5 6 a a 6 7 b o 7 8 a a 8 9 c o 9 10 a a </code></pre> <p>Group the items:</p> <pre><co...
python|pandas|group-by
1
358,163
36,655,263
Pandas: Group Timeseries into parts of a day
<p>I have a timeseries that I want to group into <code>time periods of the day</code>. Grouping by hour of the day is easy:</p> <pre><code>times = pd.DatetimeIndex(df[datetime_field]) grouped = df.groupby([times.hour]) </code></pre> <p>Now I want to group by an arbitrary number of minutes:</p> <pre><code>times = pd...
<p>one way (among many) to achieve that:</p> <pre><code>df.groupby([df.ts.dt.date, df.ts.dt.hour, df.ts.dt.minute//15]) </code></pre> <p>Explanation:</p> <pre><code>In [52]: df = pd.DataFrame({'ts':pd.date_range('2016-01-01', freq='1min', periods=10000), 'col': np.random.randint(0,100, len(times))}) In [53]: df.hea...
python|pandas|time-series
1
358,164
36,462,229
TensorFlow: How do I release a model without source code?
<p>I am using Tensorflow + Python.</p> <p>I am curious if I can release a saved Tensorflow model (architecture + trained variables) without detailed source code. I'm aware of <code>tf.train.Saver()</code>, but it looks to save only variables, and in order to restore/run them, a user needs to "define" the same architec...
<p>You can build a <code>Saver</code> from the MetaGraphDef (saved with checkpoints by default: those .meta files). and then use that Saver to restore your model. So users don't have to re-define your graph in their code. But then they still need to figure out the model signature (input, output variables). I solve this...
python|tensorflow
1
358,165
36,501,000
Adding Submatrix in Numpy without Loop
<p>Let's say I got this <code>a = np.arange(9).reshape((3,3))</code> I want get a numpy array of <code>[9,12,15]</code> which is a result of </p> <pre><code>[0+3+6, 1+4+7, 2+5+8] </code></pre>
<p>You can use<code>numpy.array.sum()</code> function by passing the <code>axis=0</code>:</p> <pre><code>&gt;&gt;&gt; a.sum(axis=0) array([ 9, 12, 15]) </code></pre>
python|numpy
5
358,166
36,296,307
Creating a separate Counter() object and Pandas DataFrame for each list within a list of lists
<p>All the other answers I could find specifically referred to aggregating across all of the nested lists within a list of lists, where as I'm looking to aggregate separately for each list.</p> <p>I currently have a list of lists:</p> <pre><code>master_list = [[a,a,b,b,b,c,c,c], [d,d,d,a,a,a,c,c,c], [c,c,c,a,a,f,f,f]...
<p>IMO, this question can show the real pandas's power. Let's do the following - instead of counting boring <code>[a,a,b,b,b,c,c,c], [d,d,d,a,a,a,c,c,c], [c,c,c,a,a,f,f,f]</code> we will count the frequency of words in real books. I've chosen the following three: 'Faust', 'Hamlet', 'Macbeth'.</p> <p>Code:</p> <pre><c...
python|pandas|dataframe|counter|nested-lists
1
358,167
36,674,717
Unable to join a dataframe even after following an example
<p>Imports modules:</p> <pre><code>import Quandl import pandas as pd from pandas.tools.plotting import df_unique </code></pre> <p>read api key:</p> <pre><code>api_key = open('quandlapikey.txt','r').read() </code></pre> <p>Currently the function reads a csv file to get the codes however I plan to change this to sqll...
<p>Seems to me that the issue with your code is somewhere around here:</p> <pre><code>... df = df['Price'] ## &lt;- you are turning the DataFrame to a Series here df.columns = [abbrv] ## &lt;- no effect whatsoever on a Series print(query) print(df) </code></pre> <p>What I would do instead is simply add the new row to...
python|pandas|quandl
0
358,168
36,249,983
Indexing the unique rows of an array
<p>I would like to get the indices of the unique rows in an array. A unique row should have its own index (starting with zero). Here is an example:</p> <pre><code>import numpy as np a = np.array([[ 0., 1.], [ 0., 2.], [ 0., 3.], [ 0., 1.], [ 0., 2.], ...
<p>A pure numpy solution :</p> <pre><code>av = a.view(np.complex) _,inv = np.unique(av,return_inverse=True) </code></pre> <p>Then <code>inv</code> is :</p> <pre><code>array([0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5], dtype=int64) </code></pre> <p><code>np.complex</code>is for packing the two components,...
python|arrays|numpy|pandas
3
358,169
36,270,082
More efficient way to map logic matrix (false/true) to uint8 matrix (0/255)?
<p>I have a 2d array of boolean values and I want to map false to 0 (uint8) and true to 255(uint8) so that I can use the matrix as a b/w image. </p> <p>Currently I have:</p> <pre><code>uint8matrix = boolMatrix.astype(numpy.uint8)*255 </code></pre> <p>but I think the multiplication is adding unnecessary computation.<...
<p>bool implicitly casts to int in numpy; so simply multiplying with np.uint8(255) will do the trick, and save you an extra pass over the data.</p>
python|numpy|type-conversion
2
358,170
5,446,855
python numpy cast problem
<p>I'm trying to interpolate with the following code</p> <pre><code> self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] ) self.samples = np.interp(self.indeces, tmp_idx, tmp_s) </code></pre> <p>where tmp_idx and tmp_s are numpy arrays. I get the following error:</p> <blockquote> <p>array cannot be safely ca...
<p>One of your possible issues is that when you have the following line:</p> <pre><code>tmp_s = np.array; tmp_idx = np.array; </code></pre> <p>You are setting <code>tmp_s</code> and <code>tmp_idx</code> to the built-in function np.array. Then when you append, you have have object type arrays, which <code>np.interp</c...
python|casting|numpy|interpolation
2
358,171
5,338,944
How to draw probabilistic distributions with numpy/matplotlib?
<p>I want to draw probabilistic functions (like the binomial distribution), but i don't find a function that returns the probability for given parameters. To write it myself i need binomial coefficients (I could write that myself), for which I haven't found a function either. Is there a 'short and/or easy' to do this?<...
<p><code>scipy.stats.binom.pmf</code> gives the probability mass function for the binomial distribution. You could compute it for a range and plot it. for example, for 10 trials, and p = 0.1, you could do</p> <pre><code>import scipy, scipy.stats x = scipy.linspace(0,10,11) pmf = scipy.stats.binom.pmf(x,10,0.1) import ...
python|numpy|matplotlib
14
358,172
53,087,524
Pandas dataframe create new column after x rows
<p>I'm trying to create a new DataFrame based on some data in a CSV file.</p> <p>My Data is of the form:</p> <pre><code>1, 81.99525117808678 2, 78.79210736916842 3, 69.33703048261454 4, 53.12612416937101 5, 48.8442549498639 6, 48.8442549498639 7, 38.96011640562207 8, 33.66251691693962 9, 29.202159649144907 10, 27.777...
<p>You can create a <code>reader</code> iterable (see <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking" rel="nofollow noreferrer">docs</a> for details), with a chunk size of 10, then concatenate each chunk:</p> <pre><code>reader = pd.read_csv('data.csv', sep=',', chunksize=10, ...
python|pandas|csv
2
358,173
53,145,705
dataframe selecting rows with given conditions and operating
<p>I have a dataframe looks like this:</p> <pre><code> import pandas as pd df = pd.DataFrame({'AA': [1, 1, 2, 2], 'BB': ['C', 'D', 'C', 'D'], 'CC': [10,20,30,40], 'DD':[], 'EE':[]}) </code></pre> <p>Now, I want to multiply a value in the column 'CC' with number 2 if 'AA'= 1 and 'BB'='C'. For example, the firs...
<pre><code>m0 = df.AA == 1 m1 = df.BB == "C" df.loc[m0 &amp; m1, "DD"] = df.loc[m0 &amp; m1, "CC"] * 2 </code></pre>
pandas|dataframe|conditional-statements
2
358,174
53,152,629
Create GUI with cv2 python alone
<p>I need to create a GUI (create a Button to select an image from directory or list the image from a particular directory and select one image for conversion)with python cv2.Because i can't install pyqt or tkinter like modules. I have cv2 , numpy and other basic modules.How can i do this without installing any other m...
<p>It looks like you can pass key inputs to opencv but <a href="https://stackoverflow.com/questions/14494101/using-other-keys-for-the-waitkey-function-of-opencv#14494131">not easily</a>, as well as <a href="https://docs.opencv.org/2.4/modules/highgui/doc/user_interface.html" rel="nofollow noreferrer">log</a> slider eve...
python|numpy|cv2
0
358,175
53,155,738
Assign a new column to classify values Items to
<p>I imported a dataframe from excel using</p> <p><code>data = pd.read_csv('transaction.csv')</code></p> <p>and have a dataframe that looks like this</p> <pre><code> Date Time Transaction Item 0 2016-10-30 09:58:11 1 water 1 2016-10-30 10:05:34 2 french fr...
<p>Create dictionary for each category by <code>dict.fromkeys</code> and <a href="https://stackoverflow.com/q/38987">merge them together</a>:</p> <pre><code>Food = ('french fries', 'Icecream', 'chocolate', 'Cookies') Drink = ('water',) Category = {**dict.fromkeys(Food, "Food"), **dict.fromkeys(Drink, "Drink")} print ...
python|pandas|dictionary
1
358,176
53,182,005
check for date and time between two columns in pandas data frame
<p>I have two data frames:</p> <p>The first date frame is:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'serialNo':['aaaa','bbbb','cccc','ffff','aaaa','bbbb','aaaa'], 'Name':['Sayonti','Ruchi','Tony','Gowtam','Toffee','Tom','Sayonti'], 'testName': [4402, 3747 ,5555,8754,1234,...
<p>You could have a column within your dataframe that combines the date and the time. Here's an example of combining a single row in the dataframe:</p> <pre><code># Combining Date_x and time_df1 value_1_x = datetime.datetime.combine(result['Date_x'][0].date() ,\ datetime.datetime.strptime(result['Time_df1'][0], '%H:%M...
python|pandas
0
358,177
53,254,056
Running cloud TPU profiler in Google Colab environment
<p>I am running a Google Colab notebook and am trying to capture TPU profiling data for use in TensorBoard, however I can't get <code>capture_tpu_profile</code> to run in the background while running my TensorFlow code.</p> <p>So far I tried to run the capture process in the background with:</p> <pre><code>!capture_t...
<p>Turns out a way to do this is to start the process from python directly like this (I also had to modify the parameter from <code>--tpu</code> to <code>--service_addr</code>):</p> <pre><code>import subprocess subprocess.Popen(["capture_tpu_profile","--logdir=gs://&lt;my_logdir&gt;", "--service_addr={}".format(os.env...
python|tensorflow|google-colaboratory|google-cloud-tpu
5
358,178
53,309,192
Similarity between two lists of documents
<p>I need to find the similarity between two lists of the short texts in Python. Texts can be 1-4 word long. The length of the lists can be 10K each. So, I need to effectively calculate 10K*10K=100M similarity scores. I didn't find how to do this effectively in spaCy. Maybe other packages can do this? I assume the word...
<p>I think your question is ambiguous - You might mean to produce a single similarity score for the similarity of the average of list 1 vs the average of list 2. I'm assuming that you want a similarity score for each combination of items from the two lists. For 10K items per list, that will produce 10K pow 2 = 100M sim...
tensorflow|nlp|similarity|spacy|sentence-similarity
1
358,179
53,257,563
RNN use mean square error does not converge
<p>I am learning RNN through <a href="https://medium.com/@erikhallstrm/hello-world-rnn-83cd7105b767" rel="nofollow noreferrer">https://medium.com/@erikhallstrm/hello-world-rnn-83cd7105b767</a>. I change the loss function to mean square error and found it does not converge. The output is stuck at 0.5. Somehow, I feel th...
<p>Just need to replace </p> <pre><code>logits_series = [tf.matmul(state, W2) + b2 for state in states_series] </code></pre> <p>by </p> <pre><code>logits_series = [tf.squeeze(tf.matmul(state, W2) + b2) for state in states_series] #Broadcasted addition </code></pre> <p>Problem can solved.</p>
tensorflow|rnn|loss
0
358,180
53,192,602
Convert a Pandas DataFrame into a list of objects
<p>I want to convert a Pandas DataFrame into a list of objects.</p> <p>This is my class:</p> <pre><code>class Reading: def __init__(self): self.HourOfDay: int = 0 self.Percentage: float = 0 </code></pre> <p>I read up on .to_dict, so I tried </p> <pre><code>df.to_dict(into=Reading) </code></pre>...
<p>having data frame with two column HourOfDay and Percentage, and parameterized constructor of your class you could define a list of Object like this:</p> <pre><code> class Reading: def __init__(self, h, p): self.HourOfDay = h self.Percentage = p listOfReading= [(Reading(row.HourOfDay,row.Perce...
python|pandas|dataframe
17
358,181
52,910,106
Tensorflow error Fetch argument <built-in function sum> must be a string or Tensor
<p>I keep getting this tensorflow error and I cannot figure out why. my code:</p> <pre><code>__future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import os a = tf.constant(2.5) b = tf.constant(4.5) total = a + b; tf.summary.scalar("a",a) tf....
<p>you've not declared 'sum' before doing sess.run. sum is a built-in function in python. You might want to run 'total'</p> <pre><code>sess.run([total,merged_op]) </code></pre> <p>to proof that sum is built-in:</p> <pre><code>sum([5,4]) &gt;&gt;&gt; 9 </code></pre>
python|tensorflow|google-colaboratory
0
358,182
53,164,899
Pandas groupby: divide last in group by first in group
<p>I have a dataframe that I have grouped by multiple columns. Within each group, I would like to then generate a value that finds the last entity of each of those groups and divide by the first entity. I would also like to show the number of entities and the last entity value in the output. </p> <p>See below for an e...
<p>Just do assign with <code>groupby</code> <code>tail</code> and <code>head</code></p> <pre><code>df_group=df.groupby(['ID','Item','End_Date','Type']) df_output=df_group.size().reset_index(name='Group Count') df_output['PCTCHange']=((df_group.value.tail(1)/df_group.value.head(1))-1).values df_output['FinalValue']=df_...
python|pandas
1
358,183
53,304,790
Numpy get maximum value based on XYZ
<p>I'm trying to read an CSV file with some XYZ data but when gridding using Python Natgrid is causing an error: <code>two input triples have the same x/y coordinates</code>. Here is my array:</p> <pre><code>np.array([[41.540588, -100.348335, 0.052785], [41.540588, -100.348335, 0.053798], [42.540588, -102.348335...
<p>If you are able to use <code>pandas</code>, you can take advantage of <code>groupby</code> and <code>max</code></p> <pre><code>&gt;&gt;&gt; pandas.DataFrame(arr).groupby([0,1], as_index=False).max().values array([[ 4.15405880e+01, -1.00348335e+02, 5.37980000e-02], [ 4.25405880e+01, -1.02348335e+02, 2.2798...
python|numpy
0
358,184
53,213,372
Tensorflow, change Tensor values given a condition
<p>I am translating a numpy code to Tensorflow.</p> <p>It has the following line:</p> <pre><code>netout[..., 5:] *= netout[..., 5:] &gt; obj_threshold </code></pre> <p>This is not the same Tensorflow syntax, I'm having trouble finding the functions with the same behavior.</p> <p>Firstly I tried:</p> <pre><code>net...
<p>If you just wanted to make 0 all values below <code>obj_threshold</code> you could just do:</p> <pre><code>netout = tf.where(netout &gt; obj_threshold, netout, tf.zeros_like(netout)) </code></pre> <p>Or:</p> <pre><code>netout = netout * tf.cast(netout &gt; obj_threshold, netout.dtype) </code></pre> <p>However, y...
python|tensorflow
5
358,185
53,092,196
Calculating kurtosis from an image
<p>I have this code:</p> <pre><code>import cv2 from scipy.stats import kurtosis, skew def main(): img1 = 'lenna.jpg' gray_img = cv2.imread(img1, cv2.IMREAD_GRAYSCALE) print(f'Kurtosis: {kurtosis(gray_img)}') </code></pre> <p>I want to calculate the kurtosis for an given image, but when I run this code, ...
<p>You are calling <code>kurtosis</code> on <code>axis=0</code> by default (<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html" rel="nofollow noreferrer">see docs</a>), but it seems like you're trying to run it on the whole array. So you can try <code>axis=None</code>:</p> <pre><co...
python|python-3.x|numpy|scipy
6
358,186
53,174,535
Manipulating duplicate rows across a subset of columns in dataframe pandas
<p>Suppose I have a dataframe as follows:</p> <pre><code>df = pd.DataFrame({"user":[11,11,11,21,21,21,21,21,32,32], "event":[0,0,1,0,0,1,1,1,0,0], "datetime":['05:29:54','05:32:04','05:32:08', '15:35:26','15:36:07','15:36:16','15:36:50','15:36:54', ...
<p>You want to <code>groupby</code> and <code>aggregate</code></p> <pre><code>df.groupby('user').agg({'event': 'max', 'datetime': lambda s: pd.to_timedelta(s).mean()}) </code></pre> <p>If you want, you can also just change your <code>datetime</code> column first to <code>timedelta</code> usin...
pandas|dataframe|duplicates|data-manipulation
3
358,187
53,202,283
Tensorflow eager mode support for text summary
<p>I am trying to make a summary of a text using tensorflow with eager mode enabled, for this I am using this code:</p> <pre><code>writer = summary_ops_v2.create_file_writer('some_path', flush_millis=10000) writer.set_as_default() tensor = tf.convert_to_tensor("Some text") meta = tf.SummaryMetadata() meta.plugin_data...
<p>I think this might have been a bug. I updated to tensorflow 1.13.1 and the summaries started been displayed correctly.</p>
python|tensorflow|tensorboard|eager
0
358,188
53,315,529
Unpacking cells containing list of lists in Pandas DataFrame into separate rows and columns of a new DataFrame
<p>I have the DataFrame <code>df</code>:</p> <pre><code> a b c 0 7 5 [[-4, 7], [-5, 6]] 1 13 5 [[-9, 4], [-3, 7]] </code></pre> <p>I want to flatten the column with list of lists cells (column 'c') into a separate DataFrame such that:</p> <ol> <li>The separate lists correspond to individ...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a>+<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>apply</code></a> with <a href...
python|python-3.x|pandas|dataframe
5
358,189
53,189,792
how to count the number of state change in pandas?
<p>i have below dataframe that have columns 0-1 .. and i wanna count the number of 0->1,1->0 every column. in below dataframe 'a' column state change number is 6, 'b' state change number is 3 , 'c' state change number is 2 .. actually i don't know how code in pandas. </p> <pre><code>number a b c 1 0 0 0 2 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="noreferrer"><code>rolling</code></a> and compare each value, then count all <code>True</code> values by <code>sum</code>:</p> <pre><code>df = df[['a','b','c']].rolling(2).apply(lambda x: x[0] != x[-1], raw=True).s...
python|pandas|dataframe
6
358,190
53,091,085
raise ValueError('Image with id {} already added.'.format(image_id)) in Tensorflow object detection api
<p>Image training is ok with ssd_mobilenet_v1_coco in tensorflow object detection api.</p> <p>getting the error while testing:</p> <pre><code>File "/home/hipstudents/anaconda3/envs/tensorflow_gpuenv/lib/python3.6/site-packages/object_detection-0.1-py3.6.egg/object_detection/utils/object_detection_evaluation.py", line...
<p>In the ssd_mobilenet_coco_v1.config file, num_examples was 8000. In my case, test dataset only has 121 samples. I forgot to update that and got new kind of error that I couldn't find on the Internet. As it is a silly mistake, so I think a very few people did that. this answer might help someone who will do this kind...
tensorflow|object-detection-api
18
358,191
53,073,155
Combine date column and time column into datetime
<p>I have two columns (both text objects), one date, the other hour-ending.</p> <pre><code>df = pd.DataFrame({'Date' : ['2018-10-01', '2018-10-01', '2018-10-01'], 'Hour_Ending': ['1.0', '2.0', '3.0']}) </code></pre> <p>How do I add the two columns together to get a datetime object that looks like this...
<p>Using <code>to_datetime</code> and <code>Timedelta</code></p> <pre><code>pd.to_datetime(df.Date)+pd.to_timedelta(df.Hour_Ending.astype('float'), unit='h') Out[122]: 0 2018-10-01 01:00:00 1 2018-10-01 02:00:00 2 2018-10-01 03:00:00 dtype: datetime64[ns] </code></pre>
pandas|datetime
1
358,192
53,202,459
Binary encoding in data processing
<p>I want to do binary encoding of income column of a dataframe which has two categories "&lt;=50k" and ">50k" as 0 and 1 respectively. How should I do that? </p>
<p>You can use "apply":</p> <pre><code>df['income']=df['income'].apply(lambda x: 1 if x&gt;50000 else 0) </code></pre> <p>Edit 1:</p> <p>I think this would be much faster than my previous answer:</p> <pre><code>df["income"] = np.where(df["col"] &lt;50000, 0, 1) </code></pre> <p>Performance:</p> <pre><code>%timeit...
pandas|numpy
0
358,193
53,008,141
C++ extension module for Python returning a Numpy array
<p>I am trying to create an extension module for Python in C++ using SWIG, which can return a Numpy array to Python. This numpy array is multidimensional and each cell can have a value or a list of values(int 64, [int32, int32] etc]. I am able to return a normal array to Python from C++. Could anyone guide me how to pr...
<p>I think the Numpy C API is a good approach. You can still use SWIG. But I would advice strongly against using SWIG typemaps, they are very complicated. Instead you can accept and return Numpy arrays as PyObject* pointer in your SWIG'ed signature and build/extract them using the C API. SWIG will wrap this correctly.<...
python|c++|arrays|numpy|swig
0
358,194
52,959,190
Grouping Pandas dataframe based on conditions?
<p>I am following the suggestions here <a href="https://stackoverflow.com/questions/26886653/pandas-create-new-column-based-on-values-from-other-columns">pandas create new column based on values from other columns</a> but still getting an error. Basically, my Pandas dataframe has many columns and I want to group the da...
<p>Based on your error message and example, there are two things to fix. One is to adjust parentheses for operator precedence in your final <code>elif</code> statement. The other is to avoid mixing <code>datetime.date</code> and <code>Timestamp</code> objects.</p> <p><strong>Fix 1:</strong> change this:</p> <pre><cod...
python|pandas|dataframe
2
358,195
53,275,541
Pandas - Filtering out column based on value
<p>I have a Pandas Dataframe that two columns as below (view with header):</p> <pre><code>name,attribute abc,{'attributes': {'type': 'RecordType', 'url': '/services/data/v38.0/sobjects/RecordType/000xyz'}, 'Name': 'Product 1'} def,{'attributes': {'type': 'RecordType', 'url': '/services/data/v38.0/sobjects/RecordType/0...
<p>Use list comprehension with <code>get</code> for working with rows also if not exist key <code>Name</code> in some row for boolean mask and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>df = ...
pandas|filter
2
358,196
53,140,438
How to create cummulative sum in dataframe python part2?
<p>How to create cumulative sum (new_supply)in dataframe python from demand column from table</p> <pre><code>item Date supply demand A 2018-01-01 0 10 A 2018-01-02 0 15 A 2018-01-03 100 30 A 2018-01-04 0 10 A 2018-01-05 0 40 A 2018-01-06 50 50 A ...
<p>As the above data doesn't have any proper column which can be used to create groups, we need to create one:</p> <pre><code>df['grp_attr'] = df['supply'].clip(upper=1) df['grp_attr'] = df[df['grp_attr'] != 0]['grp_attr'].cumsum() df['grp_attr'] = df['grp_attr'].bfill().fillna(0).astype(int) </code></pre> <p>The df ...
python|pandas
0
358,197
53,101,479
Aggregate data across dataframes based on string in first column
<p>I am wondering what the most economical way to aggregate information from several dataframes into one new one would be based on matching an ID. </p> <p>Each df has a "participant_id" column and each row has a different participant ID. I want to end up with one df that has one participant_id column and a score from ...
<p>You can use <code>merge</code> with <code>how='outer'</code> for the outer join effect you are expecting like:</p> <pre><code>df1.merge(df2, on='part_id', how='outer').merge(df3, on='part_id', how='outer') part_id col2_x col2_y col2 0 PartID_1234 1 3 6 1 PartID_5678 2 4 5 </co...
python|pandas|dataframe
1
358,198
53,232,954
How to resample AAII weekly data to daily?
<p>I would like to import the following file which contains data in a weekly format (Thursdays only) and convert it to a daily file with the values from Thursday filled out through the next Wednesday skipping Saturday and Sunday.</p> <p><a href="https://www.aaii.com/files/surveys/sentiment.xls" rel="nofollow noreferre...
<p>You can try like..</p> <pre><code>df = pd.read_excel("sentiment.xls", sheet_name = "SENTIMENT", skiprows=3, parse_dates=['Date'], date_format='%m-%d-%y') </code></pre> <p>your Date column having NaN values so when you trying to convert as <code>datetime</code> it fails to do so ..</p> <pre><code>&gt;&gt;&gt; df['...
python|pandas
1
358,199
53,279,238
How to fix the error: The truth value of an array with more than one element is ambiguous
<p>I have a problem with this and I know the code is too long and complex but here I go: this is the data I am using:</p> <pre><code>Data: date = dt.datetime(2018, 6, 26) maturity_dtime = DatetimeIndex(['2020-04-07', '2020-08-07', '2020-12-07', '2023-12-07', '2027-12-07', '2032-12-07', '2040-02-07'], ...
<p>The problem is in your <code>if</code> statement - </p> <pre><code>if maturity_date &gt; curve[nrows-1][0] </code></pre> <p>Think about what this does - </p> <p>Let's say <code>maturity_dtime</code> is a <code>pd.Series</code> that looks like this - </p> <pre><code>2020-04-07 2020-08-07 2023-12-07 </code></pre> ...
python|pandas|optimization|scipy|minimize
3