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 |
|---|---|---|---|---|---|---|
354,700 | 55,570,391 | count year from date column | <p>I would like to see count of years from date column in a dataframe.</p>
<p>I have a df column like this</p>
<pre><code>df = Date
2014-03-18 00:00:00
2014-04-23 12:00:00
2015-01-12 01:00:00
2016-05-24 00:00:00
2017-11-12 00:00:00
2017-08-18 00:00:00
</code></pre>
<p>I woul... | <p>You can use:</p>
<pre><code>df['Date'].dt.year.value_counts().sort_index()
</code></pre>
<p>Output</p>
<pre><code>2014 2
2015 1
2016 1
2017 2
</code></pre> | python-3.x|pandas|dataframe | 1 |
354,701 | 55,494,789 | How to remove multi index from dataframe in python? | <p>I have a data frame</p>
<pre><code> purchase_count
Scrips 1STCUS 20MICRONS 21STCENMGM 3MINDIA
Client_id
A100027 NaN NaN NaN NaN
A100074 NaN NaN NaN NaN
A100077 NaN NaN NaN NaN
A100088 NaN NaN ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.droplevel.html" rel="nofollow noreferrer"><code>MultiIndex.droplevel</code></a>:</p>
<pre><code>df.columns = df.columns.droplevel(0)
</code></pre>
<p>Another solution should be changed <code>pivot_table</code>, obviosl... | python|pandas|pivot|multi-index | 2 |
354,702 | 55,532,990 | How to convert objects to numeric | <p>I have very inconsistent data in one of DataFrame columns:</p>
<pre><code>col1
12.0
13,1
NaN
20.3
abc
"12,5"
200.9
</code></pre>
<p>I need to standardize these data and find a maximum value among numeric values, which should be less than 100.</p>
<p>This is my code:</p>
<pre><code>df["col1"] = df["col1"].apply(l... | <p>Cast value to <code>string</code> by <code>str(x)</code>, but then for test is necessary also replace <code>.</code> and <code>,</code> to empty value for use <code>isdigit</code>:</p>
<pre><code>df["col1"] = df["col1"].apply(lambda x: float(str(x).replace(',', '.')) if str(x).replace(',', '').replace('.', '').isdi... | python|pandas | 1 |
354,703 | 55,506,447 | Why does my GPU Tensorflow crash when trying to run an additional time? | <p>I am pretty new to Tensorflow, and I am using a GPU installation in Anaconda with Spyder. I have a recurring problem across my programs where it will crash with a "Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2" after trying to run a file more than once.</p>
<p>Closing ... | <p>I probably crashes, because Tensorflow is greedy at allocating VRAM. Please see answers <a href="https://stackoverflow.com/questions/41117740/tensorflow-crashes-with-cublas-status-alloc-failed">here</a></p> | tensorflow|anaconda|syntax-error|spyder | 0 |
354,704 | 55,287,709 | Python Pandas, New column with minimum value of previous rows | <p>I am trying to create a new column where the value will be the minimum value of all previous rows from existing columns.</p>
<p>For example:
Here is my data frame:</p>
<pre><code> A nbr
0 AA 4
1 AB 5
2 AC 2
3 AD 5
4 AE 3
5 AF 6
6 AG 1
7 AH 4
</code></pre>
<p>I am trying to add ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.Series.cummin.html" rel="nofollow noreferrer"><code>series.cummin()</code></a>:</p>
<pre><code>df['nbr_min']=df.nbr.expanding().min()
</code></pre>
<p>Or:</p>
<pre><code>df['nbr_min']=df.nbr.cummin()
print(df)
A nbr nbr_min
0 ... | python|python-3.x|pandas | 1 |
354,705 | 55,288,279 | Percentage calculation in pivot table pandas with columns | <p>I have a dataset containing several sells register from different vendors, locations, dates, and products.
The data set is like this:</p>
<pre><code>local categoria fabricante tipo consistencia peso pacote ordem vendas_kg
AREA I SABAO ASATP DILUIDO LIQUIDO 1501 A 2000... | <p>To take the percents:</p>
<pre><code>df_percent = temp_df.iloc[:, [0,1]].apply(lambda x: round(x / x.sum() * 100, 2), axis = 1)
</code></pre>
<p>to take the the variation, use <code>diff</code></p>
<pre><code>df_diff_percent = df_percent.groupby(level=[0,1]).diff().fillna(0)
sum
... | python|pandas|analytics|pandas-groupby | 1 |
354,706 | 55,471,621 | Strange csv output when csv file is read from a github repo using pandas on Debian OS | <p>I have the following data on a csv file:</p>
<pre><code>XG,612.0
YG,-1924.0500000000002
ZG,-959.085
A_mod,6.889112523645457
I1_mod,0.478595694542785
I2_mod,32.64258822366686
</code></pre>
<p>If I open it using excel or atom, everything's normal. The file is on the folder of my GitHub repo, I don't know if this is ... | <p>You're looking at the Git LFS pointer file instead of the actual file. <code>version</code>, <code>oid</code> and <code>size</code> are parts of the Git LFS <a href="https://github.com/git-lfs/git-lfs/blob/master/docs/spec.md" rel="nofollow noreferrer">spec</a>. Git LFS keeps these files in lieu of the actual large ... | python|python-3.x|pandas|csv|debian | 3 |
354,707 | 55,363,151 | Python - Should I Iterate Over Rows the Way I'm Thinking? Or Plan This Differently? | <p>I have table1, which can range from <100 to about 100,000 rows. It contains 22 columns, one of which is a Description containing a string where I want to search some terms.</p>
<pre><code>table1
+----------+--------+--------+--------+-------------+------+-------+-------+
| UniqueId | Cat1Id | Cat2Id | Cat3Id | ... | <p>Might this be something you are looking for? You might look into merging 101 on SO for more options (<a href="https://stackoverflow.com/questions/53645882/pandas-merging-101">Pandas Merging 101</a>) </p>
<pre><code>mrg = pd.merge(df1, df2[['Cat1Id', 'Cat2Id', 'Cat3Id','Val1', 'Val2']], how='left', left_on=[
... | python|pandas|loops | 0 |
354,708 | 55,542,795 | How do I use `np.where()` to compare the arrays not individual values | <p>I have an image(2D array) with 3 color channels. Something like this:</p>
<pre><code>[[[128 197 254]
[128 197 254]
[128 197 254]
...
[182 244 255]
[182 244 255]
[182 244 255]]
[[128 197 254]
[128 197 254]
[128 197 254]
...
[182 244 255]
[182 244 255]
[182 244 255]]
[[128 197 254]
[128 ... | <p>IIUC, you may use <code>np.nonzero</code></p>
<pre><code>np.nonzero((arr==255).all(axis=2))
</code></pre>
<p>That will return a tuple of arrays, which represent the indexes. If you do</p>
<pre><code>arr[ind]
</code></pre>
<p>where <code>ind</code> is the return from the first expr, you may access/modify all rows... | python|python-3.x|numpy|numpy-ndarray | 3 |
354,709 | 55,142,316 | Pytorch problem testing CNN: RuntimeError: shape '[64, 1]' is invalid for input of size 1920 | <p>Testing network:</p>
<pre><code> def test(args, model, device, test_loader):
model.eval()
total = 0
test_loss = 0
correct = 0
with torch.no_grad():
for batch_idx, batch in enumerate(test_loader):
data = batch['image']
ta... | <p>Presumably the shape of ´pred´ is [64,1] whereas the shape of <code>target</code> is [64,30]. Now if you're calling <code>target.view_as(pred)</code> you're trying to view <code>target</code> in the same shape as <code>pred</code>, but <code>target</code> has 64*30=1920 entries, whereas <code>pred</code> only has 64... | python|deep-learning|computer-vision|conv-neural-network|pytorch | 0 |
354,710 | 55,212,983 | Import CSV file in python to a numpy array | <p>I'm trying to import some values from a csv-file to a numpy array in python.
So far I've read the CSV-file with pandas but I can't succeed with creating a numpy array with the values from the csv columns.</p> | <p>Just found the answer. Just had to use DataFrame.values</p> | python|pandas|csv|numpy | 0 |
354,711 | 55,408,902 | What's the best approach to populate Pandas DataFrame NaN values according to other row values? | <p>I have a DataFrame with some NaN values in all columns (Totally 3 columns). I want to populate the NaN values in each cell with the latest valid values in other rows with the fastest approach.
As an example if column A is NaN and column B is '123', I want to find the latest value in column A when the column B is '12... | <p>This solution uses for loop, but it loops over values of A where it is NaN.</p>
<pre><code>A = The column containing NaNs
B = The column to be referenced
import pandas as pd
import numpy as np
#Consider this dataframe
df = pd.DataFrame({'A':[1,2,3,4,np.nan,6,7,8,np.nan,10],'B':['xxxx','b','xxxx','d','xxxx','f','y... | python|pandas|performance|dataframe | 0 |
354,712 | 55,235,230 | tensorflow: Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob` | <p>I get this warning most of the time when i define a model using Keras. It seems to somehow come from tensorflow though:</p>
<pre><code>WARNING:tensorflow:From C:\Users\lenik\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\backend\tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops... | <p>This depreciation warning is due to the Dropout layer in <code>tf.keras.layers.Dropout</code>.<br>To avoid this warning, you need to clearly specify <code>rate=</code> in Dropout as: <code>Dropout(rate=0.2)</code>.
<br><br>Earlier it was <code>keep_prob</code> and it is now deprecated to <code>rate</code> i.e. rate ... | python|tensorflow|keras|deep-learning | 10 |
354,713 | 55,224,761 | __init__() takes from 1 to 6 positional arguments but 11 were given | <p>pls help noob to solve the problem.</p>
<p>i got 2 lists filled with str variables:</p>
<pre><code>crops = ['Кук зер', 'Подсол', 'Пшен оз', 'Сах св', 'Соя', 'Ячм оз', 'Ячм яр']
clusters = ['Восток', 'Восток_2', 'Курск', 'Север', 'Центр', 'Юг',
'Юг_Краснодар', 'Юг_Ставрополь', 'Агросервис']
</code></p... | <p>The error <code>__init__() takes from 1 to 6 positional arguments but 11 were given</code> means that the DataFrame constructor takes a max of 6 different arguments and you fed it 11.</p>
<p>Each set of <code>{}</code> creates a separate dict in Python, which is not what you want. If you remove all the <code>{}</co... | python|pandas|dataset | 4 |
354,714 | 55,485,755 | I have this data set for crimes of a 12 month time period , over 250k rows and i want to predict future crimes by date and location | <p>I have this 250k data set with these features </p>
<pre><code> date_time FullAddress call_type priority lat long
0 6/14/17 21:54 10 14TH ST\, San Diego\, CA 1151 2.0 32.705449 -117.151870
1 3/29/17 22:24 10 14TH ST\, San Diego\, CA 1016 2.0 32.705449 -117.151870
2 6/... | <p>Time - is a sequence and in order to predict a sequence you want to use RNN (<a href="https://en.wikipedia.org/wiki/Recurrent_neural_network" rel="nofollow noreferrer">wiki</a>) (LSTM for example). A good book for details: <a href="https://www.researchgate.net/publication/36419563_Supervised_Sequence_Labelling_with_... | python|dataframe|machine-learning|data-science|sklearn-pandas | 0 |
354,715 | 55,290,190 | Ordering the plot of a pivot by count for each week | <p>When plotting the below data set:</p>
<pre><code>date = ['2/18/2019','2/18/2019','2/18/2019','2/18/2019','2/25/2019','2/25/2019','2/25/2019','2/25/2019','3/4/2019','3/4/2019','3/4/2019','3/4/2019',
'3/11/2019','3/11/2019','3/11/2019','3/11/2019','3/18/2019','3/18/2019','3/18/2019','3/18/2019']
name = ['P','... | <p>The order of columns is how the bars will be stacked. If you have E, L, N, P in your pivot table, that will be the order of the series (current code). You can change this order, but all bars will have the same order. Here is an example ordering the bars by count of Letter group, (i.e. E = 2) </p>
<pre><code>piv = d... | python|pandas|matplotlib | 1 |
354,716 | 55,187,696 | Division by 0 in python broadcasting? | <p>I'm using Python2.7 to create a simple vector field and then plotting it... </p>
<p>But Jupyter complains about a division by 0 ("RuntimeWarning: divide by zero encountered in divide"), and I can't find it. </p>
<pre><code>import numpy as np
def field_gen(x0, y0, x, y, q_cons = 1):
dx = x0-x
dy = y0-y
... | <p>Don't be fooled into think <code>np.where</code> does all the work here. Python will still evaluate all the input arguments first, before running calling <code>np.where</code>.</p>
<p>So in your command <code>kmod = np.where( dist>0.00001, q_cons / dist, 0 )</code>, Python will evaluate <code>dist>0.00001</c... | python|numpy|vectorization|array-broadcasting|divide-by-zero | 2 |
354,717 | 55,352,910 | Reading last N rows of a large csv in Pandas | <p>I have file with 50 GB data. I know how to use Pandas for my data analysis.<br>
I am only in need of the large 1000 lines or rows and in need of complete 50 GB.<br>
Hence, I thought of using the <code>nrows</code> option in the <code>read_csv()</code>.<br>
I have written the code like this: </p>
<pre><code>import ... | <p>A pure pandas method:</p>
<pre><code>import pandas as pd
line = 0
chksz = 1000
for chunk in pd.read_csv("Analysis_of_50GB.csv",encoding="utf-16",chunksize = chksz,index_col=0, usecols=0):
line += chunk.shape[0]
</code></pre>
<p>So this just counts the the number of rows, we read just the first column for perfo... | python|pandas | 3 |
354,718 | 55,243,614 | Return sunrise and sunset time based on a datetime using Python | <p>My <code>df</code> is like this. </p>
<pre><code>DateTime Pdc
01/04/2016 10:00 1
01/04/2016 10:05 2
02/04/2016 10:10 3
02/04/2016 10:15 4
03/04/2016 10:20 5
03/04/2016 10:25 6
03/04/2016 10:30 7
</code></pre>
<p>I want to add two columns of sunrise time and sunset time based on t... | <p>You can retrieve sunset and sunrise time from <a href="https://sunrise-sunset.org/api" rel="nofollow noreferrer">https://sunrise-sunset.org/api</a>.
All you need is to know your latitude and longitude. If you don't know them you can retrieve them from <code>geopy</code> lib:</p>
<pre><code>import requests
from ge... | python|pandas|datetime|timezone | 1 |
354,719 | 55,321,864 | AttributeError: The layer has never been called and thus has no defined input shape | <p>I'm tring to build an autoencoder in TensorFlow 2.0 by creating three classes: Encoder, Decoder and AutoEncoder.
Since I don't want to manually set input shapes I'm trying to infer the output shape of the decoder from the encoder's input_shape.</p>
<pre><code>import os
import shutil
import numpy as np
import tenso... | <p>You were almost there, just overcomplicated things a bit. You are receiving this error because <code>Decoder</code> layer is dependent on the <code>Encoder</code> layer <strong>which wasn't built yet</strong> (as the call to <code>build</code> was unsuccessful) and it's <code>input_shape</code> attribute <strong>was... | tensorflow|tf.keras|tensorflow2.0 | 5 |
354,720 | 55,521,403 | pip can't find tensorflow-gpu 2.0-alpha | <p>I'm trying to install tensorflow-gpu where the version is 2.0.0-alpha0. I've tried these two specific commands:</p>
<pre><code>pip install tensorflow-gpu==2.0.0-alpha0
pip install -U --pre tensorflow-gpu==2.0.0-alpha0
</code></pre>
<p>pip says:</p>
<pre><code>Collecting tensorflow-gpu==2.0.0-alpha0
Could not find... | <p>The actual version is <a href="https://pypi.org/project/tensorflow-gpu/2.0.0a0/" rel="nofollow noreferrer"><code>2.0.0a0</code></a>, not <code>2.0.0-alpha0</code>. You want:</p>
<pre><code>pip install --pre tensorflow-gpu==2.0.0a0
</code></pre>
<p>You also need to run this on a compatible Windows or Linux system. ... | python|tensorflow|pip|pypi | 2 |
354,721 | 7,052,776 | How to truncate the values of a 2D numpy array | <p>I have a two-dimensional numpy array(uint16), how can I truncate all values above a certain barrier(say 255) to that barrier? The other values must stay the same. Using a nested loop seems to be ineffecient and clumsy.</p> | <p>actually there is a specific method for this, 'clip':</p>
<pre><code>import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array.clip(0,255) # clip(min, max)
</code></pre>
<p>output:</p>
<pre><code>array([[100, 200],
[255, 255]], dtype=uint16)
</code></pre> | python|numpy | 21 |
354,722 | 56,814,449 | Implementing custom convolutional layer in Keras - error when loading model | <p>I have implemented a minimal example of Wavenet, closely following the steps from here - <a href="https://github.com/basveeling/wavenet" rel="nofollow noreferrer">https://github.com/basveeling/wavenet</a>.</p>
<p><strong>The issue is, that the model uses a custom layer, which works fine during training but once th... | <p>There is only one custom object, which is <code>CausalConv1D</code>.</p>
<pre><code>objects = {'CausalConv1D': wavenet_utils.CausalConv1D}
</code></pre>
<p>Now you must be sure that your <code>get_config</code> method is correct and has everything needed in the <code>__init__</code> method of your layer. </p>
<p>... | python|tensorflow|keras|neural-network|deep-learning | 2 |
354,723 | 56,850,822 | Replace values using loc command | <p>There's a dataframe and I need to <code>replace</code> values above 512 with 263.</p>
<p>So, I used this code line to filter my indexes first:</p>
<pre><code>df.loc[df['Fare']>512]['Fare'].astype(int)
</code></pre>
<p>Here is the result of this:</p>
<pre><code>258 512
679 512
737 512
1234 512
N... | <p>when using <code>.loc</code> you want to use <code>[row, col]</code> and not <code>[row][col]</code>.</p>
<p>try:</p>
<pre class="lang-py prettyprint-override"><code>df.loc[df['Fare']>512, 'Fare']=df.loc[df['Fare']>512, 'Fare'].astype(int).replace({512:263},inplace=True)
</code></pre> | python|pandas | 2 |
354,724 | 56,811,525 | Calculate probability vector from sample data | <p>I'd like to compare two distributions using Jensen-Shannon Divergence metric. To do this, I need two <strong>probability vectors</strong>. From the <a href="https://scipy.github.io/devdocs/generated/scipy.spatial.distance.jensenshannon.html" rel="nofollow noreferrer">scipy.spatial documentation</a>.</p>
<blockquote... | <p>The probability distribution (the probabilty vector in <code>scipy</code>) is the underying frequency distribution divided by the number of samples, so</p>
<pre><code>p = np.histogram(x1)[0] / len(x1)
q = np.histogram(x2)[0] / len(x2)
</code></pre>
<p><strong>Note:</strong></p>
<pre><code>np.sum(p) == 1
np.su... | python|numpy|scipy|spatial | 2 |
354,725 | 56,763,439 | Efficient method to return first and last item from pandas df | <p>I am trying to implement a more efficient method to return the first and last item of a <code>pandas</code> <code>df</code> where equal to a specific value. I'll post my current method below but there could be a more efficient way. </p>
<pre><code>import pandas as pd
d = ({
'X' : ['X','Y','X','Z','X'],
... | <p>Using <code>query</code> (or any selection method, really) and <code>iloc</code>, this should be straightforward.</p>
<pre><code>df.query('X == "X"').iloc[[0, -1]]
X Y
0 X 2
4 X 1
</code></pre>
<p>Assumes there are no NaNs in Y. Otherwise, chain <code>dropna</code>:</p>
<pre><code>df.query('X == "X"').dr... | python|pandas | 3 |
354,726 | 56,624,139 | Using pandas to join on compound keys with mixture of soft and hard keys | <p>I am looking for a way to do partial soft join in pandas which means I have compound join key </p>
<pre><code>["soft_key", "hard_key_1", "hard_key_2"]
</code></pre>
<p>where soft key should be joined on some range, not precise matching.
In <code>pandas.merge_asof</code> it is referred as <code>tolerance</code>. E.... | <p>Here is one way from <code>merge_asof</code></p>
<pre><code>pd.merge_asof(df2.sort_values('soft_key'),df1.sort_values('soft_key'),by=['hard_key_1','hard_key_2'],on='soft_key',tolerance=2).dropna()
soft_key hard_key_1 hard_key_2 val_2 val_1
1 12 2 5 "Mary" "Jo"
</code></pre> | python|pandas|join | 2 |
354,727 | 56,727,667 | How can I use the .findall() function for a excel file iterating through all rows of a column? | <p>I have a big excel sheet with information about different companies altogether in a single cell for each company and my goal is to separate this into different columns following patterns to <strong>scrape</strong> the info from the first column. The original data looks like this:</p>
<p><a href="https://i.stack.imgu... | <p>I would go with this, which just replaces the 'E-mail:...' with a delimiter and then splits and assigns to the right column </p>
<pre><code>df['Name'] = np.nan
df['Affiliation'] = np.nan
df['Email'] = np.nan
df['Mobile'] = np.nan
for i in range(0, len(df)):
full_value = df['Companies'].loc[i]
full_value =... | python|excel|pandas | 1 |
354,728 | 56,454,145 | How is this generating an image? | <p>I went through the GAN network using tensorflow in <a href="https://www.tensorflow.org/alpha/tutorials/generative/dcgan#the_generator" rel="nofollow noreferrer">tensorflow official site</a>.</p>
<p>Here I came across this point </p>
<pre class="lang-py prettyprint-override"><code>generator = make_generator_model()... | <p>That method is defined as</p>
<pre><code> def make_generator_model():
model = tf.keras.Sequential()
model.add(layers.Dense(4*4*1024, use_bias = False, input_shape = (100,)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
</code></pre>
<p>As you can see, what you get is a <... | python|python-3.x|tensorflow | 0 |
354,729 | 56,857,927 | Use of window() function in TensorFlow Dataset to access more than one row | <p>I've got a problem with transforming the dataset read from .csv files by <a href="https://www.tensorflow.org/api_docs/python/tf/data/experimental/CsvDataset" rel="nofollow noreferrer">tf.data.experimental.CsvDataset</a> into "timeseries".</p>
<p>What I'm trying to do is to access more than one row of the dataset at... | <p>Ok after tackling the problem from many sides I've finally managed to achieve the required result. I've got two solutions: one that processes features and labels as separate datasets and the one which appies transformations to the dataset in one go. Both might be useful depending on the use case.</p>
<ol>
<li>Proce... | python|tensorflow|tensorflow-datasets | 1 |
354,730 | 56,726,000 | Implementing and running a 3D U-net for denoising of synthetic data | <p>I'm building a u-net for denoising some synthetic images over time. My data is (256,256,128,1) which is 256*256 grayscale images over 128 time-steps(trajectory is random cosin). I have 120 images, so the whole dataset is of shape (120,256,256,128,1). I've added 5% random noise to this data for getting the noisy data... | <p>The size of the input you feed to your network (256x256x128 images) is enormous, on top of that you have 64 layers on the first level of your architecture. I guess, only taking into account the conv layers of the first level should allready aggregate into something like 10 to 100Gb of GPU memory which is way too big... | python|tensorflow|keras | 1 |
354,731 | 56,809,410 | How to convert a string of hours and minutes to minutes in python? | <p>I have a column in my dataframe df:</p>
<pre><code>Time
2 hours 3 mins
5 hours 10 mins
1 hour 40 mins
</code></pre>
<p>I want to create a new column in df 'Minutes' that converts this column over to minutes</p>
<pre><code>Minutes
123
310
100
</code></pre>
<p>Is there a python function to do this?</p> | <p>You need to convert it via <code>to_datetime</code></p>
<pre><code>s=pd.to_datetime(df.Time.replace({'hours':'hour'},regex=True),format='%H hour %M mins')
s.dt.hour*60+s.dt.minute
Out[406]:
0 123
1 310
2 100
Name: Time, dtype: int64
</code></pre>
<p>Or we using <code>str.findall</code> with <code>numpy</... | python|pandas | 11 |
354,732 | 56,544,635 | Using face-api.js in Cordova with Android | <p>Cordova does not allow loading local files to TensorFlow training used in face-api.js, however this problem does not happen in iOS or Browser. How to solve?</p> | <p>To load the files locally, which will be decompressed and used for training in TensorFlow, you must tell the Face-api.js library which method will be called to read files, setting the values in faceapi.env.monkeyPatch.</p>
<p>I can not say that this is the best solution, but it was a solution that worked. I separa... | android|cordova|tensorflow|face-api | 0 |
354,733 | 56,523,318 | Tensorflow: create vector based on input | <p>I am not really experienced in Tensorflow and I am doing one of those things that would apparently be very easy, but getting stuck at it.</p>
<p>I need to create a matrix given an input using a tensorflow layer.
Here is what I've gotten:</p>
<pre class="lang-py prettyprint-override"><code>def createTransformationM... | <p>You can do it using tensorflow </p>
<pre><code>scaleValue = tf.placeholder("float32", 2)
b = tf.expand_dims(scaleValue, axis=1)
c = tf.constant([[1,0,0,0]], 'float32')
d = tf.matmul(b,c)
res = tf.reshape(d, shape=[-1])
with tf.Session() as sess:
print (sess.run([res], feed_dict={scaleValue: np.array([1,3])}))
... | python|tensorflow|keras | 1 |
354,734 | 56,488,316 | Inverse row selection for concatenated pandas dataframe | <p>For the development of a regression multiple experiments are recorded. All experiments are concatenated into a single dataframe. For the training I'd like to use every n'th sample and visualize the performance on the remaining data.</p>
<p>The following code works fine for a single experiment, but fails with the co... | <p>You can use modulo with <code>10</code> and compare by <code>0</code> for boolean mask and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>, <code>~</code> is for invert mask:</p>
<pre><code>df = pd.... | python|pandas|dataframe | 2 |
354,735 | 56,446,579 | Pandas function to return country name using city name | <p>I am trying to create a column in the pandas dataframe that reads the city name from a column in the same dataframe and outputs the country name.</p>
<p>I tried looking into geolocation but couldn't find an accurate solution other than getting the lat and long of the city and using that lat and long to derive the c... | <p>What code are you using so far?</p>
<p>Maybe have a second dataframe of all cities/countries and just reference against that?</p> | pandas|geolocation | 0 |
354,736 | 56,465,346 | LSTM timesteps in Sonnet | <p>I'm currently trying to learn <code>Sonnet</code>.</p>
<p>My network (incomplete, the question is based on this):</p>
<pre><code>class Model(snt.AbstractModule):
def __init__(self, name="LSTMNetwork"):
super(Model, self).__init__(name=name)
with self._enter_variable_scope():
self.l... | <p>We generally wrote the RNNs in Sonnet to work on a single timestep basis, as for Reinforcement Learning you often need to run one timestep to pick an action, and without that action you can't get the next observation (and the next input timestep) from the environment. It's easy to unroll a single timestep module ove... | python|tensorflow|deep-learning|eager-execution|sonnet | 1 |
354,737 | 56,716,616 | How to deal with triplet loss when at time of input i have only two files i.e. at time of testing | <p>I am implementing a siamese network in which i know how to calculate triplet loss by picking anchor, positive and negative by dividing input in three parts(which is a handcrafted feature vector) and then calculating it at time of training.</p>
<pre><code>anchor_output = ... # shape [None, 128]
positive_output = ..... | <p>Colab notebook with test code on CIFAR 10:
<a href="https://colab.research.google.com/drive/1VgOTzr_VZNHkXh2z9IiTAcEgg5qr19y0" rel="nofollow noreferrer">https://colab.research.google.com/drive/1VgOTzr_VZNHkXh2z9IiTAcEgg5qr19y0</a></p>
<p>The general idea:</p>
<pre><code>from tensorflow import keras
from tensorflow... | keras|deep-learning|lstm|tensorflow-estimator|loss-function | 0 |
354,738 | 56,497,509 | Merge regression results back to original dataframe | <p>I am working on a simple time series linear regression using statsmodels.api.OLS, and am running these regressions on groups of data based on an identifier variable. I have been able to get the grouped regressions working, but am now looking to merge the results of the regressions back into the original dataframe an... | <p><strong>UPDATE:</strong></p>
<p>I've solved this with a relatively simple method, in which I converted the series to a list, and just set a new column in the dataframe equal to the list. However, I would be really curious to hear if others have better/different/unique solutions to this problem. Thanks!</p> | python-3.x|regression|pandas-groupby | 0 |
354,739 | 56,819,142 | Tensorflow Lite tflite Process finished with exit code -1073741819 | <p>Posting a question that took me a while to figure out and was not able to find when searching, hopefully this helps someone else save sometime.</p>
<p>When calling set.tensor program crashes with a response Process finished with exit code -1073741819</p>
<pre><code>interpreter = tf.lite.Interpreter(model_path="..... | <p>Call to allocate_tensors is required before set_tensor can be called</p>
<pre><code>interpreter = tf.lite.Interpreter(model_path="....")
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
interpreter.allocate_tensors()
interpreter.set_tensor(input_details[0]['index']... | python|tensorflow-lite | 1 |
354,740 | 56,510,866 | How to create a fixed length tf.Dataset from generator? | <p>I have a generator which yields infinite amount of data (Random image crops). I would like to create a <code>tf.Dataset</code> based on let's say 10,000 first data points and cache it to use them to train models? </p>
<p>Currently, I have a generator which takes 1-2 seconds to create each datapoint and this is the ... | <p>You can use the <code>Dataset.cache</code> function with the <code>Dataset.take</code> function to accomplish this.</p>
<p>If everything fits in memory its as simple as doing something like this:</p>
<pre class="lang-py prettyprint-override"><code>def generate_example():
i = 0
while(True):
print ('yielding... | tensorflow|tensorflow-datasets | 1 |
354,741 | 56,485,336 | How to change values based on neighboring values on the same column in Pandas | <p>I am working with a dataset using Pandas dataframe. There are two columns, <code>timestamp</code> and <code>pump_state</code>. The latter is either 0 or 1. </p>
<p><a href="https://i.stack.imgur.com/p1pF4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p1pF4.png" alt="enter image description here... | <p>Consider the following approach (follow comments):</p>
<pre><code>import numpy as np
import pandas as pd
# create sample data
NUM = 30
df = pd.DataFrame({
'timestamp': pd.date_range(start='5/29/2019 00:00:00',
periods=NUM, freq='1min'),
'pump_state': [1] * NUM})
df.loc[5:8, '... | python|pandas|dataframe|time-series | 0 |
354,742 | 56,573,651 | How can I create a lineplot for datetime-indexed data without converting the index to another format? | <p>I'd like to make a time-series graph. I have a pd.DataFrame that is indexed by datetime. I'd like to graph this datetime data directly instead of converting it to ordered categorical. I don't want to use <code>sns.tsplot()</code> because it warns about deprecation.</p>
<pre class="lang-py prettyprint-override"><cod... | <p>Create <code>DatetimeIndex</code> is not necessary:</p>
<pre><code>df = pd.DataFrame(numberofmice)
df["time"] = pd.to_datetime(df["time"])
sns.lineplot(data = df, x = "time", y = "mice")
</code></pre>
<p>Your code working like pointed @anky_91 - instead <code>time</code> use <code>df.index</code>:</p>
<pre><code... | python|pandas|seaborn | 2 |
354,743 | 56,617,528 | Keras model doest not provide same results after converting into tensorflow-js model | <p>Keras model performs as expected in python but after converting the model the results are different on the same data.</p>
<p>I tried updating the keras and tensorflow-js version but still the same issue.</p>
<p>Python code for testing:</p>
<pre><code>
import keras
import cv2
model = keras.models.load_model("keras... | <p>It has to do with the image used for the prediction. The image needs to have completely loaded before the prediction.</p>
<pre><code>imEl.onload = function (){
const pred =
model.predict(preprocessing_img(imgEl)).dataSync()
const class_index = tf.argMax(pred);
}
</code></pre> | javascript|python|keras|tensorflowjs | 1 |
354,744 | 56,632,776 | Pandas: Extract data from column A that does not exist for column B | <p>My data includes invoices and I have to check whether an invoice was already paid or not.
For each invoice I loop through all report dates. If on one day, the invoice doen't show up, it means the customer already made a payment and of course it won't appear again on subsequent days.</p>
<p>You can see from the tab... | <p>Here is on way we using <code>crosstab</code>, then is the the invoice eq to 0 , which means the previous invoices should be count as <code>Closed</code></p>
<pre><code>s=pd.crosstab(df.ReportDate,df.InvoiceNo).eq(0)
Newdf=(s.iloc[::-1,:].cummax()&~s).replace({True:'Closed',False:'Open'}).stack().reindex(pd.Mu... | python|python-3.x|pandas|jupyter-notebook | 4 |
354,745 | 56,687,527 | Keras model.fit() Raises Error About Unspecified Parameter `steps_per_epoch` | <p>I am trying to fit a Keras model with a tf.Dataset as my dataset. I specify the parameter <code>steps_per_epoch</code>. However, this error is raised:
<code>ValueError: When using iterators as input to a model, you should specify the 'steps_per_epoch' argument.</code> This error confuses me because I am specifying t... | <p>Your <em>train_dataset</em> and <em>validation_dataset</em> are Datasets (take a look at the documentation of tensorflow for the function <em>from_tensor_slices</em>): <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs... | python|tensorflow|keras | 0 |
354,746 | 56,748,245 | Searching in a dataframe cell for lists of lists | <p>I have a dataframe which consists of 2 columns Error and Comments
My Error column would contain a list of strings in each cell. I need help in writing code for searching through the dataframe and find the comments of that row where my Dataframe Error content matches with user input val1.</p>
<p>i have tried the giv... | <p>Simplist is compare lists if need exact match:</p>
<pre><code>m = df['Error'].apply(lambda x: x == val1)
</code></pre>
<p>If order should be different, convert to sets and comapre:</p>
<pre><code>m = df['Error'].apply(lambda x: bool(set(x) == set(val1)))
</code></pre>
<p>If need intersection:</p>
<pre><code>m =... | pandas|dataframe | 2 |
354,747 | 56,769,626 | How to in-place update values in multiple columns in a DataFrame on condition from another using assignment operator? | <p>There is one DataFrame <code>S</code> to be updated:</p>
<pre><code>n ii a b c
0 True 10 11 1.20
1 False 2 0 NaN
2 True 34 75 2.14
3 True 22 88 0.02
</code></pre>
<p>from another DataFrame <code>T</code> with another set of columns</p>
<pre><code> a b c
8 13 1.19
31 72 2.10
20 83 ... | <p>Try returning the dataframe:</p>
<pre><code> def process(S):
ii = S.ii
# ... internal calculations that produce T
columns = ['a', 'b', 'c']
S.loc[ii, columns] = T[columns] # < ----- in-place update
return S
</code></pre>
<p>And call the function like this:</p>
<pre><c... | python|pandas|dataframe|pass-by-reference | 0 |
354,748 | 56,455,063 | How to delete an element by index from a numpy array in Python 3? | <p>I want to delete an element from a numpy array by index.</p>
<p>The commands </p>
<pre class="lang-py prettyprint-override"><code>arr = np.linspace(-5,5,10)
del arr[0]
</code></pre>
<p>The code above throws an error saying <code>cannot delete array elements</code>.
Using <code>pop</code> doesn't work either. What... | <p>You should use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html" rel="nofollow noreferrer"><code>np.delete</code></a> for it.</p>
<pre><code>arr = np.linspace(-5,5,10)
arr = np.delete(arr, 0)
</code></pre> | python-3.x|numpy | 1 |
354,749 | 56,771,226 | einstein summation of boolean arrays in numpy | <p>Einstein summation (numpy.einsum) of boolean arrays in numpy doesn't produce expected results. Numpy.einsum function does logical operations on boolean arrays, which is questionable in the numeric contexts. </p>
<pre><code># summation of a boolean numpy array
x = numpy.array([True, False, True])
print(numpy.sum(x... | <p>The difference here is that <code>sum</code> casts the <code>boolean</code> into integers before summing, while <code>einsum</code> skips this step except if you specify it explicitly.</p>
<p>Try:</p>
<pre><code>print(numpy.einsum('i->', x, dtype=int))
</code></pre> | numpy|boolean-operations|numpy-einsum | 3 |
354,750 | 56,856,065 | How to define conditional for pandas column of several last row in data frame? | <p>Supposed I have a data frame with these rows as the last 8 row. </p>
<pre class="lang-py prettyprint-override"><code>time a b b d e f
2018-03-04 10:00:00 86.0 194.0 1.084830 1.088466 196.000000 84.333333
2018-03-04 10:30:00 37.0 59.0 1.0822... | <p>IIUC, <code>g</code> is not already in <code>df.columns</code>, so we can do:</p>
<pre><code>vals = np.arange(0.7,1,0.05)
df['g'] = 0
df.iloc[-len(vals):, -1] = vals
</code></pre> | python|pandas | 5 |
354,751 | 56,687,531 | Vectorize a function for a GroupBy Pandas Dataframe | <p>I have a Pandas dataframe sorted by a datetime column. Several rows will have the same datetime, but the "report type" column value is different. I need to select just one of those rows based on a list of preferred report types. The list is in order of preference. So, if one of those rows has the first element i... | <p>You can avoid to use <code>groupby</code>. One way could be to categorize your column 'REPTYPE' with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Categorical.html#pandas.Categorical" rel="nofollow noreferrer"><code>pd.Categorical</code></a> and then <a href="https://pandas.pydata.org/pa... | numpy|vectorization|pandas-groupby | 0 |
354,752 | 56,612,570 | Convert a list of NumPy np.uint8 arrays to a np.unicode_ array | <p>I have a list of NumPy variably-sized arrays with <code>dtype=np.uint8</code>(these represent UTF-8 encoded strings). How do I efficiently and fast convert this list to a single <code>dtype=np.unicode_</code> array?</p>
<pre><code>l = [np.frombuffer(b'asd', dtype = np.uint8), np.frombuffer(b'asdasdas', dtype = np.u... | <p><strong>update</strong></p>
<p>It turns out Python utf-8 codec can be used to decode
an ndarray directly, without needing to copy its contents
to a bytesstring with <code>.tostring()</code> first: with the codecs
module it is possible to retrieve the callable that
coverts utf-8 byte-sequences to unicode strings wit... | python|string|numpy|unicode | 0 |
354,753 | 56,759,112 | How to fix 'The kernel appears to have died. It will restart automatically" caused by pytorch | <p>I have a strange problem with Pytorch. When i use something torch functions with tensors like tensor.rehsape or torch.transpose, i don't have problem and all ok, even when i've created network all ok, but when i wanna train network my jupyter crashed.</p>
<p><img src="https://i.stack.imgur.com/pDyTo.png" alt="cras... | <p>The hint for the solution is available, via the Jupyter notebook terminal (if opened it directly and not via the anaconda interface), where a more proper error code appears</p>
<blockquote>
<p>OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll
already initialized. OMP: Hint This means that multipl... | jupyter|pytorch | 3 |
354,754 | 56,576,297 | Best way to save nested list/array to CSV for easy loading later | <p>Firstly, let me apologize for the html table. It's the only way I could make this skewed table look good.</p>
<p>Now as for the question, I'm trying to find the best way to save an array of coordinates (<strong>Coordinates</strong> column in table) in a column of a csv file for later use.</p>
<p>At the moment, aft... | <p>I would store the column as a separate <code>npy</code> file.</p>
<p>I would use at save time:</p>
<pre><code>df.assign(Coordinates=np.nan).to_csv(...) # save all columns except coordinates to a csv file
np.save('... .npy', df['Coordinates'].values) # save coordinates as a npy file
</code></pre>
<p>Then at load... | python|csv|numpy|dataframe | 0 |
354,755 | 56,782,077 | Get max value of column for rows where a condition is met | <p>I have a DataFrame that looks like this:</p>
<pre><code>| Age | Married | OwnsHouse |
| 23 | True | False |
| 35 | True | True |
| 14 | False | False |
| 27 | True | True |
</code></pre>
<p>I want to find the highest age of anyone who is married and owns a house. The answer here wo... | <p>Your first approach is solid, but here is a simple option:</p>
<pre><code>df[df['Married'] & df['OwnsHouse']].max()
Age 35.0
Married 1.0
OwnsHouse 1.0
dtype: float64
</code></pre>
<p>Or, just the age:</p>
<pre><code>df.loc[df['Married'] & df['OwnsHouse'], 'Age'].max()
# 35
</code></pre... | python|python-3.x|pandas | 5 |
354,756 | 56,548,280 | How to extrapolate missing values with groupby - Python? | <p>I have the following dataset:</p>
<pre><code>data = {
'date': ['1/1/2019', '1/2/2019', '1/3/2019', '1/4/2019', '1/1/2019', '1/2/2019', '1/3/2019', '1/4/2019'],
'account_id': [1, 1, 1, 1, 2, 2, 2, 2],
'value_1': [1, 2, 3, 4, 5, 6, 7, 8],
'value_2': [1, 3, 6, 9, 10, 12, 14, 16]
}
df = pd.DataFrame(data,index ... | <p>You can modify the linked answer as follows:</p>
<pre><code>def extrapolate(df):
new_max = df.index.max() + pd.to_timedelta('30D')
dates = pd.date_range(df.index.min(), new_max, freq='D')
ret_df = df.reindex(dates)
x = np.arange(len(df))
# new x values
new_x = pd.Series(np.arange(len(ret_d... | python|pandas | 0 |
354,757 | 56,638,423 | Find absolute minimum between two numpy arrays but keep the sign | <p>Consider two arrays of different length:</p>
<pre><code>A = np.array([58, 22, 86, 37, 64])
B = np.array([105, 212, 5, 311, 253, 419, 123, 461, 256, 464])
</code></pre>
<p>For each value in <code>A</code>, I want to find the smallest absolute difference between values in <code>A</code> and <code>B</code>. I use ... | <p>Let's use broadcasted subtraction here. We then use <code>argmin</code> to find the absolute minimum, then extract the values in a subsequent step.</p>
<pre><code>u = A[:,None] - B
idx = np.abs(u).argmin(axis=1)
u[np.arange(len(u)), idx]
# array([-47, 17, -19, 32, -41])
</code></pre>
<p>This uses pure NumPy bro... | python|pandas|numpy|difference | 5 |
354,758 | 56,482,935 | Unable to convert Dataframe object to datetime | <p>I have been to trying to convert dataframe object to datetime with format Y-m-d. My data looks like:</p>
<p><code>pdi.head()</code></p>
<pre><code> Date Predicted_Linear_Regression
0 [2005-02-16T00:00:00.000000000] 0.000663
1 [1982-02-03T00:00:00.000000000] 0.000666
2 [1995-07-1... | <p>Your <code>Date</code> column contains lists of dates, not dates. Extract the first element of each list, then convert to datetime:</p>
<pre><code>pd.to_datetime(df['Date'].str[0])
</code></pre> | python-3.x|pandas|dataframe|datetime | 1 |
354,759 | 56,799,334 | Pandas: Calculate average of values for a time frame | <p>I am working on a large datasets that looks like this:</p>
<pre><code>Time, Value
01.01.2018 00:00:00.000, 5.1398
01.01.2018 00:01:00.000, 5.1298
01.01.2018 00:02:00.000, 5.1438
01.01.2018 00:03:00.000, 5.1228
01.01.2018 00:04:00.000, 5.1168
.... , ,,,,
31.12.2018 23:59:59.000, 6.3498
</code></pre>
<p>The ... | <p>Perhaps this will work?</p>
<pre><code>import numpy as np
# Create one year of random data spaced evenly in 1 minute intervals.
np.random.seed(0) # So that others can reproduce the same result given the random numbers.
time_idx = pd.date_range(start='2018-01-01', end='2018-12-31', freq='min')
df = pd.DataFrame({'... | python|python-3.x|pandas | 3 |
354,760 | 56,759,263 | Pandas replicate one column from a row to a column in multiple rows in another dataframe | <p>I have this dataframe(df1) with one row</p>
<pre><code>text val1 val2
"test" 3 2
</code></pre>
<p>I have this dataframe(df2) with many rows</p>
<pre><code>text val5
"this" 1
"is" 2
"test" 3
</code></pre>
<p>I want to create a new column in df2 and put value from first dataframe in this new colum... | <p>Actually i have tried the same in different manner. Try the below code :</p>
<pre><code>mask = (df2['text'] == df1['text'][0])
import numpy as np
val2 = []
for data in mask:
if data:
val2.append(df1['val2'][0])
else:
val2.append(np.nan)
df2['val2'] = val2
</code></pre>
<p>Now if you loo... | python-3.x|pandas | 0 |
354,761 | 56,722,461 | Time Text to Secs and Milliseconds | <p>I have a field in a data frame that has a string of time </p>
<pre class="lang-py prettyprint-override"><code>df['Time'] which equals
01:21.46
</code></pre>
<p>what I would like to do is have that convert to secs and milliseconds so </p>
<p>81.46</p>
<p>I have tried to make a datetime but that has made more pro... | <p>You don't need <code>datetime</code> for this,</p>
<pre><code>def time_split(time_str):
minute,second=time_str.split(":")
if minute[0]==0:
minute = minute[1]
second,milisecond=second[0:2],second[2:]
if second[0]==0:
second = second[1]
return int(minute),int(second),float(miliseco... | python|pandas | 0 |
354,762 | 56,517,766 | Is there a fast way to add two three dimensional arrays? | <p>The three lines of code adding the masking [height, width, 1] to the R, G, B also [height, width, 1] drag the runtime of this code from less than a second to 5 - 10 minutes.</p>
<p>Is there a better way to add two numpy matrices? I know it is from the addition process because when I take it out it runs significant... | <h2>Fixing the Slow-Down</h2>
<p>The specific issue that slows down your program lies in the call to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.expand_dims.html" rel="nofollow noreferrer"><code>np.expand_dims(...)</code></a>:</p>
<pre><code>basis = np.expand_dims(mask, 1)
</code></pre>
<p>Th... | python|numpy|opencv | 2 |
354,763 | 56,847,807 | Loss of Multi-Output Model in Pytorch | <p>I have a multi-output model in PyTorch when I train them using the same loss and then to backpropagate I combine the loss of both the output but when one output loss decreases others increase and so on. How can I fix the problem?</p>
<pre class="lang-py prettyprint-override"><code>def forward(self, x):
#neural ... | <p>If you have two different loss functions, and you finish the <code>forwards</code> for both of them separately, it is smart to do </p>
<pre><code>(loss1 + loss2).backward()
</code></pre>
<p>This is computationally efficient.</p>
<p>What you should achieve is to make your model learn, how to minimize the loss.
So... | machine-learning|deep-learning|pytorch | -1 |
354,764 | 25,886,070 | Scipy stats.skew -- IndexError: tuple index out of range | <p>I am getting a wierd error.... this doesn't happen if I use np.random.random instead of np.random.randint </p>
<pre><code>>>> import numpy as np
>>> import scipy.stats as stats
>>> rdata = np.random.randint(5000)
>>> skew = stats.skew(rdata)
Traceback (most recent call last):
F... | <p>Take a closer look at the docstrings for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html" rel="nofollow"><code>numpy.random.randint</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random.html" rel="nofollow"><code>numpy.random.random</co... | python|numpy|random|scipy|outofrangeexception | 1 |
354,765 | 25,537,137 | 32 bit RGBA numpy array from PIL image | <p>Say I load an image as:</p>
<pre><code>> image = Image.open('temp.png')
<PngImagePlugin.PngImageFile image mode=RGBA size=1200x600 at 0x112F0C488>
</code></pre>
<p>Notice that the image dimensions are <code>1200x600</code>.</p>
<p>I would like to retrieve this image as a 2D numpy array, where each entry... | <h3>1. Indexing</h3>
<p>You're misunderstanding the way that NumPy indexes images. NumPy prefers <a href="http://en.wikipedia.org/wiki/Row-major_order" rel="noreferrer">row-major indexing</a> (<em>y</em>, <em>x</em>, <em>c</em>) for images <a href="http://docs.scipy.org/doc/numpy/reference/internals.html#multidimensio... | python|numpy|computer-vision|python-imaging-library | 5 |
354,766 | 25,909,984 | Missing data, insert rows in Pandas and fill with NAN | <p>I'm new to Python and Pandas so there might be a simple solution which I don't see. </p>
<p>I have a number of discontinuous datasets which look like this: </p>
<pre><code>ind A B C
0 0.0 1 3
1 0.5 4 2
2 1.0 6 1
3 3.5 2 0
4 4.0 4 5
5 4.5 3 3
</code></pre>
<p>I now look f... | <p><code>set_index</code> and <code>reset_index</code> are your friends. </p>
<pre><code>df = DataFrame({"A":[0,0.5,1.0,3.5,4.0,4.5], "B":[1,4,6,2,4,3], "C":[3,2,1,0,5,3]})
</code></pre>
<p>First move column A to the index:</p>
<pre><code>In [64]: df.set_index("A")
Out[64]:
B C
A
0.0 1 3
0.5 4 2
... | python|numpy|pandas | 51 |
354,767 | 25,538,584 | python changing string to date | <p>I have 2 date columns (begin and end) in a data frame where the dates are in the following string format '%Y-%m-%d %H:%M:%S.%f'. How can I change these into date format in python? I also want to create a new column that shows the difference in days between the end and begin dates.</p>
<p>Thanks in advance!</p> | <p>If you're using a recent version of pandas you can pass a format argument to <code>to_datetime</code>:</p>
<pre><code>In [11]: dates = ["2014-08-27 19:53:06.000", "2014-08-27 19:53:15.002"]
In [12]: pd.to_datetime(dates, format='%Y-%m-%d %H:%M:%S.%f')
Out[12]:
<class 'pandas.tseries.index.DatetimeIndex'>
[20... | python|pandas|string-formatting|date-formatting | 4 |
354,768 | 25,471,457 | Generating random numbers with a given probability density function | <p>I want to specify the <a href="http://en.wikipedia.org/wiki/Probability_density_function" rel="nofollow noreferrer">probability density function</a> of a distribution and then pick up N random numbers from that distribution in Python. How do I go about doing that?</p> | <p>In general, you want to have the inverse cumulative probability density function. Once you have that, then generating the random numbers along the distribution is simple:</p>
<pre><code>import random
def sample(n):
return [ icdf(random.random()) for _ in range(n) ]
</code></pre>
<p>Or, if you use NumPy:</p>
... | python|numpy|scipy|probability | 10 |
354,769 | 25,516,995 | Efficiently update values held in scoring matrix | <p>I am continuously calculating correlation matrices where each time the order of the underlying data is randomized. When a correlation score with randomized data is greater than or equal to the original correlation determined with ordered data, I would like to update the corresponding cell in a scoring matrix with +1... | <p>Assuming everything has the same indices, this should work as expected and be pretty quick.</p>
<pre><code>scoring_matrix += (data_random >= data_sorted).astype(int)
</code></pre> | python|numpy|matrix|pandas | 2 |
354,770 | 25,754,913 | Trying to Solve Monty Hall in Python | <p>I'm trying to understand this solution of the Monty Hall problem, I understand most of the code, but am stuck on two pieces. </p>
<p>Below is the code, but specifically I'm stuck on these two parts</p>
<pre><code>result[bad] = np.random.randint(0,3, bad.sum())
</code></pre>
<p>and the entire <code>switch_guess</c... | <blockquote>
<p>… specifically I'm stuck on these two parts</p>
</blockquote>
<pre><code>result[bad] = np.random.randint(0,3, bad.sum())
</code></pre>
<p>Let's break this down into pieces. It may help to reduce that <code>10000</code> to something small, like <code>5</code>, so you can print out the values (either ... | python|numpy | 2 |
354,771 | 25,577,352 | Plotting CDF of a pandas series in python | <p>Is there a way to do this? I cannot seem an easy way to interface pandas series with plotting a CDF. </p> | <p>I believe the functionality you're looking for is in the hist method of a Series object which wraps the hist() function in matplotlib</p>
<p>Here's the relevant documentation</p>
<pre><code>In [10]: import matplotlib.pyplot as plt
In [11]: plt.hist?
...
Plot a histogram.
Compute and draw the histogram of *x*. The ... | python|pandas|series|cdf | 92 |
354,772 | 25,870,923 | How to square or raise to a power (elementwise) a 2D numpy array? | <p>I need to square a 2D numpy array (elementwise) and I have tried the following code:</p>
<pre><code>import numpy as np
a = np.arange(4).reshape(2, 2)
print a^2, '\n'
print a*a
</code></pre>
<p>that yields:</p>
<pre><code>[[2 3]
[0 1]]
[[0 1]
[4 9]]
</code></pre>
<p>Clearly, the notation <code>a*a</code> gives m... | <p>The fastest way is to do <code>a*a</code> or <code>a**2</code> or <code>np.square(a)</code> whereas <code>np.power(a, 2)</code> showed to be considerably slower.</p>
<p><code>np.power()</code> allows you to use different exponents for each element if instead of <code>2</code> you pass another array of exponents. Fr... | python|arrays|numpy | 78 |
354,773 | 26,293,142 | efficient way to compute numpy.ndarray internal multiplication | <p>I have two matrices a and b with the same shape:</p>
<pre><code>a = np.ndarray(shape=(3, 2), dtype=int)
b = np.ndarray(shape=(3, 2), dtype=int)
</code></pre>
<p>and i want the internal multiplication of them like:</p>
<pre><code> 1 2
a = 4 5
7 8
9 8
b = 6 5
3 2
</code></pre>
<p>and i want the res... | <p>You can do simple multiplication first and then sum over axis=0:</p>
<pre><code>>>> a = np.array([[1, 2], [4, 5], [7, 8]])
>>> b = np.array([[9, 8], [6, 5], [3, 2]])
>>> (a * b).sum(axis=0)
array([54, 57])
</code></pre> | python|performance|numpy|matrix|multidimensional-array | 2 |
354,774 | 26,372,538 | Pandas HDFStore - Get Last Record from Multiple Tables | <p>I have a large number of data frames exported to a series of HDFStore files through Pandas. I need to be able to quickly pull in the most recent record, for each of these dataframes on demand.</p>
<p>The setup:</p>
<pre><code><class 'pandas.io.pytables.HDFStore'>
File path: /data/storage_X100.hdf
/X1 ... | <p>use <code>start</code> and/or <code>stop</code> to specify a range of rows. You still need to iterate over the keys, but this will just select the last row of a table, so should be very fast.</p>
<pre><code>In [1]: df = DataFrame(np.random.randn(10,5))
In [2]: df.to_hdf('test.h5','df',mode='w',format='table')
In ... | python|pandas|hdfstore|hdf | 4 |
354,775 | 26,313,881 | Add calculated column to a pandas pivot table | <p>I have created a pandas data frame and then converted it into pivot table.</p>
<p>My pivot table looks like this:</p>
<pre><code>Operators TotalCB Qd(cb) Autopass(cb)
Aircel India 55 11 44
Airtel Ghana 20 17 3
Airtel India 41 9 9
Airtel Kenya 9 ... | <p>This should do it, assuming <code>data</code> is your pivoted dataframe:</p>
<pre><code>data['Autopass(cb)%'] = data['Autopass(cb)'] / data['TotalCB'] * 100
data['Qd(cb)%'] = data['Qd(cb)'] / data['TotalCB'] * 100
</code></pre>
<p>Adding a new column to a dataframe is as simple as <code>df['colname'] = new_series<... | python|pandas | 7 |
354,776 | 26,408,751 | python pandas groupby optimisation | <p>I have a large dataframe of many rows and columns and I need to groupby one of the columns 'group'
here is a small example</p>
<pre><code> group rank word
0 a 0.739631 entity
1 a 0.882556 physical_entity
2 b 0.588045 abstraction
3 b 0.640933 thing
4 ... | <p>I think the idea is to <code>groupby</code> first, then <code>sort</code> each <code>group</code> and keep the first observation using <code>.agg()</code>:</p>
<pre><code>In [192]:
print df
group rank word
0 a 0.739631 entity
1 a 0.882556 physical_entity
2 b 0.588045 ... | python|pandas|group-by | 1 |
354,777 | 26,129,509 | Biopython for similarity matrix - looking for better performance | <p>I want to calculate the similarity between a input sequence and a short fragment from the sequence. The outcome is a similarity matrix with each position being the score of the alignment.
It works, but is unfortunately slow. How could I implement the loop more efficiently in python and numpy? I am also thinking to u... | <p>First I would try to compute only half of the diagonal, <strong>starting</strong> the inner loop in the <code>i</code> point and avoiding the calculation of previous alignments:</p>
<pre><code>for i in range(full_size - frag_size):
curr_frag = seq[i:i + frag_size]
# ADD THIS ----vvvvv------------vvv
fo... | python|numpy|biopython | 2 |
354,778 | 26,371,325 | Using a function while slicing | <p>Looking for some clarification and some direction here</p>
<p>--Given a simple Pandas data frame</p>
<pre><code>df = pd.DataFrame(['123abc','456xyz'],columns=['foo'])
foo
0 123abc
1 456xyz
</code></pre>
<p>--This works</p>
<pre><code>df.foo.str[:3]
0 123
1 456
</code></pre>
<p>--This does not</p>... | <p>If you are just wanting to extract just the numbers from the strings then you can use <code>extract</code>:</p>
<pre><code>In [23]:
df = pd.DataFrame(['123abc','45xyz'],columns=['foo'])
df.foo.str.findall(r'\d+').str[0]
Out[23]:
0 123
1 45
Name: foo, dtype: object
</code></pre>
<p>If you just want to slic... | python|pandas | 1 |
354,779 | 26,314,495 | python/numpy: vectorize nested for loops | <p>I have been trying to shrug off my FORTRAN sensibilities over the last few days and embrace python's vecotrization to get rid of as many loops as possible and optimise my code.</p>
<p>A number of posts on this site have been incredibly useful in achieving this, but I have hit a problem I’m not sure how to solve.</p... | <p>Looks like <code>some_function</code> takes 3 scalars and returns a scalar. <code>B</code> is also scalar. So</p>
<pre><code> B = x + y + z
for p in range( 10 ):
BL[p] = BL[p] + 2. * B
for q in range( 10 ):
BLB[q] = BLB[q] + BL[q]
</code></pre>
<p>can be simplifie... | python|for-loop|numpy|vectorization|nested-loops | 0 |
354,780 | 67,095,317 | TensorFlow SGD decay parameter | <p>I am using TensorFlow 2.4.1 and Python3.8 for Computer Vision based CNN models such as VGG-18, ResNet-18/34, etc. My question is specific to weight decay declaration. There are two ways of defining it:</p>
<ol>
<li>The first is by declaring it for each layer using 'kernel_regularizer' parameter for 'Conv2D' layer</l... | <p><a href="https://github.com/keras-team/keras/releases/tag/2.3.0" rel="nofollow noreferrer">Decay argument</a> has been deprecated for all optimizers since Keras 2.3.
For learning rate decay, you should use <a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/schedules/LearningRateSchedule" rel="no... | python|tensorflow | 2 |
354,781 | 66,866,552 | How to fetch preceding ids on fly using pandas | <p>I have a data frame like as shown below</p>
<pre><code>df = pd.DataFrame({'subject_id':[11,11,11,12,12,12],
'test_date':['02/03/2012 10:24:21','05/01/2019 10:41:21','12/13/2011 11:14:21','10/11/1992 11:14:21','02/23/2002 10:24:21','07/19/2005 10:24:21'],
'original_enc':['A742','... | <p>Use only one column for <code>groupby</code>:</p>
<pre><code>test_df['previous_enc_id'] = test_df.groupby('subject_id')['enc_id'].shift()
</code></pre> | python|pandas|dataframe|numpy|pandas-groupby | 1 |
354,782 | 67,166,657 | Pandas data frame values are plotting with their individual labels and not on the correct scale | <p>I have a pandas data frame,</p>
<pre><code> Time Sc Recovery Y Recovery ... Tb Recovery Ho Recovery Bi Recovery
0 6:18:16 84.0 84.6 ... 90.1 91.3 88.2
1 6:20:13 92.5 82.5 ... 85.8 87.6 85.0
2 6:22:10 91.8 83.9 ... 85.2 ... | <p>My problem was that my values were not floats or integers, so matplotlib had no way of knowing where my values were to be placed.</p>
<p>If that doesn't fix your problem then try looking at this source I found for formating your x and y ticks:
<a href="https://www.overcoded.net/matplotlib-axis-ticks-frequency-331416... | python|pandas|dataframe|matplotlib|plot | 0 |
354,783 | 67,074,095 | Replicate multidimensional NumPy array on an axis up-to specific value | <p>I have a two-dimensional NumPy array with shape</p>
<blockquote>
<p>(2, 2)</p>
</blockquote>
<p>Example array</p>
<blockquote>
<p>array([[1, 2],
[3, 4]])</p>
</blockquote>
<p>I am trying to have it copy on just the first axis until it reaches the shape:</p>
<blockquote>
<p>(5, 2)</p>
</blockquote>
<p>Example result ... | <pre><code>np.repeat(arr, [3, 2], axis=0)
</code></pre> | python|arrays|numpy|multidimensional-array | 1 |
354,784 | 67,167,763 | Mean of the previous n rows | <p>I have the following Data Frame:</p>
<pre><code>date = pd.date_range('2021-01-01', periods = 21, freq = '60S')
df = pd.DataFrame({ 'Date': date,
'Type':'DM','DM','DM','DS','DS','DS','DS','DM','DS','DS','DM','DM','DM','DM','DM','DM','DM','DS','DS','DS','DM'],
'Value': [105,130,104,205,206,208,222,160,105,130,104,205,... | <pre><code>df["mean"] = df[df.Type == "DM"].rolling(3)["Value"].mean()
df["mean"] = df["mean"].ffill()
df.loc[df.Type == "DM", "mean"] = np.nan
print(df)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code> ... | python|pandas | 2 |
354,785 | 67,063,906 | Convert date format using python | <p>I am trying to convert the date format from a column in an specific format in python</p>
<p><strong>Input Data:</strong></p>
<pre><code> Date
01/10/2020
01-mar-2020
1-june-2019
01/01/2021
1/11/2020
</code></pre>
<p><strong>Output looking for:</strong></p>
<pre><code> Date
2020-10-01
2020-03-01
2019-06-01
2... | <p>Just use <code>dayfirst</code> parameter of <code>to_datetime()</code> method and set that equal to <code>True</code>:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], errors='coerce',dayfirst=True)
</code></pre>
<p>Finally:</p>
<pre><code>df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')
</code></pre>
<p>Now if... | python|pandas | 2 |
354,786 | 66,962,496 | Need help filling in blanks on a pandas Dataframe | <p>I have a dataframe that contains Names and associated numbers. The issue is that the values don't associate with the Names. Here is an example below:</p>
<p><a href="https://i.stack.imgur.com/hp30d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hp30d.png" alt="enter image description here" /></a>... | <pre><code>import pandas as pd
import numpy as np
</code></pre>
<p>If your <strong>'Name'</strong> column don't contains NaN's(it contains <code>''</code> or <code>' '</code>) then make use of <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer"><code>replace()</co... | python|pandas|numpy | 1 |
354,787 | 67,062,057 | csv file converted to parquet adds 'e0' to end of values | <p>I am running a test to populate a table in Redshift. I added mock data to a csv file and then converted to parquet with pandas. I'm using the COPY command to get the data from the parquet file in the s3 bucket to my Redshift database.</p>
<p>I got the error:</p>
<pre><code> 'file has an incompatible Parquet schem... | <p>It looks like you are writing the parquet file with these fields in scientific notation. This is where e stands for 'times ten to the power of' eg. 1.1e2 equals 110. Check your formatting pandas.</p> | pandas|amazon-redshift | 1 |
354,788 | 67,155,475 | How to strip time and from from a non-datetime string in Python? | <p>I have strings that look something like this:</p>
<p>"Audio was recorded at 21:50:00 02/07/2019 (UTC) by device 243B1F05 at gain setting 2 while battery state was 3.6V."</p>
<p>I attempted to use the parser from dateutil:</p>
<pre><code>from dateutil.parser import parse
s = "Audio was recorded at 21:5... | <p>Use re, for regex:</p>
<pre><code>from dateutil.parser import parse
import re
s = "Audio was recorded at 21:50:00 02/07/2019 (UTC) by device 243B1F05 at gain setting 2 while battery state was 3.6V."
t = re.search(' (\d{2}:\d{2}:\d{2} \d{2}\/\d{2}\/\d{4}) ', s).group(1)
dt = parse(t, fuzzy=True)
print(dt)... | python-3.x|pandas | 2 |
354,789 | 66,821,613 | join dictionaries in single data frame on a common key | <pre><code>d1 = [{'x':'a','y':0.5}, {'x':'b', 'y':3.0}]
d2 = [{'x':'a','w':1.0}, {'x':'b', 'w':1.0,'z':1.5}]
</code></pre>
<p>I'd like to "join" these dictionaries in a data frame on the common key <code>x</code></p>
<pre><code> x y w z
0 a 0.5 1.0 NaN
1 b 3.0 1.0 1.5
</code></pre>
<p>I tri... | <h3><code>toolz.dicttoolz.merge</code></h3>
<p>This is a pure python/dictionary merge.<br />
The first thing I'll do is to rearrange the list of dictionaries such that I have a hashable key, namely <code>x</code>.</p>
<pre><code>d1_ = {d['x']:d for d in d1}
d2_ = {d['x']:d for d in d2}
</code></pre>
<p>This assumes the... | python|pandas | 2 |
354,790 | 67,084,303 | why is jupyter notebook not accepting my csv file link? | <p><em><strong>I'm trying to visualize some data with a seaborn plot and the csv file link keeps returning the error '"link.csv" is not one of the example datasets.'
What am I doing wrong?</strong></em></p>
<pre><code>import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt... | <p>Seaborn <code>load_dataset()</code> function is used to load an example dataset from Seaborn library. It is not used to load just any data, just the data specified in their documentation (specifically data that can be found in <a href="https://github.com/mwaskom/seaborn-data" rel="nofollow noreferrer">https://github... | python|pandas|seaborn | 1 |
354,791 | 67,036,638 | Pandas filter and create new columns | <p>I have a Pandas df:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(['Air type:1', 'Space kind:2', 'water', np.NaN], columns = ['A'])
A
0 Air type:1
1 Space kind:2
2 water
3 NaN
</code></pre>
<p>I would like to split the entries in A that have a ":" in them into two n... | <p>Another version, using <code>.extract()</code>:</p>
<pre><code>df[["B", "C"]] = df["A"].str.extract(r"([^:]+):(.*)")
print(df)
</code></pre>
<p>Prints:</p>
<pre><code> A B C
0 Air type:1 Air type 1
1 Space kind:2 Space kind 2
2 w... | python|pandas | 3 |
354,792 | 67,068,424 | PyTorch - How to use Avg 2d Pooling as a dataset transform? | <p>In Pytorch, I have a dataset of 2D images (or alternatively, 1 channel images) and I'd like to apply average 2D pooling as a transform. How do I do this? The following does not work:</p>
<pre><code> omniglot_dataset = torchvision.datasets.Omniglot(
root=data_dir,
download=True,
transform=t... | <p>yutasrobot's answer above is perfectly satisfactory. Another answer I received on the PyTorch forum can be found at <a href="https://discuss.pytorch.org/t/how-to-use-avg-2d-pooling-as-a-dataset-transform/117995/2" rel="nofollow noreferrer">https://discuss.pytorch.org/t/how-to-use-avg-2d-pooling-as-a-dataset-transfor... | pytorch|torchvision | 1 |
354,793 | 67,136,029 | Formatting a distorted python data frame | <p>Is there a direct method to set rows of a distorted table in corresponding order?</p>
<p>Herewith I have attached an snapshot of the distortion.</p>
<p><img src="https://i.stack.imgur.com/H3hSN.png" alt="Table here" /></p> | <p>here is a way to read your excel file if i understand your question correctly</p>
<pre><code>df = pd.read_excel('path\filename.xlsx',sheet_name='name of your sheet name')
df.columns = ['col_name','values']
temp_1_df = df['col_name'].copy()
temp_1_df.dropna(inplace=True)
temp_2_df = df['values'].copy()
temp_2_df.drop... | pandas | 0 |
354,794 | 67,017,456 | Fast unique index based on outer conditions in Python | <p>Suppose I have two lists of indices <code>index1 = [1, 1, 2, 2, 3, 4, 5]</code>, <code>index2 = [0, 1, 2, 3, 4, 5, 6]</code> and a <code>numpy</code> array <code>x=array([1.3876, -0.573, -1.765, 1.2202, -1.6507, -0.653, 0.9196, 0.0935])</code> that generates <code>index2</code>. I would like to keep unique indices i... | <p>I assuming that:</p>
<ul>
<li>indices are always integers between 0 and <code>len(x)-1</code> included;</li>
<li>there is a lot of values (i.e. at least thousands of values);</li>
<li>the output order of <code>index1</code> does not matter as long as the relation between <code>index1</code> and <code>index2</code> i... | python|performance|numpy | 1 |
354,795 | 66,909,576 | Tensorflow 2 Object Detection API - Official Models: Can't change other parameters in params_override argument | <p>When using any of the Object Detection models from TensorFlow's Official Models in the ModelZoo, there is an argument called params_override. Based on the code here (<a href="https://github.com/tensorflow/models/blob/master/official/modeling/hyperparams/params_dict.py" rel="nofollow noreferrer">https://github.com/te... | <p>I saw the additional instructions a little bit further down the README document.</p>
<ol>
<li>You can create a YAML config file along with the command, e.g. my_retinanet.yaml. This file specifies the parameters to be overridden, which should at least include the following fields.</li>
</ol>
<pre><code>python3 ~/mode... | python|tensorflow|object-detection-api | 0 |
354,796 | 67,085,832 | remove all row if the row is duplicate in python | <p>I try to drop the duplicate row but I got the the error code: 'Series' object has no attribute 'remove'.</p>
<p>May I know how can I replace the 'remove' command or fix the attributeError?</p>
<p>If the row is duplicate in allMYemail.csv, the row must remove.
There is my code:</p>
<pre><code>import csv
import re
imp... | <p>Since your question is not clear on what it wants to do,
If you only want to remove fully duplicate rows in just one df then @Renaud 's solution will do the job.
If you want to remove the rows based on the duplicates in a single column 'email' then try this:</p>
<pre><code>def firstline(d):
return(d.reset_index(d... | python|pandas|dataframe|csv | 2 |
354,797 | 66,974,852 | Function to write dataframe to SQL | <p>I have this function that takes in a dataframe and writes it to SQL as a table.</p>
<pre><code>def insert(df):
with connection.cursor as cur:
cur.execute('''create tablaexyz.xyz
(ID integer,
first_name varchar(100),
last_name v... | <p>Without reference to a specific RDBMS, it might be hard to "guess" the correct datatypes for all corner cases. On the other hand, e.g. DuckDB provides functionality to integrate pandas dataframes as queryable views (see section <a href="https://duckdb.org/docs/api/python" rel="nofollow noreferrer">efficien... | python|sql|pandas | 0 |
354,798 | 67,077,104 | Filter duplicate rows based on a condition in Pandas | <p>I have the below dataframe where there are duplicate rows based on a column "Reason".</p>
<pre><code>No Reason
123 -
123 -
345 Bad Service
345 -
546 Bad Service
546 Poor feedback
</code></pre>
<p>I have subsetted these rows based on</p>
<pre><code>df_duplicates = df[df['No'].duplicated() == True]... | <blockquote>
<p>filter them only when the "Reason" for the corresponding duplicated row is both missing OR if any one is missing.</p>
</blockquote>
<p>You can do:</p>
<pre><code>df[df['Reason'].eq('-').groupby(df['No']).transform('any')]
#or df[df['Reason'].isna().groupby(df['No']).transform('any')]
</code></... | pandas|duplicates | 2 |
354,799 | 66,761,218 | Pandas groupby apply function with an array of functions | <p>I have a dataset like this (example purpose)</p>
<pre><code>df = pd.DataFrame({
'Store' : [100, 100, 100, 100, 101, 101, 101, 101],
'Product' : [5, 3, 10, 1, 3, 11, 2, 5],
'Category' : ['A', 'B', 'C', 'A', 'B', 'A', 'C', 'A'],
'Sales' : [100, 235, 120, 56, 789, 230, 300, 35]
})
</code></pre>
<p>So it... | <p>you can use <code>pivot_table</code> and <code>unstack</code></p>
<pre><code>table = df.pivot_table(index=['Store', 'Category'], values=['Sales'], aggfunc='sum')#.unstack().add_prefix('Category_')
t_sales = table.sum(level=0)
table=table.div(table.sum(level=0)).mul(100).unstack().add_prefix('Category_')
table.assign... | python|pandas|group-by|data-science|feature-engineering | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.