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 |
|---|---|---|---|---|---|---|
800 | 71,460,499 | Append new data into existing excel file pandas python | <p>hello everyone I'm attempting to add new data (columns and values) to an already existing excel spreadsheet. I have
Order_Sheet.xlsx saved with data as such:</p>
<pre><code> Item: Quantity: Price:
disposable cups 7000 $0.04
</code></pre>
<p>and add this info from spreadsheet_1.xlsx</p>
<pre><... | <p>Working only with pandas 1.4+. The following code assumes that the order of the row are the same between the first and the second write. It also assumes that you exactly know the number of existing columns.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df2 = pd.DataFrame({"c": ... | python|pandas|dataframe|export-to-excel | 1 |
801 | 71,609,482 | Drop the value that matches the string from list in python | <p>I have a list that contains strings. I want to drop out the ones that have specific strings using python.</p>
<p>For example:</p>
<pre><code>my_sample_list = ["I am practicing Python", "I am practicing Java", "I am practicing SQL"]
</code></pre>
<p>I want to drop out the element that co... | <p>Turn them to sets and do an intersection and back to list</p>
<pre><code>list(set(my_sample_list).intersection(set(my_new_sample_list)))
['I am practicing Java', 'I am practicing Python']
</code></pre> | python|pandas|string|list | 1 |
802 | 71,576,520 | Merging two dataframes that share a date column | <p>Lets say i have two dataframes (df_aapl) and (df_csco) and i wanna merge them based on the date(They both span the same timeframe and share the same dates).</p>
<p>I've tried pd.merge function but it duplicates the other columns. Like this...</p>
<p>(These are made up numbers)</p>
<div class="s-table-container">
<ta... | <pre><code>import pandas as pd
df_aapl = pd.read_excel(r"Desktop\book2.xlsx",sheet_name = 'Sheet1')
df_csco = pd.read_excel(r"Desktop\book2.xlsx",sheet_name = 'Sheet2')
## Assuming both df_aapl,df_csco data frames have same number of columns with same names.
data = pd.concat([df_aapl,df_csco],axis... | python|pandas | 0 |
803 | 71,590,615 | mathematical row operation on a dataframe | <p>I have a very large labelled dictionary array dataframe, df of dimension (9 by 4500) with index <code>[1,2,3,...,4500]</code>. I intend to carry out the following respective mathematical row operation element-by-element on the dataframe:</p>
<pre><code>[ 0. 0.00000771 0.00006065 ... 79.96962749 79.9696980... | <p>I can suggest first converting your dataframe to numpy array for ease of handling (It's my own preference)</p>
<pre><code>array = np.array(df)
mu1, mu2 = [],[]
#mu1 and mu2 calculation
for i in array:
mu1.append([number * index for index, number in enumerate(i)])
mu2.append([number * index ** 2 for index, ... | python|arrays|pandas|dataframe|numpy-ndarray | 1 |
804 | 69,848,550 | Plot a bar chart with Seaborn library and group by function | <p>The requirement is to Plot a bar chart using a seaborn library, showing total sales (<code>Customer_Value</code>) by the <code>Last_region</code>. Here my code</p>
<pre><code>import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
customer = pd.read_csv('D:\PythonTraining\Customer.csv')
df = custo... | <p>The issue is that <code>Last_region</code> becomes the index when you group on it. Also note that <code>df</code> here is most likely a Series, not a DataFrame, in which case <code>Customer_Value</code> would also not be a column.</p>
<ul>
<li><p>Either use <code>x=df.index</code> and <code>y=df.values</code></p>
<p... | python|pandas|dataframe|seaborn | 2 |
805 | 72,230,205 | ValueError when fitting my model. (ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224,3,3)) | <p>I am new to machine learning and I am using kaggle's notebook to code. I am making a classification model with multiple categories. I used efficientnet to make my model's architecture but the issue happens with every other model I've tried. The images to be classified are divided in train and val folders in the data... | <p>I think the problem is in the <strong>.flow_from_directory</strong> method. The shape pf the image in that method should not include the image channels and you can specify you are working with 3 channels by setting an additional parameter “color_mode” to “rgb”.</p> | python|pandas|tensorflow|machine-learning|keras | 0 |
806 | 50,630,821 | cannot instantiate an Xception model in Keras | <p>I'm running Keras in an NVIDIA Docker container on a multi-GPU machine. I'd like to instantiate a fairly standard model (Xception), but I keep getting weird errors. MRE:</p>
<pre><code>import tensorflow as tf
from keras.applications import Xception
height = 299
width = 299
num_classes = 1000
# Instantiate model
m... | <p>It seems its a known issue with keras and tensorflow <code>1.4</code> version as mentioned <a href="https://github.com/keras-team/keras/issues/9621" rel="nofollow noreferrer">here</a>. You may want to update both to the latest version to resolve this issue.</p> | python|tensorflow|keras | 2 |
807 | 50,399,123 | Extract values from csv file while going through a list using a for loop | <p>I've run into an issue when trying to extract values (in order to count them) from a .csv file while using a for loop to go through a list to try and find the correct values.</p>
<p>The .csv file is structured as follows:</p>
<pre><code>word,pleasantness,activation,imagery
a,2.0000,1.3846,1.0
abandon,1.0000,2.3750... | <p>IIUC, given you have a <code>.csv</code> such as:</p>
<pre><code>z = StringIO("""word,pleasantness,activation,imagery
a,2.0000,1.3846,1.0
abandon,1.0000,2.3750,2.4
abandoned,1.1429,2.1000,3.0
abandonment,1.0000,2.0000,1.4""")
df = pd.read_csv(z)
</code></pre>
<p>which yields </p>
<pre><code>>>> df
w... | python|python-3.x|pandas | 2 |
808 | 45,717,484 | Numpy Array random mutation | <p>I'm coding my first genetic algorithm in Python.
I particularly care about the optimization and population scalability.</p>
<pre><code>import numpy as np
population = np.random.randint(-1, 2, size=(10,10))
</code></pre>
<p>Here I make a [10,10] array, with random number between -1 and 1.<br>
And now I want to perf... | <p>Let's say you have an array <code>fitness</code> with the fitness of each specimen, with size <code>len(population)</code>. Let's also say you have a function <code>fitness_mutation_prob</code> that, for a given fitness, gives you the mutation probability for each of the elements in the specimen. For example, if the... | python|numpy|genetic-algorithm|mutation | 1 |
809 | 45,708,443 | TensorFlow - object detection module, error appear when trying to use protoc | <p>having problems with <code>protoc</code>, the line doesn't work in windows.</p>
<p>I get this <code>errors</code>:</p>
<p>using this line</p>
<pre><code>protoc --proto_path=./object_detection/protos --python_out=c:\testmomo ./object_detection/protos/anchor_generator.proto
</code></pre>
<p>I get this error</p>
<... | <p>I was trying different things, and figured out where was the problem.</p>
<p>Make sure you're doing it this way:</p>
<pre><code># From models/
protoc object_detection/protos/*.proto --python_out=.
</code></pre>
<p>whereas I was trying to do it like:</p>
<pre><code># from object_detection/
protoc protos/*.proto -... | python|tensorflow|deep-learning|object-detection|protoc | 15 |
810 | 62,543,843 | cannot import torch audio ' No audio backend is available.' | <pre><code>import torchaudio
</code></pre>
<p>When I just try to import torch audio on Pycharm, I have this error</p>
<pre><code>61: UserWarning: No audio backend is available.
</code></pre>
<p>warnings.warn('No audio backend is available.')</p> | <p>You need to install the audio file I/O backend. If Linux it's <code>Sox</code>, if Windows it's <code>SoundFile</code><br></p>
<p>To check if you have one set run <code>str(torchaudio.get_audio_backend())</code> and if 'None' is the result then install the backend.</p>
<p>SoundFile for Windows <code>pip install PySo... | python-3.x|pytorch|torch | 24 |
811 | 73,572,260 | Model is not learning/training pytorch | <p>Here is my training loop</p>
<pre><code>def train(model, train_dl, valid_dl, loss_fn, optimizer, scheduler, acc_fn, epochs=50):
start = time.time()
model.cuda()
train_loss, valid_loss = [], []
train_acc, valid_acc = [], []
best_acc = 0.0
for epoch in range(epochs):
print('Epoc... | <p>Welcome to stackoverflow!</p>
<p>You are calling <code>model.cuda()</code> inside the training loop, but supplying the optimizer externally. Smells like the optimizer was initialized on the wrong parameters.</p>
<p>ps: let me know whether that makes sense and/or works</p> | python|image|pytorch | 0 |
812 | 73,840,379 | Pandas date convesrion unconverted data remains | <p>In Pandas (Juypter) I have a column with dates in string format:</p>
<pre><code>koncerti.Date.values[:20]
array(['15 September 2010', '16 September 2010', '18 September 2010',
'20 September 2010', '21 September 2010', '23 September 2010',
'24 September 2010', '26 September 2010', '28 September 2010',
... | <p>Solution: <code>koncerti.Date = pd.to_datetime(koncerti.Date, format='%d %B %Y', exact=False)</code></p>
<p>Addditional parameter was needed: <code>exact=False</code></p> | python|pandas|datetime | 0 |
813 | 71,143,488 | How to convert two ECG measurments to HR with frequency 20 hz | <p>I have data from two ECG sensors taken at a frequency of 50hz.
I want to convert this to an HR signal with a frequency of 20hz. I have tried a solution with heartpy, but I can't get good values for HR at low frequency.
Does anybody have an example of how I can implement this in python?</p>
<p>The data looks like thi... | <p>I have made an example in python using neurokit and their <a href="https://github.com/neuropsychology/NeuroKit/blob/master/docs/examples/heartbeats.ipynb" rel="nofollow noreferrer">example</a> for heartbeats and simply taking the mean of the two ECG examples. Afterwards, I use a simple downsampling function to get t... | python|pandas|medical|downsampling | 0 |
814 | 71,201,140 | tensorflow.keras.Model inherit | <pre class="lang-py prettyprint-override"><code>import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class KerasSupervisedModelWrapper(keras.Model):
def __init__(self, batch_size, **kwargs):
super().__init__()
self.batch_size = batch_size
def summary... | <p>You could try something like this:</p>
<pre><code>import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class KerasSupervisedModelWrapper(keras.Model):
def __init__(self, batch_size, **kwargs):
super().__init__()
self.batch_size = batch_size
def su... | python|tensorflow|keras | 2 |
815 | 71,216,162 | Is it possible to train except for a specific area when implementing cycleGAN? | <p>Recently, I am conducting research to create fake images using cycleGAN. The figure below is an example of the cycleGAN result. It can be seen that all areas are changed as in the image. However, I want to change the image only for a specific area. Is it possible to change only the image of the part except for the r... | <p>I think what you describe is possible. You would need to alter the cycleGan pipeline. To focus the representational capacity of the network on everything other than the red marked part you could replace the red marked part with the same part from the original image, this would enforce a focus on the other regions. W... | tensorflow|keras|generative-adversarial-network | 0 |
816 | 60,542,475 | Confirm that TF2 is using my GPU when training | <p>I am wondering if there is a way to confirm that my TF model is training on my GPU after I stored the training data on it as advised in the TF tutorial. Here is a short code example:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
print('Num GPUs Available:', len(tf.config.experimental.... | <p>There a couple of ways to check for GPU in Tensorflow 2.x. Essentially, if GPU is available, then the model will be run on it (unless it's busy by e.g. another instance of TF that locked it). The placement will be seen also in the log files and can be confirmed with e.g. <code>nvidia-smi</code>.</p>
<p>In the code ... | python|python-3.x|tensorflow | 7 |
817 | 60,591,479 | How to fill multidimensional array using an equation in python | <p>I am new to python and I would like to fill a Numpy multidimensional array using an equation. In Fortran I can use the index of the array to fill it up, is this possible to do in python? Say I have an equation a=i*j where i and j are the row and column position respectively. So if I have an n by n array then the arr... | <p>You could use <code>numpy</code> <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasting</a> to get this result:</p>
<pre class="lang-py prettyprint-override"><code>i = np.arange(3)[:, np.newaxis] # (3, 1)
# array([0, 1, 2])
j = np.arange(4)[np.newaxis, :] #... | python|arrays|numpy | 3 |
818 | 72,500,942 | Error when trying to use df.merge: "You are trying to merge on object and int64 columns" | <p>I'm currently trying to write a program that takes a chemical compound's identifier (something called the CID number) and then gives back the compound's properties by using the pubchempy documentation.</p>
<p>However, I keep getting an error when I try to merge the data values that I get from pubchempy to the initia... | <p>It seems you want to merge two dataframes on <code>CID</code> column. <code>CID</code> column type of <code>df2</code> is <code>int</code>, you need change it to object to match the type of <code>CID</code> in <code>df</code></p>
<pre class="lang-py prettyprint-override"><code>df = df.merge(df2.astype({'CID': str}),... | python|pandas|dataframe|pubchem | 0 |
819 | 72,624,204 | expanding mean include conditions | <p>I have two dataframe, df1 and df2, the shape is the same</p>
<p>now I'd like to calculate expanding mean of df2 along columns from a certain column for each row. however, I'd like to add condition by df1>0 so only include certain columns in calculating mean.</p>
<p>Here is what I have in my mind. I think I need t... | <p>Here's a solution using the <code>mask</code> you have provided.</p>
<pre><code>df2[mask].expanding(axis=1).mean()
2021-10-01 2021-10-02 2021-10-03 2021-10-04
0 0.030476 0.031228 0.031003 0.031064
1 0.012853 0.013100 0.013100 0.013081
2 NaN 0.008568 0.008713 0.008917
3... | python|pandas | 1 |
820 | 72,615,652 | Improvement of iteration thru data frames | <p>Trying to find some insides in two data frames,know that loops are not solution in pandas and using two sheets with 15k rows each. How can I improve the speed on the code that follows? Its not possible to use merge because after matching the condition row from err need to be removed in order to don't be matched agai... | <p>Setup:</p>
<pre><code>scr = pd.DataFrame({'id' : ['10101.A', '10101.A', '10101.A'],'date' : ['10-5-2022', '10-5-2022', '9-5-2022'], 'qty': [1, 1, 1]})
err = pd.DataFrame({'id' : ['10101.A', '10101.A', '10101.A'], 'date' : ['4-5-2022', '13-5-2022', '16-5-2022'],'qty': [1, 1, 1], 'r':['a', 'b', 'c']})
scr['date'] = pd... | python|pandas|nested-loops | 2 |
821 | 59,695,402 | Iterate over list elements in Pandas dataframe column and match with values in a different dataframe | <p>I have two dataframes, I want to iterate over the elements in each list in the Companies column and match it with the company names in my second dataframe only if the date from the first dataframe occurs after the date of the second dataframe. I want two columns for the name matches and two columns for the date matc... | <p>Start from more pandasonic way to convert <em>Date</em> columns in both DataFrames
from <em>string</em> do <em>datetime</em>:</p>
<pre><code>df.Date = pd.to_datetime(df.Date)
df2.Date = pd.to_datetime(df2.Date)
</code></pre>
<p>Then proceed as follows:</p>
<pre><code>df3 = df.explode('Companies')
df3 = df3.merge(... | python|pandas | 1 |
822 | 32,281,529 | What is the correct way to mix feature sparse matrices with sklearn? | <p>The other day I was dealing with a machine learning task that required to extract several types of feature matrices. I save this feature matrices as numpy arrays in disk in order to later use them in some estimator (this was a classification task). After all, when I wanted to use all the features I just concatenated... | <blockquote>
<p>Is this the right approach to mix several feature extractors in order to yield a big feature matrix?</p>
</blockquote>
<p>In terms of correctness of the result, your approach is right, since <code>FeatureUnion</code> runs each individual transformer on the input data and concatenates the resulting ma... | python|numpy|pandas|scikit-learn | 6 |
823 | 32,216,630 | Get Maximum Value from Dataframe | <p>I'm running the following code to get the maximum value in a dataframe. It works fine.</p>
<pre><code> p_max_shot1_15_CH8 = corrected_shot1_data[['CH 8 [psi]']][0.0119:0.0122].max()
</code></pre>
<p>I would like to use the max value for math, but it is not a value but another dataframe</p>
<pre><code> CH 8 [psi]... | <p>You should be able to get values without an index using <code>.values</code>:</p>
<pre><code>p_max_shot1_15_CH8 = corrected_shot1_data[['CH 8 [psi]']][0.0119:0.0122].max().values
</code></pre>
<p>Alternatively, try putting max first, e.g.:</p>
<pre><code>max(p_max_shot1_15_CH8 = corrected_shot1_data[['CH 8 [psi]'... | pandas|ipython-notebook | 0 |
824 | 32,483,772 | How to index numpy array on subset of array of bools that is smaller than numpy array's dimensions? | <p>My question is inspired by another one: <a href="https://stackoverflow.com/questions/32481491/intersection-of-2d-and-1d-numpy-array/32483377#32483377">Intersection of 2d and 1d Numpy array</a> I am looking for a succinct solution that does not use <code>in1d</code></p>
<p>The setup is this. I have a <code>numpy ar... | <p>If I understand the question, this should do it:</p>
<pre><code>A[:, 3:][listed_array[:, 3:]] = 0
</code></pre>
<p>which is a concise version of</p>
<pre><code>mask3 = listed_array[:, 3:]
A3 = A[:, 3:] # This slice is a *view* of A, so changing A3 changes A.
A3[mask3] = 0
</code></pre> | python|numpy | 1 |
825 | 40,426,118 | How to create bounding boxes around the ROIs using TensorFlow | <p>I'm using inception v3 and tensorflow to identify some objects within the image.
However, it just create a list of possible objects and I need it to inform their position in the image.</p>
<p>I'm following the flowers tutorial: <a href="https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html" r... | <p>Inception is a classification network, not a localization network.</p>
<p>You need another architecture to predict the bounding boxes, like <a href="https://people.eecs.berkeley.edu/~rbg/papers/r-cnn-cvpr.pdf" rel="noreferrer">R-CNN</a> and its newer (and faster) variants (Fast R-CNN, Faster R-CNN).</p>
<p>Optiona... | python|neural-network|tensorflow|artificial-intelligence | 6 |
826 | 40,683,430 | Training letter images to a neural network with full-batch training | <p>According to <a href="https://iamtrask.github.io/2015/07/12/basic-python-network/" rel="nofollow noreferrer">this tutorial</a>(Pure Python with NumPy), I want to build a simple(at simplest level for learning purpose) neural network(Perceptron) that can train to recognize "A" letter. In this tutorial, in the proposed... | <p>Fist off: Great that you try to understand neural networks by programming them from scratch, instead of starting of with some complex library. Let me try to clear things up: your understanding here:</p>
<blockquote>
<p>Each time we subtract output matrix with input matrix and calculate the error and updating rate... | python|numpy|machine-learning|neural-network|artificial-intelligence | 2 |
827 | 40,359,666 | Pandas Dataframe groupby: produce multiple output columns | <p>I have the following code: </p>
<pre><code>def func(x):
return (1, 2, 3)
df.groupby[col].aggregate(func)
</code></pre>
<p>How to make three columns as the result of one aggregation function? I also tried returning np.array, pd.Series, but it doesn't help.</p> | <p>In <code>func()</code> you have to return a dataframe and I believe you should use <code>apply()</code>, for example like so:</p>
<pre><code>def func(x):
return pd.DataFrame([1,2,3]).T
df.groupby[col].apply(func)
</code></pre> | python|pandas|numpy|dataframe | 3 |
828 | 61,921,978 | Python Pandas Column to Minutes | <p>I've subtracted two datetimes from each other, like so:</p>
<p><code>df['Time Difference'] = df['Time 1'] - df['Time 2']</code></p>
<p>resulting in a timedelta object. I need the total number of minutes from this object, but I can't for the life of me figure it out. Currently, the "Time Difference" column looks li... | <p>use <code>dt.total_seconds()</code> and divide by 60 to get the minutes:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'td': pd.to_timedelta(['0 days 00:01:00.000000000',
'0 days 00:04:00.000000000',
'0 days 00:03:00.000000... | python|pandas|data-science|timedelta | 0 |
829 | 61,824,375 | Replacing null value in Python with next available value by group | <pre><code>df = pd.DataFrame({
'group': [1,1,1,2,2,2],
'value': [None,None,'A',None,'B',None]
})
</code></pre>
<p>I would like to replace missing values by the first next non missing value by group. The desired result is:</p>
<pre><code>df = pd.DataFrame({
'group': [1,1,1,2,2,2],
'value': ['A','A','A'... | <p>The Easiest way as @Erfan mention using backfill method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.bfill.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.bfill</code></a>.</p>
<h2>Solution 1)</h2>
<pre><code>>>> df['value'] = df.groupby('group... | python|pandas|pandas-groupby | 0 |
830 | 57,869,559 | numpy: Different results between diff and gradient for finite differences | <p>I want to calculate the numerical derivative of two arrays <code>a</code> and <code>b</code>.</p>
<p>If I do </p>
<pre><code>c = diff(a) / diff(b)
</code></pre>
<p>I get what I want, but I loose the edge (the last point) so <code>c.shape ~= a.shape</code>.</p>
<p>If I do</p>
<pre><code>c = gradient(a, b)
</code... | <p>These functions, although related, do different actions.</p>
<p><code>np.diff</code> simply takes the differences of matrix slices along a given axis, and used for <code>n</code>-th difference returns a matrix smaller by <code>n</code> along the given axis (what you observed in the <code>n=1</code> case). Please se... | numpy|numpy-ndarray | 4 |
831 | 58,076,848 | How to copy the current row and the next row value in a new dataframe using python? | <p>The df looks like below:</p>
<pre><code>A B C
1 8 23
2 8 22
3 8 45
4 9 45
5 6 12
6 8 10
7 11 12
8 9 67
</code></pre>
<p>I want to create a new df with the occurence of 8 in 'B' and the next row value of 8.</p>
<p>New df:
The df looks like below:</p>
<pre><code>A B C
1 8 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with compared by shifted values with <code>|</code> for bitwise <code>OR</code>:</p>
<pre><code>df = df[df.B.shift().eq(8) | df.B.eq(8)]
print (df)
A ... | python|pandas|dataframe | 5 |
832 | 57,894,304 | showing of angle between two vector in python in degrees | <p>i wrote following program in python </p>
<pre><code>import math
import numpy as np
u =np.array([2,2])
v =np.array([0,3])
#alculate manualy
product =np.dot(u,v)
normu = np.linalg.norm(u)
normv = np.linalg.norm(v)
cost = product /(normu * normv)
</code></pre>
<p>what i want is to show angle in degrees, for inst... | <p>The <code>cost</code> you have is not the angle. It is the cosine of the angle. You need to take the inverse cosine THEN convert radians to degrees.</p>
<pre><code>print(np.rad2deg(np.arccos(cost)))
#45.000000000000007
</code></pre> | python|numpy | 1 |
833 | 57,925,014 | Filtering rows on multiple string conditions at the same column | <p>I want to filter a dataframe on multiple conditions. Let's say I have one column called 'detail', i want to get a dataframe where the 'detail' column values match the following:</p>
<pre><code>detail = unidecode.unidecode(str(row['detail']).lower())
</code></pre>
<p>So now I have all <code>detail</code> rows unide... | <p>Actually @user3483203's comment is the right solution as to filter in pandas you use <code>&</code> and <code>|</code> instead of <code>and</code> and <code>or</code>. In any case in case you want to get rid of <code>unidecode</code> you might use this solution:</p>
<pre class="lang-py prettyprint-override"><co... | python|pandas|dataframe | 1 |
834 | 58,112,952 | Filter column in pandas and convert to float | <p>I have a pandas dataframe, which contains some pretty infiltered data</p>
<pre><code>df['Q53']
OUTPUT:
0 Hvor mange timer træner din virksomhed medarbe...
3 NaN
4 NaN
5 ... | <p>You can check if <code>isdigit</code> to select only <code>True</code> columns.</p>
<pre><code>df[df['Q53'].apply(lambda x: str(x).isdigit())]
</code></pre> | python|pandas|dataframe | 2 |
835 | 34,039,290 | How to loop through a dataframe, create a new column and append values to it in python | <p>I have the following problem. I have a dataframe with several columns, one of those contains strings as values. I want to loop through this column, change those values and save the changed values in a new column. </p>
<p>The code I have written so far looks like this:</p>
<pre><code>def get_classes(x):
for... | <p>You can use powerfull <code>Counter</code> from Collections:</p>
<pre><code>from collections import Counter
foo = lambda x: ','.join(sorted([k for k,v in Counter(x).iteritems() if v>=3]))
df['new'] = df['column'].str.split(',').map(foo)
#In [33]: df
#Out[33]:
# column NewColumn new
#0 A,A,A,C A ... | python|for-loop|pandas|dataframe | 2 |
836 | 34,046,048 | Debugging nans in the backward pass | <p>I'm trying to debug a somewhat complicated and non-canonical NN architecture. Computing the forward pass is fine and is giving me the expected results, but when I try to optimize using Adam or any of the standard optimizers, even after one iteration with a very small learning rate I get nans everywhere. I'm trying t... | <p>Debugging NaNs can be tricky, especially if you have a large network. <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/add_check_numerics_ops" rel="nofollow noreferrer"><code>tf.add_check_numerics_ops()</code></a> adds ops to the graph that assert that each floating point tensor in the graph does not... | tensorflow | 24 |
837 | 36,891,977 | Diff of two Dataframes | <p>I need to compare two dataframes of different size row-wise and print out non matching rows. Lets take the following two:</p>
<pre><code>df1 = DataFrame({
'Buyer': ['Carl', 'Carl', 'Carl'],
'Quantity': [18, 3, 5, ]})
df2 = DataFrame({
'Buyer': ['Carl', 'Mark', 'Carl', 'Carl'],
'Quantity': [2, 1, 18, 5]})
</code></p... | <p><a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.DataFrame.merge.html" rel="noreferrer"><code>merge</code></a> the 2 dfs using method 'outer' and pass param <code>indicator=True</code> this will tell you whether the rows are present in both/left only/right only, you can then filter the m... | python|pandas|dataframe|diff | 130 |
838 | 36,763,771 | dataframe to long format | <p>I have the following df:</p>
<pre><code>tz.head()
state 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
0 AL 5.7 4.5 4.0 4.0 5.7 11.0 10.5 9.6 8.0 7.2 6.8 6.1
1 AK 7.5 6.9 6.6 6.3 6.7 7.7 ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="noreferrer"><code>melt</code></a>:</p>
<pre><code>print pd.melt(df,id_vars=['state'],var_name='year', value_name='unemployment')
state year unemployment
0 AL 2004 5.7
1 AK 2004 7.5
2... | python|pandas | 13 |
839 | 36,960,086 | GroupBy - How to extract seconds from DateTime with diff() | <p>I have the following dataframe:</p>
<pre><code>In [372]: df_2
Out[372]:
A ID3 DATETIME
0 B-028 b76cd912ff 2014-10-08 13:43:27
1 B-054 4a57ed0b02 2014-10-08 14:26:19
2 B-076 1a682034f8 2014-10-08 14:29:01
3 B-023 b76cd912ff 2014-10-08 18:39:34
4 B-023 f88g8d7sds 2014-10-08 ... | <p><strong>UPDATE:</strong> <code>transform()</code> from <code>class NDFrameGroupBy(GroupBy)</code> doesn't seem to do downcasting and works as expected: </p>
<pre><code>In [220]: (df_2[['ID3','DATETIME']]
.....: .sort_values(by='DATETIME')
.....: .groupby('ID3')
.....: .transform(lambda x: x.... | python|python-3.x|pandas|dataframe | 4 |
840 | 54,752,287 | Get input (filenames) from tensorflow dataset iterators | <p>I am using tensorflow datasets to train a model. A list of filenames is taken by the dataset to read them during the session, and I would like to get the filename together with the image.
In more detail, I have something like this:</p>
<pre><code>filenames = tf.constant(["/var/data/image1.jpg", "/var/data/image2.j... | <p>You just need to keep the filename along with the image data in the dataset:</p>
<pre><code>filenames = tf.constant(["/var/data/image1.jpg", "/var/data/image2.jpg", ...])
labels = tf.constant([0, 37, ...])
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
dataset.shuffle()
def _parse_function(filen... | python|tensorflow|iterator|tensorflow-datasets | 5 |
841 | 54,824,768 | RNN model (GRU) of word2vec to regression not learning | <p>I am converting Keras code into PyTorch because I am more familiar with the latter than the former. However, I found that it is not learning (or only barely).</p>
<p>Below I have provided almost all of my PyTorch code, including the initialisation code so that you can try it out yourself. The only thing you would n... | <p><strong>TL;DR</strong>: Use <code>permute</code> instead of <code>view</code> when swapping axes, see the end of answer to get an intuition about the difference.</p>
<h1>About RegressorNet (neural network model)</h1>
<ol>
<li><p>No need to freeze embedding layer if you are using <code>from_pretrained</code>. As <a... | python|tensorflow|machine-learning|keras|pytorch | 8 |
842 | 54,930,568 | Weird "too many indices for array" error in python | <p>Let's create a large np array 'a' with 10,000 entries</p>
<pre><code>import numpy as np
a = np.arange(0, 10000)
</code></pre>
<p>Let's slice the array with 'n' indices 0->9, 1->10, 2->11, etc.</p>
<pre><code>n = 32
b = list(map(lambda x:np.arange(x, x+10), np.arange(0, n)))
c = a[b]
</code></pre>
<p>The weird th... | <p>Your <code>b</code> is a list of arrays:</p>
<pre><code>In [84]: b = list(map(lambda x:np.arange(x, x+10), np.arange(0, 5)))
In [85]: b
Out[85]:
[array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])... | python|numpy|numpy-ndarray|index-error | 2 |
843 | 55,083,787 | No module named 'object_detection' | <p>I downloaded Tensorflow object_detection API. I was able to run the tutorial and see the results. </p>
<p>However, while I want to train my own data, i have an error here at this code:</p>
<pre><code>python3 train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config
<... | <p>You can try the following steps.
Change to the object detection directory, activate your virtualenv and then do the following</p>
<pre><code>export PYTHONPATH=$PYTHONPATH:home/<username>/<path>/models/research
export PYTHONPATH=$PYTHONPATH:home/<username>/<path>/models
export PYTHONPATH=$PYT... | python|tensorflow|object-detection|object-detection-api | 1 |
844 | 49,762,795 | Finding the mode of a series consisting of list elements in Pandas | <p>I am working with a <code>pd.Series</code> where each entry is a list. I would like to find the mode of the series, that is, the most common list in this series. I have tried using both <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>pa... | <p>You need to convert to <code>tuple</code> , then using <code>mode</code></p>
<pre><code>pd.Series([[1,2,3], [4,5,6], [1,2,3]]).apply(tuple).mode().apply(list)
Out[192]:
0 [1, 2, 3]
dtype: object
</code></pre>
<p>Slightly improvement: </p>
<pre><code>list(pd.Series([[1,2,3], [4,5,6], [1,2,3]]).apply(tuple).mod... | python|list|pandas|dataframe|series | 5 |
845 | 28,363,447 | What are the advantages of using numpy.identity over numpy.eye? | <p>Having looked over the man pages for <code>numpy</code>'s <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.eye.html" rel="noreferrer"><code>eye</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.identity.html" rel="noreferrer"><code>identity</code></a>, I'd assumed th... | <p><code>identity</code> just calls <code>eye</code> so there is no difference in how the arrays are constructed. Here's the code for <a href="https://github.com/numpy/numpy/blob/v1.9.1/numpy/core/numeric.py#L2125" rel="noreferrer"><code>identity</code></a>: </p>
<pre><code>def identity(n, dtype=None):
from numpy ... | python|arrays|performance|numpy | 82 |
846 | 28,314,870 | Python - multiple list by a scalar | <p>Refer to the question mentioned on this link <a href="https://stackoverflow.com/questions/8194959/in-python-how-will-you-multiply-individual-elements-of-an-array-with-a-floating">In Python how will you multiply individual elements of a list with a floating point or integer number?</a></p>
<p>I use <code>import nump... | <p>you want to turn the <code>np.array()</code> back to a list?</p>
<pre><code>import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)
SP_LIST =list(SP)
</code></pre>
<p>As the post you link to also contains:</p>
<pre><code>[x * P for x in S]
</code></pre>
<p>returns a list directly</p> | python|numpy | 1 |
847 | 73,216,116 | Reference dict variables for data manipulation purposes | <p>I have successfully iterated through multiple directories to create a dictionary of lists (excel files) of DataFrames (sheets). However, <strong>a) how would I read in specific worksheets that match 1-2 list values? and exclude all other worksheets so I don't read in unnecessary amount of data in memory.</strong></p... | <p>Following @srinath's recommendation, I decided to append the root link with the filename, like so <code>file_list.append(os.path.join(root,filename))</code>. This change has been made in my question, and the title has been revised to reflect the change in status. Thank you to everyone and @srinath.</p> | python|pandas|list|loops|dictionary | 0 |
848 | 30,931,830 | Combining different elements of array in Numpy while doing vector operations | <p>I have a function <code>f</code> which I am using to evolve a Numpy array <code>z</code> repeatedly. Thus my code looks like this:</p>
<pre><code>for t in range(100):
z = f(z)
</code></pre>
<p>However, now I want to combine elements of array while evolving. For example, in simple Python, I would like to do som... | <p>You can roll the data <em>back and forth</em> to achieve the same result. </p>
<pre><code>Z = f(z)
Z = np.roll(Z, 1) + z
Z = np.roll(Z, -2) + z
z = np.roll(Z, 1)
</code></pre>
<hr>
<p>I had also first thought about slicing but went with <code>np.roll</code> when I found it.</p>
<p>Prompted by @hpaulj's comment I... | python|arrays|numpy | 2 |
849 | 67,418,422 | How to skip the lines of an excel file loaded to a Pandas dataframe if data types are wrong (checking types) | <p>I have just coded this:</p>
<pre><code>import os
import pandas as pd
files = os.listdir(path)
#AllData = pd.DataFrame()
for f in files:
info = pd.read_excel(f, "File")
info.fillna(0)
try:
info['Country'] = info['Country'].astype('str')
except ValueError:
continue
try... | <p>I first have to say that <em>type checking</em> and <em>type casting</em> are 2 different things.</p>
<p>Pandas' <code>astype</code> is used for <em>type casting</em> (it will "convert" a type to another type, it will not check if a value is of certain type) .</p>
<p>But if what you want is to not keep the... | python|python-3.x|pandas|dataframe | 1 |
850 | 67,253,963 | What does "TypeError: 'generator' object does not support item assignment" mean? | <p>When I try to run the following code I get an error called: <code>TypeError: 'generator' object does not support item assignment</code>. How can I fix this?</p>
<pre><code>import os, glob
import pandas as pd
import re
import sys
path = r'C:\Users\Nicole\02_Datenverarbeitung und Analyse\Input'
all_files... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>...
# Use brackets instead of parenthesis
df_from_each_file = [
pd.read_csv(
f, sep=",", encoding="iso-8859-1", error_bad_lines=False, warn_bad_lines=False
)
for f in all_files
]
# Assign new column to each df
for ... | python|pandas|date | 0 |
851 | 34,842,544 | count of unique occurrences of a value pandas python | <p>So I have an extremely simple dataframe:</p>
<pre><code>values
1
1
1
2
2
</code></pre>
<p>I want to add a new column and for each row assign the sum of it's unique occurences, so the table would look like:</p>
<pre><code>values unique_sum
1 3
1 3
1 3
2 2
2 2
</code></pre>
<p>I have seen some examples in R, but f... | <p>Just use <code>map</code> to map your column onto its <code>value_counts</code>:</p>
<pre><code>>>> x
A
0 1
1 1
2 1
3 2
4 2
>>> x['unique'] = x.A.map(x.A.value_counts())
>>> x
A unique
0 1 3
1 1 3
2 1 3
3 2 2
4 2 2
</code></pre>
<p>(I named ... | python|pandas | 2 |
852 | 60,116,795 | Create pd series based on conditions on df1, and reporting values from df2 or df3 | <p>First post here. I'm new to Python, but have made alot of progress leveraging the answers posted here to others questions. Unfortunately i'm having trouble with what seems to be an easy task.
I have 3 pandas series, indexed on dates</p>
<pre><code>df1 = {'signal': [0,0,1,1,0,0,1]} #binary trading signal
df2 = {... | <p>use <code>Series.where()</code>, specify the column names.</p>
<p>see <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html</a></p>
<pre><code>>>> df3.where... | python|pandas|dataframe | 1 |
853 | 65,279,392 | Convert Python Array to String in List [Pandas] | <p><strong>I want to convert pandas data frame from this:</strong></p>
<pre><code> label
0 ['hello', 'world']
1 ['just','string']
</code></pre>
<p><strong>To this:</strong></p>
<pre><code>0 hello world
1 just string
</code></pre>
<p><strong>But, my output like this:</strong></p>
<pre><code>0 [ ' h e l l... | <p>You can use <code>str.join</code></p>
<pre><code>import pandas as pd
df = pd.DataFrame({"col": [["Hello","world"], ["just","string"]]})
df["col"] = df["col"].str.join(" ")
</code></pre>
<p>df is:</p>
<pre><code>col
0 Hello world
1 ... | python|arrays|pandas|csv | 0 |
854 | 65,255,166 | Interesting results with duplicate columns in pandas.DataFrame | <p>Can anyone help to explain why I get errors in some actions and not others when there is a duplicate column in a <code>pandas.DataFrame</code>.</p>
<p><strong>Minimal, Reproducible Example</strong></p>
<pre><code>import pandas as pd
df = pd.DataFrame(columns=['a', 'b', 'b'])
</code></pre>
<p>If I try and insert a li... | <p>Why use loc and not just:</p>
<pre><code>df['a'] = list(range(5))
</code></pre>
<p>This gives no error and seems to produce what you need:</p>
<pre><code>a b b
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 NaN NaN
4 NaN NaN
</code></pre>
<p>same for creating column c:</p>
<pre><code>df['c'] = list(range(5))
</c... | python|pandas|dataframe | 1 |
855 | 50,127,527 | How to save training history on every epoch in Keras? | <p>I can't keep my PC running all day long, and for this I need to save training history after every epoch. For example, I have trained my model for 100 epochs in one day, and on the next day, I want to train it for another 50 epochs. I need to generate the loss vs epoch and accuracy vs epoch graphs for the whole 150 e... | <p>Keras has the CSVLogger callback which appears to do exactly what you need; from the <a href="https://keras.io/api/callbacks/csv_logger/" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>Callback that streams epoch results to a CSV file.</p>
</blockquote>
<p>It has an append parameter for adding to the file. ... | python|tensorflow|keras | 17 |
856 | 50,223,197 | Converting Matlab code into Python - FFT | <p>I need to convert a piece of MATLAB code to Python and I'm bad at both. The code in MATLAB uses <code>fft</code> and <code>fftshift</code>. I tried to use NumPy in Python. The code runs but when I compare the outcome they are not matching. I appreciate your help.</p>
<p>Here is the MATLAB code: </p>
<pre class=... | <p>The error in your Python code is that you define <code>h</code> to be of size <code>Modes_number+1</code>, which is one more than the size in the MATLAB code. The first value in <code>hfft</code> is the sum of all input values. In MATLAB this is <code>-1j*S*200 = -2500.4j</code>, and in your Python code this is <cod... | python|matlab|numpy|fft | 1 |
857 | 63,992,639 | Pandas to_sql - append vs replace | <p>I'm trying to understand how to modify the to_sql function to my needs. Here's the dataframe <code>df_interface</code>:</p>
<pre><code>| YEAR | QUARTER | USER_ACCOUNT | BYTES | USER_CODE |
|------|---------|--------------|---------------|-----------|
| 2020 | 2 | SHtte34 | 7392577516389 | 2320885 ... | <p>The <code>if_exists</code> argument refers to the table as a whole, not individual rows within the table. <code>if_exists="replace"</code> means "if the table exists then drop it and create a new one with the rows in the DataFrame, whereas <code>if_exists="append"</code> means "append t... | python|pandas|oracle|sqlalchemy | 2 |
858 | 64,014,323 | Pandas: Only the last row is appearing | <p>While the definitions of both tissue and tube can be seen using the print function, only tube shows up in pandas.</p>
<pre><code>from bs4 import BeautifulSoup as bs
import re
from requests import get
import requests
import numpy as np
import pandas as pd
def get_soup(url):
soup = bs(requests.get(url).content, ... | <p>In the following line</p>
<pre class="lang-py prettyprint-override"><code>data = {'Word':[i],'Definition':[m]}
</code></pre>
<p>you are overwriting your dictionary i.e. the <code>data</code> variable, because of that your dataframe contains only one rows, you can rather create two empty list for Word and Definition ... | python|pandas|google-colaboratory | 2 |
859 | 64,022,213 | Python pandas fill missing value (NaN) based on condition of another column | <p>I have figured out how to fill the NaN values with the previous cell by using <code>df.fillna(method='ffill')</code>.</p>
<p>However, I am not sure how to base it on a condition that if the country name differs from the country name in its previous cell, then the total case cell value should be 0, otherwise replace ... | <p>Simply using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> w... | python|pandas | 1 |
860 | 47,006,726 | Panda in Python skips computation on first line | <p>I have a file with its content as </p>
<pre><code>0.08300343840033242
0.5721455830484666
0.46518116038504165
</code></pre>
<p>I ran following script on it:</p>
<pre><code>import pandas as pd
import csv
df = pd.read_csv('circle1.csv')
df1 = df**2
print df1
</code></pre>
<p>Problem in the output is pandas skips th... | <p>You're not loading your data properly, it appears your CSV has no headers. In which case, specify <code>header=None</code>.</p>
<pre><code>df = pd.read_csv('circle1.csv', header=None, names=['Value'])
df
Value
0 0.083003
1 0.572146
2 0.465181
</code></pre>
<hr>
<pre><code>df ** 2
Value
0 0.006889... | python|pandas|csv | 0 |
861 | 46,953,310 | Importing Excel into Panda Dataframe | <p>The following is only the beginning for an Coursera assignment on Data Science. I hope this is not to trivial for. But I am lost on this and could not find an answer.
I am asked to import an Excelfile into a panda dataframe and to manipulate it afterwards. The file can be found here: <a href="http://unstats.un.org/u... | <p>I think you need add parameters:</p>
<ul>
<li><code>index_col</code> for convert column to index</li>
<li><code>usecols</code> - parse columns by positions</li>
<li>change header position to <code>15</code></li>
</ul>
<hr />
<pre><code>energy=pd.read_excel('Energy Indicators.xls',
sheet_name='En... | python|excel|pandas|dataframe|import | 3 |
862 | 38,877,766 | Converting pandas dataframe into list of tuples with index | <p>I'm currently trying convert a pandas dataframe into a list of tuples. However I'm having difficulties getting the Index (which is the Date) for the values in the tuple as well. My first step was going here, but they do not add any index to the tuple.</p>
<p><a href="https://stackoverflow.com/questions/9758450/pand... | <p>You can iterate over the result of <code>to_records(index=True)</code>.</p>
<p>Say you start with this:</p>
<pre><code>In [6]: df = pd.DataFrame({'a': range(3, 7), 'b': range(1, 5), 'c': range(2, 6)}).set_index('a')
In [7]: df
Out[7]:
b c
a
3 1 2
4 2 3
5 3 4
6 4 5
</code></pre>
<p>then this wo... | python|pandas|numpy|tuples | 10 |
863 | 38,619,143 | Convert Python sequence to NumPy array, filling missing values | <p>The implicit conversion of a Python sequence of <em>variable-length</em> lists into a NumPy array cause the array to be of type <em>object</em>.</p>
<pre><code>v = [[1], [1, 2]]
np.array(v)
>>> array([[1], [1, 2]], dtype=object)
</code></pre>
<p>Trying to force another type will cause an exception:</p>
<... | <p>You can use <a href="https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest">itertools.zip_longest</a>:</p>
<pre><code>import itertools
np.array(list(itertools.zip_longest(*v, fillvalue=0))).T
Out:
array([[1, 0],
[1, 2]])
</code></pre>
<p>Note: For Python 2, it is <a href="https://docs.py... | python|arrays|numpy|sequence|variable-length-array | 34 |
864 | 63,126,775 | header and skiprows difference in pandas unclear | <p>Can any one please elaborate with good example the difference between header and skiprows in syntax of
pd.read_excel("name",header=number,skiprows=number)</p> | <p>You can follow <a href="https://towardsdatascience.com/import-csv-files-as-pandas-dataframe-with-skiprows-skipfooter-usecols-index-col-and-header-fbf67a2f92a" rel="nofollow noreferrer">this article</a>, which explains the difference between the parameters <code>header</code> and <code>skiprows</code> with examples f... | python|excel|pandas | 3 |
865 | 63,317,748 | calculate mean of cells from different dataframes | <p>I want to calculate the mean of multiple cells from different dataframes. I have calculated the correlation between variables with <code>df.corr()</code> and I have to do this another 9 times and calculate the mean of correlation of each varaible.</p>
<p>For example, the first dataframe with correlations I got as a ... | <p>It's pretty forward, you could just do:</p>
<pre class="lang-py prettyprint-override"><code>(df1.corr() + df2.corr()) / 2
</code></pre>
<p>as the two dataframes have the same columns</p> | python-3.x|pandas|dataframe | 1 |
866 | 63,021,958 | How can l extract a section of the pandas dataframe like marked in the picture below? | <p><img src="https://i.stack.imgur.com/xiGWo.jpg" alt="Click here to open the marked image" /></p>
<p>I am trying to extract the section (matrix) of the numbers in pandas dataframe like as marked in the given picture embedded above.<br />
Please anyone who can assist me, I want to perform analytics based on the section... | <p>You can use the .iloc[] function to select the rows and columns you want.</p>
<pre><code>dataframe.iloc[5:15,6:15]
</code></pre>
<p>This should select rows 5-14 and columns 6-14.
Not sure if the numbers are correct but I think this method is what you were looking for.</p>
<p>edit: changed .loc[] to .iloc[] because w... | python|pandas | 2 |
867 | 63,094,112 | Return Pandas entry in specific format? | <p>Right now, I'm searching through a pandas dataframe for entries that match a certain username. It's returning stuff like this:
<code>{"username":{"0":"user","1":"user","2":"user"},"title":{"0":"Title","1":&q... | <p>Here is how you can use a nested dictionary comprehension:</p>
<pre><code>d = {"username":{"0":"user","1":"user","2":"user"},
"title":{"0":"Title","1":"asdfasdfasdf","2":"Bob&qu... | python|pandas | 0 |
868 | 67,936,385 | Unable to import 'pandas_profiling' module | <p>I have installed 'pandas_profiling' through <code>conda install -c conda-forge pandas-profiling</code> in the base environment. I could see through the <code>conda list</code> that pandas_profiling has been installed correctly (snapshot attached),
<a href="https://i.stack.imgur.com/gIwj3.png" rel="nofollow noreferre... | <p>Occasionally you will encounter this error if you import a package from the current notebook. It is important to ensure that the pip version is associated with the current Python kernel. That way, the installed packages can be used in the current notebook.</p>
<p>As detailed <a href="https://jakevdp.github.io/blog/2... | python|conda|pandas-profiling | 0 |
869 | 31,742,495 | Pandas DataFrame get substrings from column | <p>I have a column named "KL" with for example:</p>
<pre><code>sem_0405M4209F2057_1.000
sem_A_0103M5836F4798_1.000
</code></pre>
<p>Now I want to extract the four digits after "M" and the four digits after "F". But with <code>df["KL"].str.extract</code> I can't get it to work.</p>
<p>Locations of M and F vary, thus ... | <p>If you want to use <code>str.extract</code>, here's how:</p>
<pre><code>>>> df['KL'].str.extract(r'M(?P<M>[0-9]{4})F(?P<F>[0-9]{4})')
M F
0 4209 2057
1 5836 4798
</code></pre>
<p>Here, <code>M(?P<M>[0-9]{4})</code> matches the character <code>'M'</code> and then captures 4 ... | python|pandas|dataframe | 1 |
870 | 31,948,243 | Pandas (0.16.2) Show 3 Rows of Dataframe | <p>I'm trying to limit the output of the pandas dataframe to the first 3 rows. However I get a summary of all 500000 data points. When I run this without specifying "Time [s]" as the index it works properly and I only get 3 rows of data. I'm running Pandas 0.16.2 and Python 3.</p>
<pre><code>%matplotlib inline
impo... | <p>You're trying to slice a df which has a <code>datetimeindex</code> using integer values that are not valid which is why you get the full df.</p>
<p>Example:</p>
<pre><code>In [34]:
df = pd.DataFrame(index=pd.date_range(start=dt.datetime(2015,1,1), end=dt.datetime(2015,1,10)))
df[:3]
Out[34]:
Empty DataFrame
Colum... | pandas|ipython-notebook | 1 |
871 | 41,560,053 | Python reshaping array in a certain order using np.reshape | <p>I have an array (a) that is the shape <code>(1800,144)</code> where <code>a[0:900,:]</code> are all real numbers and the second half of the array <code>a[900:1800,:]</code> are all zeros. I want to take the second half of the array and put it next to the first half horizontally and push them together so that the new... | <p>sorry, this is too big for a comment, so I will post it here.
If you have a long array and you need to split it and reassemble it, there are other methods that can accomplish this. This example shows how to assemble an equally sized sequence of numbers into a single array.</p>
<pre><code>a = np.arange(100)
>>... | python|arrays|numpy|reshape | 1 |
872 | 41,561,011 | Reset the index for a pandas DataFrame created from a groupby or pivot? | <p>I have data that contains prices, volumes and other data about various financial securities. My input data looks like the following:</p>
<pre><code>import numpy as np
import pandas
prices = np.random.rand(15) * 100
volumes = np.random.randint(15, size=15) * 10
idx = pandas.Series([2007, 2007, 2007, 2007, 2007, 200... | <p>You need to label each year 0-4. To do this, use the <code>cumcount</code> after grouping. Then you can pivot correctly using that new column as the index.</p>
<pre><code>df['year_count'] = df.groupby(level='year').cumcount()
df.reset_index().pivot(index='year_count', columns='year', values='price')
year ... | python|pandas | 3 |
873 | 41,348,587 | Pandas groupby and then select one row | <p>I hava pandas dataframe where I have to group by some columns. Most groups in the group by only have one row, but a few have more than one row. For each of these, I only want to keep the row with the earliest date.
I've tried both the <code>agg</code> and <code>filter</code> functions, but they don't seem to do what... | <p>Sort by date and then just grab the first row.</p>
<pre><code>df.sort_values('date').groupby(['id', 'period', 'type']).first()
</code></pre> | python|pandas | 16 |
874 | 41,446,914 | Unsupported operand type for unicode error in Python | <p>I have a pandas dataframe in the below format:</p>
<pre><code> Timestamp Clientip
2015-07-22T02:40:06.499174Z 106.51.235.133
2015-07-22T02:40:06.632589Z 115.250.16.146
</code></pre>
<p>To sessionize the above data, I grouped it based on clientip and then created a session num... | <p>Try this:</p>
<pre><code>In [162]: df
Out[162]:
Timestamp Clientip
0 2015-07-22T02:40:06.499174Z 106.51.235.133
1 2015-07-22T02:50:06.000000Z 106.51.235.133
2 2015-07-22T02:40:06.632589Z 115.250.16.146
3 2015-07-22T03:30:16.111111Z 115.250.16.146
In [163]: df.Timestamp = pd.to_d... | python|pandas | 2 |
875 | 61,238,095 | Pandas adding extra zeros to decimal value | <p>I'm importing a file into pandas dataframe but the dataframe is not retaining original values as is, instead its adding extra zero to some float columns. </p>
<p>example original value in the file is 23.84 but when i import it into the dataframe it has a value of 23.8400</p>
<p>How to fix this? or is there a way t... | <p>For anyone who encounters the same problem, I'm adding the solution I found to this problem. Pandas read_csv has an attribute as dtype where we can tell pandas to read all columns as a string so this will read the data as is and not interpret based on its own logic. </p>
<p>df1 = pd.read_csv('file_location', sep = ... | python|pandas | 1 |
876 | 68,862,658 | Trying to find FP,FN,TP,TN but i'm having some errors | <p>I'm trying to find FP,FN,TP,TN values but it gives me this error:</p>
<pre><code>AttributeError: 'function' object has no attribute 'sum'
</code></pre>
<p>Here is that part my code:</p>
<pre><code>FP = confusion_matrix.sum(axis=0) - np.diag(confusion_matrix) <-- Error in this line
FN = confusion_matrix.sum(axis... | <p>You're getting this error because <code>confusion_matrix</code> is a function, and you're trying to call the <code>sum</code> function on it.</p>
<p>If you're using <code>confusion_matrix</code> from <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html" rel="nofollow noref... | python|pandas|numpy|confusion-matrix | 3 |
877 | 68,534,141 | AutoEncoder Resulting In (61,61,3) instead of (64,64,3) | <p>I am trying to build a convolutional autoencoder. Here is my architecture.</p>
<pre><code>
def MainEncoder():
inp = Input(shape=(64,64,3))
x = Conv2D(256,2)(inp)
x = MaxPool2D()(x)
x = Conv2D(128,2)(x)
x = Flatten()(x)
encoded = Dense(100,activation="relu")(x)
encoder= Model(in... | <p>When using Convolution, you need to be aware that pixels on the edge of the image will not be kept.</p>
<p>If you want them to be of similar shapes, you can add the keyword "padding" and set its value to "same" when defining your Conv2D.</p>
<p>Here's what it's probably going to look like :</p>
<... | python|tensorflow|autoencoder | 0 |
878 | 36,599,346 | make the values in a column being rownames | <p>I want to <strong>convert the dataframe</strong> </p>
<p><a href="https://i.stack.imgur.com/8BjmB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8BjmB.png" alt="orginal dataframe"></a></p>
<p><strong>into</strong> </p>
<p><a href="https://i.stack.imgur.com/MAsfr.png" rel="nofollow noreferrer">... | <pre><code>data.pivot('index', 'col', 'data')
</code></pre> | python|pandas|dataframe | 1 |
879 | 36,411,276 | Python Pandas dataframe: Collect values of a column | <p>I have the following data frame:</p>
<pre><code> var_1 var_2 item_list
0 0 1 [beer, apple, pear, rice]
1 0 1 [egg, banana, oil, pear]
2 0 1 [beer, noodle]
3 1 0 ... | <p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> <code>Series</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> and convert <a href="ht... | python|pandas|dataframe | 3 |
880 | 53,068,443 | I am having trouble installing Tensorflow - gpu into my anaconda virtual enviorment | <p>Every time I try and re-install Cuda it fails and whenever I try and import Tensorflow with the current set up I have it will pip install but it will not import and will instead return:</p>
<blockquote>
<blockquote>
<blockquote>
<p>import tensorflow as tf
Traceback (most recent call last):
... | <p>This is basically DLL load error. The answer is already given in the past posts.
<a href="https://stackoverflow.com/questions/20201868/importerror-dll-load-failed-the-specified-module-could-not-be-found">DLL failed-1</a>,<a href="https://github.com/pytorch/pytorch/issues/9263" rel="nofollow noreferrer">DLL load fai... | python|tensorflow|anaconda|conda | 0 |
881 | 65,744,701 | Python Pandas Groupby to count unique records in a single column | <p>I have a df having a single column containing rows of repeating data. I want to display a pivot table of unique values of that column along with their count. I know it would be some sort of groupby however I could not get it to work, please help.</p>
<p><a href="https://i.stack.imgur.com/FYAH7.png" rel="nofollow nor... | <p>Try:</p>
<pre><code>df.groupby("PdDistrict").size()
</code></pre> | python|pandas|matplotlib | 1 |
882 | 65,817,029 | How to expand series into dataframe | <p>Suppose we have a dataframe like:</p>
<pre class="lang-py prettyprint-override"><code>data = pd.DataFrame({'num': [1,2,3],
'tags': [['toto','tata','titi'],
['one','two','three'],
['he','she','us']]})
</code></pre>
<p>data</p>
<pre><code>... | <p>You can think of <code>apply()</code> as going rowwise through column <code>tags</code> in this case. So applying <code>pd.Series</code> is going to make each list a "horizontal" series. Then since you have a "vertical" column of these "horizontal" series you are left with a single data... | python|pandas|dataframe|series|expand | 0 |
883 | 65,489,827 | How to make a similar custom generator in Keras for a CNN that takes multiple images as inputs? | <p>I am working on DR detection using CNNs on Google Colab. The CNN that I have designed has <strong>3 inputs for 3 different grayscale images</strong> of each eye (one original, one with extracted blood vessels, and one with extracted exudates). The code for the CNN is as follows:</p>
<pre><code>#Custom CNN Model
from... | <p>you say the ImageDataGenerator causes Colab to crash. Please show the code you used for this. Did you use .flow_from_directory? If so what is the setting for the batch_size? If this is set with to large a value it may cause use of two much memory especially if you have 3 generators running. The fact that you have 3... | python|tensorflow|keras|conv-neural-network|google-colaboratory | 0 |
884 | 65,501,679 | Simple calculation on table. Please help me to make my code more effective | <p>Please help me to make my code more effective. This is my df:</p>
<pre><code>df = pd.DataFrame([['A', 80], ['A', 64], ['A', 55], ['B', 56], ['B', 89], ['B', 73], ['C', 78], ['C', 100], ['C', 150], ['C', 76], ['C', 87]], columns=['Well', 'GR'])
</code></pre>
<pre><code>Well GR
A 80
A 64
A 55
B ... | <p>one string solution with method <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer">transform</a>:</p>
<pre><code>df['Vshale'] = df.groupby('Well').transform(lambda x: (x - np.min(x))/(np.max(x) - np.min(x)))
</code></pre> | python|pandas|pandas-groupby | 1 |
885 | 21,093,729 | Dot product of csr_matrix causes segmentation fault | <p>I have two (scipy) CSR sparse matrices:</p>
<pre><code>A (12414693, 235470)
B (235470, 48063)
</code></pre>
<p>Performing:</p>
<pre><code>A.dot(B)
</code></pre>
<p>causes a segmentation fault.</p>
<p>What am I doing wrong?</p>
<p><strong>EDIT</strong></p>
<p>I've submitted a bug to the scipy developer communi... | <p>Your problem is very likely being caused by an overflow of an index stored in an <code>int32</code>, caused by the result of your dot product having more than 2^31 non-zero entries. Try the following...</p>
<pre><code>>>> import scipy.sparse
>>> c = np.empty_like(A.indptr)
>>> scipy.spars... | python|numpy|scipy|sparse-matrix | 4 |
886 | 63,734,091 | Python Dataframe select last n rows based on present value condition | <p>I have a dataframe. I want to select last n (=2) rows if present value is <code>True</code>.</p>
<p>My code:</p>
<pre><code>df = pd.DataFrame({'A':[10,20,30,40,50,60],'B':[False,False,True,False,True,False]})
A B
0 10 False
1 20 False
2 30 True # Here, I should select 30,20
3 40 False
4 50 Tru... | <p>Let us try <code>limit</code> with <code>bfill</code></p>
<pre><code>n = 2
df[df.B.where(df.B).bfill(limit=n-1)==1]
Out[95]:
A B
1 20 False
2 30 True
3 40 False
4 50 True
</code></pre> | python|pandas|numpy | 3 |
887 | 63,364,332 | Reformat pivot table output for table | <p>I have a pivot table called <code>pivot</code> that I have created using:</p>
<pre><code>pivot = MonthyData.pivot_table(index=['year'],columns=MonthyData['month'], values=['total_pos'], aggfunc='sum')
pivot = pivot.rename(columns=lambda x: look_up.get(f'{str(x).zfill(2)}', x))
pivotdf = pivot.reset_index()
pivotdf=p... | <p>As @QuangHoang, pointed out in the comments, it helps if you provide the name of the columns because you are applying <code>.pivot()</code> onto the data.frame, so it can look for the column to pivot. Once you have that, you almost have the table you need, just need to remove the names of the index:</p>
<pre><code>M... | python|pandas | 0 |
888 | 21,483,959 | How can get ' USDJPY'(currency rates) with pandas and yahoo finance? | <p>I am learning and using the pandas and python.</p>
<p>Today, I am trying to make a fx rate table,
but I got a trouble with getting the pricess of 'USDJPY'.</p>
<p>When I get a prices of 'EUR/USD', i code like this.</p>
<pre><code>eur = web.DataReader('EURUSD=X','yahoo')['Adj Close']
</code></pre>
<p>it works.</p... | <p>Yahoo Finance doesn't provide historical data on exchange rates (i.e. there's no "Historical Prices" link in the top left of the page like there would be for stocks, indices, etc...)</p>
<p>You can use FRED (Federal Reserve of St. Louis data) to get these exchange rates...</p>
<pre><code>import pandas.io.data as w... | python|ios|pandas|currency|yahoo-finance | 15 |
889 | 24,680,318 | Bokeh datetime axis should show all yyyy, mm, dd, hh, mm, ss | <p>I create my datetimeindex via</p>
<pre><code>datetimes = pd.to_datetime(SeriesOfUnixtimeStamps,"s")
line(x=datetimes,y,x_axis_type="datetime",...)
</code></pre>
<p>Depending on how much I zoom in or out, the x-axis only shows lets say <code>:07:03</code> instead of <code>2014-06-12 12:07:03</code>. I want to show... | <p>Unfortunately at the moment we don't have this capability, although I have opened an <a href="https://github.com/ContinuumIO/bokeh/issues/813" rel="nofollow noreferrer">issue</a> over on our GitHub page so you can track its progress.</p>
<p>The fix may be relatively simple, but we're in the midst of a SciPy release... | python|pandas|bokeh | 1 |
890 | 29,876,541 | re.match takes a long time to finish | <p>I am new to python and have written the following code that runs very slow. </p>
<p>I have debugged the code and found out it is the last <code>re.match()</code> that is causing the code to run very slow. Even though the previous match does the same kind of match against the same DataFrame, it comes back quickly. <... | <p>"Poorly" designed regular expressions can be unnecessarily slow. </p>
<p>My guess is that <code>.*\sCN</code> and <code>*\sMUT</code> combined with a big string that does <strong>not</strong> match, makes it that slow, since it forces your script to check all possible combinations. </p>
<hr>
<p>As @jedwards said,... | python|regex|pandas | 0 |
891 | 53,770,530 | Color mapping of data on a date vs time plot | <p>I am trying to plot 3 variables x,y,z on a 2d plot, with x (date) on the x axis, y (time) on the y axis and z (temperature) mapped with a colorscale.
I have the three variables available within a pandas Dataframe and created an extra column with the datenumber so that matplotlib can work with it. </p>
<pre><code>i... | <p><code>imshow</code> requires a 2d array as input. You'll need to reformat your data into a 2d array: <code>Date</code> x <code>Time</code> with <code>Tgrad</code> as your values. Pandas makes this fairly easy with <code>pivot</code>. It does require that you have nicely spaced data points, i.e., a grid-like data set... | python|pandas|imshow | 2 |
892 | 53,668,128 | Counting the number of rows that fulfill a condition and assigning to each row a number from 1 to nRows pandas | <p>So again, i have another question related to this: I'm processing a DataFrame, which looks like the following:</p>
<p><a href="https://i.stack.imgur.com/vvObO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vvObO.png" alt="enter image description here"></a></p>
<p>the thing is that now I want to... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> by column <code>contributor_id</code> and helper <code>Series</code> for distingoush multiple <code>0</code> in same group:</p>
<pre><code>m = df[... | python|pandas|dataframe|pandas-groupby | 0 |
893 | 53,671,498 | Interpolate array to constant density | <p>I have been going in circles with this apparently simple issue for hours and I can't seem to find the answer.</p>
<p>The setup is straightforward: given an array of floats, interpolate extra points so that the resulting interpolated data is distributed with a constant (or approximately constant) density.</p>
<p>Th... | <p>You want to sample y points instead of x points. Sampling y points is easy:</p>
<pre><code>d_interp = np.linspace(data.min(), data.max(), N)
</code></pre>
<p>Now you want to interpolate (y, x) instead of (x,y). You could try this, but this won't work:</p>
<pre><code>t = np.interp(d_interp, data, xp)
</code></pre>... | python|numpy|interpolation | 0 |
894 | 19,963,253 | using math function on an arange | <p>I have a function that I want to apply to an arange: </p>
<pre><code>import math
from numpy import arange
x = arange(7.0,39.0,0.0001)
fx = math.exp(-2.0 / (-14.4 + 19.33 * x - 0.057 * pow(x,2)))
</code></pre>
<p>The resulting error is as follows:</p>
<pre><code>`TypeError: only length-1 arrays can be converted ... | <p>Use Numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html" rel="nofollow"><code>exp</code></a> instead of <code>math</code>'s:</p>
<pre><code>>>> from numpy import arange, exp
>>> x = arange(7.0,39.0,0.0001)
>>> fx = exp(-2.0 / (-14.4 + 19.33 * x - 0.057 * po... | python|math|python-2.7|numpy | 6 |
895 | 72,094,230 | How to concat all columns in a multiindex dataframe? | <p>I have a multiindex df that I'm trying to concat.
The columns are:</p>
<pre><code>a.columns
MultiIndex([( 'Note', '507.3'),
( 'Note', '507.4'),
( 'Note', '507.5'),
( 'Note', '507.6'),
('Standard Deviation', '507.3'),... | <p>Firstly, may I suggest that you will be more likely to get an answer that is helpful for you, if you are clearer about what your expected output is.</p>
<p>However, based on your statement that:</p>
<p><code>pd.concat([a['Note']['507.3'],a['Note']['507.4'],a['Note']['507.5']], axis=1)</code></p>
<p>achieved what you... | python|pandas|dataframe | 1 |
896 | 72,004,269 | How to calculate minutes passed since given date | <p>I have a dataframe that has a column named <code>Created_Timestamp</code>. I want to see how many minutes passed since that given date. I want to know dwell time in minutes from the column <code>Created_Timestamp</code>.</p>
<pre class="lang-none prettyprint-override"><code> Created_Timestamp Dwell Time
20... | <pre><code>import pandas as pd
from datetime import datetime
curtime = datetime.now()
qqq = pd.to_datetime(df['Created_Timestamp'])
aaa = pd.to_datetime(curtime)
ttt = (aaa - qqq).dt.total_seconds()/60
df['Dwell Time'] = ttt
</code></pre>
<p>Output</p>
<pre><code> Created_Timestamp Dwell Time Dwell Time
0... | python|pandas|datetime|timedelta | 1 |
897 | 71,923,159 | How to get output_attentions of a pretrained Distilbert Model? | <p>I am using a pretrained DistilBert model:</p>
<pre><code>from transformers import TFDistilBertModel,DistilBertConfig
dbert = 'distilbert-base-uncased'
config = DistilBertConfig(max_position_embeddings=256 , dropout=0.2,
attention_dropout=0.2,
output_hidden_stat... | <p>I am posting the answer as @cronoik suggested: I modified the code as <code> dbert_model = TFDistilBertModel.from_pretrained('distilbert-base-uncased',config, output_attentions=True)</code> This gave both hidden states and attention in output.</p> | python|tensorflow|tf.keras|huggingface-transformers|distilbert | 0 |
898 | 16,652,663 | Building NumPy on RedHat | <p>I installed a local version of Python 2.7 in my home directory (Linux RedHat) under ~/opt using the --prefix flag.
More specifically, Python was placed in ~/home/opt/bin.</p>
<p>Now, I want to install NumPy, but I am not really sure how I would achieve this. All I found in the INSTALL.txt and online documentation w... | <p>Your local version of python should keep all of it's files somewhere in <code>~/opt</code> (presumably). As long as this is the python installation that gets used when you issue the command </p>
<pre><code>python setup.py build --fcompiler=gnu95
</code></pre>
<p>you should be all set because in the <code>sys</cod... | python|numpy|setup.py | 1 |
899 | 16,992,422 | For loop speed with Numpy | <p>I am trying to get this code running fast in python however I am having trouble getting it to run anywhere near the speed it runs in MATLAB. The problem seems to be this for loop which takes about 2 second to run when the number "SRpixels" is approximately equal to 25000.</p>
<p>I cant seem to find any way to trim ... | <p>Vectorization is almost always the best way to speed up numpy code, and much of this seems vectorizable. To start, for example, the location arrays seem quite simple to do:</p>
<pre><code># these are all of your j values
inds = np.arange(0,SRpixels)
# these are the j values you don't want to skip
sel = np.invert((... | python|numpy | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.