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 |
|---|---|---|---|---|---|---|
3,900 | 66,047,311 | Slow numpy and pandas imports on Google Cloud Run | <p>I'm developping an API and deploying it on Google Cloud Run.</p>
<p>There is a prestart python script that import pandas and numpy. When I time the imports numpy take about 2 seconds and pandas about 4 seconds on Cloud Run as opposed to less than 0.5 second on my local machine.</p>
<p>I'm using <code>python:3.8-alpi... | <p>This is a known issue in the Python ecosystem.</p>
<blockquote>
<p>all modules are imported at runtime, and some modules are 300-500MB large in size</p>
</blockquote>
<p>There are tons of complaints about slow import times. The best thread is this one: <a href="https://stackoverflow.com/questions/16373510/improving-... | python-3.x|pandas|docker|google-cloud-platform|alpine-linux | 2 |
3,901 | 52,669,198 | Mapping two arrays containing strings to the same integer values | <p>I have 2 arrays like:</p>
<pre><code>['16.37.235.200','17.37.235.200','16.37.235.200', '18.37.235.200']
['17.37.235.200','17.37.235.200','16.37.235.200', '17.37.235.200']
</code></pre>
<p>And I want to map (injective) every IP address to an integer value.<br>
Like for that instance above, eg.:</p>
<pre><code>[0,1... | <p>Ok i found this solution for seperate mapping of the lists
<a href="https://stackoverflow.com/questions/9206609/python-map-list-of-strings-to-integer-list">Python Map List of Strings to Integer List</a></p>
<p>Works like i want for seperated mapping of the 2 lists.</p> | python|arrays|string|numpy|integer | 0 |
3,902 | 52,897,402 | How to iterate through two numpy arrays of different dimensions | <p>I am working with the MNIST dataset, <code>x_test</code> has dimension of (10000,784) and <code>y_test</code> has a dimension of (10000,10). I need to iterate through each sample of these two numpy arrays at the same time as I need to pass them individually to <code>score.evaluate()</code></p>
<p>I tried <code>ndit... | <p><em>Assuming</em> that what you are actually trying to do here is to get the individual loss per sample in your test set, here is a way to do it (in your approach, even if you get past the iteration part, you will have issues with <code>model.evaluate</code>, which was not designed for <em>single</em> sample pairs).... | arrays|numpy|keras | 1 |
3,903 | 52,597,757 | Outer product with Numpy and Ndarray | <p>In one of my codes, I use numpy for matrices calculations.</p>
<p>At one point, I have to do the outer product between 2 vectors to get a matrix. That's where I'm stuck. At first, I tried numpy.dot, or other matrix product, but when the arguments are both 1D, it only does the scalar product, which not what I want. ... | <p><code>outer</code> is not a method of any class, it is just a plain old function found in the <code>numpy</code> module.</p>
<p>Here is an example of how to use it:</p>
<pre><code>import numpy
x = numpy.array([1, 2, 3])
y = numpy.array([4, 5, 6])
# x.__class__ and y.__class__ are both 'numpy.ndarray'
outer_produc... | python|numpy|multidimensional-array | 3 |
3,904 | 52,525,361 | Convert a list of vectors to DataFrame in PySpark | <p>Firstly, I have load the data by:</p>
<pre><code>import urllib.request
f = urllib.request.urlretrieve("https://www.dropbox.com/s/qz62t2oyllkl32s/kddcup.data_10_percent.gz?dl=1", "kddcup.data_10_percent.gz")
data_file = "./kddcup.data_10_percent.gz"
raw_data = sc.textFile(data_file)
</code></pre>
<p>Then, I creat... | <p>You can use <code>from_records()</code>:</p>
<pre><code>vector_data = [np.array(...), np.array(...)]
pd.DataFrame.from_records(vector_data)
</code></pre> | python|pandas|pyspark|jupyter-notebook | 0 |
3,905 | 58,254,885 | Error in build while using keras custom layer | <p>I am trying to train an unsupervised classification model for which i am using deep clustering with my model on Keras.
The code I am referring for clustering is <a href="https://github.com/XifengGuo/DCEC/blob/master/DCEC.py" rel="nofollow noreferrer">this</a>.
While running the code i am getting an error in the cut... | <p>Replace</p>
<pre><code>input_dim = input_shape[1]
</code></pre>
<p>with </p>
<pre><code>input_dim = input_shape[1].value
</code></pre>
<p>in the <code>build()</code> method of <code>ClusteringLayer</code>, so that input_dim will be 128 instead of Dimension(128).</p> | python|tensorflow|keras|deep-learning|unsupervised-learning | 2 |
3,906 | 44,393,358 | How to compress numpy arrays before inserting into LMDB dataset? | <p>I have size of [82,3,780,1024] tensors - merge of 82 different image frames - in uint8 format. LMDB goes wild in terms of size, once i start to insert these. Is there any way to compress these tensors before inserting? </p>
<p>For inserting I follow the question <a href="https://stackoverflow.com/questions/44266384... | <p>You could use one of the many fast in-memory compression algorithms. One very good option would be to use <a href="http://blosc.org/" rel="nofollow noreferrer">blosc</a> library, which itself allows you to use quite a few algorithms specialized (or performing well) in this scenarios.</p>
<p>You can get the list of ... | numpy|lmdb | 1 |
3,907 | 61,179,299 | Pandas transform: assign result to each element of group | <p>I am currently using pandas groupby and transform to calculate smth for each group (once) and then assign the result to each row of the group.
If the result of calculations is scalar it can be obtained like:</p>
<pre><code>df['some_col'] = df.groupby('id')['some_col'].transform(lambda x:process(x))
</code></pre>
<... | <p>Sometime transform is a pain to work with If that's not a problem for you I'd suggest you to use <code>groupby</code> + a <code>left</code> <code>pd.merge</code> as in this example:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({"id":[1,1,2,2,2],
"col":... | python|pandas|numpy|data-structures | 0 |
3,908 | 61,159,317 | How to count occurrence of each element in pandas series of lists? | <p>I'm a newbie and quite stuck with my python project. I have a pandas series containing lists, like this:</p>
<pre><code>>> df.head()
>> column1
['A', 'B']
['A']
['A', 'C']
['A', 'B', 'C']
['B']
</code></pre>
<p>The desired output should be like this:</p>
<pre><code>>> colum... | <p>Try: </p>
<pre><code>df1['column1'].explode().groupby().count()
</code></pre>
<p>or </p>
<pre><code>df1.explode('column1').groupby('column1').count()
</code></pre> | python|pandas|list|series | 2 |
3,909 | 61,013,644 | take numeric value without label in line, regex | <p>Input:</p>
<pre><code>df=pd.DataFrame({'text':['value 123* 333','122* 666','722 888*']})
print(df)
text
0 value 123* 333
1 122* 666
2 722 888*
</code></pre>
<p>I need to extract from <code>df['text']</code> only numeric values, but withou <code>*</code>label
my code:</p>
<pre><code>df.... | <p>You may use</p>
<pre><code>df['text'].str.extract(r'(?=([0-9]+(?:\.[0-9]+)?))\1(?!\*)')
</code></pre>
<p>See the <a href="https://regex101.com/r/upKQeA/1" rel="nofollow noreferrer">regex demo</a>. Or, you may also require a word boundary on the left with <code>r'\b(?=([0-9]+(?:\.[0-9]+)?))\1(?!\*)'</code>. See <a ... | python|regex|pandas | 2 |
3,910 | 42,562,633 | What is a 2D float tensor? | <p><strong>Disclamer:</strong> I know <strong>nothing</strong> about CNN and deep learning and I don't know <a href="http://torch.ch/" rel="nofollow noreferrer">Torch</a>.</p>
<p>I'm using <a href="http://docs.opencv.org/3.1.0/da/df5/tutorial_py_sift_intro.html" rel="nofollow noreferrer">SIFT</a> for my object recogni... | <p>2D float tensor = 2D float matrix.</p>
<p>FYI: <a href="https://stats.stackexchange.com/q/181556/12359">The meaning of tensors in the neural network community</a></p> | tensorflow|computer-vision|deep-learning|torch|tensor | 1 |
3,911 | 42,476,129 | parsing tab delimited values from text file to variables | <p>Hello I've been struggling with this problem, I'm trying to iterate over rows and select data from them and then assign them to variables. this is the first time I'm using pandas and I'm not sure how to select the data</p>
<pre><code>reader = pd.read_csv(file_path, sep="\t" ,lineterminator='\r', usecols=[0,1,2,9,10... | <p>The general workflow you're describing is: you want to read in a csv, find a row in the file with a certain ID, and unpack all the values from that row into variables. This is simple to do with pandas.</p>
<p>It looks like the CSV file has at least 10 columns in it. Providing the usecols arg should filter out the c... | python|parsing|pandas|csv | 1 |
3,912 | 43,043,805 | Converting Theano Euclidean distance to keras engine format | <p>I have the following code in <code>theano</code> in order to calculate <code>L2</code> distance </p>
<pre><code>def distance(square=False):
X = T.fmatrix('X')
Y = T.fmatrix('Y')
squared_euclidean_distances = (X ** 2).sum(1).reshape((X.shape[0], 1)) + (Y ** 2).sum(1).reshape \
((1, Y.shape[0])) - 2 *... | <p>I found the mistake. I forgot to <code>transpose</code> Y</p>
<p>def distance_matrix(vects):</p>
<pre><code>x, y = vects
# <x,x> + <y,y> - 2<x,y>
x_shape = K.int_shape(x)
y_shape = K.int_shape(y)
return K.reshape(K.sum(K.square(x), axis=1), (x_shape[0], 1)) +\
K.reshape(K.sum(K.square(y), a... | tensorflow|theano|keras|keras-layer | 1 |
3,913 | 72,311,770 | Pytorch: tensor normalization giving bad result | <p>I have a tensor of longitudes/latitudes that i want to normalize. I want to use this tensor to perform a neural network algorithm on it that returns me the best trip between these different long/lat.
I used this function:</p>
<pre><code>from torch.nn.functional import normalize
t=normalize(locations)
</code></pre>
<... | <p><a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.normalize.html?highlight=functional%20norm" rel="nofollow noreferrer">This</a> is how <code>torch.nn.functional.normalize</code> works.</p>
<p>In my opinion, you should divide your original tensor value with the maximum value of longitudes/latitu... | python|pytorch|tensor|normalize | 0 |
3,914 | 72,458,259 | Changing date column of csv with Python Pandas | <p>I have a csv file like this:</p>
<p>Tarih, Şimdi, Açılış, Yüksek, Düşük, Hac., Fark %<bR>
31.05.2022, 8,28, 8,25, 8,38, 8,23, 108,84M, 0,61%</p>
<p>(more than a thousand lines)</p>
<p>I want to change it like this:</p>
<p>Tarih, Şimdi, Açılış, Yüksek, Düşük, Hac., Fark %<bR>
5/31/2022, 8.28, 8.25, 8.38, 8.23, 108.84... | <p>Just looking at converting the date, you can import to a datetime object with arguments for <code>pd.read_csv</code>, then convert to your desired format by applying <code>strftime</code> to each entry.</p>
<p>If I have the following <code>tmp.csv</code>:</p>
<pre><code>date, value
30.05.2022, 4.2
31.05.2022, 42
01.... | python|pandas|dataframe|datetime | 2 |
3,915 | 72,169,307 | Normalize a list with jsons to a dataframe in steps | <p>I have a problem. I have a <code>list</code> with <code>JSONs</code>. I want to create a complete dataframe in steps. My idea is, for example: My list contains 100 elements. I want to say the size of the steps should be 25. So I say <code>len(list) / size = 4 = 100 / 25</code>. I have 4 runs of the for loop and 4 ti... | <p>The problem most likely arose that at the first iteration an empty dataframe was obtained.Since the list_dictionaries[:0] slice was used. Try the code below.</p>
<pre><code>list_dictionaries = [my_Dict, my_Dict2, my_Dict2, my_Dict2]
df_complete = pd.DataFrame()
for i in range(0, len(list_dictionaries)):
df = pd... | python|json|pandas|loops|for-loop | 1 |
3,916 | 50,636,635 | resample a pandas df within each group | <p>I have a df that has a <code>MultiIndex</code> of <code>(id, date)</code> and I would like to do 2 things:</p>
<ol>
<li><p>convert the <code>DateTimeIndex</code> named <code>date</code> to a <code>PeriodIndex</code> within each <code>id</code> group</p></li>
<li><p><code>resample</code> the frequency of the <code>P... | <p>If use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.resample.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.resample</code></a> is necessary <code>DatetimeIndex</code> set before <code>groupby</code>, also <code>apply</code> is not necessary, faster is <... | python|python-3.x|pandas | 2 |
3,917 | 50,562,684 | separate list dictonary into columns and values | <p>I have data frame which contains a column "ExtData" with values <code>[{"key":"title","value":"activation"},{"key":"remarks","value":"activation"}]</code></p>
<p>I have to separate this data and create a new data frame with "title" and "remarks" column name and their value "activation" i.e "key" is column name and ... | <p>Here is solution, using <a href="https://pandas.pydata.org/pandas-docs/version/0.21.0/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> method:</p>
<pre><code>def separate_extdata(row):
for d in row['ExtData']:
row[d['key']] = d['value']
return row... | python|pandas | 1 |
3,918 | 50,627,481 | Create multiple dataframe columns containing calculated values from an existing column | <p>I have a dataframe, <code>sega_df</code>: </p>
<pre><code>Month 2016-11-01 2016-12-01
Character
Sonic 12.0 3.0
Shadow 5.0 23.0
</code></pre>
<p>I would like to create multiple new columns, by applying... | <p>One vectorised approach is to drown to <code>numpy</code>:</p>
<pre><code>A = sega_df.values
A = (100 - 5*A) * 0.2
res = pd.DataFrame(A, index=sega_df.index, columns=('Weighted_'+sega_df.columns))
</code></pre>
<p>Then join the result to your original dataframe:</p>
<pre><code>sega_df = sega_df.join(res)
</code>... | python|pandas|for-loop|dataframe | 1 |
3,919 | 45,609,903 | np.where on multiple variables | <p>I have a data frame with:</p>
<pre><code>customer_id [1,2,3,4,5,6,7,8,9,10]
feature1 [0,0,1,1,0,0,1,1,0,0]
feature2 [1,0,1,0,1,0,1,0,1,0]
feature3 [0,0,1,0,0,0,1,0,0,0]
</code></pre>
<p>Using this I want to create a new variable (say new_var) to say when feature 1 is 1 then the new_var=1, if feature_2=1 then new_v... | <p>I think you need <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> - it select first <code>True</code> values and all another are not important:</p>
<pre><code>m1 = df['feature1']==1
m2 = df['feature2']==1
m3 = df['feature3'... | python|pandas|if-statement|case-when|np | 1 |
3,920 | 45,633,591 | What does this groupby function mean I have done? | <p>I have 3 columns: topic, year and country.
I am trying to find the maximum number of topics per country over the years and want it to group by the maximum project count for each country. </p>
<p>I've used this groupby function below: </p>
<pre><code>df.groupby(['topic', 'year', 'country']).count()
</code></pre>
... | <p>that groupby should give you the count of each unique tuple of <code>('topic', 'year', 'country')</code></p> | python|pandas|plot|group-by | 0 |
3,921 | 45,556,099 | Error when placing markers at specific points using matplotlib and markevery | <p>I'd like to place markers on a line specific points. I have a TRUE/FALSE list that says where on the x-axis the markers are wanted. Here is the snippet I am using:</p>
<pre><code>markers_on = list(compress(self.x, self.titanic1))
a0.plot(self.x, self.nya, marker='v', markevery=markers_on)
</code></pre>
<p>self.tit... | <p>If the list supplied to <code>markevery</code> is a list of integers, it is interpreted as a list of <strong>indices</strong> of the values to mark. </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,1,0.2)
y = np.random.rand(len(x))
boolean= [True, False, False, True, True]
mark =... | python|numpy|matplotlib | 2 |
3,922 | 62,473,828 | Identical random crop on two images Pytorch transforms | <p>I am trying to feed two images into a network and I want to do identical transform between these two images. <code>transforms.Compose()</code> takes one image at a time and produces output independent to each other but I want same transformation. I did my own coding for <code>hflip()</code> now I am interested to ge... | <p>I would use workaround like this - make my own crop class inherited from RandomCrop, redefining <strong>call</strong> with</p>
<pre class="lang-py prettyprint-override"><code> …
if self.call_is_even :
self.ijhw = self.get_params(img, self.size)
i, j, h, w = self.ijhw
self.call_... | deep-learning|pytorch|vgg-net|spacy-transformers | 1 |
3,923 | 62,575,164 | Creating a 'vocabulary' to group words having same meaning for word frequency | <p>I have this output from n-grams analysis by using CountVectorizer (texts are stored in pandas dataframe):</p>
<pre><code> Frequency
Words
playstation 5 106
hours app 32
app store 20
5 playstation 17
hour app 16
... ...
</code></pre>
<p>I would like to know if it is possible to create a 'vocabulary' ... | <p>How about using the Levenshtein distance to check how closer the two words are like</p>
<pre><code>from fuzzywuzzy import fuzz
fuzz.token_sort_ratio('playstation 5','5 playstation')
>> 100
fuzz.token_sort_ratio('playstation 5','4 playstation')
>> 92
</code></pre>
<p>I have used the <a href="https://pypi... | python|pandas|n-gram | 1 |
3,924 | 62,616,253 | numpy where output - how can I use the value? | <p>I have a list <code>some_list = [[1, 2], [3, 4], [3, 6]]</code>
I want to find some index where expression was evaluated as true:</p>
<pre><code>np.where([3 in sublist for sublist in some_list])
</code></pre>
<p>The output is <code>(array([1, 2], dtype=int64),)</code>.</p>
<p>Since I'd like to remove sublist with <c... | <p><code>where</code> just returns a <strong>tuple of arrays</strong> that index where the element values True.</p>
<pre><code>In [447]: some_list = [[1, 2], [3, 4], [3, 6]]
</code></pre>
<p>Your list test:</p>
<pre><code>In [448]: [3 in sublist for sublist in some_list] ... | python|python-3.x|numpy|tuples | 2 |
3,925 | 62,781,228 | Efficient way to extend a numpy array to n*length and duplicate its elements? | <p>I'm looking for a fast way to take a numpy array, such as <code>[[1,2,3,4]]</code>
and turn it into an extended version of itself with its elements repeated <code>N</code> times.
I.E. if <code>N = 2</code>, then <code>[[1,2,3,4]]</code> -> <code>[[1,1,2,2,3,3,4,4]]</code></p>
<p>Obviously I can brute force it wit... | <p>Try this:</p>
<pre><code>from numpy import repeat
x = [[1,2,3,4]]
N = 3
y = repeat(x, N).reshape((1,-1))
print(y)
</code></pre>
<p><strong>Edit:</strong> Quang's solution is shorter, I admit ...</p>
<pre><code>y = repeat(x, N, axis=-1)
</code></pre> | python|arrays|numpy | 1 |
3,926 | 62,741,673 | Unable to install tensorflow module in Python3 | <p>I'm installing tensorflow. My system has the following specifications:</p>
<pre><code>py --version
Python 3.8.2
</code></pre>
<p>I tried the following commands to install tensorflow module</p>
<pre><code>py -m pip install --upgrade tensorflow
ERROR: Could not find a version that satisfies the requirement tensorflow ... | <p>TensorFlow supports only 64-bit system architecture. Hence it shows compatibility issue in 32-bit and no matching distribution found.</p> | python|tensorflow | 0 |
3,927 | 54,557,767 | Combinations in python with different elements | <p>I'm struggling when calculating different types of combinations.</p>
<p>Let's explain with an example, I have this array or it could be a dataframe and I want different combinations of some columns from it.</p>
<p>As I will then multiply this matrix by the combination to sum the numbers.</p>
<pre><code>test = np.... | <p>I really don't understand the logic behind the example, but does this solve your problem?</p>
<pre><code>from itertools import product,permutations
a = set(permutations([0,0,1]))
b = set(permutations([0,1]))
comb = []
for t1,t2,t3 in product(a,b,a):
comb.append([*t1,*t2,*t3])
print(comb)
# [[1, 0, 0, 0, 1, ... | python|python-3.x|numpy | 0 |
3,928 | 54,462,351 | Running session failed due to tensors datatype and shape Tensorflow | <p>I tried to load the model and graph using the following methodology: </p>
<pre><code>saver = tf.train.import_meta_graph(tf.train.latest_checkpoint(model_path)+".meta")
graph = tf.get_default_graph()
outputs = graph.get_tensor_by_name('output:0')
outputs = tf.cast(outputs,dtype=tf.float32)
X = graph.get_tensor_by_n... | <p>This happens when you are trying to evaluate a node in the graph which is dependent on a value from a placeholder. Because of that, you are getting an error that states that you must feed a value for the placeholder. Have a look at this example:</p>
<pre><code>tf.reset_default_graph()
a = tf.placeholder(tf.float32)... | python|python-3.x|tensorflow|machine-learning | 1 |
3,929 | 54,549,519 | Save arrays from loop in one txt file in columns | <p>I'm creating an array of zeros (587x1) in which I want to replace a zero with a one in a specific line of the array given as an index from another file. This part works fine in my code so far. </p>
<p>Afterwards, I want to save all these newly created arrays in one txt file as columns next to each other, separated ... | <p>You can try this code, that adds a given <code>(n,1)</code> shaped array as a column to a textfile that contains a <code>(n,m)</code> shaped matrix of integers:</p>
<pre><code>def appendAsColumn(arr):
fileContent = np.loadtxt('outfile.txt', dtype = int, ndmin = 2)
fileContent = np.hstack((fileContent, arr.a... | python|arrays|numpy | 0 |
3,930 | 73,625,640 | GUI for editing and saving a python pandas dataframe | <p>In a python function I want to show the user a pandas dataframe and let the user edit the cells in the dataframe. My function should use the edited values in that dataframe (i.e. they should be saved).</p>
<p>I've tried pandasgui, but it does not seem to return the edits to the function.</p>
<p>Is there a function/l... | <p>Recently solved this problem with <a href="https://github.com/man-group/dtale" rel="nofollow noreferrer">dtale</a></p>
<pre><code>import pandas as pd
import dtale
df = pd.read_csv('table_data.csv')
dt = dtale.show(df) # create dtale with our df
dt.open_browser() # bring it to a new tab (optional)
df = dt.data ... | python|pandas|user-interface | 0 |
3,931 | 60,609,917 | How can I use a generator to run my Neural Network model? | <p>I have a neural network model that run perfectly, but I am using a very large data and I try to use a generator to run the model, but it gives me the following error: </p>
<pre><code>"UnimplementedError:
File "<ipython-input-63-352f4097b60f>", line 146, in <module>
validation_steps = len(df_vali... | <p>From what I can see the problem is a type mismatch due to the use of a CSV file. A number (the labels) is read from the CSV as a string and it's not converted to an int automatically.</p>
<p>This is the expected outputs (labels) which you read from the CSV:</p>
<pre><code>Y_out = df.iloc[start_index: end_index]['c... | python|pandas | 0 |
3,932 | 60,567,183 | 'tf.data()' throwing Your input ran out of data; interrupting training | <p>I'm seeing weird issues when trying to use <code>tf.data()</code> to generate data in batches with keras api. It keeps throwing errors saying it's running out of training_data.</p>
<p><strong>TensorFlow 2.1</strong></p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import nibabel
import tenso... | <p><strong>TF 2.1</strong></p>
<p>This is now working with the following parameters:</p>
<pre><code>def load_image(file, label):
nifti = np.asarray(nibabel.load(file.numpy().decode('utf-8')).get_fdata()).astype(np.float32)
xs, ys, zs = np.where(nifti != 0)
nifti = nifti[min(xs):max(xs) + 1, min(ys):max(y... | python|tensorflow|keras|tensorflow-datasets | 0 |
3,933 | 72,608,651 | How to get the Pearson correlation between matrices | <p>This is the Python analog to <a href="https://stats.stackexchange.com/questions/24980/correlation-between-matrices-in-r">this question</a> asked about R. In summary, I have to numpy matrices of identical shape and I want to get their Pearson correlation. I just need one number. Feeding the matrices to np.corrcoef pr... | <p>IIUC, you can <code>stack</code> and <code>reshape</code>:</p>
<pre><code>l = [a, b, c]
# only if matrices
l = list(map(np.asarray, l))
x = np.stack(l).reshape(len(l), -1)
np.corrcoef(x)
</code></pre>
<p>Output:</p>
<pre><code>array([[1. , 0.72280632, 0.72280632],
[0.72280632, 1. , 1. ... | python|r|arrays|numpy|matrix | 0 |
3,934 | 72,690,687 | Reseting indexes when I have same name multi index in pandas | <p>I have this dataset:</p>
<pre class="lang-py prettyprint-override"><code>mydf = pd.DataFrame({'date':pd.date_range('01/01/2020', periods=48, freq='15D'),
'value':np.random.randint(20,30,48)})
mydf
date value
0 2020-01-01 20
1 2020-01-16 28
2 2020-01-31 23
3 2020-02-15 27
... | <p>A simple trick to know is that you can rename series inline like this</p>
<p>Instead of <code>mydf['date'].dt.year</code></p>
<p>Do <code>mydf['date'].dt.year.rename("year")</code>.</p> | python|pandas | 1 |
3,935 | 72,663,020 | Numpy - Vectorized calculation of a large csv file | <p>I have a 20 GB <code>trades.csv</code> file. It has two columns (trade_time and price). And the csv file contains 650 million rows.</p>
<p><strong>Sample Data</strong></p>
<p><a href="https://gist.github.com/dsstex/bc885ed04a6de98afc7102ed08b78608" rel="nofollow noreferrer">https://gist.github.com/dsstex/bc885ed04a6... | <p>The original algorithm is super slow because it is doing a nested loop with iterrows/tuples.</p>
<p>If I understood good, for <em>each</em> row, you check if <em>any</em> of the posterior rows reach to the "fixed" percentage. If it reaches <code>up</code>, you tag as 1, if it reaches <code>down</code> you ... | python|pandas|dataframe|numpy | 1 |
3,936 | 59,494,111 | Pandas Python - value_counts() or idxmax() returns different value each time | <p>I have a Series which consists of a list of some random products. This is what it looks like if I print the describe:</p>
<pre><code><bound method NDFrame.describe of 176 reversible jacket
231 the north face resolve 2 jacket
234 ... | <p>It seems there has been <a href="https://stackoverflow.com/questions/51933763/pandas-series-value-counts-returns-inconsistent-order-for-equal-count-strings">previous issues</a> regarding how pandas <code>value_counts()</code> deals with tied values, in an inconsistent way.</p>
<p>As for <code>idxmax()</code> the <a... | python|python-3.x|pandas | 1 |
3,937 | 32,463,573 | converting python pandas column to numpy array in place | <p>I have a csv file in which one of the columns is a semicolon-delimited list of floating point numbers of variable length. For example:</p>
<pre><code>Index List
0 900.0;300.0;899.2
1 123.4;887.3;900.1;985.3
</code></pre>
<p>when I read this into a pandas DataFrame, the datatype for that column is ... | <p>If I understand you correctly, you want to transform your data from pandas to numpy arrays.
I used this:</p>
<pre><code>pandas_DataName.as_matrix(columns=None)
</code></pre>
<p>And it worked for me.
For more information visit <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.as_matri... | python-2.7|csv|numpy|pandas | 0 |
3,938 | 40,653,937 | Numpy: how to find the unique local minimum of sub matrixes in matrix A? | <p>Given a matrix A of dimension MxN (4x4), how would one find the next-best minimum of each 2x2 submatrix?</p>
<pre><code>A = array([[ 32673. , 15108.2 , 26767.2 , 9420. ],
[ 32944.2 , 14604.01 , 26757.01 , 9127.2 ],
[ 26551.2 , 9257.01 , 26595.01 , 9309.2 ],
... | <p>Given the dependency between iterations in choosing the global minimum, here's an approach with one-loop -</p>
<pre><code>def unq_localmin(A, dim):
m, n = A.shape
M4D = A.reshape(m//dim, dim, n//dim, dim)
M2Dr = M4D.swapaxes(1,2).reshape(-1,dim**2)
a = M2Dr.copy()
N = M2Dr.shape[0]
R = np.e... | python|algorithm|numpy|matrix | 2 |
3,939 | 18,737,942 | Clustering in python(scipy) with space and time variables | <p>The format of my dataset:
[x-coordinate, y-coordinate, hour] with hour an integer value from 0 to 23.</p>
<p>My question now is how can I cluster this data when I need an euclidean distance metric for the coordinates, but a different one for the hours (since d(23,0) is 23 in the euclidean distance metric). Is it po... | <p>You'll need to define your own metric, which handles "time" in an appropriate way. In the docs for <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow">scipy.spatial.distance.pdist</a> you can define your own function</p>
<pre><code>Y = pdist(X, f)
</code></... | python|numpy|scipy|cluster-analysis|euclidean-distance | 3 |
3,940 | 61,662,711 | How can I get columns from Multi-Index? | <p>I have a dataframe called "keytable" which features a Multi-Index composed of 'Month', 'Day' and 'Hour'. I want to keep that multi-index while creating 3 new columns with the values of 'Month', 'Day' and 'Hour'. How can I do it?
Here's the dataframe:</p>
<pre><code>keytable.head()
Out[59]:
pp p... | <p>To make new columns called 'Month', 'day', 'year', just
<code>new_table=key_table.reset_index()</code> will work. Having index duplicated as columns is a very poor practice, but if you really insist, then </p>
<pre><code>newdf = new_table[['Year', 'Month', 'Year']].set_index(['Year', 'Month', 'Year']).
new_table.s... | python|pandas|dataframe|multi-index | 1 |
3,941 | 61,998,103 | Trying to get consistent time format in Pandas | <p>I’m having an issue getting some timestamps into a consistent format.</p>
<p>I have the timestamps:
‘00:00:02.285932’
‘00:00:07’
‘00:00:11.366717’
‘00:00:11.367594’
In pandas from a CSV file. I would like the second line to be consistent with the others.
‘00:00:07.000000’</p>
<p>If I run:
timestps.pd.to_datetime(t... | <p>you can either use <code>datetime</code> and simply not use the year/month/day in your code or convert to <code>timedelta</code>. methods available for both types are different so the choice depends on what you want to do... Ex:</p>
<pre><code>import pandas as pd
# example series:
s = pd.Series(['00:00:02.285932', ... | python|pandas|formatting|timestamp | 0 |
3,942 | 58,161,122 | How to filter rows in Python pandas dataframe with duplicate values in the columns to be filtere | <p><strong>Overall context:</strong></p>
<p>I have a data frame that contains observations for every five minute starting at 5 AM in the morning and ending at 8 PM in the evening for several days. I need to filter all the observations that start from 9 AM in the morning and end at 5 PM in the evening for every day.</p... | <p>Use dateTime.hour that is present in the dateTime object in your data, you could then filter the data based on which is greater than 9 and which is less than or equal to 5 or (17) and then add into your resulting data frame or array </p>
<p>The following piece of code might help you,</p>
<pre><code>dummy = []
for ... | python|pandas|dataframe | 2 |
3,943 | 57,745,575 | How to update multiple rows and columns in pandas? | <p>I want to update multiple rows and columns in a CSV file, using <code>pandas</code></p>
<p>I've tried using <code>iterrows()</code> method but it only works on a single column. </p>
<p>here is the logic I want to apply for multiple rows and columns:</p>
<pre class="lang-py prettyprint-override"><code>if(value <... | <p>Here is another way of doing it,</p>
<p>Consider your data is like this:</p>
<pre><code> price strings value
0 1 A a
1 2 B b
2 3 C c
3 4 D d
4 5 E f
</code></pre>
<p>Now lets make <code>strings</code> column as the index:</p>
<pre><code>df.se... | python|pandas|csv|dataframe|data-manipulation | 2 |
3,944 | 34,241,680 | Returning only one boolean statement if two matrices identical | <p>Suppose there is a matrix <code>A</code> and a matrix <code>B</code>. Is there a logical statement that can return only one value, either <code>True</code> or <code>False</code> based on whether all elements of <code>A</code> are identical to all elements in <code>B</code>?</p>
<p>For example <code>A = array([[1, 0... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_equal.html" rel="nofollow"><code>np.array_equal</code></a>.</p>
<p>Also, you can apply <code>.all()</code> to the equality-bool-array you got by comparing <code>A==B</code>, like this:</p>
<pre><code>(A==B).all()
</code></pre>
<p>The la... | python|python-2.7|numpy|matrix | 3 |
3,945 | 34,116,402 | Tensorflow Convolution Neural Net - Training with a small dataset, applying random changes to Images | <p>Say I have a very small dataset, just 50 Images. I want to re-use the code from the tutorial at <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/tutorials/mnist/pros/index.md" rel="nofollow noreferrer">Red Pill</a>, but apply random transformations to the same set of Images in each Batc... | <p>One thing to start with: Instead of computing y_conv and then the cross-entropy, use the merged <code>tf.softmax_cross_entropy_with_logits</code> operator. This may not solve your problem, but it's more numerically stable than the naive version in the Red Pill example.</p>
<p>Second, try printing out the cross_en... | tensorflow|training-data|conv-neural-network | 4 |
3,946 | 34,360,375 | Python Pandas Dataframe filter and replace | <p>I constructed a dataframe which looks like this:</p>
<pre><code>title category1 category2 category3 category4
'a' 0.44214 NAN 0.99 0.35
'b' NAN NAN NAN NAN
'c' 0.31 0.41 0.5 0.53
</code></pre>
<p>For each row, I want to indicate the two highest values w... | <p>You can rank the rows (setting <code>axis=1</code>) in descending order all numeric values in the dataframe. Then do a boolean comparison to find the rank values less than or equal to two (<code>le(2)</code>), which would be rank values 1 and 2. Finally, convert the boolean mask to integers.</p>
<pre><code>>&g... | python|pandas|filter | 2 |
3,947 | 73,195,941 | Extract data and add to new column based on value id | <p>I am trying to extract elevation data from my stations information dataframe and add it to my rides dataframe.</p>
<p>Take df1 and df2 for example:</p>
<pre><code>df1 = pd.DataFrame(
{
"Ride ID": ["100", "101", "102", "103"],
"StartStation ID... | <p>simple merge with Station ID Column
Try this,</p>
<pre><code>pd.merge(df1, df2, left_on=['StartStation ID'], right_on=['Station ID'])
</code></pre>
<p>O/P:</p>
<pre><code> Ride ID StartStation ID Endstation ID Station ID Elevation
0 100 2 3 2 13
1 101 ... | python|pandas | 0 |
3,948 | 73,259,957 | create a dataframe from multiple JSON file with unique keys | <p>I have a JSON that looks something like this:</p>
<pre><code>translation_map:
str_empty:
nl: {}
bn: {}
str_6df066da34e6:
nl:
value: "value 1"
publishedAt: 16438
audio: "value1474.mp3"
bn:
value... | <p>Use a <a href="https://www.w3schools.com/python/gloss_python_for_nested.asp" rel="nofollow noreferrer">nested loop</a> and <a href="https://docs.python.org/3.8/library/stdtypes.html#dict.values" rel="nofollow noreferrer"><code>dict.values()</code></a> like so:</p>
<pre><code>json_text = {
"translation_map&q... | python|json|pandas|dataframe | 1 |
3,949 | 73,312,440 | Pandas append/concat two values from a dictionary object into a data frame | <p>I am trying to combine a set of two values from a dictionary object into a data frame column I am replacing. This is what my fruits column data frame looks like:</p>
<pre><code>Fruits
------
{'type': 'Apples - Green', 'storeNum': '123456', 'kind': 'Granny Smith'}
{'type': 'Banana', 'storeNum': '246810', 'kind': 'Org... | <p>You can concatenate string columns with <code>+</code>.</p>
<pre class="lang-py prettyprint-override"><code>data = [{'type': 'Apples - Green', 'storeNum': '123456', 'kind': 'Granny Smith'},
{'type': 'Banana', 'storeNum': '246810', 'kind': 'Organic'},
{'type': 'Orange', 'storeNum': '36912', 'kind': 'C... | python|pandas | 1 |
3,950 | 35,119,310 | How to sort a dataframe based on idxmax? | <p>I have a dataframe like this:</p>
<pre><code> A B C
0 1 2 1
1 3 -8 10
2 10 3 -20
3 50 7 1
</code></pre>
<p>I would like to rearrange its columns based on the index of the maximal absolute value in each column. In column <code>A</code>, the maximal absolute value is in row 3, in <code>B</code> i... | <p>This is ugly, but it seems to work using <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.reindex_axis.html" rel="nofollow"><code>reindex_axis</code></a>:</p>
<pre><code>import numpy as np
>>> df.reindex_axis(df.columns[list(np.argsort(abs(df).idxmax(axis=0)))], axis... | python|sorting|pandas | 1 |
3,951 | 35,273,135 | Get a value in a numpy array from a index in a variable | <p>I am trying to access a value in a multi dimensional numpy array.
This can be easily done when you know everything, for exemple :</p>
<p><code>T = numpy.arrange(9).reshape(3, 3)
T[2, 2]</code></p>
<p>And it returns 8, which is what I want.
Now, Let's assume <code>[2, 2]</code> is stored in <code>index</code> varia... | <p>Try </p>
<pre><code>ind=tuple(2,2)
x[ind]
</code></pre>
<p><code>x[2,2]</code> is the same as <code>x[(2,2)]</code> which is translated into a method call: <code>x.__getitem__((2,2))</code>.</p>
<p>Some <code>numpy</code> functions build an index as a list or array, then convert it to a <code>tuple</code> for use... | python|arrays|numpy|indexing | 2 |
3,952 | 30,818,367 | How to present numpy array into pygame surface? | <p>I'm writing a code that part of it is reading an image source and displaying it on the screen for the user to interact with. I also need the sharpened image data. I use the following to read the data and display it in <code>pyGame</code></p>
<pre><code>def image_and_sharpen_array(file_name):
#read the image dat... | <p>I often use the numpy <code>swapaxes()</code> method:
In this case we only need to invert x and y axis (axis number 0 and 1) before displaying our array :</p>
<blockquote>
<pre><code>return image.swapaxes(0,1),out
</code></pre>
</blockquote> | python|numpy|pygame|pygame-surface | 4 |
3,953 | 67,249,850 | Pandas: how to select columns to be displayed in groupby results? | <p>I have a dataframe with 10 columns from which I want to list some columns of rows where <code>ROUGE_L</code> is maximum grouped by <code>Model</code>, I tried:</p>
<pre><code>sdf = df.groupby(['Model','Checkpoint'])['ROUGE_L'].max()
</code></pre>
<p>It prints:</p>
<pre><code>Model Checkpoint ROUGE_L
4 100... | <p>Need more precision about your original dataframe but the code below should work:</p>
<pre><code>>>> df.loc[df.groupby("Model")["ROUGE_L"].idxmax()]
Model Checkpoint ROUGE_L
2 4 1015300 0.205
7 16000 1040800 0.408
</code></pre>
<p>To select columns, append <code>... | python|pandas | 1 |
3,954 | 67,309,104 | BertForTokenClassification Has Extra Output | <p>I am using PyTorch's BertForTokenClassification pretrained model to do custom word tagging (not NER or POS, but essentially the same). There are 20 different possible tags (using BIO scheme): 9 B's, 9 I's, and an O. Despite there being 19 possible tags, the feed-forward layer that is added on top of BERT has 20 tags... | <p>I figured it out. The reason is because I was not accounting for the <code>PAD</code> token.</p> | pytorch|bert-language-model|huggingface-transformers|named-entity-recognition | 0 |
3,955 | 67,500,461 | How does NumPy compute the inverse of a matrix? | <p>Given a square matrix <code>A</code> as a <a href="https://numpy.org" rel="nofollow noreferrer">NumPy</a> array, like</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
A = np.array(
[
[1, 2, 3],
[3, 4, 6],
[7, 8, 9],
]
)
</code></pre>
<p>which algorithm does ... | <p>Following @projjal 's comment, all of these are equivalent to compute the inverse of a square matrix:</p>
<pre><code>import numpy as np
from scipy.linalg import lu_factor, lu_solve
A = np.array([[1, 2, 3],[3, 4, 6],[7, 8, 9]])
A_inv_1 = np.linalg.inv(A)
A_inv_2 = np.linalg.solve(A,np.eye(A.shape[0]))
A_LU = lu_f... | python|numpy|linear-algebra | 1 |
3,956 | 59,909,904 | How to reshape numpy array of shape (4, 1, 1) into (4, 2, 1)? | <p>Suppose I have a numpy array</p>
<pre><code>arr = np.array([1, 4, 4, 5]).reshape((4, 1, 1))
</code></pre>
<p>Now I want to reshape <code>arr</code> into <code>arr1</code> such that</p>
<pre><code>>>> print(arr1)
[[[1]
[1]]
[[4]
[4]]
[[4]
[4]]
[[5]
[5]]]
>>> arr1.shape
(4, 2, 1)
</cod... | <pre><code>In [484]: arr = np.array([1, 4, 4, 5]).reshape((4, 1, 1))
In [485]: np.concatenate([arr,arr],axis=1)
Out[485]:
array([[[1],
[1]],
[[4],
[4]],
[[4],
[4]],
[[5],
... | numpy | 0 |
3,957 | 59,907,842 | Explode List containing many dictionaries in Pandas dataframe | <p>I am having a dataset which look like follows(in dataframe):</p>
<pre><code>**_id** **paper_title** **references** **full_text**
1 XYZ [{'abc':'something','def':'something'},{'def':'something'},...many others] something
... | <p>Assuming your original DataFrame is a list of dictionaries with one key:value pair and a key named 'reference':</p>
<pre><code>print(df)
id paper_title ... | python|pandas|dataframe|machine-learning|data-cleaning | 2 |
3,958 | 60,032,032 | python Keyword matching(keyword list - column) | <p>supposed dataset,</p>
<pre><code> Name Value
0 K Ieatapple
1 Y bananaisdelicious
2 B orangelikesomething
3 Q bluegrape
4 C appleislike
</code></pre>
<p>and I have keyword list like</p>
<pre><code>[apple, banana]
</code></pre>
<p>In this dataset, matching column 'Value' - [keyword list]... | <p>Use <code>str.contains</code> to match words to your sentences:</p>
<pre><code>keywords = ['apple', 'banana']
df['Value'].str.contains("|".join(keywords)).sum() / len(df)
# 0.6
</code></pre>
<p>Or if you want to keep the rows:</p>
<pre><code>
df[df['Value'].str.contains("|".join(keywords))]
Name ... | python|pandas|dataframe|match|keyword | 2 |
3,959 | 60,128,513 | sum function issue | <p>i am not good at python right now, i have been trying something for a long time but i couldn't do, i want to sum values in a column but i had an error like this:</p>
<pre><code><lambda>() missing 2 required positional arguments: 'y' and 'z'
</code></pre>
<p>These are codes:</p>
<pre><code>threshold = sum(da... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.sum.html" rel="nofollow noreferrer"><code>pd.Series.sum</code></a> and check threshold with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.gt.html" rel="nofollow noreferrer"><code>pd.Series.gt</co... | python|pandas | 0 |
3,960 | 59,989,080 | How to convert 3D string to numpy array which is originated after saving 3D image in CSV | <p>I have a CSV file, which has one column with image data. Before saving to CSV each image was a 3D numpy array. So each cell of this column was a 3D array. After saving to CSV and reading using pandas they converted to string. Now I want to recreate an array from them. Below you can find a sample of string which I wa... | <p>Regarding the error that you added:</p>
<pre><code>ast.literal_eval(my_string_array)
....
[[[205 60 145]
^
SyntaxError: invalid syntax
</code></pre>
<p><code>literal_eval</code> works on a limited subset of Python syntax. For example it will work on a valid list input, e.g. <code>"[[205, 60, 145]]"</c... | python|numpy | 0 |
3,961 | 65,411,383 | saved model can not load layer which contains custom method | <p>I have a model which applies a custom function in the output layer. But the path to this function is static. Whenever I try to load the model on a different system it can not find the function because it searches the wrong path. Actually it uses the path in which the function was located at on the system I saved the... | <p>The problem has nothing to do with paths, when you saved your model, your custom function was serialized and saved inside the HDF5 by Keras, but this format is specific to a python version, so the file can only be loaded with the same python version (it could work with newer versions, but not with older versions of ... | python|tensorflow|keras | 2 |
3,962 | 49,983,957 | Not getting top5 values for each month using grouper and groupby in pandas | <p>I'm trying to get top5 values for amount for each month along with the text column. I've tried <strong>resampling</strong> and <strong>group by</strong> statement</p>
<p><strong>Dataset:</strong></p>
<pre><code>text amount date
123… 11.00 11-05-17
123abc… 10.00 11-08-17
Xyzzy… 22... | <p>assuming that <code>amount</code> is a numeric column:</p>
<pre><code>In [8]: df.groupby(['text', pd.Grouper(key='date', freq='M')]).apply(lambda x: x.nlargest(2, 'amount'))
Out[8]:
text amount date
text date
123abc… 2017-11-30 1 123abc… 10.0 2017-11-08
123… 2017-11-30 0 ... | pandas | 2 |
3,963 | 63,756,716 | Pandas .apply with conditional if in different columns | <p>I have a dataframe as below. I am trying to check if there is a <code>nan</code> in the <code>Liq_Factor</code>, if yes, put 1 otherwise divide <code>use/TW</code>. Result in column Testing.</p>
<pre><code>+---+------------+------------+--------+--------+--------+
| 1 | | Liq_Factor | Zscire | Use | Tw... | <p>You can use apply or another alternative is where function from numpy:</p>
<pre><code>df['Liq_Factor'] = np.where(df['Liq_Factor'] == np.Nan, 1, df['Use']/df['TW'])
</code></pre>
<p>Following your comments below you can do:</p>
<pre><code># create another column with the calculation
df['calc'] = (1/3)* df['ATV']/df[... | python|pandas|apply | 2 |
3,964 | 64,049,115 | Pandas group by and count by date. Then transpose the count to column name | <p>I have this dataframe</p>
<pre><code>import pandas as pd
from datetime import datetime
df = pd.DataFrame([
{"_id": "1", "date": datetime.strptime("2020-09-29 07:00:00", '%Y-%m-%d %H:%M:%S'), "status": "started"},
{"_id": "2", &qu... | <p>You only need <code>unstack</code>:</p>
<pre><code>df.groupby([pd.Grouper(freq='d'), 'status']).size().unstack('status', fill_value=0)
</code></pre>
<p>Output:</p>
<pre><code>status end started
date
2020-09-17 1 0
2020-09-19 2 0
2020-09-25 0 1
2020-09-29 1 ... | python|pandas | 1 |
3,965 | 63,852,176 | Set manual location of legend with matplotlib and GetDistTool | <p>I try to set manually the location for the main legend of a main plot produced by <a href="https://getdist.readthedocs.io/en/latest/" rel="nofollow noreferrer"> Getdist tool</a>.</p>
<p>The plot below represents the 1/2 sigma confidence levels coming from a covariance matrix with joint distributions. It is produced ... | <p>There's an argument in pyplot's <code>legend</code> function called <code>bbox_to_anchor</code>. It's something like a relative deviation and I'm not exactly sure how it works. But basically you can set there some values of horizontal and vertical shifts and then adjust to fit your desired position.</p>
<p>For examp... | python|numpy|matplotlib|legend | 1 |
3,966 | 63,836,589 | How many days does it take to accumulate x inches for everyday? | <p>Here is a snapshot of my dataframe. It goes on for another 60+ years. The only thing I done is set my index as the <strong>DATE</strong> column.</p>
<pre><code> PRCP
DATE
1950-01-01 0.00
1950-01-02 0.00
1950-01-03 0.08
1950-01-04 0.00
1950-01-05 0.00
1950-01-06 0.00
1950-01-07 0.21
1950... | <p>For anyone curious, I tried a different, more basic approach. It may not be efficient but here it is.</p>
<pre><code> depth_list = [1.0,4.0,10.0,20.0] # various threshold depths to reach.
df_j = pd.DataFrame(df['DATE']) # creating an empty dataframe with DATE as the index
for d in depth_lis... | python|pandas | 0 |
3,967 | 63,846,510 | pandas print full column values | <p>Pandas print full ID column when I convert it to string</p>
<p><code>"RiversideCA_" + str(df_clark_county['ID'])</code></p>
<p>I only want to get those ID that is associate with particular row.
<a href="https://i.stack.imgur.com/sDdkr.png" rel="nofollow noreferrer">Please view picture for more calrity</a><... | <p>You need to change type of column to string use <code>astype</code></p>
<pre><code>"RiversideCA_" + df_clark_county['ID'].astype(str)
</code></pre> | pandas|dataframe|data-analysis | 0 |
3,968 | 46,967,581 | Adding values to all rows of dataframe | <p>I have two pandas dataframes <strong><em>df1</em></strong> (of length 2) and <strong><em>df2</em></strong> (of length about 30 rows). Index values of df1 are always different and never occur in df2. I would like to add the average of columns from <strong><em>df1</em></strong> to corresponding columns of <strong><em... | <p>When using <code>mean</code> on <code>df1</code>, it calculates over each column by default and produces a <code>pd.Series</code>. </p>
<p>When adding adding a <code>pd.Series</code> to a <code>pd.DataFrame</code> it aligns the index of the <code>pd.Series</code> with the columns of the <code>pd.DataFrame</code> a... | python|pandas|dataframe|addition | 4 |
3,969 | 46,923,541 | Python Dataframe set value by position and not Index | <p><a href="https://i.stack.imgur.com/g2UpZ.png" rel="nofollow noreferrer">What I tried</a></p>
<p><a href="https://i.stack.imgur.com/g2UpZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g2UpZ.png" alt="so far"></a></p>
<p>So I'm trying to change a single cell in an <code>dataframe</code> but by u... | <p>To set by position, use <code>.iloc</code>, e.g.</p>
<pre><code>df.iloc[0,0] = 2.
</code></pre>
<p>This modifies your dataframe in-place.</p> | python|pandas|dataframe|cell | 0 |
3,970 | 46,841,269 | What does the String mean in numpy.r_? | <p>in numpy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow noreferrer">documents</a>:</p>
<pre><code>>>> np.r_['0,2,0', [1,2,3], [4,5,6]]
array([[1],
[2],
[3],
[4],
[5],
[6]])
</code></pre>
<p>what does the third number mean in ... | <p>I haven't used the string parameter of <code>r_</code> much; it's easier, for me, to work directly with <code>concatanate</code> and its variantes.</p>
<p>But looking at the docs:</p>
<blockquote>
<p>A string with three comma-separated integers allows specification of the
axis to concatenate along, the minimum... | python|numpy | 1 |
3,971 | 46,961,952 | How to make a tuple including a numpy array hashable? | <p>One way to make a numpy array hashable is setting it to read-only. This has worked for me in the past. But when I use such a numpy array in a tuple, the whole tuple is no longer hashable, which I do not understand. Here is the sample code I put together to illustrate the problem:</p>
<pre><code>import numpy as np
... | <p>You claim that</p>
<blockquote>
<p>One way to make a numpy array hashable is setting it to read-only</p>
</blockquote>
<p>but that's not actually true. Setting an array to read-only just makes it read-only. It doesn't make the array hashable, for multiple reasons.</p>
<p>The first reason is that an array with t... | python-3.x|numpy|tuples|hashable | 14 |
3,972 | 38,615,121 | Limit Tensorflow CPU and Memory usage | <p>I've seen several questions about GPU Memory with Tensorflow but I've installed it on a Pine64 with no GPU support.</p>
<p>That means I'm running it with very limited resources (CPU and RAM only) and Tensorflow seems to want it all, completely freezing my machine.</p>
<p><br></p>
<p>Is there a way to limit the am... | <p>This will create a session that runs one op at a time, and only one thread per op</p>
<pre><code>sess = tf.Session(config=
tf.ConfigProto(inter_op_parallelism_threads=1,
intra_op_parallelism_threads=1))
</code></pre>
<p>Not sure about limiting memory, it seems to be allocated on demand, I've... | python|memory-management|tensorflow|cpu-usage | 16 |
3,973 | 67,943,218 | Pandas Plot Multiple Lines Based on Per Column Trend | <p>So I have the following data below, so basically every column after <code>tree</code> is a progression of the value of it's values(e.g Tree_0, Tree_1 and etc.)</p>
<pre><code>tree,ave_1-2021-06-12,ave_2-2021-06-12,ave_3-2021-06-12
Tree_0,290.7,248.7,247.8
Tree_1,261.1,258.7,221.5
Tree_2,220.0,251.9,233.5
Tree_3,246.... | <p>You can first set the Tree column aside as the index and then take the <code>T</code>ranspose to put the trees in the legend and <code>ave_*</code> to the x-axis:</p>
<pre><code>df.set_index("tree").T.plot()
</code></pre>
<p>to get</p>
<p><a href="https://i.stack.imgur.com/kOir0.png" rel="nofollow noreferr... | pandas|matplotlib|data-visualization | 0 |
3,974 | 67,979,101 | Pandas JSON_normalize (nested json) - int object error | <p>i have tried the below code to normalize JSON, but getting error - " AttributeError: 'int' object has no attribute 'values'"</p>
<p>Code:</p>
<pre><code>import pandas as pd
import http.client
import json
conn = http.client.HTTPSConnection("api.buyucoin.com")
payload = ''
headers = {
'Content-Typ... | <p>If you check the help of <code>pd.json_normalize(...)</code>, it says</p>
<pre><code>Parameters
----------
data : dict or list of dicts
Unserialized JSON objects.
</code></pre>
<p>It means that you have to parse it first. Since your <code>data1['data']</code> is a list of jsons, you need to specify <code>data</c... | python|json|pandas | 0 |
3,975 | 67,788,061 | How can I create a line plot with plotly_express, where a pandas dataframe can be selected over a drop down menu? | <p>I want to create a line plot in which the underlying data can be selected over a drop down menu. The data is in a pandas dataframe and I am using plotly_express.</p>
<p>I tried to use this <a href="https://stackoverflow.com/questions/46410738/plotly-how-to-select-graph-source-using-dropdown">post</a> as a basis but ... | <p>fundamentally you need to use <strong>graph object</strong> parameter structure for <strong>updatemenus</strong></p>
<ul>
<li>have generated a dataframe that appears to match your structure</li>
<li>create the graph using <strong>plotly express</strong></li>
<li>generate <strong>updatemenu</strong> which are paramet... | python|pandas|drop-down-menu|plotly|plotly-express | 0 |
3,976 | 67,969,133 | Block matrix with optimization variables in CVXPY | <p>I want to build a block matrix that has the form</p>
<pre><code>Q = [[A, B], [C, D]]
</code></pre>
<p>where each of the blocks <code>A,B,C,D</code> are the following matrices:</p>
<ul>
<li><code>A</code> is simply 2x2 identity matrix</li>
<li><code>B</code> is the embdedding of a 2x1 vector <code>b=(b_1,b_2)</code> ... | <p>You might get a better answer at other than a programming site. However in this case it's straightforword.</p>
<p>Since swapping two rows and (the same) two columns can be done by</p>
<pre><code>M -> Q'*M*Q
</code></pre>
<p>where Q is a permutation matrix (and hence orthogonal), such a transformed matrix will be ... | python|numpy|mathematical-optimization|cvxpy | 0 |
3,977 | 67,927,011 | Python SQLAlchemy Importing Table Names in Lowercase (Snowflake) | <p>Using both pandas.read_sql as well as pandas.read_sql_table, I keep getting the entire table back with all the column names in lowercase.
Is there anyway around this?</p>
<p>I wanted to do some transformations on the data then replace the table in the DB, but it's a pain if doing so changes all the column names to l... | <blockquote>
<p>Snowflake stores all case-insensitive object names in uppercase text.
In contrast, SQLAlchemy considers all lowercase object names to be
case-insensitive. Snowflake SQLAlchemy converts the object name case
during schema-level communication, i.e. during table and index
reflection. If you use uppercase ob... | python|sql|pandas|sqlalchemy|snowflake-cloud-data-platform | 1 |
3,978 | 31,845,258 | multi index plotting | <p>I have some data where I've manipulated the dataframe using the following code:</p>
<pre><code>import pandas as pd
import numpy as np
data = pd.DataFrame([[0,0,0,3,6,5,6,1],[1,1,1,3,4,5,2,0],[2,1,0,3,6,5,6,1],[3,0,0,2,9,4,2,1],[4,0,1,3,4,8,1,1],[5,1,1,3,3,5,9,1],[6,1,0,3,3,5,6,1],[7,0,1,3,4,8,9,1]], columns=["id",... | <p>I would use a factor plot from seaborn.</p>
<p>Say you have data like this:</p>
<pre><code>import numpy as np
import pandas
import seaborn
seaborn.set(style='ticks')
np.random.seed(0)
groups = ('Group 1', 'Group 2')
sexes = ('Male', 'Female')
means = ('Low', 'High')
index = pandas.MultiIndex.from_product(
[... | python|pandas|matplotlib|seaborn | 33 |
3,979 | 41,336,576 | What are the input/output tensors, for the translation(RNN) tutorial? | <p>As per <a href="https://stackoverflow.com/questions/39781946/unable-to-deploy-a-cloud-ml-model">Unable to deploy a Cloud ML model</a> if I want to deploy my model to the Google Cloud ML I need explicitly set the "input"/"output" collections that will store the references to the input/output tensors, like this:</p>
... | <p>According to the code below, the inputs are: encoder_inputs, decoder_inputs, target_weights, and the output is the third element of the output of the return value of step()</p>
<p><a href="https://github.com/petewarden/tensorflow_makefile/blob/master/tensorflow/models/rnn/translate/seq2seq_model.py#L170" rel="nofol... | tensorflow | 1 |
3,980 | 41,337,477 | Select non-null rows from a specific column in a DataFrame and take a sub-selection of other columns | <p>I have a dataFrame which has several coulmns, so i choosed some of its coulmns to create a variable like this <code>xtrain = df[['Age','Fare', 'Group_Size','deck', 'Pclass', 'Title' ]]</code> i want to drop from these coulmns all raws that the Survive coulmn in the main dataFrame is nan.</p> | <p>You can pass a boolean mask to your df based on <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="noreferrer"><code>notnull()</code></a> of 'Survive' column and select the cols of interest:</p>
<pre><code>In [2]:
# make some data
df = pd.DataFrame(np.random.randn(5,7), ... | python|pandas | 52 |
3,981 | 41,598,763 | How to custom sort pandas multi-index? | <p>The following code generates the pandas table named <code>out</code>. </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Book': ['B1', 'B1', 'B2', 'B3', 'B3', 'B3'],
'Trader': ['T1', 'Z2', 'Z2', 'T1', 'U3', 'T2'],
'Position':[10, 33, -34, 87, 43, 99]... | <p>Pandas has built-in functionality within the <code>pivot_table</code> function to compute the marginal totals.</p>
<pre><code>table = pd.pivot_table(df,
index='Book',
columns='Trader',
values='Position',
aggfunc=np.sum,
margins=True,
... | python|pandas | 2 |
3,982 | 27,628,765 | Apply numpy index to matrix | <p>I have spent the last hour trying to figure this out</p>
<p>Suppose we have</p>
<pre><code>import numpy as np
a = np.random.rand(5, 20) - 0.5
amin_index = np.argmin(np.abs(a), axis=1)
print(amin_index)
> [ 0 12 5 18 1] # or something similar
</code></pre>
<p>this does not work:</p>
<pre><code>a[amin_index]
... | <p>Is because <code>argmin</code> returns indexes of columns for each of the rows (with <code>axis=1</code>), therefore you need to access to each row at those particular columns:</p>
<p><code>a[range(a.shape[0]), amin_index]</code></p> | python|arrays|numpy | 1 |
3,983 | 61,397,388 | Calculate grouped rolling cumulative sum with multiplier | <p>I would like to calculate the rolling cumulative sum after multiplying a column by a constant within a Pandas DataFrame. For example, given the series:</p>
<pre><code>0
0
1
0
0
0
</code></pre>
<p>I would like to apply a constant multiple, for example 1.5, to cumulatively to compute the following series:</p>
<pre>... | <p>This is a one-liner but it produces the output in the same <code>Value</code> column, since it only has <code>0</code> or <code>1</code> multiplying <code>1 time x</code> is the same as <code>0 + x</code></p>
<pre><code>df.iloc[df.Value.idxmax()+1:, df.columns == 'Value'] =
(df.iloc[df.Value.idxmax()+1:, df.col... | python|pandas | 2 |
3,984 | 61,357,913 | How to create matrix from set of lists which contains more than 4 values? | <p>I have set of lists (i.e. list x , list y, list z), e.g.</p>
<pre><code>x = ['41.95915452', '41.96333025', '41.98135503', '41.95096716', '41.96504172', '41.96526867', '41.98068483', '41.98117072', '41.98059828', '41.95915452', '41.96333025', '41.98135503', '41.95096716']
y = ['12.60718918', '12.62725589', '12.6201... | <p>Use numpy vstack and transpose. </p>
<p>Try this code.</p>
<pre><code>np.vstack([x, y, z]).T
</code></pre>
<p>If you want the output is list, then use</p>
<p><code>np.vstack([x, y, z]).T.tolist()</code></p> | python|list|numpy|matrix|eigenvalue | 1 |
3,985 | 61,362,484 | Why use the pip in a conda virtual environment makes the global effect? | <p>previously, I installed the tensorflow 1.13 in my machine.
There are some projects depending on different version of tensorflow and I do not want to mixed up different version of tensowflow.</p>
<p>So I just tried create a env called tf2.0 and used pip to install tensorflow 2.0.0b1 in that specific virtual environm... | <p>It's hard to troubleshoot the described conditions without more details (exact commands run, showing <code>PATH</code> before and after and post activation, etc.). Nevertheless, you can try switching to following <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#pip-in... | tensorflow|pip|anaconda|conda|tensorflow2.0 | 0 |
3,986 | 68,506,555 | Pandas If Else condition on multiple columns | <p>I have a df as:</p>
<pre><code>df:
col1 col2 col3 col4 col5
0 1.36 4.31 7.66 2 2
1 2.62 3.30 2.48 2 1
2 5.19 3.58 1.62 0 2
3 2.06 3.16 3.50 1... | <p>When you do a bitwise operation on Series objects or arrays, you get an array of booleans, each of whose elements is True or False. Those are basically 0 or 1, and in fact more convenient in most cases:</p>
<pre><code>df['col6'] = (df['col4'] > 1) & (df['col5'] > 1)
df['col7'] = df['col6']
</code></pre>
<p... | python|pandas|dataframe|if-statement | 2 |
3,987 | 68,512,460 | to group but not using the groupby function of Python/Pandas | <pre><code>INPUT DATA-
array([['00:00:00', 20, 15.27],
['00:15:00', 20, 9.07],
['00:30:00', 20, 7.33],
...,
['00:30:00', 407, 34.0],
['00:00:00', 407, 172.0],
['00:10:00', 407, 187.0]], dtype=object)
</code></pre>
<p>First column - time
second column - id
third column - price</... | <p>Update:</p>
<pre><code>from collections import defaultdict
d = defaultdict(list)
for t,id,price in trial:
d[t,id].append(price)
print (d)
</code></pre>
<p>I am able to group the prices based on t and id. How do I find the sum of the prices for each id?</p> | python|pandas|dataframe|numpy | 0 |
3,988 | 36,354,101 | Linear regression with tensorflow is very slow | <p>I am trying to implement a simple linear regression in tensorflow (with the goal of eventually extending it to more advanced models). My current code looks as follows:</p>
<pre><code>def linear_regression(data, labels):
# Setup placeholders and variables
num_datapoints = data.shape[0]
num_features = dat... | <p>It is so slow, since you train the network point by point which requires <code>NUM_STEPS * num_datapoints</code> iterations (which leads to <strong>5 hundred thousands</strong> cycles).</p>
<p>All you actually need to train your network is</p>
<pre><code>for i in range(NUM_STEPS):
sess.run(train_step, feed_dic... | python|performance|regression|tensorflow | 5 |
3,989 | 36,462,909 | How to set matrix columns iteratively and fast? | <p>I have the following Python code:</p>
<pre><code>H = np.zeros(shape=(N-q+1,q),dtype=complex)
for i in range(0,N-q+1):
H[i,:] = u[i:q+i]
</code></pre>
<p>where <em>N</em> and <em>q</em> are constants and <em>u</em> is a vector long enough so no out of bounds error would occur when <em>u[i:q+i]</em>.</p>
<p>I h... | <p>You could use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ndarray.strides.html" rel="nofollow"><code>stride.as_strided</code></a>:</p>
<pre><code>import numpy.lib.stride_tricks as stride
s = u.strides[0]
H2 = stride.as_strided(u, shape=(N-q+1,q), strides=(s, s)).astype(complex)
</code... | python|numpy|optimization | 2 |
3,990 | 53,331,692 | Python Groupby Running Total/Cumsum column based on string in another column | <p>I want to create 2 Running Total columns that ONLY aggregate the <code>Amount</code> values based on whether <code>TYPE</code> is <code>ANNUAL</code> or <code>MONTHLY</code> within each <code>Deal</code>
so it would be <code>DF.groupby(['Deal','Booking Month'])</code> then somehow apply a sum function when <code>TYP... | <p>Use <code>filters</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transform.html" rel="nofollow noreferrer"><code>transform</... | python|pandas|cumulative-sum | 3 |
3,991 | 52,973,306 | Finding average of the smallest 4 values in an array which generates 200 random numbers | <p>I have the following code run in the spyder IDE:</p>
<pre><code>idnum = 201034628
seed(idnum);
w = np.random.rand(200)
print(w)
</code></pre>
<p>This generates the following result:</p>
<pre><code>[0.00176212 0.79092217 0.1759531 0.00239256 0.78842458 0.30404404
0.25633004 0.88271124 0.72031936 0.17356416 0.567... | <p>You can use <a href="https://docs.python.org/3.6/library/heapq.html#heapq.nsmallest" rel="nofollow noreferrer"><code>heapq.nsmallest</code></a> which should be slightly faster than sorting:</p>
<pre><code>import heapq
import statistics
print(statistics.mean(heapq.nsmallest(4, w)))
</code></pre> | python|numpy | 2 |
3,992 | 65,715,347 | Firestore with Bigquery or Tensorflow for training and predictions? | <p>I am using Google-Firestore as data storage for my mobile application. I want to Pub/Sub <code>onChange</code> or export data every day to train a custom AI model. The model would make predictions based on which I can nudge the user on the app.</p>
<p>What is the best Google Cloud Platform architecture for something... | <p>It all depends on what you are trying to achieve. Try and keep it as simple as possible otherwise, you will create a problematic model that is hard to debug if it goes wrong. I would take a look at the Firebase Machine Learning mobile SDK. I have added some of the documentation below for you to see if it meets your ... | tensorflow|google-cloud-platform|google-cloud-firestore|google-bigquery | 0 |
3,993 | 65,785,748 | how can i call mysql function using sqlalchemy in python? | <p>i'm trying to call a function in mysql from python here is my code
using sqlalchemy</p>
<pre><code>CREATE DEFINER=`root`@`localhost` FUNCTION `my_function`() RETURNS int
READS SQL DATA
DETERMINISTIC
BEGIN
insert into employeedata (select * from employee where joiningdate <'20160101');
RETURN 1;
END
</co... | <p>If you just want to run a function you don't need to use Pandas SQL interface. You can use the following:</p>
<pre><code>from sqlalchemy import text
with engine.connect() as connection:
result = connection.execute(text("SELECT my_function()"))
print(result)
</code></pre>
<p>Reference: <a href="htt... | python|mysql|pandas|database|sqlalchemy | 0 |
3,994 | 65,874,080 | ValueError: zero-dimensional arrays cannot be concatenated, | <p>I have two arrays with axis=0 (there are the result of the mean and the std of a df):</p>
<pre><code>df_cats =
0 58.609619
1 105.926514
2 76.706543
3 75.405762
4 68.937744
...
75 113.124268
76 125.557373
77 130.514893
78 141.373779
79 109.185791
Length: 80, dtype:... | <p>One dimensionnal arrays don't have a second dimension. This is where your problem comes from. You can concatenate by modifying the shape of these arrays to turn them into 2D arrays with only one column with the following code :</p>
<pre><code>df_dogs.shape=(df_dogs.shape[0],1)
df_cats.shape=(df_cats.shape[0],1)
</co... | python|arrays|numpy|concatenation|pca | 0 |
3,995 | 21,285,380 | Find column whose name contains a specific string | <p>I have a dataframe with column names, and I want to find the one that contains a certain string, but does not exactly match it. I'm searching for <code>'spike'</code> in column names like <code>'spike-2'</code>, <code>'hey spike'</code>, <code>'spiked-in'</code> (the <code>'spike'</code> part is always continuous). ... | <p>Just iterate over <code>DataFrame.columns</code>, now this is an example in which you will end up with a list of column names that match:</p>
<pre><code>import pandas as pd
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)
spike_cols = [col for col in... | python|python-3.x|string|pandas|dataframe | 363 |
3,996 | 63,415,585 | Pandas multiple merge creates multidimensional duplicate columns | <p>My goal is to merge 4 excel worksheets into 1 based on similar Hostnames, Serial Number, Category... I'm using the pandas merge function below.</p>
<pre><code>InventoryDf = pd.read_excel("Inventory.xlsx", sheet_name='Inventory')
SoftwareDf = pd.read_excel("Inventory.xlsx", sheet_name='Software')
... | <p>Started with advanced techniques using <code>functools</code>. Add <code>inspect</code> to the mix <a href="https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string">get variable name</a></p>
<ol>
<li>iterate over your list of dataframes. Capture the name and rename the <em>IP addres... | python|pandas|dataframe|merge|duplicates | 1 |
3,997 | 63,488,042 | Python fast insert multiple characters into all possible places of string | <p>I want to insert multiple characters into all possible places of string, my current implementation is using <code>itertools.combinations_with_replacement</code> (<a href="https://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement" rel="nofollow noreferrer">doc</a>) to list all possible ... | <p>A recursive solution:</p>
<pre><code>def mix(s, t, p=''):
return s and t and mix(s[1:], t, p+s[0]) + mix(s, t[1:], p+t[0]) or [p + s + t]
</code></pre>
<p>My <code>p</code> is the prefix built so far. In each recursive step, I extend it with the first character from <code>s</code> or the first character from <code... | python|numpy | 1 |
3,998 | 21,467,628 | Python method to compare 1 value_id against another columns' value_ids in separate dataframes? | <p>I have 2 csv files. Each contains a data set with multiple columns and an ASSET_ID column. I used pandas to read each csv file in as a df1 and df2. My problem has been trying to define a function to iterate over the ASSET_ID value in df1 and compare each value against all the ASSET_ID values in df2. From there I wan... | <p>Create a boolean mask of the values will index the rows where the 2 df's match, no need to iterate and much faster.
Example:</p>
<pre><code># define a list of values
a = list('abcdef')
b = range(6)
df = pd.DataFrame({'X':pd.Series(a),'Y': pd.Series(b)})
# c has x values for 'a' and 'd' so these should not match
c =... | python|csv|pandas|comparison|dataframe | 2 |
3,999 | 53,744,941 | Creating IsHoliday feature in pandas dataframe | <p>i'm trying to create an IsHoliday feature in my pd.dataframe,having datetime as index, based on a csv file whice includes the holidays in one year. Having little experience with pandas i can think of an iterative approach by comparing the values of the two dataframes
To be more specific :</p>
<pre><code>for i in r... | <p>You might want to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> for that:</p>
<pre><code>df['IsHoliday'] = np.where(df.index.isin(Holidays),True,False)
</code></pre> | python|pandas | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.