Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
366,000 | 67,103,081 | Accuracy of solutions of differential equations with DeepXDE | <p>We used DeepXDE for solving differential equations. (DeepXDE is a framework for solving differential equations, based on TensorFlow). It works fine, but the accuracy of the solution is limited, and optimizing the meta-parameters did not help. Is this limitation a well-known problem? How the accuracy of solutions can... | <p>There are actually some methods that could increase the accuracy of the model:</p>
<ol>
<li>Random Resampling</li>
<li>Residual Adaptive Refinement (RAR): <a href="https://arxiv.org/pdf/1907.04502.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1907.04502.pdf</a></li>
</ol>
<p>They even have an implemented exam... | tensorflow|optimization|deep-learning | 0 |
366,001 | 67,167,886 | Make TensorFlow use the GPU on an ARM Mac | <p>I have installed <code>TensorFlow</code> on an M1 (<strong>ARM</strong>) Mac according to <a href="https://github.com/apple/tensorflow_macos/issues/153" rel="nofollow noreferrer">these instructions</a>. Everything works fine.</p>
<p>However, model training is happening on the <code>CPU</code>. How do I switch traini... | <h2>Update</h2>
<p>The <a href="https://github.com/apple/tensorflow_macos" rel="nofollow noreferrer">tensorflow_macos tf 2.4</a> repository has been archived by the owner. For <code>tf 2.5</code>, refer to <a href="https://developer.apple.com/metal/tensorflow-plugin/" rel="nofollow noreferrer">here</a>.</p>
<hr />
<p>I... | python|macos|tensorflow|deep-learning|arm | 3 |
366,002 | 66,916,390 | Error when adapting batch size in tf.keras.utils.Sequence | <p>I study using tf.keras.utils.Sequence on Tensorflow 2.4.1. I used the example code in Sequence in API document (<a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence</a>) and finetuned by adding <code>... | <p>I faced exactly this problem. In my case, I update the data after every epoch (the number increases). I notice that the number of batches in each epoch stays the same (although it should depend on the number of samples). My guess is that it is called once during initialization and not updated during each epoch.</p> | keras|sequence|tensorflow2.0|data-generation | 0 |
366,003 | 67,127,120 | Dense layer binary classification cannot be set to 2 | <p>I'm fairly new to keras and tensorflow. I'm trying to figure out why running my code gives me an error when using dense layer = 2 and not dense = 1. This is how I assigned the classes based on a dir structure:</p>
<pre><code>res_scans = np.array([process_scan(path) for path in res_scan_paths])
non_res_scans = np.arr... | <p>From the following statement of yours, it seems like you're trying to build a binary classification model.</p>
<pre><code># For the CT scans had the presence of viral pneumonia
# assign 1, for the normal ones assign 0.
</code></pre>
<p>That's why the correct setting would be as follows:</p>
<pre><code>...
# (1)
# la... | python|tensorflow|machine-learning|keras|deep-learning | 2 |
366,004 | 67,083,192 | how to unstack or unpivot a pandas dataframe based on conditional row values? | <p>I have a pandas dataframe that looks like this:</p>
<p><a href="https://i.stack.imgur.com/bfhWW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bfhWW.png" alt="enter image description here" /></a></p>
<p>But I need to pull out table and chair into their own columns to compare side by side like so:... | <p>Let us try <code>get_dummies</code></p>
<pre><code>df = df.join(df.furniture.where(df.furniture.isin(["table","chair"]),'amount').str.get_dummies().mul(df.pop("amount"),0))
df
Out[87]:
CID furniture amount chair table
0 1 couch 2 0 0
1 2 couch ... | pandas|unpivot | 2 |
366,005 | 66,817,950 | I am trying to make a contour plot animation in matplotlib | <p>I have 16 contour plots with changing titles and I want to just create an animation from the 16 contour plots.</p>
<p>I first set up the images and the data below, but I am having little luck in the animation part.
I am trying to follow this example but I'm struggling:
<a href="https://stackoverflow.com/questions/42... | <p>This will give you an array with all subplots:</p>
<pre class="lang-py prettyprint-override"><code>fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25
</code></pre>
<p>You have to index the <code>ax</code> array to plot on the subfigures:</p>
<pre class="lang-py prettyprint-override"><code># plot on th... | python|numpy|matplotlib|animation|jupyter | 1 |
366,006 | 67,045,753 | logits and labels must be broadcastable: logits_size=[384,2971] labels_size=[864,2971] | <p>I am training a RNN based English to Hindi Neural Machine Translation model. I have an LSTM layer in it and attention layer, too. I am getting an error that <code>(0) Invalid argument: logits and labels must be broadcastable: logits_size=[384,2971] labels_size=[864,2971]</code></p>
<p>My model summary is</p>
<pre><... | <p>You have to properly connect your embedding to CNN and your CNN to LSTM</p>
<p>Encoder:</p>
<pre><code>num_encoder_tokens = 333
latent_dim = 128
encoder_inputs = Input(shape=(None,))
enc_emb = Embedding(num_encoder_tokens, latent_dim, mask_zero = True)(encoder_inputs)
encoder_CNN = Conv1D(16, kernel_size=11, activ... | python-3.x|tensorflow|keras|conv-neural-network|lstm | 1 |
366,007 | 66,926,517 | Pandas: forcing merge from multiple rows from Excel file into a single row(s) into single lines | <p>I've been given a few sets of MS-Excel worksheets with a lot of nested data in areas, and I have researching for a few hours looking for a way to reduce each 'id' row to single rows. Specifically merging 'Step ID', 'Install Steps', and 'Expected step' into single lines with some formatting.</p>
<p>Here is shortened... | <p>If you <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer"><strong><code>melt()</code></strong></a> the dataframe:</p>
<pre class="lang-py prettyprint-override"><code>melt = df.melt(['Name', 'ID', 'Host', 'Step ID']).ffill()
# Name ID Host Step ID variable... | python|excel|pandas | 2 |
366,008 | 66,775,878 | Pandas: determine id of tree of categories from two columns | <p>I have a tree of categories setup as follows. The top level is defined by parent_id = -1 (in this case I have two nodes (i.e. Linear Asset and Point Asset) at the top level.</p>
<pre><code>asset_tree = [
{'id': 1, 'name': 'Linear Asset', 'parent_id': -1},
{'id': 2, 'name': 'Lateral', 'parent_id': 1},
{'i... | <p>You can first transform <code>asset_tree</code> into a nested dictionary, storing the relationships between the levels. This way, you can then use a recursive generator function that takes in a level row and traverses new tree, using the names in the row to get the id of the right most name in the level:</p>
<pre><c... | python|pandas | 1 |
366,009 | 67,117,804 | Find and replace a duplicate value in pandas DF | <p>I have the below df in pandas:</p>
<p><a href="https://i.stack.imgur.com/6ZGgB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6ZGgB.png" alt="enter image description here" /></a></p>
<p>I need to find the duplicate value, in this case the number 1 in the index 2 and apply the formula ma.trunc(ma.... | <p>You can locate all of the duplicates with the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer">duplicated()</a> command. Note that keep="first" (default value) will prevent the first occurence from being marked as a duplicate.</... | python|pandas | 1 |
366,010 | 67,011,517 | Jupyter Notebook Import Error: cannot import name 'np_version_under1p17' from 'pandas.compat.numpy' | <pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as md
import datetime as dt
import time
from zipfile import ZipFile
from matplotlib.pyplot import xticks
%matplotlib inline
</code></pre>
<blockquote>
<p>------------------------------------... | <p>I encountered the same problem and I think that there is no "<em>one-step</em>" solution.
For me, I recently installed python 64-bit version as I was using the 32-bit version till then. But due to some reason the new version was installed in a different location.
My problem was actually with the notebook. ... | python|pandas|numpy|jupyter-notebook|anaconda | 1 |
366,011 | 67,017,887 | Why can't I implement my TensorFlow while-loop correctly? | <p>I have two tensors as follows:</p>
<pre><code>a = tf.constant([1, 0, 0, 1, 0, 1, 1])
b = tf.constant(0) # see below
</code></pre>
<p>I want to add one to b each time a[i] = 1
So I did this:</p>
<pre><code>i = tf.constant(0)
def condition(i):
return i < 7
def f1(): return 1
def f2(): return 0
def body(i):
... | <p>You can't have border effects in your loop. It means that your condition function and your body function must take as argument all the variable that you are using in your loop.</p>
<p>You should declare your functions the following way:</p>
<pre><code>def condition(i,a,b):
return i < 7
def f1(): return 1
def... | tensorflow|while-loop | 0 |
366,012 | 67,061,451 | Check if a string is present in multiple lists | <p>I am trying to categorize a dataset based on the string that contains the name of the different objects of the dataset.</p>
<p>The dataset is composed of 3 columns, df['Name'], df['Category'] and df['Sub_Category'], the Category and Sub_Category columns are empty.</p>
<p>For each row I would like to check in differe... | <p>Here is an approach that expands lists, merges them and re-combines them.</p>
<pre><code>df = pd.DataFrame({"name":['vitrine murale vintage','commode ancienne', 'lustre antique', 'solex', 'sculpture médievale', 'jante voiture', 'lit et matelas', 'turbine moteur']})
furniture_check = ['canape', 'chaise', 'b... | python|pandas|list|numpy | 0 |
366,013 | 66,791,588 | how to convert column values to str when reading multi-sheet xlsx using pd.read_excel? | <p>I have a muti-sheet <code>xlsx</code> file which I want to process selected pages and finally save them as <code>CSV</code>.</p>
<p>This is a snapshot of a few raws from one page:</p>
<p><a href="https://i.stack.imgur.com/WuAH5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WuAH5.png" alt="enter ... | <p>the excel set those values to datetime format. maybe you can postprocess with the dataframe,</p>
<pre><code>nKCol = df['Contract']
oKCol = df['Contract'].copy()
# update cell to %b-%y string format; Nan if error
nKCol = pd.to_datetime(nKCol, er... | python|excel|pandas|openpyxl | 1 |
366,014 | 66,851,759 | knn image classification, bad accuracy | <p>I have an knn algorithm for image classification. In trainImages I have images for training, in trainLabels their's labels, validationImages and validationLabels are for testing</p>
<pre><code>import imageio
import glob
import numpy as np
import os
import csv
trainImages = []
for imagePath in glob.glob('C:/Users/ra... | <p>KNN does not elaborate attributes of specific class. It just finds difference on (lets say) every pixel value but not features. KNN works better on data having columns as attributes (Tabular data) in which every attribute defines a specific feature. but in image case, every pixel value do not define specific feature... | python|numpy|machine-learning|knn | 1 |
366,015 | 67,000,961 | How to count no. of rows between time intervals(hourly) in pandas? | <p>My data has various columns including a date and a time column. The data is stretched across three months. I need to count no. of rows in a particular hour irrespective of the date. So that would mean getting the count of rows in 00:00 to 01:00 window and similarly for the rest 23 hours. How do I do that? Overall I ... | <p>You can split the time string with the delimiter <code>:</code>. Then create an another column <code>hour</code> for hour. Then use <code>groupby()</code> to group them on the basis of new column <code>hour</code>. You can now store the data in a new series or dataframe to get the desired output</p> | python|pandas|dataframe | 1 |
366,016 | 66,948,554 | What's the most efficient way to add (new) documents from a Dataframe to MongoDB? | <p>In this use case, I am trying to add documents to a MongoDB collection using pymongo that are retrieved from various RSS news feeds based on the date (not datetime), title, and article summary in dataframe format (the date being the index to the dataframe).</p>
<p>When I store the dataframe to the database, they are... | <p>I'd be minded to take an <code>md5</code> hash of the document and store that as the <code>_id</code>; then you can just use <code>insert_many()</code> with <code>ordered=False</code> to insert any items that aren't duplicates; you can run this as often as you like and only new items will be added; bear in mind that... | python|pandas|mongodb|dataframe|pymongo | 1 |
366,017 | 66,942,429 | iterating through a nested list of strings to get first item | <p>I'm trying to extract items from column <code>gen</code> in a dataframe (sample below). My goal is to iterate through every line in <code>gen</code> into a new dataframe column with items matching the predefined list <code>genre_code</code>.</p>
<pre><code>df = pd.DataFrame({'id': [620, 843, 986], 'tit': ['AAA', 'BB... | <p>If you want to filter <code>gen</code> column based on your list, you can do:</p>
<pre><code>df["gen"] = df["gen"].apply(lambda x: [g for g in x if g in genre_code])
print(df)
</code></pre>
<p>Prints:</p>
<pre><code> id tit gen
0 620 AAA []
1 843 BBB [Scien... | python|pandas|loops|nested-lists | 3 |
366,018 | 66,774,281 | tensorflow image_dataset_from_directory difference from PIL load | <p>tensorflow version:2.5.0-dev20210301</p>
<p>pillow version:8.1.2</p>
<p>I trained model using API image_dataset_from_directory to load image
and tried to inference image using PIL,</p>
<p>first, I put only one image in my directory.</p>
<p>But I found the return of image_dataset_from_directory doesn't match PIL read... | <p>when you use image_dataset_from_directory(path etc it looks in the directory defined by path and looks for sub directories. It process the subdirectories in alphanumeric order. Then it fetches the files from the sub directories again in alphanumeric order. So when you do take[1] the file you are actually getting m... | python-3.x|tensorflow|python-imaging-library | 0 |
366,019 | 66,818,735 | i got runtime error on use of Random Search Keras Tuner for optimization | <p>I use Keras tuner for hyperparameter tuning on digit recognizer datasets but got error<br />
first I made build method in CNNHyperModel class for hyper parameter tuning
second I use Conv2D , MaxPooling2D, Dropout then neural network
I already imported libraries which i required for this program</p>
<pre><code>class ... | <p>Kernel size should be 3x3 not 3 . i.e kernel_size=(3,3) . Kernel is a matrix and not a single digit.</p> | python-3.x|keras-layer|tf.keras|tensorflow2.x|keras-tuner | 0 |
366,020 | 67,009,111 | KElbowvisualizer Re-Formatting other Plots | <p>I randomly selected a number of clusters to plot my dataset with to see the distribution and then I went back and visualized the optimal # of clusters to use with my dataset by using KElbowvisualizer. However, when I went back to my original distribution to change the number of clusters, the formatting of the plot c... | <p>I realized that the problem here is that the imported KElbowVisualizer changes the format of all plots but I could not find a way to turn it off while plotting, so it should only be imported for visualizing the k-elbow distribution and then turned off (not imported) after.</p>
<pre><code>from yellowbrick.cluster imp... | python|pandas|matplotlib|k-means|yellowbrick | 0 |
366,021 | 66,783,914 | Creating multiple plots with for loop? | <p>I have a dictionary of dataframes where the key is the name of each dataframe and the value is the dataframe itself.</p>
<p>I am looking to iterate through the dictionary and quickly plot the top 10 rows in each dataframe. Each dataframe would have its own plot. I've attempted this with the following:</p>
<pre><code... | <p>By default, <a href="https://seaborn.pydata.org/generated/seaborn.barplot.html" rel="nofollow noreferrer">seaborn.barplot()</a> plots data on the current Axes. If you didn't specify the Axes to plot on, the latter will override the previous one. To overcome this, you can either create a new figure in each loop or pl... | python|pandas|matplotlib|seaborn | 0 |
366,022 | 66,782,661 | Pandas Filtering Between Grouped Rows | <p>Suppose I had a pandas table "df" that looks like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">FIELD1</th>
<th style="text-align: center;">FIELD2</th>
<th style="text-align: center;">FIELD3</th>
<th style="text-align: center;">FIELD4</th>
<th... | <p>You can use a join/merge to achieve this:</p>
<pre><code>df_merge = df.merge(df
, left_on=['FIELD1','FIELD2']
, right_on=['FIELD1','FIELD5']
,suffixes=('_l', '_r')
)
df_merge.loc[:,['FIELD1_l','FIELD2_l','FIELD3_l','FIELD4_l','FIELD5_l']]
<... | python|pandas | 0 |
366,023 | 66,928,389 | I'm getting the type error on writing the following code | <p>Code on Jupyter Notebook:</p>
<pre><code>import pandas as pd
import matplotlib as plt
%matplotlib inline
import numpy as np
data = pd.read_csv("E:Datascience\Bivariate\Titanic.csv")
data.head()
data.shape
data['Survived'].value_counts()
data=pd.get_dummies(data)
data.fillna(0,inplace=True)
data.sha... | <p>use this</p>
<pre><code>logreg=LogisticRegression()
</code></pre>
<p>instead of</p>
<pre><code> logreg=LogisticRegression
</code></pre>
<p>This will solve your issue.</p>
<p>You can refer this <a href="https://towardsdatascience.com/logistic-regression-using-python-sklearn-numpy-mnist-handwriting-recognition-matplot... | python|pandas|jupyter|typeerror | 3 |
366,024 | 66,867,941 | Getting an error when checking if values in a list match a column PANDAS | <p>I'm just wondering how one might overcome the below error.</p>
<p><strong>AttributeError: 'list' object has no attribute 'str'</strong></p>
<p>What I am trying to do is create a new column "PrivilegedAccess" and in this column I want to write "True" if any of the names in the first_names column m... | <p>It seems you need select one column for <code>str.contains</code> and then use map or convert boolean to strings:</p>
<pre><code>Search_for_These_values = ['Privileged','Diagnostics','SYS','service account'] #creating list
pattern = '|'.join(Search_for_These_values)
PrivilegedAccounts_DF = pd.DataFrame({'first_name... | python|pandas | 0 |
366,025 | 67,166,618 | How to merge two Pandas columns that are not identical into 1 column | <p>I want to be able to combine two specific columns from a dataframe that aren't identical into a new column.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Team or Club</th>
<th>After School Activity</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Yes</td>
<td>Drama</td>... | <pre><code>from numpy import nan
</code></pre>
<p>Just use <code>apply()</code> method and <code>replace()</code> method:</p>
<pre><code>df=df.replace(nan,' ',regex=True)
combined=df[['Team or Club', 'After School Activity']].apply(','.join,1)
</code></pre>
<p>Now If you print <code>combined</code> you will get your d... | python|pandas|dataframe | 0 |
366,026 | 67,005,037 | Rules in String into in Pandas | <p>I would like to use Pandas to read simple rules in string.</p>
<p>I write this and it's worked :</p>
<pre><code>import numpy as np
import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
a = "(df['col1'] > 1) & (df['col2'] > 3)"
df[eval(a)]
</code></pre>
<p>But, I woul... | <pre><code>>>> import numpy as np
>>> import pandas as pd
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df
| | col1 | col2 |
|---:|-------:|-------:|
| 0 | 1 | 3 |
| 1 | 2 | 4 |
>>> a = 'col1 > 1 & col... | python|pandas | 2 |
366,027 | 67,061,163 | only keep part of a list in pandas series | <p>I have a Pandas series containing a list of strings like so:</p>
<pre><code>series_of_list.head()
0 ['hello','there','my','name']
1 ['hello','hi','my','name']
2 ['hello','howdy','my','name']
3 ['hello','mate','my','name']
4 ['hello','hello','my','name']
type(series_of_list)
pandas.core.series.Series
</code></pre>
<... | <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html#pandas.Series.apply" rel="nofollow noreferrer"><code>pandas.Series.apply()</code></a> the function on each element.</p>
<pre class="lang-py prettyprint-override"><code>series_of_list = series_of_list.apply(lambda x: x[:2])
</code></pre> | python|pandas|list|series | 2 |
366,028 | 66,974,019 | How can I count the number of transitions from one state to another in python? | <p>This is my dataframe. I want to create a column that gives me the number of transitions between these states.</p>
<pre><code>-------
Id Mode
G18 Start
G18 None
G18 Start
G18 Start
G18 Cool
...
G50 Mod Cool
G50 Mod Cool
G50 Mod Cool
G50 Mod Cool
G50 Mod Cool
</cod... | <p>Assuming the name of your DataFrame is <code>df</code>. If I understand you correctly, a transition occurs if, for a given row, the value of <code>df.Mode</code> is different from the shifted value. So you can add a Boolean column indicating the transitions:</p>
<pre class="lang-py prettyprint-override"><code>df['tr... | python|pandas | 0 |
366,029 | 66,902,056 | Key error in six.moves with return sys.modules[fullname] | <p>I am trying to put together an Azure function to run on an HTTP trigger. My problem is whenever I run the function I get a key error exception from the six module. It seems to be called when importing pandas and I cannot figure out why. Here is the traceback:</p>
<pre><code>Exception has occurred: KeyError
'six.move... | <p>It turns out my problems arose from a badly configured local environment. After redoing the virtual environment it sorted itself out quite well.</p> | python|pandas|azure|azure-functions|six | 1 |
366,030 | 66,932,614 | Cumulative count at a group level Python | <p>I have a pandas dataframe like this :</p>
<pre><code>df = pd.DataFrame([
['A', 1234, 20120201],
['A', 1134, 20120201],
['A', 1011, 20120201],
['A', 1123, 20121004],
['A', 1111, 20121004],
['A', 1224, 20121105],
['B', 1156, 20120403],
['B', 2345, 2012050... | <p>First, let's count the number of invoices paid on each day for each company:</p>
<pre class="lang-py prettyprint-override"><code>tmp1 = df.groupby(['company', 'date']).size().rename('totalpaidinvoices')
</code></pre>
<p>Then for each company, we need to count how many invoices were paid prior to the current period. ... | python|pandas|dataframe | 4 |
366,031 | 66,773,279 | Python: Multiprocessing running portion of code that it shouldn't | <p>I was sort of playing around with multiprocessing and different math libraries to calculate pi and wanted to know how much faster was it with or without multiprocessing by implementing <code>time.perf_counter()</code>. mp.Pool maps 20 threads as the same with my CPU threads count, while processing main, it also proc... | <p>TLDR: To fix your problem, just indent the last two lines.</p>
<p>The <code>multiprocessing</code> library actually runs the entire Python script in each thread. As an experiment run <code>python</code> in the same directory as the program and try importing it. You will notice that the bottom two statements will run... | python|numpy|multiprocessing|mpmath | 2 |
366,032 | 67,021,899 | No module named 'Pandas' | <p>this is the following code which i was try to run:</p>
<pre><code>dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", &... | <p>The pandas module name is all lower case. Try <code>import pandas as pd</code> instead.</p> | python|pandas|import|site-packages | 2 |
366,033 | 67,126,602 | how to extract specific content from dataframe based on condition python | <p>Consider the following pandas dataframe:
<a href="https://i.stack.imgur.com/lCGFu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lCGFu.png" alt="enter image description here" /></a></p>
<p>this is an example of ingredients_text :</p>
<blockquote>
<p>farine de blé 34% (france), pépites de chocolat... | <pre><code>df = pd.DataFrame({'ingredient_text': ['a%bgC, abc, a%, cg', 'xyx']})
ingredient_text
0 a%bgC, abc, a%, cg
1 xyx
</code></pre>
<p>Split the ingredients into a list</p>
<pre><code>df['ingredient_text'] = df['ingredient_text'].str.split(',')
ingredient_text
0 [a%bgC, abc, ... | python|pandas | 1 |
366,034 | 67,116,913 | retrieve data from pandas.core.series.series and save them into matrix | <p>I have a variable generated while running a program, which has the series type, and contents shown as follows. It can be seen that <code>test_prior</code> is a series, where each series element is a also a series. How to retrieve these element series and save them into a numpy array. Or, is that possible to save thi... | <p>I think you can convert the <code>Series</code> to a <code>DataFrame</code> and then use <code>explode</code>:</p>
<pre><code>test_prior.to_frame().apply(lambda c: c.explode(), axis=1)
</code></pre>
<p>Note that this will only work if the array in each row has the same length. But if this was not the case, then arra... | python|python-3.x|pandas|numpy|scipy | 1 |
366,035 | 66,860,905 | Web-scraping w/ Python: make my web scraping code faster? | <p>I would like to scrape two tables from 2 links. My code is:</p>
<pre><code>import pandas as pd
import xlwings as xw
from datetime import datetime
def last_row(symbol, name):
# Function that outputs if the last row of the df should be deleted or not,
# based on the 2 requirements below.
requirements =... | <p>You could use <a href="https://selenium-python.readthedocs.io/" rel="nofollow noreferrer">selenium</a> to automate clicking on the button. It's not hard but a lot of effort for something so trivial. I don't like scraping but sometimes it's all we have, right?</p> | python|pandas|web-scraping | 1 |
366,036 | 66,864,912 | Cannot convert Numpy array as tensor for input | <p>When I want to make text generation depending on various factors with an lstm model, when I try to use the data I want to use, I get a Failed to convert a NumPy array to a Tensor (Unsupported object type list) error while taking inputs. Below is my given data:</p>
<div class="s-table-container">
<table class="s-tabl... | <p>Sample code which converts numpy array to Tensor.</p>
<pre><code>import numpy as np
import tensorflow as tf
a = [0.1, 0.2, 0.3, 0.4]
arg = tf.convert_to_tensor(a, dtype=tf.float32)
</code></pre>
<p>Output</p>
<pre><code><tf.Tensor: shape=(4,), dtype=float32, numpy=array([0.1, 0.2, 0.3, 0.4], dtype=float32)>
</... | python|numpy|tensorflow|machine-learning|lstm | 0 |
366,037 | 67,178,966 | convert column to plain text pandas | <p>I have column like below</p>
<p>df =</p>
<pre><code>idx text
0 i
1 am
2 a
3 boy
4 .
5 he
6 is
7 running
8
9 .
</code></pre>
<p>I want to convert it to plain text and remove space before <code>.</code> fullstop like below:</p>
<pre><code>i am a boy. he is running.
</code></pre>
<p>I tried but still unsuccessful.</p... | <p>If need remove one or more spaces before <code>.</code> use <code>.join</code> with <code>re.sub</code>:</p>
<pre><code>import re
out = re.sub('\s+\.','.', ' '.join(df['text']))
</code></pre>
<p>Or:</p>
<pre><code>import re
#https://stackoverflow.com/a/18878958/2901002
df = re.sub(r'\s+([.])', r'\1', ' '.join(df['te... | python|pandas|dataframe | 2 |
366,038 | 66,770,281 | I am trying to create a table from a csv file to give me a proportion for a variable | <p>The following code is what I have but it is throwing a code saying no numeric types to aggregate.
The code:</p>
<pre><code>import pandas
import numpy as np
link = 'https://raw.githubusercontent.com/dvanderelst-python-class/python-class/spring2021/assignment_data/young_people_survey.csv'
data = pandas.read_csv(link,i... | <p>In your groupby you're saying which columns you are grouping (Age and Smoking) but not which column to calculate the mean. When it tries to calculate the mean of the Smoking column with values 'never smoked', 'former smoker' is says that this is not a numeric column.</p>
<p>If you change your groupby to</p>
<pre><co... | python|pandas|statistics | 0 |
366,039 | 67,117,848 | A question about "ModuleNotFoundError: No module named 'numpy.typing'" | <p>I am trying to import <a href="https://numpy.org/doc/stable/reference/typing.html#numpy.typing.ArrayLike" rel="noreferrer">ArrayLike</a> doing <code>from numpy.typing import ArrayLike</code>, and I get the error mentioned in the title:</p>
<p><code>ModuleNotFoundError: No module named 'numpy.typing'</code></p>
<p>I ... | <p>Re-posting the resolution in the comments above as a community wiki for better visibility:</p>
<blockquote>
<p>The numpy typing module was introduced in numpy 1.20</p>
</blockquote>
<p>Make sure that you have the correct <code>numpy</code> version by running the following at the beginning of your notebook:</p>
<pre>... | python|numpy|annotations | 5 |
366,040 | 67,059,690 | How to convert pandas data frame into list of tuples<string, list of list> | <p>I have a data frame which has a following structure</p>
<pre><code>title field1 field2 field3 field4 field5
title1 value11 value12 value13 value14 value15
title1 value21 value22 value23 value24 value25
title1 value31 value32 value33 value34 value35
title2 value1_... | <p>You can use <code>tuple()</code> inside lambda function in <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>df.GroupBy.apply()</code></a> as follows:</p>
<p>Assuming the fields columns are from the 2nd column onwards. If not, you can modify... | python|pandas|dataframe | 1 |
366,041 | 66,853,422 | Read in Values from external file, add them, print results | <p><strong>Problem:</strong>
I have 50 text files, each with thousands of lines of text, each line has a value on it. I am only interesting in a small section near the middle (lines 757-827 - it is actually lines 745-805 I'm interested in, but the first 12 lines of every file is irrelevant stuff). I would like to read ... | <p>Solution was to edit code as shown starting from 'xmin = 745':</p>
<pre><code>xmin = 745
xmax = 815
skip = 12
for n in range(0, numfiles):
total = 0
x = np.linspace(0, 8191, 8192)
finalprefix = str(n).zfill(3)
fullprefix = folderToAnalyze + prefix + finalprefix
y = loadtxt(fullprefix + &qu... | python|numpy|for-loop|import|add | 0 |
366,042 | 67,088,435 | Determine the trend of the market over time use Pandas + python3 | <pre><code>print(df)
Index Time left Type Price
0 1797.0 4.00 0.83
1 1789.0 4.00 0.83
2 1781.0 4.00 0.83
3 1757.0 4.00 0.83
4 1445.0 4.00 0.83
5 1413.0 NaN NaN
6 1397.0 ... | <p>You can find indices of min and max with <code>idxmin</code> and <code>idxmax</code>, then compare them:</p>
<pre><code># get indices of min and max:
z = df.set_index('Time left').groupby('Type')['Price'].agg(['idxmin', 'idxmax'])
# if index of max < index of min, then it's increasing
# (since it's `Time left`, ... | python-3.x|pandas | 0 |
366,043 | 67,140,570 | Keras Deep NN does not include all the the classes | <p>I have made a model which has been trained to predict a number from 34-63 (no decimal numbers) In total that is 30 potential outputs.</p>
<p>When I run the model it complains and wants me to put in 15 in my last layer, which I have understood should be the number of outputs.</p>
<p>I Also get following output in the... | <p>As mentioned in <a href="https://stackoverflow.com/questions/67140570/keras-deep-nn-does-not-include-all-the-the-classes?noredirect=1#comment118694835_67140570">the comments</a>, the number of classes in the dataset was only 15, hence why an output of 15 values is appropriate.</p>
<p>To get the top <code>k</code> cl... | numpy|tensorflow|keras|neural-network|multiclass-classification | 1 |
366,044 | 66,937,088 | How to efficiently find separately for each element N maximum values among multiple matrices? | <p>I am looping through a large number of H x W matrices. I cannot store them all in memory. I need to get N matrices. For example, the element of the 1st of N matrix in position (i, j) will be the largest among all elements in position (i, j) of all processed matrix matrices. For the second of the N matrix, the elemen... | <p>The comments suggested using the <code>np.partition</code> function. I replaced the use of numpy with <a href="https://cupy.dev/" rel="nofollow noreferrer">cupy</a>, which uses the GPU. And also added a buffer to sort less frequently.</p>
<pre><code>import cupy as np
buf = // # As much as fits into the GPU
largests... | python|algorithm|numpy|matrix|memory-efficient | 1 |
366,045 | 47,492,556 | AttributeError: 'module' object has no attribute 'to_rgb' | <p>I wrote a simple code to form taylor digram using skillmetrics package. I used python version Python 2.7.12. The code is as follows:-</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import skill_metrics as sm
fire=pd.read_csv('fire.csv')
PMfire = zip(fire['Date'],fire['PM_fire'... | <p>The <code>to_rgb</code> function was added relatively recently to the <code>matplotlib.colors</code> namespace. You probably have an older version of matplotlib installed. Try updating to the latest version of matplotlib.</p> | python|python-2.7|numpy|matplotlib | 7 |
366,046 | 47,186,040 | Pandas: Pivot column to headers | <p>I'm trying to pivot the values in a column to column headers, but maintain the rest of the data. Here's my full code, along with the closest I can get to what I'm looking for. The only problem with this is that I can't figure out how to keep the <code>end</code> column:</p>
<pre><code>import pandas as pd
starts ... | <pre><code>pd.pivot_table(df,index=['start','end'],columns='id',values='type',aggfunc='sum').reset_index()
Out[1587]:
id start end XXX YYY
0 2017-01-01 2017-01-31 car truck
1 2017-02-01 2017-03-03 car truck
2 2017-03-04 2017-04-03 car truck
3 2017-04-04 2017-05-04 car truck
</code... | python|pandas|pivot | 6 |
366,047 | 47,101,273 | Selecting rows of pandas dataframe according to threshold of column | <p>I have a pandas dataframe with a column "value" and a column "timestamp". Now I would like to filter the rows according to thresholds of the timestamp. I have done the following:</p>
<pre><code>idx = df.index[df['timestamp'] >= start and df['timestamp'] <= end]
df = df.loc[idx]
</code></pre>
<p><code>df</cod... | <p>IIUC</p>
<pre><code>mask=(df['timestamp'] >= start & df['timestamp'] <= end)
df=df[mask]
</code></pre> | python|pandas | 1 |
366,048 | 47,213,602 | tf.nn.embedding_lookup with float input? | <p>I would like to implement an embedding table with float inputs instead of int32 or 64b.
The reason is that instead of words like in a simple RNN, I would like to use percentages.
For example in case of a recipe; I may have 1000 or 3000 ingredients; but in every recipe I may have a maximum of 80.
The ingredients will... | <p><a href="https://www.tensorflow.org/api_docs/python/tf/nn/embedding_lookup" rel="nofollow noreferrer"><code>tf.nn.embedding_lookup</code></a> can't allow float input, because the point of this function is to select the embeddings at the <strong>specified rows</strong>.</p>
<p>Example:</p>
<p><a href="https://i.sta... | machine-learning|tensorflow|nlp|word-embedding | 2 |
366,049 | 47,288,982 | Pandas DataFrame GroupBy sum/count to new DataFrame | <p>My DataFrame is</p>
<pre><code>State|City|Year|Budget|Income
S1|C1|2000|1000|1
S1|C2|2000|1200|2
S2|C3|2000|5500|3
</code></pre>
<p>I need to get a new DataFrame with columns: </p>
<pre><code>State, Year, Count, Sum_Budget, Sum_Income:
</code></pre>
<p>That is,</p>
<pre><code>State|Year|Count|Sum_Budget|Sum_Inc... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>agg</code></a>:</p>
<pre><code>d = {'Income':'Sum_Income','Budget':'Sum_Budget','City':'Count'}
agg_d = {'Budget':'sum', 'Income':'sum', 'City':'size'}
df = df.groupby(['... | python|pandas|pandas-groupby | 4 |
366,050 | 47,400,696 | Python reading csv with 13 digit ISBN number converts into scientific notation | <p>I have a python program which give me around 200 csv files with 25 records each. I want to merge these 200 files into one file csv and load it in SQL server. (I am assuming this is good way to load)</p>
<p>My final aim is to have one csv file with all the data of 200 csv and load the data on SQL server as well.</p>... | <p>Use <code>dtype=str</code>:</p>
<pre><code>for files in glob.glob("*.csv"):
print files
df = pd.concat([df,pd.read_csv(files, dtype={'ISBN-13':str})],axis=0)
</code></pre> | python|sql-server|pandas|csv | 1 |
366,051 | 47,525,521 | Pandas Column values between range like 1-250, 251-500, so on | <p><strong>Dataset:</strong></p>
<pre><code> id MarketPlaceValuation
0 100
1 250
2 200
3 100
4 325
5 175
6 150
7 125
8 225
9 325
10 625
11 100
12 75
13 100
14 200
15 225
.. ..
40... | <p>I think you need:</p>
<pre><code>#specify bins
bins = [0,250,500,1000,1500,2000,3000,4000,5000,100000]
#generate labels from bins
labels = ['{} - {}'.format(i + 1, j) for i, j in zip(bins[:-1], bins[1:])]
cat = pd.cut(df['MarketPlaceValuation'], bins=bins, labels=labels)
#get mean per categories
df = df.groupby(c... | python|pandas|numpy | 0 |
366,052 | 47,388,677 | Indices such that elements are in the closed interval | <p>I got a numpy 1d arrays, and I want to find the indices of the array such that its values are in the closed interval specified by another 1d array. To be concrete, here is an example</p>
<pre><code>A= np.array([ 0.69452994, 3.4132039 , 6.46148658, 17.85754453,
21.33296454, 1.62110662, 8.02040621,... | <p>Given the sorted nature of <code>b</code>, we can simply use <code>searchsorted/digitize</code> to get the indices where elements off <code>A</code> could be placed to keep the sorted order, which in essence means getting the boundary indices for each of the <code>b</code> elements and finally subtract <code>1</code... | python-2.7|numpy|intervals|matrix-indexing | 0 |
366,053 | 47,089,830 | How to use pandas where i have to split the Date column and find out the no of days delayed | <p>Here is the code: </p>
<p>Cell 1:</p>
<pre><code>%matplotlib notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
purchase_data = pd.read_csv('Lokad_PurchaseOrders.csv')
purchase_data
</code></pre>
<p>Cell 2:</p>
<pre><code>imp... | <p>Firstly, you should make sure that the <code>end_date</code> and <code>start_date</code> are both strings rather than Series object as the error says. You can check that using the <code>type()</code> function. </p>
<p>And to split the Series type data, you can refer to <a href="https://stackoverflow.com/a/44049442/... | python|pandas | 0 |
366,054 | 47,324,354 | how pytorch nn.module save submodule | <p>I have some question about how pytorch nn.module works</p>
<pre><code>import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.sub_module = nn.Linear(10, 5)
self.value = 3
net = Net()
print(net.__dict__)
</code></pre>
<p>output </... | <p>I will try to keep it simple. </p>
<p>Every time you create a new item in the class <code>Net</code> for instance: <code>self.sub_module = nn.Linear(10, 5)</code> it calls the method <code>__setattr__</code> of its parent class, in this case <code>nn.Module</code>. Then, inside <code>__setattr__</code> method, the ... | python|pytorch | 1 |
366,055 | 47,495,048 | Crop multiple faces from a picture using opencv and store them in a folder | <p>I am a beginner to opencv and I have tried to crop a single face from a picture for my project but couldn't crop all the faces from the picture.
What can be done to detect all the faces and crop them to move to a folder?
taking images from the input folder and posting the cropped image to the output folder.</p>
<pr... | <pre><code>#### the counter
cnt = 0
for pic in range(1, (numPics+1)):
img = cv2.imread('input/'+str(pic)+'.jpg')
height = img.shape[0]
width = img.shape[1]
size = height * width
if size > (500^2):
r = 500.0 / img.shape[1]
dim = (500, int(img.shape[0] * r))
img2 = cv2.res... | python|numpy|opencv|ubuntu|face-detection | 2 |
366,056 | 47,531,990 | Find the first instance of a value looking backward in pandas dataframe | <p>I have a dataframe like the following:</p>
<pre><code>Timestamp Value
11/23/2017 7
11/24/2017 3
11/25/2017 5
11/26/2017 7
11/27/2017 7
11/28/2017 7
</code></pre>
<p>I want to write something which returns the first instance of the last value, 7, looking upward, and stops when the value changes to something... | <p>Create helper <code>Series</code> for get unique consecutive values of column <code>Value</code>, get index of max value by<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idxmax.html" rel="nofollow noreferrer"><code>idxmax</code></a> and last select value by <code>loc</code>:</p>
<pre><... | python|pandas | 2 |
366,057 | 47,240,763 | Pandas: How to create a "master" record when de-duping | <p>Example pandas dataframe below -</p>
<pre><code>ID ADDRESS COLUMN1 COLUMN2 COLUMN3
1 123 FRONT ST 2017
1 123 FRONT ST 2016
1 123 FRONT ST 2018
2 324 2nd st 2008
2 324 2nd st 2014
</code></pre>
<p>My goal is to de-dupe the dataframe above but for... | <pre><code>df.groupby('ID').first()
Out[156]:
ADDRESS COLUMN1 COLUMN2 COLUMN3
ID
1 123FRONTST 2017.0 2016.0 2018.0
2 3242ndst 2008.0 2014.0 NaN
</code></pre> | python|pandas|dataframe|pandas-groupby | 2 |
366,058 | 47,263,061 | Overflow for astype(int) with big number | <p>I have the following number in python:</p>
<pre><code>import pandas
x = pandas.Series(1508770848527.423339843750000)
</code></pre>
<p>When I'm using <code>x.apply(np.floor)</code> I'm getting 1508770848527.0 but when I'm applying <code>x.astype(int)</code> I'm getting -2147483648.</p>
<p>How can I prevent this ov... | <p>Convert to <code>int64</code>:</p>
<pre><code>print (x.astype('int64'))
0 1508770848527
dtype: int64
</code></pre>
<p>Or like commented <a href="https://stackoverflow.com/questions/47263061/overflow-for-astypeint-with-big-number/47263093#comment81476847_47263061">Willem Van Onsem</a>:</p>
<pre><code>print (x.a... | python|pandas|overflow|rounding | 2 |
366,059 | 47,220,777 | Using python3.6 TypeError: an integer is required | <p>I am using python 3.6 version, I am getting following error:</p>
<blockquote>
<p>TypeError: an integer is required (invsf['Destn Branch'] =
invsf.apply(lambda x: convloc(x['Destn Branch'])))</p>
</blockquote>
<p>Code:</p>
<pre><code>loclist = ['Destn Branch','Hub SC Location','Origin Branch']
maplist = dict(... | <p>A few pointers:</p>
<ul>
<li>You've declared a dict with <code>{...}</code>. Calling <code>dict()</code> over it is redundant.</li>
<li><p>If your apply operation affects one column only, you should call apply on that series. </p>
<pre><code>invsf['Destn Branch'] = invsf['Destn Branch'].apply(covloc)
</code></pre>... | python|pandas | 2 |
366,060 | 47,213,852 | Python/Scrapy handle missing table data, list index out of range | <p>I'm using round-col as the list length as there's always data in that column which tells me the size of the table.
I'm scraping data to csv so all fields have to correspond but the trouble I'm facing is when the loop hits 'no data' the list index goes out of range or 'TypeError: 'NoneType' object is not sub scriptab... | <p>Instead of trying to build based on the columns, you need to loop over the rows, and start building the items per row, I've used item loaders here so that you can avoid several <code>.extract_first()</code> or <code>.strip()</code>, please try this:</p>
<pre><code># -*- coding: utf-8 -*-
import scrapy
# This shoul... | python|pandas|loops|csv|scrapy | 1 |
366,061 | 47,492,742 | Panda array from list of dictionaries | <p>I have a list of dictionaries like this</p>
<pre><code>[{"Key":[val1,val2,...]}, {"Key2":[val1,val2,...]}, ...]
</code></pre>
<p>I would like to convert this to a csv format where the keys are column headers, and he values form the column values</p>
<p>To do this I had intended to use a <code>pandas</code> datafr... | <p>I'm assuming your keys are unique, otherwise this wouldn't make much sense.</p>
<p><strong>Option 1</strong> </p>
<ol>
<li>merge your dictionaries to a single dict</li>
<li>pass the dict to <code>pd.DataFrame</code></li>
<li>save as CSV using <code>df.to_csv</code></li>
</ol>
<pre><code>dct = [{...}, {...}, ... | python|pandas|csv|dictionary | 4 |
366,062 | 47,276,289 | What is the difference between an array with shape (N,1) and one with shape (N)? And how to convert between the two? | <p>Python newbie here coming from a MATLAB background.</p>
<p>I have a 1 column array and I want to move that column into the first column of a 3 column array. With a MATLAB background this is what I would do:</p>
<pre><code>import numpy as np
A = np.zeros([150,3]) #three column array
B = np.ones([150,1]) #one colu... | <p>Several things are different. In <code>numpy</code> arrays may be 0d or 1d or higher. In MATLAB 2d is the smallest (and at one time the only dimensions). MATLAB readily expands dimensions the end because it is <code>Fortran ordered</code>. <code>numpy</code>, is by default <code>c ordered</code>, and most readil... | python|arrays|numpy | 3 |
366,063 | 47,484,317 | Vectorized operations in Pandas - Python | <p>I am learning Python and trying to make vectorized operations in Pandas in particular. However as I am trying to normalize a Pandas dataframe using Vectorized operations I am getting error messages.</p>
<p>This reproducible example uses the surveys.csv dataset that can be found in this link: <a href="http://www.da... | <p>This is because you need to understand dataset. There are <code>null</code> values in weight column. You need to remove columns with null value to normalize weight operation. Make a slice of data as <code>test_data</code> and perform operations.</p>
<pre><code>surveys_df = pd.read_csv("surveys.csv")
test_data = sur... | python|pandas|vectorization | 2 |
366,064 | 47,470,441 | Cannot build Pandas from setup.py in Wine environment | <p>I am attempting to cross-compile a Python script from my Linux platform to a Windows executable using Wine. I have successfully installed Python 3.6.0 for Windows 64 bit and pyinstaller, in addition to all of the Python dependencies for my program, inside of my Wine environment.</p>
<p>Running <code>wine py my_file... | <p>I know I'm late, but hopefully this will still be helpful and/or point others in the right direction.</p>
<p>This problem results from a hidden import in pandas/a missing hook in pyinstaller. It's solved by adding <a href="https://github.com/pyinstaller/pyinstaller/pull/2998/files" rel="nofollow noreferrer">this</a... | python|python-3.x|pandas|pyinstaller|wine | 0 |
366,065 | 47,185,894 | Iteration order with pandas groupby on a pre-sorted DataFrame | <h2>The Situation</h2>
<p>I'm classifying the rows in a DataFrame using a certain classifier based on the values in a particular column. My goal is to append the results to one new column or another depending on certain conditions. The code, as it stands looks something like this:</p>
<pre><code>df = pd.DataFrame({'A... | <p>Yes, when you pass <code>sort=False</code> the order of first appearance is preserved. The <code>groupby</code> source code is a little opaque, but there is one function <a href="https://github.com/pandas-dev/pandas/blob/v0.23.4/pandas/core/groupby/groupby.py#L1754-L1762" rel="noreferrer"><code>groupby.ngroup</code>... | python|pandas|group-by|pandas-groupby | 7 |
366,066 | 47,512,749 | Fill missing rows with zeros from a data frame | <p>Now I have a DataFrame as below:</p>
<pre><code>video_id 0 1 2 3 4 5 6 7 8 9 ... 53 54 55 56
user_id ...
0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0
1 2 0 4 13 16 2 0 10... | <p>You could use <code>arange</code> + <code>reindex</code> -</p>
<pre><code>df = df.reindex(np.arange(df.index.min(), df.index.max() + 1), fill_value=0)
</code></pre>
<p>Assuming your index is meant to be monotonically increasing index.</p>
<hr>
<pre><code>df
0 1 2 3 4 5 6 7 8 9
0 0 0... | python|pandas|dataframe | 2 |
366,067 | 47,336,863 | Pandas - DatetimeIndex as column headings | <p>I have a dataframe that is 438x14401. I have a DateTimeIndex that is the same length (width?) as the columns in the dataframe, which are now just labeled 1 - ... I am trying to replace those values with the dates in my DateTimeIndex.</p>
<p><a href="https://i.stack.imgur.com/N9HWb.png" rel="nofollow noreferrer"><im... | <p>You can assign your <code>DatetimeIndex</code> directly to <code>stations.columns</code>:</p>
<p>Sample df:</p>
<pre><code>df = pd.DataFrame({'a': [1,2,3], 'b': [9,8,7], 'c': [7,5,1], 'd':[1,3,5]})
df
a b c d
0 1 9 7 1
1 2 8 5 3
2 3 7 1 5
some_date_range = pd.date_range('2017-01-01', periods=len... | python|pandas|multiple-columns|heading | 1 |
366,068 | 47,486,451 | Python: how to put initial centroids on specific data points in k-means? | <p>I have the following data:</p>
<pre><code>import pandas as pd
import random
import matplotlib.pyplot as plt
df = pd.DataFrame()
df['x'] = [3, 2, 4, 3, 4, 6, 8, 7, 8, 9]
df['y'] = [3, 2, 3, 4, 5, 6, 5, 4, 4, 3]
df['val'] = [1, 10, 1, 1, 1, 8, 1, 1, 1, 1]
k = 2
centroids = {i + 1: [np.random.randint(0, 10), np.rand... | <p>You can sort the dataframe by <code>val</code> column to get the indexes of top <code>k</code> values and then slice the dataframe using <code>df.iloc</code>.</p>
<hr>
<p>Sorting in the descending order:</p>
<pre><code>df = df.sort_values('val', ascending=False)
print(df)
x y val
1 2 2 10
5 6 6 8
0... | python|pandas|machine-learning|k-means|centroid | 1 |
366,069 | 47,356,993 | OSError: raw write() returned invalid length when using print() in python | <p>I'm using python tensorflow to train a model to recognise images in python. But I'm getting the below error when trying to execute train.py from <a href="https://github.com/loicmarie/sign-language-alphabet-recognizer" rel="noreferrer">github</a> </p>
<pre><code>Traceback (most recent call last):
File "train.py", li... | <p>If you're unable to migrate to 3.6 or from Windows like me, install the <em>win_unicode_console</em> package, import it and add this line at the beggining of your script to enable it:</p>
<pre><code>win_unicode_console.enable()
</code></pre>
<p>This issue appears to be generally unique to pre-3.6 Python as the cod... | python|python-3.x|image-processing|tensorflow | 12 |
366,070 | 47,477,728 | Fit dataframe into linear regression sklearn | <p>I am making a project for a class, and i am trying to predict nfl socre games using linear regression and predict functions from sklearn, my problem comes when i want to fit the training data into de fit function, here is my code:</p>
<pre><code>onehotdata_x1 = pd.get_dummies(goal_model_data,columns=['team','oppone... | <p>The problem is that after <code>pd.get_dummies</code> there are no <code>team</code> and <code>opponent</code> columns.</p>
<p>I use this data in txt format for my example: <a href="https://ufile.io/e2vtv" rel="nofollow noreferrer">https://ufile.io/e2vtv</a> (same as yours).</p>
<hr>
<p><strong>Try this and see:<... | python|pandas|scikit-learn | 3 |
366,071 | 47,316,635 | How to convert strings with even or odd numbers to 0 or 1? | <p>Starting with the data of this form:</p>
<pre><code> col_1 col_2
0 a1 a6
1 a3 a7
2 a4 a2
3 a5 a8
</code></pre>
<p>Where values are letters with numbers at the end. And I would like to convert values to 0 or 1 depending on the parity or oddness of the number at the end string, to da... | <pre><code>import re
df.applymap(lambda x : int(re.findall(r'\d+',x)[0])%2)
Out[866]:
col_1 col_2
0 1 0
1 1 1
2 0 0
3 1 0
</code></pre> | python|pandas | 1 |
366,072 | 47,231,496 | pandas fill missing dates in time series | <p>I have a dataframe which has aggregated data for some days. I want to add in the missing days </p>
<p>I was following another post, <a href="https://stackoverflow.com/questions/19324453/add-missing-dates-to-pandas-dataframe">Add missing dates to pandas dataframe</a>, unfortunately, it overwrote my results (maybe fu... | <p>You need to use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.period_range.html" rel="noreferrer"><code>period_range</code></a> rather than <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="noreferrer"><code>date_range</code></a>:</p>
<pre><code>In... | python|pandas | 44 |
366,073 | 47,328,528 | Encoding error when installing Keras on Windows 10 | <p>I am trying to install Keras on Windows 10. I installed Visual Studio 2015 Community Edition, CUDA 8.0, its second patch, cuDNN 6.0, PyCharm, Anaconda, Python 3.6.3 in this specific order.
I installed <code>tensorflow-gpu</code>.
I added <code>\path-to\Python\Python36\bin</code> to the <code>PATH</code> environment ... | <p>This is coming from pyyaml module. Based on the fact that from version 3.6 Python for Windows is using UTF-8 for it's console IO it leads to errors. In case of running a subprocess, it thinks that the output from subprocess will be also UTF-8... which is not the case.</p>
<p>There are 3 ways to fix this:</p>
<ol>
... | python|windows|tensorflow|keras | 1 |
366,074 | 47,166,551 | Python Code not clear (arrays) | <p>I have the following lines: </p>
<pre><code>Xtest = numpy.arange(-15,15,0.1)
Xtest = numpy.array([Xtest,Xtest*0+1]).T
</code></pre>
<p>Why does the second line look like this in the sense of <strong>"Xtest*0+1"</strong> ? I've tried </p>
<pre><code>Xtest = numpy.array([Xtest,1]).T
</code></pre>
<p>I get the sam... | <p>Since <code>Xtest</code> is an array, it has more than one entry. When you multiply it by zero, you have that many zeroes. Then you add one to make it into an array full of one's. In contrast, when you directly put in <code>1</code>, you end up with a single <code>1</code>, which is different.</p> | python|arrays|python-3.x|numpy|multidimensional-array | 1 |
366,075 | 47,113,637 | Bar Chart from Dataframe Error module 'numpy' has no attribute 'arrange' | <p>I am trying to plot a bar chart from a dataframe. If I do numpy arrange I see the error <code>module 'numpy' has no attribute 'arrange'</code> . If I don't do arrange I see no error but the chart opens but I don't see any bars.
Here's my code:</p>
<pre><code>data = []
for x in tracks:
data.append({'Track_Name':... | <p>Give a Pandas DataFrame, you can plot a bar graph of the <code>Track_Name</code> column vs <code>plays</code> using <code>df.plot(kind='bar', x='Track_Name', y='plays')</code>:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame( {'Track_Name': ['Silvestre - Sport Theories 12" Snip... | python|pandas|numpy|plot | 2 |
366,076 | 11,157,450 | How do you force a figure redraw ipython notebook inline? | <p>I am using pandas and ipython notebook inline. I drew a figure with pandas dataframe</p>
<pre><code>figure()
subplot = df['likes'].hist()
subplot.set_title("Likes")
display(fig)
draw()
</code></pre>
<p>I am trying to add a title to the histogram for example and I'd like to redraw it, but ipython notebook does not ... | <p>It seems that ipython notebook closes the figure after I execute the cell's code. To format the axes I have to execute all the code in a single cell.</p> | ipython|pandas | 3 |
366,077 | 11,069,309 | Python: import scipy leads to traceback referencing a deleted file | <p>When I try to import the scipy module (version 0.11.0b1) in the Python interpreter (version 2.6.1), I receive the following error:</p>
<hr>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in module
File "/Users/...long path.../Desktop/scipy-0.11.0b1/scipy/\__init__.py", line 114, in m... | <p>Add the scipy path as show below.</p>
<pre><code>from cx_Freeze import setup, Executable
include_files = ['C:\\Users\\User\\Anaconda\\Lib\\site-packages\\scipy']
setup(name = "ventana",
options = {'build_exe': {'include_files':include_files}},
version = "0.1",
description = "ventana",
exec... | python|numpy|scipy | 3 |
366,078 | 11,146,229 | Creating a masked array in Python with multiple given values | <p>I am graphing several columns of a large array of data (through numpy.genfromtxt) against an equally sized time column. Missing data is often referred to as nan, -999, -9999, etc. However I can't figure out how to remove multiple values from the array. This is what I currently have:</p>
<pre><code>for cur_col in ra... | <p>I would suggest using <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.html" rel="noreferrer">masked arrays</a> like so:</p>
<pre><code>>>> a = np.arange(12.0).reshape((4,3))
>>> a[1,1] = np.nan
>>> a[2,2] = -999
>>> a
array([[ 0., 1., 2.],
[ 3., ... | python|arrays|numpy|mask | 6 |
366,079 | 11,177,496 | How do I write this matlab example to python | <p>I am trying to convert this to python. I just really need help with 1 line. I nevered learn matlab</p>
<pre><code>function [xc,yc,R,a] = circfit(x,y)
%
% [xc yx R] = circfit(x,y)
%
% fits a circle in x,y plane in a more accurate
% (less prone to ill condition )
% procedure than circfit2 but using more mem... | <p>You may find <a href="http://mathesaurus.sourceforge.net/matlab-numpy.html" rel="nofollow">this reference</a> useful.</p>
<ul>
<li><p>Matlab arrays are indexed starting at 1; Python arrays start at 0</p></li>
<li><p>Python does not have a left-matrix-div operator, but numpy.linalg.solve performs the same operation<... | python|matlab|numpy|porting | 3 |
366,080 | 68,398,917 | How to change pandas' Datetime Index from "End of month" To just "Month" | <p>I'm using pandas to analyze some data about the House Price Index of all states from quandl:
HPI_Data = quandl.get("FMAC/HPI_AK")</p>
<p>The data looks something like this:</p>
<pre><code> HPI Alaska
Date
1975-01-31 35.105461
1975-02-28 35.465209
1975-03-31 35.843110
</code></pre>
<p... | <p>Not sure if I understand correctly. So please clarify your question if this is not correct.</p>
<p>You can convert a string to a pandas date time object using <code>pd.to_datetime</code> and use the <code>format</code> parameter to specify how to parse the string</p>
<pre><code>import pandas as pd
# Creating a dumm... | python|pandas | 1 |
366,081 | 68,195,425 | Incomplete python source distrubtion when building Fortran/Numpy extension | <p>When building a source distribution of a Python package that contains a Fortran/Numpy Extension, the source distribution is incomplete. It lacks the source files <code>fortranobject.c</code> and <code>fortranobject.h</code>, which are copied by numpy's own <code>setup</code> function when you do a <em>binary</em> bu... | <p>OK, I finally tracked down the issue, which I think is a bug in how <code>Extension</code> in Numpy's <code>distutils</code> handles <code>pyf</code> source files. Here's the bug report: <a href="https://github.com/numpy/numpy/issues/19441" rel="nofollow noreferrer">https://github.com/numpy/numpy/issues/19441</a>.</... | numpy|python-packaging | 0 |
366,082 | 68,363,350 | Count number of column value repeats in a pandas time window | <p>I have this dataset where accesses to a web server is sorted based on datetime, and the IPs of clients.
I want to know how many times a unique client has accessed the server during a specified time period, for example 10 seconds.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Datetime</... | <p>Let's try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby cumcount</code></a> on <code>IP</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer... | python|pandas|datetime | 0 |
366,083 | 68,202,085 | Convert string to array then sum error for pandas | <p>I have the following table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">userid</th>
<th style="text-align: center;">eventid</th>
<th style="text-align: right;">urlclick</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">A</td>
<td style="text-alig... | <pre><code>time.groupby(['userid','eventid']).urlclick.apply(lambda x: x.sum(axis = 0))
</code></pre> | python|arrays|numpy | 0 |
366,084 | 68,408,186 | Removing strings from a pandas data series | <p>I have a complicated pandas series dataframe with a combination of floats, integers and strings. I am trying to remove all the nan from the rows so I can read and manipulate the numbers. The dataframe looks like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>VAR1</th>
<th>VAR2</th>
<th... | <p>You should use a simple:</p>
<pre><code>df. dropna()
</code></pre>
<p>Or if your "NaN" is a string perhaps <code>df.replace("NaN", "0")</code> will do work</p> | python|pandas|dataframe|nan|series | 0 |
366,085 | 68,330,934 | How to use column names as x axis values in matplotlib? | <p>I've started learning matplotlib and I've been struggling with a task for a while now. I have a dataframe that looks something like the one below. I would like to plot this with the years as x-axis values and with each city (i.e. each row) as it's own plot. Seemingly easy task (literally one click in Excel) but I st... | <p>It looks like you only need to transpose your data. If you have a Dataframe, by default Matplotlib will put on x-axis the index of the DataFrame, and will plot every column separately.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
data = [{'City': 'city1', '1990': 0, '1991': 2, '2019': 5, '... | python|pandas|matplotlib|jupyter-notebook | 1 |
366,086 | 68,029,144 | Is there any negative effect for using cropped images with the TFRecord format? | <p>The TensorFlow Object Detection API requires TFRecord image cropping properties, like so:</p>
<pre><code>{
'image/height': 1800,
'image/width': 2400,
'image/filename': 'image1.jpg',
'image/source_id': 'image1.jpg',
'image/encoded': ACTUAL_ENCODED_IMAGE_DATA_AS_BYTES,
'image/format': 'jpeg',
'image/obje... | <p>No, you definitely need the bounding box information to train an object detector. Do they potentially use contextual information? Maybe, but it's a learned behaviour.</p>
<p>You need to provide images where your objects are visible in multiple backgrounds, scales, illuminations, etc in order to train a network to ro... | tensorflow | 1 |
366,087 | 68,157,542 | show the xy data point when the mouse over over the data point | <p>I want to show the data point (x value, y value) of a graph when hover to a specific data point.<br />
does anyone know how to achieve it based on my current code?</p>
<pre><code> ax = df.plot(x=1, y=2) #x value from column 1 of pandas dataframe,
#y value from column 2 of pan... | <p>Here is an example of how to achive this using <code>bokeh</code>:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
from bokeh.models import HoverTool
from collections import OrderedDict
x = np.sort(np.... | python|pandas|matplotlib | 0 |
366,088 | 68,200,272 | Dynamic xml parsing and converting to csv in Python | <p>I have an XML file as below</p>
<pre><code><D1>
<RECORD>
<NODE>XT-300</NODE>
<ST_DURATION>10</ST_DURATION>
<DT_VAL>PBM98XX</DT_VAL>
<ST_VAL>98987</ST_VAL>
<EXIST>Yes</EXIST>
&l... | <p>Here’s one way:</p>
<pre><code>import xmltodict
d = xmltodict.parse("""
<D1>
<RECORD>
<ELEC>EL-13</ELEC>
<VAL>10</VAL>
<POWER>Max</POWER>
<WIRING>2.3</WIRING>
<ENABLED>Yes... | python|python-3.x|pandas|dataframe|pandas-datareader | 0 |
366,089 | 68,178,722 | How to convert pandas dataframe to json | <p>I have json that looks like this:</p>
<pre><code>{
"response": {
"docs": [{
"region_s" : "North America",
"country_s": "Panama",
"ArticleHeading_s": "The expected vaccination process... | <p>I think this will do:</p>
<pre class="lang-py prettyprint-override"><code>docs = df.to_dict('records')
out = {
"response":{
"docs":docs,
},
}
</code></pre>
<p>and the dump the out dictionary to json file</p> | python|json|pandas | 0 |
366,090 | 68,316,558 | Conditionally replace column data over a range of rows | <p>I would like to select a range of rows (done) and conditionally replace the values in a column. How best to perform this</p>
<p><code>df.loc[ (df['Time'] > 80) & (df['Time'] < 120) ]</code></p>
<p>This successfully provides the locations over a given time range. What I need need todo is within this range r... | <p>There is 2 possible solutions - <code>replace</code> by match only this condition:</p>
<pre><code>m1 = (df['Time'] > 80) & (df['Time'] < 120)
#alternative
m1 = df['Time'].between(80, 120, inclusive=False)
df.loc[m1 , 'Vel'] = df.loc[m1 , 'Vel'].replace('00','FF')
</code></pre>
<p>Or set values with chaine... | python|pandas | 1 |
366,091 | 68,245,308 | How to reverse all values in a dataframe column? | <p>I wasn't sure how to form this question, so the problem isn't really what it sounds for.
Let's say I have a column with floats, ranging from 0.000000 to 1.000000
I want to reverse those values so for example:</p>
<pre><code>1.000000 == 0.000000
0.122000 == 0.888000
0.950000 == 0.050000
0.324546 == 0.675454
</code></... | <p>Just simply substract 1 from your series:</p>
<pre><code>s=pd.Series([1.0, 0.122, 0.95, 0.324546])
s=(1-s)
#here s is your Series
#If needed the difference as positive number use abs() method
s=(s-1).abs()
</code></pre>
<p>output:</p>
<pre><code>0 0.000000
1 0.878000
2 0.050000
3 0.675454
</code></pre>
<... | python|pandas|dataframe | 2 |
366,092 | 68,349,212 | Improve performance of a nested apply in pandas | <p>I have a pandas DataFrame <code>names</code> and a Series <code>illegal_words</code>.</p>
<pre><code># names - ca. 250k rows
name
0 MISS ELFRIEDA ALPERT
1 DALE VON PETTY
2 MOHAMMAD IBN MASILLAH
3 YELENA THE MORRIS
4 MR. SHENNA DEMOSS
...
# illegal_words - ca. 2k rows
0 MISS... | <p>Can you try that?</p>
<pre><code>illegal_words = ['MISS', 'VON', 'THE']
out = df['name'].str.replace(fr"({'|'.join(illegal_words)}) ", '', regex=True)
</code></pre>
<pre><code>>>> out
0 ELFRIEDA ALPERT
1 DALE PETTY
2 MOHAMMAD IBN MASILLAH
3 YELENA MORRIS
4 ... | python|pandas|performance | 2 |
366,093 | 68,045,764 | How to select data from a Pandas series and get the data type not another object? | <p>I have a Pandas dataframe from which I select the first row to get a series. What is the best way to select data <code>nb</code> in order to get the integer <code>2</code>, not another series ?</p>
<p>My problem is that when I select <code>route.nb</code> I get a object instead of an integer.</p>
<p>This is how my s... | <p>You can either use the fact it’s the first element in the series:</p>
<pre><code>route.iloc[0]
</code></pre>
<p>Or you can use the full index for that element:</p>
<pre><code>route[('nb', '', '')]
</code></pre>
<p>When you do <code>route['nb']</code> it returns a series with the 2 remaining index levels. If you acce... | python|pandas | 1 |
366,094 | 68,264,711 | pd.read_html changed number formatting | <p>Cannot get <code>1,2,3,4,5,6</code> from the column of <code>CCCCCCC</code>, after <code>pd.read_html</code> format changed to <code>123456</code>, and my <strong>expected result</strong> should be keep <code>1,2,3,4,5,6</code></p>
<p><strong>HTML code</strong></p>
<pre><code>html = """<html>
&l... | <p>You need to add the <code>thousands</code> parameter and set it to <code>None</code> by default it's <code>','</code>.</p>
<pre><code>from bs4 import BeautifulSoup
import pandas as pd
soup = BeautifulSoup(html,'html.parser')
table = soup.find('div', attrs={'id':'MMMMMMMM'})
df_list = pd.read_html(str(table), header... | python|pandas|list|dataframe|beautifulsoup | 2 |
366,095 | 68,069,736 | Pandas convert dataframe to pivot table to show count | <p>How do I transform my df so that it becomes sort of a pivot table to show the count of each of Col2 for the user id:</p>
<p>I have a df:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Col1</th>
<th>Col2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>A</td>
<td>A1</td>
</tr>... | <p>Check <code>crosstab</code></p>
<pre><code>out = pd.crosstab(df.ID, df.Col2)
Out[157]:
Col2 A1 A2 A3 B1 B2 B3
ID
1 1 1 1 1 1 0
2 1 0 1 1 0 1
</code></pre> | python|pandas|dataframe | 1 |
366,096 | 68,316,121 | Python rolling mean starting on the next row | <p>I have results from a horse race and want to have the rolling win count for the start of each race. This is what I currently have:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Horse</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>4</td>
</tr>
<tr>
<td>A</td>
<td>1</t... | <p>Use the shift operator and cumsum</p>
<pre><code>df["Wins"] = (df["Position"].shift(1) == 1).cumsum()
</code></pre>
<p>output:</p>
<pre><code> Horse Position Wins
0 A 4 0
1 A 1 0
2 A 3 1
</code></pre> | python|pandas|rolling-computation | 2 |
366,097 | 68,188,439 | How to populate value of a column in a pandas df from another df? | <p>I have a dataframe:</p>
<pre><code>dict1 = {'Name': ['abc', 'def', 'ghi' , 'jkl'], 'Group': ['Group1', 'Group2', np.nan, np.nan], 'Class' : ['ClassA', 'ClassB' , np.nan, np.nan]}
df1 = pd.DataFrame(dict1)
df1:
Class Group Name
0 ClassA Group1 abc
1 ClassB Group2 def
2 NaN NaN ghi
3 NaN N... | <p>You can try doing this:</p>
<pre><code>dfNew=df1.merge(df2,on='Name',how='outer',suffixes=('','_y'))
dfNew['Group']=dfNew['Group'].fillna(dfNew['Group_y'])
dfNew['Class']=dfNew['Class'].fillna(dfNew['Class_y'])
dfNew=dfNew.drop(dfNew.filter(like='_').columns,1)
Out[35]:
Name Group Class
0 abc Group1 Class... | python|pandas|dataframe|numpy | 1 |
366,098 | 68,217,794 | How to add one dataframe to another inplace? | <p>The following code would not add df2 into df1. Note that I must use a function <code>f</code> here.</p>
<pre><code>>>> import pandas
>>> df1 = pandas.DataFrame({'A': [1, 2, 3], 'B': [11, 12, 13]})
>>> df2 = pandas.DataFrame({'C': [1, 2, 3], 'D': [11, 12, 13]})
>>> def f(df1, df2):... | <p>It seems that this is the most succinct code for this problem.</p>
<pre><code>>>> import pandas
>>> df1 = pandas.DataFrame({'A': [1, 2, 3], 'B': [11, 12, 13]})
>>> df2 = pandas.DataFrame({'C': [1, 2, 3], 'D': [11, 12, 13]})
>>> def f(df1, df2):
... df1[df2.columns] = df2
...
&... | python|pandas | 2 |
366,099 | 68,289,466 | how to add index suffix to each value in group | <p>Not sure how to articulate this exactly, but say I have</p>
<pre><code>df = pd.DataFrame({'A': ["a", "a", "a", "b", "b"], 'B': np.arange(5)})
df
A B
0 a 0
1 a 1
2 a 2
3 b 3
4 b 4
</code></pre>
<p>how would I add an index suffix for each groupby, to get:... | <p>Try with</p>
<pre><code>df.A + '-' + df.groupby('A').cumcount().add(1).astype('str')
Out[19]:
0 a-1
1 a-2
2 a-3
3 b-1
4 b-2
dtype: object
</code></pre> | python|pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.