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 |
|---|---|---|---|---|---|---|
368,300 | 52,045,161 | How to only make one pass of tf.data.dataset? | <p>I have a tfrecord dataset. I want to make inference on the dataset thus I only want to use the dataset once. But if I keep running the iterator, it will throw out of range error in the end. </p> | <p>The typical way to deal with this is to catch the <code>OutOfRangeError</code>:</p>
<pre><code>... # set up model, data etc.
next_batch_op = iter.get_next()
try:
while True:
batch = sess.run(next_batch_op)
... # do something with batch, e.g. inference
except tf.errors.OutOfRangeError:
...... | python|tensorflow | 0 |
368,301 | 52,308,830 | turn column that has numbers and some dash to int? | <p>This column:</p>
<pre><code>x['bags']
</code></pre>
<p>has this:</p>
<pre><code>bags
1
34
12
13
3
12
-
11
1
</code></pre>
<p>I want to turn it to <code>int</code> because it is an object type.</p>
<p>I want to use it in <code>groupby</code> like this:</p>
<pre><code>x.groupby(['user'])['bags'].sum()
</code></p... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> with <code>errros=coerce</code> for convert non numeric to <code>NaN</code>s and another values to <code>float</code>s (because <code>NaN</code> is <code>float</code> by de... | python|pandas | 0 |
368,302 | 52,330,532 | Tensorflow neural network predicts different answers for the same data after creating a server | <p>I have trained a neural network using TensorFlow 1.8.0 and eager execution.
After training I saved it and there were no problems with loading and predicting.
Then I made a python server (using flask) which loads the trained model to receive POST requests with data in format json, which is later standardized and proc... | <p>So the problem was not in the model itself or creating a server.
I used a config file to read the checkpoint directory. I've written there:</p>
<pre><code> checkpointDir = 'path/to/the/checkpoint'
</code></pre>
<p>but those quotes were unnecessary and the script couldn't read the path, so the model didn't restore ... | python|tensorflow|server|neural-network | 0 |
368,303 | 52,006,414 | panda aggregate by functions | <p>I have data like below:</p>
<pre><code>id movie details value
5 cane1 good 6
5 wind2 ok 30.3
5 wind1 ok 18
5 cane1 good 2
5 cane22 ok 4
5 cane34 good 7
5 wind2 ok 2
</code></pre>
<p>I want the output with below criteria:</p>
<p>If movie name starts with 'cane' - sum the v... | <p>You should aim for vectorised operations where possible.</p>
<p>You can calculate 2 results and then concatenate them.</p>
<pre><code>mask = df['movie'].str.startswith('cane')
df1 = df[mask].groupby('movie')['value'].sum()
df2 = df[~mask].groupby('movie').size()
res = pd.concat([df1, df2], ignore_index=0)\
... | python|pandas|dataframe | 2 |
368,304 | 52,053,955 | Turn 2010 Q1 to datetime as 2010-3-31 | <p><a href="https://i.stack.imgur.com/9c8AF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9c8AF.png" alt="enter image description here"></a></p>
<p>How to find a smart solution to turn Year_Q to datetime? I tried to use </p>
<pre><code>pd.to_datetime(working_visa_nationality['Year_Q'])
</code></p... | <p>I a bit changed <a href="https://stackoverflow.com/a/46350953/2901002"><code>MaxU</code> answer</a>:</p>
<pre><code>df = pd.DataFrame({'Year_Q': ['2010 Q1', '2015 Q2']})
df['Dates'] = pd.PeriodIndex(df['Year_Q'].str.replace(' ', ''), freq='Q').to_timestamp()
print (df)
Year_Q Dates
0 2010 Q1 2010-01-01
... | python|pandas|time-series|data-cleaning | 1 |
368,305 | 52,216,526 | Sort array columns based upon sum | <p>Let's suppose I have an array as such:</p>
<pre><code>np.array([1., 1., 0.],
[0., 4., 0.],
[8., 0., 8.],
[0., 0., 0.],
[5., 0., 0.],
[2., 2., 2.]])
</code></pre>
<p>With column[0] summing to 16, column[1] to 6 and column[2] to 10.</p>
<p>How do I efficiently in Numpy re-arrange ... | <p>You can try <code>sum</code> along <code>axis=0</code> and use <code>argsort</code> then reverse the array and use:</p>
<pre><code>a[:,np.argsort(a.sum(axis=0))[::-1]]
array([[1., 0., 1.],
[0., 0., 4.],
[8., 8., 0.],
[0., 0., 0.],
[5., 0., 0.],
[2., 2., 2.]])
</code></pre> | python|numpy | 7 |
368,306 | 52,032,682 | Working with Pandas Dataframe Subtraction and Indexes | <p>I have several text files, with some chronological metrics on real estate data over time. I would like to import this data into a dataframe, and then calculate a new dataframe that is the difference between a metric for a specific city, relative to the average of all the cities, at that date. For a given date, I wou... | <p>I believe need:</p>
<pre><code>df = pd.concat([pd.read_csv(f, na_values = ['#VALUE!', '#DIV/0!'], keep_default_na = True)
for f in glob.glob('city Text Files/*.txt')])
#get only numeric columns
cols = df.select_dtypes(np.number).columns
#create DataFrame with same size as original with means
df_a... | python|pandas|subtraction | 2 |
368,307 | 52,004,346 | TypeError: 'Series' object is not callable - Rolling window - Python | <p>I have an Hodrick-Prescott (HP) function defined in Python as follows:</p>
<pre><code>import statsmodels.api as sm
def func_HP(close, params):
cycle,trend = sm.tsa.filters.hpfilter(close,params)
return trend
</code></pre>
<p>If i apply that function to a column present in a datafrate like this:</p>
<pre>... | <p>Yep, it looks like the hp_filter function returns an array. So you'd need to add something like:</p>
<pre><code>def func_HP(close, params):
cycle,trend = sm.tsa.filters.hpfilter(close,params)
df_trend = pd.dataframe(trend)
return df_trend
</code></pre> | python|pandas|series|statsmodels|rolling-computation | 0 |
368,308 | 52,426,449 | Installing tensorflow-gpu via conda-forge results in using CPU-only tensorflow | <p>I am creating a conda environment solely for using the <code>tensorflow-gpu</code> package from the <code>conda-forge</code> channel</p>
<pre class="lang-none prettyprint-override"><code>conda create -n tst -c conda-forge tensorflow-gpu
</code></pre>
<p>This results in both <code>tensorflow-gpu</code> <strong>and<... | <p>From looking at the lists of packages on conda-forge (<a href="https://conda-forge.org/feedstocks/" rel="nofollow noreferrer">https://conda-forge.org/feedstocks/</a>), it looks like there's no tensorflow-gpu package there. There's some weird compatibility issues between conda-forge and default anaconda packages - I ... | python|tensorflow|conda | 1 |
368,309 | 52,198,701 | Latent Semantic Analysis results | <p>I'm following a tutorial for LSA and having switched the example to a different list of strings, I'm not sure the code is working as expected. </p>
<p>When I use the example-input as given in the tutorial, it produces sensible answers. However when I use my own inputs, I'm getting very strange results.</p>
<p>For... | <p>The problem looks like it's due to a combination of the small number of examples you're using, and the normalisation step. Because the <code>TrucatedSVD</code> maps your count vector to lots of very small numbers and one comparatively large number, when you normalise these you see some strange behaviour. You can see... | python|scikit-learn|svd|sklearn-pandas|lsa | 1 |
368,310 | 52,216,747 | keras - tensorflow - LSTM - csv - how to use fit_generator | <p>Iam tyring to implement a simple RNN LSTM model but stuck. The problem itself is simple. I will be giving 5 consecutive digits to the model (but 1 digit at a time) and then I want the model to predict the 6th one.</p>
<p>Example:
Input data: <strong>1, 2, 3, 4, 5</strong> (1 digit at each time step)
And the outpu... | <p>You can convert <code>tensor</code> to <code>numpy</code> by <code>eval()</code> directly.</p>
<pre><code>features = tf.reshape(features, [NR_FEATURES, 1])
# convert tensor to numpy
with tf.Session() as sess:
features = features.eval()
# Your data shape needs to be adjusted relative to your model input.
feature... | python|tensorflow|keras|generator|lstm | 1 |
368,311 | 52,279,702 | Pandas rearrange hour-date excel table into a datetime dataframe | <p>I have an Excel data set that looks like this:</p>
<pre><code> 24 25 26 27
1 0,3818 0,0713 0,07222 0,3542
2 0,17802 0,04508 0,06877 0,17319
3 0,22356 0,07314 0,04991 0,22448
4 0,1771 0,07038 0,07406 0,19136
5 0,19389 0,06164 0,05497 0,18538
6 0,20401 0,07475 0,06417 0,21413
7 0,18... | <p>This is the best I've got:</p>
<p>if your data is on a <code>pandas.DataFrame</code> called <code>df</code> you can do:</p>
<pre><code>df2 = df.unstack()
start = pd.Timestamp('01/01/2013')
df2 = df2.reset_index()
df2['date'] = [start + pd.DateOffset(days = int(x)-1) for x in df2.level_0.values]
df2['date'] += pd... | python|excel|pandas | 1 |
368,312 | 52,188,862 | Pandas Python Regular Expression Assistance | <p>I wasn't sure what to call this title, feel free to edit it if you think there is a better name.</p>
<p>What I am trying to do is find cases that match certain search criteria. </p>
<p>Specifically, I am trying to find sentences that contain the word "where" in them. Once I have identified that, I am trying to fin... | <p>You could just filter with <code>str.contains</code>:</p>
<pre><code>df[(df['R'].str.contains('where', flags=re.IGNORECASE) & df['R'].str.contains('sqlcommand', flags=re.IGNORECASE))]
Q R
0 file.sql <sentence>dave likes stuff</sentence><properti...
</code></pre>
<p>or use <... | python|python-3.x|pandas | 0 |
368,313 | 52,212,262 | pandas groupby multiple columns values | <p>I was try to get a average columns for all the std columns</p>
<p><a href="https://i.stack.imgur.com/uoY6v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uoY6v.png" alt="enter image description here"></a></p>
<p>I want to add one more column to calculate the average value from Std_4-Std_10 valu... | <p>Use:</p>
<pre><code>df.filter(like='Std').mean(1)
</code></pre>
<p>To add it back into your dataframe, use:</p>
<pre><code>df['mean_Std'] = df.filter(like='Std').mean(1)
</code></pre> | python|pandas | 0 |
368,314 | 52,364,222 | Find closest/similar value(vector) inside a matrix | <p>let's say I have the following numpy matrix (simplified):</p>
<pre><code>matrix = np.array([[1, 1],
[2, 2],
[5, 5],
[6, 6]]
)
</code></pre>
<p>And now I want to get the vector from the matrix closest to a "search" vector:</p>
<pre><code>search_vec = np.ar... | <p><strong>Approach #1</strong></p>
<p>We can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query.html" rel="noreferrer"><code>Cython-powered kd-tree</code> for quick nearest-neighbor lookup</a>, which is very efficient both memory-wise and with performance -</p>
<pre><code>I... | python|numpy | 9 |
368,315 | 52,370,048 | Calculating Matthew correlation coefficient for a matrix takes too long | <p>I would like to calculate Matthew correlation coefficient for two matrices A and B. Looping over columns of A, and calculate MCC for that column and all 2000 rows of matrix B, then take the max index. The code is:</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn.metrics import matthews_corrcoef as... | <p>Maybe try this using numpy and dot products in python</p>
<pre><code>def compute_mcc(true_labels, pred_labels):
"""Compute matthew's correlation coefficient.
:param true_labels: 2D integer array (features x samples)
:param pred_labels: 2D integer array (features x samples)
:return: mc... | python|r|python-3.x|scikit-learn|sklearn-pandas | 1 |
368,316 | 52,275,093 | model.fit on keras.sequential when using tf.data.Dataset raises a ValueError | <p>I am trying to build my first classifier on tensorflow 1.10 using tf.data.dataset as an input to a Keras.sequential but the fit method returns the following error:</p>
<pre><code>ValueError: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (None,)
</code></pre>
<p>First I... | <p>You're missing some '=' in your code. </p>
<p>Each dataset operation should be like :</p>
<pre><code>dataset = dataset.some_ops(...)
</code></pre>
<p>Here is how your code should look:</p>
<pre><code>import tensorflow as tf
from tensorflow import keras
image_size=50
batch_size=10
# Reads an image from a file, de... | tensorflow|keras|python-3.6|tensorflow-datasets | -1 |
368,317 | 52,382,901 | Read excel cell values containing formulae with pandas | <p>I am trying to read an excel with pandas but because it has formulae it will return nan values when reading it instead of the cell values. </p>
<pre><code>df=pd.read_excel('Test.xlsx',sheet_name='Sheet1')
</code></pre> | <p>@Naga kiran if you want to see the value instead of the formula you can add:</p>
<pre><code>wb = load_workbook('empty_book.xlsx', data_only=True)
</code></pre>
<p>But openpyxl never evaluates formula (<a href="https://openpyxl.readthedocs.io/en/latest/usage.html#using-formulae" rel="nofollow noreferrer">https://open... | python|pandas|xlsx | 1 |
368,318 | 52,005,226 | python - pandas - setting x ticks labels | <p>I have a Dataframe = </p>
<pre><code>from collections import OrderedDict
dico = OrderedDict({"Cisco" :54496.923851069776,
"Citrix" :75164.2973859488,
"Datacore/veritas/docker/quest" :7138.499540816414,
"Dell / EMC" : 34836.42983441935,
"HPE": 40265.33070005489,
"IBM Hard Ware / IBM services" : 220724.89293359307,
"... | <p>You don't get <code>20000</code> because you are creating powers of <code>10</code> as <code>pow(10,i-1)</code>. It is mathematically not possibly from this equation. Moreover, <code>10000</code> is not displayed because you just use <code>ax.set_xticklabels</code> to reset the labels of the already existing xticks.... | python|pandas | 2 |
368,319 | 52,062,496 | Why is a.dot(b) faster than a@b although Numpy recommends a@b | <p>According to the answers from this <a href="https://stackoverflow.com/questions/3890621/how-does-multiplication-differ-for-numpy-matrix-vs-array-classes#">question</a> and also according to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html?highlight=matrix%20multiplication" rel="noreferrer... | <p>Your premise is incorrect. You should use larger matrices to measure performance to avoid function calls dwarfing insignificant calculations.</p>
<p>Using Python 3.60 / NumPy 1.11.3 you will find, as explained <a href="https://stackoverflow.com/questions/34142485/difference-between-numpy-dot-and-python-3-5-matrix-m... | python|arrays|performance|numpy|matrix | 27 |
368,320 | 52,339,907 | Numpy polynomial generation | <p>I am using numpy.polynomial.Polynomial to generate a second degree polynomial on the domain 0 to 0.02 such that it fits the points (0,0) and (0.02,16)</p>
<p>The resulting polynomial object is as so:</p>
<p><a href="https://i.stack.imgur.com/j1Pb3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/... | <p>A <code>numpy.polynomial.Polynomial</code> object with a <code>coef</code> array of <code>array([4., 8., 4.])</code> doesn't necessarily represent the polynomial <code>4 + 8x + 4x^2</code>. Input is rescaled according to the <code>Polynomial</code> object's <code>domain</code> and <code>window</code> first, mapping ... | python|numpy | 7 |
368,321 | 52,037,352 | Fuse two arrays | <p>I have two NumPy arrays with unique elements of </p>
<p>when i do <code>np.unique(array_1)</code> i get <code>array([0, 1, 2, 4, 5, 6], dtype=int8)</code></p>
<p>when i do <code>np.unique(array_2)</code> i get <code>array([0, 1, 2, 4, 5, 6], dtype=int8)</code></p>
<p>What i want is to fuse these arrays, by which ... | <p>If you want to sum up the arrays you can simply write:</p>
<pre><code>import numpy as np
arr1 = np.array([0, 1, 2, 4, 5, 6])
arr2 = np.array([0, 1, 2, 4, 5, 6])
arr_result = arr1 + arr2
Output: array([ 0, 2, 4, 8, 10, 12])
</code></pre>
<p>If you had a different thing in mind, I am afraid that I don't understan... | python|numpy | 2 |
368,322 | 60,456,773 | Tensorflow applying operations inside a model: FailedPreconditionError | <p>Say I have CNN model that outputs N probability maps as mask the same size of the input image in a Unet like fashion. I would then want to apply for example least square fit on top of each mask to get coefficients for functions as output instead and use these to calculate my models loss.</p>
<pre><code>def unet_mod... | <p>before adding each variables I needed to make sure that x_map and y_map also is batched by expanding the dims with axis -1</p> | python|tensorflow|keras | 0 |
368,323 | 60,718,518 | Python3.7 Pandas1.0.1 Dataframe - Calculate sum of column within a range and regroup as one new row? | <p>My first question on StackOverflow. Please be good to me :)</p>
<p>Hello, I just started a small project on data science and I wanted to ultimately create a pie chart via matplot showing the percentage of device model on the site's overall traffic (i.e. 30% iPhone, 20% iPad, 10% Mac, etc.).</p>
<pre><code>useragen... | <p>Use:</p>
<pre><code>#first sorting data if necessary
df1 = df.sort_values('count', ascending=False)
#then get top 4 rows
df2 = df1.head(4)
#filter column `count` for all values after 4 rows
summed = df1.loc[df1.index[4:], 'count'].sum()
#create DataFrame by another counts
df3 = pd.DataFrame({'useragent':['Other']... | python|pandas|dataframe|pandas-groupby | 2 |
368,324 | 60,498,676 | Facing this error while classifying Images, containing 10 classes in pytorch, in ResNet50. My code is: | <p>This is the code I am implementing: I am using a subset of the CalTech256 dataset to classify images of 10 different kinds of animals. We will go over the dataset preparation, data augmentation and then steps to build the classifier.</p>
<pre><code>def train_and_validate(model, loss_criterion, optimizer, epochs=25)... | <p>This happens when there are either incorrect labels in your dataset, or the labels are 1-indexed (instead of 0-indexed). As from the error message, <code>cur_target</code> must be smaller than the total number of classes (10). To verify the issue, check the maximum and minimum label in your dataset. If the data is i... | image-processing|deep-learning|computer-vision|pytorch|resnet | 4 |
368,325 | 60,637,571 | How can I use a 3d numpy array of indices to retrieve the corresponding values i a 4d array? | <p>I have a 4d numpy array <code>temperature</code> of data with the measured temperature at points x,y,z and time t. Assuming I have an array <code>indices</code> with the indices where the first instance of a condition is met, say <code>temperature < 0</code>, how do I extract a 3d array with the first temperatur... | <p><code>Numpy</code> <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow noreferrer">advanced indexing</a> does always work:</p>
<pre><code>import numpy as np
temperatures = np.random.random((11,8,5, 200)) * 1000
indices = np.argmax(temperatures > 900, axis=3)
x, y, z = temper... | python|arrays|numpy | 3 |
368,326 | 60,374,611 | Convert multiple string to dataframe in python | <p>There are three strings that I want to convert.</p>
<pre class="lang-py prettyprint-override"><code> row='A;B;C'
col='aaa,bbb,ccc;aaa,bbb,abc;aaa,bbb,ccc'
val='99,80,90;100,100,100;90,90,90'
</code></pre>
<p>I wanna convert <code>String</code> to <code>Dataframe</code> or <code>Matrix</code> in Python.</p>
<p... | <p>How about:</p>
<pre><code>def create_frame(row_str, col_str, val_str,
record_delim=';', field_delim=','):
out = zip(row_str.split(record_delim),
col_str.split(record_delim),
val_str.split(record_delim))
df = pd.DataFrame({i: dict(zip(c.split(field_delim),
... | python|pandas|dataframe|matrix|split | 0 |
368,327 | 60,417,326 | What is the extra 5 bytes in front of the grpc request and response | <p>I am using <a href="https://github.com/tensorflow/serving/tree/master/tensorflow_serving/apis" rel="nofollow noreferrer">tensorflow-serving</a> for deep learning model server, it is a grpc serivce. And in order to track the server's requests and responses, there is a proxy in the middle of the server and client. The... | <p>gRPC has a 5 byte header. Search for Length-Prefixed-Message in <a href="https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md" rel="nofollow noreferrer">https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md</a>.</p> | tensorflow|grpc|tensorflow-serving | 2 |
368,328 | 60,428,455 | Apply regex to a DataFrame after groupby to filter values in a column | <p>I have a DataFrame that looks like this</p>
<pre><code> text row
0 string1111 14.0
1 string1234 14.0
2 strin1gabc 12.0
3 anotherstring 12.0
4 12351 15.0
</code></pre>
<p>I am trying to group by <code>row</code> and concatenate <code>text</code> for each <code>row</code>, the... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a> for replace column by values without numbers, then aggregate, change columns order and last remove rows filled by empty strings by converting column to <cod... | python|regex|pandas|group-by | 1 |
368,329 | 60,749,798 | Pandas: Remove Year-Week rows before today? | <p>I want to drop rows before current week from my dataframe. The intended code is not working though, as the single digit weeks are still showing up. Is there a better way?</p>
<pre><code>import pandas as pd
import numpy as np
from datetime import date, datetime, timedelta
data = {
"Year": [2019, 2020, 2020, 202... | <p>Here's a possible solution, inspired by <a href="https://stackoverflow.com/a/45437018">this answer</a>:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from datetime import datetime
data = {
"Year": [2019, 2020, 2020, 2020, 2020, 2020, 2020],
"Week": [40, 8, 9, 10, 11, 12, 13]
}
df ... | python|pandas|dataframe|datetime | 0 |
368,330 | 60,724,571 | Understanding tf.nn.depthwise_conv2d | <p>From
<a href="https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d</a></p>
<blockquote>
<p>Given a 4D input tensor ('NHWC' or 'NCHW' data formats) and a filter
tensor of shape [filter_height, filter_width,... | <p>In pytorch terms:</p>
<ol>
<li>always one input channel per group, 'channel_multiplier' output
channels per group;</li>
<li>not in one step;</li>
<li>see 1</li>
</ol>
<p>I see a way to emulate several input channels per group. For two, do <code>depthwise_conv2d</code>, then split result Tensor as deck of cards by ... | python|tensorflow|pytorch|conv-neural-network | 1 |
368,331 | 60,586,295 | How to plot frequency distribution using seaborn in python/pandas for a bipartite text based graph data | <p>I have a dataframe with 70k rows, & it looks like this:</p>
<pre><code>mirna gene_id
osa-miR2873a Os01g0100100
osa-miR169d Os01g0100100
osa-miR169a Os01g0100100
osa-miR396a-3p Os01g0100200
osa-miR396b-3p Os01g0100200
... ...
</code></pre>
<p>I am using matplotlib & seaborn for plotting t... | <p>You could groupby mirna and summarize by gene_id count. Then you could just do a histogram of that.</p> | python|python-3.x|pandas|matplotlib|seaborn | -1 |
368,332 | 60,623,993 | How to plot grouped data using MatPlotLib? | <p>I have data from facebook that I parsed through and I want to make a plot using <strong>MatPlotLib</strong>. I want to see how often I use certain words per year in a line graph. I have this data that I want to look like the figure below but plotted with MatPlotLib instead of Altair. (Don't worry about the titles or... | <p>You want to <code>pivot</code> the table and plot:</p>
<pre><code># convert to dataframe
df = pd.DataFrame(df)
df.pivot(index='year',columns='word',values='count').plot()
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/FlfTw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fl... | python|pandas|matplotlib|data-visualization | 2 |
368,333 | 60,374,316 | How to concatenate many txt files with different names into one array with numpy on python? | <p>I have files with the following convention for names</p>
<pre><code>acc_exp01_user01
acc_exp02_user01
acc_exp03_user02
acc_exp04_user02
acc_exp05_user03
acc_exp06_user03
and so on...
</code></pre>
<p>Notice that for each experiment numbering, they share the same user with 1 other.</p>
<p>How do I iterate through... | <p>You can use the command prompt to do that in one line.</p>
<p>You need to be in the directory where your txt files are.</p>
<p>So use the command: <code>cd /path_to_the_txt_files/</code></p>
<p>Windows:</p>
<pre><code>C:\> type acc_exp0* > one_big_file
</code></pre>
<p>Linux:</p>
<pre><code>$ cat acc_exp... | python|numpy | 1 |
368,334 | 60,757,709 | Pandas: Merge data frames without connection column | <p>I have 3 different data frames with only one column each - one with the 'store' column, another with the 'brand' column and the other with the 'date' column.
I intend to obtain all possible combinations. I tried with the merge function, but since I don't have a connection column, I couldn't.</p>
<p>Can someone tell... | <p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow noreferrer"><code>tertools.product</code></a> by <code>Series</code> and pass to <code>DataFrame</code> constructor:</p>
<pre><code>from itertools import product
df1 = pd.DataFrame({'store':list('abc')})
df2 = pd.DataFr... | pandas|merge | 1 |
368,335 | 60,694,574 | Count the number of column for each rows of a pandas where a condition holds | <p>I have a Pandas dataframe as follow: </p>
<pre><code>data = pd.DataFrame({'w1':[0,1,0],'w2':[5,8,0],'w3':[0,0,0],'w4' :[5,1,0], 'w5' : [7,1,0],'condition' : [5,1,0]})
</code></pre>
<p><a href="https://i.stack.imgur.com/7ySBi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7ySBi.png" alt="enter i... | <p>Compare all columns without last by column <code>condition</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a> and count <code>True</code>s by <code>sum</code>:</p>
<pre><code>data['new'] = data.iloc[:, :-1]... | python|pandas | 5 |
368,336 | 60,443,836 | loop through a dataframe and append rows from a specific column to a new list when the condition is met | <p>here is what my code looks like</p>
<pre><code>pos_list = []
for i in range(len(df)):
if df.loc[i, "sentiment"] == 1:
pos_list = df.loc[i, "tweets"].tolist()
else:
pass
print(pos_list)
</code></pre>
<p>so if the sentiment == 1 I want to add a row from the tweets column to a list</p> | <p>Try using the <code>append</code> method:</p>
<pre><code>pos_list = []
for i in range(len(df)):
if df.loc[i, "sentiment"] == 1:
pos_list.append(df.loc[i, "tweets"])
else:
pass
print(pos_list)
</code></pre>
<p>Hope this helps.</p> | python|pandas|dataframe | 1 |
368,337 | 60,620,524 | Does anybody know how to decode plot data points as extracted from a Python bokeh-generated html file? | <p>Reading the html source I see that data arrays are formatted like:</p>
<pre><code> 'x' =>
array (
'__ndarray__' => 'A loooooong string',
'dtype' => 'float64',
'shape' =>
array (
0 => 3053,
... | <p>This is the function that you need: <a href="https://github.com/bokeh/bokeh/blob/2.0.0/bokehjs/src/lib/core/util/serialization.ts#L126" rel="nofollow noreferrer">https://github.com/bokeh/bokeh/blob/2.0.0/bokehjs/src/lib/core/util/serialization.ts#L126</a></p>
<p>I can't paste the code here since there are different... | python|numpy|bokeh | 2 |
368,338 | 60,667,547 | Pandas : Two 'isin', one condition | <p>I've been using pandas for some months and today I found something weird.</p>
<p>Let's say I have these two dataframes :</p>
<pre><code>df1 = pd.DataFrame(data={'C1' : [1,1,1,2],'C2' : ['A','B','C','D']})
df2 = pd.DataFrame(data={'C1':[2,2,2],'C2':['A','B','C']})
</code></pre>
<p>What I want is : from df2, every pai... | <p>You can do it with inner <code>merge</code>:</p>
<pre><code>df2.merge(df1, how='inner', on=['C1', 'C2'])
Empty DataFrame
Columns: [C1, C2]
Index: []
</code></pre> | python|pandas|dataframe | 2 |
368,339 | 60,552,527 | Error while trying to graph a decision boundary for a KNN | <p>I have a csv dataframe with 2 variables (an input dataframe, denoted by X) and another numpy array consisting of my target variables.</p>
<p>This looks something like this:</p>
<pre><code>>X
Duration Grand Mean
0 142 383.076805
1 334 182.067833
2 97 232.677513
3 220 448.38... | <p>Your error is due to the way you slice pandas <code>df</code> (you do it like it were a numpy array which is obviously wrong).</p>
<p>One possible way of correcting it, put the line:</p>
<pre><code>X = X.values
</code></pre>
<p>at the top of your code and you're fine to go.</p>
<p><strong>Proof</strong></p>
<pr... | python|numpy|machine-learning|scikit-learn|knn | 0 |
368,340 | 60,637,825 | Opencv 2.4.13 requires python 2.7,but the Monocular Total Capture repo requires python 3.5 | <p>I'm trying to use this repo :</p>
<p><a href="https://github.com/CMU-Perceptual-Computing-Lab/MonocularTotalCapture" rel="nofollow noreferrer">https://github.com/CMU-Perceptual-Computing-Lab/MonocularTotalCapture</a></p>
<p>It requires "OpenCV 2.4.13 (compiled from source with CUDA 9.0, CUDNN 7.0)",so I'm trying t... | <p>This is strange because the repo explicitly says that it should use what you are trying to use. My guess is that someone made a mistake on the dependency list. Try upgrading Opencv first then contact the repo maintainers since they wrote the contradiction. </p> | python|linux|opencv|tensorflow|anaconda | 0 |
368,341 | 60,716,805 | How to remove NaN on CSV? | <p>I have a .csv file of a table consisting of 12 col and 30k rows. One of the col is 'mentions', some of the data are empty (NaN). I am trying to remove all the rows where mentions = NaN. I don't want to fill it with new data. I just wanna remove those rows so they wont be part of the analysis.</p>
<p>Please help. Th... | <p>Assuming your <code>DataFrame</code> is named <code>df</code>:</p>
<pre class="lang-py prettyprint-override"><code>df = df.dropna(subset=["mentions"])
</code></pre> | python|pandas|numpy|csv|export-to-csv | 1 |
368,342 | 60,636,815 | how to count the frequency of digits exist in a column csv | <p>I wanted to count the number of digits exist in a column of my CSV file. For now these are my codes. I am able to get the digits that is in the rows, but i only wanted to know if there are digits in each rows, if yes return 1, else 0. And to also count how many numbers exist in the row.</p>
<pre><code>news=pd.read_... | <pre><code>import pandas as pd
from io import StringIO
data = StringIO("""
id STORY
1 The theme underlined 2013 key messages. 1 of it is
2 14th February is a Valentines Day
3 Today is Monday
""")
df = pd.read_csv(data, sep=' ', engine='python')
df['howmanynumbers'] = df['STORY'].str.count('(\d+)')
df['existnu... | python|pandas|csv | 0 |
368,343 | 60,432,231 | NumPy "Too many indices for array" error whilst predicting from neural network | <p>I have a text file with data:</p>
<pre><code>0,13,10,10,11,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,0,0,0,0,0,0,0,14,13,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,... | <p>Your input array is one-dimensional but when you do:</p>
<pre><code>z = inputdata[:,150]
</code></pre>
<p>You are treating it as a 2d array (you are trying to extract the 151th column of <code>input_data</code>).</p> | arrays|numpy|keras|neural-network|python-3.7 | 0 |
368,344 | 60,475,373 | Jupyter Notebook not recognizing packages in the newly added kernals | <p>I have anaconda base environment and 1 other environment where i have tensorflow installed which i am trying to import in my jupyter notebook after changing the kernel.</p>
<p>i installed jupyter notebook in my conda base environment using the following command:</p>
<p><code>conda install -c conda-forge jupyterhub... | <p>Solved it by editing the .jason file and providing the right path to the environment executable.</p>
<p>Edit.</p>
<p>all i did was to go into <code>C:\Users\YOUR_USERNAME\AppData\Roaming\jupyter\kernels</code>
and you will find all the kernels which you added into Jupyter Notebook.<br>
Now just go to folder which is... | python|tensorflow|jupyter-notebook|anaconda|jupyter | 5 |
368,345 | 60,347,070 | Values from .max() as new dataframe in Python | <p>I have some 10Hz GPS data from which I have added some rolling .sum() columns e.g below</p>
<pre><code>resultsQ1['5s']=resultsQ1['OdChange'].rolling(window=50,axis=0).sum()
</code></pre>
<p>I have then identified the largest value in the new column while grouping from another column e.g below</p>
<pre><code>combi... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>res=resultsQ1.merge(resultsQ1.groupby('Stat5s')['5s'].max(), right_index=True, left_on="Stat5s", suffixes=["", "_max"])
res=res.loc[res["5s_max"]==res["5s"]]
#so you can differentiate the final result from records that make it up:
res["cat"]="total"+res.ass... | python|python-3.x|pandas | 0 |
368,346 | 60,358,108 | Python break for loop if equal to row length in Excel | <p>I'm pulling data from excel and transferring to a web page. After clicking on the first input box on the web page, values from the first row (starting at 'B2') are entered. </p>
<p>I'm using a for loop to tab to the next input box and enter in data from the next cell in the row. After all data are entered, I want t... | <p>Working code below.</p>
<pre><code>x = len(df.columns)
z = 1
n = 1
b = 1
while z < x:
m = df.iloc[n, b]
ActionChains(browser) \
.send_keys(str(m)) \
.perform()
z = z + 1
b = b + 1
if z == x:
break
else:
ActionChains (browser) \
.send_keys(Keys.T... | python|excel|pandas|selenium | 1 |
368,347 | 60,540,132 | Exclude one column in matching pattern | <p>I have a data frame with multiple columns</p>
<pre><code> ID|NAME|CITY|AGE|A Bot(S)_S|B Cost_S|C Value(!)_S|D Bot($)_S|E Value(!)_S
</code></pre>
<p>I am able to find the columns ending with '_S' using below code</p>
<pre><code> df.columns[df.columns.str.contains('_S')]
</code></pre>
<p>But i need one or more co... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>pandas.DataFrame.filter</code></a>:</p>
<pre><code>df.filter(regex="[^D]_S")
</code></pre> | python|regex|pandas | 1 |
368,348 | 60,728,151 | Remove duplicate data in a rows from data frame python without affecting the shape of the DataFrame | <p>have a data-frame :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- begin snippet: js hide: false console: true babel: false --></code></pre>
</div>
</div>
<... | <p>As follows, you can select the duplicated rows and column of interest ('A') and set the value to NAN. </p>
<pre class="lang-py prettyprint-override"><code># create df
df = pd.DataFrame([
[1, 10],
[1, 20],
[1, 30],
[2, 10]],
columns=['A', 'B'])
# replace duplicated elements with NAN, preserving... | python-3.x|pandas|dataframe|duplicates|pandas-groupby | 0 |
368,349 | 60,608,446 | Plotting minimum value across several columns using pandas | <p>I have several columns in a pandas data frame and I want to plot the minimum value across several columns for each row. i.e. </p>
<pre><code>np.random.seed(2020)
x = np.random.rand(10,3)
df = pd.DataFrame(x, columns = ["x" , "y", "z"])
</code></pre>
<p>I just want to plot something like this:</p>
<pre><code>plt.h... | <p>IIUC, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.min.html" rel="nofollow noreferrer"><code>DataFrame.min</code></a> across axis 1 and the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.hist.html" rel="nofollow noreferrer"><code>Series.h... | python|pandas|plot | 2 |
368,350 | 60,406,032 | pandas, expand series of dataframes | <p>I have a series that looks like this:</p>
<pre><code> result
3 pd.DataFrame({"ABC":1,"American":2,"Heroes":3})
8 pd.DataFrame({"ABC":1,"American":2,"Heroes":3})
11 pd.DataFrame({"ABC":1,"American":2,"Heroes":3})
14 pd.DataFrame({"ABC":1,"American":2,"Heroes":3})
17 pd.DataFrame({"ABC":1,"American":2... | <p>This is a pretty convoluted structure, I tried reconstructing your series of dataframes this way (I don't see any series with this structure in the link you point to):</p>
<pre><code>df_list = [pd.DataFrame({"ABC":[1],"American":[2],"Heroes":[3]}),
pd.DataFrame({"ABC":[1],"American":[2],"Heroes":[3]}),
... | python|pandas|indexing|concat | 0 |
368,351 | 60,386,712 | Pandas: filling NaNs only in rows intervals for which lower bound is given | <p>I have a <code>pd.Dataframe</code> with multiple missing values. I would like to fill (backfill in this case) only intervals for which I give the lower bound. I made it work with the following code. I was wondering if the for loop can be avoided and the process speeded-up (I work with several millions of rows).</p>
... | <p>Here is a solution without for-loops:</p>
<p>First I create a new DataFrame with the Start-indices, then I evaluate, at what indices I have to change the value, and what value that would be.</p>
<pre><code>new=pd.DataFrame({'Start':start_filling_indices})
new['filluntil']=new.apply(lambda row: df.iloc[row.Start:].... | python|pandas | 2 |
368,352 | 60,454,432 | Validation metrics stagnate while training keeps improving | <p>This is a model I've been using. It takes a pretrained InceptionV3 model and adds some fully connected layers on top of it. The whole thing is made trainable (including the pretrained InceptionV3 layers).</p>
<pre class="lang-py prettyprint-override"><code>with tf.device('/cpu:0'):
pretrained_model = InceptionV... | <p>After having tried several models and had a more thorough look at the data, it seems that the labels are not as clear as what I thought, and there is a lot of porosity between the different 28 classes.</p>
<p>Every time the model makes a "wrong" prediction on test data, a careful inspection of the picture makes it ... | python|tensorflow|keras|computer-vision | 1 |
368,353 | 60,645,903 | How to pass an object to a separate function - Python | <p>I’m aiming to animate a scatter plot using the df below. I’m trying to pass the <code>plot</code> and <code>groups</code> function to the <code>animate</code> function. I’m trying to return the values from each function are pass them to subsequent functions but I’m getting a<code>NameError</code> as these values are... | <p>animation draws/repeats on the global <code>figure</code>, so you need to create <code>subplots</code> in global scope. If you define <code>subplots</code> inside <code>plot</code> function, every call of <code>plot</code> will create a new <code>subplots</code></p>
<pre><code>import pandas as pd
import matplotlib.... | python|pandas|function | 1 |
368,354 | 60,701,604 | How to plot a PCM wave using the binary inputs from a .txt file | <p>In my case I will have a <code>PCM.txt</code> file which contains the binary representation of a PCM data like below.</p>
<blockquote>
<p>[1. 1. 0. 1. 0. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0.
1.
0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1.
0. 1. 0. 1. 0. 1. 0. 1.... | <p>I think you want this:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.arange(100)
y = [1.,1.,0.,1.,0.,1.,1.,1.,1.,1.,0.,1.,1.,1.,1.,1.,1.,1.,0.,1.,1.,1.,0.,1.,0.,1.,0.,1.,0.,0.,1.,0.,0.,0.,0.,0.,1.,0.,0.,0.,0.,0,0.,0.,1.,0.,0.,1.,0.,1.,0.,1.,0.,1.,0.,1.,1.,1.,1.,1.,0.,1.,1.,1.,1.,1.,1.,1... | python|numpy|matplotlib|plot|pcm | 0 |
368,355 | 60,508,243 | Calculate percentile of value in column in dataframe | <p>I have a dataframe <code>df1</code> that has two columns:</p>
<pre><code>val1 val2
Fwd 729
jeoq 28.2
ke 225.24
</code></pre>
<p>And I another dataframe <code>df2</code> that has:</p>
<pre><code>val1 val2
jdj 184.8
oem 33
kiwe 99.4
frqp 82
</code></pre>
<p>I want for each value in ... | <p>Ok, so I will assume that you want to know for each value from <code>df2['val2']</code>, what would be the corresponding percentile in the sorted values from <code>df1['val2']</code>.</p>
<p>You should first build a sorted Series to be able to later use <code>searchsorted</code>:</p>
<pre><code>dfs = df1['val2'].s... | python|pandas|dataframe|quantile | 0 |
368,356 | 60,554,426 | Split string with nested dictionary and convert into Dataframe | <p>I've this issue with this data.</p>
<p>First Lines of CSV</p>
<pre><code>{'grade1': '47.614465', 'grade2': '-122.32174', 'grade3': '{"addr": "123 AV MOUNTIAN", "town": "HAMBOURG", "dep": GR", "code": ""}'}
{'grade1': '47.61699416', 'grade2': '-122.320405', 'grade3': '{"addr": "5555 WALL STREET", "town": "NY", "dep... | <p>I think it can be fixed the following way:</p>
<pre><code>import json, pandas
def fix_line(line):
# first convert the string to proper JSON
json_string = line.replace("'",'"').replace('"{', '{').replace('}"', '}')
# convert JSON to dict
d = json.loads(json_string)
# convert dict to a tuple
... | python|pandas|dictionary | 1 |
368,357 | 60,373,833 | Compare json objects with csv file | <h2>Edit: So far my code is finding the comparisons. Am working on appending the JSON object data to the row of where the word matching occurs.</h2>
<p>I'm trying to find the matching words between my JSON file and my CSV then check where that word has a low rating(the column with decimal values) from the CSV.</p>
<p>... | <p>First define a mapping function : </p>
<pre><code>import json
import pandas
def apply_fun (row):
for value in contents['words']
if value['word'] in row['word'] :
return json.dumps(value)
return ""
</code></pre>
<p>Then add it to your dataframe : </p>
<pre><code>x = dfSynsets.apply(la... | python|json|pandas|csv|string-comparison | 0 |
368,358 | 60,603,357 | How can I optimise the ordinal encoding of a 2D array of strings in Python? | <p>I have a Pandas series that holds an array of strings per row:</p>
<pre><code>0 []
1 []
2 []
3 []
4 [0007969760, 0007910220, 0007910309]
... | <p>With the following Cython function I get a speed-up factor of about 5. It uses a temporary list for row-wise copies of relevant data which should be initialized big enough so that it can hold each row's data (i.e. if an upper bound for the maximum number of elements per row is known, use that one, otherwise use a he... | python|c|numpy|optimization|encoding | 1 |
368,359 | 72,629,156 | Tensorflow / Keras + Python use pre trained NN | <p>I want to use pre trained neuralnetwork with TF.Keras and Python.
I want to try some different cases.
I see on <a href="https://keras.io/api/applications/" rel="nofollow noreferrer">https://keras.io/api/applications/</a> the different pre trained NN that i can use.</p>
<p>I also want to use a non trained neural netw... | <p>Tbh, the question is phrased very oddly, but it sounds like you want to perform transfer learning. Take a look here - <a href="https://www.tensorflow.org/tutorials/images/transfer_learning" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/transfer_learning</a></p> | python|tensorflow|machine-learning|keras|neural-network | 0 |
368,360 | 72,555,421 | Find all rows indices in which elements of 2D NumPy array occur | <p>Lets say we have 2D array like this one:</p>
<pre><code>input_array = np.array([[0, 4, 6],
[5, 4, 1],
[2, 1, 0],
[4, 1, 0],
[1, 5, 3]])
</code></pre>
<p>How to get 2D array in which we have all the indices of rows in whic... | <p>Here's maybe a slightly more elegant solution using numpy's <code>any()</code> and a list comprehension. This also works if there are missing values in the range from 0 to 6.</p>
<pre><code>>>> np.array([np.any(input_array == i, axis=1) for i in range(6)], dtype=int)
array([[1, 0, 1, 1, 0],
[0, 1, 1... | python|arrays|numpy | 1 |
368,361 | 72,533,467 | I am looking for an efficient way to filter dataframe column. Column A is what I have Column B is what I desire | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>All Animals except Tiger/Lion;Elephant;Giraffe;all snakes;monkeys</td>
<td>Elephant;Giraffe;all snakes;monkeys</td>
</tr>
<tr>
<td>Elephant;All Animals except Tiger/Lion;Giraffe;butterflies;mo... | <p>It looks like you can split by a semi-colon, filter out the elements containing the text lion or tiger and then put it back together, eg:</p>
<pre><code>df['output'] = (
df['A'].str.split(';', expand=True).stack()
[lambda v: ~v.str.contains('lions?|tiger', case=False)]
.groupby(level=0).apply(';'.join)
)... | python|pandas|dataframe | 1 |
368,362 | 72,712,466 | How to export WTForms form.data as an XLSX | <p>Pretty new to using flask I've created a front end form that will create an excel file for listing.
I was using <a href="https://www.youtube.com/watch?v=MwZwr5Tvyxo&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH" rel="nofollow noreferrer">Corey Schafers tutorial on Flask</a> as a template.
I'm guessing I need to parse ... | <p>Fixed using Pandas</p>
<pre><code>if form.submit():
# write form data to an excel file
df = pd.DataFrame(form.data, index=[0])
# print dataframe
print(df)
print(SKU)
df.to_excel(xlsx, sheet_name=current_user.username + '_' + str(datetime.date.today()),columns=form.data, index=form.data... | python|pandas|flask-wtforms | 0 |
368,363 | 72,799,090 | Pandas - Reducing multiple rows with almost identical data into one | <p>I am working with data that is almost identical, consisting of IDs and Type, however there could be multiple different types per ID. How can I merge/fuse each ID with all its respective types?</p>
<p>Current data form:</p>
<pre><code>data = {'Name': {0: np.nan, 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan},
'ID': {0:... | <p>You can use:</p>
<pre><code>out = (df.assign(Cat=df.groupby('ID').cumcount().add(1).astype(str))
.pivot(['Name', 'ID'], 'Cat'))
out.columns = out.columns.to_flat_index().str.join('-')
out = out.reset_index().rename_axis(columns=None)
</code></pre>
<p>Output:</p>
<pre><code>>>> out
Name ID Ty... | python|pandas|merge|rows|fuse | 1 |
368,364 | 72,523,484 | TF Serving Predict API Output Interpretation | <p>Is the TensorFlow Serving (TFS) Predict API output the same as the tf.keras.model.predict method (i.e. the outputs of the model according to the compiled metrics)?</p>
<p>For example, if we have a tf.keras.model compiled with BinaryAccuracy metric, will the output of the TFS predict API be a list of binary accuracy ... | <p>I am not able to clearly get your question about compiled metrics and the output prediction of the model. But here's the comparision of outputs from <code>Keras predict</code> method and <code>TF Serving's Predict API</code>.</p>
<p>The output format of prediction for both Keras and TF Serving Predict API is simila... | tensorflow|tensorflow-serving|tfx | 0 |
368,365 | 72,794,896 | Efficiently convert Numpy 2D array of counts to zero-padded 2D array of indices? | <p>I have a numpy 2D array of n rows (observations) X m columns (features), where each element is the count of times that feature was observed. I need to convert it to a zero-padded 2D array of feature_indices, where each feature_index is repeated a number of times corresponding to the 'count' in the original 2D array.... | <p>One solution would be to <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.html" rel="nofollow noreferrer"><code>flatten</code></a> the array and use <a href="https://numpy.org/doc/stable/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>np.repeat</code></a>.</p>
<p... | python|arrays|numpy|performance|indexing | 1 |
368,366 | 72,555,226 | How can I specify a different decimal format on each column when using Pandas DataFrame to CSV? | <p>I am parsing specific columns from a text file with data that looks like this:</p>
<pre><code> n Elapsed time TimeUTC HeightMSL GpsHeightMSL P Temp RH Dewp Dir Speed Ecomp Ncomp Lat Lon
s hh:mm:ss m m hPa ∞C % ∞C ∞ m/s m/s m/s ∞... | <p>You can pass dictionary and then if round by <code>0</code> casting columns to integers:</p>
<pre><code>d = {'hpa':1, 'spdkt':0, 't':1, 'td':1, 'dir':0}
df = df.round(d).astype({k:'int' for k, v in d.items() if v == 0})
print (df)
n s time m1 m2 hpa t rh td dir spd u v \
0 1 0 23... | python|pandas|dataframe|csv | 1 |
368,367 | 72,754,661 | Find distance between rows in pandas dataframe but with reference to 1 row | <p>In this pandas dataframe:</p>
<pre><code>y_train feat1 feat2
0 9.596113 -7.900107
1 -1.384157 2.685313
2 -8.211954 5.214797
</code></pre>
<p>How do I go about adding a "distance from Class 0" column at the end of the dataframe, that returns the distance from y_train=0 for each class (i.e... | <p>pairwise_distances wants a first input X - all the points - and then Y - where we want to compute the distance to.</p>
<p>So for X we have: All the classes. Each feature is one coordinate of its location or in mathematical terms, the class is a vector <em>f</em> = [<em>f</em><em><sub>0</sub>, <em>f</em></em><sub>1</... | pandas|dataframe|euclidean-distance | 1 |
368,368 | 72,761,858 | Formatting our data into PyTorch Dataset object for fine-tuning BERT | <p>I'm using an already existing code from <em>Towards Data Science</em> for fine-tuning a BERT Model.
The problem I'm facing belongs to this part of the code which where try to format our data into a PyTorch <code>data.Dataset</code> object:</p>
<pre><code>class MeditationsDataset(torch.utils.data.Dataset):
def _i... | <p>Special functions in Python use <em><strong>double underscores</strong></em> prefix and suffix. In your case, to implement a <a href="https://pytorch.org/docs/stable/data.html#map-style-datasets" rel="nofollow noreferrer"><code>data.Dataset</code></a>, you must have <a href="https://docs.python.org/3/reference/datam... | python|oop|pytorch|bert-language-model | 1 |
368,369 | 72,834,710 | gspread_pandas - how to automate daily task and add new row at the row 2 or end of sheet | <p>I have a script that I run manually. Every day I am changing start='A2' to A+1,. Finally I have some time to automate it with Google Cloud, but I don't know how to insert new row above A2 after script is successful (so i can make a space for script data and not to override previous day) or find last not empty row an... | <p>Ok, I used:
pozycja = spread.get_sheet_dims(sheet="nowa_rentownosc")
pozycja = pozycja[0]+1</p>
<p>and it worked. :)</p> | python|pandas|gspread | 0 |
368,370 | 72,743,708 | How to check if there are multiple versions using groupby | <p>I want to check if there are documents with different versions in one group. if so, they should be written into a new dataframe.</p>
<p>My initial dataframe looks as follows:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>document</th>
<th>version</th>
<th>group</th>
</tr>
</thead>
<tbo... | <p>You can use masks for boolean indexing:</p>
<pre><code># is the full row not duplicated?
m1 = ~df.duplicated()
# is there more that one version per document+group?
m2 = df.groupby(['document', 'group'])['version'].transform('nunique').gt(1)
out = df[m1&m2] # keep if both conditions are met
</code></pre>
<p>outp... | python|pandas | 4 |
368,371 | 72,520,705 | Combine every two rows of pandas dataframe into separate columns | <p>I have a dataframe with 3 columns (x, y and data), I need to combine every two rows and end up with two data columns.
Essentially I need to combine the rows with the same x and y coordinates into one whilst keeping the two data variables separate creating 4 columns (x, y, u and v)</p>
<pre><code>Original data exampl... | <p>if sorting your dataframe by coordinates is not an issue then you can probably try:</p>
<pre class="lang-py prettyprint-override"><code>
df = pd.DataFrame(dict(
x=[1,1,1,1],
y=[1,1,2,2],
data=[0.2,0.5,0.7,0.2]
)).sort_values(by=["x", "y"])
df["label"] = ["u", &quo... | python|pandas | 1 |
368,372 | 72,692,706 | Compare values per row | <p>For building an ensemble model I want to create a table with all results of a classification. Next I want to calculate per row the amount of different values and find the most frequent value.</p>
<hr />
<p>Let's say the initial table looks like:</p>
<pre><code>+----+--------+--------+--------+
| | col1 | col2... | <p>Check <code>nunqiue</code> and <code>mode</code></p>
<pre><code>df["most_frequent"] = df.mode(axis=1) # when there is only one most freq value return
#df.mode(axis=1).max(1) #if there is more than one same freq value
#df.mode(axis=1).min(1) # for get the smallest
df["different_values"] = df.nun... | python|pandas | 3 |
368,373 | 72,749,917 | Shap/numpy: all the input array dimensions for the concatenation axis must match exactly | <p>Could someone please explain how to fix when this code (a reproducible example):</p>
<pre><code>from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedKFold,KFold
from sklearn.feature_selection import SelectKBest
#from xgboost import XGBClassifier
from sklearn.feature_selec... | <p>Before you can fix a problem, you have to understand it. When it comes to <code>shape</code> errors, you have to know the shape of all variables involved. Sometimes that can be deduced, but often I have to add some print statements to be sure.</p>
<pre><code>shap_values = np.array(list_shap_values[0])
for i in ran... | python|numpy|scikit-learn|shap | 0 |
368,374 | 72,525,904 | Python - Adding rows based on information in columns | <p>What I'm looking to do is to add to the 'TestDate' column based on the information in 'eperf2', 'mperf2', and 'sperf2' columns. The 'StudentTestID' is the unique identifier. In the dataframe if there is anything in the 'eperf2' column for that specific 'StudentTestID' then I want the 'TestDate' to say "April 1&... | <p>I hope this gives you an idea :)</p>
<pre><code>for i in range(3000): # because you have less than 3000 records or use `while loop`
eperf2 = df.iloc[i][12] # because eperf2 is 12th column
mperf2 = df.iloc[i][13]
sperf2 = df.iloc[i][14]
if (eperf2 | mperf2 | sperf2): # of course, create 3 `if` co... | python|pandas|dataframe | 0 |
368,375 | 72,583,085 | count number of adjacent elements in a matrix | <p>I have a matrix such as this</p>
<pre><code>h_diag = np.array([[1,0,1], [0,0,0], [1,0,1]])
array([[1, 0, 1],
[0, 0, 0],
[1, 0, 1]])
</code></pre>
<p>I want an equal sized matrix where each element represent how many adjacent number it has. For the above matrix (both vertical and horizontal), it would b... | <p>Implementation of @jaghana suggestion</p>
<pre><code>x = np.array([[1,0,1], [0,0,0], [1,0,1]])
y = np.full_like(x, fill_value=8, dtype=int)
y[:, (0, -1)] = y[(0, -1), :] = 5 # edges = 5
y[(0, 0, -1, -1), (0, -1, 0, -1)] = 3 # corners=3
array([[3, 5, 3],
[5, 8, 5],
[3, 5, 3]])
</code></pre> | pandas|dataframe|numpy | 1 |
368,376 | 72,831,329 | Calculate difference between two dates in python | <p>I have two columns date1 and date2 in <code>2/23/2022 12:30:26</code> format ,i want to calculate difference in hours. How to implement .</p> | <p>You can convert two columns to datetime type then subtract at last get hours from timedelta object.</p>
<pre class="lang-py prettyprint-override"><code>df['date1'] = pd.to_datetime(df['date1'])
df['date2'] = pd.to_datetime(df['date2'])
df['diff'] = (df['date1']-df['date2']) / pd.Timedelta(hours=1)
</code></pre> | python|python-3.x|pandas|datetime | 3 |
368,377 | 72,780,440 | How to plot local date and time vs temperature from CSV file that uses UTC for date and time | <p>I have a CSV file where each row has date and time and temperature, where the date and time are UTC.</p>
<p>I can plot temperature as a function of time, but the X axis shows the UTC time.</p>
<p>What is the best way to generate a plot where the X axis shows my local time (which is currently Pacific Daylight Time)?<... | <p>Use the <code>tz_convert</code> function on a <code>datetime</code> type <code>pandas</code> column to convert it to PDT.</p>
<pre><code>import pandas as pd
df['Time'] = pd.to_datetime(tdf['Time'])
df['Time_local'] = df['Time'].dt.tz_convert('PST8PDT')
</code></pre> | python|pandas|time-series|utc | 0 |
368,378 | 72,599,219 | how to compute mean absolute deviation row wise in pandas | <p>snippet of the dataframe is as follows. but actual dataset is 200000 x 130.</p>
<pre><code>ID 1-jan 2-jan 3-jan 4-jan
1. 4 5 7 8
2. 2 0 1 9
3. 5 8 0 1
4. 3 4 0 0
</code></pre>
<p>I am trying to compute Mean Absolute Deviation for each row value like ... | <p>It's possible to specify <code>axis=1</code> to apply the mean calculation across columns:</p>
<pre class="lang-py prettyprint-override"><code>df['mean_across_cols'] = df.mean(axis=1)
</code></pre> | python|pandas|dataframe|for-loop|mean | 0 |
368,379 | 72,669,152 | in creating a custom layer, when the build method is called in Keras | <p>Sorry, I am new to deep learning and keras. I am trying to define a layer myself.</p>
<p>I looked into the keras document, <a href="https://keras.io/api/layers/base_layer/#layer-class" rel="nofollow noreferrer">https://keras.io/api/layers/base_layer/#layer-class</a></p>
<pre><code>class SimpleDense(Layer):
def __... | <p>To know about this <code>SimpleDense</code> layer and answer your questions, we need to explain <code>weight</code> and <code>bias</code>. weight in <code>SimpleDense</code> first gets random numbers and <code>bias</code> gets <code>zero</code> numbers and in the training of the model, this weight and bias change to... | python|tensorflow|keras|deep-learning|tensorflow2.0 | 2 |
368,380 | 72,539,701 | How to perform computations easily between every column in a polars DataFrame and the mean of that column | <h2>Environment</h2>
<pre><code>macos: monterey
node: v18.1.0
nodejs-polars: 0.5.3
</code></pre>
<h2>Goal</h2>
<p>Subtract every column in a <a href="https://www.pola.rs/" rel="nofollow noreferrer">polars</a> DataFrame with the mean of that column.</p>
<h2>Pandas solution</h2>
<p>In pandas ... | <p>You tagged this problem with [python-polars], so I'll provide a solution using Polars with Python. (Perhaps you can translate that to Node-JS.)</p>
<p>Starting with our data:</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
df = pl.DataFrame(
{
"A": [13520, 13472, 13456... | pandas|dataframe|python-polars|rust-polars|nodejs-polars | 6 |
368,381 | 72,549,382 | splitting the file and rearrangement | <p>My text file contain data of temp variation</p>
<pre><code>#
1 2
2 4
3 4
#
6 1
3 2
1 7
</code></pre>
<p>I want the column values to be splitted at # and generate the new files by appending the splitted files</p>
<p>expected output1</p>
<pre><code>1 6
2 3
3 1
</code></pre>
<p>expected output2</p>
<pre><code>2 ... | <p>A more complex problem than it seems at first glance. I had to carefully look at the example output to fully see what was going on.</p>
<p>Simulated text file:</p>
<pre><code>sim_txt = io.StringIO('''
#
1 2
2 4
3 4
#
6 1
3 2
1 7
''')
df = pd.read_csv(sim_txt, sep='\s+', header=None, names=[0,1])
df_out = df... | pandas|dataframe | 0 |
368,382 | 72,639,483 | How to combine multiple mm-dd-yy values into a year_month column? (python) | <p>I'm learning python so sorry if this is a basic question, but I couldn't find the specific answer I was looking for from questions posted here previously.</p>
<p>I have the dataframe below, which lists grocery items, their prices, and the dates purchased. I want to create a new column called year_month. So basically... | <p>One way using <code>pandas.to_datetime</code> with <code>strftime</code>:</p>
<pre><code>df["Year_Month"] = pd.to_datetime(df["Date"]).dt.strftime("%m-%Y")
print(df)
</code></pre>
<p>Output:</p>
<pre><code> Item Price Date Year_Month
0 Apples 2.99 03-22-2022 03-2022... | python|pandas|datetime | 0 |
368,383 | 72,771,213 | Find words in array and get their indexes in Dataframe in Pandas | <p>I have a dataframe :</p>
<pre><code>import pandas as pd
data = {'token_1': [['cat', 'run','today'],['dog', 'eat', 'meat']],
'token_2': [[ 'in', 'the' , 'morning','cat', 'run', 'today',
'very', 'quick'],['dog', 'eat', 'meat', 'chicken', 'from', 'bowl']]}
df = pd.DataFrame(data)
</code><... | <p>Use list comprehension with <code>enumerate</code> for indices:</p>
<pre><code>L = [[i for i, x in enumerate(b) if x in a] for a, b in zip(df['token_1'], df['token_2'])]
print (L)
[[3, 4, 5], [0, 1, 2]]
</code></pre> | python|pandas|dataframe | 2 |
368,384 | 72,628,294 | How can I transform dataframe using pd.melt | <p>This is my dataframe for example</p>
<pre><code>df = pd.DataFrame([['Bob', 'lunch', 70],
['Bob', 'dinner', 160],
['Sara', 'lunch', 150],
['Sara', 'dinner', 220]],
columns=['Name', 'Meal', 'Cost'])
</code></pre>
<pre><code> Name Meal ... | <h3>a) This looks more like a job for <code>pivot()</code> not <code>melt()</code>.</h3>
<pre><code>df.pivot(index=['Name'], columns=['Meal'], values=['Cost'])
</code></pre>
<p>The result is a pivot-table:</p>
<pre><code> Cost
Meal dinner lunch
Name
Bob 160 70
Sara 220 150
</code></pre>
<p>Not exactly... | python|pandas | 2 |
368,385 | 72,693,671 | PyTorch running under WSL2 getting "Killed" for Out of memory even though I have a lot of memory left? | <p>I'm on Windows 11, using WSL2 (Windows Subsystem for Linux). I recently upgraded my RAM from 32 GB to 64 GB.</p>
<p>While I can make my computer use more than 32 GB of RAM, WSL2 seems to be refusing to use more than 32 GB. For example, if I do</p>
<pre><code>>>> import torch
>>> a = torch.randn(100... | <p>According to <a href="https://joe.blog.freemansoft.com/2022/01/setting-your-memory-and-swap-for-wsl2.html" rel="nofollow noreferrer">this blog post</a>, WSL2 is automatically configured to use 50% of the physical RAM of the machine. You'll need to add a <code>memory=48GB</code> (or your preferred setting) to a <cod... | memory|pytorch|out-of-memory|windows-subsystem-for-linux|wsl-2 | 1 |
368,386 | 72,645,802 | Convert a pdb file in a csv file | <p>I am Cosimo from Italy, I am a student of physical chemistry, i am doing my thesis and i have a big problem.
I nead to convert a pdb file in a csv for work with pandas.
I've tried every way but with no success.
Can you help me?</p> | <p>I've never worked with pdb files, but after a quick search I found this :</p>
<p><a href="http://rasbt.github.io/biopandas/tutorials/Working_with_PDB_Structures_in_DataFrames/" rel="nofollow noreferrer">http://rasbt.github.io/biopandas/tutorials/Working_with_PDB_Structures_in_DataFrames/</a></p>
<p>It seems like you... | pandas|dataframe | 0 |
368,387 | 72,560,165 | How to prevent NVIDIA from automatically upgrading the driver on Ubuntu? | <p>I was training models last night on my Ubuntu workstation, and then woke up this morning and saw this message:</p>
<pre><code>Failed to initialize NVML: Driver/library version mismatch
</code></pre>
<p>Apparently the NVIDIA system driver automatically updated itself, and now I need to reboot the machine to use my GP... | <p>I think I have had the same issue. It is because of so-called unattended upgrades on Ubuntu.</p>
<h1>Solution 1: check the changed packages and revert the updates</h1>
<p>Check the apt history logs</p>
<pre><code>less /var/log/apt/history.log
</code></pre>
<p>Then you can see what packages have changed. Use <code>ap... | tensorflow|ubuntu|pytorch|nvidia|nvidia-docker | 1 |
368,388 | 72,556,521 | Why does my for loop combined with if-statement provide a wrong output? | <p>I have a pandas dataframe called <code>df_dummy</code> with 3 columns: Days, Vacations_per_day and day_of_week. And I have a list called <code>legal_days</code>. I want to see if values from df_dummy['Days'] are found in the list legal_days and if found, change the value of Vacations_per_day column to 4 for that spe... | <p>Looking at your code, I don't see how this would occur. However, your solution seems to be outside the normal use-case for modifying a pandas dataframe. You could accomplish all of this with <code>loc</code> and <code>isin</code>:</p>
<pre><code>df_dummy.loc[df_dummy['Days'].isin(legal_days), 'Vacations_per_day'] = ... | python|pandas|list|for-loop|if-statement | 1 |
368,389 | 72,546,580 | Select MultiIndex rows by level, in Pandas | <p>How can I select rows from a MultiIndex DataFrame that have more than 1 level? For example, given the following DataFrame:</p>
<pre><code> col
L1 L2
a 1 5624
2 1656
3 265677
4 3755
b 5 47
6 85544
c 7 97656
d 8 12774
e 9 111
10... | <p>Check <code>transform</code> <code>count</code></p>
<pre><code>out = df[df.groupby(level=0)['col'].transform('count').values>1]
</code></pre> | python|pandas|multi-index | 1 |
368,390 | 72,522,941 | Python: ways to vectorize "apply a power function with random power to each row in NumPy array" | <p>I would like to find efficient ways to do the following operation:</p>
<ol>
<li>I have a vector of known values, which will be the first row in the following array mentioned.</li>
<li>I would like to create an array. For each row other than the first row, it is essentially the first row applied with a power function... | <p>Broadcasting to the rescue:</p>
<pre class="lang-py prettyprint-override"><code>In [2]: beta = np.array([0, 1, 2])
In [3]: lo, hi, num_rows_desired = 0, 3, 3
In [4]: exps = np.random.uniform(lo, hi, num_rows_desired)
In [5]: exps[0] = 1 # Set the first 'power' to 1
In [6]: beta ** exps[:, None]
Out[6]:
array([[... | python|arrays|numpy|vectorization | 3 |
368,391 | 72,657,483 | Filter rows from a CSV that has only beginning or starting quotes, but dont have end quote for a column | <p>I have a sample CSV file which has 2 rows.</p>
<p>pandas.read_csv is successful if the row columns has both START & END double quotes in its columns. But if a row column has only start double quote and does not have a end double quote for the column, pandas.read_csv is failing with error, "ParserError: Erro... | <p>When rows are not properly formatted, it might be too difficult to use standard methods for reading them.</p>
<p>You could separate the bad from the good rows into two csv files first. Then you could create two data frames from these files.</p>
<pre class="lang-py prettyprint-override"><code>
original = "csvtes... | python|python-3.x|pandas|python-2.7 | 3 |
368,392 | 72,778,254 | TypeError: no numeric data to plot- plotting dataframe | <p>I am getting the following type of error: <strong>no numeric data to plot</strong></p>
<p>When trying to plot the data frame</p>
<pre><code>df_prevalence.head()
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>State</th>
<th>Percent</th>
</tr>
</thead>
<tbody>
<tr>
<td... | <p>You likely inverted the x and y:</p>
<pre><code>ax = df_prevalence.plot(kind='barh', y='Percent', x='State', ...)
</code></pre>
<p>output (with smaller size):</p>
<p><a href="https://i.stack.imgur.com/SC0qj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SC0qj.png" alt="enter image description her... | python|pandas|dataframe | 0 |
368,393 | 72,808,040 | How to read csv row by row and prevent skipping lines | <p>Have this as data from a csv as rawdata coming in by REST api.</p>
<pre><code>serial-number;device-identification;created;value-data-count;volume,m3,inst-value,0,0,0;duration-since-last-readout,second(s),inst-value,0,0,0;op-time,second(s),inst-value,0,0,0;enhanced-id,,inst-value,0,0,0;model/version,,inst-value,0,0,0... | <p>Read line by line (one line of headings and one line of content), using the longest headings as the complete headings:</p>
<pre><code>a = """
serial-number;device-identification;created;value-data-count;volume,m3,inst-value,0,0,0;duration-since-last-readout,second(s),inst-value,0,0,0;op-time,second(s)... | python|json|pandas | 1 |
368,394 | 72,649,170 | Is there an elegant way to iterate over index and one column of a pandas dataframe? | <p>I'd like have a loop that iterates over both the index, and the entries in one specific column of a dataframe. I've found a solution that works, but I feel there should be something more elegant. Any suggestions?</p>
<p>Working example:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(index = [10, 20, 30])
df['A... | <p>The dataframe entry has a dictionary interface for this purpose. You can do <code>df['A'].items()</code></p>
<pre><code>import pandas as pd
df = pd.DataFrame(index=[10, 20, 30])
df['A'] = [1, 2, 3]
df['B'] = [5, 7, 9]
for i, v in df['A'].items():
print(i, v)
</code></pre>
<pre><code>10 1
20 2
30 3
</code></pre> | python|pandas|dataframe | 4 |
368,395 | 72,544,707 | If..else use different input datasets | <p>I'm a python beginner could you please help me to this?</p>
<p><em><strong>If variable is true I need to use A Dataset as input else have to use B dataset.</strong></em></p>
<p>How to write this please help me.</p> | <p>You could create a third variable df and assign that to a copy of A or B and use that for the code:</p>
<pre><code>if variable:
df = A.copy()
else:
df = B.copy()
##some code using df##
</code></pre>
<p>Alternatively, you could write a function for the code using the df, and have A or B as an input like this... | python|pandas | 1 |
368,396 | 72,742,207 | insert dtype in std::map | <p>I want to do a map that takes a pair of <code>pybind11::dtype</code> and <code>int</code> and maps it into an OpenCV format:</p>
<pre><code>static std::map<std::pair<pybind11::dtype, int>, int> ocv_types;
</code></pre>
<p>So I <code>insert</code>ed all combinations but there seems to be a problem when a... | <p>As you noted <code>pybind11::dtype</code> do not have any particular order.
So IMO best approach is to use <code>std::unordered_map</code> and provide respective hashes. <code>pybind11</code> already has some <a href="https://pybind11.readthedocs.io/en/stable/reference.html#_CPPv44hash6handle" rel="nofollow noreferr... | c++|numpy|stdmap|pybind11 | 1 |
368,397 | 72,805,627 | How does PIL Image save NumPy arrays with non-integer and non-positive values? | <p>I have a NumPy array of size 28 x 280, which contains real number values (both positive and negative values). I am using the following code to save this array to file through a PIL Image -</p>
<pre><code>img = Image.fromarray(img)
img.save(save_path, "PNG")
</code></pre>
<p>Now, when I load this saved imag... | <p>If you want to save negative and floating point data as an image, you should probably use <strong>TIFF</strong> format.</p>
<p><strong>PNG</strong> is only able to store unsigned integer data at up to 16-bit/channel, i.e. in range 0..65535.</p>
<hr />
<p>Here is a demonstration of saving positive and negative floati... | python|image|numpy|python-imaging-library | 2 |
368,398 | 72,608,732 | Create new column in dataframe using multiple columns of different types | <p>I have a DataFrame for the boardgame <a href="https://boardgamegeek.com/boardgame/167791/terraforming-mars" rel="nofollow noreferrer">Terraforming Mars</a> on which I want to do several calculations in pandas. The df has columns for points accumulated through different methods, as well as the <code>game_id</code>, <... | <p>So I ended up using this function, which I wouldn't consider overly pythonic. It, did, however, do the trick:</p>
<pre><code>def winners(df):
'''
Takes in a DataFrame and outputs a winners column.
If there is a tie, it adds both winners to the column
'''
lst = []
for x in range(df['Game... | python|pandas|dataframe | 0 |
368,399 | 72,818,112 | How to modify lambda function to use with an if-statement? | <p>I stuck in the middle with the problem of how to create four new rows in a dataframe which would be populated by 1 and 0 on a certain condition. I decided to use Lambda functons but instead of numbers it returns <code><function <lambda> at 0x000002B0251C7700></code>.</p>
<p>What am I doing wrong and how ... | <p><code>lambda</code> only defines function but it doesn't execute it.</p>
<p>You may have to use it with <code>.apply()</code> to run on every row - but in <code>lambda</code> you should use <code>row[...]</code> instead of <code>df[...]</code></p>
<pre><code>func1 = lambda row : 1 if (row["stage_x"] <= ... | python|pandas|dataframe|if-statement|lambda | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.