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 |
|---|---|---|---|---|---|---|
8,700 | 44,762,560 | puzzling when pandas reading text seperated by whitespace | <p><code>pandas</code> could not read text as follows:</p>
<pre><code>NothGrassland Meteor Sites
MTCLIM v4.3 OUTPUT FILE : Mon Jun 26 16:57:31 2017
year yday Tmax Tmin Tday prcp VPD srad daylen
(deg C) (deg C) (deg C) (cm) (Pa) (W m-2) (s)
1961 1 -24.08 -36.19 ... | <p>For me works <code>sep="\s+"</code> or <code>delim_whitespace=True</code>:</p>
<pre><code>import pandas as pd
from pandas.compat import StringIO
temp=u"""NothGrassland Meteor Sites
MTCLIM v4.3 OUTPUT FILE : Mon Jun 26 16:57:31 2017
year yday Tmax Tmin Tday prcp VPD srad daylen
... | pandas | 2 |
8,701 | 44,580,199 | pytest 3.0.7 error when import pandas 2.20.1 | <p>Anyone have the same issue I have for running pytest with following error. The way I install the environment is
download python from <a href="https://www.python.org/downloads/" rel="nofollow noreferrer">https://www.python.org/downloads/</a> and install pkg file
create req.file and install package by pip install -r r... | <p>so what i have tried is using virtual env to set up python project and reinstall all package to make sure project environment is isolated to my local. so set up virtual env and then no problem to install pandas anymore</p>
<pre><code>$pip3 install virtualenv
$virtualenv --python=/usr/bin/python3.6 <path/to/new/p... | python-3.x|pandas|pytest | 0 |
8,702 | 61,046,870 | How to save weights of keras model for each epoch? | <p>I want to save keras model and I want to save weights of each epoch to have best weights. How I do that?</p>
<p>Any help would be appreciated.</p>
<p><strong>code</strong>:</p>
<pre><code>def createModel():
input_shape=(1, 22, 5, 3844)
model = Sequential()
#C1
model.add(Conv3D(16, (22, 5, 5), stri... | <p>model.get_weights() will return a tensor as a numpy array. You can save those weights in a file with extension .npy using np.save().</p>
<p>To save weights every epoch, you can use something known as callbacks in Keras.</p>
<pre class="lang-python prettyprint-override"><code>from keras.callbacks import ModelCheckp... | python|tensorflow|machine-learning|keras|deep-learning | 3 |
8,703 | 60,999,536 | Seaborn example to plot with date on the X axis not showing dates | <p>I am executing this code from <a href="https://seaborn.pydata.org/generated/seaborn.lineplot.html" rel="nofollow noreferrer">this page</a> and it is not working as expected.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np, pandas as pd; plt.close("all")
index = pd.date_range("1 1 2000", peri... | <p>It works fine on my system, running your code without changing anything:</p>
<p><a href="https://i.stack.imgur.com/FHyAP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FHyAP.png" alt="enter image description here"></a></p>
<p>I obviously have a different default figure size and style, but that ... | python|pandas|seaborn | 1 |
8,704 | 60,915,372 | How to apply linear layer to 2D layer only in one dimension (by row or by column) - partially connected layers | <p>I'm trying to apply a linear layer to a 2D matrix of tensors connecting it only by column as in the picture below.</p>
<p><a href="https://i.stack.imgur.com/IOiBE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IOiBE.png" alt="1D linear layer applied to 2D layer"></a></p>
<p>The input shape is <... | <p>The PyTorch <a href="https://pytorch.org/docs/stable/nn.html?highlight=linear#torch.nn.Linear" rel="nofollow noreferrer"><code>nn.Linear</code></a> module can be applied to multidimensional input, the linear will be applied to the last dimension so to apply by column the solution is to swap rows and columns.</p>
<p... | neural-network|artificial-intelligence|pytorch | 2 |
8,705 | 71,452,476 | Looping through Dataframe to delete "near duplicate" rows | <p>I have a dataframe and would like to get rid of rows where a particular column has matching values to subsequent values. An example can be found below:</p>
<p>Original Data Frame:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Cat1</th>
<th>Cat2</th>
<th>Cat3</th>
<th>Averag... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>drop_duplicates</code></a></p>
<p>By default it uses all columns to identify the duplicated rows:</p>
<pre><code>df.drop_duplicates()
</code></pre>
<p>To limit to a subset of columns:</p>
... | pandas|dataframe|loops|for-loop | 0 |
8,706 | 71,639,199 | Python Pandas Error: 'DataFrame' object has no attribute 'Datetime' when trying to create an average of time periods | <p>I am trying to create a dataframe (df) that creates a sample sums, means, and standard deviations of the following 12 monthly return series by month from another dataframe cdv file called QUESTION1DATA.csv and he head of performance data looks like this: <a href="https://i.stack.imgur.com/kxKrc.png" rel="nofollow no... | <p><code>to_datetime</code> is available in <code>Pandas</code> and should be use as follows:</p>
<pre><code>>>pd.to_datetime('13000101', format='%Y%m%d', errors='ignore')
datetime.datetime(1300, 1, 1, 0, 0)
</code></pre>
<p>In your case <code>portlist</code> is a list and hence the code is throwing error.</p>
<p... | python|pandas|file|datetime | 0 |
8,707 | 42,555,276 | tensorflow - run optimizer op on a large batch | <p>Normally, we call the run command with the optimizer operation as input to update the trainable parameters of some model:</p>
<pre><code>session.run(model.optimizer_op, feed_dict={model.X: X_batch, model.y: y_batch})
</code></pre>
<p>But when the batch size is large, X_batch can't fit in GPU memory.
How can I spli... | <p>This depends mainly on your GPU memory size. However, it is hard to fit your entire dataset along with the model and its required operations (i.e. predicting probabilities). Thus, you would need to think of batching in a different perspective. I assume your code goes along these lines:</p>
<pre><code># Model Defini... | python|memory|tensorflow | 0 |
8,708 | 42,379,818 | Correct way to set new column in pandas DataFrame to avoid SettingWithCopyWarning | <p>Trying to create a new column in the netc df but i get the warning</p>
<pre><code>netc["DeltaAMPP"] = netc.LOAD_AM - netc.VPP12_AM
C:\Anaconda\lib\site-packages\ipykernel\__main__.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexe... | <p>As it says in the error, try using <code>.loc[row_indexer,col_indexer]</code> to create the new column.</p>
<pre><code>netc.loc[:,"DeltaAMPP"] = netc.LOAD_AM - netc.VPP12_AM.
</code></pre>
<h2>Notes</h2>
<p>By the <a href="http://pandas-docs.github.io/pandas-docs-travis/indexing.html#indexing-view-versus-copy" re... | python|pandas | 46 |
8,709 | 42,574,644 | Tensorflow installation on Ubuntu permission error | <p>I installed virtual box on my Windows 10 machine and installed Ubuntu on the virtual box. Then I installed Tensorflow on Ubuntu by following <a href="https://www.tensorflow.org/install/install_linux" rel="nofollow noreferrer">this instructions from Tensorflow.org</a>. Everything went well including pip install and s... | <p>It seems like you need elevated permissions to write to <code>/usr/local/lib</code>.</p>
<p>Executing <code>sudo pip install tensorflow</code> will install tensorflow using root privileges.</p>
<p>(Also, your problem is with Ubuntu, not with Windows 10! Your host system has no influence in the permissions of the g... | python|ubuntu|tensorflow | 1 |
8,710 | 43,403,147 | how to create a encode_raw tensorflow function? | <p>I am trying to perform the opposite of what tf.decode_raw does.</p>
<p>An example would be given a tensor of dtype=tf.float32, I would like to have a function encode_raw() that takes in a float tensor and returns a Tensor of type string.</p>
<p>This is useful because then I can use tf.write_file to write the file.... | <p>I would recommend writing numbers as text with <code>tf.as_string</code>. If you really want to write them as a binary string, however, it turns out to be possible:</p>
<pre><code>import tensorflow as tf
with tf.Graph().as_default():
character_lookup = tf.constant([chr(i) for i in range(256)])
starting_dtype =... | tensorflow | 3 |
8,711 | 72,256,025 | Stop pandas dataframe from converting to vector | <p>I have below <code>pandas dataframe</code></p>
<pre><code>import pandas as pd
df = pd.DataFrame({'product name': ['laptop', 'printer', 'printer',], 'price': [1200, 150, 1200], 'price1': [1200, 150, 1200]})
</code></pre>
<p>Now I want to print one single row</p>
<pre><code>df.iloc[1,:]
</code></pre>
<p>This gives be... | <p>Actually, <code>df.iloc[1,:]</code> is not a <code>pd.DataFrame</code> it is a <code>pd.Series</code> you can check it with <code>type(df.iloc[1, :])</code>. So row or column doesn't have any sense in these case.</p>
<p>To keep it as a <code>pd.DataFrame</code> you could select a range of rows of length 1: <code>df.... | python-3.x|pandas | 1 |
8,712 | 50,312,585 | compare rows in dataframe to change values | <p>I'm using python3 and there are two data frames: df1 df2</p>
<pre><code>df1
num1 num2 num3 class
0 1 2 3 0
1 1 2 4 0
2 1 2 5 0
3 2 2 4 0
df2
num1 num2 num3 class
0 1 2 3 1
1 1 2 4 1
</code></pre>
<p>I want to compare the two data frames so that the rows i... | <p>You could do an <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">outer merge</a> on <code>['num1', 'num2', 'num3']</code>, and keep the <code>class</code> column only from <code>df2</code> (so drop the <code>class</code> from <code>df1</code>):</p... | python|pandas | 2 |
8,713 | 50,479,021 | Keras callback causes error : You must feed a value for placeholder tensor 'conv2d_1_input' with dtype float | <p>im new to tensorflow and keras and deep learning scene.
i tried to make a simple neural network to recognize emotion in fer2013 database and keep running into this error after training the first epoch</p>
<blockquote>
<pre><code>File "main.py", line 92, in <module>
train(image_data, label_data, conv_arch,... | <p>I had a similar problem. The issue appeared when using TensorBoard callback with the <code>histogram_freq</code> parameter greater than 0.</p>
<p>Clearing tensorflow session right before creating the model fixed it</p>
<pre><code>import keras.backend as K
K.clear_session()
</code></pre>
<p>(from this <a href="htt... | python|tensorflow|keras | 4 |
8,714 | 45,557,110 | Force Pandas to keep multiple columns with the same name | <p>I'm building a program that collects data and adds it to an ongoing excel sheet weekly (read_excel() and concat() with the new data). The issue I'm having is that I need the columns to have the same name for presentation (it doesn't look great with x.1, x.2, ...). </p>
<p>I only need this on the final output. Is th... | <p>You can add spaces to the end of the column name. It will appear the same in a Excel, but pandas can distinguish the difference.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns=['x','x ','x '])
df
x x x
0 1 2 3
1 4 5 6
2 7 8 9
</code></pre> | python|excel|pandas | 1 |
8,715 | 54,281,633 | How to set a color for a specific row in pandastable, using python 3.7 | <p>I have created a simple pandastable form in python, but I have some problems getting the rows in colors.</p>
<p>I have tried the following definition from the documentation, but it does not seem to work?</p>
<pre><code>pt.setRowColors(rows=rows1, clr="red")
</code></pre>
<p>Here is my code:</p>
<pre><code># pand... | <p>The <a href="https://pandastable.readthedocs.io/en/latest/pandastable.html#pandastable.core.Table.setRowColors" rel="nofollow noreferrer">pandastable API docs</a> suggest you should use a Hex value for the colour:</p>
<blockquote>
<p>setRowColors(rows=None, clr=None, cols=None)[source]
Set rows color from menu.... | python|pandas | 0 |
8,716 | 54,346,347 | Getting pandas column name based on bool mask | <p>I have two dataframes, <code>df1</code> and <code>df2</code>, where one value is changed in <code>df2</code>.
I'm trying to get the column name for the value that changed.</p>
<p>df1</p>
<pre><code> type method
0 variable method1
1 variable method1
2 variable method1
3 variable method1
</code></pre>... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow noreferrer"><code>DataFrame.any</code></a> for test at least one <code>True</code> per column and then filter columns names:</p>
<pre><code>print (changes.any())
type True
method False
dtype: bool
p... | python|pandas | 4 |
8,717 | 71,173,925 | Sort data across columns per row and return column names in new variable | <p>I have a table with 3 columns - a, b, and c. How do I add a 4th column (d) which stores the column names of dates in sorted order (across columns) while ignoring the NaT cells - example shown below:</p>
<pre><code> a b c d
|:------------:|:------------:|:-------------:|:... | <p>Use <code>np.argsort</code> for positions columns with remove missi values and convert to lists in lambda function:</p>
<pre><code>df['d'] = df.apply(lambda x: list(df.columns[np.argsort(x.dropna())]), axis=1)
</code></pre>
<p>Or sorting per rows, remove NaNs and convert index to lists:</p>
<pre><code>df['d'] = df.a... | python-3.x|pandas | 1 |
8,718 | 71,093,763 | Pandas - assign incremented value if condition in other column is matched | <p>This is my dataset:</p>
<pre class="lang-py prettyprint-override"><code># dataset
DATE NUMBER
0 10. 9. 2002 NaN
1 10. 9. 2002 8.0
2 10. 9. 2002 9.0
3 10. 9. 2002 NaN
4 10. 9. 2002 11.0
</code></pre>
<p>I would like to add a new column 'T_ID' where I will store number that increments ... | <p>Use</p>
<pre><code>df['T_ID'] = df.NUMBER.isna().cumsum()
</code></pre>
<p>This uses <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.isna.html" rel="nofollow noreferrer"><code>isna()</code></a> to get an array with bools. This can be used by <a href="https://pandas.pydata.org/docs/reference/ap... | pandas|dataframe | 3 |
8,719 | 71,232,640 | Getting "AttributeError: Can only use .str accessor with string values" while transposing the data in dataframe | <p>I have one source file with structure as below:</p>
<pre><code>ID|RcrdId|SrcId|Name|Address
row1|r1|src1#src2|val1#val2|val4#val5
row2|r2|src2#src1|val11#val12|val14#val15
row3|r3|src1|val44|val23
</code></pre>
<p>I need to include values in Name and Address fields only for Src2 value which is present in SrcID colum... | <p>Split your values to get a list then explode it into multiple rows. Filter out your rows and fill missing values with original ones:</p>
<pre><code>cols = ['SrcId', 'Name', 'Address']
df[cols] = df[cols].apply(lambda x: x.str.split('#')).explode(cols) \
.query("SrcId == 'src2'").reindex... | python|pandas|dataframe | 1 |
8,720 | 52,086,175 | How to split a large dataframe into multiple dataframe based on the first 3 characters of the column names? | <p>I have a huge dataframe (2077 columns) that I would like to break down into multiple dataframes (78 exactly). Each column name starts with a 3 letter acronym (coc, cou, wam etc.). How would I split up the master dataframe into multiple smaller data frames based on the first 3 letters of the column names?</p>
<p>Tha... | <p>Call <code>groupby</code> with a lambda and iterate over the group object to separate them out into a list of DataFrames:</p>
<pre><code>df_list = [g for _, g in df.groupby(by=lambda x: x[:3], axis=1)]
</code></pre>
<p>If you want a mapping of {prefix : dataFrame} instead, you can create a dictionary:</p>
<pre><c... | python|string|pandas|dataframe|multiple-columns | 1 |
8,721 | 52,306,416 | tf.summary.image seems not work for estimator prediction | <p>I want visualize my input image use tf.estimator when predict, but it seems tf.summary.image not save image. But it work for training.</p>
<p>This is my code in model_fn:</p>
<pre><code>...
summary_hook = tf.train.SummarySaverHook(
save_secs=2,
output_dir='summary',
scaffold=tf.train.Scaffo... | <p>I would assume that you need to put the summary ops (histogram/image) <em>before</em> calling <code>merge_all</code> so that <code>merge_all</code> actually has something to merge.</p>
<pre><code>...
tf.summary.histogram("logit",logits)
tf.summary.image('feat', feat)
summary_hook = tf.train.SummarySaverHook(
sa... | python|tensorflow|tensorflow-estimator | 2 |
8,722 | 52,200,710 | Pandas+seaborn faceting with multidimensional dataframes | <p>In Python <code>pandas</code>, I need to do a facet grid from a multidimensional <code>DataFrame</code>.
In columns <code>a</code> and <code>b</code> I hold scalar values, which represent conditions of an experiment.
In columns <code>x</code> and <code>y</code> instead I have two numpy arrays. Column <code>x</code> ... | <p>I think the best way to go is to split the nested arrays first and then create a facet grid with seaborn.</p>
<p>Thanks to this post (<a href="https://stackoverflow.com/questions/38372016/split-nested-array-values-from-pandas-dataframe-cell-over-multiple-rows">Split nested array values from Pandas Dataframe cell ov... | python|pandas|seaborn|facet | 2 |
8,723 | 60,372,163 | scipy.linalg.expm of hermitian is not special unitary | <p>If I have a (real) hermitian matrix, for instance </p>
<pre><code>H = matrix([[-2. , 0.5, 0.5, 0. ],
[ 0.5, 2. , 0. , 0.5],
[ 0.5, 0. , 0. , 0.5],
[ 0. , 0.5, 0.5, 0. ]])
</code></pre>
<p>(This matrix is hermitian; it is the Hamiltonian of a 2-spin Ising chain with coupling to a... | <p>you're using the wrong norm. Use</p>
<pre><code>np.sqrt( np.sum( np.abs(T[0])**2 ) )
</code></pre>
<p>Or even in a shorter way</p>
<pre><code>np.linalg.norm( T[0] )
</code></pre> | python|numpy|matrix|scipy|linear-algebra | 2 |
8,724 | 60,632,054 | Filter rows from multiple date columns based on the specific year and month in Pandas | <p>For the given dataframe as follows:</p>
<pre><code> id start_date end_date
0 1 2014/5/26 2014/5/27
1 2 2014/6/27 2014/6/28
2 3 2014/7/20 2014/7/21
3 4 2014/9/12 2014/9/13
4 5 2014/10/10 2014/10/11
5 6 2020/3/20 2020/4/21
6 7 2020/4/10 2020/4/11
7 8 2020/4/15 2020/... | <p>I think here is better <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> for processing by columns, <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow... | python-3.x|pandas|dataframe|datetime | 1 |
8,725 | 60,411,332 | Unpacking list of lists of dicts column in Pandas dataframe | <p>I have <code>df_in</code> where one of the columns is a <code>list</code> of <code>lists</code> of <code>dicts</code>:</p>
<pre><code>df_in = pd.DataFrame({
'A': [1, 2, 3],
'B': [
[{'B1': 1, 'B2': 2, 'B3': 3}, {'B1': 4, 'B2': 5, 'B3': 6}, {'B1': 7, 'B2': 8, 'B3': 9}],
[{'B1': 10, 'B2': 11, '... | <p>Use dictionary comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html" rel="nofollow noreferrer"><code>DataFrame.pop</c... | python|pandas|dataframe | 4 |
8,726 | 60,410,049 | Holoviews Image with HoverTool tooltip from different datasource | <p>I have a 100x100 km grid GeoDataFrame (Mollweide) that I am plotting as a <code>gv.Image</code> with classified values (8 Categories) through Holoviews/Bokeh:</p>
<pre class="lang-py prettyprint-override"><code># convert GeoDataFrame to xarray object
xa_dataset = gv.Dataset(grid.to_xarray(), vdims=f'{metric}_cat', ... | <p>Found the answer myself: even when using <code>gv.Image</code>, I can specify additional <code>vdims</code>, e.g.:</p>
<pre class="lang-py prettyprint-override"><code># xa_dataset from GeoDataFrame
# with additional vdims
xa_dataset = gv.Dataset(
grid.to_xarray(),
vdims=[f'{metric}_cat', 'postcount', 'userc... | python|bokeh|geopandas|holoviews|geoviews | 2 |
8,727 | 72,751,931 | pandas: calculate the daily average, grouped by label | <p>I want to create a graph with lines represented by my <code>label</code></p>
<p>so in this example picture, each line represents a distinct label</p>
<p><a href="https://i.stack.imgur.com/4jlue.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4jlue.png" alt="enter image description here" /></a></p>... | <p>You can use <code>.pivot</code> (<a href="https://pandas.pydata.org/docs/reference/api/pandas.pivot.html?highlight=pivot" rel="nofollow noreferrer">documentation</a>) function to create a convenient structure where <code>datetime</code> is index and the different <code>labels</code> are the columns, with <code>count... | python|pandas|dataframe|matplotlib | 2 |
8,728 | 59,847,311 | series.where on a series containing lists | <p>I have this series called <code>hours_by_analysis_date</code>, where the index is <code>datetime</code>s, and the values are a list of ints. For example:</p>
<pre><code>Index |
01-01-2000 | [1, 2, 3, 4, 5]
01-02-2000 | [2, 3, 4, 5, 6]
01-03-2000 | [1, 2, 3, 4, 5]
</code></pre>
<p>I want to return all the indi... | <p>It's confused between comparing two array-like objects and equality test for each element.</p>
<p>You can use <code>apply</code>:</p>
<pre><code>hours_by_analysis_date.apply(lambda elem: elem == [1,2,3,4,5])
</code></pre> | pandas|series | 1 |
8,729 | 59,781,612 | Concat dataframe without doubling the index | <p>I want to concat those 2 dataframe: </p>
<pre><code> circulating_supply
currency
BCH 18225550
BTC 18163250
ETH 109296900
QASH 350000000
XRP 43653780000 ... | <p>Join the dataframes (which does a left join on the indices by default) and specify a suffix for each column since they have the same name.</p>
<pre><code>>>> df1.join(df2, lsuffix='_1', rsuffix='_2')
circulating_supply_1 circulating_supply_2
currency
B... | python|pandas | 0 |
8,730 | 59,721,119 | Installing OpenCV into PyCharm | <p>Idk if this is a stackoverflow-appropriate post so forgive if the question is misplaced. I'm trying to install OpenCV into my Pycharm IDE through the conda virtual environment. I typed <code>conda install -c conda-forge opencv</code> inside the PyCharm terminal and it has been doing this for 11 hours and God knows... | <p>While you can install packages directly in PyCharm by going to <code>file->settings</code> select <code>Project Interpreter</code> and click on the '+' icon on the top right (see image)
<a href="https://i.stack.imgur.com/kxuZm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kxuZm.png" alt="ente... | opencv|intellij-idea|computer-vision|pycharm|pytorch | 1 |
8,731 | 54,992,495 | Count values occurrences in pandas and put the result in one single string | <p>My dataframe looks like this:</p>
<pre><code>id column1 column2
a x l
a x n
a y n
b y l
b y m
</code></pre>
<p>Currently, I generate value counts with this</p>
<pre><code>def value_occurences(grouped, column_name):
return (grouped[column_name].value_c... | <p>You can first generate groups of the <code>df</code> by <code>df.groupby(['id'])</code> and apply <code>value_counts</code> to each group:</p>
<pre class="lang-py prettyprint-override"><code>import io, pandas as pd
def seqdict(x):
return ', '.join('{}:{}'.format(*i) for i in sorted(x.items()))
def value_occur... | python|pandas | 0 |
8,732 | 54,997,082 | Creating Pandas Dataframe row on the basis of other column value | <p>I have a dataframe having three column :</p>
<pre><code>order_no product quantity
0 5bf69f 3
0 5beaba 2
1 5bwq21 1
1 5bf69f 1
</code></pre>
<p>I want to create row if quantity value is greater than 1 like this:</p>
<pre><code>order_no product quantity
0 5b... | <p>First is necessary unique index values, so if necessary:</p>
<pre><code>df = df.reset_index(drop=True)
</code></pre>
<p>Then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.repeat.html" rel="nofollow noreferrer"><code>Index.repeat</code></a> by column <code>quantity</code> and e... | python|pandas | 3 |
8,733 | 49,552,204 | How to open the log `global_step/sec` like `tf.estimator.Estimator` using MonitoredTrainingSession? | <p>I meet a small probelms but I don't how to deal with it.</p>
<p>When I use the <code>tf.estimator.Estimator</code>, it will log two line each step like:</p>
<pre><code>INFO:tensorflow:global_step/sec: 1110.33
INFO:tensorflow:loss = 0.00026583532, step = 9376 (0.090 sec)
</code></pre>
<p>But when I use the <code>t... | <p>OK, I find the question. The reason is that the arg <code>log_every_steps</code> of <code>tf.train.LoggingTensorHook</code> not match the <code>log_step_count_steps</code> of <code>MonitoredTrainingSession</code>.</p>
<p>Note, the two args must be same, if different, such 5 and 10, the <code>global_step/sec</code> ... | python|tensorflow | 1 |
8,734 | 49,646,959 | How can I include missing items using groupby in Pandas? | <p>Let's say I have a dataframe with the following columns: date, time, day, month, year, description, price, type, manufacturer</p>
<p>Using pandas and <code>value_counts()</code>, I can get the count for every unique item in a column:</p>
<pre><code>df.manufacturer.value_counts()
</code></pre>
<p>Also, using group... | <p>I think you can convert days to <code>categorical</code>s, so then if use <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html#operations" rel="nofollow noreferrer"><code>groupby + mean</code></a> get <code>NaN</code>s for missing categories:</p>
<pre><code>df = pd.DataFrame({
'day': ['Monday',... | python|pandas | 3 |
8,735 | 49,394,681 | Reading multiple CSVs into different arrays | <p>Update. Here is my code. I am importing 400 csv files into 1 list. Each csv file is 200 rows and 5 columns. My end goal is to sum the values from the 4th column of each row or each csv file. The below code imports all the csv files. However, I am struggling to isolate 4th column of data from each csv file from the l... | <p>So you have a list of 100 arrays. What can you tell us about their shapes?</p>
<p>If they all have the same shape you could use</p>
<pre><code>arr = np.stack(data)
</code></pre>
<p>I expect <code>arr.shape</code> will be (100,200,5)</p>
<pre><code>fthcol = arr[:,:,3] # 4th column
</code></pre>
<p>If they are... | python|arrays|list|loops|numpy | 0 |
8,736 | 73,206,882 | How to append I'd after the last maximum number to next numbers | <p>I have 2 dataframes and I wan to append one with the other.When appended I want the column with I'd as continuous numbers.
Example:</p>
<p>Df1:
| I'd | value |
|-----|-------|
| 1. | ABC |
| 2. | Bcs. |</p>
<p>Df2:
| I'd | value |
|-----|-------|
| 1. | Xyx |
| 2. | Yus |</p>
<p>Expected output:
| I'd | va... | <p>I am not sure if I understood your question, but if it is what I think it is, you want a "concatenation" of dataframes.</p>
<p>The command is pd.concat (see the docs: <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference... | python|pandas|dataframe | 1 |
8,737 | 73,268,612 | Range mapping in Python | <p><strong>MAPPER DATAFRAME</strong></p>
<pre><code> col_data = {'p0_tsize_qbin_':[1, 2, 3, 4, 5] ,
'p0_tsize_min':[0.0, 7.0499999999999545, 16.149999999999977, 32.65000000000009, 76.79999999999973] ,
'p0_tsize_max':[7.0, 16.100000000000023, 32.64999999999998, 76.75, 6759.850000000006]}
map_df = p... | <p>Try using <code>pd.cut()</code></p>
<pre><code>bins = map_df['p0_tsize_min'].tolist() + [map_df['p0_tsize_max'].max()]
labels = map_df['p0_tsize_qbin_'].tolist()
df.assign(p0_tsize_qbin_mapped = pd.cut(df['val'],bins = bins,labels = labels))
</code></pre>
<p>Output:</p>
<pre><code> id val p0_tsize_qbin_mapped
0 ... | python-3.x|pandas|dataframe|range-map | 2 |
8,738 | 73,459,767 | Loading a tokenizer on huggingface: AttributeError: 'AlbertTokenizer' object has no attribute 'vocab' | <p>I'm trying to load a <code>huggingface</code> model and tokenizer. This normally works really easily (I've done it with a dozen models):</p>
<pre><code>from transformers import pipeline, BertForMaskedLM, BertForMaskedLM, AutoTokenizer, RobertaForMaskedLM, AlbertForMaskedLM, ElectraForMaskedLM
tokenizer = AutoTokeniz... | <p>There seems to be some issue with the tokenizer. It works, if you remove <code>use_fast</code> parameter or set it true, then you will be able to display the vocab file.</p>
<pre><code>tokenizer = AutoTokenizer.from_pretrained("sultan/BioM-ALBERT-xxlarge", use_fast=True)
model = AlbertForMaskedLM.from_pret... | huggingface-transformers|huggingface-tokenizers | 1 |
8,739 | 67,379,210 | How to use if condition for an column in python | <p>Having a column where i need to check for NaN rows using a conditional statement based on which i am looking to update a new column.</p>
<p><strong>Input Data</strong></p>
<pre><code>Column1 Column2
AxBZ234
AYBY123
NaN
ZX23468
AC23YUK
NaN
</code></pre>
<p><strong>Script i have been using</strong></p>
<pre><c... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isna.html" rel="nofollow noreferrer"><code>Series.isna</code></a>:</p>
<pre><code>df['col2'] = n... | python|pandas | 2 |
8,740 | 67,288,042 | Python array, getting every n entries, then moving onto the next n entries until the end of the array | <p>I have a 1D numpy array with 4,050,000 entries, I will call image_t. I am trying to slice it in such a way that I retrieve the first 10,000 entries, so image_t[0:10000], then the next step would be image_t[10000:20000] and so forth until it reaches the last slice.</p>
<p>This would end up giving me 405 different arr... | <p>you can use np.array_split(). the following code should work:</p>
<pre><code>split_array = np.array_split(img_t, 405)
</code></pre>
<p>now split_array variable is a list of 405 arrays, each with shape of (10000,)</p> | python|arrays|function|for-loop|numpy-slicing | 0 |
8,741 | 67,452,371 | Pandas Melt function for time series data | <p>I am trying to melt my pandas data frame but I am not quiet sure how to assign the variables properly. I looked through the other examples on stack but I can't seem to find a variation matching this. My data frame (df1) looks like this :</p>
<pre><code>[IN]: df1
[OUT]:
40025.0 21201.0 30061.0 ... | <p>If <code>date</code> is currently the index, you should be able to <code>reset_index()</code> and then <code>set_index('date')</code> afterwards:</p>
<pre class="lang-py prettyprint-override"><code>df1 = (df1
.reset_index()
.melt(id_vars='date', var_name='FIPS', value_name='Covid_cases')
.set_index('date... | python|pandas|dataframe | 1 |
8,742 | 67,549,023 | Why is the GNU scientific library matrix multiplication slower than numpy.matmul? | <p>Why is it that the matrix multiplication with Numpy is much faster than <code>gsl_blas_sgemm</code> from GSL, for instance:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import time
N = 1000
M = np.zeros(shape=(N, N), dtype=np.float)
for i in range(N):
for j in range(N):
M[i,... | <p><strong>TL;DR:</strong> the C++ code and Numpy do not use the same matrix-multiplication library.</p>
<p>The <em>matrix multiplication of the GSL library is not optimized</em>. On my machine, it runs sequentially, does not use <em>SIMD instructions</em> (<a href="https://en.wikipedia.org/wiki/Streaming_SIMD_Extensio... | python|c++|performance|numpy|gsl | 27 |
8,743 | 59,952,801 | Renaming columns in pandas based on strings in list | <p>Im trying to replace the column names of a dataframe (<code>sens_second_X</code>) based on the strings in a list (<code>updated_fist_stage</code>) being substrings to the column names.
<code>updated_fist_stage = ['ccc_230', 'LN_S_P500', 'mf_100']</code>
and </p>
<pre><code>sens_second_X.columns = ['resid', 'ccc_... | <p>You can try something like below with <code>str.extract</code></p>
<pre><code>mapped = sens_second_X.columns.str.extract(r'({})'.format('|'.join(updated_fist_stage))
,expand=False)
sens_second_X.columns = pd.Index(pd.Series(mapped).fillna(pd.Series(sens_second... | python|pandas | 1 |
8,744 | 60,132,430 | reshaping vectors into tensors for embedding layer in keras LSTM mini-batch training | <p>I'm trying to train an LSTM topic model (many-to-one problem) on text using an embedding layer and mini-batch training in <code>keras</code> with <code>tensorflow</code> backend in Python. I am struggling with formatting my inputs and outputs in a way that is compatible with the embedding layer format. </p>
<p>My i... | <p>I am not really sure what you are trying to do with that reshaping but <code>Embedding</code> layers expect 2D tensor, not a 3D tensor that you are trying to push through this layer.</p>
<p>Here is what documentation says about the input of <code>Embedding</code> layer</p>
<blockquote>
<p>2D tensor with shape: (... | python|tensorflow|keras|deep-learning|word-embedding | 1 |
8,745 | 65,135,679 | python dataframe vector comparison | <p>I have a df like this:</p>
<pre><code> | name | age |
|----|------|
| Dav | 25 |
| Las | 50 |
| Oms | 70 |
</code></pre>
<p>how to create a new df or matrix based on comparison on the age difference of these people to each other?
the output will like this(the * are just for explaining, does't nee... | <p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html" rel="nofollow noreferrer">corr</a> to compute the all pairs differences:</p>
<pre><code>import numpy as np
from operator import sub
# compute all pairs diffs
res = df.set_index('name').T.corr(sub).abs() # ... | python|pandas|dataframe|compare | 0 |
8,746 | 65,379,271 | How to find the index of a list element in a numpy array using ranges | <p>Say I have a numpy array as follows:</p>
<p><code>arr = np.array([[[1, 7], [5, 1]], [[5, 7], [6, 7]]])</code></p>
<p>where each of the innermost sub-arrays is an element. So for example; [1, 7] and [5, 1] are both considered elements.</p>
<p>... and I would like to find all the elements which satisfy: [<=5, >=... | <p>Are you looking for</p>
<pre><code>(arr[:,:,0] <= 5) & (arr[:,:,1] >= 7)
</code></pre>
<p>? You can perform broadcasted comparison.</p>
<p>Output:</p>
<pre><code>array([[True, False],
[True, False]])
</code></pre> | python|numpy | 3 |
8,747 | 65,395,280 | Subclass definitions of TensorFlow models with customizable hidden layers | <p>I am learning about Models subclass definitions in TensorFlow</p>
<p>A pretty straightforward definition will be something like this</p>
<pre><code>class MyNetwork1(tf.keras.Model):
def __init__(self, num_classes = 10):
super().__init__()
self.num_classes = num_classes
self.input_lay... | <p>Seems like a very complicated way to do things. If you use a dictionary for a variable number of layers instead of eval, everything works fine.</p>
<pre><code>class MyNetwork2(tf.keras.Model):
def __init__(self, num_classes=2, hidden_dimensions=[100],
hidden_activations=['relu']):
super(... | python|python-3.x|tensorflow|keras|neural-network | 1 |
8,748 | 65,204,011 | Is there a way in Python to get a sub matrix as in Matlab? | <p>For example, let's say that I have the following matrices in Matlab:</p>
<pre><code>A = zeros(10)
B = ones(2,2)
</code></pre>
<p>I want to add the matrix A with B in specific positions of A that are stored like this:</p>
<pre><code>locations = [1, 3]
</code></pre>
<p>I can do this:</p>
<pre><code>A(locations, locati... | <pre><code>A = np.zeros([10,10])
B = np.ones([2,2])
print(B)
A[:2,:2]=B
print(A)
#output B
[[1. 1.]
[1. 1.]]
#output A
[[1. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.... | python|matlab|numpy | 0 |
8,749 | 49,975,169 | Azure HDInsights Spark Cluster Install External Libraries | <p>I have a HDInsights Spark Cluster. I installed tensorflow using a script action. The installation went fine (Success).</p>
<p>But now when I go and create a Jupyter notebook, I get:</p>
<pre><code>import tensorflow
Starting Spark application
The code failed because of a fatal error:
Session 8 unexpectedly rea... | <p>This looks like error with Spark application resources. Check resources available on your cluster and close any applications that you don't need. Please see more details here: <a href="https://docs.microsoft.com/en-us/azure/hdinsight/spark/apache-spark-resource-manager#kill-running-applications" rel="nofollow norefe... | azure|apache-spark|tensorflow|machine-learning|azure-hdinsight | 1 |
8,750 | 50,145,209 | Installing tensorboard built from source | <p>This is about a tensorboard which is built from source, not about pip-installed one.</p>
<p>I could successfully build it.</p>
<pre><code>$ git clone https://github.com/tensorflow/tensorboard.git
$ cd tensorboard/
$ bazel build //tensorboard
tensorflow/tensorboard$ bazel build //tensorboard
Starting local Bazel se... | <p>It seems there exists an script in the /tensorboard/pip_packages try to build wheels</p> | tensorflow|tensorboard | 2 |
8,751 | 49,840,892 | Deep Q Network is not learning | <p>I tried to code a Deep Q Network to play Atari games using Tensorflow and OpenAI's Gym.
Here's my code:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import gym
import numpy as np
import os
env_name = 'Breakout-v0'
env = gym.make(env_name)
num_episodes = 100
input_data = tf.placeholde... | <p>Here are some things that stand out that you could look into (it's always difficult in these kinds of cases to tell for sure without trying exactly which issue(s) is/are the most important ones):</p>
<ul>
<li>100 episodes does not seem like a lot. In the image below, you see learning curves of some variants of Doub... | tensorflow|neural-network|artificial-intelligence|reinforcement-learning|q-learning | 12 |
8,752 | 63,871,508 | In pycharm Pandas Datafram want to highlight specific column with specific color | <p>I have following code ,working in Pycharm, It not working is any basic problem? there is many similar questions in stack overflow forum, I have gone through that , I came to conclusion that <em><strong>style</strong></em> function not works in Pycharm I have to switchover to Jupiter Notebook , is it true ? please gu... | <p>looks like your trying to print it should be</p>
<pre><code>import pandas as pd import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
def color_negative_red(val):
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
# from the resource given I assume apply is an actu... | python|pandas|dataframe|styles | 0 |
8,753 | 63,876,479 | Reading in data into jupyter notebook | <p>When I read in a file (whether it'd be in .csv or .txt format) I tend to use the pandas.read_csv() method to read them. I was wondering if there is any difference with using this method and using with open(file). And if so, is there any advantages using one over another?</p>
<p>Any insights on this will be greatful.... | <ul>
<li><p>The advantage of using <strong>pandas</strong>, is that you have to write minimal
code, but also you probably load alot of stuff that you dont need.</p>
</li>
<li><p>The advantage of using <code>open()</code> is that you have more control, and
you program is gonna be significantly more minimalistic</p>
</li... | python|pandas | 0 |
8,754 | 63,917,784 | How can write and indicator function in Python? | <p>I want to make an indicator function for pde in Python u(x) = 2<em>x if 0<x<1/2 and 2-2</em>x if 1/2<x<1
but when i do it an error occurs.</p>
<p>I have chosen the np.where which is a if else function.</p>
<p>Can someone help me?</p>
<pre><code>import numpy as np
x = np.linspace(0,1)
x
np.where(x>0 &a... | <p>It would be really helpful if you provided the error message instead of just saying "an error occurs".</p>
<p>Anyway, add parentheses, i.e. <code>(x>0) & (x<0.5)</code>. You need them because the <code>&</code> operator has <a href="https://docs.python.org/3/reference/expressions.html#operato... | python|numpy|pde | 0 |
8,755 | 64,048,720 | Pytorch Unfold and Fold: How do I put this image tensor back together again? | <p>I am trying to filter a single channel 2D image of size 256x256 using unfold to create 16x16 blocks with an overlap of 8. This is shown below:</p>
<pre><code># I = [256, 256] image
kernel_size = 16
stride = bx/2
patches = I.unfold(1, kernel_size,
int(stride)).unfold(0, kernel_size, int(stride)) # size = [31, 31, 16... | <p>I believe you will benefit from using <code>torch.nn.functional.fold</code> and <code>torch.nn.functional.unfold</code> in this case, as these functions are built specifically for images (or any 4D tensors, that is with shape B X C X H X W).</p>
<p>Let's start with unfolding the image:</p>
<pre><code>import torch
im... | machine-learning|pytorch|artificial-intelligence|vision | 5 |
8,756 | 47,064,242 | Python Pandas Conditional First Differencing | <p>I have a Pandas dataframe that looks like something this:</p>
<pre><code> Item1 Item2 Item3
Customer date
1 2014-03-24 0.0 10.0 50.0
2014-06-23 0.0 20.0 60.0
2014-09-22 ... | <p>you almost there, adding <code>.mask</code> </p>
<pre><code> df.groupby(level=0).diff().mask(df==0)
Out[740]:
Item1 Item2 Item3
Customer date
1 2014-03-24 NaN NaN NaN
2014-06-23 NaN 10.0 10.0
2014-09-... | python|pandas|diff | 1 |
8,757 | 63,221,977 | Drawing OpenCV contours and save as transparent image | <p>I'm trying to draw contours i have found using findContours.</p>
<p>If i draw like this, i get a black background with the contour drawn on it.</p>
<pre><code> out = np.zeros_like(someimage)
cv2.drawContours(out, contours, -1, 255, 1)
cv2.imwrite('contours.png',out)
</code></pre>
<p>If i draw like this, i... | <p>To work with transparent images in OpenCV you need to utilize the fourth channel after BGR called alpha with controls it. So instead of creating a three-channel image, create one with four channels, and also while drawing make sure you assign the fourth channel to 255.</p>
<pre><code>mask = np.zeros((55, 55, 4), dty... | python|numpy|opencv | 3 |
8,758 | 67,738,552 | Pandas to ODBC connection with to_sql | <p>I'm trying to export a pandas DataFrame into an MS Access table through <code>pyodbc</code>.</p>
<pre class="lang-py prettyprint-override"><code>conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=my_db.accdb;')
df.to_sql('test', conn, index=False)
DatabaseError: Execution failed on sql '... | <p><code>.to_sql()</code> expects the second argument to be either a SQLAlchemy <code>Connectable</code> object or a DBAPI <code>Connection</code> object. If it is the latter then pandas <em>assumes</em> that it is a SQLite connection.</p>
<p>You need to use the <a href="https://github.com/gordthompson/sqlalchemy-acces... | python|pandas|ms-access|pyodbc | 0 |
8,759 | 67,990,805 | How to transform or melt column in python? | <p>I have this tabular table, but I want to make it into a simple form. The existing form is like this:</p>
<pre><code>group mp_current mh_current mp_total mh_total
contractor 25 4825 0 0
</code></pre>
<p>I want to transform the table into this form:</p>
<pre><code>group ... | <h3><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="noreferrer"><code>wide_to_long</code></a></h3>
<p>You specify the stubnames (column prefixes), the separator (<code>'_'</code>), and that the suffix is anything (<code>'.*'</code>) as it by default expects numerics. T... | python|pandas|transform | 8 |
8,760 | 61,225,373 | Pandas replace rows based on multiple conditions | <p>Take for example the following dataframe:</p>
<pre><code>df = pd.DataFrame({"val":np.random.rand(8),
"id1":[1,2,3,4,1,2,3,4],
"id2":[1,2,1,2,2,1,2,2],
"id3":[1,1,1,1,2,2,2,2]})
</code></pre>
<p>I would like to replace the id2 rows where id3 does not equal a... | <p>If <code>id1</code> column is like counter of groups create helper <code>Series</code> by <code>reference</code> group by filtering and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> first and then use... | python|pandas|dataframe | 2 |
8,761 | 61,542,620 | Is there a package called document_base? | <p>I tried to implement YOLOv3 using PyTorch and I found that models had changed to doqu and I changed it accordingly. What I got next was this</p>
<blockquote>
<p>ModuleNotFoundError: No module named 'document_base'</p>
</blockquote>
<p>When I tried to install it with pip however I got this</p>
<blockquote>
<p>ERROR: ... | <p>It's a module inside <code>doqu</code>: <a href="https://bitbucket.org/neithere/doqu/src/default/doqu/document_base.py" rel="nofollow noreferrer">https://bitbucket.org/neithere/doqu/src/default/doqu/document_base.py</a></p>
<p>To import it:</p>
<pre><code>import doqu.document_base
</code></pre>
<p>or</p>
<pre><c... | python-3.x|pip|pytorch|google-colaboratory|yolo | 0 |
8,762 | 61,468,817 | How to add length 1 dimension to NDArray en c# | <p>I have an NDArray of shape (480, 640, 3) in c# using NumSharp.</p>
<p>I need to reshape it to (1, 480, 640, 3).</p>
<p>On python it would be with <code>imgArr = imgArr.reshape((1, 480, 640, 3))</code>.</p>
<p>How can this be done on c#?</p>
<p>Thank you!</p>
<p><em>PS: Sorry for the tags, but there are not NumS... | <p>Solved it with a bit ok luck. I can't explain why, but the solution was to give a -1 in one of the three lasts dimensions, <code>imgArr = imgArr.reshape(new Shape(1, 480, -1, 3))</code>.</p>
<p>(for the curious, <code>imgArr = imgArr.reshape(new Shape(1, 480, 640, 3))</code> did not work)</p> | c#|numpy|numpy-ndarray | 0 |
8,763 | 68,650,265 | What is the "data.max" of a torch.Tensor? | <p>I have been browsing the documentation of torch.Tensor, but I have not been able to find this (just similar things).</p>
<p>If <code>a_tensor</code> is a <code>torch.Tensor</code>, what is <code>a_tensor.data.max</code>? What type, etc.?</p>
<p>In particular, I am reading <code>a_tensor.data.max(1)[1]</code> and <co... | <p>When accessing <code>.data</code> you are accessing the underlying data of the tensor. The returned object <em>is</em> a <code>Torch.*Tensor</code> as well, however, it won't be linked to any computational graph.</p>
<p>Take this example:</p>
<pre><code>>>> x = torch.rand(4, requires_grad=True)
>>>... | python|pytorch | 1 |
8,764 | 68,821,679 | Divide into groups with approximately equal count of rows and draw bars with average values | <p>I have many rows in:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(columns = ['param_1', 'param_2', ..., 'param_n'])
</code></pre>
<p>and I need to group rows into several groups and display stacked bars with averaged values:</p>
<pre class="lang-py prettyprint-override"><code>bin_count = 10
... | <p>Use <code>pd.qcut</code> to split the DataFrame by passing it a <code>range</code> based on the length of the DataFrame.</p>
<h3>Sample Data</h3>
<pre><code>import pandas as pd
import numpy as np
# 111 rows to split into (10) groups
Nr = 111
df = pd.DataFrame({'param_1': np.random.randint(0, 10, Nr),
... | python|pandas | 1 |
8,765 | 68,662,594 | how to scrape data from an interactive code | <p>I want to scrape data from a tourist <a href="https://tn.tunisiebooking.com/" rel="nofollow noreferrer">site</a>
there is a list of hotels i'm extracting names and arrangements but i've got stuck in extracting the price of every arrangement because it's interactive the price shows up as soon as i choose the arrangem... | <p>In order to get prizes for all the arrangement options, performing click operations is necessary.</p>
<p>Below code retrieves 1st options(like Breakfast) arrangements and its prizes. Need to repeat the same process for all the other options available.</p>
<pre><code>hotels = driver.find_elements_by_xpath("//div... | python|pandas|selenium|selenium-webdriver|web-scraping | 2 |
8,766 | 68,816,292 | Deep learning AI for integers in a sequence | <p>I am new to ML, and I would like to use keras to categorize every number in a sequence as a 1 or 0 depending on whether it is greater than the previous number. That is, if I had:</p>
<p>sequence a = [1, 2, 6, 4, 5],</p>
<p>The solution should be:
sequence b = [0, 1, 1, 0, 1].</p>
<p>So far, I have written:</p>
<pre>... | <p>There are few issues with how you are approaching this -</p>
<ol>
<li><p>Your <strong>setup</strong> for the deep learning problem is flawed. You want to use the information of the previous element to infer the labels for the next element. But for inference (and training), you only pass the current element. If tomor... | python|tensorflow|machine-learning|keras|deep-learning | 2 |
8,767 | 53,307,748 | Extract Grind-Anchors from Object-Detection API Model | <p>I'm currently trying to get my SSDLite Network, which I trained with the Tensroflow Object-detection API working, with iOS.</p>
<p>So I'm using the Open Source Code of <a href="https://github.com/vonholst/SSDMobileNet_CoreML" rel="nofollow noreferrer">SSDMobileNet_CoreML</a>.</p>
<p>The Graph allready works with s... | <p>I allready figured it out. A little below quote was a link to a <a href="https://gist.github.com/vincentchu/5f2f669aeb6df9864ec6c43252261269" rel="nofollow noreferrer">Python Notebook</a> which explains everything in detail.</p> | tensorflow|tensor|coreml|object-detection-api | 1 |
8,768 | 52,987,904 | How to apply a pandas function based on the value of another column? | <p>I have a pandas dataframe with two columns, one with some string values and another one with empty dicts:</p>
<pre><code>ColA ColB
True {}
False {}
True {}
True {}
False {}
False {}
True {}
</code></pre>
<p>I have a function that updates a dict with some other values:</p>
<pre><code>def update_dict(a):
re... | <p>It is possible but working with <code>dict</code> in values of columns is not recommended, because lost all vectorized functions:</p>
<pre><code>def update_dict(a):
a.update({"VAL":["yes"]})
return a
df['ColB'] = [update_dict(j) if i == 'False' else j for i, j in zip(df['ColA'], df['ColB'])]
print (df)
... | python|python-3.x|pandas | 0 |
8,769 | 52,905,459 | Import and reshape MNIST data, numpy | <p>I want to reshape the MNIST dataset from shape (70000, 784) to (70000, 28, 28), the following code is tryed, but it gets a TypeError:</p>
<p>TypeError: only integer scalar arrays can be converted to a scalar index</p>
<pre><code>df = pd.read_csv('images.csv', sep=',', header=None)
x_data = np.array(df)
x_data = ... | <p>I think, the problem with the second one is because ur using a for loop it can take more time. So i would suggest you can try this</p>
<pre><code>import tensorflow as tf
#load the data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
#... | python|numpy|machine-learning|computer-vision | 2 |
8,770 | 65,798,822 | Python - Group by time periods with tolerance | <p>Three columns exist in this data set: ID (unique employee identification), WorkComplete (indicating when all work has been completed), and DateDiff (number of days from their start date). I am looking to group the DaysDiff column based on certain time periods with an added layer of tolerance or leniency. For my mock... | <ol>
<li>You can use <code>np.select</code> for the primary conditions.</li>
<li>Then, use <code>mask</code> for the specific condition you mention. <code>s</code> is the <em>first</em> index location for all <code>Y</code> values <em>per group</em>. I then temporarily <code>assign</code> <code>s</code> as a new colum... | python|python-3.x|pandas|datetime|pandas-groupby | 1 |
8,771 | 65,668,608 | Getting an error while training Resnet50 on Imagenet at 14th Epoch | <p>I am training Resnet50 on imagenet using the script provided from PyTorch (with a slight trivial tweak for my purpose). However, I am getting the following error after 14 epochs of training. I have allocated 4 gpus in the server I'm using to run this. Any pointers as to what this error is about would be appreciated.... | <p>It is difficult to tell what the problem is just by looking at the error you have posted.</p>
<p>All we know is that there was an issue reading the file at <code>'/data/users2/oiler/github/imagenet-data/val/n02102973/ILSVRC2012_val_00009130.JPEG'</code>.</p>
<p>Try the following:</p>
<ol>
<li>Confirm the file actual... | python|pytorch|imagenet|pytorch-dataloader | 1 |
8,772 | 63,377,361 | KeyError with a poisson process using pandas | <p>I am trying to create a function which will simulate a poison process for a changeable dt and total time, and have the following:</p>
<pre><code>def compound_poisson(lamda,mu,sigma,dt,T):
points = pd.Series(0)
out = pd.Series(0)
inds = simple_poisson(lamda,dt,T)
for ind in inds.index:
if inds[ind+dt] >... | <p>In short, yes, it's a floating point error. It's quite hard to know how you got there, but probably something like this:</p>
<pre><code>>>> 0.1 * 0.1
0.010000000000000002
</code></pre>
<p>Maybe use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.round.html" rel="nofollow no... | python|pandas|function|numpy|stochastic-process | 0 |
8,773 | 53,559,771 | Count number of rows between time intervals | <p>I have a pandas DataFrame with start and end times (datetime.time) for a list of processes:</p>
<pre><code>from datetime import time
import pandas as pd
df = pd.DataFrame(columns=['start', 'end'],
index=pd.Index(['proc01', 'proc02'], name='Processes'),
data=[
... | <p>Iterating over a Dataframe is usually a sign you're not using <code>pandas</code> optimally. You could instead substract the processes that have ended from the processes that have started, like this:</p>
<pre><code>res = []
for b in bins:
s = (df['start'] < b).sum()
e = (df['end'] < b).sum()
res.a... | python|pandas | 3 |
8,774 | 53,659,787 | Python - For Loop ( two parallel iterations) | <p>I am working on the estimation module of a prototype. The purpose is to send proper seasonality variation parameters to the forecaster module.</p>
<p>Initially, in the booking curve estimation, we were using a formula for day of year seaonality - trigonometric function with 5 orders (fixed). It goes like this:</p>
... | <pre><code>orders = np.array([2, 6, 10, 24])
z = np.array([0.08, 0.11, 0.25, 0.01, 0.66, 0.19, 0.45, 0.07])
doy = np.arange(365) + 1
s = 0
for k in range(len(orders)):
s += z[2 * k ] * np.sin(orders[k] * np.pi * doy / 365.)
s += z[2 * k + 1] * np.cos(orders[k] * np.pi * doy / 365.)
s = np.exp(s)
</code></p... | python-3.x|numpy|for-loop | 1 |
8,775 | 71,835,768 | How to groupby without reset_index() based on multtindex? | <p><strong>data struncture</strong></p>
<pre><code> col1 col2
A 2021-01-01
A 2022-01-01
B 2021-01-01
B 2022-01-01
</code></pre>
<p>This is a dataframe with multiindex(<code>ts_code</code>, <code>date</code>).</p>
<p><strong>Goal</strong></p>
<p>I want to get min date for <code>ts_code</code>. So I ha... | <p>You can either rename your axis for your code to work, or you can pass <code>level=0</code> into <code>groupby()</code></p>
<p>Option 1:</p>
<pre><code>df.rename_axis(['ts_code','date']).groupby('ts code')
</code></pre>
<p>Option 2:</p>
<pre><code>df.groupby(level=0)
</code></pre> | pandas | 1 |
8,776 | 71,931,961 | Calculating mean values yearly in a dataframe with a new value daily | <p>I have this dataframe, which contains average temps for all the summer days:</p>
<pre><code>DATE TAVG
0 1955-06-01 NaN
1 1955-06-02 NaN
2 1955-06-03 NaN
3 1955-06-04 NaN
4 1955-06-05 NaN
... ... ...
5805 2020-08-27 2.067854
5806 2020-08-28 3.267854
5807 2020-08-29 3.067854
5808 2020-... | <p>If I understand correctly, can you try this ?</p>
<pre><code>df['DATE']=pd.to_datetime(df['DATE'])
df.groupby(df['DATE'].dt.year)['TAVG'].mean()
</code></pre> | python|pandas|dataframe|date|mean | 0 |
8,777 | 71,943,408 | Why can't I import functions in python files in another folder? | <pre><code>from keras.models import load_model
import cv2
import numpy as np
from PIL import Image
from MaskDetection.MaskCropper import cropEyeLineFromMasked
IMAGE_SIZE = (224, 224)
actors_dict = {0: 'Andrew Garfield',
1: 'Angelina Jolie',
2: 'Anthony Hopkins',
3: 'Ben Af... | <p>When python imports something, it imports it from its predefined locations...it essentially searches a predefined list of locations from where modules should be imported. If your module is not present in that list of directories or locations, it will return an error. You can find the list by typing:</p>
<pre><code>i... | python|tensorflow | 0 |
8,778 | 71,846,365 | Tensorflow with custom loss containing multiple inputs - Graph disconnected error | <p>I have a CNN output a scalar, this output is concatenated with the output of an MLP and then fed to another dense layer. I get a Graph Disconnected error</p>
<p>Please advise as to how to fix this. Thanks in advance.</p>
<pre><code>from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2... | <p>You can customize what happens in Model.fit based on <a href="https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit" rel="nofollow noreferrer">https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit</a></p>
<ul>
<li>We create a new class that subclasses keras.Model.</li>
<li>We just o... | tensorflow|keras|tensorflow2.0 | 1 |
8,779 | 56,721,498 | How can I use the Keras.applications' ResNeXt in TensorFlow's eager execution? | <p>I am trying to get ResNet101 or ResNeXt, which are only available in Keras' repository for some reason, from <a href="https://keras.io/applications/" rel="nofollow noreferrer">Keras applications</a> in TensorFlow 1.10:</p>
<pre><code>import tensorflow as tf
from keras import applications
tf.enable_eager_execution(... | <p>As the error indicates, tf.placeholder() which is used as placeholder for feeding data to a tf Session using feed_dict, is incompatible with eager mode. </p>
<p>This link nicely explains it with an example: <a href="https://github.com/tensorflow/tensorflow/issues/18165#issuecomment-377841925" rel="nofollow noreferr... | python|tensorflow|keras|eager-execution | 3 |
8,780 | 56,774,065 | Matrix of percentages of values to the sum of values grouped by a column's criteria | <p>I have a matrix of values and need to get their shares to the sum of a respective group.</p>
<p>Example:</p>
<p><a href="https://i.stack.imgur.com/uZ1oj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uZ1oj.png" alt="enter image description here"></a></p>
<p>Need to get - a matrix of percentage... | <p>Create <code>MultiIndex</code>, so possible use parameter <code>level</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.div.html" rel="nofollow noreferrer"><code>DataFrame.div</code></a>:</p>
<pre><code>cols = df.columns[2:]
df1 = df.groupby(['region'])[cols].sum()
#anoth... | python|pandas | 3 |
8,781 | 66,830,486 | Mapping data from Excel sheet1 to sheet2 creates duplicate column in python | <p>I am trying to map values from Sheet1 to sheet2 using an pandas dataframe, Having Column names listed in sheet2, but when i writes data into sheet 2, it leaves the first column null and append data into an duplicate column.</p>
<p>It also happens when i am trying to print dataframe2</p>
<pre><code>df1 = pd.read_exce... | <p>To avoid potential issue of the columns having any non-standard characters in their names or anything else weird going on with the column names, have you tried:</p>
<pre><code>df2[0] = df1['col3']
df2[1] = df1['col5']
df2[2] = df1['col8']
df2[3] = df1['col6']
</code></pre>
<p>Also, what's the output of print(df1) pl... | python|pandas | 0 |
8,782 | 47,256,926 | calculate the mean of one row according it's label | <p>calculate the mean of the values in one row according it's label:</p>
<pre><code>A = [1,2,3,4,5,6,7,8,9,10]
B = [0,0,0,0,0,1,1,1,1, 1]
Result = pd.DataFrame(data=[A, B])
</code></pre>
<p>I want the output is: 0->3; 1-> 7.8</p>
<p>pandas has the groupby function, but I don't know how to implement this. Thanks</p> | <p>This is simple <code>groupby</code> problem ...</p>
<pre><code>Result=Result.T
Result.groupby(Result[1])[0].mean()
Out[372]:
1
0 3
1 8
Name: 0, dtype: int64
</code></pre> | pandas|pandas-groupby | 1 |
8,783 | 47,403,217 | python, tensorflow, how to get a tensor shape with half the features | <p>I need the shape of a tensor, except instead of feature_size as the -1 dimension I need feature_size//2</p>
<p>The code I'm currently using is</p>
<pre><code>_, half_output = tf.split(output,2,axis=-1)
half_shape = tf.shape(half_output)
</code></pre>
<p>This works but it's incredibly inelegant. I don't need an e... | <p>A simple way to get the shape with the last value halved:</p>
<pre><code>half_shape = tf.shape(output[..., 1::2])
</code></pre>
<p>What it does is simply iterate <code>output</code> in its last dimension with step 2, starting from the second element (index 1).</p>
<p>The <code>...</code> doesn't touch other dimen... | python|tensorflow | 1 |
8,784 | 47,435,240 | Pandas groupby date month and count items within months | <p>I have a dataframe like this:</p>
<pre><code>STYLE | INVOICE_DATE2
A | 2017-01-03
B | 2017-01-03
C | 2017-01-03
A | 2017-02-03
A | 2017-01-03
B | 2017-02-03
B | 2017-01-03
</code></pre>
<p>I'm trying to group them by month and count itself within month, result must like this:</p>
<pre>... | <p>Here is a one liner...</p>
<pre><code>ans = df.groupby([df.INVOICE_DATE2.apply(lambda x: x.month), 'STYLE']).count()
</code></pre>
<p>Here is the output</p>
<pre><code>In [21]: ans
Out[21]:
INVOICE_DATE2
INVOICE_DATE2 STYLE
1 A 2
B 2... | python|pandas | 3 |
8,785 | 47,092,185 | TensorFlow Word2Vec model running on GPU | <p>In <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb" rel="nofollow noreferrer">this TensorFlow example</a> a training of skip-gram Word2Vec model described. It contains the following code fragment, which explicitly requires CPU device for computations, i.e. <... | <p>The error is raised because <code>AdagradOptimizer</code> does not have a GPU kernel for its sparse apply operation; a sparse apply is triggered because differentiating through the embedding lookup results in a sparse gradient. </p>
<p><code>GradientDescentOptimizer</code> and <code>AdamOptimizer</code> do support ... | python|word2vec|tensorflow|word-embedding | 2 |
8,786 | 68,294,637 | ValueError: Failed to find data adapter that can handle <numpy.narray> | <p>I am using the following code:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
in = np.array([10,20,30,40,50,60,70],dtype=float)
out = np.array([50,68,86,104,122,140,158],dtype=float)
ly1 = tf.keras.layers.Dense(units=3, input_shape=[1])
ly2 = tf.keras.layers.Dense(unit... | <p>After renaming variable <code>in</code> to <code>in1</code>it started working as shown below</p>
<pre><code>import tensorflow as tf
print(tf.__version__)
import numpy as np
print(np.__version__)
in1 = np.array([10,20,30,40,50,60,70],dtype=float)
out = np.array([50,68,86,104,122,140,158],dtype=float)
ly1 = tf.keras.... | python|numpy|tensorflow|keras | 0 |
8,787 | 68,092,747 | Python Compare two different size dataframes on If condition | <p>I have two data frames. Main and auxiliary. The main data frame is big. Auxiliary is small. I want to compare both and produce True/False in the Main data frame.</p>
<p>My code:</p>
<pre><code>mdf =
A B C
0 3 0 -2
1 -3 -4 -5
2 4 -3 5
3 1 -8 1
adf =
A_low A_up B_low B_up C_low C_up
0 -2... | <p>Try with reformatting <code>adf</code>:</p>
<pre><code>adf.columns = adf.columns.str.split('_', expand=True).swaplevel(0, 1)
</code></pre>
<p><code>adf</code>:</p>
<pre><code> low up low up low up
A A B B C C
0 -2 2 -6 -2 -4 4
</code></pre>
<p>Then with <a href="https://numpy.org/doc/stable/user/bas... | python|pandas|dataframe|numpy | 1 |
8,788 | 68,435,244 | pandas merge rows with same value in one column | <p>I have a pandas dataframe in which one particular column (ID) can have 1, 2, or 3 entries in another column (Number), like this:</p>
<pre><code> ID Address Number
120004 3188 James Street 123-456-789
120004 3188 James Street 111-123-134
120004 100 XYZ Avenue 001-002-003
321002 ... | <p>You can first use <code>groupby</code> to flatten up the <code>Numbers</code> and then rename the columns. Finally, create the <code>Address</code> column by taking the first address from each group.</p>
<pre><code>(
df.groupby('ID')
.apply(lambda x: x.Number.tolist())
.apply(pd.Series)
.rename(lambd... | pandas|dataframe | 1 |
8,789 | 59,119,966 | How to make code flexible enough so blank column value is filtered same as nan? | <p>I want to create logic that is fired off only when a particular row integer in the index is present and in the same row if a particular column is empty. </p>
<p>The dataframe has a code where all 'nan' are filled with blanks like so:</p>
<pre><code>df = df.fillna('')
</code></pre>
<p>This is the logic I am using ... | <p>I think it is better to <code>replace</code> blank with null </p>
<pre><code>df=df.replace({'' : np.nan})
</code></pre>
<p>Or we can adding one more condition </p>
<pre><code>if 12 in df.index:
if df.col1.isnull()[12] or (df.col1[12]==''):
[rest of the code]
</code></pre> | python-3.x|pandas | 1 |
8,790 | 59,418,086 | With tf.keras.callbacks.ModelCheckpoint, what are the valid string values for the 'monitor' argument? | <p>Using the following link:
<a href="https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint?version=stable" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint?version=stable</a>
I am unable to determine the valid argument inputs for the <code>... | <p>The <code>monitor</code> arg of <code>ModelCheckpoint</code> expects you to provide a string, this needs to be the name of a metric or a loss, for example, if your compile method looks like this</p>
<p><code>model.compile(loss='mse', optimizer='sgd', metrics=['mae', 'accuracy'])</code></p>
<p>the valid strings for... | python-3.x|tensorflow|tensorflow2.0|tf.keras | 1 |
8,791 | 57,281,816 | performing mathematical operations for each row of a 2d array against another 2d array | <p>I can only use the numpy import.
I need to calculate the closest distance is the test set to the training set. I.E find the closest distance in the the test(find the distance between all the lists in training array) and return both the test name and training name. The following formula is used:</p>
<pre><code>dist(... | <p>you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html" rel="nofollow noreferrer"><code>numpy.linalg.norm</code></a>. here is an example:</p>
<pre><code>>>> import numpy as np
>>> arr = np.array([1, 2, 3, 4])
>>> np.linalg.norm(arr)
5.477225575051... | python|numpy | 0 |
8,792 | 56,983,420 | Find a substring that appears before a word in a string upto a number | <p>I have a string :</p>
<pre><code>"abc mysql 23 rufos kanso engineer"
</code></pre>
<p>I want the regex to output the string before the word "engineer" till it sees a number.</p>
<p>That is the regex should output :</p>
<pre><code>23 rufos kanso
</code></pre>
<p>Another example:</p>
<p>String:</p>
<pre><code>d... | <p>Use <a href="https://stackoverflow.com/a/2973495/7177029"><code>positive look-ahead</code></a> to match until the word engineer preceded by a digit.</p>
<p><a href="https://regex101.com/r/p6Nycm/1/" rel="nofollow noreferrer"><code>The regex</code></a> - <code>(?=\d)(.+)(?=engineer)</code></p>
<p>Just to get an ide... | python|regex|pandas | 0 |
8,793 | 46,128,720 | Quadratic trend line equation on plot? | <p>I've seen many examples for displaying a linear trend line's equation on a plot, but haven't found one for displaying one of a higher order. I assumed it would be similar, but I keep getting errors. I have a feeling it has to do with not understanding the purpose of the z's in my print statement. Here is my code, th... | <p>In principle the error messages are pretty good at explaining what's wrong.
In the string <code>"y=%.6fx^2+%.6fx+(%.6f)"</code> you have 3 format specifiers, you later only provide 2 arguments (<code>%(z[0],z[1])</code>)</p>
<p>The solution is of course to supply to as many arguments as format specifiers.</p>
<p... | python|numpy|matplotlib | 0 |
8,794 | 46,063,249 | Delete some rows of a column if a value does not exist | <p>Given the following DataFrame:</p>
<pre><code>import pandas as pd
d = pd.DataFrame({'Group':['a','a','c','c'],'Value':[1,1,2,2]})
print(d)
Group Value
0 a 1
1 a 1
2 c 2
3 c 2
</code></pre>
<p>Since there is no row with a group of 'b', I want to delete any row with a group of ... | <p>A more intuitive solution to <code>len</code> would be creating a mask and then using <code>.all</code>. After that, just reassign to the filtered slice. </p>
<pre><code>if ~(d.Group == 'b').all():
d = d[d.Group != 'a']
d
Group Value
2 c 2
3 c 2
</code></pre>
<p>You can also use a host ... | python|pandas|dataframe | 1 |
8,795 | 50,690,757 | Combine pandas DataFrames to give unique element counts | <p>I have a few pandas DataFrames and I am trying to find a good way to calculate and plot the number of times each unique entry occurs across DataFrames. As an example if I had the 2 following DataFrames:</p>
<pre><code> year month
0 1900 1
1 1950 2
2 2000 3
year month
0 1900 1
1... | <p><code>concat</code> then using <code>groupby</code> <code>agg</code></p>
<pre><code>pd.concat([df1,df2]).groupby('year').month.agg(['count','first']).reset_index().rename(columns={'first':'month'})
Out[467]:
year count month
0 1900 2 1
1 1950 1 2
2 1975 1 2
3 2000 2 ... | python|pandas|dataframe | 1 |
8,796 | 51,002,693 | groupby and sum two columns and set as one column in pandas | <p>I have the following data frame:</p>
<pre><code>import pandas as pd
data = pd.DataFrame()
data['Home'] = ['A','B','C','D','E','F']
data['HomePoint'] = [3,0,1,1,3,3]
data['Away'] = ['B','C','A','E','D','D']
data['AwayPoint'] = [0,3,1,1,0,0]
</code></pre>
<p>i want to groupby the columns ['Home', 'Away'] and change... | <p>A simple way is to create two new Series indexed by the teams:</p>
<pre><code>home = pd.Series(data.HomePoint.values, data.Home)
away = pd.Series(data.AwayPoint.values, data.Away)
</code></pre>
<p>Then, the result you want is:</p>
<pre><code>home.add(away, fill_value=0).astype(int)
</code></pre>
<p>Note that <co... | python|python-3.x|pandas|pandas-groupby | 1 |
8,797 | 51,022,861 | Replace value in a specific with corresponding value | <p>I have a dataframe called <code>REF</code> with the following structure:</p>
<pre><code>old_id new_id
3 6
4 7
5 8
</code></pre>
<p>I want to replace all the values that can be found equal to any of the <code>old_id</code> values in another dataframe <code>NEW</code> that is:</p>
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a>:</p>
<pre><code>s = df1.set_index('old_id')['new_id']
df2['old_id'] = df2['old_id'].map(s).fillna(df2['old_id'])
</code></pre>
<p>Or <a href="https://stackoverflow.com/q/492595... | python|python-3.x|pandas|replace|replacewith | 3 |
8,798 | 50,911,227 | How can I visualize categorical data? | <p>I have two datasets like this (dots are random numbers):</p>
<pre><code> Category 1
A B C D E F G H
1 3 0 0 3 . . .
2 2 0 0 2 . . . .
3 0 2 4 2 . . . .
4 1 1 5 2 . . . .
5 0 . . . . . . .
6 2 . . . . . . .
7 3 . . . . . . .
8 0 . . . . . . .
Category 2
A B C D E F G H
1 1 0 0 1 . . ... | <p>Rename the columns <code>A B C D E F G H</code> into:
<code>A1 B1 C1 D1 E1 F1 G1 H1</code> for Dataset 1
<code>A2 B2 C2 D2 E2 F2 G2 H2</code> for Dataset 2</p>
<p>Then merge the datasets.</p> | python|pandas|matplotlib|visualization|data-visualization | 0 |
8,799 | 51,043,135 | How to fill first N/A cell when apply rolling mean to a column -python | <p>I need to apply rolling mean to a column as showing in pic1 s3, after i apply rolling mean and set windows = 5, i got correct answer , but left first 4 rows empty,as showing in pic2 sa3.</p>
<p>i want to fill the first 4 empty cells in pic2 sa3 with the mean of all data in pic1 s3 up to the current row,as showing i... | <p>I think need parameter <code>min_periods=1</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>rolling</code></a>:</p>
<blockquote>
<p>min_periods : int, default None</p>
<p>Minimum number of observations in window required to have a... | python|pandas|rolling-average | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.