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
6,400
66,241,524
How can I scrape a table's header that contains an image?
<p>I'm trying to scrape a table from a wiki website, by using pandas library, the header consists of 5 parts: name, stars, image, health, notes.<br /> I successfully scraped name, stars and notes, but the &quot;Health&quot; header has an image instead of a string name.<br /> (I would like to display &quot;Health&quot; ...
<pre><code>df = url[1] df.rename(columns={'Unnamed: 3':'Health'}, inplace=True) </code></pre> <p>result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;"></th> <th style="text-align: left;">Name</th> <th style="text-align: right;">Image</th> <th style="text-align: ...
html|python-3.x|pandas|dataframe|web-scraping
0
6,401
66,006,228
3D CNN using keras-tensorflow on pycharm ( Process finished with exit code 137 (interrupted by signal 9: SIGKILL) )
<p>I'm doing a 3D CNN to classify LUNA16 data set (CT scan data set), I'm using keras-tensorflow on pycharm.</p> <p>I'm following this code <a href="https://github.com/keras-team/keras-io/blob/master/examples/vision/3D_image_classification.py" rel="nofollow noreferrer">https://github.com/keras-team/keras-io/blob/master...
<p>Right now the code is running flawlessly on google colab.</p> <p>I think the limitation was with the GPU (my gpu is RTX 2080ti) vs google colab gpu Nvidia T4.</p> <p>I just preprocessed the data and saved it as a numpy array, then uploaded the arrays to google colab, and run the code after preprocessing. Now everyth...
python|tensorflow|keras|deep-learning
0
6,402
66,115,893
Multiple instances of tensorflow lite with NNAPI delegate
<p>NNAPI Delegate in Tensorflow lite uses shared memory for input and output tensors of the graph. However the name of the shared memory pool is hardcoded (<code>&quot;input_pool&quot;</code> and <code>&quot;otput_pool&quot;</code>):</p> <pre><code> // Create shared memory pool for inputs and outputs. nn_input_memor...
<p>The name given to the shared name is just used as a label. Using the same name when creating two different shared memory regions won't cause the same memory to be used. See for example <a href="https://cs.android.com/android/platform/superproject/+/master:system/core/libcutils/ashmem-dev.cpp;l=370" rel="nofollow nor...
tensorflow|tensorflow-lite|nnapi
1
6,403
46,251,557
Tensorflow : Is there way to feed the crop value (central fraction) to tf.image.central_crop?
<p>I want to central crop images, with different crop fraction for each image.</p>
<p>Lets say that you have the images saved in a list called <code>images</code> where <code>images[0]</code> is the first one and so on. Lets assume that the central crop fractions lie on the list called <code>central</code> where the <code>central[0]</code> is the fraction that you want for the first image and so on f...
python|tensorflow
0
6,404
46,257,905
pandas_datareader not working in jupyter-notebook (Anaconda)
<p>ModuleNotFoundError Traceback (most recent call last) in () 3 from matplotlib import style 4 import pandas as pd ----> 5 import pandas_datareader.data as web 6 7 style.use('ggplot')</p> <p>ModuleNotFoundError: No module named 'pandas_datareader'</p>
<p>data reader gotta be installed separetly.</p> <p>if using anacoda, try:</p> <pre><code>conda install -c https://conda.anaconda.org/anaconda pandas-datareader </code></pre>
python-3.x|pandas|anaconda|jupyter-notebook
4
6,405
58,253,826
Eigen values and vectors calculation error in python
<p>I'm trying to obtain the eigenvectors and values of any matrix 'X' in a specific format. I used the <code>linalg</code> function to get the eigen pairs but the expected output format is different from my result. For example, <code>v</code> and <code>e</code> denote the eigenvalues and eigenvectors. <code>v1 = 1</cod...
<p><strong>np.linalg.eigh</strong></p> <p>First, one should note that <code>np.linalg.eigh</code> calculates the eigenvalues of a Hermitian matrix -- this will not apply for all matrices. If you want to calculate the eigenvalues of any matrix <code>X</code> you should probably switch to something like <code>np.linalg....
python|numpy|matrix|eigenvalue|eigenvector
0
6,406
58,550,023
Pandas apply not working inside Spark parallelized code
<p>I am trying to use Pandas "apply" inside the parallelized code but the "apply" is not working at all. Can we use "apply" inside the code which gets distributed to the executors while using Spark (parallelize on RDD)?</p> <p>Code:</p> <pre><code>def testApply(k): return pd.DataFrame({'col1':k,'col2':[k*2]*5}) ...
<p>I am also getting the same error (TypeError: an integer is required (got type bytes)</p> <pre><code>from pyspark.context import SparkContext TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_11288/3937779276.py in &lt;module&gt; ----&gt; 1 from pyspark.contex...
python|apache-spark|pyspark|apply|pandas-apply
0
6,407
69,286,904
How to get evenly-spaced data quickly with a MultiIndex in pandas
<p>I have a dataframe indexed by stock ticker and date that's pretty sparse, something like:</p> <pre><code>df = pd.DataFrame({ 'ticker': ['SPY', 'GOOGL', 'GOOGL', 'TSLA', 'TSLA'], 'date': ['2021-01-01', '2021-09-01', '2021-09-21', '2021-09-21', '2021-09-22'], 'price': [430.0, 2500.0, 2600.0, 700.0, 710.0],...
<p>You'll probably see a huge improvement in performance using an <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>asof</code> merge</a>. First create all the rows you need from the cartesian product of unique ticker labels and the last three da...
python|pandas
3
6,408
44,740,150
Measure correlation without counting some values
<p>I have an array:</p> <pre><code>a = np.array([[1,2,3], [0,0,3], [1,2,0],[0,2,3]]) </code></pre> <p>which looks like:</p> <pre><code>array([[1, 2, 3], [0, 0, 3], [1, 2, 0], [0, 2, 3]]) </code></pre> <p>I need to calculate paired correlations, <strong>but without</strong> taking <code>0</code>...
<p>Actually, i decieded to change all zeros in data to <code>np.nan</code></p> <pre><code>for i,e_i in enumerate(array_data): for j, e_j in enumerate(e_i): if e_j == 0: array_data[i,j] = np.NaN </code></pre> <p>and then, <code>pandas.corr()</code> worked fine...</p>
python|numpy|correlation
0
6,409
44,770,573
Python pandas large database using excel
<p>I am comfortable using python / excel / pandas for my dataFrames . I do not know sql or database languages . </p> <p>I am about to start on a new project that will include around 4,000 different excel files I have. I will call to have the file opened saved as a dataframe for all 4000 files and then do my math on th...
<p>You definitely want to use a database. At nearly 2GB of raw data, you won't be able to do too much to it without choking your computer, even reading it in would take a while. </p> <p>If you feel comfortable with python and pandas, I guarantee you can learn SQL very quickly. The basic syntax can be learned in an hou...
python|pandas
2
6,410
60,760,573
Multiply 2 different dataframe with same dimension and repeating rows
<p>I am trying to multiply two data frame</p> <p>Df1</p> <pre><code>Name|Key |100|101|102|103|104 Abb AB 2 6 10 5 1 Bcc BC 1 3 7 4 2 Abb AB 5 1 11 3 1 Bcc BC 7 1 4 5 0 </code></pre> <p>Df2</p> <pre><code>Key_1|100|101|102|103|104 AB 10 2 1 5 1 BC 1 10 ...
<p>You can <code>rename</code> the df2 <code>Key_1</code> to <code>Key</code>(similar to df1) , then set index and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mul.html" rel="nofollow noreferrer"><code>mul</code></a> on <code>level=1</code></p> <pre><code>df1.set_index(['Name','...
python-3.x|pandas|dataframe
4
6,411
61,051,911
How to ensure each worker use exactly one CPU?
<p>I'm implementing <a href="https://arxiv.org/abs/1910.06591" rel="nofollow noreferrer">SEED</a> using ray, and therefore, I define a <code>Worker</code> class as follows</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import gym class Worker: def __init__(self, worker_id, env_name, n): ...
<p>You can pin your core at each worker. For example, you can use something like psutil.Process().cpu_affinity([i]) to pin an index i core at each worker. </p> <p>Also, before you pin your cpu, make sure to know what cpu has been assigned to the worker by this api. <a href="https://github.com/ray-project/ray/blob/203c...
python|numpy|ray
2
6,412
71,787,733
Pandas filter/subset columns based on conditions
<p>I have about 300 columns that are basically encoding of categorical variables. I'd like to drop columns where <code>sum</code> of values of column is <code>&lt;</code>, say 3.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'id': [0, 1, 2, 3, 4, 5], 'col1': [0, 0, 0, 0, ...
<p>You can use <code>loc</code> to use a boolean indexing on the columns:</p> <pre><code>N = 3 out = df.loc[:, df.sum(axis=0) &gt; N] </code></pre> <p>If <code>id</code> is not actually numeric or if <code>N</code> can be a very large number, then maybe <code>set_index</code> with <code>id</code> first, then use boolea...
python|pandas
2
6,413
71,465,857
How to conditionally aggregate a Pandas dataframe
<p>I have a dataframe with some data that I'm going to run simulations on. Each row is a datetime and a value. Because of the nature of the problem, I need to keep the original frequency of 1 hour when the value is above a certain threshold. When it's not, I could resample the data and run that part of the simulation o...
<p>So I found a solution.</p> <pre><code>grouped = df.resample(&quot;1D&quot;) def conditionalAggregation(x): if x['v'].max() &lt;= 3: idx = [x.index[0].replace(hour=0, minute=0, second=0, microsecond=0)] return pd.DataFrame(x['v'].max(), index=idx, columns=['v']) else: return x conditi...
python|pandas|dataframe
1
6,414
42,221,022
Pandas subtract all values from one value, move to next value and repeat
<p>I have a df with two columns 'a' and 'b' </p> <pre><code>[a] [b] 11 100 2 100 10 100 </code></pre> <p>What I need is an extra column 'c', which represents following calculation:</p> <p>((11-2) + (11-10)) / 100</p> <p>((2-11) + (2-10)) / 100</p> <p>((10-11) + (10-2)) / 100</p> <pre><code>[a] [b] [c] 11 ...
<p>I'll give a numpy example. For</p> <pre><code>&gt;&gt;&gt; a = numpy.array([11, 2, 10]) &gt;&gt;&gt; b = numpy.array([100, 100, 100]) </code></pre> <p>you can do</p> <pre><code>&gt;&gt;&gt; c = (len(a) * a - sum(a)) / b </code></pre> <p>Similar for a pandas data frame.</p>
python|pandas|dataframe|sum
2
6,415
69,782,130
Set alignment of columns in pandastable
<p>I am trying to set different alignment types for different columns in <a href="https://pandastable.readthedocs.io/en/latest/" rel="nofollow noreferrer">pandastable</a>.</p> <p>Meanwhile I have found a way to set the alignment for the complete table using the global configuration as shown here (in this example, defau...
<p>You can use <code>pt.columnformats['alignment'][colname]</code> to set the alignment of an individual column with name <code>colname</code>.</p> <p>For example, to change the alignment for the <code>label</code> column (one of the columns in the data model returned by <code>.getSampleData()</code>:</p> <pre class="l...
python|tkinter|pandastable
2
6,416
69,673,717
Python: numpy.sum returns wrong ouput (numpy version 1.21.3)
<p>Here I have a 1D array:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 75491328, 754...
<p>The problem is caused by integer overflow, you should change the datatype of <code>np.array</code> to <code>int64</code>.</p> <pre><code>import numpy as np np.array([Your values here], dtype=np.int64) </code></pre>
python|arrays|numpy
1
6,417
72,437,909
Playing with my Apple Health Data but the csv is harder to wrangle than I have encountered
<p>My pandas dataframe comes out as:</p> <pre><code> BURNED CALORIES Date 00 - 01 01 - 02 02 - 03 .... 23 - 24 1/13/19 17.6 11.53 3.24 28.6 1/14/19 1.5 1.46 2.41 27.44 </code></pre> <p>The top row is the hourly breakdown but the only column is...
<p>IIUC, is that what you're looking for?</p> <pre><code>df2=df.melt(id_vars='Date', var_name='variable') df2.rename(columns={'variable':'hours', 'value':'calories burned'}, inplace=True) df2 </code></pre> <pre><code> Date hours calories burned 0 1/13/19 00-01 17.6 1 1/14/19 00-01 1.5 2 1/13/19 01-02 ...
pandas|time|time-series
1
6,418
50,317,538
calculate end time from start time and duration (minutes) using pandas. Error on standard approach
<p>i have a pandas dataframe:</p> <p>Start_time | Duration(minutes) </p> <p>2018-03-01 16:37:09 | 155 </p> <p>2018-03-01 07:02:10 | 5 </p> <p>2018-03-01 13:07:09 | 250 </p> <p>2018-03-01 20:46:34 | 180 </p> <p>2018-03-01 07:45:49 | 5</p> <p>I want output as</p> <p>Start_time | End time 2018-03-01 16:37:0...
<p>You need change <code>DatetimeIndex</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> for remove first error:</p> <blockquote> <p>Cannot compare type 'Timestamp' with type 'int' ** </p> </blockquote> <pre><code...
python|pandas
3
6,419
45,584,907
Flatten layer of PyTorch build by sequential container
<p>I am trying to build a cnn by sequential container of PyTorch, my problem is I cannot figure out how to flatten the layer.</p> <pre><code>main = nn.Sequential() self._conv_block(main, 'conv_0', 3, 6, 5) main.add_module('max_pool_0_2_2', nn.MaxPool2d(2,2)) self._conv_block(main, 'conv_1', 6, 16, 3) main.add_module('...
<p>This might not be exactly what you are looking for, but you can simply create your own <code>nn.Module</code> that flattens any input, which you can then add to the <code>nn.Sequential()</code> object:</p> <pre><code>class Flatten(nn.Module): def forward(self, x): return x.view(x.size()[0], -1) </code><...
python|conv-neural-network|pytorch
18
6,420
45,713,159
print mismatch items in two array
<p>I want to compare two array(4 floating point)and print mismatched items. I used this code:</p> <pre><code>&gt;&gt;&gt; from numpy.testing import assert_allclose as np_assert_allclose &gt;&gt;&gt; x=np.array([1,2,3]) &gt;&gt;&gt; y=np.array([1,0,3]) &gt;&gt;&gt; np_assert_allclose(x,y, rtol=1e-4) AssertionError: N...
<p>Just use</p> <pre><code>~np.isclose(x, y, rtol=1e-4) # array([False, True, False], dtype=bool) </code></pre> <p>e.g.</p> <pre><code>d = ~np.isclose(x, y, rtol=1e-4) print(x[d]) # [2] print(y[d]) # [0] </code></pre> <p>or, to get the indices</p> <pre><code>np.where(d) # (array([1]),) </code></pre>
python-3.x|numpy
7
6,421
62,877,986
AttributeError: module 'pandas' has no attribute 'df'
<p>For a current project, I am planning to clean a Pandas DataFrame off its Null values. For this purpose, I want to use <code>Pandas.DataFrame.fillna</code>, which is apparently a solid soliton for data cleanups.</p> <p>When running the below code, I am however receiving the following error <code>AttributeError: modul...
<p>When you load the file to the pandas - in your code the <code>data</code> variable is a <code>DataFrame</code> instance. However, you made a typo.</p> <pre><code>df = pd.json_normalize(data) df = df.fillna() </code></pre>
python|pandas|dataframe
2
6,422
71,231,466
Muliply only numeric values from object type column pandas
<pre><code>df = pd.DataFrame({'col1': [1, 2, 4, 5, 'object']}) df['col1'] * 5 </code></pre> <p>this code multiplies 'object' string to 5 and writes the string 5 times but I want to multiply only numeric values strings should be leave as it is. I have also tried to convert column to numeric using to_numeric with errors=...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.isnumeric.html#pandas.Series.str.isnumeric" rel="nofollow noreferrer"><code>isnumeric</code></a> to identify rows with numerics values.</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1': [1, 2, 4, 5, 'object']}) mask_ = df['col1...
python|pandas
0
6,423
52,273,275
regex replacing multiple codes with values in a column
<p>I have a dataframe(df) with different columns. One of the column (col1) is as follows:</p> <pre><code> col1 ---- 0 1 1 2 2 1-2 3 1,2 4 1-3 5 3 </code></pre> <p>I am using .replace method in python/pandas to replace the codes in col1 using the code:</p> <pre><code> df.col1.replace(to_replace=({'...
<p>Repeating your work I don't seem to get the same error as you do with input </p> <p><code>df = pd.DataFrame({'col1' : ['1', '2', '1-2', '1,2', '1-3', '3']})</code></p> <p>and applying the same .replace method:</p> <p><code>df.col1.replace(to_replace=({'1':'Normal','2':'1-2 more than normal','3':'3-4 more than nor...
python|string|pandas|dictionary
0
6,424
52,046,971
sigmoid_cross_entropy loss function from tensorflow for image segmentation
<p>I'm trying to understand what the <code>sigmoid_cross_entropy</code> loss function does with regards to image segmentation neural networks:</p> <p>Here is the relevant Tensorflow source <a href="https://github.com/tensorflow/tensorflow/blob/600caf99897e82cd0db8665acca5e7630ec1a292/tensorflow/python/ops/nn_impl.py#L...
<p><code>sigmoid_cross_entropy_with_logits</code> is used in multilabel classification.</p> <p>The whole problem can be divided into binary cross-entropy loss for the class predictions that are independent(e.g. 1 is both even and prime). Finaly collect all prediction loss and average them.</p> <p>Below is an example:...
python|tensorflow|machine-learning|neural-network|deep-learning
7
6,425
52,422,265
Python MultiIndex Column Rename
<p>I am a <strong>NEWBIE</strong> to panda framework. I tried various things shown below and I Want to rename a column name in pandas dataframe , can some one please guide me with this. The column is multilevel pivot column. </p> <pre><code>import pandas as pd import numpy as np df = pd.read_excel(r'D:\cod_sheets\18_0...
<p>You just need to add the argument to <code>df_pivot.rename(columns = {"CDS_STATUS":"CDS"})</code> that is <code>df_pivot.rename(columns = {"CDS_STATUS":"CDS"},inplace=True)</code></p>
python|pandas|pivot-table|pandas-groupby
1
6,426
52,107,106
Visualizing cumsum python
<p>This is related to post <a href="https://stackoverflow.com/questions/52104500/rolling-difference-using-pandas">Rolling Difference using Pandas</a></p> <p>Now that I have this dataframe below, i am trying to visualize this. </p> <pre><code>Item Add Subtracts Month Net_Items Monthly_Available_Items C 68 ...
<p>You can add a legend by specifying the <code>label</code></p> <pre><code>ax2 = sns.barplot(x = 'Month', y = 'Monthly_Available_Items', data = stack_df, color = 'purple', label = "Monthly_Available_Items") ax2.legend() # will show the legend for the barplot...
python|pandas|matplotlib|seaborn
0
6,427
60,478,009
Convert pandas DataFrame to 2-layer nested JSON using groupby
<p>Assume that I have a pandas dataframe called <code>df</code> similar to:</p> <pre><code>source tables src1 table1 src1 table2 src1 table3 src2 table1 src2 table2 </code></pre> <p>I'm currently able to output a JSON file that iterates through ...
<p>Is this what you're looking for?</p> <pre><code>data = [ {k: v} for k, v in df.groupby('source')['tables'].agg( lambda x: {v: {} for v in x}).items() ] with open('data.json', 'w') as f: json.dump(data, f, indent=2) </code></pre> <p>There are two layers to the answer here. To group the table...
python|json|pandas|dataframe|object
1
6,428
72,769,631
How use two columns as a single condition to get results in pyspark
<p>I have:</p> <pre><code>+-----------+------+ |ColA |ColB | +-----------+------+ | A | B| | A | D| | C | U| | B | B| | A | B| +-----------+------+ </code></pre> <p>and I want to get:</p> <pre><code>+-----------+------+ |ColA |ColB | +-----------...
<p>Need add parentheses and <code>|</code> for bitwise OR:</p> <pre><code>pandasDF[(pandasDF[&quot;colA&quot;]!=&quot;A&quot;) | (pandasDF[&quot;colB&quot;]!=&quot;B&quot;)] sparkDF.where((sparkDF['colA'] != 'A') | (sparkDF['colB'] != 'B')).show() </code></pre>
pandas|apache-spark|pyspark
1
6,429
72,799,969
install tensorflow-decision-forests in windows
<p>I have to install tensorflow-decision-forests in windows. I tried:</p> <pre><code>pip install tensorflow-decision-forests pip3 install tensorflow-decision-forests pip3 install tensorflow_decision_forests --upgrade </code></pre> <p>I get:</p> <pre><code>ERROR: Could not find a version that satisfies the requirement t...
<p><code>tensorflow-decision-forests</code> 0.2.6 <a href="https://pypi.org/project/tensorflow-decision-forests/#files" rel="nofollow noreferrer">provides</a> binary wheels only for Linux and no source code. So <code>pip</code> cannot install it on non-Linux platforms.</p> <p>There're <a href="https://github.com/tensor...
python|tensorflow|pip|tensorflow-decision-forests
1
6,430
72,805,397
How to create a new dataframe that contains the value changes from multiple columns between two exisitng DFs
<p>The first two tables represent snippets from the first and second dataframes, respectively. I am trying to create a new dataframe that contains the numerical changes for each attribute</p> <p><img src="https://i.stack.imgur.com/2o0vM.png" alt="" /></p> <p>Please also see my other post for how I framed the same quest...
<p>You can try setting <code>ID</code> and <code>Name</code> columns as index then do substraction</p> <pre class="lang-py prettyprint-override"><code>out = (df2.set_index(['ID', 'Name']) - df1.set_index(['ID', 'Name'])).reset_index() </code></pre> <pre><code>print(df1) ID Name A B 0 1 a 89 91 print(df2...
python|pandas|dataframe
0
6,431
61,663,005
Working with pandas to select/extract rows from dataframe
<p>I am trying to extract information from a number of countries from a dataset I downloaded. I was able to figure out how to pull one country, but have had syntax errors trying to pull more than one in the same line. Here it is with the output:</p> <pre><code>ef=df1.loc[df1['countries'] == 'Hong Kong'] print(ef) <...
<p>If you want to filter the dataframe based on multiple countries you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a>.</p> <pre><code>country_list = ['Hong Kong', 'US', 'Canada', 'India', 'Russia'] ef = df1[df1...
python|pandas|csv|dataframe
2
6,432
61,964,496
Pandas - json normalize inside dataframe
<p>I want to break down a column in a dataframe into multiple columns. </p> <p>I have a dataframe with the following configuration:</p> <pre><code> GroupId,SubGroups,Type,Name -4781505553015217258,"{'GroupId': -732592932641342965, 'SubGroups': [], 'Type': 'DefaultSite', 'Name': 'Default Site'}",OrganisationGr...
<p>You can try using <code>ast</code> package:-</p> <pre><code>import pandas as pd import ast data = [[-4781505553015217258,"{'GroupId': -732592932641342965, 'SubGroups': [], 'Type': 'DefaultSite', 'Name': 'Default Site'}","OrganisationGroup","CompanyXYZ"], [-4781505553015217258,"{'GroupId': 8123255835936628631, '...
json|pandas|dataframe
0
6,433
62,020,666
Is there any way to insert image logo/ Text in before saving to_html in pandas
<p>I am saving pandas output as to_html()</p> <p>Is there any way to integrate the logo/Text at the top of the html page before saving.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_html.html" rel="nofollow noreferrer"><code>to_html</code></a> returns a string with the html if the first parameter <code>buf</code> is <code>None</code>. You can than prepend your image or text html to this string and then write...
pandas
1
6,434
61,657,329
How to resample a pandas dataframe to hourly mean, taking into account both a time and a column with a string value?
<p>I am trying to make an hourly mean of a dataframe in python, by taking into account the date info but also string info in a certain column. Please see the example below.</p> <pre><code> station time temperature 0 EHAM 2020-01-01 13:30:00 2 1 EHAM 2020-01-01 13:50:00 5 2 ...
<p>Aggregate <code>mean</code> with convert <code>datetimes</code> to dates by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>Series.dt.date</code></a>:</p> <pre><code>#convert sampel data to numeric df['temperature'] = df['temperature'].a...
python|string|pandas|dataframe|datetime
1
6,435
61,806,786
How to create multiple columns when map the column data in pandas
<p>I am trying to create three additional columns from one column , I have datetime and categorial data , I want to show the number of categories contain each row for example </p> <p><strong>I have the date, categories and count. This is the dataframe</strong></p> <p><a href="https://i.stack.imgur.com/k5l8d.png" rel=...
<p>You can make use of pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">pivot</a></p> <p>Considering your original dataframe containing columns <code>CreatedDate</code>, <code>Categories</code> and <code>count</code></p> <pre><code>cate...
python|python-3.x|pandas
0
6,436
58,019,367
Selectively update dataframe column with a dictionary map
<p>I want to use a dictionary to map / replace row values in a pandas column - but only for a subset of rows based on a criteria</p> <pre><code>df['var'] = df['var'].map(mydict) </code></pre> <p>but only where </p> <pre><code>df['anothervar'] is somevalue </code></pre> <p>Can I do this?</p>
<p>Check with <code>np.where</code> </p> <pre><code>df['var'] = np.where(df['anothervar']=='somevalue',df['var'].map(mydict),df['var']) </code></pre>
python|pandas
0
6,437
55,017,220
Getting "key error" while plotting using Pandas
<p>I am trying to do a simple plot of a data from a text file. Below is the file:</p> <pre><code>Date,Open,High,Low,Close 03-10-16,774.25,776.065002,769.578768,772.559998 04-10-16,776.03,778.710022,772.890015,776.429993 05-10-16,779.30,782.070007,775.650024,776.469971 06-10-16,779.00,780.479989,775.539978,776.859985 0...
<p>This modification will work. You misunderstood how to use df.plot(). Please refer this page <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html" rel="nofollow noreferrer">visualization</a>. This code below is just a basic visualization, you can change to <strong>df.plot.box()</strong>...
python-3.x|pandas
0
6,438
54,769,135
assign new value to repeated (or multiple) objective element(s) to a pandas dataframe
<p>I have a pandas dataframe:</p> <pre><code>df = pd.DataFrame({'AKey':[1, 9999, 1, 1, 9999, 2, 2, 2],\ 'AnotherKey':[1, 1, 1, 1, 2, 2, 2, 2]}) </code></pre> <p>I want to assign a new value to a specific column and for each element having a specific value in that column.</p> <p>Let say I want to assign the new v...
<p>You can use loc in this way:</p> <pre><code>df.loc[df["AKey"]==9999, "AKey"] = 8888 </code></pre> <p>Producing the following output:</p> <p><a href="https://i.stack.imgur.com/OtxfV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OtxfV.png" alt="enter image description here"></a></p> <p>With yo...
python|pandas|pandas-loc
1
6,439
54,873,983
merge consecutive matching rows
<p>I want to merge all consecutive rows by matching all 'X' fields and concatenating the 'Y' field.</p> <p>Below is sample data -</p> <pre><code>[Y X1 X2 X3 X4 X5 A NaN -3810 TRUE None None B NaN -3810 TRUE None None C NaN -3810 TRUE None None D NaN -3810 None None None E ...
<p>A little bit tricky , using <code>shift</code> create the groupkey , then <code>agg</code> </p> <pre><code>df.fillna('NaN',inplace=True) # notice here NaN always no equal to NaN, so I replace it with string 'NaN' df.groupby((df.drop('Y',1)!=df.drop('Y',1).shift()).any(1).cumsum()).\ agg(lambda x : ','.join(x) ...
python|pandas
3
6,440
55,120,541
How can I evaluate the accuracy loss of the converted ftlite model?
<p>I trained a model based on the ssd-moblienet algorithm.And use the eval.py script to evaluate the mAP of the model.</p> <p>I need to use this model on iOS, so I converted it to a tflite model and it works now.</p> <p>I want to analyze the precision loss when converting a model by the mAP value before and after the...
<p>There isn't any official script. You'll have a write a custom script which uses Tensorflow's metrics API found at <code>model/research/object_detection/metrics</code> passing the detections and groundtruth as arguments.</p> <p>An example</p> <pre><code># Append to $PYTHONPATH path to models/research and cocoapi/Pyth...
tensorflow|object-detection|tensorflow-lite
3
6,441
49,607,116
can anyone explain how does this code work? pandas in python
<pre><code>` for column in list(df.columns[df.isnull().sum() &gt; 0]): mean = df[column].mean() df[column].fillna(mean,inplace=True) df.info()` </code></pre> <p>i don't understand the first line of code, i mean, ... <strong>list</strong>() ... does it means everything in the parenthesis will be return to the ...
<p><code>list</code> here convert <code>Index</code> (columns names with at least one <code>NaN</code>) to <code>list</code>:</p> <pre><code>df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,np.nan,5,7,1,0], '...
pandas
0
6,442
49,366,765
How can I read endlessly from a Tensorflow tf.data.Dataset?
<p>I'm switching my old datalayer (using Queues) to the "new" and recommended Dataset API. I'm using it for the first time, so I'm providing code examples in case I got something fundamentally wrong.</p> <p>I create my Dataset from a generator (that will read a file, and provide n samples). It's a small dataset and n_...
<p>Datasets have <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#repeat" rel="nofollow noreferrer"><code>repeat</code></a> and <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle" rel="nofollow noreferrer"><code>shuffle</code></a> methods.</p> <pre class="lang-py prettyprint...
tensorflow|tensorflow-datasets
3
6,443
49,344,432
ValueError: Cannot feed value of shape (64,) for Tensor 'x:0', which has shape '(?, 100, 100, 3)'
<p>From skimage import io, transform:</p> <pre><code> import os import tensorflow as tf import numpy as np import time import glob import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' path = 'D:/data/datasets/flower_photos/' model_path = 'D:/data...
<p>Since <strong>w = 100, h = 100, c = 3</strong> and you have defined your input placeholder <code>x</code> as follows,</p> <pre><code>x=tf.placeholder(tf.float32,shape=[None,w,h,c],name='x') </code></pre> <p><code>x</code> has the shape of <strong>(?,100,100,3)</strong>. Here <strong>?</strong> refer the batch size...
python|tensorflow
3
6,444
73,349,869
Not a gzipped file error when reading a gzipped file
<p>I saved a gzip parquet file:</p> <pre><code>df.to_parquet(&quot;meth_450_clin_all_kipan.parquet.gz&quot;, compression=&quot;gzip&quot;) </code></pre> <p>And then I want to load it as matrix:</p> <pre><code>matrix = pd.read_table('../input/meth-clin-kipan/meth_450_clin_all_kipan.parquet.gz') </code></pre> <p>Tracebac...
<p>The solution is to read the file using <code>read_parquet</code> and then convert it into a numpy array.</p> <pre><code>matrix = pd.read_parquet('../input/meth-clin-kipan/meth_450_clin_all_kipan.parquet.gz').to_numpy() </code></pre>
python|pandas|gzip
1
6,445
67,334,116
Shift rows in array independently
<p>I want to shift each row by its row-number and be relative to my desired output shape. An example:</p> <pre><code>array([[0, 1, 2], array([[0, 1, 2], array([[0, 1, 2, 0, 0], [1, 2, 3], -&gt; [1, 2, 3], -&gt; [0, 1, 2, 3, 0], [2, 3, 4]]) ...
<p>Here is a solution for square matrices of size n.</p> <p><code>np.concatenate((A,np.zeros((n,n))),axis=1).flatten()[0:-n].reshape([n,2*n-1])</code></p>
python|arrays|numpy
2
6,446
60,225,723
Ordering dataframe columns row by row
<p>I have a df that looks like this</p> <pre><code>df = pd.DataFrame({'A' : ['1','2','3','7'], 'B' : [7,6,5,4], 'C' : [5,8,7,1], 'v' : [1,9,9,8]}) df=df.set_index('A') df B C v A 1 7 5 1 2 6 8 9 3 5 7 9 7 4 1 8 </code>...
<p>If performance is important use <a href="https://numpy.org/doc/1.18/reference/generated/numpy.sort.html" rel="nofollow noreferrer"><code>numpy.sort</code></a> with <code>axis=1</code>:</p> <pre><code>df[['B','C']] = np.sort(df[['B','C']], axis=1) print (df) B C v A 1 5 7 1 2 6 8 9 3 5 7 9 7 ...
python|pandas
4
6,447
60,196,260
How to use keras ImageDataGenerator flow_from_directory given a map from image name to class label?
<p>Folder's structure is like following:</p> <pre><code>-dataset |---train_set | |-- img01.jpg | |-- img02.jpg | |-..... | |---val_set </code></pre> <p>I don't have subfolders in train_set whose name is class label. However I have a dictionary from image name to class label like <cod...
<p>Keras ImageDataGenerator class also offers <a href="https://keras.io/preprocessing/image/#flow_from_dataframe" rel="nofollow noreferrer">flow_from_dataframe()</a> method, that should do the job. </p> <p>Check out this <a href="https://medium.com/datadriveninvestor/keras-imagedatagenerator-methods-an-easy-guide-550e...
image-processing|keras|tensorflow2.0
0
6,448
65,313,416
Getting pandas dataframe from json file
<p>I would like to flatten a JSON file to create a pandas DataFrame. The json output is:</p> <pre><code>{ 'info': { 'status': [ ], 'weightcorp': { 'weight': 4.0 } }, 'results': [ { 'instrument': 'A', 'ts': [ { 'date': '2020-12-10', 'indicato...
<p>Let's try a custom function to your data:</p> <pre><code>def flatten(d): ''' remove all intermediate dictionaries and list ''' ret = dict() for k, v in d.items(): # case when value is a dictionary if isinstance(v, dict): sub = flatten(v) for kk, vv in sub.i...
json|pandas|list|dataframe|dictionary
2
6,449
65,461,750
tensorflow.python.framework.errors_impl.UnknownError: Failed to rename; : Access is denied. ; Input/output error
<p>I am not able to download and load tensorflow dataset on my Windows 10 machine. It works okay on Google colab. Can someone please help me?</p> <p><strong>Code:</strong></p> <pre><code>import tensorflow_datasets as tfds datasets, info = tfds.load(&quot;imdb_reviews&quot;, as_supervised=True, with_info=True) </code><...
<p>Had this issues and upgrading the tensorflow-datasets solved this</p> <pre><code>pip install -U tensorflow-datasets </code></pre> <p>this will replace the tensorflow-datasets-1.2.0 and install tensorflow-datasets-4.2.0</p> <p>working on windows 10</p>
python|tensorflow|tensorflow2.x
3
6,450
65,271,478
Failed to save list of DataFrames to multisheet Excel spreadsheet
<p>I was trying to do the same thing with the question <a href="https://stackoverflow.com/questions/14225676/save-list-of-dataframes-to-multisheet-excel-spreadsheet">here</a>, and followed the method given by the answers. Here is my code:</p> <pre><code>import pandas as pd import xlsxwriter mylist=[df_1,df_2,df_3] fo...
<p>You have some pieces inside the loop that should be outside. Reference the docs here: <a href="https://xlsxwriter.readthedocs.io/example_pandas_multiple.html" rel="nofollow noreferrer">https://xlsxwriter.readthedocs.io/example_pandas_multiple.html</a></p> <pre><code>writer = pd.ExcelWriter('data.xlsx', engine='xlsxw...
python|excel|pandas
1
6,451
49,969,539
Adding a name (string) column to an existing pandas DF
<p>I have an array(of float data type) from a FITS file of (1, 5000) dimension. I have created a pandas DF from it so that I can export it as a csv later. <a href="https://i.stack.imgur.com/CXCjB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXCjB.png" alt="The data frame from the data"></a>. Howev...
<pre><code>FSC0029m4226 = pd.DataFrame(np.array(FSC0029m4226).byteswap().newbyteorder()) </code></pre>
python|string|python-2.7|pandas|dataframe
0
6,452
63,906,723
Keras image_dataset_from_directory not finding images
<p>I want to load the data from the directory where I have around 5000 images (type 'png'). But it returns me an error saying that there are no images when obviusly there are images. This code:</p> <pre><code>width=int(wb-wa) height=int(hb-ha) directory = '/content/drive/My Drive/Colab Notebooks/Hair/Images' train_ds =...
<p>I have found the answer so I am posting in case it might help someone.</p> <p>The problrem is the path, as I was using the path to the folder with the images whereas I should have used the directory (one folder above).</p> <pre><code>directory = '/content/drive/My Drive/Colab Notebooks/Hair' </code></pre> <p>Note th...
tensorflow|keras|tensorflow-datasets|image-preprocessing
14
6,453
46,914,292
How to do reinforcement learning with an LSTM in PyTorch?
<p>Due to observations not revealing the entire state, I need to do reinforcement with a recurrent neural network so that the network has some sort of memory of what has happened in the past. For simplicity let's assume that we use an LSTM. </p> <p>Now the in-built PyTorch LSTM requires you to feed it a an input of sh...
<p>Maybe you can feed your input sequence in a loop to your LSTM. Something, like this:</p> <pre><code>h, c = Variable(torch.zeros()), Variable(torch.zeros()) for i in range(T): input = Variable(...) _, (h, c) = lstm(input, (h,c)) </code></pre> <p>Every timestep you can use (h,c) and input to evaluate action ...
recurrent-neural-network|backpropagation|reinforcement-learning|pytorch
1
6,454
46,859,478
Update columns in df2 based on df1 on index of date
<p>I want to to have a data frame <strong>df2</strong> that will contain the values from <strong>df1</strong>. Both data frames have an index of date. Both data frames contain the same columns. I just want to update the columns of df2 if the index of df2 exists in df1. </p> <p><strong>df1</strong> </p> <pre><code>Sym...
<p>You can try to merge on indices:</p> <pre><code>df3 =df1.merge(df2, left_index=True, right_index=True, suffixes=("","_"), how='right') df3= df3.drop(['K1_', 'K2_', 'K3_'], axis=1).fillna(0) </code></pre>
python|pandas
1
6,455
63,314,009
fill NaN values of a df under condition
<p>I have a resampled df:</p> <pre><code> Timestamp Loading Power Energy ID status 2020-04-09 06:45:00 1.0 1000 5000 1 on 2020-04-09 06:46:00 1.0 1000 5500 1 on 2020-04-09 06:47:00 NaN ...
<p>Use for loop like this</p> <p>df[&quot;status&quot;]=[df[&quot;status&quot;].values[i-1] if pd.isna(x) else x for i,x in enumerate (df[&quot;status&quot;] .values) ]</p>
python|pandas
0
6,456
63,257,389
Pandas Boolean Indexing to Compare DataFrame and Results in List of Dicts
<p>I have the below dataframes</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame([[70, np.nan, &quot;hello&quot;], [89, 3, 4], [210, 5, 64], [11, 75, 8]], columns=[&quot;ID&quot;, &quot;A&quot;, &quot;B&quot;], dtype='object') df2 = pd.DataFrame([[70, np.nan, &quot;world&quot;], [89, 33, 44], [...
<p>Let us try <code>where</code>, also I recommend output series not dict</p> <pre><code>s=df2.set_index('ID').where(diff_mask.drop('ID',1).values).stack() Out[74]: ID 70 B world 89 A 33 B 44 21 B 6 11 A 7 dtype: object </code></pre> <p>to dict</p> <pre><code>d=[y.unstack().rese...
python|pandas|numpy|dataframe
4
6,457
63,089,129
Question on restoring training after loading model
<p>Having trained for 24 hours, the training process saved the model files via <code>torch.save</code>. There was a power-off or other issues caused the process exited. Normally, we can load the model and continue training from the last step.</p> <p>Why should not we load the states of optimizers (Adam, etc), is it nec...
<p>Yes, you can load the model from the last step and retrain it from that very step.</p> <p>if you want to use it only for inference, you will save the state_dict of the model as</p> <pre><code>torch.save(model, PATH) </code></pre> <p>And load it as</p> <pre><code>model = torch.load(PATH) model.eval() </code></pre> <p...
pytorch
2
6,458
62,968,276
Apply an Encoder-Decoder (Seq2Seq) inference model with Attention
<p>Hello a <strong>StackOverflow</strong> community!</p> <p>I'm trying to create an inference model for a <strong>seq2seq</strong> (<em>Encoded-Decoded</em>) model with <strong>Attention</strong>. It's a definition of the inference model.</p> <pre><code>model = compile_model(tf.keras.models.load_model(constant.MODEL_PA...
<p>I think you also need to take the encoder output as output from the encoder model and then give it as input to the decoder model as the attention part requires it. Maybe this changes could help-</p> <pre><code>model = compile_model(tf.keras.models.load_model(constant.MODEL_PATH, compile=False)) encoder_input = model...
python|tensorflow|keras|seq2seq|encoder-decoder
0
6,459
67,859,542
API to get mean and standard deviation for TFLite Models
<p>How can we get these values of mean and standard deviation for any TFLite model ? Is there any API to fetch mean and std deviation ? where is this information stored ?</p> <p>How can TFLite users know with what values they have to normalize the input ? Can these values obtained run time ?</p> <p>To change these mean...
<p>If you're talking about the quantization parameters (mean and std to convert float to int), see <a href="https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/Tensor.QuantizationParams" rel="nofollow noreferrer">https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/Tensor.QuantizationParams</...
python|tensorflow|tensorflow2.0|tensorflow-lite
0
6,460
67,889,133
What is the sql equivalent function of the python function .size()?
<p>I am trying to solve a problem on bigquery; list of customers with consistent transactions for 6 months. I already solved it with python but I don't know how to replicate the code on sql. This is the code</p> <pre><code>df.groupby(['Month','accounttoken'])['transactionid'].value_counts() a=df[df.groupby(['Month','ac...
<p>count(*) is counting the number of rows in a group.</p> <pre><code>SELECT count(*) as num_transactions FROM data GROUP BY Month, accounttoken, name HAVING count(*) &gt;= 5 </code></pre> <p>You can use these SQL Query for the replacement of last two line of python code given by you. I hope SQL query given by you is a...
python|pandas|google-bigquery
0
6,461
67,684,718
How to display `.value_counts()` in interval in pandas dataframe
<p>I need to display <code>.value_counts()</code> in interval in pandas dataframe. Here's my code</p> <pre><code>prob['bucket'] = pd.qcut(prob['prob good'], 20) grouped = prob.groupby('bucket', as_index = False) kstable = pd.DataFrame() kstable['min_prob'] = grouped.min()['prob good'] kstable['max_prob'] = grouped.max(...
<p>Use named aggregation for simplify your code, for counts is used <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a> to new column <code>counts</code> and is apply function for column <code>bucket</code>:</p...
python|pandas|dataframe
1
6,462
61,522,733
Reshape model input LSTM
<p>Hello everyone i'm trying to build a model to predict emotion in speech. Since the audio have different lengths the feature matrixes also have different lengths and therefore i have a variable timestep. I read on other answers that i can leave the input shape of LSTM as follows: <code>model.add(LSTM(1, input_shape=(...
<p>I am also new to this but from what I have found: The input to LSTM is 3-D [samples,timesteps,features] For more information, please visit this link : <a href="https://stats.stackexchange.com/questions/264546/difference-between-samples-time-steps-and-features-in-neural-network">https://stats.stackexchange.com/questi...
python|tensorflow|keras|lstm|recurrent-neural-network
0
6,463
61,581,042
Make a new column based on other columns id values - Pandas
<p>How can i make new columns based on another columns id values? </p> <p>The data look like this.</p> <pre><code>value id 551 54089 12 54089 99 54089 55 73516 123 73516 431 73516 742 74237 444 74237 234 74237 </code></pre> <p>I want the datase...
<p>Use <code>groupby</code> with <code>unstack</code>:</p> <pre><code>df = df.groupby('id')['value'].apply(lambda x: pd.Series(x.tolist(), index=['v1', 'v2', 'v3']))\ .unstack() # or df.groupby('id')['value'].apply(lambda x: pd.Da...
python|pandas|dataset
3
6,464
68,657,888
Pandas Taking the Nlargest ignoring 0
<p>Hi is there a way in Pandas to do nlargest but only take values excluding 0? For example if we have [5, 0, 0] and we want to take the 2 largest, then it would only return 5 because the other values are 0?</p>
<p>You can simply remove the value 0 before you do nlargest:</p> <pre><code>l = pd.Series([5,0,0]) l[l != 0].nlargest(2) 0 5 dtype: int64 </code></pre> <p>Similarly, if you have a list of numbers you want to exclude:</p> <pre><code>l[~l.isin(list_of_excluded_numbers)].nlargest(2) </code></pre>
pandas
-1
6,465
53,299,543
Is there any method in tensorflow like get_output in lasagne
<p>I found that it is easy to use lasagne to make a graph like this.</p> <pre class="lang-py prettyprint-override"><code>import lasagne.layers as L class A: def __init__(self): self.x = L.InputLayer(shape=(None, 3), name='x') self.y = x + 1 def get_y_sym(self, x_var, **kwargs): y = L.get_output(self...
<p>I'm not familiar with lasagne but you should know that ALL of TensorFlow uses graph based computation (unless you use tf.Eager, but that's another story). So by default something like:</p> <p><code>net = tf.nn.conv2d(...)</code> </p> <p>returns a reference to a Tensor object. In other words, <code>net</code> is N...
tensorflow|theano|lasagne
0
6,466
52,996,993
reshaping daily data on intraday values pandas
<p>I have a DF that looks like this:</p> <pre><code> Last 1996-02-26 09:31:00 65.750000 1996-02-26 09:32:00 65.890625 1996-02-26 09:33:00 NaN 1996-03-27 09:31:00 266.710000 1996-03-27 09:32:00 266.760000 1996-03-27 09:33:00 266.780000 </code></pre> <p>I want to ...
<p>If your index is <code>str</code> dtype, create a MultiIndex and call <code>unstack</code>:</p> <pre><code>idx = pd.MultiIndex.from_arrays(zip(*df.index.str.split())) df = df.set_index(idx)['Last'].unstack(0) print(df) 1996-02-26 1996-03-27 09:31:00 65.750000 266.71 09:32:00 65.890625 266....
python|pandas
2
6,467
65,756,217
custom sorting values of dataframe
<p>I want to custom sort my dataframe. This is sample dataframe which has structure like mine:</p> <pre><code>data = {'name':['name1','name1','name1','name2','name2','name2','name3','name3','name3'], 'col1':[19, 38, 25, 10, 39, 28, 25, 20, 23], 'col2':[29, 28, 25, 20, 19, 18, 15, 10, 13], 'col3'...
<p>If I understand, you want to sort groups of three rows:</p> <pre><code>groups = df.reset_index().loc[:,&quot;date&quot;:].groupby(lambda x: int(x/3)) df[:] = groups.apply(lambda x: x.sort_values(&quot;name&quot;, ascending = False)).values print(df) # date name col1 col2 col3 #0 2020-12-31 name3 2...
pandas|dataframe|sorting
0
6,468
65,654,800
Plot from matplotlib and pandas is not working with data json file because ValueError
<p>I tried generate a simple plot, but error here. My code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd real_estates = pd.read_json('/Users/pablo/Desktop/project/REscraper/real_estates.json') # print(real_estates) plt.plot(real_estates.size, real_estates.price) plt.show() ...
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.size.html" rel="nofollow noreferrer" title="Pandas docs">size</a> happens to be an attribute of a DataFrame. Use a <a href="https://docs.python.org/3/reference/expressions.html#subscriptions" rel="nofollow noreferrer" title="Python docs">subscrip...
python|json|pandas|matplotlib
0
6,469
65,751,866
pandas pivot table issue - assuming it is how i am structuring it?
<p>i have a dataset that contains video game platforms, and the year that games were released for it.</p> <p>what i'm trying to do is end up with a dataframe that has the count of titles for each year released by platform.</p> <p>my initial dataframe looks like this:</p> <pre><code>platform year 0 Wii 2006.0 1...
<p>Here is the solution with pivot table:</p> <pre><code>res = pd.pivot_table(df,index=['year', 'platform'],aggfunc = 'size') &gt;&gt;&gt; print(res) year platform 1984.0 NES 1 1985.0 NES 1 1989.0 GB 1 1990.0 SNES 1 1996.0 GB 1 1999.0 GB 1 2004.0 PS2 ...
python|pandas|pandas-groupby|pivot-table
1
6,470
65,578,017
Error: Error when checking input: expected dense_Dense1_input to have 3 dimension(s). but got array with shape 1,9
<p>Im really new to tensorflow.js and im trying to do simple model that tell you on what side of the canvas you cliked</p> <pre><code>const model = tf.sequential(); model.add( tf.layers.dense({ units: 200, activation: &quot;sigmoid&quot;, inputShape: [0, 1], }) ...
<p>The inputShape is of size 2, therefore, the features (here xtrain and xtest) should be of dimension 3.</p> <p>Additionnally, it does not make sense to have a dimension size to be 0 (that will mean that the tensor is empty).</p> <p>Given your xtrain and xtest shape, <code>[a, b]</code>, the inputShape, should be <cod...
javascript|tensorflow|tensorflow.js
0
6,471
63,515,884
Classify text from a Pandas Series
<p>I have the following dataframe which is built from parsing raw text files into a list and then into the dataframe.</p> <pre><code> Content 0 POLITICS 1 A Renewed Pus...
<h2>Addresses: <em>At some point the pattern changes</em></h2> <ul> <li>Using a list comprehension, find data for each header <ul> <li>The order of list creation matters, <code>time</code>, <code>top</code>, and then <code>head</code>.</li> <li>The <code>time</code> pattern must be consistent with 2 character time zone...
python|pandas
3
6,472
53,458,023
for loop for row wise comparison in pandas
<p>I have following pandas dataframe</p> <pre><code>code tank prod_receipt tank_prod 12345 1 MS MS 23452 2 MS No Data 23333 2 HS HS 14567 3 MS No Data 12343 2 MS MS </code></p...
<p>Dont use loops, because slow, better here is use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a>:</p> <pre><code>m1 = df['tank_prod'] == 'No Data' m2 = df['prod_receipt'] == df['tank_prod'] df['new'] = np.select([m1, m2], ['No ...
python|pandas
4
6,473
71,893,469
Converting a dataframe stringcolumn into multiple columns and rearrange each column based on the labels
<p>I want to convert a stringcolumn with multiple labels into separate columns for each label and rearrange the dataframe that identical labels are in the same column. For e.g.:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Label</th> </tr> </thead> <tbody> <tr> <td>0</td> <td...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df = df.assign(xxx=df.Label.str.split(r&quot;\s*,\s*&quot;)).explode(&quot;xxx&quot;) df[&quot;Col&quot;] = df.groupby(&quot;xxx&quot;).ngroup() df = ( df.set_index([&quot;ID&quot;, &quot;Label&quot;, &quot;Col&quot;]) .unstack(2) .droplevel(0, axi...
python|pandas|dataframe|sorting
1
6,474
55,224,109
Custom upsampling of images with TensorFlow
<p>I have trouble implementing a layer function in TensorFlow. Maybe someone with more experience has an idea how to solve this. The usage of the function should be the following:</p> <p>In: a <code>[B x W x H x 2]</code> tensor called <code>A</code></p> <p>Out: a new tensor called <code>B</code> of size <code>[B x p...
<p>You can do that in a vectorized way (which should be much faster than looping or mapping) like this:</p> <pre><code>import tensorflow as tf import numpy as np def gaussian_upsampling(A, p, q): s = tf.shape(A) B, W, H, C = s[0], s[1], s[2], s[3] # Add two dimensions to A for tiling A_exp = tf.expand...
python|tensorflow
1
6,475
56,519,204
How to compute a moving average of value for the previous date untill the first event?
<p>I have a dataframe with data where the first column is an identification number, ID1, the second is a date, DATE, and the third is some value, VALUE.</p> <pre><code>d = {'ID1': [1,2,3,4,1,2,4,1,3,2,4,1], 'DATE': ['1/06/2016', '1/06/2016','2/06/2016','1/06/2016','3/06/2016', '4/06/2016','2/06/2016','5/06/2016...
<p>I think you are looking for <code>expanding</code></p> <pre><code>s=df.groupby('ID1').VALUE.expanding(min_periods=1).mean().reset_index(level=0,drop=True) df['new']=s </code></pre>
python|pandas|moving-average
1
6,476
66,964,560
How do I calculate percentage change of a timeseries of daily data
<p>I have a daily timeseries of indexdata and want to take yearly pct changes of it. If I use <code>DataFrame.pct_change(periods=...)</code> I will have to define the exact number of days till the same day last year which is not correct as the number of working days differs from year to year. Do anyone have any idea ho...
<p><strong>EDIT</strong>: starting from the good answer from @Pablo C: given OP's definition of the DataFrame, we first need to convert the index to <code>DatetimeIndex</code>, otherwise @Pablo C's answer will throw <code>NotImplementedError: Not supported for type Index</code></p> <pre><code>import pandas as pd list=...
python|pandas|percentage
0
6,477
68,107,160
fill all nan values in a dataframe with values from a column
<p>I have a df like this</p> <pre><code>index a b c 0 0 0 1 1 nan 1 2 2 0 1 3 3 1 nan 4 4 1 0 5 5 nan 0 6 6 nan nan 7 </code></pre> <p>I want to fill the first 2 columns(actually fi...
<p>Just do</p> <pre><code>out = df.fillna(dict.fromkeys(list(df),df.c)) Out[206]: a b c 0 0.0 0.0 1 1 2.0 1.0 2 2 0.0 1.0 3 3 1.0 4.0 4 4 1.0 0.0 5 5 6.0 0.0 6 6 7.0 7.0 7 </code></pre>
python|pandas|dataframe
2
6,478
59,081,876
How to overcome the u200d unicode while reading excel files using pandas
<p>The excel file contains Indian language data. The excel file is being read but while displaying the content it shows \u200d in between. I need to avoid it to do further processing of data. Kindly help.</p>
<p>try this </p> <pre><code>s = 'This is some \u200d text that has to be cleaned\u200d! it\u200d annoying!' s.encode('ascii', 'ignore') output : This is some text that has to be cleaned! it annoying!' </code></pre>
python|pandas|nlp
0
6,479
59,305,007
Compute dataframe columns from a string formula in variables?
<p>I use an excel file in which I determine the names of sensor, and a formula allowing me to create a new &quot;synthetic&quot; sensor based on real sensors. I would like to write the formula as string like for example &quot;y1 + y2 + y3&quot; and not &quot;df ['y1'] + df ['y2'] + df ['y3]&quot; but I don't see which ...
<p>I think pandas.query is what you want. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html</a></p> <p>Example:</p> <pre><code>formula_cell = "y1 + y2 + y3 + ...
python|pandas|dataframe|variables|formula
1
6,480
46,129,407
How to extract a item from list of items in a python dataframe column?
<p>I have a Dataframe like this :</p> <pre><code> Date sdate 0 2012-3-12 [2012, 03, 12] 1 2012-3-25 [2012, 03, 25] 2 2012-4-20 [2012, 04, 20] 3 2012-4-12 [2012, 04, 12] 4 2012-4-26 [2012, 04, 26] </code></pre> <p>I need to extract the year,month and day to separate columns like this </p> <pre><c...
<p>Use <code>apply</code> with <code>pd.Series</code> and <code>rename</code> the columns</p> <pre><code>In [784]: df.sdate.apply(pd.Series).rename(columns={0:'year',1:'month',2:'day'}) Out[784]: year month day 0 2012 3 12 1 2012 3 25 2 2012 4 20 3 2012 4 12 4 2012 4 26 </c...
python|pandas|for-loop|dataframe
2
6,481
46,134,201
How to get original values after using factorize() in Python?
<p>I'm a beginner trying to create a predictive model using Random Forest in Python, using train and test datasets. train["ALLOW/BLOCK"] can take 1 out of 4 expected values (all strings). test["ALLOW/BLOCK"] is what needs to be predicted. </p> <pre><code>y,_ = pd.factorize(train["ALLOW/BLOCK"]) y Out[293]: array([0, ...
<p>First, you need to save the <code>label</code> returned by <code>pd.factorize</code> as follows:</p> <pre><code>y, label = pd.factorize(train["ALLOW/BLOCK"]) </code></pre> <p>And then after you got the numeric predictions, you can extract the corresponding labels by <code>label[pred]</code>:</p> <pre><code>pred =...
python|pandas|random-forest|prediction
7
6,482
45,847,893
Concatenate rows in python dataframe
<p>This question may be very basic, but I would like to concatenate three columns in a pandas DataFrame.<br> I would like to concatenate col1, col2 and col3 into col4. I know in R this could be done with the paste function quite easily.</p> <pre><code>df = pd.DataFrame({'col1': [2012, 2013, 2014], 'col2': 'q', 'col3'...
<p>Use <code>pd.DataFrame.sum</code> with <code>axis=1</code> after converting to strings.<br> I use <code>pd.DataFrame.assign</code> to create a copy with the new column</p> <pre><code>df.assign(col4=df[['col1', 'col2', 'col3']].astype(str).sum(1)) col1 col2 col3 col4 0 2012 q 1 2012q1 1 2013 q ...
python|pandas
4
6,483
51,089,531
Read CSV file with features and labels in the same row in Tensorflow
<p>I have a .csv file with around 5000 rows and 3757 columns. The first 3751 columns of each row are the features and the last 6 columns are the labels. Each row is a set of features-labels pair.</p> <p>I'd like to know if there are built-in functions or any fast ways that I can:</p> <ol> <li>Parse the first 3751 col...
<p>You could look into <code>tf.data.Dataset</code>'s input pipelines (<a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer">LINK</a>). What you basically do is you can read a csv file, possibly batch/shuffle/map it somehow and create an iterator over the dataset. Whenever you e...
python|python-3.x|pandas|tensorflow
2
6,484
51,078,007
Keras array shape error
<p>How come I am getting a shape <code>ValueError</code> for my neural network when what I am passing in is an array of shape <code>(8,1)</code> but the error I am getting is that the neural network is complaining about getting a <code>(1,)</code>?</p> <p>Neural Network:</p> <pre><code>&gt;&gt;&gt; observation_dimens...
<p><code>model.predict</code> takes a batch of samples, if you give it a single sample with the wrong shape, it will interpret the first dimension as the batch one.</p> <p>A simple solution is to add a dimension with a value of one:</p> <pre><code>q_network.predict(obs.reshape(1, 8)) </code></pre>
python|tensorflow|neural-network|keras
2
6,485
51,080,137
Adding missing rows from the another table based on 2 columns
<p>I have a subset of a dataframe like bellow</p> <pre><code>ID var1 var2 var3 111 A 1 1 222 A 1 1 333 A 1 1 444 A 2 1 555 A 2 1 666 A 2 1 </code></pre> <p>and I want to join missing information from dataframe bellow. But only those ID that subset contains var1 and var2</p> ...
<p>Use <code>merge</code></p> <pre><code>In [164]: df2.merge(df1[['var1', 'var2']].drop_duplicates()) Out[164]: ID var1 var2 var3 0 111 A 1 1 1 222 A 1 1 2 333 A 1 1 3 777 A 1 0 4 888 A 1 0 5 444 A 2 1 6 555 A 2 1 7 666 A ...
python|pandas|numpy
1
6,486
66,573,190
how to get correct correlation plot on time series data with matplotlib/seaborn?
<p>I have time-series data that collected weekly basis, where I want to see the correlation of its two columns. to do so, I could able to find a correlation between two columns and want to see how rolling correlation moves each year. my current approach works fine but I need to normalize the two columns before doing ro...
<p>Customizing the legend in esaborn is painstaking, so I created the code in matplotlib.</p> <ol> <li>Corrected the method for calculating the correlation coefficient. Your code gave me an error, so please correct me if I'm wrong.</li> <li>The color of the line graph seems to be the color of the tableau from the desir...
python|pandas|matplotlib|seaborn
1
6,487
66,387,891
Pandas df comparing two dates condition
<p>I'd like to add 1 if <code>date_</code> &gt; <code>buy_date</code> larger than 12 months else 0</p> <p>example df</p> <pre><code>customer_id date_ buy_date 34555 2019-01-01 2017-02-01 24252 2019-01-01 2018-02-10 96477 2019-01-01 2017-02-18 </code></pre> <p>output df</p> <pre>...
<p>Based on what I understand, you can try adding a year to <code>buy_date</code> and then subtract from <code>date_</code> , then check if days are + or -.</p> <pre><code> df['buy_date&gt;_than_12_months'] = ((df['date_'] - (df['buy_date']+pd.offsets.DateOffset(years=1))) ...
python|pandas
4
6,488
66,383,718
How to find column with specific row is zero in pandas
<p>I have pandas dataframe like below.</p> <pre><code> index col_A col_B col_C col_D col_E a 12 15 28 34 23 b 23 37 46 34 92 c 34 32 24 93 12 d 12 0 1 0 0 </code></pre> <p>I want ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> for select index <code>d</code> and then filter by another <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofo...
python|pandas
2
6,489
66,744,172
How to pass the image buffer to Tensorflow JS decodeImage method?
<p>So I have the following code; <code>CLIENT</code></p> <pre><code>const imageData = context.getImageData(0, 0, 320, 180); const buffer = imageData.data.buffer; socket.emit(&quot;signal&quot;, buffer); //Pass it to the server through websocket </code></pre> <p><code>BACKEND</code></p> <pre><code>socket.on(&quot;signal...
<p>The buffer data contains already the decoded image. To get the tensor out of it, here is simply what it takes on the server side:</p> <pre><code>tf.tensor(data).reshape([IMAGE_H, IMAGE_W, -1]); // IMAGE_H is the height of the image, here 180 // IMAGE_W is the width of the image, here 320 </code></pre>
node.js|reactjs|socket.io|tensorflow.js
0
6,490
57,713,794
Pandas rank subset of rows based on condition column
<p>I want to rank the below dataframe by <code>score</code>, only for rows where<code>condition</code> is <code>False</code>. The rest should have a rank of <code>NaN</code>.</p> <pre><code>df=pd.DataFrame(np.array([[34, 65, 12, 98, 5],[False, False, True, False, False]]).T, index=['A', 'B','C','D','E'], columns=['sco...
<p>You can filter by condition column <code>rank</code>:</p> <pre><code>df['new'] = df.loc[~df['condition'].astype(bool), 'score'].rank() print (df) score condition new A 34 0 2.0 B 65 0 3.0 C 12 1 NaN D 98 0 4.0 E 5 0 1.0 </code></pre>
pandas|dataframe|conditional-statements|rank
4
6,491
57,574,467
How to get deviation from a reference value for multindex dataframe
<p>I'm interested in finding deviations from my simulated data from experiment, in a manner similar to the following:</p> <pre><code>my_frame = pd.DataFrame(data={'simulation1':[71,4.8,65,4.7], 'simulation2':[71,4.8,69,4.7], 'simulation3':[70,3.8,68,4.9], ...
<p>Create new DataFrame by subtract column <code>experiment</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>DataFrame.sub</code></a> and then change <code>MultiIndex</code>:</p> <pre><code>df = my_frame.sub(my_frame['experiment'], ...
python|pandas
2
6,492
57,609,350
Can I use a boolean loop to find equal values btw two df cols then set df1['col1'] = df2['col2']
<p>I have to find the values of <code>df2 col1</code> that are equal to <code>df1 col1</code>, then replace <code>df1 col2</code> with <code>df2 col2</code> from the same row. </p> <p>I've already tried <code>.isin()</code> (possibly incorrectly) and multiple conditions i.e. <code>if (df1['col1'] == df2['col1']) &amp;...
<p>Please, if you find a solution without using loops, it is always better. In your case, finding rows that are in an other column can be solved by an inner join. Here is, I hope, a code that can solve your issue.</p> <pre class="lang-py prettyprint-override"><code>In [1]: ## Set the exemple with replicable code impor...
python|pandas|loops|iterator
0
6,493
73,018,028
To check whether female household income is higher than the average male house hold income (using dataframe given)
<p>This is the code that I have done to check whether females' household income is higher than males' average household income.</p> <pre class="lang-py prettyprint-override"><code>#Get total number of female customers df_Female = df[df['Gender']=='Female'] FemaleIncomeArray = df_Female.loc[:,'Income'].values #get femal...
<p>sometimes when you check a condition on series or dataframes, your output is a series such as ( , False). In this case you must use any, all, item,... use print function for your condition to see the series</p>
python|pandas|dataframe
0
6,494
51,528,643
How to unpack multiple dictionary objects inside list within a row of dataframe?
<p>I have a dataframe with the below dictionaries within a single list in every row and per row, the list are different sizes with they are of different sizes as below:</p> <pre><code>ID unnest_column 1 [{'abc': 11, 'def': 1},{'abc': 15, 'def': 1}, {'abc': 16, 'def': 1}, {'abc': 17, 'def': 1}, {...
<p>IIUC, from</p> <pre><code>df = pd.DataFrame() df['x'] = [[{'QuestionId': 11, 'ResponseId': 1},{'QuestionId': 15, 'ResponseId': 1}, {'QuestionId': 16, 'ResponseId': 1}, {'QuestionId': 17, 'ResponseId': 1}, {'QuestionId': 18, 'ResponseId': 1, 'Value': 'abc'}, {'QuestionId': 23, 'DataLabel': 'xxx', 'ResponseId': 1...
python|python-3.x|pandas
3
6,495
36,238,101
Using Pandas to export multiple rows of data to a csv
<p>I have a matching algorithm which links students to projects. It's working, and I have trouble exporting the data to a csv file. It only takes the last value and exports that only, when there are 200 values to be exported. </p> <p>The data that's exported uses each number as a value when I would like to get the who...
<p>You keep overwriting in the loop so you only end up with the last bit of data, you need to append to the csv with <code>df.to_csv('try.csv',mode="a",header=False)</code> or create one df and append to that and write outside the loop, something like:</p> <pre><code>df = pd.DataFrame() for m in M: s = m['student'...
python|csv|pandas
1
6,496
35,814,769
python pandas HDF5Store append new dataframe with long string columns fails
<p>For a given path, i process many GigaBytes of files inside, and yield dataframes for every processed one. For every dataframe that is yield, which includes two string columns of varying size, I want to dump them to disk using the very efficient HDF5 format. The error is raised when the HDFStore.append procedure is c...
<p>Have you seen this post? <a href="https://stackoverflow.com/questions/22710738/pandas-pytable-how-to-specify-min-itemsize-of-the-elements-of-a-multiindex">stackoverflow</a> </p> <pre><code>data_store.append('df',dataframe,min_itemsize={ 'string' : 5761 }) </code></pre> <p>Change 'string' to your type.</p>
python|pandas|hdf5
0
6,497
38,028,762
OutOfRangeError: RandomShuffleQueue
<p>Hi I am trying to run a conv. neural network addapted from MINST2 tutorial in tensorflow. I am having the following error, but i am not sure what is going on:</p> <pre><code>W tensorflow/core/framework/op_kernel.cc:909] Invalid argument: Shape mismatch in tuple component 0. Expected [784], got [6272] W tensorflow/c...
<p>This looks like an issue with your image.set_shape([784]). The error is saying that it was expecting something of size [784] but it got [6272]. I'm semi-familiar with this tutorial and the images should be 28x28 which would give you a size of 784 but maybe there are 6272 images and your dimensions are confused becau...
python|tensorflow|conv-neural-network
0
6,498
31,550,031
ValueError with Pandas - shaped of passed values
<p>I'm trying to use Pandas and PyODBC to pull from a SQL Server View and dump the contents to an excel file.</p> <p>However, I'm getting the error when dumping the data frame (I can print the colums and dataframe content):</p> <pre><code>ValueError: Shape of passed values is (1, 228), indices imply (2, 228) </code><...
<p>To query data from a database, you can better use the built-in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html" rel="nofollow"><code>read_sql_query</code></a> function instead of doing the execute and converting to dataframe manually.<br> For your example, this would give so...
python|pandas|pyodbc
2
6,499
64,509,263
How do I rewrite the following SQL code in Pandas to display the query and not just the headers?
<p>I have a dataset and I am trying to write SQL query into Pandas.</p> <p>The SQL query code is:</p> <pre><code>`SELECT Industry_type, No_of_Employees, Employee_Insurance_Premium, Percent_Female_Employees FROM cdc_new WHERE Industry_type= 'Hospitals' AND Employee_Insurance_Premium='Decreased' ORDER BY Percent_Female_E...
<p>Assuming you have read in the entire table from sql with something like:</p> <pre><code>cdc_new = pd.read_sql(query, conn) </code></pre> <p>You can use the following syntax:</p> <pre><code>df = (cdc_new.loc[(cdc_new['Industry_type'] == 'Hospitals') &amp; (cdc_new['Employee_Insurance_Premium'] == 'D...
python|sql|pandas
1