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 |
|---|---|---|---|---|---|---|
370,500 | 62,408,157 | Replace values in dataframe column (regex) | <p>I have a dataframe column with names:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'Names': ['ROS-053', 'ROS-54', 'ROS-51', 'ROS-051B', 'ROS-051A', 'ROS-52']})
df.replace(to_replace=r'[a-zA-Z]{3}-\d{2}$', value='new', regex=True)
</code></pre>
<p>The format needs to be three letters foll... | <p>You can do:</p>
<pre><code>df['Names'] = df.Names.replace('^([a-zA-Z]{3})-0?(\d{2})(.*)$', r'\1-0\2', regex=True)
</code></pre>
<p>Output:</p>
<pre><code> Names
0 ROS-053
1 ROS-054
2 ROS-051
3 ROS-051
4 ROS-051
5 ROS-052
</code></pre> | python|regex|pandas|replace | 0 |
370,501 | 62,135,816 | Pandas count occurence of value in dictionary | <p>Given a DF:</p>
<pre><code>pd.DataFrame({"A":[1,2,3],
"B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
{"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
{"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
})
</code></pre>
<p>How do i get a count of numbe... | <p>You can do an <code>apply</code>:</p>
<pre><code>df['count'] = df.B.apply(pd.Series).eq('Closed').sum(1)
</code></pre>
<p>Output:</p>
<pre><code> A B count
0 1 {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'} 2
1 2 {'Mon': 'Open', 'Tue': 'Open', 'Wed... | python|pandas | 4 |
370,502 | 62,313,327 | Network loss stalls where it should fall to zero quickly | <p>I have a neural network with 30 input nodes, 1 hidden node, and 1 output node. I am training it on a dataset where the inputs are 30-dimensional vectors with entries between -1 and 1, and the targets are the 2nd entry of these vectors.</p>
<p>I expect the network to train and learn to output the 2nd entry of the in... | <p>Your targets are between -1 and 1, but a sigmoid output activation limits outputs to [0, 1], making it impossible to achieve zero loss if any targets happen to be < 0 (which is very likely with a large dataset). You could fix it by using <code>tanh</code> as activation instead, which maps to [-1, 1], or just usin... | python|tensorflow|keras|deep-learning|neural-network | 2 |
370,503 | 62,052,734 | How embedding_bag exactly works in PyTorch | <p>in PyTorch, torch.nn.functional.embedding_bag seems to be the main function responsible for doing the real job of embedding lookup. On PyTorch's documentation, it has been mentioned that embedding_bag does its job > without instantiating the intermediate embeddings. What does that exactly mean? Does this mean for ex... | <p>In the simplest case, <code>torch.nn.functional.embedding_bag</code> is conceptually a two step process. The first step is to create an embedding and the second step is to reduce (sum/mean/max, according to the "mode" argument) the embedding output across dimension 0. So you can get the same result that em... | neural-network|pytorch|torch|embedding|python-embedding | 5 |
370,504 | 62,304,144 | Compute weighted sum of a 2D Numpy array | <p>I have a numpy 2D array of some dimension say 2 by 2 (in <code>numpy.float32 dtype</code>)</p>
<pre><code>[[0.001 0.02],
[0.3 0.9]]
</code></pre>
<p>I want to create a new mask matrix for the given matrix such that,</p>
<pre><code>if a1<= matrix element <a2:
new element = a3
if b1<= matrix element &... | <p>You can achieve this result with <code>numpy.select</code> and a dictionary summarizing your conditions.</p>
<pre><code>arr = np.array([[0.001, 0.02], [0.3, 0.9]])
selection_dict = {10: (0<=arr)&(arr<0.05),
5: (0.05<=arr)&(arr<1.0)}
In [52]: np.select(condlist=selection_dict.v... | python|numpy | 3 |
370,505 | 62,384,026 | tf.keras mean_squared_error strange return when data length > batch size | <p>MSE as a loss function in a sequential model, does not work properly when data length > batch size.</p>
<p>Let's start with data length < 32.
In this case it works fine, next we'll do the same with 3 more values in data.</p>
<p>Firstly we get our data, then we calculate MSE, then we run one epoch of our simple ... | <p>I do not know if I exactly understand what you are trying to do here, but your problem is related to the fact that, by default, in <code>model.fit(xs, ys, epochs=1)</code>, <code>batch_size</code> parameter is equal to <code>32</code>.</p>
<p>This is why your code fails, if you set it to <code>64</code> and increas... | tensorflow|keras|deep-learning|loss-function|mean-square-error | 0 |
370,506 | 62,109,679 | Keras vs Pytorch NN code small differences, need clarification | <p>I have the Keras and Pytorch code for the same neural network. Some of the lines are switched around between the two.
I am wondering why for the Pytorch version max pooling comes before batch normalization and reel activation. In Keras it comes after those two lines. And for flattening, I'm also confused on how Pyt... | <p>Max pooling downsamples the data by picking the maximum of a certain pool of values. Comparisons between data will not be affected by batch normalization and ReLU activation because both are one-to-one monotonically increasing functions.</p>
<pre class="lang-py prettyprint-override"><code>relu(x) = max(0, x)
bn(x) ... | python|tensorflow|keras|pytorch | 1 |
370,507 | 62,097,369 | Error when installing a python module in Linux | <p>I am encoutering two kinds of issues while trying to install a package called Boltztrap2. </p>
<p>1) Trying to install <a href="https://pypi.org/project/BoltzTraP2/" rel="nofollow noreferrer">Boltztrap2</a> using 'pip3'. However, when I punch in the command, the process goes smoothly for a while and then spits out ... | <pre><code>python3 -m pip install --upgrade pip
pip3 install numpy
</code></pre>
<p>Check if you can upgrade pip?
If that works then you can pip install numpy.</p> | numpy|pip | 1 |
370,508 | 62,292,854 | Resnet18 first layer output dimensions | <p>I am looking at the model implementation in PyTorch. The 1st layer is a convolutional layer with filter size = 7, stride = 2, pad = 3. The standard input size to the network is 224x224x3. Based on these numbers, the output dimensions are (224 + 3*2 - 7)/2 + 1, which is not an integer. Does the original implementatio... | <p>The dimensions always have to be integers. From <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d" rel="nofollow noreferrer"><code>nn.Conv2d</code> - Shape</a>:</p>
<p><a href="https://i.stack.imgur.com/UUfW7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UUfW7.png" alt="Conv2d Sh... | neural-network|pytorch|conv-neural-network|deep-residual-networks | 1 |
370,509 | 62,432,572 | RuntimeError: value cannot be converted to type uint8_t without overflow: -0.192746 | <p>I am new to Pytorch and am aiming to do an image classification task using a CNN based on the EMNIST dataset.</p>
<p>I read my data in as follows:</p>
<pre><code>emnist = scipy.io.loadmat(DATA_DIR + '/emnist-letters.mat')
data = emnist ['dataset']
X_train = data ['train'][0, 0]['images'][0, 0]
X_train = X_train.resh... | <p>What fixed my problem was replacing <code>out = self.cnn1(x)</code> with <code>out = self.cnn1(x.float())</code></p> | python-3.x|runtime-error|pytorch|conv-neural-network | 0 |
370,510 | 62,223,734 | Use tensorflow.js model in android | <p>There are some great models in tensorflow.js for face mesh detection, pose detection etc. How can I use these models on Android? Is there a way to convert tensorflow.js models to tflite models? </p> | <p>You can try converting your tf.js model into Keras python model first (refer to <a href="https://github.com/tensorflow/tfjs/tree/master/tfjs-converter" rel="nofollow noreferrer">https://github.com/tensorflow/tfjs/tree/master/tfjs-converter</a>), and then convert it to a lite model (refer to <a href="https://www.tens... | android|tensorflow|mobile|tensorflow-lite | 0 |
370,511 | 62,386,107 | Custom agora sdk flutter with open cv and tensorflow | <p>I want to use open cv and tensorflow for flutter agora sdk on ios, but I dont know how to import it. This is link repo <code>https://github.com/AgoraIO/Flutter-SDK</code>. Anyone can help me ?</p> | <p>Take a look at the example here: <a href="https://github.com/AgoraIO-Community/Agora-Flutter-Quickstart" rel="nofollow noreferrer">https://github.com/AgoraIO-Community/Agora-Flutter-Quickstart</a></p>
<p>To answer your question specifically, to import the SDK you need to add it to your pubspec.yml file in your Flut... | ios|tensorflow|opencv|flutter|agora.io | 0 |
370,512 | 62,444,459 | Align pandas dataframes with multiindex | <p>I have two pandas dataframes <code>df1</code> and <code>df2</code> with a different multiindex. I would like to align both dataframes according to the last index level. The shorter dataframe rules, i.e. all the dates that are not in the shorter dataframe should be removed from the longer dataframe.</p>
<p>If I were... | <p>You can create the new index for the desired level (2 in your case) by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.intersection.html" rel="nofollow noreferrer"><code>intersection</code></a> and then select the rows with <a href="https://pandas.pydata.org/pandas-docs/stable/refere... | pandas|multi-index | 1 |
370,513 | 62,290,461 | Search for string pattern in dataframe column, return each occurence and join to another dataframe | <p>I'm trying to do something similar to <a href="https://stackoverflow.com/questions/59522281/how-to-loop-through-pandas-df-column-finding-if-string-contains-any-string-from">How to loop through pandas df column, finding if string contains any string from a separate pandas df column?</a>, specifically the second probl... | <p>(edited). </p>
<p>The pattern piece is a good start, but then you have to merge / join it with the original dataframe: </p>
<pre><code>df.index.name = "inx"
pattern = re.compile (r'(\[[\w ]+\]\.\[[\w ]+\])')
# extract the attributes.
extracts = df.MDX_TEXT.str.extractall(pattern).rename(columns={0:"attrname"})
... | python|pandas|string|dataframe | 0 |
370,514 | 62,230,177 | Filter By Time Without Date in datetime64 | <p>Let's say I have a dataframe with a column called <code>my_date_time</code> and its type is <code>datetime64</code>.</p>
<p>How can I filter by just the time portion?</p>
<p>For example, I would like to do something like:</p>
<pre><code>df[some_magic_func(df['my_date_time']) < '09:30:00.123456']
</code></pre>
... | <p>You can use the following to filter :</p>
<pre><code>df.loc[df.my_date_time.dt.time<pd.to_datetime('09:30:00.123456').time()]
</code></pre> | pandas|datetime|time | 3 |
370,515 | 62,273,200 | Pandas line graph - y-axis high values at the bottom and low values at the top (fliped 180 degree) | <p>I am new to pandas and just want to show my rank vs my friends rank using pandas.
And because a lower Rank is better than a higher rank (the #1 = better then #2)
I want the graph to rising and not to fall. With the code I have, the graph is falling... Please help.</p>
<pre><code>import pandas as pd
import matplotl... | <p>Are you looking for <code>invert_yaxis</code>:</p>
<pre><code>fig, ax = plt.subplots()
lines = df.plot.line(ax=ax)
ax.invert_yaxis()
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/uuToH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uuToH.png" alt="enter image description h... | python|pandas|matplotlib | 1 |
370,516 | 62,372,645 | Run inference using ONNX model in python input incompatibility problem? | <p>I am a beginner in programming, I am trying to run the "tinyyolov2-8.onnx" model, I am struggling with the input formating, can anyone suggest how to formate the input for this model. code is given below,</p>
<pre><code>import numpy as np
from PIL import Image
import tensorflow as tf
sess_ort = ort.InferenceSess... | <pre><code>help(sess_ort)
...
| run(self, output_names, input_feed, run_options=None)
| Compute the predictions.
|
| :param output_names: name of the outputs
| :param input_feed: dictionary ``{ input_name: input_value }``
| :param run_options: See :class:`onnxruntime.RunOptions`.
| ... | python|numpy|tensorflow|onnx|onnxruntime | 0 |
370,517 | 62,168,434 | Check for sequence in column of Pandas DataFrame | <p>My DataFrame looks like this:</p>
<pre><code> Category Date
81 Monate 2020-01-01
88 Monate 2020-01-02
58 Monate 2020-01-03
3 Monate 2020-01-04
23 Monate 2020-01-05
.. ... ...
134 Wochen 2020-05-24
145 Tage 2020-05-25
147 Tage 2020-05-26
146 Tage 2020-05-27
148 ... | <p>I believe you can create a numeric dictionary stating the order and replace the values of the Category column and check if <code>series.diff</code> is never negative with <code>series.all</code>:</p>
<pre><code>def check(dataframe):
d = {'Monate':1,'Wochen':2,'Tage':3}
return dataframe['Category'].replace(d... | python|pandas|series | 2 |
370,518 | 62,432,363 | how do I insert a column at a specific column index in pandas data frame? (Change column order in pandas data frame) | <p>I have a pandas data frame and I want to move the "F" column to after the "B" column. Is there a way to do that?</p>
<pre><code> A B C D E F
0 7 1 8 1 6
1 8 2 5 8 5 8
2 9 3 6 8 5
3 1 8 1 3 4
4 6 8 2 5 0 9
5 2 N/A 1 3 8
df2
A B F C D E
0 ... | <p>You can try <code>df.insert</code> + <code>df.pop</code> after getting location of B by <code>get_loc</code></p>
<pre><code>df.insert(df.columns.get_loc("B")+1,"F",df.pop("F"))
print(df)
</code></pre>
<hr>
<pre><code> A B F C D E
0 7.0 1 6.0 NaN 8 1.0
1 8.0 2 8.0 5.0 8 5.0
2 9.0 3 5.... | python|pandas|dataframe | 6 |
370,519 | 62,333,297 | Find index location of first and last occurrence of a value per day in a Pandas DataFrame with a DateTime index | <p>I'm trying to find the first and last occurrence of a value for each day in a column.</p>
<p>I have a dataframe that looks like this:</p>
<pre><code> a b c
2019-04-01 19:47:00 False False True
2019-04-01 19:48:00 False False True
2019-04-01 19:49:00 True ... | <pre><code>df['d'] = pd.to_datetime(df.index).strftime(date_format='%Y%m%d')
df = df.reset_index()
df.columns = ['date','a','b','c','d']
df[(sum([df['a'],df['b'],df['c']])>0)].groupby('d').agg(first=('date','first'),
last=('date','last'))
</code></pre>
<p>Out... | python|pandas | 0 |
370,520 | 62,067,398 | pandas dataframe - does filtering / selecting cols by String preserve order? | <p>I have a use case where I have say 10 cols out of which 5 start with the string 'Region'. I need to get a resulting dataframe which only contains those cols (starting with string 'Region'). Not only that, I need to make sure the order is preserved (e.g. if in original df, the col order is <code>'Region 1', 'Region 2... | <p>Two steps first use <code>filter</code></p>
<pre><code>s=df.filter(like='Region')
</code></pre> | python|pandas|string|dataframe|contains | 2 |
370,521 | 62,103,487 | Vectorize code in function where loops use range in Python/NumPy | <p>I have a function which is called many times in other functions. To improve computation I am trying to vectorize the code though I did not manage to do so in this particular case in which there are complex ranges involved. Does any of you see how it can be done in this specific case?</p>
<pre><code>def growdh_no_bl... | <pre><code>from numba import jit
sig = np.random.randn(44100)
import numpy as np
vectorized = jit(growdh_no_bloom)
</code></pre>
<p>Or simply put </p>
<pre><code>import numba
import random
@numba.njit()
def growdh_no_bloom:
for i in range(): #your for loop with range
</code></pre>
<blockquote>
<p>Numba is an... | python|numpy|for-loop|vectorization|array-broadcasting | 3 |
370,522 | 62,227,841 | Latitude and Longitude data in dataset while training the model | <p>I am using California housing data, which has latitude and longitude. Is it good practice to remove them (latitude & longitude)before I continue to train my model?</p> | <p>If you are just using raw lat/long information, then yes, you should remove them. That's because the values of lat/long are not meaningful in and of themselves, conditional on your model not having any "understanding" of what a change in lat/long means. For instance, what would a change in 1 degree in latitude mean ... | python|database|pandas|data-science|feature-engineering | 0 |
370,523 | 62,344,514 | In using Keras Tuner with Tensorflow 2 I am getting an error : division by zero | <p>I am experimenting with kerastuner.</p>
<p>Here is my code with a reproducible example:</p>
<pre><code>import kerastuner as kt
from kerastuner.tuners.bayesian import BayesianOptimization
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.boston_housing.load_data(
path="boston_housing.npz", test_split=0... | <p>The possible reason (due to the low readability of your code pasted above) could be using different datasets with saved models. I suggest you add <code>overwrite=True</code> in the <code>BayesianOptimization</code> construction code block. Let me know if it helps.</p> | python-3.x|tensorflow2.0|keras-2|keras-tuner | 1 |
370,524 | 62,244,779 | Python - Filter local extrema based on relative height | <p>Using <a href="https://stackoverflow.com/a/48024165/13490000">fuglede's answer</a>, it's easy to find the local extrema of a DataFrame column :</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Generate a noisy AR(1) sample
np.random.seed(0)
rs = np.random.randn(200)
xs = [0]
... | <p>I think you have missed the excellent answer from Foad reported here <a href="https://stackoverflow.com/questions/48023982/pandas-finding-local-max-and-min">Pandas finding local max and min</a></p>
<p>Instead of calculating max and min by a shift of 1, you can set a window (number of neighbors) and find the local m... | python|pandas|numpy|dataframe | 2 |
370,525 | 62,435,132 | How to append dataframe with selected columns having higher feature score | <p>Hi I am new to python let me know if the question is not clear.
Here is my dataframe:</p>
<pre><code>df = pd.DataFrame(df_test)
</code></pre>
<blockquote>
<pre><code> age bmi children charges
0 19 27.900 0 16884.92400
1 18 33.770 1 1725.55230
2 28 33.000 ... | <p>So first you want to find out which features have the largest values, then find the Featurename of the columns you do not want to see.</p>
<pre><code>colToDrop = feature.iloc[~feature['Score'].nlargest(2)]['Feature'].values
</code></pre>
<p>Next we just filter the original df and remove those columns from the colu... | python|pandas|dataframe|feature-selection | 0 |
370,526 | 62,158,568 | Merge dataframe on python | <p>I'm working with dataframes on Python, I'm having trouble joining two dataframes.
A dataframe is related to information from countries around the world.
Another dataframe is related to the detailed information of one of the countries of the world of the previous dataframe (i.e. I'm going to add information on the re... | <p>Make sure you have one column that's identical in both CSV files. I would add a column to the CSV with data of one country and enter the name of that country in each cell. Let's call the header of that column "country_name". Then do this:</p>
<pre><code>countries = pd.read_csv(filepath)
one_country = pd.read_csv(fi... | python|pandas|csv | 0 |
370,527 | 62,117,257 | Is there a list about the supported ML-Algorithms in TensorFlow? | <p>I am writing my bachelor thesis on "Machine Learning in Java" and compare frameworks and libraries. Currently I am collecting information about the different machine learning algorithms supported by the framework. I write them down in Excel, and use this data to evaluate the individual frameworks. Now to my problem:... | <p>The list of tensorflow optimizers can be found here:
<a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/optimizers</a></p> | algorithm|tensorflow|machine-learning|deep-learning | -1 |
370,528 | 62,266,185 | Process y_pred and y_true chunk wise in custom loss function in Tensorflow | <p>In my Tensorflow model y_pred contains probabilities from 0 to 1 and y_true contains labels of 0 and 1. </p>
<p>In my custom loss function I'd like to use the information of 4 (or n) consecutive pairs of y_true and y_pred.</p>
<p>In numpy I could do something like this</p>
<pre><code>y_true=np.array([1,1,1,1,0,0,... | <p>Taking care of when the <code>len(y_true) % 4 != 0</code>:</p>
<pre><code>@tf.function
def custom_loss_tf(y_true, y_pred):
length = tf.shape(y_true)[0]
end_i = length % 4
start_y_true, end_y_true = y_true[:length-end_i], y_true[length-end_i:]
start_y_pred, end_y_pred = y_pred[:length-end_i], y_pred[length-e... | python|tensorflow | 1 |
370,529 | 62,407,269 | How do I flatten multi level pandas DF? | <p>thanks for taking the time to read my question!</p>
<p>When I get some stock data from an API i get them back in a pandas Dataframe. This works fine for me to process when I request 1 symbol, but when I request more then 1 symbol i get lost :) :</p>
<p><a href="https://i.stack.imgur.com/iMrRG.png" rel="nofollow no... | <p>you can access to a specific level of dataframe columns and replace it</p>
<pre><code>df.columns = df.columns.get_level_values(0)
</code></pre> | python|pandas|multiple-columns | 0 |
370,530 | 62,104,804 | Discrepancy between keras CosineSimilarity metrics and cosine similarity computed between target and predicted vector | <p>I have trained a sequential model in keras, with sparse vectors as inputs (<code>padded_inputs_multil</code> for training and <code>padded_inputs_tr</code> for testing) and dense vectors as output (<code>target_multil_array</code> for training and <code>target_tr_r_array</code> for testing):</p>
<pre><code>model_mu... | <p>According to the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/cosine_similarity" rel="nofollow noreferrer">cosine_similarity documentation</a>, the default <code>axis</code> value is <code>axis=-1</code></p>
<p>and as answered <a href="https://stackoverflow.com/questions/47435526/what-is-the-m... | python|tensorflow|keras|recurrent-neural-network|cosine-similarity | 0 |
370,531 | 62,360,586 | Uncaught (in promise) Error: Number of splits must evenly divide the axis | <h1>Summary</h1>
<ol>
<li>Context</li>
<li>The problem</li>
<li>What did I try to fix this bug?</li>
<li>How to reproduce this bug (+ required data)?</li>
<li>My questions</li>
<li>Sources</li>
</ol>
<hr>
<h1>Context</h1>
<p>I would want to generate a new sequence of notes of a MIDI file thanks to MusicRNN chord_pi... | <p>I got same error when I was trying to quantize my note sequence which was already in quantized format. It is worthy to check your note sequence format.</p> | javascript|tensorflow|midi|tensorflow.js|magenta | 1 |
370,532 | 62,123,889 | FinViz - Stock scraping giving error --AMZN not found 'NoneType' object has no attribute 'find_next' | <p>I am new to BeautifulSoup package.
I am playing with a code that I got from some website and I got stuck with the above error. Please help.</p>
<pre><code>import pandas as pd
import re
from bs4 import BeautifulSoup as bs
import requests
def get_fundamental_data(df):
for symbol in df.index:
try:
... | <p>I was able to fix my own code based on this thread.</p>
<p><a href="https://stackoverflow.com/questions/44093182/beautifulsoup-scraping-error-attributeerror-nonetype-object-has-no-attribute">BeautifulSoup Scraping ERROR: AttributeError: 'NoneType' object has no attribute</a></p>
<p>My code after fix:</p>
... | pandas|beautifulsoup | 1 |
370,533 | 62,130,393 | GradientTape not computing gradient | <p>I understand that so long as i am defining a computation in <code>tf.GradientTape()</code> context, the gradient tape would compute the gradient w.r.t all the variables that the output of the computation depends on. However, i think i am not quite grasping the subtelties of the gradient as the following code does no... | <p>The <code>GradientTape</code> object <code>g</code> goes out of scope after the <code>with</code> statement ends.</p>
<p>In other words, try printing the gradient inside the <code>with</code> statement.</p>
<p>Here's what works for me:</p>
<pre><code>def get_gradients(inputs, target, model):
with tf.GradientT... | tensorflow|deep-learning|tensorflow2.0|gradienttape | 0 |
370,534 | 62,403,385 | How to compare two columns in a dataframe with a function and for loop? | <p>I have two columns floors and floor total</p>
<pre><code>df = pd.DataFrame({"floor": [1,2,30], "floors_total": [1, 50, 30]})
</code></pre>
<p>I want to write a function such as if in a row both values in floors total and floor are equal then return "last floor" and then if floor = 1 then return "first floor" and i... | <p>You can avoid the (slow) iteration over the dataframe with <code>np.where</code>:</p>
<pre><code>df['floor_position'] = np.where(df['floor'] == df['floors_total'],
'last floor',
np.where(df['floor'] == 1, 'first floor',
'other'))
</code></pre> | python|pandas|dataframe | 1 |
370,535 | 62,379,369 | How can I split a dataframe into multiple columns when my column header has \ in the name? | <p>I have a dataframe called ratings. It is a single column, named "tconst\taverageRating\tnumVotes", although it needs to be split into 3, separated by "\". </p>
<p>I understand that this statement can be used: <code>ratings[['tconst','taverageRating','tnumVotes']] = ratings.???.str.split("\",expand=True,)</code></p>... | <p>Are you sure you are reading the data in correctly?
Looking at the header names, it looks likely that your data is actually <code>\t</code> i.e.<code>tab</code> separated (so, <code>\t</code> and <code>numVotes</code> make sense separately). In that case you should read your data like this:</p>
<pre><code>pd.read_... | python|pandas | 2 |
370,536 | 62,329,369 | Perform groupby calculation on column excluding certain conditions | <pre><code>I have this df:
data = {'A':[102, 102, 102, 102, 312, 312, 312],
'B':[1001,1001,1001,1001,1001,1001,1001],
'C':[3005,3005,3005,3005,3005,3005,3005],
'D':[2004,2004,2004,2004,2002,2002,2002],
'E':[1,3,5,999,1,5,999],
'F':[300,1,192,837,19,1,1037]}
df = pd.DataFrame ... | <p>You can subsection your frame and <code>transform</code> that particular section, and then reassign the results back:</p>
<pre><code># Get the sub group
>>> grp = df[df['E'].ne(999)]
# Not required: this shows the Intermediate state of the transformed percentage
>>> grp['F'].mul(100).div(grp.grou... | python|pandas|dataframe|pandas-groupby|percentage | 0 |
370,537 | 62,202,769 | Find out the index of a rolling function in a pandas df | <p>I have a pandas df with some values, and I am trying to find out the min value of a column or a rolling basis, as well as the indices of those rolling min values.</p>
<p>For example,</p>
<pre><code>df["low"].rolling(200).min()
</code></pre>
<p>creates a series of the min "low" in a rolling 200 period.</p>
<p>Can... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.argmin.html" rel="nofollow noreferrer"><code>argmin</code></a>:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame({'low': np.random.randint(0,100,20)})
window_size = 4
df['min'] = df['low'].rolling(... | python|pandas | 2 |
370,538 | 62,429,207 | Renaming Columns in Pandas using for loop | <p>I am working on a python program which connects to salesforce and downloads the data in the form of a csv file. Salesforce doesn't allow aliasing the column. So I am using a config file to alias the column name. I need to replace only few column names not all. I tried using for loop in the code, it works if there is... | <p>Thank you edkloczko, I found the answer, I just changed the code to </p>
<pre><code>if st_src_val =="" or st_dst_val=="":
print("No columns to Rename in Stories")
sf_df.to_csv(local_dir+"\PF_Stories.csv", index=False, encoding='utf8')
else:
st_src=list(cfg['Column_Alias']['Stories_Src_Col'].split(','))
... | python|pandas | 0 |
370,539 | 62,336,406 | How to efficiently update the column names in a pandas dataframe? | <p>I would like to refactor the following code:</p>
<pre><code>labels = list(df.columns)
labels[0] = labels[0].replace(' ', '_')
labels[1] = labels[1].replace(' ', '_')
labels[2] = labels[2].replace(' ', '_')
labels[3] = labels[3].replace(' ', '_')
labels[5] = labels[5].replace(' ', '_')
labels[6] = labels[6].replace(... | <h1>Ways to fix the column names</h1>
<ul>
<li>For making the same change to all column name</li>
</ul>
<h2>Use a <code>list comprehension</code></h2>
<pre class="lang-py prettyprint-override"><code>df.columns = [col.replce(' ', '_') for col in df.columns]
</code></pre>
<h2>Use <a href="https://pandas.pydata.org/pa... | python|pandas | 1 |
370,540 | 62,313,026 | Updating dataframe updates entire column instead of the row | <p>I'm importing a csv as a dataframe and then I'm updating a column in the dataframe and exporting it to a new csv file. However, the first update statement appears to be updating all rows for the entire column (instead of just for that row). I'm using <code>df.at</code> with the index as I iterate through the datafra... | <p><code>type = str(df['Type'].values[0])</code> doesn't this mean type is unchanged throughout your loop? Therefore, all <code>A</code> and <code>B</code> columns are updated to the same value. I believe you want</p>
<pre><code>type = str(row['Type'])
</code></pre>
<p>On the other hand, you can make do without loopi... | python|pandas | 1 |
370,541 | 62,450,604 | A function to calculate velocity in pandas dataframe | <p>I was wondering if there was some function/library that can calculate velocity in a pandas dataframe. I have the following dataframe:</p>
<pre><code>Time bar_head_x bar_head_y bar_head_z
0.00 -203.3502 1554.3486 1102.8210
0.01 -203.4280 1554.3492 1103.0592
0.02 -203.4954 1554.3234 1103.279... | <p>df.diff() gives you the next minus the current row.</p>
<p>Since your <code>bar_head...</code> columns indicate position, the differences generated by df.diff can be intepreted as the vectors pointing from current to next positions. np.linalg.norm of these vectors gives you the length of the vectors, i.e. distance ... | python|pandas|acceleration | 2 |
370,542 | 62,460,171 | Pandas between_time equivalent for Dask DataFrame | <p>I have a Dask dataframe created with <code>dd.read_csv("./*/file.csv")</code> where the <code>*</code> glob is a folder for each date. In the concatenated dataframe I want to filter out subsets of time like how I would with a <code>pd.between_time("09:30", "16:00")</code>, say.</p>
<p>Because Dask's internal repre... | <p>Filtering in Dask works just like pandas with a few convenience functions removed.</p>
<p>For example if you had the following data:</p>
<pre><code>time,A,B
6/18/2020 09:00,29,0.330799201
6/18/2020 10:15,30,0.518081116
6/18/2020 18:25,31,0.790506469
</code></pre>
<p>The following code:</p>
<pre class="lang-py pr... | python|pandas|dask | 3 |
370,543 | 62,250,924 | Remove prefix from all cell values of dataframe | <p>I have a pandas data frame, which looks like the following:</p>
<pre><code> col1 col2 col3 ...
field1:index1:value1 field2:index2:value2 field3:index3:value3 ...
field1:index4:value4 field2:index5:value5 field3:index5:value6 ...
</co... | <p>Given</p>
<pre><code>>>> df
col1 col2 col3
0 1:index1:value1 2:index2:value2 3:index3:value3
1 1:index4:value4 2:index5:value5 3:index5:value6
</code></pre>
<p>you can use</p>
<pre><code>>>> df.apply(lambda s: ... | python|python-3.x|regex|pandas | 0 |
370,544 | 62,250,184 | Conv3D size doesn’t make sense with NIFTI data? | <p>So I am writing custom dataset for medical images, with .nii (NIFTI1 format), but there is a confusion.</p>
<p>My dataloader returns the shape <code>torch.Size (1,1,256,256,51)</code> . But NIFTI volumes use anatomical axes, different coordinate system, so it doesn’t make any sense to permute the axes, which I norm... | <p>In pytorch 3d convolution layer naming of the 3 dimensions you do convolution on is not really important (e.g. this layer doesn't really have a special treatment for depth compared to height). All difference is coming from kernel_size argument (and also padding if you use that). If you permute the dimensions and cor... | pytorch|conv-neural-network|medical|nifti|niftynet | 1 |
370,545 | 62,284,354 | Pytorch BatchNorm2d RuntimeError: running_mean should contain 64 elements not 0 | <p>I'm using Octave Convolutions and have set up a BatchNorm2d adaptation that for some reasen is giving me</p>
<p><code>RuntimeError: running_mean should contain 64 elements not 0</code> </p>
<p>I've set up some debugging prints to check what was wrong with my Tensors' dimensions, but was unable to find it.
Here is ... | <p>Solved. It was a typo on the call for the low frequency BN.</p>
<pre><code> hf = self.bnh(hf) if type(hf) == torch.Tensor else hf
lf = self.bnh(lf) if type(lf) == torch.Tensor else lf
</code></pre>
<p>Should have been</p>
<pre><code> hf = self.bnh(hf) if type(hf) == torch.Tensor else hf
lf = self.bn... | machine-learning|pytorch|batch-normalization | 0 |
370,546 | 62,420,661 | Error in python3 np.exp(matrix1 * matrix2) - "loop of ufunc does not support argument 0 of type float which has no callable exp method" | <p>I have a function where I need to perform <code>np.exp(matrix1 @ matrix2)</code>, but I receive the error message: <code>loop of ufunc does not support argument 0 of type float which has no callable exp method</code></p>
<ul>
<li><code>matrix1</code> is a 210 by 4 matrix of <code>float</code> values</li>
<li><code>... | <p><code>exp</code> works on an array of floats:</p>
<pre><code>In [186]: arr = np.array([1.,2.,3.])
In [187]: np.exp(arr)
Out[187]: array([ 2.71828183,... | python|numpy|matrix | 0 |
370,547 | 62,308,415 | Building Tensorflow 1.5 | <p>I have an old Macbook Pro 3,1 running ubuntu 20.04 and python 3.8. The mac CPU doesn't have support for avx (Advanced Vector Extensions) which is needed for tensorflow 2.2 so whilst tensorflow installs, it fails to run with the error:</p>
<blockquote>
<p>illegal instruction (core dumped)</p>
</blockquote>
<p>I'v... | <p>Usually there are instructions for building in the repository's README.md. Isn't there such for TensorFlow? It would be odd.</p> | python|tensorflow|ubuntu | 0 |
370,548 | 51,463,911 | handling real time data in python , rolling window | <p>I want to create a function that will read a series of time values from a file (with gaps in the sampling rate,thats the problem) and would read me exactly 200 days and allow me to move through the entire data length,say 10000 day,sort of a rolling window. </p>
<p>I am not sure how to code it. Can I add a statement... | <pre class="lang-js prettyprint-override"><code>import numpy as np
import pandas as pd
import datetime as dt
# load data in days and y arrays
# ... or generate them:
N = 1000 # number of days
day_min = dt.datetime.strptime('2000-01-01', '%Y-%m-%d')
day_max = 2000
days = np.sort(np.unique(np.random.uniform(low=0, hig... | python|numpy|time | 1 |
370,549 | 51,160,777 | MUL operation in merged dataframes | <p>data 1</p>
<pre><code>import pandas as pd
#data 01
df_products = pd.DataFrame([{'Product ID' : 4109,'Price' : 5.0,'Product' : 'Sushi Roll'},
{'Product ID' : 1412,'Price' : 0.5,'Product' : 'Egg'},
{'Product ID' : 8931,'Price' : 1.5,'Product' : 'Bagel'}])
df_products = df_product... | <p>If I understand you correctly, to define a new column in a dataframe use:</p>
<pre><code>df_overall['Total'] = df_overall['Price'] * df_overall['Quantity']
print(df_overall)
</code></pre>
<p>Output:</p>
<pre><code> Price Product Customer Quantity Total
Product ID ... | python|python-3.x|pandas | 1 |
370,550 | 51,170,169 | Clean-up database connection with SQLAlchemy in Pandas | <p>With Pandas, I can very easily read data from a database into a dataframe:</p>
<pre><code>from sqlalchemy import create_engine
import pandas
query = 'SELECT * FROM Table_Name;'
engine = create_engine('...')
df = pandas.read_sql_query(query, engine)
print(df.head())
</code></pre>
<p>I would like to make sure th... | <h3>Backgrounds:</h3>
<p>When using <code>sqlalchemy</code> with pandas <code>read_sql_query(query, con)</code> method, it will create a <code>SQLDatabase</code> object with an attribute <code>connectable</code> to <a href="https://github.com/pandas-dev/pandas/blob/v0.23.3/pandas/io/sql.py#L954" rel="noreferrer"><code... | python|pandas|sqlalchemy | 33 |
370,551 | 51,370,986 | When creating a new data frame, how do I set the key labels to the numbers in a linespace np.array? | <p>I am hoping to make a new data frame using several 1-d numpy arrays, one of which I would like to use as the key labels. I would like each existing array to represent one row. Do you guys have any suggestions?</p>
<p>Thanks!</p> | <p>You can use <code>np.row_stack</code> before feeding to <code>pd.DataFrame</code>:</p>
<pre><code>import pandas as pd
import numpy as np
A = np.array([1, 2, 3, 4])
B = np.array([5, 6, 7, 8])
C = np.array([9, 10, 11, 12])
K = np.linspace(0, 1, 3)
df = pd.DataFrame(np.row_stack((A, B, C)), index=K)
</code></pre>
... | python|python-3.x|pandas|numpy | 0 |
370,552 | 51,408,351 | Pandas: Iterate through columns and starting at one column | <p>Does anyone know how to incorporate a forloop for columns but start at any column? (The third one for this scenario)</p>
<p>Lets say this is the dataframe:</p>
<pre><code>spice smice skice bike dike mike
1 23 35 34 34 56
135 34 23 21 56 34
231 12 67 21 62 75
</code></pre>... | <p>Since <code>df.columns</code> provides you the list of columns, you can do below and iterate from 3rd column name.</p>
<pre><code>for col in df.columns[2:]:
#print(df[col].unique())
</code></pre> | python|pandas|dataframe | 11 |
370,553 | 51,331,533 | Error with Pandas Rank Across Columns Using a Dict | <p>I used to use a piece of code to rank across columns within each category using a dict. But with the new Pandas/Python3, I am getting the following error:</p>
<p>ValueError: Shape of passed values is (100, 4), indices imply (100, 100)</p>
<p>Any suggestions or assistance is appreciated. </p>
<p>Below is the code:... | <p>I ran that code on my machine and it worked fine, although I'm using Anaconda 3.6.4 and Pandas 0.22.0. Maybe its a version issue. Is this the correct output?</p>
<p>the output:</p>
<pre><code>d = dict()
d ={'A': 'Health Care', 'AA': 'Materials', 'B': 'Health Care', 'BB': 'Materials'}
data = pd.DataFrame(np.random.... | pandas|dictionary|rank | 0 |
370,554 | 51,272,642 | Python: ContextualVersionConflict: pandas 0.22.0; Requirement.parse('pandas<0.22,>=0.19'), {'scikit-survival'}) | <p>I have this issue: </p>
<blockquote>
<p>ContextualVersionConflict: (pandas 0.22.0 (...),
Requirement.parse('pandas<0.22,>=0.19'), {'scikit-survival'})</p>
</blockquote>
<p>I have even tried to uninstall pandas and install scikit-survival + dependencies via anaconda. But it still does not work....</p>
<p>An... | <p>Restarting jupyter notebook fixed it. But I am unsure why this would fix it?</p> | python|pandas|scikit-learn | 5 |
370,555 | 51,275,497 | print row from a data in numpy structured array | <p>i have the next structured array in numpy:</p>
<pre><code>>>> matriz
rec.array([('b8:27:eb:07:65:ad', '0.130s', 255),
('b8:27:eb:07:65:ad', '0.120s', 215),
('b8:27:eb:07:65:ad', '0.130s', 168) ],
dtype=[('col1', '<U17'), ('col2', '<U17'), ('col3', '<i4'),
('col4','<U... | <p>You can do the following:</p>
<pre><code>matrix = np.array([('b8:27:eb:07:65:ad', '0.130s', 255),
('b8:27:eb:07:65:ad', '0.120s', 215),
('b8:27:eb:07:65:ad', '0.130s', 168)],
dtype=[('col1', '<U17'),
('col2', '<U17'),
... | python|arrays|python-3.x|numpy | 1 |
370,556 | 51,408,022 | n-dimensional array reduction to 2-d array with additional columns | <p>I have an n-dim array in numpy and I have n column vectors.
I need to convert the n-dim array to a 2-D numpy array having </p>
<p><code>rows = size of n-dim array</code></p>
<p><code>cols = n + 1</code></p>
<p>to simplify with an example,</p>
<pre><code>a = np.random.randint(50, size=(2,2))
r = np.array([0.2,1.9... | <p>Here's a solution that uses <code>np.meshgrid</code> to create the column combinations and stacks it together using <code>np.vstack</code>:</p>
<pre><code>In [101]: a = np.array([[45, 18], [ 4, 24]])
In [102]: col_vecs = [np.array([4, 5]), np.array([0.2, 1.9])]
In [103]: np.vstack([np.ravel(a)] + [c.ravel() for c... | python|numpy | 1 |
370,557 | 51,181,171 | Plot Data from CSV and group values in colum | <p>I am pretty new in python and try to understand how to do the following:</p>
<p>I am trying to plot data from a csv file where I have values for A values for B and values for C. How can I group it and plot it based on the Valuegroup and as values using the colum values? </p>
<pre><code>import pandas as pd
import m... | <p>If you want to take a mean of <code>Value</code> for each <code>Valuegroup</code> and show them with line chart, use </p>
<pre><code>csv_loader.groupby('Valuegroup')['Value'].mean().plot()
</code></pre>
<p>There are various chart types available, please refer to <a href="https://pandas.pydata.org/pandas-docs/st... | python|pandas|csv|dataframe | 3 |
370,558 | 51,432,705 | Reading multiple feature vectors from one TFRecord example in Tensorflow | <p>I know how to store one feature per example inside a tfrecord file and then read it by using something like this:</p>
<pre><code>import tensorflow as tf
import numpy as np
import os
# This is used to parse an example from tfrecords
def parse(serialized_example):
features = tf.parse_single_example(
serialize... | <p>Firstly, note that np.ndarray.tobytes() flattens out multi-dimensional arrays into a list, i.e.</p>
<pre><code>feat = np.random.randn(N, 2)
reshaped = np.reshape(feat, (N*2,))
feat.tobytes() == reshaped.tobytes() ## True
</code></pre>
<p>So, if you have a N*2 array that's saved as bytes in TFRecord format, you h... | tensorflow|tfrecord | 1 |
370,559 | 51,544,271 | Error when checking target: expected lambda_1 to have 1 dimensions, but got array with shape (60000, 10) | <p>i am trying to create a invertible networks, when it goes backward , the weight matrix is the transpose of the weight matrix in forward process. so i define a custom layer</p>
<pre><code> class Backwardlayer(Dense):
def __init__(self,output_dim,b_layer,activation=None,use_bias=True,kernel_initializer='glo... | <p>The error is self explaining: "tensors don't have kernels". </p>
<blockquote>
<p>Layers have kernels.</p>
</blockquote>
<p>This is not true: </p>
<pre><code>encoder_layer_1 = layer_1(input_img)
encoder_layer_2 = layer_2(encoder_layer_1)
encoder_layer_3 = layer_3(encoder_layer_2)
encoder_layer_4 = layer_4(enco... | python|tensorflow|keras|tensor | 1 |
370,560 | 51,424,189 | Dynamic number of epochs with a tensorflow keras model | <p>I want to have a neural net that trains until a certain level of accuracy has been reached. Is there a built in function to use instead of running each epoch individually until the accuracy has been reached?</p>
<pre><code>model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.... | <p>No, there isn't any built in function to do this. However, you can easily define a custom callback that stops training once the training accuracy reaches a certain threshold:</p>
<pre><code>import keras
class AccuracyStopping(keras.callbacks.Callback):
def __init__(self, acc_threshold):
super(Accuracy... | python|tensorflow|keras | 3 |
370,561 | 51,550,696 | Round only some columns in pandas | <p>I have a pandas dataframe and I would like to round only some of its columns (not all of them, not one of them). They will all be rounded to the same number of decimals.</p>
<p>The procedure I use at the moment looks like this:</p>
<pre><code># example dataframe
df1 = pd.DataFrame({'a':[0.1111,0.2222],'b':[0.3333... | <p>You can customize for each column using a dict like</p>
<pre><code>In [658]: df1.round({'a': 2, 'c': 2})
Out[658]:
a b c
0 0.11 0.3333 0.56
1 0.22 0.4444 0.67
</code></pre>
<hr>
<p><strong>Or</strong>, You could do</p>
<pre><code>In [649]: cols = ['a', 'c']
In [650]: df1[cols] = df1[cols].... | python|pandas | 11 |
370,562 | 51,506,845 | Function not recognizing libraries | <p>I have the simplest of questions, but this has never happened to me and can't find an answer.
I have the following piece of code:</p>
<pre><code>import datalab as dl
import pandas as pd
</code></pre>
<p>Where datalab is a script I wrote, and between other things, it contains this very simple function:</p>
<pre><c... | <p>Each Python module has its own global namespace. So if you want to use the <code>pd</code> name in the <code>datalab</code> module, you need to import it there as well, usually at the top of the script, like this:</p>
<pre><code>import pandas as pd
…
def fecha(vartime, df=df):
…
</code></pre> | python|pandas|function | 3 |
370,563 | 51,509,485 | Killed worker when aggregating Dask data first over ID then on minutes | <p>My goal is to aggregate NYC Citibike data first over <code>station_id</code> then on minutes of <code>starttime</code> in Dask. </p>
<p>The head of the Dask DataFrame looks as follows,</p>
<pre><code>df_start.head()
</code></pre>
<p>displays,</p>
<pre><code> starttime start_station_name
start_station_id ... | <p>The answer ends up being,</p>
<pre><code>def min_counter(b):
return b.groupby(pd.Grouper(key='starttime', freq='5min')).count()
counter_per_station = df_start.groupby('start_station_id').apply(min_counter)
</code></pre>
<p>hope this helps people facing the same issue.</p> | python-3.x|pandas|pandas-groupby|dask | 2 |
370,564 | 51,432,652 | Extending a Keras Pre-trained model to images with additional channels or bands | <p>I was just hoping to clarify some information about a previous post that discusses how a Keras pre-trained model like VGG or InceptionV3 can be extended to different sized images. My problem is that I have some satellite images that come in 8-bands. So an image might be <code>650x650x8</code> instead of the usual RB... | <p>From the Keras <a href="https://keras.io/applications/#vgg16" rel="nofollow noreferrer">docs</a>:</p>
<blockquote>
<p>input_shape: optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'chann... | python|tensorflow|keras|keras-layer | 1 |
370,565 | 51,164,876 | Speed Up Keras LSTM | <p>I am trying to train LSTM using Keras, but the training is extremely slow (I have gpu Nvidia Titan X). Does someone know how can I speed up my training speed ?</p>
<p>Thank you very much in advance</p> | <p>replace standard <code>LSTM</code> to <code>CuDNNLSTM</code>. You can import it from, </p>
<pre><code>from keras.layers import CuDNNLSTM
</code></pre> | python-3.x|tensorflow|keras | 7 |
370,566 | 51,381,923 | tf.confusion_matrix with tf.assign_add | <p>I am trying to use <code>tf.confusion_matrix</code> with <code>tf.assign_add</code> in order to update a confusion matrix every global step.</p>
<pre><code>y_true = tf.placeholder(tf.int16,shape=[None,])
y_pred = tf.placeholder(tf.int16,shape=[None,])
cm = tf.confusion_matrix(labels=y_true,predictions=y_pred)
cm_in... | <p>You get </p>
<blockquote>
<p>AttributeError: 'Tensor' object has no attribute 'assign_add'</p>
</blockquote>
<p>because <code>assign_add</code> only makes sense for variables (see <a href="https://stackoverflow.com/a/51167200/7443104">my other answer</a>)</p>
<p>As you know the number of classes you should crea... | tensorflow | 1 |
370,567 | 51,468,346 | Python - Pandas - Filter out columns based on row average | <p>I have a DataFrame with several columns and a date index:</p>
<pre><code>TIME A B C D E
---------------------------------------------------------------------
2015-03-01 0.74 -0.70 2.62 2.64 3.43
2015-03-02 0.15 -1.2... | <p>I think need:</p>
<pre><code>#if necessary create DatetimeIndex
df = df.set_index('TIME')
#get mean per rows
s = df.mean(axis=1)
#create boolean mask by +/- 100 chained by OR (|)
m = (df.gt(s + 100, axis=0) ) | (df.lt(s - 100, axis=0))
#remove column by condition - inverted mask with any for check at least one Tr... | python|pandas|dataframe | 1 |
370,568 | 51,555,288 | I want to use python "loop" for drop list | <pre><code>import pandas as pd
import os
import xlrd
os.chdir('D:\python')
file_name='D:\python\\test.xlsx'
sheet='test01'
df=pd.DataFrame(pd.read_excel(file_name,sheet))
df.drop(list(df.filter(regex = 'Abc')), axis = 1, inplace = True)
df.drop(list(df.filter(regex = 'def')), axis = 1, inplace = True... | <p>Try like this :</p>
<pre><code>df=pd.DataFrame(pd.read_excel(file_name,sheet))
l = list(map(chr, range(97, ord('s'))))
li = [''.join(l[x:x+3]) for x in range(0, len(l), 3)]
for i in li:
df.drop(list(df.filter(regex = i)), axis = 1, inplace = True)
</code></pre> | python|pandas|for-loop|while-loop | 0 |
370,569 | 51,438,894 | Machine learning random forest classifier | <pre><code>data=pd.DataFrame({'gender':['m','f','m'],'icds':[['i10'],['i20','i30'],['i40']],'med':[[1,2,4,5],[3,4,6],[5,6,7]]})
</code></pre>
<p>Which machine learning algorithm shall I use for this type of data? I think of the inconsistent length of arrays in the <code>med</code> column. Whenever I try to pass it in ... | <p>Yeah, you are right, the algorithm you should use is RF or logistic also should be good. The issue is with the inconsistent length of data in 'med' column. If its not necessary you can use the following functions to average/sum out the numerical data in med columns arrays:</p>
<pre><code>def sum_out(x):
return np.n... | python|pandas | 0 |
370,570 | 51,140,765 | Count Specific Values in Dataframe | <p>If I had a column in a dataframe, and that column contained two possible categorical variables, how do I count how many times each variable appeared? </p>
<p>So e.g, how do I count how many of the participants in the study were male or female?</p>
<p>I've tried value_counts, groupby, len etc, but seem to be gettin... | <p>Supposing that "gender" is the column of the dataframe,we can count the occurences of the categorical data using</p>
<pre><code>df['gender'].value_counts().to_dict()
</code></pre>
<p>it will give us the count of the two class of data in dictionary format</p>
<pre><code>{"male":4,"female":5}
</code></pre>
<p>if y... | python|python-3.x|pandas | 2 |
370,571 | 51,326,602 | Pandas: Group by, filter rows, get the mean | <p>In python I have a pandas data frame <code>df</code> like this:</p>
<pre><code> ID Geo Speed
123 False 40
123 True 90
123 True 80
123 False 50
123 True 10
456 False 10
456 True 90
456 False 40
456 True 80
</code></pre>
<p... | <p>Use <code>~</code> for inverting <code>False</code>s to <code>True</code>s for filtering by <code>False</code>s by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>print (df[~df["Geo"]])
ID Geo Sp... | python|pandas|filter|group-by|mean | 4 |
370,572 | 51,293,554 | Resize two axes at once h5py | <p>Is there a way to <code>resize</code> two axes by appending new data?. I was able to append new data to one axis using <code>resize</code> and <code>maxshape</code> following Docs in <a href="http://docs.h5py.org/en/latest/high/dataset.html#Dataset.maxshape" rel="nofollow noreferrer">h5py Docs</a>.
But what I am tr... | <p>Writing to a resizable <code>dataset</code> is just like writing to a numpy array - you have to specify the correct size of a slice - in all dimensions.</p>
<p>When expanding in 2 dimensions, it requires some care to fill in all the blocks correctly. Not only are you adding rows, but also columns:</p>
<pre><code>... | python|numpy|h5py | 0 |
370,573 | 51,127,344 | Tensor is not an element of this graph; deploying Keras model | <p>Im deploying a keras model and sending the test data to the model via a flask api. I have two files:</p>
<p>First: My Flask App:</p>
<pre><code># Let's startup the Flask application
app = Flask(__name__)
# Model reload from jSON:
print('Load model...')
json_file = open('models/model_temp.json', 'r')
loaded_model_... | <p>Flask uses multiple threads. The problem you are running into is because the tensorflow model is not loaded and used in the same thread. One workaround is to force tensorflow to use the gloabl default graph .</p>
<p>Add this after you load your model</p>
<pre><code>global graph
graph = tf.get_default_graph()
</co... | python|tensorflow|flask|keras | 36 |
370,574 | 51,218,047 | Could we sample pandas data frame based on aggregate criteria | <pre><code>a = df[df.contribution <= 0.1].sample(frac = 0.1)
</code></pre>
<p>I need to do something like this:
take any sample of rows but total contribution from rows should be less than 100</p>
<pre><code>a = df.sample(sum(df['contribution'])<100)
</code></pre> | <p>The thought being you would like the sample to contain more records than less.
Sadly using a loop.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1,35,(15,1)),columns = ['contribution'])
for i in reversed(range(len(df))):
if df['contribution'].sample(i).sum() < 100... | pandas|random | 0 |
370,575 | 51,307,978 | Installing Tensorflow GPU - Cannot find libcublas.so.9.0 even though its present and in path | <p>I run into the error </p>
<pre><code>ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory
</code></pre>
<p>even though the file exists and the <code>PATH</code> and <code>LD_LIBRARY_PATH</code> are set. I am using tensorflow-gpu 1.9.0</p>
<p>The file exists:
<a href="https://i.... | <p>It turned out to be a driver issue. I went back to Ubuntu 16.04, did a fresh install of Ubuntu and the Nvidia drivers and I was able to install Tensorflow_gpu without a problem.</p> | python-3.x|ubuntu|tensorflow | 1 |
370,576 | 51,266,042 | Upsampling (disaggregating) summed quarterly data to monthly data | <p>I am trying to upsample data from aggregated quarterly up to monthly, but the numbers that below code produces are not what I need. I would need these data points to be disaggregated into monthly numbers (that add back up to the immediately following quarter). So each new value would need to be about a third of the ... | <p>You can do this, but <code>method=cubic</code> is not working due to NaN's.</p>
<pre><code>df.resample('M').asfreq().interpolate()
</code></pre>
<p>Output:</p>
<pre><code> 0
2000-01 0.000000
2000-02 18319.282557
2000-03 36638.565113
2000-04 54957.847670
2000-05 36638.565113
2000-06 18... | python|pandas|data-analysis|resampling | 1 |
370,577 | 51,407,521 | Splitting train and test set with labels in sklearn? | <p>I have an augmented dataset in which I have a list <code>label</code> to group original data and their augmentations. Is there a method in <code>sklearn</code> like <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer"><code>train_test_spli... | <p>You can use <code>GroupKFold</code> to do this. Here's how you would do a single 66/33 split.</p>
<pre><code>from sklearn.model_selection import GroupKFold
gkf = GroupKFold(n_splits=3)
train, test = next(gkf.split(X, y, groups=label))
X_train = X[train]
y_train = y[train]
X_test = X[test]
y_test = y[test]
</code>... | python|python-3.x|numpy|scikit-learn | 2 |
370,578 | 51,123,198 | Strange behaviour of the loss function in keras model, with pretrained convolutional base | <p>I'm trying to create a model in Keras to make numerical predictions from the pictures. My model has <em>densenet121</em> convolutional base, with couple of additional layers on top. All layers except for the two last ones are set to <code>layer.trainable = False</code>. My loss is mean squared error, since it's a re... | <p>Looks like I found the solution. As I have suggested the problem is with BatchNormalization layers. They make tree things</p>
<ol>
<li>subtract mean and normalize by std</li>
<li>collect statistics on mean and std using running average</li>
<li>train two additional parameters (two per node).</li>
</ol>
<p>When one s... | python|tensorflow|keras|deep-learning|transfer-learning | 12 |
370,579 | 51,320,044 | Storing output multi 1 dimensional arrays as a data file | <pre><code>import numpy as np
import matplotlib.pyplot as plt
x = open(r'''C:\Users\Documents\ex.txt''')
[INPUT ex.txt file:
-1.642195902 0.751055263
0.496998351 -1.306558434
-0.490237525 -0.188855324
-1.357284374 0.282238191
-0.160982328 -1.115393803
1.167022948 0.564800286
-2.050084963 0... | <p>Try this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = open(r'''C:\Users\Documents\ex.txt''')
ls = x.readlines()
x1 = np.array([])
x2 = np.array([])
x_array = np.array([])
x3_array = np.array([])
for l in ls:
col = l.split()
x_array = np.append(x_array, [float(col[0]), float(... | python|numpy | 0 |
370,580 | 51,448,305 | Should samples from np.random.normal sum to zero? | <p>I am working on the motion model of a robot. In every time step, the robot's motion is measured, then I sample the normal distribution with the measurement as the mean and a small sigma value for covariance in order to simulate noise. This noisy motion is then added to the robot's previous state estimate.</p>
<p>Bu... | <p>The short answer to your question is no. Be careful not to conflate the sum of an array of independent random variables and the mean of those independent random variables.</p>
<p>Per the article that @Hongyu Wang referenced in his comment, let's verify the following:</p>
<p>"If X and Y are independent random varia... | python|numpy|statistics|robotics|normal-distribution | 1 |
370,581 | 51,352,582 | Sampling None-size tensor from distribution in tensorflow | <p>The following code:</p>
<pre><code>import tensorflow as tf
tfd = tf.contrib.distributions
mean = [0.0, 0.0]
scale = [1.0, 1.0]
dist = tfd.MultivariateNormalDiag(loc=mean, scale_diag=scale)
samp = dist.sample([None])
</code></pre>
<p>Gives the error:</p>
<pre><code>TypeError: Expected int32, got None of type '_M... | <p>You could do</p>
<pre><code>num_samples = tf.placeholder(dtype=tf.int32, shape=())
sampl = dist.sample(num_samples)
</code></pre>
<p>and then feed in the number of samples. Likewise, if you have a scalar tensor representing the number of samples, you can pass that in.</p> | tensorflow | 1 |
370,582 | 51,380,386 | Extract and sum totals for time period | <p>I have a dataset of rainfall, with rainfall values being associated with a time (minute) and date on which rainfall occurred, if no rainfall occurred, nothing is logged. As such some days with large storms may have 100 readings, while some days will have none or only one or two. Example below:</p>
<pre><code>D M ... | <p>You can use the following to generate your three dataframes/series</p>
<h3>Create a column with datetime dtype using <code>to_datetime</code></h3>
<pre><code>df['date'] = pd.to_datetime(df['Y'].astype(str)+'-'+df['M'].astype(str)+'-'+df['D'].astype(str)+' '+df['Hr'].astype(str)+':'+df['Min'].astype(str)+':00')
</c... | python|pandas|datetime | 2 |
370,583 | 51,117,963 | Would like to read in Two columns of dates but only get One | <p>I have a text.csv file with 6 columns. I want 2 columns read in as dates for later differences. However, I only get ONE column coming back as a <strong>datetime</strong>. Any ideas? </p>
<p>Also, I have several empty dates that return <strong>nan NOT 0(zeros)</strong> as in <strong>na_values = 0</strong>??</p>
<... | <p>There is problem some values in <code>Birth Date</code> are contains at least one not parseable datetime, so <code>read_csv</code> silently not parse column.</p>
<p>You can check this values by:</p>
<pre><code>dates = pd.to_datetime(df['Birth Date'], errors='coerce')
print (df.loc[dates.isnull(), 'Birth Date'])
<... | python|pandas | 1 |
370,584 | 51,301,354 | Rows to columns Python Pandas dataframe (pd.melt) | <p>I have a dataframe, df, containing transactions by card. One card can have multiple transactions and thus multiple rows. I want to create a new dataframe with one row per card. Problem is that the number of transactions per card can vary. I was under the assumption that the pd.melt could solve this.</p>
<p>datafram... | <p>Okay, you can use <code>cumcount</code> and <code>unstack</code>:</p>
<pre><code>df_out = df.set_index(['CardCode',df.groupby('CardCode').cumcount() + 1])\
.unstack()\
.sort_index(level=1, axis=1)
df_out.columns = [f'{i}_{j}' for i,j in df_out.columns]
df_out = df_out.reset_index()
df_out
<... | python|pandas | 0 |
370,585 | 51,437,654 | pandas work on jupyter but not recognized in cmd or anaconda prompt | <p>I want to run a script in .py with <code>cmd</code> or anaconda prompt but says pandas can't be recognized.</p>
<pre><code>'pandas' in sys.modules
False
</code></pre>
<p>the version of python is the correct where these libraries are installed. The correct path is somehow not in connection with the cmd and all the... | <p>The solution was to write the word <code>python</code> too.</p>
<pre><code>python hx.py
</code></pre>
<p>now it runs if typed in the anaconda prompt.</p>
<p>All nice.</p> | python|pandas|anaconda | 1 |
370,586 | 51,470,552 | Convert pandas Dataframe to numeric | <p>My dataframe appears to be non-numeric after some transformations (see previous post on dropping duplicates: <a href="https://stackoverflow.com/questions/51470071/drop-duplicates-pandas-dataframe">drop duplicates pandas dataframe</a>)</p>
<p>When I use it in a statsmodels regression I get this error:</p>
<p>ValueE... | <p>One issue with the original answer <a href="https://stackoverflow.com/questions/51470071/drop-duplicates-pandas-dataframe">in this post</a> is that the transformation converts the integers to objects. This happens after the transpose since now the same column stores integers as well as the index which is textual.</p... | python|pandas|numeric | 3 |
370,587 | 48,279,399 | Handle double quotes inside the field value pandas | <p>I have a row like below in a csv file</p>
<pre><code>"1"|"A "Great" Experience"|"T"
</code></pre>
<p>When I read this using below code</p>
<pre><code>pandas.read_csv(file2Name,sep = '|',keep_default_na=False,quoting=csv.QUOTE_ALL)
</code></pre>
<p>it gives the output as: <code>[1,A Great" Experience",T]</code></... | <p><code>pd.read_csv</code> function has parameter <code>quotechar</code>:</p>
<blockquote>
<p>quotechar : str (length 1), optional</p>
<p>The character used to denote the start and end of a quoted item. Quoted
items can include the delimiter and it will be ignored.</p>
</blockquote>
<p>You can change the de... | python|pandas | 2 |
370,588 | 48,027,801 | Cannot optimize using tf.reduce_sum(), but succeeded using tf.reduce_mean() | <pre><code>import tensorflow as tf
import numpy as np
#date generation
x_data = np.float32(np.random.rand(2, 100))
y_data = np.dot([0.1, 0.2], x_data) + 0.3
#linear model
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b
#minimize variance
loss = tf.red... | <p>The loss by summing across all the samples at once are more than the mean loss. </p>
<p>For example let's take that our desired y_data = [1.2, 3.2, 2.4] and predicted y = [1, 3, 3]</p>
<p>then by the following lines :</p>
<pre><code>tf.reduce_sum(tf.square(y - y_data))
</code></pre>
<p>Loss will turn out to be :... | python|tensorflow|machine-learning | 6 |
370,589 | 48,326,454 | Why tensorflow random_normal function gives different outputs with a fixed seed value | <p>I set fixed a seed value and run the session using following line of codes.</p>
<pre><code>with tf.Session() as sess:
matrix = tf.random_normal([2,2], mean=1, stddev=1, seed=1)
print(matrix.eval())
print(matrix.eval())
print(matrix.eval())
print(sess.run(matrix))
print(sess.run(matrix))
... | <p>In each run, your computational graph is evaluated anew, thereby generating new random numbers, but not resetting the seed.</p>
<p>I think running the entire Python file again should give the same output as before.</p> | python|tensorflow | 3 |
370,590 | 48,219,085 | create loop using values from an array | <p>I have an array D of variable length,</p>
<p>I want to create a loop that performs a sum based on the value of D corresponding to the number of times looped</p>
<p>i.e. the 5th run through the loop would use the 5th value in my array.</p>
<p>My code is:</p>
<pre><code>period = 63 # can be edited to an input() co... | <p><s>Right now, D is just a scalar. </p>
<p>I'd suggest reading <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.normal.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.normal.html</a> to learn about the parameters. </p>
<p>If y... | python|arrays|numpy|for-loop | -1 |
370,591 | 48,236,364 | Using Pandas shift with multi-index | <p>I have am trying to make a simple stock portfolio tracker. I start with $100k dollars and invest based on weights in two stocks. Each month, I want to sell the stock and then set the new starting dollars (shares bought in last period * current price) and reinvest in the two stocks again based on this months weights.... | <p>Think about organizing your data this way (I've left off 2017-03-01 because you don't show prices for that date and it makes the example more concise):</p>
<pre><code>Date AAPL Return GOOG Return AAPL Weight GOOG Weight
2017-01-01 1.4 1.083 0.6 0.4
2017-02-01 0.7... | python|python-2.7|pandas | 1 |
370,592 | 48,128,399 | Python pandas plotting Quarter values | <p>Receiving error: Axis must have <code>freq</code> set to convert to Periods
when trying to plot from a DataFrame with index values like 2006Q1</p>
<pre><code> df1 = SalesReport[['Time','Product1','Product2','Product3']]
df1['Time'] = pd.to_datetime(df1['Time'], format='%d/%m/%y')
df1 = df1.set_index('Time')
df1.... | <p>I don't know the reasons why it does not work using <code>plt.plot()</code> but you can try to plot with <code>pandas</code>'s <code>plot</code> function, which also uses matplotlib... I am using Python 3 and pandas 0.20</p>
<pre><code>df.plot()
</code></pre>
<p><a href="https://i.stack.imgur.com/TgxC0.png" rel="nof... | python|pandas|plot | 4 |
370,593 | 48,405,980 | how can I do 2d 3d multiplication | <p>I have two array one is 3d : </p>
<pre><code>np.array([[[1,2,3],[3,2,1]],
[[2,3,2],[1,2,5]]])
</code></pre>
<p>and one 2d array : </p>
<pre><code>np.array([[2,3],
[3,4]])
</code></pre>
<p>and I want to multiply these two to get </p>
<pre><code>np.array([[[2,4,6],[9,6,3]],
[[6,9,6],... | <p>Use <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasting</a>:</p>
<pre><code>In [129]: b[:,:,None] * a
Out[129]:
array([[[ 2, 4, 6],
[ 9, 6, 3]],
[[ 6, 9, 6],
[ 4, 8, 20]]])
</code></pre> | python|arrays|numpy | 3 |
370,594 | 48,222,860 | Tensorflow equivalent of numpy.fill() | <p>I cannot find the equivalent of <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.fill.html" rel="nofollow noreferrer">numpy's fill function</a> in Tensorflow. Tensorflow has a <a href="https://www.tensorflow.org/api_docs/python/tf/fill" rel="nofollow noreferrer">fill function</a>, b... | <p>You could first determine the shape of your tensor using <a href="https://www.tensorflow.org/api_docs/python/tf/shape" rel="nofollow noreferrer"><code>shape</code></a>, and then use the <code>constant</code> or <code>fill</code> methods.</p>
<pre><code>>>> mytf = tf.ones([2,3], tf.int32)
>>> mynew... | python|tensorflow | 1 |
370,595 | 48,377,376 | error arise when using queue runner in tensorflow | <p>I am new to tensorflow and I am now learning how to use queue runner. What I want to do is to read binary files from a dir and make each file an array. I use two threads and make 4 arrays a batch. The code is as follows. </p>
<pre><code> import glob
import tensorflow as tf
def readfile(filenames_queue):
... | <p>Your <code>readfile(...):</code> function is supposed to return an iterable so that you can return features and labels or other things like that.</p>
<p>So to fix your code change <code>readfile(...):</code> to </p>
<pre><code>return [arrays]
</code></pre> | python|tensorflow | 0 |
370,596 | 48,293,700 | Django ORM calculations between records | <p>Is it possible to perform calculations <strong><em>between</em></strong> records in a Django query? </p>
<p>I know how to perform calculations <strong><em>across</em></strong> records (e.g. data_a + data_b). Is there way to perform say the percent change between data_a row 0 and row 4 (i.e. 09-30-17 and 09-30-16)... | <p>There is no row 0 in a Django database, so we'll assume rows 1 and 5.</p>
<p>The general formula for calculation of percentage as expressed in Python is:</p>
<pre><code>((b - a) / a) * 100
</code></pre>
<p>where a is the starting number and b is the ending number. So in your example:</p>
<pre><code>a = 100
b = 7... | django|pandas|django-models|django-queryset | 1 |
370,597 | 48,082,018 | How to create dataframe of top 5 close words to a particular word lists from a dictionary in pandas | <p>I have a word2vec dictionary which gives a top similar words to given word.</p>
<p>I want to pass the list of words for which similarity needs to calculated from a file or list</p>
<p><strong>Input</strong> </p>
<pre><code>word_list =['wan,'floor','street']
</code></pre>
<p>Similarity of these words should b... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>words = ['wan', 'floor', 'street']
similar = [[item[0] for item in model.most_similar(word)[:5]] for word in words]
df = pd.DataFrame({'Word': words, 'Similar Words': similar})
</code></pre> | python|string|pandas|word2vec|gensim | 0 |
370,598 | 48,222,307 | Regular expression SpaCy | <p>I am creating a spaCy regular expression matches for matching number and extracting it pandas data frame.</p>
<p>Question: Panda picks up from number but overwrites value instead of appending. How to solve it?</p>
<p>(original code credit: yarongon)</p>
<pre><code>from __future__ import unicode_literals
import sp... | <p>You need append values to list in loop:</p>
<pre><code>L = []
for match in re.finditer(NUM_PATTERN, doc.text):
start, end = match.span()
L.append(doc.char_span(start, end))
</code></pre>
<p>and then use <code>DataFrame</code> constructor:</p>
<pre><code>df = pd.DataFrame(L,columns=['Number'])
</code></pre... | regex|pandas|nltk|spacy | 2 |
370,599 | 48,105,997 | How to determine activation, loss, optimizer in keras while making artificial neural network | <p>This is my dataframe</p>
<p><a href="https://drive.google.com/file/d/1qAnyOkp_YayqzZ4i0CwqCTDiYTIOmv6I/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1qAnyOkp_YayqzZ4i0CwqCTDiYTIOmv6I/view?usp=sharing</a></p>
<p>I need to find the value of ra, last column of that dataset via the ANN</p... | <p>You can remove the second hidden layer as simple Ann is enough for this and also we don’t have to use activator at the output layer as it is regression problem. </p>
<p>Please see the sample code <a href="https://github.com/naveenkambham/MachineLearningModels/blob/master/NeuralNetwork.py" rel="nofollow noreferrer">... | python|tensorflow|keras|data-science | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.