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 |
|---|---|---|---|---|---|---|
18,700 | 65,334,350 | How do I sort a txt file dataset into two datasets using a label? | <p>I loaded the data set with</p>
<pre><code>np.loadtxt("dataset")
</code></pre>
<p>which has given me an array of arrays? I guess what I am trying to do is sort these internal arrays which comprise of three variables x, y and z where z is either a +1 or a -1 which denotes if it is positive or negative.</p>
<... | <p>You can break down the dataset into two separate arrays as following:</p>
<pre><code>negex, posex = np.delete(dataset[dataset[:,2] < 0],2,1) , np.delete(dataset[dataset[:,2] > 0],2,1)
</code></pre> | python|numpy | 0 |
18,701 | 65,250,714 | Recurrent Neural Network with multiple output sequences of different length | <p>So I am using <code>tensorflow 2</code> and trying to predict many sequences of differing lengths from one sequence of a fixed length. Specifically, the input sequence have a fixed length of 31 and I want to predict 15 sequences where the first 5 sequences have one length (for example 10), the next 5 have another l... | <p>This is perhaps easier to solve using the functional API</p>
<pre><code>inp = tf.keras.layers.Input(shape = (maximum_sequence_length, nb_features))
X = tf.keras.layers.LSTM(neurons, return_sequences = False)(inp)
T1 = tf.keras.layers.RepeatVector(length_of_first_5_seqs-1)(X)
T2 = tf.keras.layers.RepeatVector(length_... | python|tensorflow|lstm | 0 |
18,702 | 65,145,214 | Identify first entry by group in pandas data frame | <p>I have data like this</p>
<p><a href="https://i.stack.imgur.com/QeGmj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QeGmj.png" alt="enter image description here" /></a></p>
<p>I wish to generate this:</p>
<p><a href="https://i.stack.imgur.com/XfJSX.png" rel="nofollow noreferrer"><img src="https:... | <pre class="lang-python prettyprint-override"><code>In [2]: df = pd.DataFrame({'id' : [1]*3 + [2]*3 + [3],
...: 'date' : ['01/02/2020', '02/02/2020', '03/02/2020', '01/02/2020', '02/02/2020', '03/02/2020', '04/05/2020']})
...: df
Out[2]:
id date
0 1 01/02/2020
1 1 02/02/2020
2 1 03/02/2020
3 ... | python|pandas|dataframe|group-by | 0 |
18,703 | 65,317,531 | python How to add ordinals number to pandas dataframe | <p>I'm trying to automate a report by adding ordinal reference to items in a pandas dataframe or array</p>
<p>This is my data</p>
<pre><code> 0 [John]
1 [Jack, Tom]
2 [Eric, Chris, Bob]
</code></pre>
<p>This is prefered output</p>
<pre><code>0 [Primary oncall: John]
1 [Primary oncall: Jack, Secondary oncall: Tom]
2 [... | <p>This is a crude solution, that requires you create a mapping for each count of each list in the column :</p>
<pre><code>df = pd.DataFrame({"header": [["John"],
["Jack", "Tom"],
["Eric", "Chris", ... | python|pandas|numpy | 0 |
18,704 | 49,798,451 | Python: Would vectorization/broadcasting boost speed? | <p><strong>GOAL:</strong> Merge arrays p1 to p10 to create one large array named 'a' and return all values in 'a' that appear in 'a', 4 times.</p>
<p><strong>Question:</strong> This code is super slow because of all the looping to be done, How can I make it swifter? Would vectorization and/or broadcasting aid in effic... | <p>Yes and yes. You can get rid of the loops and it will speed up things:</p>
<pre><code>>>> a = np.concatenate([p1,p2,p3,p4,p5,p6,p7,p8,p9,p10])
>>> np.flatnonzero(np.bincount(a, minlength=314000)==4)
array([ 29, 33, 38, ..., 313944, 313949, 313973])
</code></pre> | python|loops|numpy|vectorization|array-broadcasting | 3 |
18,705 | 62,935,897 | How can I force the x axis to use column entries | <p>I am trying to create a chart using a data frame which has TimePeriod as 201811, 201812, 201901, ..., 202006 which I want to use as the x axis values and plot against the y values (Total lives). See figure here:</p>
<p><a href="https://i.stack.imgur.com/bRZ6c.png" rel="nofollow noreferrer"><img src="https://i.stack.... | <p>You <code>Timeperiod</code> is integers, you can convert it to string:</p>
<pre><code>aggregated_lives['TimePeriodId'] = aggregated_lives['TimePeriodId'].astype(str)
</code></pre>
<p>then use your plot command.</p> | python|pandas|matplotlib | 1 |
18,706 | 63,143,788 | Numpy multidimensional indexing for np.ufunc.at and np.ix_ | <p>I would like to know how I can take index from an array and multiply with another array. I have two 4d arrays and one 2d index array:</p>
<pre><code>base = np.ones((2, 3, 5, 5))
to_multiply = np.arange(120).reshape(2, 3, 4, 5)
index = np.array([[0, 2, 4, 2], [0, 3, 3, 2]])
</code></pre>
<p>The row index of the index... | <p>Can't be done with <code>ix_</code>. From its docs:</p>
<blockquote>
<p>This function takes N 1-D sequences and returns N outputs with N
dimensions each,</p>
</blockquote>
<p>Your <code>index</code> is 2d.</p>
<p>However, we can do the equivalent 'by-hand':</p>
<pre><code>In [196]: np.multiply.at(base1, (np.arange(... | python|numpy|numpy-ndarray|numpy-slicing|numpy-ufunc | 2 |
18,707 | 67,971,076 | Weird behavior of np.gradient with increased resolution | <p>I would like to plot cos(x) and it's derivative -sin(x) on the same plot.
What I do it the following:</p>
<pre><code>import numpy as np
x = np.linspace(0,10,20) #x values: 0-10, 20 values
f = np.cos(x) # function
df = np.gradient(f) # derivative
# plot
plt.plot(f, label ="function")
plt.plot(df, labe... | <p>It's because of the default spacing assumed between two consecutive values, which is 1. See <a href="https://stackoverflow.com/a/24633888/9332187">this answer</a> for details.</p>
<p>In your examples, as you're using <code>np.linspace</code>, spacing can be programatically found as</p>
<pre><code>sp = np.diff(x)[0]
... | python|numpy | 5 |
18,708 | 67,898,345 | How to self-join a pandas dataframe on multiple columns and create a new frame with a new column (new column only has info from right side) | <p>I have the following dataset.</p>
<pre><code>ID LineID TeamID ShiftID DateTime Production Theoretical Scrap
1 3 1 NULL 18/6/2020 4:00 482.5291 511.2351
2 2 1 NULL 18/6/2020 5:00 467.8704 519.9842
3 1 1 NULL 18/6/2020 5:00 390... | <p>You should first split the dataframe depending whether the <code>Scrap</code> column contains positive data and then join the parts:</p>
<pre><code>df1 = df.loc[~(df['Scrap']>0),['LineID', 'TeamID', 'ShiftID',
'DateTime', 'Production','Theoretical']]
df2 = df.loc[df['Scrap']>... | python|pandas|join|merge|self-join | 1 |
18,709 | 61,431,197 | How to repeat specific elements in numpy array? | <p>I have an array <code>a</code> and I would like to repeat the elements of <code>a</code> n times if they are even or if they are positive. I mean I want to repeat only the elements that respect some condition.</p>
<p>If <code>a=[1,2,3,4,5]</code> and <code>n=2</code> and the condition is even, then I want <code>a</... | <p>a numpy solution. Use <code>np.clip</code> and <code>np.repeat</code></p>
<pre><code>n = 2
a = np.asarray([1,2,3,4,5])
cond = (a % 2) == 0 #condition is True on even numbers
m = np.repeat(a, np.clip(cond * n, a_min=1, a_max=None))
In [124]: m
Out[124]: array([1, 2, 2, 3, 4, 4, 5])
</code></pre>
<p>Or you may us... | python|numpy | 2 |
18,710 | 68,669,782 | Setting explicit limits for rounding | <p>Is there a more elegant way of setting an explicit rounding limit?</p>
<p><strong>What I'm using:</strong></p>
<pre><code>arr= #original array
rnd_lim=1.7
rounded_arr=np.where(arr.__ge__(rnd_lim), arr,np.floor( arr))
rounded_arr=np.where(rounded_arr.__lt__(rnd_lim), rounded_arr,np.ceil(rounded_arr))
</code></pre>
<p... | <p>Use <code>np.divmod</code> to separate the whole numbers and fractions in each element. Then round the fractional parts using your method and recombine:</p>
<pre class="lang-py prettyprint-override"><code>>>> arr = np.array([0.6, 0.8, 1.6, 1.8, 2.6, 2.8])
>>> rnd_lim = 0.7
>>> whole, frac ... | python|numpy|rounding | 1 |
18,711 | 68,576,415 | Append new element in row and save CSV [python] | <p>I have a csv that looks like this:</p>
<pre><code>nom_ele_title,nom_ele_type,nom_ele_parent_id
Aspirateur,2,PLACARDS
COIN CUISINE,1,None
Plaques vitro,2,EQUIPEMENTS
Micro-ondes,2,EQUIPEMENTS
USTENSILES
Tabourets bar x 3
Horloge
Pack vaisselle
Pack verrerie
</code></pre>
<p>I would like that when the element has no &... | <p>To save changed CSV data, you need to create a CSV Writer and expictly write the rows to it.</p>
<p>Try:</p>
<pre><code>import csv
with open("missed.csv", "r") as fin, open("out.csv", "w", newline='') as fout:
reader = csv.reader(fin)
writer = csv.writer(fout) # added... | python|pandas|csv|append | 0 |
18,712 | 53,006,403 | Saving autoencoder output array as an image | <p>I have designed an autoencoder to read an (256*256) RGB image which gives an output as an array of float32 elements with dimensions (256,256,3) with some of the elements as shown in the figure. </p>
<pre><code>img = Image.open('C:\\Users\\ece\\Desktop\\validation\\validate\\small_0002_7.jpg')
x = image.img_to_array... | <p>The auto encoder should match the output amplitude to the input amplitude, so you probably have a preprocessing in your layer or your cost function also has a scaling factor.</p>
<p>To save your image, multiply the result by 255, cast it as <code>np.uint8</code>, then save it with something like <code>spicy.misc.im... | python-3.x|numpy|neural-network|deep-learning|autoencoder | 0 |
18,713 | 53,187,009 | Classfying image with multi standard | <p>I'm not sure if it is right to describe this as "multi standard" but my problem is this.</p>
<p>I'm classfying pictures of fashion products,
and I want it to be classified some how like:</p>
<pre><code>id, brand, product_kind, sex
1, gucci, wallet, woman
2, H&M, backpack, unisex
3, zara, coat, man
</code></pre... | <p>Your problem is basically 3 different classifiers, so the "easiest" would be to train three independent ones.</p>
<p>You can also have 3 independent output layers (with perhaps additional hidden layers for each of them), each of them with the traditional softmax outputs, and your cost function is the sum of the los... | tensorflow|keras|classification | 1 |
18,714 | 65,752,599 | Updating weights manually in Pytorch | <pre><code>import torch
import math
# Create Tensors to hold input and outputs.
x = torch.linspace(-math.pi, math.pi, 2000)
y = torch.sin(x)
# For this example, the output y is a linear function of (x, x^2, x^3), so
# we can consider it as a linear layer neural network. Let's prepare the
# tensor (x, x^2, x^3).
p = ... | <p><code>param</code> variable inside the loop <a href="https://stackoverflow.com/q/35488769/1714410"><em>references</em></a> each element of <code>model.parameters()</code>. Thus, updating <code>param</code> is the same as updating the elements of <code>model.parameters()</code>.</p>
<p>As for your second example, I ... | neural-network|pytorch | 1 |
18,715 | 65,606,970 | extract attributes from pandas columns that satisfy a condition [sorted by frequency] | <p>So this is regarding <a href="https://stackoverflow.com/questions/61262719/extract-attributes-from-pandas-columns-that-satisfy-a-condition">a previous question</a> I've posted on SO a while ago.</p>
<p>Going back to the beginning, here's the minimal example:</p>
<p>I have a dataframe that looks like:</p>
<pre><code>... | <p>I hope simplify and increasing performance in another solution should be used by one loop with generator comprehension with <code>join</code>:</p>
<pre><code>f = lambda x: '+'.join(i for i, j
in sorted(x.items(), key=lambda y: y[-1], reverse=True) if j != 0)
df = df_test.apply(f, axis=1).to_f... | python|pandas|subset | 2 |
18,716 | 65,866,223 | how to convert pandas dataframe to columns in python | <p>I have a dataset given below:</p>
<pre><code>weekid A B C D E F
1 10 20 30 40 0 50
2 70 100 0 0 80 0
</code></pre>
<p>I am trying to convert given first dataset into another format without including missing values (which is 0 in this ca... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a> and filter the data when value != 0.</p>
<p>First you want to identify all the columns that you want to use as identifies. So you set id_vars to <code>weekid</code> as that's your prima... | python-3.x|pandas|dataframe|pivot|pandas-melt | 4 |
18,717 | 65,845,285 | CNN for variable sized images in pytorch | <p>I want to make a CNN model in pytorch which can be fed images of different sizes. I am trying to use 2d convolution layer, which takes 4D input shape (pytorch's Conv2d expects its 2D inputs to actually have 4 dimensions).
However, I'm not sure how to set up the input layer that can adjust all the variable sized imag... | <p>You can just convert the grayscale images to RGB by duplicating the single channel to three.</p>
<p>As your example, shape <code>[1, 32, 32]</code> can be converted to <code>[3, 32, 32]</code> by the following codes:</p>
<pre><code>np.concatenate((images,)*3)
</code></pre>
<p>If the shape is <code>[32, 32, 1]</code>... | python|pytorch|conv-neural-network | 0 |
18,718 | 63,390,138 | Is there any FAST way to do the following in python for time series data? | <p>I have a time series dataset as show below</p>
<pre><code>id date sales
0 2016-01-01 11.0
1 2016-01-02 12.0
2 2016-01-03 3.0
3 2016-01-08 3.1
4 2016-01-09 11.0
5 2016-01-10 34.2
6 2016-01-15 34.2
7 2016-01-1... | <p>IIUC, Q1 and Q2 are the same: use <code>diff</code> to check whether the difference is 1 day, and then use <code>cumsum</code>:</p>
<pre><code>df["date"] = pd.to_datetime(df["date"])
df["group"] = (df["date"].diff()>pd.Timedelta(days=1)).cumsum()+1
print (df)
id d... | pandas|dataframe|date|time-series|grouping | 2 |
18,719 | 71,916,374 | Python - How to count the frequency of each unique key from a column containing a dictionary of dictionaries? | <p>I have a very large dataframe containing a column called 'time_words'. Each cell of the column contains a list of dictionaries, for example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>time_columns</th>
</tr>
</thead>
<tbody>
<tr>
<td>{'<strong>Yesterday</strong>': {'text': 'Yesterda... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>df = (
df["time_columns"]
.explode()
.value_counts()
.reset_index(name="count")
.rename(columns={"index": "text"})
)
print(df)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override">... | python|pandas|dataframe|dictionary | 1 |
18,720 | 72,049,118 | How to run these Coral AI models inference in a computer rather than on the TPU? | <p>I have the Coral AI usb TPU and I have succesfully run the Getting Started example, deploying the already compiled / trained example model (image classification), with a parrot image running inference on the TPU:</p>
<pre><code>python3 examples/classify_image.py \
--model test_data/mobilenet_v2_1.0_224_inat_bird_qua... | <ul>
<li><p>Please check this repo for test models:
<a href="https://github.com/google-coral/test_data" rel="nofollow noreferrer">https://github.com/google-coral/test_data</a>.</p>
</li>
<li><p>Please use the <a href="https://coral.ai/docs/edgetpu/compiler/" rel="nofollow noreferrer">edgetpu compiler</a> to compile the... | python|tensorflow|tensorflow-lite|tpu|google-coral | 0 |
18,721 | 67,152,948 | Plot from csv with panda grouping | <p>If I have a csv with 4 columns:
how can I average the values of one column (x) over the average of another column (y) by grouping through the first one with panda? I have to do a loop for every value of the first column? I am not sure about the implementation.</p>
<p>For example, if I have a csv file:</p>
<p>a,1,2,4... | <p>Assume your dataframe looks like</p>
<pre><code>print(df)
0 1 2 3
0 a 1 2 4
1 a 2 2 5
2 a 3 2 6
3 a 4 2 5
4 b 1 3 2
5 b 2 3 3
6 b 3 3 4
</code></pre>
<p>If you want to plot with <code>a</code> average of 3rd column and <code>b</code> average of 3rd column, you can do</p>
<pre class... | python-3.x|pandas|dataframe|csv|data-analysis | 1 |
18,722 | 67,068,521 | Elegant way to replace values across dataframe without column names | <p>I have a dataframe like as shown below</p>
<pre><code>df = pd.DataFrame({'person_id': [101,101,101,101],
'start_date':['NA-NA-NA NA:NA:NA','Nil','06/06/2014 08:00:00 AM','06/06/2014 05:00:00 AM'],
'desc':['-','- ',' - ','test-date'],
'type':['te... | <pre><code>df.replace(regex=['Nil|NA|^-'], value=np.nan).dropna()
</code></pre>
<pre><code> person_id start_date desc type
3 101 06/06/2014 05:00:00 AM test-date oxygen-parlor
</code></pre> | python|pandas|string|dataframe|series | 0 |
18,723 | 67,169,145 | Cleaning Urls in a pandas dataframe | <p><There is more code to this but I collected Twitter data using twint. I am using Jupyter Notebooks as well. I have filtered the data that I want to keep for my graph. But in my nx node edges graph, has the full URL of the web pages. I want to get ride of the http://, https:// and the extra stuff after the .com or... | <p>Your problem arises because <code>urlsCleaned</code> is a <code>pd.DataFrame</code> not a <code>pd.Series</code>, to solve you have to change the line to:</p>
<pre><code>urlsCleaned = NWO_data["urls"]
</code></pre>
<p>Note that they look <strong>almost</strong> the same, but in your case, it creates a <cod... | python|pandas|dataframe|numpy | 0 |
18,724 | 47,198,889 | pandasdmx unable to create DataFrame for some OECD data | <p>I’m using pandasdmx version 0.7.0, and though I’m having success with OECD data sets with a Frequency dimension, there are other data sets like the Fossil Fuel Supports data sets, which have no Frequency dimension where I’m unable to create a pandas DataFrame, like below:</p>
<pre><code>from pandasdmx import Reques... | <p>The offical answer from the author of pandasdmx (0.7.0) is to use the parse_time parameter set to False for the write function. The write function then does not attempt to generate a DateTime index, and instead you get a string index. </p>
<pre><code>from pandasdmx import Request
# http://stats.oecd.org/sdmx-json/... | python|json|api|pandas | 0 |
18,725 | 47,182,843 | How to feed feed_dict in tensorflow my own image data | <p>
I have the following code:</p>
<pre class="lang-py prettyprint-override"><code>files = (glob.glob("*.jpg"))
q = tf.train.string_input_producer(files)
reader = tf.WholeFileReader()
file_name, content = reader.read(q)
image = tf.image.decode_jpeg(content, channels=3)
image = tf.cast(image, tf.float32)
resized_image ... | <p><a href="https://www.tensorflow.org/api_docs/python/tf/train/batch" rel="nofollow noreferrer"><code>tf.train.batch</code></a> is already returning you a tensor. This API (called <em>input pipeline</em>) allows you to stream input as tensors without manually feeding numpy arrays in session.</p>
<p>You can use <code>... | tensorflow | 0 |
18,726 | 68,361,964 | How to filter by a pandas column if the number of unique value in another column is equal a given value | <p>please I want to filter <strong>AccountID</strong> that has transaction data for at least <code>>=3</code> months ?. This is just a small fraction of the entire dataset</p>
<p>Here is what I did but, I am not sure it is right.</p>
<p><code>data = data.groupby('AccountID').apply(lambda x: x['TransactionDate'].nun... | <p>You are close, need <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for repeat aggregated values for Series with same size like original df, so possible filtering in <a href="http://p... | python|pandas | 2 |
18,727 | 68,284,587 | dataframe.sort_values() buy multiple columns with key for one column | <p>Lets say i have a dataframe that looks like this:</p>
<pre><code>col1, col2, col3, col4
txt,c,fix,txt
txt,a,error,txt
txt,a,new,txt
txt,c,new,txt
txt,c,error,txt
txt,b,new,txt
txt,b,fix,txt
</code></pre>
<p>and desired output is:</p>
<pre><code>col1, col2, col3, col4
txt,a,new,txt
txt,a,error,txt
txt,b,new,txt
txt,b... | <p>Use <code>replace</code> for replace both columns:</p>
<pre><code>custom_dict = {'new': 0, 'fix': 1, 'error': 2}
df = df.sort_values(by=['col2', 'col3'], key=lambda x: x.replace(custom_dict))
print (df)
col1 col2 col3 col4
2 txt a new txt
1 txt a error txt
5 txt b new txt
6 txt b fi... | python|pandas|dataframe | 2 |
18,728 | 68,054,788 | How to merge records with aggregate historical data? | <p>I have a table with individual records and another which holds historical information about the individuals in the former.</p>
<p>I want to extract information about the individuals from the second table. Both tables have timestamp. It is very important that the historical information happened before the record in t... | <p>IIUC:</p>
<p>try:</p>
<pre><code>out=df1.merge(df2,on='name',suffixes=('','_y'))
#merging both df's on name
out=out.mask(out['Date_Time']<=out['Date_Time_y']).dropna()
#filtering results
out=out.groupby(['Date_Time','name'])['cc'].agg(['count','mean']).reset_index()
#aggregrating values
</code></pre>
<p>output of... | pandas|pandas-groupby|aggregate-functions|relational | 1 |
18,729 | 57,084,899 | How to modify np array by slicing through the broadcast of an index vector? | <p>I have this m x n numpy array which I want to apply certain operation over the row elements. Although, it must be cast only on those elements whose index is prior to those specified by the entries on a vector of indexes.</p>
<p>I've already gone through the classic for-loop way, but I was expecting something more N... | <p>Here are two related ways which turn out to be roughly equally fast:</p>
<pre><code>import numpy as np
from timeit import timeit
M = [[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9,10]]
x = [2, 3]
def f():
MM = np.array(M)
xx = np.array(x)
MM[np.arange(5)<xx[:,None]] *= 2
return MM
def g():
MM = np.... | python|numpy|array-broadcasting | 2 |
18,730 | 50,966,774 | Define a segment function array | <p>I want to define an array <code>f</code> which is a segment function of <code>y</code>, how can I achieve that?</p>
<pre><code>import numpy as np
y0 = 1.0
y1 = 2.0
Ly = y1-y0
NY = 10
y = np.array([y0+Ly*float(i)/(NY-1) for i in range(NY)])
print('y=',y)
# I wnat f = -2.0*y, when y1<= y < Ly/2.0
# I wan... | <p>You can do this,</p>
<pre><code>f1 = np.array([-2.0*y[i] for i in range(NY/2)])
f2 = np.array([2.0*y[NY/2+i] for i in range(NY/2)])
f = np.concatenate((f1,f2),axis = 0)
print('f=',f)
</code></pre> | python|numpy | 0 |
18,731 | 66,714,485 | how can i train my CNN model on dataset from a .csv file? | <p>I'm a Python beginner and I'm using google Colab to train my first CNN model. I'm blocked on the training part: I know I have to use <code>model.fit()</code> to train the model, but I have no idea on what goes inside the <code>model.fit()</code>. Plus I'm not sure about the part of splitting my dataset from a CSV-fi... | <p>Ok lets set if we can help. First thing is about splitting the data frame. It is best to split it into a train set, a validation set and a test set. Best way to do that is to use sklearn's train, test, split. The documentation for that is [here.][1] Use the code below to split the data trame into 3 sets</p>
<pre><co... | python|csv|tensorflow|conv-neural-network|training-data | 0 |
18,732 | 66,571,756 | How can you get the activations of the neurons during an inference in tensorflow? | <p>I would like to specifically know how to get the neurons in a neural network are getting activated (the outputs of each neuron after the activation function)</p>
<p>How can I get the activations of all the neurons of a sequential model when I give input during the models' inference in Tensorflow 2?</p> | <p>Try something like this:</p>
<pre><code>intermediate_output = tf.keras.Model(model.input,
model.get_layer('conv2_block1_3_conv').output)
</code></pre>
<p>You can get a list of the layers with <code>model.layers</code> and pick the one you want.</p>
<pre><code>list(map(lambda x: ... | tensorflow|neural-network|activation-function | 3 |
18,733 | 66,673,457 | How to efficiently add or multiply every Nth element of a numpy array? | <p>Suppose I have the following numpy array.</p>
<pre><code>A = [1,2,3,4,5,6]
</code></pre>
<p><strong>Question</strong> Is there a quick way to multiply or add every nth element in A to yield the following arrays?</p>
<pre><code>B = [3*1, 2*4, 3*5, 4*6]
C = [3+1, 2+4, 3+5, 4+6]
</code></pre>
<p>I can accomplish this... | <p>You can do it in the following way:</p>
<pre><code>A = np.array([1, 2, 3, 4, 5, 6])
k = 2
B = A[:-k]
C = A[k:]
print(B * C)
print(B + C)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>[ 3 8 15 24]
[ 4 6 8 10]
</code></pre>
<p>Cheers.</p> | python|arrays|numpy | 2 |
18,734 | 57,520,730 | Get the most repeated value from columns of list other than zero in pandas data frame | <p>I have a following data frame,</p>
<pre><code>df1=
mac gw_mac ibeaconMajor ibeaconMinor
ac233f264920 ac233fc015f6 [1, 0, 1] [1, 0]
ac233f26492b ac233fc015f6 [0, 0, 0] [0, 0]
ac233f264933 ac233fc015f6 [0, 1, 1] [0, 2]
</code></pre>
<p>If all the values in a list(... | <p>Idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer"><code>DataFrame.applymap</code></a> for elementwise apply lambda function - first remve <code>0</code> values in list comprehension, get top values by <code>Counter</code> and add ... | python-3.x|pandas | 1 |
18,735 | 57,306,684 | select multiple columns by value | <p>i want to select two columns sku and month by value samsung and january</p>
<pre><code>print(field)
print(values)
output:
['SKUDESC', 'Full_month']`enter code here`
['samsung', 'January']
df[(field[0]) == values[0]) & (field[1]) == values[1]]
</code></pre>
<p>it is showing key error</p> | <p>try like below</p>
<pre><code>df[(field.column_name == 'samsung') & (field.column_name == 'January')]
</code></pre> | python|pandas | 0 |
18,736 | 57,720,292 | How do I extract an array of bits 2-9 from a bytearray? | <p>I have a 100,000 long bytearray, where every 16-bit line is a 10-bit address and 6-bit counts concatenated. I want to convert the 16-by-100,000 array into two separate (address and data) arrays in an array-wise, efficient manner. A short run-time is critical to my application.</p>
<p>What I have so far is</p>
<ol>... | <p>Assuming you want low 10 bits and high 6 bits:</p>
<pre><code>low_10 = aint & 1023
high_6 = aint >> 10
</code></pre>
<p>If you want low 6 bits and high 10 bits:</p>
<pre><code>low_6 = aint & 63
high_10 = aint >> 6
</code></pre>
<p>Unlike a Python loop, this is vectorised and runs much, much, ... | python-3.x|numpy|multidimensional-array|binary|type-conversion | 1 |
18,737 | 57,388,352 | Loop python auto_arima through several columns in a wide data format | <p>I will preface this by saying I am in no way a Python expert but my current project demands that it be programmed in Python, so any help is appreciated.
What I have is a transformed timeseries with monthly data (30 months) and 1000 + items. </p>
<p>I wish to run arima for each of these columns. They are not depende... | <p>You've probably already found a solution for this by now, but I'll leave an answer in case anyone else stumbles upon it.</p>
<p>The auto_arima is not the model itself. It is a function to help locate the best model orders. What you would do in the case above is to assign a variable to it and access the order and se... | python|pandas|loops|time-series|arima | 1 |
18,738 | 70,496,821 | Create a row for each record separated by some pattern | <p>I need to create a row in the pandas dataframe for each record in the <code>"ativos"</code> column and the other data (<code>"nome"</code>) must be repeated. Records are separated by this string <code>"\r\n"</code> in the <code>"ativos"</code> column. However, I don't know how... | <p>Use <code>str.split</code> and <code>explode</code>:</p>
<pre><code>out = df.assign(activos=df['ativos'].str.split(r'\\r\\n')).explode('ativos')
print(out)
# Output
nome ativos
0 Luiz ABC
0 Luiz DEF
0 Luiz GHI
</code></pre>
<p>Setup:</p>
<pre><code>df = pd.DataFrame({'nome': ['Luiz'], 'ativos': [r'AB... | pandas|dataframe|split|exploded | 1 |
18,739 | 51,214,165 | Drop rows after maximum value in a grouped Pandas dataframe | <p>I've got a date-ordered dataframe that can be grouped. What I am attempting to do is groupby a variable (Person), determine the maximum (weight) for each group (person), and then drop all rows that come after (date) the maximum. </p>
<p>Here's an example of the data: </p>
<pre><code>df = pd.DataFrame({'Person': 1,... | <p>Using <code>idxmax</code> with <code>groupby</code></p>
<pre><code>df.groupby('Person',sort=False).apply(lambda x : x.reset_index(drop=True).iloc[:x.reset_index(drop=True).Weight.idxmax()+1,:])
Out[131]:
Date MonthNo Person Weight
Person
1 0 1/1/2015 ... | python|pandas|dataframe|pandas-groupby | 5 |
18,740 | 51,315,912 | Pandas DataFrame, default data type for 1, 2, 3, and NaN values | <pre><code>d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print df ['one']
</code></pre>
<p>Output:</p>
<pre><code> a 1.0
b 2.0
c 3.0
d NaN
Name: one, dtype: float64
</code></pre>
<p>The valu... | <p>Type of <code>NaN</code> is <code>float</code>, so pandas will infer all <code>ints</code> numbers to be <code>floats</code> too.</p>
<p>This can be easily checked :</p>
<pre><code>>>> type(np.nan)
float
</code></pre>
<p>I would recommend <a href="https://www.johndcook.com/blog/2009/07/21/ieee-arithmet... | python|pandas|dataframe | 6 |
18,741 | 70,986,855 | deleteing the records in excel sheet before specific string | <p>I have around 400+ records in excel. i wanna try to delete the records of before specific value records and want to delete again the records from that specific record to bottom records in excel file.
when i put the sample records in excel it's working fine. but when i using that original excel file it's not working... | <p>If I understand you correctly, you want to keep the rows between the first <code>record_2</code> (inclusive) and second <code>record_2</code> (exclusive).</p>
<p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>s = df['content_name'].eq('record_2').cumsum()
df[s == 1]
</code></pre> | python|pandas|dataframe|pandas-groupby|xlwings | 0 |
18,742 | 36,208,282 | pandas: more elegant way to retrieve row and set value if exists? | <p>Using pandas, I find myself writing this a lot:</p>
<pre><code>try:
a = df.loc('A81001')
a['somecol'] = 'someval'
except KeyError:
pass
</code></pre>
<p>Is there a more elegant way to do things?</p> | <p>I don't think it's very elegant, but it will save you the <code>try</code>/<code>except</code>:</p>
<p>Consider the following:</p>
<pre><code>df = pd.DataFrame({'a': range(4), 'b': range(1, 5)})
df.b.values[df.a.values == 3] = 2
df.b.values[df.a.values == 30] = 3
>>> df
a b
0 0 1
1 1 2
2 2... | python|pandas | 0 |
18,743 | 36,014,469 | Numpy.arange(start, end, step) equivalent in Java for float values | <p>Do you know the way to achieve <code>numpy.arange(start, end, step)</code> functionality in Java for float values? I know there is a <code>numpy.arange(start, end, 1)</code> equivalent for <code>int</code> values in Java 8, ie. <code>static IntStream range(int startInclusive, int endExclusive)</code>. I also know cu... | <p>How about</p>
<pre><code>IntStream.rangeClosed(0, (int)((end-start)/step))
.mapToDouble(x -> x*step + start)
</code></pre> | java|python|numpy | 4 |
18,744 | 36,047,873 | Iteratively replace two strings with values from numpy array | <p>I'm currently trying to make an automation script for writing new files from a master where there are two strings I want to replace (x1 and x2) with values from a 21 x 2 array of numbers (namely, [[0,1000],[50,950],[100,900],...,[1000,0]]). Additionally, with each double replacement, I want to save that change as a ... | <p>I'm not sure I understood the second issue but you can use replace more than one time on the same string, so:</p>
<pre><code> s = "x1 stuff x2"
s = s.replace('x1',str(1)).replace('x2',str(2))
print(s)
</code></pre>
<p>, will output:</p>
<pre><code> 1 stuff 2
</code></pre>
<p>No need to do this ... | python|regex|numpy|replace|iteration | 0 |
18,745 | 37,267,472 | What's the fastest way to find out where a list of numpy arrays are equal? | <p>I have a list of numpy arrays, each of which are from an image, hence they're three-dimensional (height, width, channel). I need to know at which (r, w, c) points these are equal.</p>
<p>EDIT: More to the point, I'm trying to find out where these images differ. If there is a better way to do that, that would be goo... | <p>Is this the sort of thing you are trying to do?</p>
<p>Define two 3d 'images' (small for convenience):</p>
<pre><code>In [417]: img1=np.zeros((4,5,3),int); img2=np.zeros((4,5,3),int)
In [418]: img1[1:3,1:4,:]=[1,0,2] # different 'color' in the middle
In [419]: img2[1:3,1:4,:]=[2,1,0]
In [421]: img1!=img2
Ou... | image|numpy | 1 |
18,746 | 37,546,206 | Probability density function using histogram data | <p>I plot <code>numpy.ndarray</code> (length 1400) using Matplotlib. I want to detect the "peaks" and create a function such that it is 0.1 when "not a peak" and the y-value of the peak when a peak.</p>
<p>Example chart:</p>
<p><a href="https://i.stack.imgur.com/EhzVe.jpg" rel="nofollow noreferrer"><img src="https://... | <p>Apply <a href="http://nbviewer.jupyter.org/github/demotu/BMC/blob/master/notebooks/DetectPeaks.ipynb" rel="nofollow">DetectPeaks</a> to your data. Calculate the second derivative and decide regarding your mpd, mph settings.</p>
<pre><code>first_derivative = np.gradient(data)
second_derivative = np.gradient(first_de... | numpy|matplotlib|curve-fitting | 0 |
18,747 | 41,986,603 | Build new column from a function in a pandas Dataframe using values from DataFrame | <p>I'm a new to pandas DataFrame, and I'm having a bit of struggle as I can't figure how to access a particular cell to make calculation to fill a new cell.</p>
<p>I'd like to use apply to call a external function with data from a cell at row - 1.</p>
<p>I did that, but outputing everything in a simple array, but i'm... | <p><strong><em>initialization</em></strong> </p>
<pre><code>df = pd.DataFrame(dict(
col=[ 0.005742, 0.003765, -0.005536, 0.0015 , 0.007471,
0.002108, -0.003195, -0.003076, 0.005416, 0.00309 ]
), pd.to_datetime([
'2005-01-03', '2005-01-04', '2005-01-05', '2005-01-06', '2005-... | python|pandas|dataframe|apply | 2 |
18,748 | 37,963,967 | Pandas duplicate indexes to dataframe | <p>I have a Series with duplicate indexes that i would like to convert to a multi-column DataFrame.</p>
<pre><code>In [60]: np.random.seed(123456)
In [61]: b=pd.Series(np.random.random(30), index=range(6)*5)
</code></pre>
<pre><code>In [62]: b
Out[62]:
0 0.126970
1 0.966718
2 0.260476
3 0.897237
4 ... | <p>If values <code>0</code> in index can be edges of groups, you can first create <code>DataFrame</code> from <code>Serie</code>, then <code>groups</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="nofollow"><code>cumsum</code></a> and last <a href="http://pandas.p... | python|pandas|dataframe|pivot | 3 |
18,749 | 31,668,106 | Set DataFrame row index to a different column | <h2>The Setup</h2>
<p>Using</p>
<pre><code>cell = pd.read_csv('test_cell.txt',header=2,sep='\t')
</code></pre>
<p>I create a pandas DataFrame object that looks like this:</p>
<pre><code> Name Description LN18 22RV1 DU145
0 100009676_at LOC100009676 1 2 3
1 10000_at AKT... | <p>I guess what you want to do is <code>pd.merge</code> on the gene names, then sum the scores for each cell:patient pair. But your data frames are reshaped; <code>pd.stack</code> is useful for that purpose.</p>
<pre><code>cell_s=cell.set_index(['Description','Name']).stack().reset_index()
cell_s.columns = ['Descripti... | python|matrix|pandas | 1 |
18,750 | 64,236,587 | Calculating weighted average in Pandas using NumPy function | <p>Assume we have a pandas dataframe like this:</p>
<pre><code>a b id
36 25 2
40 25 3
46 23 2
40 22 5
42 20 5
56 39 3
</code></pre>
<p>I would like to perform a operation (a div b), then group by id and finally calculate a weighted average, using "a" as weights. It work's when I... | <p>Are you looking to group the weighted average by <code>id</code> ?</p>
<pre><code>df.groupby('id').apply(lambda x: np.average(x['b'],weights=x['a'])).reset_index(name='Weighted Average')
Out[1]:
id Weighted Average
0 2 23.878049
1 3 33.166667
2 5 20.975610
</code></pre>
<p>Or if yo... | python|python-3.x|pandas|numpy|weighted-average | 3 |
18,751 | 64,576,913 | Extract pandas dataframe column names from query string | <p>I have a dataset with a lot of fields, so I don't want to load all of it into a <code>pd.DataFrame</code>, but just the basic ones.</p>
<p>Sometimes, I would like to do some filtering upon loading and I would like to apply the filter via the <code>query</code> or <code>eval</code> methods, which means that I need a ... | <p>I think you can use when you load your dataframe the term use cols I use it when I load a csv I dont know that is possible when you use a SQL or other format.</p>
<p>Columns_to use=['Column1','Column3']
pd.read_csv(use_cols=Columns_to_use,...)</p>
<p>Thank you</p> | python|pandas|string|extract | 0 |
18,752 | 47,661,161 | How to get column values of csv file in pandas or other methods in python | <p>I have .csv file which looks like this:</p>
<pre><code>id,product
1,car
1,phone
2,tv
</code></pre>
<p>I want to get all rows which match the certain condition e.g:
If the id==1, and product value contains letter "a", print all matched rows (e.g '1,car' will be printed). I know this would be better to work with da... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and for check values in strings use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><c... | python|pandas|csv | 3 |
18,753 | 48,938,346 | List comprehension that ignores NaN | <p>I'm trying to build a list comprehension that has a conditional to not import nan values, but not having luck. Below is the current code along with the resulting output. What conditional will remove the nans from the list?</p>
<pre><code>def generate_labels(filtered_df, columnName):
return[
{'label': i,... | <pre><code>def generate_labels(filtered_df, columnName):
return[
{'label': i, 'value': i} for i in filtered_df[columnName].dropna().unique()
]
</code></pre> | python|pandas | 5 |
18,754 | 48,977,332 | Replace elements in a numpy ndarray accessed via index array | <p>I want to replace certain columns in a multi-dimensional array with the value that I have. I tried the following.</p>
<pre><code>cols_to_replace = np.array([1, 2, 2, 2])
original_array = np.array([[[255, 101, 51],
[255, 101, 153],
[255, 101, 255]],
[[255, 153, 51],
[255, 153, 153],
[255, 153,... | <p>Your expected output is produced by:</p>
<pre><code>>>> original_array[np.arange(cols_to_replace.size), cols_to_replace] = 0, 0, 255
</code></pre>
<p>This differs from your original approach because advanced indexing and slice indexing are evaluated "separately". By changing <code>:</code> to an <code>ara... | python|numpy|multidimensional-array | 2 |
18,755 | 58,638,973 | Python - How to replace all matching text in a column by a reference table - which requires replacing multiple matching text within a cell | <p>Hi I'm totally new to Python but am hoping someone can show me the ropes.</p>
<p>I have a csv reference table which contains over 1000 rows with unique Find values, example of reference table:</p>
<pre><code>|Find |Replace |
------------------------------
|D2-D32-dog |Brown |
|CJ-E4-cat |... | <p>You can save the excel file as CSV to make your life easier
then strip your file to contain only the table without any unnecessary information.</p>
<p>load the CSV file to python with pandas:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df_table1 = pd.read_csv("file/path/filename.csv")
d... | python|excel|pandas | 0 |
18,756 | 58,641,051 | Why `numpy.fft.irfft` is so imprecise? | <p>I understand that most FFT/IFFT routines have an error floor. I was expecting NumPy's FFT to have an error floor in the same orders as FFTW (say <code>1e-15</code>), but the following experiment shows errors in the order of <code>1e-5</code>.</p>
<p>Consider calculating the IDFT of a box. It is <a href="https://e... | <p>Thanks to <a href="https://stackoverflow.com/users/270986/mark-dickinson">MarkDickinson</a>, I realized that my math was wrong. The correct comparison would be carried out by:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.special import diric
N = 40960
K = 513
X = np.ones(K+1, dty... | python|numpy|fft | 1 |
18,757 | 56,397,222 | Python combo chart add the percentage on the bar but wrong | <p>I tried to add the percentage on the bar in combo chart, line and column graphs.<br>
However, all the values displayed are messy. </p>
<p>I provide the data here, this is also my <a href="https://stackoverflow.com/questions/56384157/python-bar-and-line-chart-with-groups-in-one-graph/56384957?noredirect=1#comment99... | <p>What I'm doing is dynamically labeling the bar graphs based on the coordinates for each patch that's drawn by the bar function.</p>
<pre><code>fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks()... | python|pandas|matplotlib|visualization|seaborn | 2 |
18,758 | 55,701,907 | Python: Numba iterate through multidimensional array | <p>I have a function that iterates through a one dimensional array and check if the values are above a threshold to create a mask. It is very fast. But how could I use this to iterate over multiple colums with different threshold on different columns. My approaches so far took 12 µs for a 1-D array with size 18531 . If... | <p>I think <code>np.where</code> might be what you are after. You can feed it a dataframe or a series</p>
<pre><code>import numpy as np
def make_mask(df, threshold):
result = np.where(df < threshold, 1 , 0)
return result
</code></pre> | python|arrays|pandas|numpy|numba | 1 |
18,759 | 39,797,819 | SettingWithCopyWarning on Column Creation | <p>I'm trying to create a moving average column for my data called 'mv_avg'. I'm getting a SettingWithCopyWarning that I have been unable to fix. I could suppress the warning, but I cannot figure out where in my code I am creating a copy, and I want to utilize best practices. I've created a generalizable example below ... | <p>you can create a copy using .copy()</p>
<pre><code>import pandas as pd
data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]}
df = pd.DataFrame(data)
df_a = df.loc[df['category'] == 'a'].copy()
df_a['mv_avg'] = df_a['value'].rolling(window=2).mean()
</code></pre>
<p>or you can use an indexer... | python|pandas | 5 |
18,760 | 44,227,249 | Implementing KS test for lognormal fit | <p>So I have some stock price data and I want to test whether the prices follow the lognormal distribution. My code is as follows:</p>
<pre><code>import scipy.stats as stats
print(stats.kstest(df['DJIA'], "lognorm", stats.lognorm.fit(df['DJIA'])))
</code></pre>
<p>The results are as follows:</p>
<pre><code>KstestRes... | <p>You are trying to fit the price data when you should be fitting the price <em>distribution</em>. Try fitting the count data from a histogram. The plot you show doesn't look like a histogram of the stock prices, it looks like a bar graph of price data.</p>
<pre><code>count, bins, ignored = plt.hist(df['DJIA'], 100, ... | python|pandas|scipy | 2 |
18,761 | 69,468,795 | Fill new column with yes if date has june else no | <p>I have a situation in pandas dataframe where if date has June month then in new column print yes else no for other months</p>
<p>Date format 2019-06-01</p> | <p>Since you haven't provided any details or sample dataframe, we can all only guess at what will actually work for your use-case. This solution assumes your <code>"Date"</code> column is the <code>datetime</code> type:</p>
<pre class="lang-py prettyprint-override"><code>df["new"] = df.where(df[&quo... | python|pandas|dataframe|numpy | 1 |
18,762 | 69,432,220 | Open a file with a specific extension, regardless of the name | <p>I have the following code:</p>
<pre><code>folder_names = []
spreadsheet_contents = []
all_data = pd.DataFrame()
current_directory = Path.cwd()
for folder in current_directory.iterdir():
folder_names.append(folder.name)
file_n = '*.csv'
spreadsheet_path = folder / file_n
spreadsh... | <p>It seems like you are using <code>pathlib</code> for the paths. <code>pathlib</code> supports recursive globbing using the <code>**</code> syntax (can be quite slow though):</p>
<pre><code>files = Path('.').glob('**/*.csv')
</code></pre>
<p>For reading the files you can do something like (passing the arguments that ... | python|pandas|pathlib | 1 |
18,763 | 69,648,108 | How to efficiently find nearest date before and after a reference date in pandas? | <p>I have a dataframe with the following columns: user ID, reference date, date of event, event value.</p>
<ul>
<li>User IDs are unique, and there are multiple entries for each ID</li>
<li>Reference date is unique to each user ID</li>
</ul>
<p>I want to find the indices of the events that happen closest to the referenc... | <p>You can easily do it using a <code>merge_asof</code> statement while setting the <code>direction</code> argument to the <code>nearest</code>, like this:</p>
<pre><code>df_merged = pd.merge_asof(df1, df2, on=['user_id'], direction='nearest')
</code></pre>
<p>Just before that, ensure that your dates are in date format... | python|pandas|datetime | 1 |
18,764 | 40,862,013 | Theano - Logistic Regression - Wrong number of dimensions | <p>I am trying to run the Logistic Regression <a href="http://deeplearning.net/software/theano/tutorial/examples.html#other-implementations" rel="nofollow noreferrer">example</a> from the Theano documentation. The code is shown below:</p>
<pre><code>import theano
import theano.tensor as T
import numpy
rng = numpy.ran... | <p>Got it, In my case, the output variable y is supposed to be a vector of floats <code>T.dvector("y")</code>, but I defined as a matrix instead <code>T.dmatrix("y")</code>. This is why the dot product <code>y * T.log(p_!)</code> wasn't happening.</p> | python|numpy|machine-learning|theano|logistic-regression | 0 |
18,765 | 40,892,203 | Can matplotlib contours match pixel edges? | <p>How to outline pixel boundaries in <code>matplotlib</code>? For instance, for a semi-random dataset like the one below,</p>
<pre><code># the code block that follows is irrelevant
import numpy as np
k = []
for s in [2103, 1936, 2247, 2987]:
np.random.seed(s)
k.append(np.random.randint(0, 2, size=(2,6)))
arr ... | <p>If the image has a resolution of 1 pixel per unit, how would you define the "edge" of a pixel? The notion of "edge" only makes sense in a frame of increased resolution compared to the pixel itself and <code>contour</code> cannot draw any edges if it is working with the same resoltion as the image... | python|numpy|matplotlib | 7 |
18,766 | 54,225,978 | with open() inside loop comprehension - getting a list of text contents of a all files in directory | <p>Is there a better manner to use the <code>with open(file) as f: f.read()</code> mechanism inside a for loop - i.e. a loop comprehension that operates on many files?</p>
<p>I am attempting to place this into a dataframe such that there is a mapping from file to file contents.</p>
<p>Here is what I have - but it see... | <p>Your code looks perfectly readable.
Perhaps you were looking for something like this (Python3 only):</p>
<pre><code>import pathlib
documents = pd.DataFrame(glob.glob('*.txt'), columns = ['files'])
documents['text'] = documents['files'].map(
lambda fname: fname.startswith('GSE') and pathlib.Path(fname).read_te... | python|pandas | 2 |
18,767 | 66,270,823 | Python: add columns to dataframe from another with matching "vlookup" | <p>I'd like to add two columns to an existing dataframe from another dataframe based on a lookup in the name column.</p>
<p>Dataframe to update looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Player</th>
<th>School</th>
<th>Conf</th>
<th>Cmp</th>
<th>Att</th>
</tr>
</thead>... | <p>Let us try</p>
<pre><code>existing_dataframe = existing_dataframe.merge(height_weight_df[['Name','School','Height','Weight']],left_on=['Player','School'],right_on=['Name','School'],how='left')
</code></pre> | python|pandas|dataframe | 2 |
18,768 | 66,035,457 | How can I merge Pandas DF and maintain merged structure? | <p>I'm not quite sure how to explain my problem so I'll just describe it.</p>
<pre><code>DF1
Name Year
0 foo 2020
1 bar 2020
2 foo 2019
3 foo 2018
DF2
Name Value
foo A
bar A
bar B
</code></pre>
<p>When I merge it, I want:</p>
<pre><code> Name Year Value
foo 2020 A
bar 2020 A
bar ... | <p>I think you mean <code>how='left'</code> not <code>how='right'</code>:</p>
<pre><code>df1.merge(df2, on='Name', how='left')
</code></pre>
<p>Output:</p>
<pre><code> Name Year Value
0 foo 2020 A
1 bar 2020 A
2 bar 2020 B
3 foo 2019 A
4 foo 2018 A
</code></pre> | python|pandas | 3 |
18,769 | 66,040,251 | How to change categorical variables in a for loop using a list with variable to change | <p>I would like to simplify the number of categories for one variable. The piece of code below is working:</p>
<pre><code>df.loc[(df['category'] == 'cat1')|(df['category'] == 'cat2')|(df['category'] == 'cat3')|...|(df['category'] == 'catn'),'category'] == 'other'
</code></pre>
<p>but I was wondering if I could do somet... | <p>It is better if you provide extra code when asking a question, typically the code to create the dataframe, this helps to test suggestions.
This code should work :</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'category': ['cat', 'dog', 'cat', 'rat']})
df['category'] = df['category'].replace(... | python|pandas|categories|.loc | 0 |
18,770 | 66,212,339 | Write a Circumflex Larger in Python | <p>I can write 'A circumflex' as a label on a graph in Python:</p>
<pre><code>df = pd.DataFrame({'x':(0,3,4,0),'y':(3,0,4,3)})
fig, ax = plt.subplots(1,1)
df.plot(x='x', y='y', ax=ax, label='A\u0302', linewidth=5, color='k', linestyle='-')
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get... | <p>Thanks to Mr. T & tmdavison, either <em><strong>$^{A}$</strong></em> or <em><strong>$\hat{A}$</strong></em> work for some reason:</p>
<p><a href="https://i.stack.imgur.com/a3qbN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a3qbN.png" alt="enter image description here" /></a></p>
<pre><code>... | python|pandas|matplotlib|unicode|font-size | 0 |
18,771 | 66,310,884 | Merging two string rows into one using Pandas | <p>I have a csv having rows like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Year 1</th>
<th>Year 1</th>
<th>Year 1</th>
<th>Year 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Month 1</td>
<td>Month 2</td>
<td>Month 3</td>
<td>Month 4</td>
</tr>
</tbody>
</table>
</div>
<p>I want these f... | <p>First convert first 2 rows of data to <code>MultiIndex</code>:</p>
<pre><code>df = pd.read_csv(file, header=[0, 1])
</code></pre>
<p>And then join values by <code>-</code>:</p>
<pre><code>df.columns = df.columns.map('-'.join)
</code></pre>
<p>Or use <code>f-string</code>s:</p>
<pre><code>df.columns = [f'{a}-{b}' for... | python|pandas|csv | 1 |
18,772 | 52,874,153 | Human Gender Classification- Train and Val accuracy not moving | <p>I am having 0.3 million image in my Train set - Male/Female and around ~50K image in the test set - Male/Female . I am using below to work , also tried to add few more layers and more units . Also, I am doing data augmentation and others provided from keras docs. </p>
<pre><code>targetSize =64
classifier.add(Conv2D... | <ol>
<li><p>Make sure you are overfitting on a small sample before trying to extend the network. </p></li>
<li><p>I would remove some/all of the <code>Dropout</code> layers and see if it improves performance. I think 3 Dropout layers is quite high.</p></li>
<li><p>Try reducing the learning rate.</p></li>
</ol> | python|tensorflow|keras|deep-learning|conv-neural-network | 0 |
18,773 | 46,532,986 | Filling missing values of categorical values based on other categorical values in pandas dataframe | <p>I want to fill missing values of categorical values in Pandas data frame with the most frequent values on another category. For example,</p>
<pre><code>import pandas as pd
import numpy as np
data = {'type': ['softdrink', 'juice', 'softdrink', 'softdrink', 'juice','juice','juice'],
'product': ['coca', np.nan,... | <p>IIUC</p>
<p>Using <code>mode</code> </p>
<hr>
<p>Data input</p>
<pre><code>import pandas as pd
import numpy as np
data = {'type': ['softdrink', 'juice', 'softdrink', 'softdrink', 'juice','juice','softdrink'],
'product': ['coca', np.nan, 'pepsi', 'pepsi', 'orange','grape',np.nan],
'price': [25, 94, 57,... | pandas | 3 |
18,774 | 46,250,770 | Error in restoring Tensorflow faster RCNN model from checkpoint file due to absence of ROI pooling layer | <p>I need to restore a Faster RCNN model in a project. But I am not able to do as there is no ROI pooling layer in Tensorflow. </p>
<p>How can I include a customized ROI pooling layer? Are there any alternatives?</p> | <p>We use <a href="https://github.com/tensorflow/models/blob/master/object_detection/meta_architectures/faster_rcnn_meta_arch.py#L1087" rel="nofollow noreferrer">crop and resize</a> for ROI.</p> | python-2.7|tensorflow|deep-learning|conv-neural-network|object-detection | 0 |
18,775 | 46,576,090 | Save tensor as JPEG image with tf.map_fn - Python/TensorFlow | <p>I have a function that returns me a variable called <strong>layer</strong> - images in the format:</p>
<pre><code><tf.Tensor 'Conv2D_1:0' shape=(?, 16, 16, 1) dtype=float32>
</code></pre>
<p>I need to save these images in .jpeg.</p>
<p>So far I've thought of doing this:</p>
<pre><code># Reshape into tf.ima... | <p>Your are almost done. The type needs to be a <code>tf.string</code>:
This gives a noisy image:</p>
<pre><code>import tensorflow as tf
import numpy as np
noise = np.random.randn(3, 128, 128, 1).astype(np.float32) * 255
# your data
layer = tf.convert_to_tensor(noise)
images = tf.image.convert_image_dtype(layer, tf.... | python|python-2.7|image-processing|tensorflow|tensor | 1 |
18,776 | 46,267,759 | scipy interpolate gives unbounded value | <p>I have a data set <code>data[xi,yi,zi]</code> I'd like to plot (with interpolation values). With scipy.interpolate, everything looks almost perfect however the interpolation is generating some values beyond the bounds of the input data. for example suppose <code>zi</code> is bound by <code>0 < zi < 1</code>,... | <p>Interpolation with radial basis functions may result in values above the maximum and below the minimum of the given data values. (<a href="http://pro.arcgis.com/en/pro-app/help/analysis/geostatistical-analyst/how-radial-basis-functions-work.htm" rel="nofollow noreferrer">Illustration</a>). This is a mathematical fea... | python|numpy|matplotlib|scipy | 2 |
18,777 | 58,428,739 | How to get the column header of a particular column in numpy | <p>I have the following data </p>
<p><code>admit_data = np.genfromtxt('/content/drive/My Drive/Colab/admission_predict.csv', delimiter=',')</code></p>
<p>What I need is to get some particular column header. I am using the following code to get the data. But not able to get those column name</p>
<p><code>print(admit_... | <p>Could you please give more information about the data that you want to extract.</p>
<p>Based on your question, tolist() function is present for Pandas series. Better convert the admit_data as pandas series(using pd.Series() function). Then you can extract the first row as list.</p> | python|numpy | 1 |
18,778 | 68,883,646 | Replacing values in a NumPy array with is_max | <p>I have an array like this:</p>
<pre><code>a = np.array(
[[
[
[0. , 0. ],
[0. , 0. ],
[0. , 0. ]
],
[
[0.07939843, 0.13330124],
[0.20078699, 0.17482429],
[0.49948007, 0.5237555... | <p>Manually construct the indices for <code>1</code> using <code>argmax</code>:</p>
<pre><code>i, j, k, _ = a.shape
idx = np.ogrid[:i,:j,:k] + [a.argmax(-1)]
a[:] = 0
a[tuple(idx)] = 1
a
array([[[[1., 0.],
[1., 0.],
[1., 0.]],
[[0., 1.],
[1., 0.],
[0., 1.]]]])
</code></pre> | python|arrays|numpy | 1 |
18,779 | 69,172,328 | How to prevent label encoder from adding y column to X numpy.array | <p>I have the following code below, however, the last line of the label encoder</p>
<p><code>X = MultiColumnLabelEncoder(columns = ['newlyConst','balcony', 'cellar', 'lift', 'garden', ]).fit_transform(df)</code></p>
<p>adds the y column (rent), into the X numpy.array.</p>
<p>I'm unsure how to specify the columns to be ... | <p>The answer is to delete the label encoder and instead use the code below in order to change the true/false values to integers. More information can be found here <a href="https://stackoverflow.com/questions/15891038/change-column-type-in-pandas#:%7E:text=The%20best%20way%20to%20convert%20one%20or%20more%20columns%20... | python|pandas | 0 |
18,780 | 44,438,623 | Cubic Root of Pandas DataFrame | <p>I understand how to take cubic root of both positive and negative numbers. But when trying to use <code>apply</code>-<code>lambda</code> method to efficiently process all elements of a dataframe, I run into an ambiguity issue. Interestingly, this error does not arise with equalities, so I am wondering what could be ... | <p>It looks like you are passing a list or array of column names. I assume this because your variable name is plural with an <code>s</code> at the end. If this is the case, then <code>sample[columns]</code> is a dataframe. This is an issue because <code>apply</code> iterates through each column, passing that column ... | python|python-3.x|pandas|numpy|dataframe | 4 |
18,781 | 44,766,841 | What is a faster way to get the location of unique rows in numpy | <p>I have a list of unique rows and another larger array of data (called test_rows in example). I was wondering if there was a faster way to get the location of each unique row in the data. The fastest way that I could come up with is...</p>
<pre><code>import numpy
uniq_rows = numpy.array([[0, 1, 0],
... | <p>There are a lot of solutions here, but I'm adding one with vanilla numpy. In most cases numpy will be faster than list comprehensions and dictionaries, although the array broadcasting may cause memory to be an issue if large arrays are used.</p>
<pre><code>np.where((uniq_rows[:, None, :] == test_rows).all(2))
</co... | python|numpy|scipy | 2 |
18,782 | 60,918,773 | How to join/write two pandas dataframes to a single file | <p>I am reading in a CSV file to a pandas data frame for scientific analysis/processing. I create a second "identical" data frame. I do the analysis/processing on the second data frame. I'd like to return the data to a CSV file with the two data frames "side by side" so the original data can be comp... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>pandas.DataFrame.merge()</code></a> like this:</p>
<pre><code>di = pd.merge(df, dg, left_index=True, right_index=True, suffixes=('_df', '_dg'))
</code></pre> | pandas|dataframe | 1 |
18,783 | 61,032,644 | Subtract two numpy arrays containing datetime.time | <p>In my script I get two huge np arrays that I want to subtract. The first numpy array <code>start_per_day</code> with the times the working day started and a second numpy array <code>end_per_day</code>.
However I get the below error. Couldn't figure it out, appreciate any help.<p>
<strong>Edit:</strong> below is a m... | <p>You may use <code>datetime.timedelta</code> instead of <code>datetime.time</code>: </p>
<pre><code>import datetime
import numpy as np
start_per_day = np.array([datetime.timedelta(hours=9, minutes=43), datetime.timedelta(hours=9, minutes=51)])
end_per_day = np.array([datetime.timedelta(hours=18, minutes=22), datet... | python|numpy|datetime | 2 |
18,784 | 71,514,224 | How to change date format in dataframe | <p>I'm trying to calculate the beta in stock but when I bring in the data it has a time in the date frame how can I drop it?
<a href="https://i.stack.imgur.com/h6T2Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h6T2Q.png" alt="enter image description here" /></a></p> | <p>If you want to transform a <code>datetime</code> object to a <code>date</code> object, you can get the date with the <code>.date</code> on the index, then just reassign it:</p>
<pre class="lang-py prettyprint-override"><code>Ford_df.index = Ford_df.index.date
</code></pre>
<p>If instead you want the index to be a st... | python|pandas|dataframe | 1 |
18,785 | 71,713,651 | Filter list of dicts in pandas series | <p>I have a pandas Series containing a list of dictionaries. I'd like to filter out dictionaries based on a condition. Here's some sample data:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'d': [[{'br': 1, 'ba': 1, 'r': 100},
{'ba': 1, 'r': 80},
{'br': 2, 'ba'... | <p>You could use a list comprehension to filter:</p>
<pre><code>df['d'] = [[d for d in row if d['r']<=100] for row in df['d']]
</code></pre>
<p>Output:</p>
<pre><code> d id name
0 [{'br': 1, 'ba': 1, 'r': 100}, {'ba': 1, 'r': ... xxas A
1 [{'br': 1, 'ba': 1... | python|pandas | 2 |
18,786 | 69,772,005 | How to convert specified elements of the ndarray to the concrete type | <p><em><strong>I have to do it without using pandas or something else, just pure numpy</strong></em></p>
<p>I have a big <code>ndarray</code> of <code>numpy.str_</code> read from the CSV file, I'd like to convert every element of every <strong>column</strong> to the particular type. For instance, I know that in the 2nd... | <p>Yes, structured arrays is what you need.</p>
<p>You have to pass the <code>dtype</code> argument as follow:</p>
<pre><code>np.array(data, dtype=[(name1, type1), (name2, type2), ...])
</code></pre>
<p>Where data is a list of tuples with fields.</p>
<p>You have to convert the original array to that structure.</p>
<p>I... | python|python-3.x|numpy|data-science|numpy-ndarray | 0 |
18,787 | 43,450,223 | Gauss-Newton products in Tensorflow | <p>I would like to use the Gauss-Newton approximation to the Hessian as a metric for an optimization problem, such as the method used to fit the value function in GAE <a href="https://arxiv.org/abs/1506.02438" rel="nofollow noreferrer">https://arxiv.org/abs/1506.02438</a>. However, does anyone know how to efficiently c... | <p>As of april 2017 there is no general-purpose efficient way to compute per-example gradients in TensorFlow, calling <code>tf.gradients</code> on all examples is probably the best for now.</p> | tensorflow | 0 |
18,788 | 43,176,191 | Bitwise Operations to change 2 LSB | <p>Suppose I have an list of numbers:</p>
<pre><code>l = [30, 31, 32, 33]
</code></pre>
<p>In binary this would the same as </p>
<pre><code>l = [00011110, 00011111, 00100000, 00100001]
</code></pre>
<p>Using binary operations I want to set the <strong>least 2 significant bits</strong> to any random value, but <stro... | <p>You can use bitwise xor:</p>
<pre><code>a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, a.shape)
a
# array([131, 79, 186, 90, 102, 179, 247, 28, 58, 60])
b
# array([2, 0, 2, 1, 0, 0, 2, 0, 3, 3])
a^b
# array([129, 79, 184, 91, 102, 179, 245, 28, 57, 63])
</code></pre>
<p>Demonstrate corr... | python-3.x|numpy|bit-manipulation|binary-operators | 1 |
18,789 | 43,171,416 | Python 3 - create combination of list within dictionary and aggregate | <p>I think I'm going about this all in a backwards way in pandas. Here's an example dataframe:</p>
<pre><code>Group rstart rend qty
1 10000 11000 1000
1 10000 11000 8000
1 10000 11000 13000
1 10000 11000 1000
2 6000 8000 4000
2 6000 8000 9000
2 6000 8000 3000
</code></pre>
<... | <p>Here is one self explanatory solution which also uses <code>itertools.combination</code> in conjunction with list comprehensions:</p>
<pre><code>def aggregate(sub_df):
# get boundaries and actual values
bound_low = sub_df["rstart"].iloc[0]
bound_high = sub_df["rend"].iloc[0]
values = sub_df["qty"].... | python|pandas|dictionary|combinations | 1 |
18,790 | 43,309,863 | How to do log-transform the y variable with file that contains timestamps of user logins in a particular geographic location? | <p>I have a large data file with timestamps that look like this if I do data.head()</p>
<pre><code> login_time
0 2016-01-01 00:11:52
1 2016-01-01 00:13:00
2 2016-01-01 00:14:49
3 2016-01-01 00:21:00
4 2016-01-01 00:23:05
</code></pre>
<p>I need to aggregate this data into 10 minute time intervals; I was t... | <p>It seems you can use:</p>
<pre><code>print(df.set_index('login_time').resample('10Min').size().reset_index(name='COUNT'))
login_time COUNT
0 2016-01-01 00:10:00 3
1 2016-01-01 00:20:00 2
</code></pre>
<p>If then if need apply <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy... | python|pandas | 1 |
18,791 | 43,058,462 | Reading a variable white space delimited table in python | <p>Right now I am trying to read a table which has a variable whitespace delimiter and is also having missing/blank values. I would like to read the table in python and produce a CSV file. I have tried NumPy, Pandas and CSV libraries, but unfortunately both variable space and missing data together are making it near im... | <p>You need your delimiter to be two spaces or more (instead of one space or more). Here's a solution:</p>
<pre><code>import pandas as pd
df = pd.read_csv('infotable.txt',sep='\s{2,}',header=None,engine='python',thousands=',')
</code></pre>
<p>Result:</p>
<pre><code>>>> print(df.head())
... | python|csv|numpy | 5 |
18,792 | 72,185,053 | Pandas dataframe: Flag a row when column value is in comma-separated string column | <p>I have the following dataframe :</p>
<pre><code>df Item ItemList
1 a r,t,y
2 b z,q,b
3 c c,d
4 b a
5 a a,z
</code></pre>
<p>and I want to check for each row if item is in itemList, and if so add a Flag like this :</p>
<pre><... | <p>Test if exist values by splitted <code>ItemList</code> in list comprehension with <code>zip</code> and <code>if-else</code> use for set <code>Yes</code> or missing values:</p>
<pre><code>df['Flag'] = ['Yes' if x in y.split(',')
else np.nan for x, y in zip(df['Item'], df['ItemList'])]
print (df... | python|pandas|dataframe | 1 |
18,793 | 45,417,595 | For a pandas dataframe column, TypeError: float() argument must be a string or a number | <p>here is the code where 'LoanAmount', 'ApplicantIncome', 'CoapplicantIncome' are type objects:</p>
<pre><code>document=pandas.read_csv("C:/Users/User/Documents/train_u6lujuX_CVtuZ9i.csv")
document.isnull().any()
document = document.fillna(lambda x: x.median())
for col in ['LoanAmount', 'ApplicantIncome', 'Coappli... | <p>In your code <code>document = document.fillna(lambda x: x.median())</code> will return a function not a value so a function cannot be converted to a float it should be either a string of numbers or an integer. </p>
<p>Hope the following code helps </p>
<pre><code>median = document['LoanAmount'].median()
document['... | python-2.7|pandas|numpy | 0 |
18,794 | 45,303,518 | generator called at the wrong time (keras) | <p>I use <code>fit_generator()</code> in keras 2.0.2 with batch size 10 and steps 320 because I have 3209 samples for training. Before the first epoch begins, the generator was called 11 times, showing:</p>
<pre><code>Train -- get ind: 0 to 10
...
Train -- get ind: 100 to 110
</code></pre>
<p>Then, after the ... | <p>By default, <code>fit_generator()</code> uses a <code>max_queue_size=10</code>.
So what you've observed is that:</p>
<ol>
<li>Before the epoch starts, your generator yields 10 batches to fill up the queue. That's samples 0 through 100.</li>
<li>Then, the epoch starts, and one batch is popped from the queue for mode... | tensorflow|keras | 2 |
18,795 | 62,597,289 | Repeated Values in Pivot | <p>I have two dataframes <code>df1</code> and <code>df2</code>.
One with clients <code>debt</code>, the other with client <code>payments</code> with <code>dates</code>.</p>
<p>I want to create a new data frame with the % of the debt paid in the month of the payment until <code>01-2017</code>.</p>
<p>The problem is that... | <p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with <code>agg_func='sum'</code>, as the fractions of monthly payments of debt can be added together:</p>
<pre><code>df3 = (
df2.join(
... | python|python-3.x|pandas|dataframe|pivot | 3 |
18,796 | 62,865,647 | Why is max and min of numpy array nan? | <p>What could be the reason, why the max and min of my numpy array is nan?
I checked my array with:</p>
<pre><code>for i in range(data[0]):
if data[i] == numpy.nan:
print("nan")
</code></pre>
<p>And there is no nan in my data.
Is my search wrong?
If not: What could be the reason for max and mi... | <p>Here you go:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
a = np.array([1, 2, 3, np.nan, 4])
print(f'a.max() = {a.max()}')
print(f'np.nanmax(a) = {np.nanmax(a)}')
print(f'a.min() = {a.min()}')
print(f'np.nanmin(a) = {np.nanmin(a)}')
</code></pre>
<p>Output:</p>
<pre><code>a.max() = nan
n... | python|numpy|max|nan | 1 |
18,797 | 54,387,686 | when training simple code of pytorch, cpu ratio increased. GPU is 0% approximately | <p>I'm doing tutorial of <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html" rel="nofollow noreferrer">Pytorch</a>.</p>
<p>Code is clearly completed. but i have one problem.</p>
<p>It is about my CPU use ratio.
If I enter into training, CPU usage ratio is increasıng up to 100%.
but GPU is rou... | <p>1.. Did you upload your model and input tensors onto GPU explicitly, showing as follow
<a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#training-on-gpu" rel="nofollow noreferrer">https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#training-on-gpu</a></p>
<p>For example,</p>... | python|visual-studio-2017|gpu|pytorch | 1 |
18,798 | 73,632,220 | How to reset both index and columns in a dataframe? | <p>I have a DataFrame in pandas like the one below.</p>
<p>After deleting several columns and rows, the index and columns are not longer a continuous range.</p>
<p>How could it set it back to 0 -> n? I tried <code>reset_index</code> without success.</p>
<pre><code> 4 12 15 22
5
9
14
26
31
37
</code></p... | <p>It looks like you want to reset both indexes.</p>
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_axis.html" rel="nofollow nore... | python|pandas|dataframe | 2 |
18,799 | 52,180,210 | What is '<U20' dtype in python? | <p>i wrote something like this: </p>
<pre><code>import numpy as np
n=['28/08/201818:20:35PM']
n=np.array(n)
n
</code></pre>
<p>the gives me the output <code>array(['28/08/201818:20:35PM'], dtype='<U20')</code>
i don't get the dtype in the output.
is it the 'UNICODE' but what about '<' & '20'</p> | <p>A 20-character (<code>20</code>) unicode string (<code>U</code>) on a little-endian architecture (<code><</code>). <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.dtypes.html" rel="nofollow noreferrer">docs</a></p> | python|python-3.x|numpy | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.