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
366,800
51,331,259
pandas converting Series to DataFrame without the "dtype" information
<p>I have a Series called Sizemode with the following structure: </p> <pre><code>In [1]:Sizemode Out[1]: 0 50000 1 248000 dtype: int64 </code></pre> <p>and while I am trying to create a dataframe out of it with the following line:</p> <pre><code>test = pd.DataFrame({'Most Frequent Size':[Sizemode...
<p><code>pd.DataFrame({'Most Frequent Size':[str(tuple(Sizemode.values))]})</code> will construct the dataframe without index error.</p> <p><code>str(tuple(Sizemode.values))</code> returns the comma-delimited string of values in <code>Sizemode</code>.</p>
pandas|dataframe|series
1
366,801
51,232,533
keyError when trying to drop a column in pandas.
<p>I want to drop some rows from the data. I am using following code-</p> <pre><code> import pandas as pd import numpy as np vle = pd.read_csv('/home/user/Documents/MOOC dataset original/vle.csv') df = pd.DataFrame(vle) df.dropna(subset = ['week_from'],axis=1,inplace = True) df.dropna(subset ...
<p>I think need omit <code>axis=1</code>, because default value is <code>axis=0</code> for remove rows with NaNs (missing values) by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>dropna</code></a> by subset of columns for check <code>NaN</co...
python|pandas|numpy
0
366,802
51,143,531
Combining nunique and where in pandas
<p>I am trying to find, for every id: the number of values equal to 0.0 and greater than 0.0</p> <p>Input DF:</p> <pre><code>ID . value 1 . 0.0 1 . 10.0 1 . 30.0 1 . 0.0 1 . 25.0 2 . 0.0 2 . 4.0 2 . 0.0 2 . 13.0 </code></pre> <p>Output DF:</p> <pre><code>id . count (value = 0...
<p>You can do with </p> <pre><code>pd.crosstab(df.ID,df.value.gt(0)) Out[392]: value False True ID 1 2 3 2 2 2 </code></pre>
pandas|pandas-groupby
3
366,803
51,322,688
How to utilize all GPUs when dealing with pytorch code?
<p>I have 2 GPUs and when I am working with pytorch code, only one GPU is used. I tried <code>CUDA_VISIBLE_DEVICES=0,1 python xxx.py</code>, but occurs </p> <blockquote> <p>'CUDA_VISIBLE_DEVICES: command not found'</p> </blockquote> <p>problems. I have also tried to add the following lines in object py file:</p> <...
<p>You need to parallelize the training data to each GPU seperatly. Data Parallelism is implemented using <code>torch.nn.DataParallel</code>. An example <a href="https://pytorch.org/tutorials/beginner/former_torchies/parallelism_tutorial.html" rel="nofollow noreferrer">from the pytorch documentation</a>:</p> <pre><cod...
python|gpu|pytorch
1
366,804
51,248,307
labels not contained in axis error - pandas dataframe
<p>I have a Dataframe named df which looks like - </p> <pre><code>pageno entity code rawentity 17727425 SAUDI CBCNTRY saudi 17727425 GARRA DRWRNAME garra 17727425 PO BOX RBCNTRY po box 17727425 NEW ZEALAND DRWRCNTRY new zealand </code></...
<p>When you're working with series you can use <code>pd.isin</code>. For example, what you want can be achieved by doing:</p> <pre><code>df = df[df['code'].isin(['DRWRCNTRY', 'RBCNTRY', 'CBCNTRY'])] </code></pre>
python|python-3.x|pandas|dataframe
1
366,805
51,130,283
Converting dtype('int64') to pandas dataframe
<p>Here's my data with type <code>dtype('int64')</code></p> <pre><code>Portugal 76 Germany 536 Argentina 637 </code></pre> <p>What I need is make it pandas dataframe with, I need this is pandas dataframe</p> <pre><code>Country Count Portugal 76 Germany 536 Argentina 637 </code></pre>
<p>I think input data are Series, so need:</p> <pre><code>df = df.reset_index() </code></pre>
python|pandas|dataframe
4
366,806
51,442,012
Python - Remove tuple from df column if present in another df column
<p>I have a function which removes a string from a df column, if the string is present in the column of another df:</p> <pre><code>df1['col'] = df1['col'][~df1['col'].isin(df2['col'])] </code></pre> <p>The problem is that I now have to use this function on a column of tuples, which the function does not work with. Is...
<p>This will give you desired output:</p> <pre><code>df1.loc[~df1['col1'].isin(df2['col'])].reset_index(drop=True) # col1 #0 (carol.clair, mark.taylor) #1 (andrew.french, jack.martin) #2 (ellis.taylor, sam.johnson) </code></pre>
python|pandas|tuples
1
366,807
51,295,136
Using the fillna() method from Pandas to replace a particular string value in a column
<p>I have a particular column(the column is called 'numbers') which outputs unique values like this:</p> <pre><code>df.numbers.unique() </code></pre> <p>Output: </p> <pre><code>([nan, '50', '22', '11', '46', '58', '22', '14', '18', '15', '33', 'XX'], dtype=object) </code></pre> <p>As seen above there are unidentifi...
<p>I think you just forget to assign it back </p> <pre><code>df.numbers=df.numbers.replace('XX',np.NaN) </code></pre>
python|pandas|numpy|data-structures
3
366,808
51,159,549
Avoiding indexing error when referencing next index while iterating
<p>So I have a pandas dataframe and I'm using iterrows() to iterate over each row do some complex stuff to it. Part of this involves subtracting the current's row's coordinates from the next's row's coordinates, so I do</p> <pre><code>sqrt(((row[5] - df.iloc[index+1, 5])**2) + ((row[4] - df.iloc[index+1, 4])**2)) &lt;...
<p>when row is last row your code tried to access a (row+1) which is not present, that's why you are getting indexing error.</p> <p>run a loop to iterate over all rows except last row, then when your code reaches to second last row it will access last row.</p> <p>try this code</p> <pre><code>for i in range(len(df.in...
python|pandas|indexing
0
366,809
51,140,916
Pandas DataFrame Advanced Indexing
<p>I am looking for some help with pandas DataFrame sorting. I have a Data frame of 8 columns that go like; </p> <blockquote> <pre><code>['Date' , 'S ID', 'Se ID', 'S #', 'File Size (Mb)', 'HD name', 'Start Time', 'End time'] </code></pre> </blockquote> <p>I've then done a: </p> <blockquote> <pre><code>DataFile.g...
<p>Okay, you need to use <code>pd.to_timedelta</code> with .str accessor:</p> <p>Where d equals to your df.head(10).to_dict() output:</p> <pre><code>df = pd.DataFrame(d) df['Start Time'] = pd.to_timedelta(df['Start Time'].str[0]) df['End Time'] = pd.to_timedelta(df['End Time'].str[0]) df_out = df.groupby(['Hard Dr...
python|pandas|dataframe|pandas-groupby
0
366,810
48,054,870
Python | pydub: how to load wav sample into pydub from np.array instead of a wav file?
<p>How would I load an audio <code>np.array</code> file into PyDub library? Currently, I use <code>AudioSegment.from_wav(file_path)</code>, but it is not convenient, if I already have the wav file loaded as a numpy array:</p> <pre><code>sample_rate, wav_sample = scipy.io.wavfile.read(file_path) </code></pre> <p>UPDAT...
<p>Ok, take this answer with a grain of salt as I don't know <code>pydub</code> enough to see if it's working properly, but you should be able to do it from the class initializer providing all the parameters it needs:</p> <pre><code>sample_rate, wav_sample = scipy.io.wavfile.read(file_path) segment = AudioSegment(dat...
python|arrays|numpy|wav|pydub
3
366,811
48,246,833
How to find increasing trend from a python list
<p>I want to print the increasing trend that I am getting between <strong>Jan and Mar, Sept to Dec.</strong> for the below provided data Can you please help me with the logic, please.</p> <p>I have tried the following code but its just not right:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt impo...
<p>You don't necessarily need all those imports for this.</p> <pre><code>trendList = [] trendStart = 0 trendEnd = 0 valuePrev = 0 count = 0 for value in count: count += 1 if count == 1: valuePrev = value trendStart = count elif valuePrev &lt;= value: #extend if equal or greater trend...
python-3.x|pandas-groupby
0
366,812
48,197,803
Preventing 1 level/value of pandas df column from being plotted
<p>I have just started using python for data visualization. I have searched google &amp; stackoverflow but was unable to find an answer to my problem. Hopefully you might be able to help:</p> <p>I have a pandas df with several data rows per person (id), and 2 other columns named StimCat (3 levels: A,B,C) &amp; rt (con...
<p>If you're not going to plot it, don't calculate it. Use <code>query</code>/boolean indexing/<code>eval</code>/<code>isin</code> and filter it out. </p> <pre><code>fig, ax = plt.subplots(figsize=(15,7)) df.query('StimCat != "C"')\ .groupby(['id','StimCat'])\ .mean()['rt']\ .unstack()\ .plot.bar(ax=ax) </co...
python|pandas|plot
1
366,813
48,212,397
Database with pandas: adding new data
<p>I have a lot of <code>Excel plains</code> and I load them using <code>pandas</code>, process the data and as an <code>output it writes all data in a Excel plain</code> that is my "database". </p> <p>The Database has to follow a pattern in the date index, e.g. <code>2017-01-01 (yyyy-mm-dd)</code>, 2017-01-02, 2017-0...
<p>Instead of using merge you can simple append and fill the NAN values with zero.</p> <pre><code>df1 date Name1 Name2 0 2017-01-01 23.2 18.4 1 2017-01-02 21.5 27.7 2 2017-01-03 0.0 0.0 3 2017-01-04 0.0 0.0 df2 date Name1 0 2017-01-04 32.5 df1.append(df2).fillna(0) N...
python|database|excel|pandas
1
366,814
48,232,626
pandas join gives NaN values
<p>I want to join 2 DataFrames</p> <p><em>Zipcode Database</em> (first 10 entries)</p> <pre><code> 0 zip_code City State County Population 0 0 90001 Los Angeles California Los Angeles 54481 1 1 90002 Los Angeles California Los Angeles 44584 2 2 90...
<p>You can cast <code>NaN</code> values to float types, but not int. In your case I would cast the <code>zip_code</code> field in both DataFrames to a float and then join.</p> <pre><code>zipcode_database.zip_code = zipcode_database.zip_code.astype(float) data.zip_code = data.zip_code.astype(float) data_2 = data.join(z...
python|python-3.x|pandas|join
2
366,815
48,019,798
slim import error with spyder: 'path' must be None or a list, not <class '_frozen_importlib_external._NamespacePath'>
<p>When I import slim with spyder:</p> <pre><code>import tensorflow.contrib.slim as slim </code></pre> <p>there is an error:</p> <blockquote> <pre><code>RuntimeError: 'path' must be None or a list, not &lt;class'_frozen_importlib_external._NamespacePath'&gt; </code></pre> </blockquote> <p><a href="https://i.stack.i...
<p>(<em>Spyder maintainer here</em>) This is a bug in Spyder that we'll fix in our <strong>3.2.7</strong> version, to be released on March 2018.</p> <p>Please take a look at <a href="https://github.com/spyder-ide/spyder/issues/5299" rel="nofollow noreferrer">this issue</a> for a temporary fix.</p>
python|tensorflow|deep-learning|spyder
1
366,816
48,280,389
Tensorflow: get predicted values from test samples
<p>I am trying to get the predicted values after training MLP and I do the following</p> <pre><code>sess.run(tf.argmax(labels_test, 1), feed_dict={X: data_test, dropout_keep_prob: 1.}) </code></pre> <p>Unfortunately, above line generate same result as this line</p> <pre><code>sess.run(tf.argmax(labels_test, 1)) </co...
<p><code>labels_test</code> is suspicious: it looks like the labels of your test data, <strong>not</strong> the labels <em>predicted</em> by your model. If this is the case, then it's not a function of <code>data_test</code> and there's no reason it should be any different a result. In short, the likely problem is th...
tensorflow|perceptron
0
366,817
48,105,485
How can I concat Dataframe?
hello <p>I make DataFrame like this:</p> <pre><code>index_date=pd.date_range('1/1/2000','31/12/2000', freq='H') </code></pre> <p><code>data=random.sample(range(8761),8761 )</code></p> <p><code>df= pd.DataFrame(data, index=index_date)</code></p> <p>I need to make the sum per month, but my code below doesn't works !...
<p>This will groupby each month.</p> <pre><code>df.groupby(df.index.month).sum() </code></pre>
python-3.x|pandas
0
366,818
48,100,954
Why does tf.matmul(a,b, transpose_b=True) work, but not tf.matmul(a, tf.transpose(b))?
<p>Code:</p> <pre><code>x = tf.constant([1.,2.,3.], shape = (3,2,4)) y = tf.constant([1.,2.,3.], shape = (3,21,4)) tf.matmul(x,y) # Doesn't work. tf.matmul(x,y,transpose_b = True) # This works. Shape is (3,2,21) tf.matmul(x,tf.transpose(y)) # Doesn't work. </code></pre> <p>I want to know w...
<p>Transpose can be defined differently for tensors of rank > 2, and here the difference is in axes that are transposed by <code>tf.transpose</code> and <code>tf.matmul(..., transpose_b=True)</code>.</p> <p>By default, <a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/transpose" rel="noreferrer"><...
python|tensorflow|deep-learning|linear-algebra|matrix-multiplication
5
366,819
48,160,696
Geo-coding - SyntaxError: can't assign to literal
<p>When running the last two lines, it reports an error message as follows:</p> <pre class="lang-none prettyprint-override"><code>File "&lt;stdin&gt;", line 32 SyntaxError: can't assign to literal </code></pre> <p>Any solution to this problem?</p> <pre><code>from geopy.geocoders import Nominatim geolocator = Nomin...
<pre><code>df=["Ycor"]=df["Coordinates"].apply(lambda x: x.latitude if x != None else None) </code></pre> <p>You have an extra <code>=</code> in there. I'm sure you meant:</p> <pre><code>df["Ycor"]=df["Coordinates"].apply(lambda x: x.latitude if x != None else None) </code></pre>
python|pandas|dataframe|literals
0
366,820
47,994,063
How do you divide a tensor based on its content?
<p>I have a tensor that looks like this:</p> <pre><code>arr = tf.convert_to_tensor([[3, 1], [6, 2], [1, 1], [3, 0], [5, 1], [1, 0], [4, 2]]) </code></p...
<p>So basically you want to</p> <ol> <li>write a conditional statement for matching second indices of each element.. I would try <code>tf.gather</code> and <code>tf.not_equal</code> (or equivalent functions) to filter the matching elements that return a matrix of the same shape as the input in (0,1) values and then mu...
python|python-3.x|tensorflow
2
366,821
48,117,562
How to exclude a class from MNIST in TensorFlow?
<p>I am new to TensorFlow and I am following the tutorial for beginners with MNIST data set and I want to train the model just with the 0-8 (excluding the class 9), so where in the code was 10, I replaced it to 9, but at the training part of code, how to ask the <code>next_batch()</code> to exclude the class 9 ? And if...
<p>You should pull the training data out of the mnist data object, dropping the class you want, and then proceed. First get the dataset without class <code>9</code> in it:</p> <pre><code>Xdata_no9 = np.array([x for (x,y) in zip(mnist.train.images,mnist.train.labels) if y[9]==0]) ydata_no9 = np.array([y[0:9] for y in ...
python|tensorflow|machine-learning|neural-network|mnist
1
366,822
48,410,530
Printing TensorFlow and NumPy values to stdout
<p>I have some problem with printing numpy.float32() value to stdout. Here is the code:</p> <pre><code>import numpy as np import tensorflow as tf n_samples = 1000 batch_size = 100 num_steps = 20000 x_data = np.random.uniform(1, 10, (n_samples, 1)) y_data = 2 * x_data + 1 + np.random.normal(0, 2, (n_samples, 1)) x =...
<p>You're seeing NaNs because the values in the network are exploding very quickly and become too large to fit in <code>float</code>. This explosion is caused primarily by your hyper-parameters:</p> <ul> <li><p><code>k</code> initial value is too large, reduce the standard deviation, e.g.:</p> <pre class="lang-py pre...
python|windows|numpy|tensorflow|nan
1
366,823
48,393,608
Pytorch network parameter calculation
<p>Can someone tell me please about how the network parameter (10) is calculated? Thanks in advance.</p> <pre><code>class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16*5*5, 12...
<p>Most layer modules in PyTorch (e.g. Linear, Conv2d, etc.) group parameters into specific categories, such as weights and biases. Each of the five layer instances in your network has a "weight" and a "bias" parameter. This is why "10" is printed.</p> <p>Of course, all of these "weight" and "bias" fields contain many...
deep-learning|conv-neural-network|pytorch
5
366,824
48,294,750
Pandas apply ValueError: bad input shape() when sending POST request
<p>I am trying to implement an API in a django framework with the following code below:</p> <pre><code>def worker_label_encoder(df,selected_col): le = LabelEncoder() enc = le.fit(np.unique(df[selected_col])) df[selected_col] = df[selected_col].apply(enc.fit_transform) </code></pre> <p>It works fine when I...
<p>There are few things wrong in you code.</p> <p>First apply function should have first argument as the value of column for which you have provided entire dataframe. </p> <p>Second why are you doing fit and then fit_transform. The standard flow is to either fit_transform or simple fit and transform. You should check...
python|django|pandas|postman
0
366,825
48,043,579
3d plot a simple data set with matplotlib
<p>Sorry if my question sounds s..., I am new to matplotlib. I have a simple dataset in pandas dataFrame, looks like this:</p> <pre><code> TAG_1 TAG_2 testTime 0 5 10, 10 758.2 1 5 16, 4 1738.1 2 5 4, 3 752.2 3 5 5,...
<p>Using this code </p> <pre><code>data = [ [758.2], [1738.1], [752.2], [868.9], [742.3] ] import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D df = pd.DataFrame(data) threedee = plt.figure().gca(projection='3d') threedee.plot(df.index, df.index, df[0]) plt.show() </code></pr...
pandas|matplotlib
1
366,826
48,173,168
Use both sample_weight and class_weight simultaneously
<p>My dataset already has weighted examples. And in this binary classification I also have far more of the first class compared to the second.</p> <p>Can I use both <code>sample_weight</code> and further re-weight it with <code>class_weight</code> in the <code>model.fit()</code> function?</p> <p>Or do I first make a ne...
<p>You can surely do both if you want, the thing is if that is what you <em>need</em>. According to the keras <a href="https://keras.io/models/model/" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <ul> <li><p><strong>class_weight:</strong> Optional dictionary mapping class indices (integers) to a weight (fl...
python|tensorflow|keras
14
366,827
48,269,152
Easily converting List of lists to numpy Multidim array for big data
<p>Let's say I have '3 deep' list of lists</p> <pre><code>len(list) --&gt; 500 len(list[0]) --&gt; 25 len(list[0][0]) --&gt; 100 </code></pre> <p>and I wanted to convert into a numpy array with the shape of (500, 25, 100). What would be the most efficient way of going about this computationally? assuming the list is ...
<p>Your list:</p> <pre><code>l = [[[1,2],[3,4]],[[5,6],[7,8]],[[9,10],[11,12]]] </code></pre> <p>Your numpy array:</p> <pre><code>arr = np.array(l) #array([[[ 1, 2], # [ 3, 4]], # # [[ 5, 6], # [ 7, 8]], # # [[ 9, 10], # [11, 12]]]) </code></pre>
python|arrays|numpy|bigdata
0
366,828
48,111,998
Is there a way to only detect objects with width > 200px in tensorflow?
<p>Is there a way filter object detection with width?</p> <p>Assuming that I have to detect apples with WIDTH > 100 Pixels. Is there a build-in tensorflow function to do that? or do I have to condition the code myself before drawing the bounding box?</p>
<p>The nice thing about applying object detection with a convolutional neural network is its ability to detect objects with an invariance against the size of the object. So the way to solve your problem would be to get the predicted bounding boxes and only accept the ones, that have a width > 100 pixels. </p> <p>Here ...
object|tensorflow|detection|object-detection
0
366,829
48,296,977
Python Pandas DataFrame: combining columns in order providing average values
<p>I have a dataframe as below. I want to combine 4 columns in order and have new df with average of it's values. Please see for detail.</p> <pre><code>a = np.random.randint(5, size=(2, 24)) df = pd.DataFrame(a,index=['alpha','bravo']) df: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16...
<p>You need floor divide array created by <code>np.arange</code> with groupby and aggregate <code>mean</code>:</p> <pre><code>a = np.arange(0, len(df.columns)) // 4 * 4 print (a) [ 0 0 0 0 4 4 4 4 8 8 8 8 12 12 12 12 16 16 16 16 20 20 20 20] df = df.groupby(a, axis=1).mean() print (df) 0 4 8...
python|pandas|dataframe|average
3
366,830
48,079,856
Binary operation in numpy
<p>I Have an array which looks like this,</p> <pre><code>array([[[-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], ..., [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024...
<p>Astype int of boolean will give you want you want i.e </p> <pre><code>arr = np.array([[[-1024, -1024, -1024, 0, -1024, -1024, -1024], [-1024, -1024, -1024, 150, -1024, -1024, -1024], [-1024, -1024, -1024,300, -1024, -1024, -1024]]]) (arr&gt;100).astype(int) array([[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, ...
python|numpy
6
366,831
48,164,040
Error running tensor flow model `TypeError: __init__() got an unexpected keyword argument 'file'`
<p>I'm trying to install tensorflow Object Detection API. I have followed all the installations steps as of <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md" rel="nofollow noreferrer">here</a>. However, when I tried running <code>python3 object_detection/builders...
<p>Just found out this is due to the version mismatch of one of the dependency which is protobuf, it must be 2.6.0 for it to compile the correct python file to support the model</p>
python|python-3.x|tensorflow|object-detection-api
0
366,832
48,176,993
How to convert a dataframe into a 2D array in-order to run some calculations?
<p>I have the following pandas dataframe:</p> <pre><code> timestamp close .. .......... ........ ........ 86 2017-03-12 14:00:00 0.000077 87 2017-03-12 16:00:00 0.000076 88 2017-03-12 18:00:00 0.000074 89 2017-03-12 20:00:00 0.000073 90 2017-03-12 22:00:00 0.000077 .. .......... ........ ..........
<p>You pretty much just need the <code>df.values</code> attribute, although you need to deal with the times first:</p> <pre><code># Make a dataframe df = pd.DataFrame(data=dict(timestamp=['2017-03-12 14:00:00', '2017-03-12 16:00:00', '2017-03-12 18:00:00', '2017-03-12 20:00:00', '2017-03-12 22:00:00'], close=[0.000077...
python|pandas|numpy
3
366,833
48,309,631
TensorFlow - tf.data.Dataset reading large HDF5 files
<p>I am setting up a TensorFlow pipeline for reading large HDF5 files as input for my deep learning models. Each HDF5 file contains 100 videos of variable size length stored as a collection of compressed JPG images (to make size on disk manageable). Using <code>tf.data.Dataset</code> and a map to <code>tf.py_func</code...
<p>I stumbled across this question while dealing with a similar issue. I came up with a solution based on using a Python generator, together with the TF dataset construction method <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator" rel="noreferrer"><code>from_generator</code></a>. Becau...
python|video|tensorflow|hdf5|tensorflow-datasets
26
366,834
48,070,320
Changing boolean value within a DataFrame iterrows does nothing
<p>The general idea is:</p> <ol> <li>Read a DataFrame from Excel</li> <li>Add a new column where I can identify valid and invalid rows (in this example, values are initialized at <code>None</code>, but I've also tried initializing at <code>False</code> and <code>0</code>)</li> <li>Iterate through DataFrame and assign ...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows.html" rel="nofollow noreferrer"><code>Dataframe.iterrows()</code></a> returns a Series which is a copy of the data. It can not be used to update the underlying DataFrame. Instead I suggest just building a list, and adding it t...
python|python-3.x|pandas
1
366,835
48,059,994
Mark Empty values in Pandas DataFrame Multi-Row Header
<p>I have a CSV file called <strong>mrh.csv</strong> which has first two rows representing the header:</p> <pre><code>Name,Height,Age "",Metres,"" A,-1,25 B,95,-1 </code></pre> <p>I am using the following code to read it into DataFrame:</p> <pre><code>import pandas as pd pd.read_csv('mrh.csv', header=[0,1], na_value...
<p>You can create new MultiIndex and assign to <code>columns</code>:</p> <pre><code>df = pd.read_csv('mrh.csv', header=[0,1], na_values=[-1,'']) a = df.columns.get_level_values(level=0) b = df.columns.get_level_values(level=1).str.replace('Un.*','') df.columns = [a, b] print (df) Name Height Age Metres ...
python|pandas|csv|dataframe
1
366,836
48,117,704
How to transform Byte[](decoded as PNG or JPG) to Tensorflows Tensor
<p>I'am trying to use Tensorflowsharp in a Project in Unity.</p> <p>The problem i'm facing is that for the transform you usually use a second Graph to transform the input into a tensor. The used functions DecodeJpg and DecodePng are not supported on Android so how can you transform that input into a tensor ? </p> <pr...
<p>Instead of feeding the byte array and then use DecodeJpeg, you could feed the actual float array, which you can get like this:</p> <p><a href="https://github.com/tensorflow/tensorflow/blob/3f4662e7ca8724f760db4a5ea6e241c99e66e588/tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowImageClassifier.java#L13...
c#|android|opencv|tensorflow|tensorflowsharp
5
366,837
48,428,732
How can I remove non characters from a dataframe? python beautiful soup
<p>I have a dataframe</p> <p>df</p> <pre><code> ID col1 1 The quick brown fox jumped hf_093*&amp; 2 fox run jump *&amp; #7 </code></pre> <p>How can I parse out non-characters in this dataframe?</p> <p>I tried this but it doesn't work </p> <pre><code>posts = ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-...
<p>If what you're looking for is removing the strings that contains special characters:</p> <p><strong>Regex:</strong></p> <pre><code>df.applymap(lambda x: re.sub("(?:\w*[^\w ]+\w*)", "", x).strip()) </code></pre> <p><strong>Output:</strong></p> <pre><code> 0 0 The quick brown fox jumped...
python|regex|pandas
2
366,838
48,215,909
Time Series Analysis for Individual Customers
<p>I a time series data for 1000 customers regarding the number of purchases they made in the last 2 years. I am able to build the time series forecasting model for the entire dataset. But now I want to build the forecasting model for the each of the 1000 customers, what is the best approach to solve this problem.</p> ...
<p>First , create a function <code>def Forecast(costumer_id,prediction_date): df_customer = df[df['customer_id']==customer_id] do forecasting on df_customer return forecast for customer and prediction_date</code> then use the Pool method of multiprocess library to parallel process the customers:</p> <p>...
python|pandas|time-series|forecasting|arima
0
366,839
48,219,986
DecisionTreeClassifier predict_proba returns 0 or 1
<p>I m trying to use the decision tree classified to identify two classes (renamed 0 and 1) based on certain parameters. I train it using a dataset and then run it on the "test dataset". When I try to calculate the probability for each data point in the test dataset, it returns 0 or 1, only. I wonder what is the proble...
<p>There is no problem - the tree behaves exactly as expected.</p> <p>A decision tree computes the class probability from the number of samples of each class that fall into a given leaf.</p> <p>The <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html" rel="nofollow noreferr...
python|decision-tree|roc|sklearn-pandas
10
366,840
48,169,184
change the value of a numpy array to a different data type
<p>I have the following code that seeks to change the number 4 on the matrix (if 4 is rolled) to an 'x'. This can be done with Python lists, but numpy arrays require the same data type. Is there a workaround, that allows me to achieve the same result?</p> <p><strong>Code</strong></p> <pre><code>import numpy as np m...
<p>With NumPy's masked array utility, you can probably achieve the same functionality, as follows:</p> <pre><code>In [1]: matrix = np.ma.array([[9,10,11,12],[8,7,6,5],[1,2,3,4]]) In [2]: matrix Out[2]: masked_array(data = [[ 9 10 11 12] [ 8 7 6 5] [ 1 2 3 4]], mask = False, fill_value = ...
python|numpy|types
1
366,841
48,253,759
Pandas dataframe. Group by value and count
<p>I have the following table:</p> <pre><code>Days, Age, Sex 5, 39, F 4, 54, M 4, 26, M 5, 42, M 4, 29, M </code></pre> <p>I want to count number of rows with F and M separately. The following command works, but I'm not OK with the representation:</p> <pre><code>df.groupby("Sex").count() <...
<p>Just to add to Wen's answer. Alternatively, you can use <code>value_counts</code> while selecting the column with <code>df.Sex</code>.</p> <pre><code>df.Sex.value_counts() M 4 F 1 Name: Sex, dtype: int64 </code></pre>
python|pandas|dataframe|pandas-groupby
7
366,842
48,079,043
find new exporting destinies: Data science - groupby and isin
<p>For the df below i want to discover the new destinies which these firms (<code>id</code> correspond to a firm) are exporting in 2016 in relation to 2015.</p> <pre><code>df = pd.DataFrame({"Id":[1,1,1,1,1,1,2,2,2,3,3], "Year":[2015,2015,2016,2016,2016,2016,2015,2016,2016,2015,2016], "...
<p>IIUC:</p> <pre><code>df.sort_values(by=['Id','Year']).drop_duplicates(subset=['Id'], keep='last') </code></pre> <p>Output:</p> <pre><code> Destiny Id Year 5 D 1 2016 8 D 2 2016 10 Z 3 2016 </code></pre>
python|pandas|group-by
3
366,843
48,170,954
Return first column in DataFrame as a list of string values
<p>how can I return a list of string values for first column (State) from below DataFrame?</p> <pre><code> Population State County California Los Angeles County 9818605 Illinois Cook County 5194675 Texas Harris County 4092459 </code></pre>
<p>last bit is solved: converting index to list with: df.index.get_level_values(0).tolist()</p> <p>Many thanks for your help! Peter</p>
python|pandas|dataframe
0
366,844
48,333,310
No output shown after reading a .txt file using Pandas in Python
<p>I am using python version 3.6.3 and installed pandas recently.</p> <p>I have created a file test.txt. 2 columns (tab separated). File &amp; code is saved in the same directory.</p> <pre><code>1 Samsung 2 Nokia 3 iPhone </code></pre> <p>When I run the code the output is blank (no error/warning). What did I d...
<p>Need to print it like this:</p> <pre><code>import pandas as pd df = pd.read_table('a.txt', sep='\t', header=None, names=["Sl.", "Name"]) print('The dataframe is {}'.format(df.head())) </code></pre>
python-3.x|pandas
0
366,845
48,131,371
Optimizing python code - filtering numpy arrays
<p>I have a big number of coordinates in 2 arrays (HLat22 and HLong22) and I've also got a LineString. The output is in indices - there is an array full of True/False that shows me the coordinates in HLat22/HLong22 that are in a certain threshold to the coordinates on my LineString ( my example is 0.005) . On the examp...
<p><strong>Often algorithmics beat low-level optimizations</strong> (e.g. binary-search vs. linear-search; the former better for big n; the latter better for small n).</p> <p>Without much experience with this area and totally ignoring the numbers you gave, here some demo you should try out! <strong>You will have to do...
python|arrays|numpy|coordinates
2
366,846
48,294,013
How to store my own class object into hdf5?
<p>I created a class to hold experiment results from my research (I'm an EE phd student) like </p> <pre><code>class Trial: def __init__(self, subID, triID): self.filePath = '' # file path of the folder self.subID = -1 # int self.triID = -1 # int self.data_A = -1 # numpy arra...
<p>Here's a small class that I use for saving data like this. You can use it by doing something like..</p> <pre><code>dc = DataContainer() dc.trials = &lt;your list of trial objects here&gt; dc.save('mydata.pkl') </code></pre> <p>Then to load do..</p> <pre><code>dc = DataContainer.load('mydata.pkl') </code></pre> ...
python|numpy|hdf5|h5py
3
366,847
48,210,199
Python 3 Pandas Timestamp Date Parse
<p>I have some time series data from an API request and when I am doing some data wrangling this error pops up below. The data wrangling is just some simple Pandas series math (not shown). </p> <p><em>TypeError: unsupported operand type(s) for -: 'str' and 'str'</em></p> <p>But when I save the data to a CSV:</p> <p...
<p>Not sure what code you are running to generate that error. However the time stamp probably needs to be converted from a string to a date time. Try using pd.to_datetime, additionally you can specify the format (list of options and meanings are provided below). The example I used for the format is year-month-day hour-...
python-3.x|pandas|csv|datetime|timestamp
1
366,848
48,013,201
Median-based linear regression in Python
<p>I would like to perform one-dimensional linear regression by minimizing the median absolute error.</p> <p>While initially assuming that it should be a fairly standard use case, a quick search surprisingly revealed that all regression and interpolation functions use the mean squared error.</p> <p>Therefore my quest...
<p>As already pointed out in the comments, even though what you are asking for in itself is well-defined, the proper approach to its solution will depend on the properties of your model. Let's see why, let's see how far a generalist optimization approach gets you, and let's see how a bit of math may simplify the proble...
python|pandas|numpy|scipy|linear-regression
15
366,849
48,592,876
'NoneType' object is not subscriptable within OrderedDict - pandas dataframe
<p>I'm trying to pull out information from an ordered dictionary into a pandas dataframe. The ordered dict is from a query into a database. In order to upload information back into the database and manipulate it, I need it to be in a pandas dataframe format.</p> <p>I have been using the following method to turn the or...
<p>You can have a helper function.</p> <pre><code>def helper(x, attribute): return None if x is None else x[attribute] df = pd.DataFrame( dict(Id = rec['Id'], UserRole = helper(rec['UserRole'], "Name")) for rec in x) </code></pre>
python|pandas|dictionary|dataframe|ordereddictionary
3
366,850
48,700,046
Effective way to store list of list of dict to csv
<p>I've got dataframe like this :</p> <pre><code>Name Nationality Tall Age John USA 190 24 Thomas French 194 25 Anton Malaysia 180 23 Chris Argentina 190 26 </code></pre> <p>so let say i got incoming data structure like this. each element representing the...
<p>You need <a href="https://stackoverflow.com/q/48700710/2901002">flatenning dictionaries</a> first, create <code>DataFrame</code> and join to original:</p> <pre><code>data = [{ 'a':{'lunch':'Apple', 'breakfast':'Milk', 'dinner':'Meatball'}, 'b':{'favourite':'coke', ...
python-2.7|pandas|csv
0
366,851
48,514,347
Combination of Map and Integration
<p>This is the equation that I'm trying to plot, but have not been successful for hours. XA is variable between 0 to 1. I'd like to plot it while I'm varying eA and n constants. I'm still learning Python and this is being too complicated for me. Any help will be very appreciable. </p> <p><a href="https://i.stack.imgur...
<p>You need to evaluate the functions in order to use them in further calculations. Also make sure to supply the needed arguments to the functions.</p> <p>Here would be an example:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.integrate import quad bracket = lambda eA,XA,n: ((1+eA*XA)/...
python|numpy|matplotlib
1
366,852
48,824,890
Replace words in pandas Dataframe using dictionary
<p>I have a pandas dataframe </p> <pre><code>id text 1 acclrtr actn corr cr 2 plate corr aff 3 alrm alt </code></pre> <p>and dictionary</p> <pre><code>dict={'acclrtr':'accelerator','actn':'action','corr':'corrosion','cr':'chemical resistant','aff':'affinity','alrm':'alarm','alt':'alternate'} </code></pre> <p...
<p><strong>UPDATE:</strong></p> <pre><code>In [108]: data Out[108]: id text 0 1 acclrtr actn corr cr 1 2 plate corr affinity # NOTE: `affinity` 2 3 alrm alt In [109]: d2 = {r'(\b){}(\b)'.format(k):r'\1{}\2'.format(v) for k,v in d.items()} In [110]: d2 Out[110]: {'(\\b)accl...
python-3.x|pandas|dictionary|dataframe|replace
9
366,853
48,693,587
Implement Embedding Dropout in Tensorflow
<p>I am reading this paper on "<a href="https://arxiv.org/pdf/1708.02182.pdf" rel="nofollow noreferrer">Regularizing and Optimizing LSTM Language Models</a>" and they talk about <code>Embedding Dropout</code> which says "As the dropout occurs on the embedding matrix that is used for a full forward and backward pass, th...
<p>You can use embedding dropouts like this..</p> <pre><code>with tf.variable_scope('embedding'): self.embedding_matrix = tf.get_variable( "embedding", shape=[self.vocab_size, self.embd_size], dtype=tf.float32, initializer=self.initializer) with tf.name_scope("embedding_dropout"): self.embedding_matrix = tf.nn....
python|tensorflow
2
366,854
48,493,726
how can i get a column of multilevel index after pivot_table in pandas?
<p>dataframe:</p> <pre><code>df = pd.DataFrame({ 'date': [1,1,2,2,3,4,4], 'id': [1,1,1,2,2,2,3], 'item': [200,201,200,333,334,334,444], 'buy': [1,1,2,5,4,0,1] }) df = df[['date','id','item','buy']] date id item buy 0 1 1 200 1 1 1 1 201 1 2 2 1 200 2 3 2 2 ...
<p>For <code>pivot</code> , you can point out <code>values</code>, then you will received what you need </p> <pre><code>df.pivot_table(index=['id','item'], columns=['date'], values='buy',aggfunc='sum', fill_value=0).reset_index() Out[64]: date id item 1 2 3 4 0 1 200 1 2 0 0 1 1 201 1 0 0...
python|pandas
1
366,855
48,860,704
Pandas: Remove limited duplicates
<p>So, I have a file that gets generated at runtime. A sample of the file looks like this:</p> <pre><code>ID,Class_id,Column_A,Column_B,Column_C,Column_D,Mask 1,987,vermont,CA,450,liase,2 2,456,WB,cloo,452,var,1 3,987,CA,Cp,1000000,liase,2 4,456,SA,Cap,98376,clop,1 5,765,IN,clas,543,king,2 6,987,SA,CLA,200,loop,2 7,45...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with mask comparing <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noref...
python|python-2.7|pandas
1
366,856
48,744,666
Tensorflow Object Detection API 1-channel image
<p>Is there any way to use pre-trained models in Object Detection API of Tensorflow, which trained for RGB images, for single channel grayscale images(depth) ?</p>
<p>I tried the following approach to perform object detection on Grayscale (1 Channel images) using a pre-trained model (faster_rcnn_resnet101_coco_11_06_2017) in Tensorflow. It did work for me.</p> <p>The model was trained on RGB Images, So I just had to modify certain code in <a href="https://github.com/tensorflow/m...
tensorflow|object-detection|depth
4
366,857
48,796,169
How to fix ipykernel_launcher.py: error: unrecognized arguments in jupyter?
<p>I am following this tensorflow <a href="https://www.tensorflow.org/get_started/get_started_for_beginners" rel="noreferrer">tutorial</a> after two days setting up the environment I finally could run <code>premade_estimator.py</code> using cmd</p> <p><a href="https://i.stack.imgur.com/DmlmX.png" rel="noreferrer"><img...
<p>A more elegant solution would be:</p> <pre><code>args, unknown = parser.parse_known_args() </code></pre> <p>instead of </p> <pre><code>args = parser.parse_args() </code></pre>
python|python-3.x|tensorflow|jupyter-notebook|jupyter
59
366,858
48,890,688
How do I handle these pandas error messages?
<p>Often when using pandas I get UserWarning and PerformanceWarning messages like these:</p> <pre><code>C:\Users\User\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py:558: UserWarning: merging between different levels can give an unintended result (2 levels on the left, 1 on the right) warnings.warn(msg, Use...
<p>One approach that I often use is to configure the <code>filterwarnings()</code> method in the <code>warnings</code> package to filter the warnings to raise which will enable you to debug them (e.g., using <code>pdb</code>). To do this you just need to <code>import</code> the <code>warnings</code> package and then se...
python-3.x|pandas
3
366,859
48,863,427
Tensorflow c api trace data
<p>I wanted to know how can I get FULL_TRACE Data from Session run using C API Tensorflow. My problem is I found python example but I don't know how to implement it with C API .</p> <p>python example :</p> <h1>Run the graph with full trace option</h1> <pre><code>with tf.Session() as sess: run_options = tf.RunO...
<p>If you ask, how to put options to your TF_SessionRun. This is a work-around to extract them from Python and use them in C-API.</p> <p>PYTHON</p> <pre><code>runOptions = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) runConfig = tf.ConfigProto(run_options=runOptions) # run_options? runConfSer = [int(i) for in ...
tensorflow|profiler|c-api
1
366,860
48,835,129
Filling Nan Values in Multi-Index Groupby Object
<p>I'm trying to create a multi-index groupby object that takes email domains and finds the percent change by month. I'm running into issues when an observation is absent for a given month. </p> <p><strong>Original Dataframe</strong></p> <pre><code>tracking_df = tracking_df[['transaction_mm_yy', 'ST_Email_Domain', 'i...
<p>There is the way </p> <pre><code>s.unstack().stack(dropna=False).fillna(0) Out[774]: transaction_mm_yy ST_Email_Domain 2017-10 AOL.COM 0.0 GMAIL.COM 31.0 HOTMAIL.COM 2.0 MAIL.COM 3.0 ...
python|python-3.x|pandas|pivot-table
1
366,861
48,777,573
joint probability with a condition
<p>I am working with wind speed (sknt) and visbility (vsby) data in hourly intervals from weather stations. I was able to calculate the joint probability for both wind speed and visibility using this, </p> <pre><code>df1=df.groupby('vsby').size().div(len(df)) df2=df.groupby(['vsby', 'sknt']).size().div(len(df)).div(v...
<p>Try the below. To select a column using <code>.loc</code> it is sufficient to just provide the name.</p> <pre><code>df2 = df2.reset_index() df2.loc[df2['sknt'] &gt;= 7, 'vsby'].sum() </code></pre>
python|pandas|pandas-groupby
0
366,862
48,756,599
How to modify LoggingTensorHook formatter?
<p>sing standard implementation of the cnn given in <a href="https://www.tensorflow.org/tutorials/layers" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/layers</a>, during the training results are shown with the tensor hook defined as follows</p> <pre><code># Set up logging for predictions tensors_to...
<p>You just need to pass what to print in the tensors dictionary for the hook.</p> <p>Best, -Tony</p> <pre><code>last_step = 1000 def formatter_log(tensors): """ Format the log output """ logstring = "Step {} of {}: " \ " training Dice loss = {:.4f}," \ " training Dice = {...
tensorflow|hook|formatter
0
366,863
48,874,639
Bokeh not displaying plot for pandas
<p>I can't get Bokeh to display my plot. This is my Python code.</p> <pre><code>import pandas as pd from bokeh.plotting import figure, ColumnDataSource from bokeh.io import output_file, show if __name__ == '__main__': file = 'Overview Data.csv' overview_df = pd.read_csv(file) overview_ds = ColumnDataSour...
<p>Bokeh does not know what to do with those string dates unless you tell it. There are two basic possibilities:</p> <ul> <li><p>Keep them as strings, and treat them as categorical factors. You can do that by telling Bokeh what the factors are when you create the plot:</p> <pre><code>p = figure(plot_width=400, plot_h...
python|pandas|dataframe|plot|bokeh
4
366,864
48,622,775
Row wise calculations(Python)
<p>Trying to run the following code to create a new column 'Median Rank':</p> <pre><code>N=data2.Rank.count() for i in data2.Rank: data2['Median_Rank']=i-0.3/(N+0.4) </code></pre> <p>But I'm getting a constant value of 0.99802. Even though my rank column is as follows:</p> <pre><code>data2.Rank.head() Out[464]: ...
<p>Your code isn't vectorised. Use this:</p> <pre><code>N = data2.Rank.count() data2['Median_Rank'] = data2['Rank'] - 0.3 / (N+0.4) </code></pre> <p>The reason your code does not work is because you are assigning the <em>entire</em> column in <em>each</em> loop. So only the last <code>i</code> iteration sticks, value...
python|pandas
1
366,865
48,690,234
Min of Str Column in Pandas
<p>I have a dataframe where one column contains a list of values, e.g.</p> <pre><code>dict = {'a' : [0, 1, 2], 'b' : [4, 5, 6]} df = pd.DataFrame(dict) df.loc[:, 'c'] = -1 df['c'] = df.apply(lambda x: [x.a, x.b], axis=1) </code></pre> <p>So I get:</p> <pre><code> a b c 0 0 4 [0, 4] 1 1 5 [1, 5] 2 2 ...
<p>You can get help from numpy:</p> <pre><code>import numpy as np df['d'] = np.array(df['c'].tolist()).min(axis=1) </code></pre> <p>As stated in the comments, if you don't need the column <code>c</code> then:</p> <pre><code>df['d'] = df[['a','b']].min(axis=1) </code></pre>
python|pandas
3
366,866
48,556,510
how can i delete whole day rows on condition column values.. pandas
<p>i have below times series data frames</p> <p>i wanna delete rows on condtion (check everyday) : check aaa>100 then delete all day rows (in belows, delete all 2015-12-01 rows because aaa column last 3 have 1000 value)</p> <pre><code> .... date time aaa 2015-12-01,00:00:00,0 2015-12-01,00:15:00,0 201...
<p>I think you need if <code>MultiIndex</code> first compare values of <code>aaa</code> by condition and then filter all values in first level by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>, last filter again by <a href...
python|pandas|time-series|row
1
366,867
48,558,918
Remove Column name in a dictionary generated via Pandas
<p>I have a dataframe in Pandas with two columns 'page_id' and 'access_time'. Each page_id could have multiple access_time values Using the following code:</p> <pre><code>df.groupby('page_id').apply(lambda dfg: dfg.drop('page_id', axis=1).to_dict(orient='list')).to_dict() </code></pre> <p>I got the output as a neste...
<p>Without looking into the logic of your code. The following can produce your desired output:</p> <pre><code>result = ( df.groupby('page_id') .apply(lambda dfg: dfg.drop('page_id', axis=1).to_dict(orient='list')) .apply(lambda x: x['accessed_time']) .to_dict() ) result Out[63]: {1: [20171223, 201...
python|pandas
2
366,868
48,472,277
Housing dataset from Hands On Machine Learning with Sci-Kit Learn & Tensorflow does not display when I try to recreate it
<p>I am trying to recreate the housing dataset/code from the book by using the code below. For some reason I get the error that is displayed all the way in the end</p> <pre><code>In [32]: import os import tarfile from six.moves import urllib In [37]: DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-...
<p>import pandas as pd fetch_housing_data()</p> <p>After importing the pandas. Just call the function fetch_housing_data(). This should fix the problem.</p> <p>The book has similar mistakes where author has forgot to add a line or two.</p>
python-3.x|pandas|numpy|machine-learning
2
366,869
48,490,541
Reshape dataframe by string variable
<p>I have a dataframe as below</p> <pre><code>df = pd.DataFrame({'a': ['aaa\nbbb\nccc','ddd\nfff\nggg'], 'b':[1,2]}) df </code></pre> <p>I want to get</p> <pre><code> a b 0 aaa 1 1 bbb 1 2 ccc 1 3 ddd 2 4 fff 2 5 ggg 2 </code></pre> <p>I understand how to make it in <code>R</code> with <code>librar...
<p>Use:</p> <pre><code>df = (df.set_index('b')['a'] .str.split('\n', expand=True) .stack() .reset_index(level=1, drop=True) .reset_index(name='a') .reindex(columns=df.columns)) print (df) a b 0 aaa 1 1 bbb 1 2 ccc 1 3 ddd 2 4 fff 2 5 ggg 2 </code></pre> <p>Alt...
python|pandas
2
366,870
48,631,131
Encoding lemmas for use in Affinity Propagation/Finding natural clusters in text data
<p>I have a dataframe that several columns of lemmatized text (multiple paragraphs worth of text per row - not categorical), plus some other int, datetime, and float columns. I'd like to use the text for Affinity Propagation, to find clusters within the data. sklearn.cluster.affinitypropagation doesn't work with text d...
<p>Not sure your level of understanding, so I'm going to try to be pretty verbose.</p> <p>Check out the <code>from sklearn.feature_extraction.text import TfidfVectorizer</code></p> <p>TFIDF stands for Term Frequency Inverse Document Frequency. (A bit of a misnomer, I might have chosen Term Frequency Inverse Corpus F...
python|python-3.x|pandas|scikit-learn
-1
366,871
48,797,880
Unexpected Result When Filtering PANDAS DF Row
<p>I typically filter a pandas DataFrame using the following syntax:</p> <pre><code>FDF = DF[DF['Color'] == 'Blue'] </code></pre> <p>I expect to see a result where FDF, which is my filtered DataFrame returns just the rows where the color column is set to blue. Instead, I get something like this. Funny thing is, the...
<p>Not sure I understand the negative ratings on this question. However, I was able to work around the issue by assigning a new index and renaming the columns.</p>
python|pandas
0
366,872
48,670,877
Write multiple dataframes to a single text file without any delimiters
<p>I have 5 different data frames that I'd like to output to a single text file one after the other. </p> <p>Because of my specific purpose, I do not want a delimiter.</p> <p>What is the fastest way to do this?</p> <p>Example: Below are 5 dataframes. Space indicates new column. </p> <pre><code> 1st df AAA 1 2 3 4...
<p>to gather some data frame in single text file do:</p> <pre><code>whole_curpos = '' #read every dataframe for df in dataframe_list: #gather all the column in a single column df['whole_text'] = df[col0].astype(str)+df[col1]+...+df[coln] for row in range(df.shape[0]): whole_curpos = whole_curpos + df['whole_t...
python|pandas|dataframe|text|export
0
366,873
48,509,732
Amazon Web Services: -bash: activate: No such file or directory
<p>I'm trying to use <code>Deep Learning AMI (Ubuntu)</code> on Amazon Web Services (AWS). When you login, you get a message as follows (I'm showing part of it here):</p> <pre><code>Please use one of the following commands to start the required environment with the framework of your choice: for MXNet(+Keras1) with Pyt...
<p>A little late over here, but is anaconda installed in the instance. If so please try</p> <pre><code>conda activate tensorflow_p36 </code></pre>
python|bash|amazon-web-services|tensorflow
0
366,874
48,521,986
deleting characters between two different keywords
<p>i have a string like below.</p> <p>stg = "Abel read (reading)|book(peripheral)~Q27.8#basillary NEC~Q28.1|| "</p> <h2>Requirement:</h2> <p>Need to delete the character between two keywords ~ and # and then print the remaining.</p> <h2>Output:</h2> <p>"Abel read (reading)|book(peripheral)basillary NEC~Q28.1|| "</...
<p>Using <strong><a href="https://www.programiz.com/python-programming/methods/string/find" rel="nofollow noreferrer">string.find</a></strong> method</p> <pre><code>stg = "Abel read (reading)|book(peripheral)~Q27.8#basillary NEC~Q28.1|| " start = stg.find( '~' ) end = stg.find( '#' ) if start != -1 and end != -1: ...
python-3.x|pandas|pandas-groupby
0
366,875
48,643,604
importing CSV file with values wrapped in " when some of them contains " as well as commas
<p>I think I searched throughout but if I missed something - let me know please.</p> <p>I am trying to import CSV file where all non numerical values are wrapped with ". I have encountered a problem with: </p> <pre><code> df = pd.read_csv(file.csv) </code></pre> <p>Example of CSV:</p> <pre><code>"Business focus","C...
<p>This seems like badly formed CSV data as the '"' characters within the values should be escaped. I've often seen such values escaped by doubling them up or prefixing with a \. See <a href="https://en.wikipedia.org/wiki/Comma-separated_values#cite_ref-13" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Comma-...
python|pandas|csv|quotes
2
366,876
48,632,273
How to encode inputs like artist or actor
<p>I am currently developing a neural network that tries to make a suggestion for a specific user based on his recent activities. I will try to illustrate my problem with an example.</p> <p>Now, let's say im trying to suggest new music to a user based on the music he recently listened to. Since people often listen to ...
<p>The approach you describe is called <a href="https://en.wikipedia.org/wiki/Recommender_system#Content-based_filtering" rel="nofollow noreferrer">content-based filtering</a>. The intuition is to recommend items to customer A similar to previous items liked by A. An advantage to this approach is that you only need dat...
tensorflow|machine-learning|neural-network|deep-learning|artificial-intelligence
0
366,877
48,793,892
Is there a faster way of combining functions containing mpf (mpmath floats) with numpy arrays?
<p>I was having problems with the accuracy of floats in Python. I need high accuracy because I want to use explicitly written spherical bessel functions J_n (x), which deviate (especially for n>5) from their theoretical values at low x values if <code>numpy</code> floats are used (15 precise digits).</p> <p>I have tr...
<p>Note that the loss of accuracy you observe near zero comes from the fact that you are subtracting two nearly equal terms both of the form <code>10395 z^-6 + O(z^-4)</code>. As the true value is <code>1/135135 z^6 + O(z^8)</code> you will lose a factor of <code>~1.4 x 10^9 z^-12</code> in accuracy. So if you want to ...
python|performance|numpy|floating-point|mpmath
0
366,878
48,831,881
CentOS 7: libstdc++.so.6: version `CXXABI_1.3.9' not found
<p>I am running a python script using PyCharm on CentOS 7. The script imports tensorflow and allocates some potion of GPU memory to the script.</p> <p>The script worked fine without any issues until yesterday. I am not sure why this happened. I am running the following versions of gcc and libstdc++ on CentOS</p> <pre...
<p>Facing a similar problem with zmq on CentOS 7 I come up with a workaround since a fresh installation and environment did not help.</p> <p>The original issue was:</p> <pre><code>(mtango-py)$ python -c "import zmq" ... ImportError: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by /home/...
gcc|tensorflow|centos|pycharm|anaconda
7
366,879
48,793,091
Pandas read_excel
<p>I struggled for a few hours how to read an excel file with pd.read_excel where the path is a website address. I figured out that the link doesn't go directly to the file but just triggers downloading. Is there any easy way to solve it?</p> <p>Part of code: </p> <pre><code>link_energy = 'http://unstats.un.org/unsd/...
<p>For me works everything as expected in the following code:</p> <pre><code>import pandas as pd link_energy = 'http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls' df_energy = pd.read_excel(link_energy) df_energy </code></pre> <p>without errors on the following env:</p> <p>The vers...
python|pandas
1
366,880
48,579,891
Simple Machine learning model training returning Nan
<p>I am trying to start learning ML.</p> <p>I wrote a simple example:</p> <pre><code>import numpy as np # Prepare the data input = np.array(list(range(100))) output = np.array([x**2 + 2 for x in list(range(100))]) # Visualize Data import matplotlib.pyplot as plt plt.plot(input, output, 'ro') plt.show() # Define yo...
<p>You got the math wrong. When you compute the gradient update for GD you have to divide by the number of samples in your dataset: that's why it is called <strong>mean</strong> squared error and not just squared error. Also, you might want to use smaller inputs since you're trying to work with an exponential, as it t...
python|numpy|machine-learning|linear-regression
5
366,881
48,629,568
Drop multiples columns from the dataframe in python
<p>I want to drop multiple columns(around 800) from the dataframe using python. I have written below code:</p> <pre><code> def corr_df(x, corr_val): # Creates Correlation Matrix and Instantiates corr_matrix = x.corr() iters = range(len(corr_matrix.columns) - 1) drop_cols = [] df_drop=pd.DataFram...
<p>Drop multiple columns by numerical index like this:</p> <pre><code>cols = [1069, 1068, 1067] df = df.drop(df.columns[cols], axis=1) </code></pre>
python|python-3.x|pandas|dataframe|multiple-columns
1
366,882
70,857,643
Merging cells, in the same column, in the same df- Python
<p>I am attempting to merge two cells together. The reason for this is due to the fact that every unit under 'Chassis' should be an alphanumeric (ABCD123456) however the PO provided occasionally shifts the last number to the next row (no other data on said row) making the data look like this <a href="https://i.stack.im...
<p>Create a virtual group and merge rows of this group for <code>Chassis</code> column:</p> <pre><code># Convert 'NaN' string to pd.NA df = df.replace('Nan', pd.NA) cols = df.columns.difference(['Chassis']) m = df[cols].any(1) df = df.assign(Chassis=df.groupby(m.cumsum())['Chassis'] \ .transform('sum')).loc[m]....
python|pandas|merge|pypdf2|tabula-py
0
366,883
70,917,645
deconstruct and reconstruct a pretrained network in pytorch
<p>I'd like to use the G network I've found here: <a href="https://github.com/scaleway/frontalization/blob/master/network.py" rel="nofollow noreferrer">https://github.com/scaleway/frontalization/blob/master/network.py</a> With the point: <a href="https://github.com/scaleway/frontalization/tree/master/pretrained/generat...
<p>My current solution</p> <p>First, I've created a new model class switching encoder and decoder</p> <pre><code>class G2(nn.Module): def __init__(self): super(G2, self).__init__() self.main = nn.Sequential( nn.ConvTranspose2d(512, 256, 4, 1, 0, bias = False), # Output HxW = 4x4 ...
python|model|pytorch
0
366,884
70,865,481
How to compare 2 CSV files
<p>I have 2 CSV files:</p> <p>CSV 1 - original_names.csv</p> <pre><code>Serial,Names 1,James 2,Stephen 3,Ben 4,Harry 5,Jack 6, Peter </code></pre> <p>CSV 2 - dup_names.csv</p> <pre><code>Serial,Names 1,James 2,Kate 3,Ben 4,Sara </code></pre> <p>Desired Output - new.csv</p> <pre><code>Serial,Names,flag 1,0,T 2,Kate,F...
<p>Do an outer join, then just add some logic here. If the 2 name columns match, put a <code>'T'</code> flag in, else put <code>'F'</code>. Then replace the <code>'names'</code> should be <code>0</code> is <code>'T'</code>, else the name in the second csv. If there is no name in the second csv, fill those with the name...
python|pandas|dataframe
0
366,885
70,928,845
Pandas: Get list of shared values of column B that two different values from column B have in common
<p>I have a table like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>image</th> <th>user</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> </tr> <tr> <td>2</td> <td>1</td> </tr> <tr> <td>3</td> <td>1</td> </tr> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>2</td> </tr> <...
<p>You can do that with the following</p> <pre><code>seen = df.groupby(&quot;user&quot;)[&quot;image&quot;].apply(set) shared = list(seen[1].intersection(seen[2])) print(shared) [1,3] </code></pre>
python|pandas|dataframe
1
366,886
70,761,416
Converting nested json into a pandas data frame in Python
<p>I have a nested data frame in JSON. I have no problem with taking a data frame that isn't nested and converting into pandas data frame.</p> <p>What I am having issues is when there are multiple levels of the data frame and I need to write independent records for each of the json entries.</p> <pre><code>{ 'type': '...
<p>Use <code>explode</code>:</p> <pre><code>json = [{'type': 'text1', 'key': ['key1']}, {'type': 'text2', 'key': ['key1', 'key2']}, {'type': 'text3', 'key': 'key'}] df = pd.DataFrame(json).explode('key') \ .assign(key_index=lambda x: x.groupby(level=0).cumcount()) print(df) # Output type ...
python|json|pandas
1
366,887
70,817,631
How to rename a subset of columns based on offset/index and variable range?
<p>I am working with student test data. The data provided is in a new format and I need to align it with the older format for an existing BI application. Where a range of columns used to contain questions numbers, the column name now contains the correct answer (this includes duplicate column names as imported form the...
<p>Here is a solution using <code>set_axis()</code></p> <pre><code>cols = df.columns tn = cols.get_loc('TestName')+1 total = cols.get_loc('Total') (df.set_axis(cols[:tn].tolist() + list(range(1,len(df.columns[tn:total+1]))) + cols[total:].tolist(),axis=1)) </code></pre> <p>Output:</p> <pre>...
python|pandas
1
366,888
70,901,306
Numpy dot product of 3D arrays with shapes (X, Y, Z) and (X, Y, 1)
<p>I have 2 numpy 3D arrays: <strong>A</strong> of shape <strong>(X, Y, Z)</strong> and <strong>B</strong> of shape <strong>(X, Y, 1)</strong>. I need to perform dot product of each column of A with the single column of B, obtaining another array <strong>C</strong> of shape <strong>(X, Z)</strong>.<br /> I managed do a...
<p>@fsl gave this <code>einsum</code>:</p> <pre><code>np.einsum('ijk,ijl-&gt;ik',a,b) </code></pre> <p>with a bit of transpose, you can place the <code>j</code>, sum-of-products dimension in the standard <code>dot</code> order (last of A, 2nd to the last of B):</p> <pre><code>np.einsum('ikj,ijl-&gt;ik',a.transpose(0,2,...
python|arrays|numpy
2
366,889
70,846,469
Pandas DateTimeIndex - create a new value which has the max value of previous month
<p>I have something like the following dataframe (notice <code>dt</code> is the index)</p> <pre><code> fx fy dt 2019-05-29 0.000000 0.000000 2019-05-30 65.410004 156.449997 2019-05-31 70.279999 125.040001 2019-06-01 49.220001 147.979996 2019-06-02 100.580002 232.539993 2019-06-0...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.to_period.html" rel="nofollow noreferrer"><code>DatetimeIndex.to_period</code></a> for month period with shifting and mapping by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.map.html" rel="n...
pandas
2
366,890
71,013,422
Creating Multiple Excel sheets using data frames Python pandas
<p>I am trying to create Multiple Excel sheets using Python Pandas But its only creating the latest one and old one is getting replaced. Here my Scan2 Replaces Scan1 Sheet in output.xlsx file it's not saving the sheets.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from openpyxl import load_wo...
<p>To save multiple sheets to excel, you have to use pandas' ExcelWriter method</p> <p>try this:</p> <pre><code>writer = pd.ExcelWriter('output.xlsx', engine = 'xlsxwriter') dfdf.to_excel(writer, sheet_name = 'Scan01') dfdfd.to_excel(writer, sheet_name = 'Scan02') </code></pre> <p>other way of doing it without ExcelWr...
python|excel|pandas
3
366,891
71,002,770
Python Pandas - how to add columns of filtered sum and calculate percentage weight
<p>I would like to add two columns to a pandas df to show daily totals and weights. Existing df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Name</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>2022-2-1</td> <td>Apple</td> <td>5</td> </tr> <tr> <td>2022-2-1</td> <td>Pe...
<p>Use <code>groupby</code> + <code>transform('sum')</code>:</p> <pre><code>df['Daily Total'] = df.groupby('Date')['Value'].transform('sum') df['Percentage Weight'] = (df['Value'] / df['Daily Total'] * 100).round(1).map('{}%'.format) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df Date Name Value Da...
python|pandas
1
366,892
70,767,238
Unable to convert tensorflow.python.framework.ops.Tensor object to numpy array for passoing it in sklearn.metrics.cohen_kappa_score function
<p>I thought of implementing kappaScore metrics using <code>sklearn.metrics.cohen_kappa_score</code></p> <pre><code>def kappaScore(y_true,y_pred): k = cohen_kappa_score(y_true,y_pred,weights='quadratic') return k </code></pre> <p>Error I get when I try to run this code:</p> <pre><code>OperatorNotAllowedInGraphE...
<p>There's a way to solve this problem wrapping cohen_kappa_score in <a href="https://www.tensorflow.org/api_docs/python/tf/py_function" rel="nofollow noreferrer"><code>tf.py_function</code></a>. It's available in tensorflow 2.x, but I don't know since which version of framework; <code>py_function</code> does all heavy...
python|numpy|tensorflow|scikit-learn|deep-learning
0
366,893
70,782,222
I've created a python script to import excel sheets into my DB, But now i want create Gui which will take file path as input
<p>So i want add GUI in to my script as i already created .exe file of my script and it will take simple file-path from user and and write it into my database. My code of taking input:</p> <pre><code>filename = input(&quot;Input the Filename: &quot;) dfs = pd.read_excel(filename, usecols=['SR_NO','NTN'], sheet_name=Non...
<p>If you only need something simple, you can use Tkinter (it's already built-in in Python) and its <code>askopenfile</code> function. More information about the usage can be found here: <a href="https://docs.python.org/3/library/dialog.html#tkinter.filedialog.askopenfile" rel="nofollow noreferrer">https://docs.python....
python|pandas
0
366,894
70,879,238
How to convert duration strings to seconds?
<p>I have such a column in a pandas dataframe:</p> <pre><code>duration 1 day 22:12:15.778543 2 days 10:09:07.118723 00:18:23.985112 </code></pre> <p>I would like to convert this <code>duration</code> to seconds.</p> <p>How can I do this? I am not sure if this is possible because of the special string format I got (<cod...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.total_seconds.html" rel="nofollow noreferrer"><code>Series.dt.total_seconds...
pandas|datetime|time|strptime
2
366,895
70,804,697
Why is my pytorch classification model not learning?
<p>I have created a simple pytorch classification model with sample datasets generated using sklearns <code>make_classification</code>. Even after training for thousands of epochs the accuracy of the model hovers between 30 and 40 percentage. During training itself the loss value is fluctuating very far and wide. I am ...
<p>You should not be using ReLU activation on your output layer. Usually softmax activation is used for multi class classification on the final layer, or the logits are fed to the loss function directly without explicitly adding a softmax activation layer.</p> <p>Try removing the ReLU activation from the final layer.</...
machine-learning|deep-learning|neural-network|pytorch|classification
0
366,896
70,832,831
AttributeError: 'SingleBlockManager' object has no attribute 'log'
<p>I am using a big data with million rows and 1000 columns. I already referred this post <a href="https://stackoverflow.com/questions/21752989/numpy-efficiently-avoid-0s-when-taking-logmatrix">here</a>. Don't mark it as duplicate.</p> <p>If sample data required, you can use the below</p> <pre><code>from numpy import *...
<p>You can replace the zero values with a value you like and do the logarithm operation normally.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd m = pd.DataFrame(np.array([[1,0], [2,3]])) m[m == 0] = 1 print(np.log(m)) </code></pre> <p>Here you would get zeros for zero ite...
python|pandas|dataframe|numpy|numpy-ufunc
1
366,897
70,868,189
Tensorflow Serving keeps returning the same output
<p>So, I'm following this tutorial: <a href="https://www.youtube.com/watch?v=t6NI0u_lgNo&amp;t=1826s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=t6NI0u_lgNo&amp;t=1826s</a> and right after the tensorflow serving part I had been testing my fastapi API code which looks like this:</p> <pre><code>from fastap...
<p>There's no issue at all to get different confidence for different leaf images. Images are different in each category and the model detect confidence accordingly</p>
python|tensorflow|fastapi|tensorflow-serving
0
366,898
70,993,128
EDA for loop on multiple columns of dataframe in Python
<p>Just a random q. If there's a dataframe, df, from the Boston Homes ds, and I'm trying to do EDA on a few of the columns, set to a variable feature_cols, which I could use afterwards to check for na, how would one go about this? I have the following, which is throwing an error: <a href="https://i.stack.imgur.com/xXMB...
<p>There are two problems in your pictures. First is a <code>keyError</code>, because if you want to access subset of columns of a dataframe, you need to pass the names of the columns in a list not a tuple, so the first line should be</p> <pre><code>feature_cols = df[['RM','ZN','B']] </code></pre> <p>However, this will...
python|pandas|for-loop|eda
1
366,899
71,011,777
How to create quantiles with non-unique bin edges? Python or R
<p>I want to divide my data into quantiles (quintiles to be more specific). However, when using qcut in Pandas or ntile in R, I either get the error that &quot;bin edges must be unique&quot; (qcut) or equal values get assigned to different quintiles (ntile).</p> <p>Looking at the following data: [1, 8, 2, 1, 8] I would...
<p><strong>Update</strong></p> <blockquote> <p>In this specific case the 1s could also be assigned to quintile 2 instead of 1 (depending on definition). It is just important that equal values are assigned to the same quintile.</p> </blockquote> <pre><code>cut_rank = lambda x: pd.cut(x.rank(method='min'), 5, labels=[&qu...
python|r|pandas|dplyr|quantile
2