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 |
|---|---|---|---|---|---|---|
13,700 | 66,307,502 | How can I convert an array inside a python dictionary to a tuple? | <p>I have this dictionary:</p>
<pre><code>{
0: array([-0.16638531, -0.11749843]),
1: array([-0.2318372 , 0.00917023]),
2: array([-0.42934129, -0.0675385 ]),
3: array([-0.63377579, -0.02102854]),
4: array([-0.26648222, -0.42038916]),
5: array([-0.17250316, -0.73490218]),
6: array([-0.4277433... | <p>From this answer <a href="https://stackoverflow.com/a/10016379/14316282">here</a> it looks like for each value in the dictionary you can:</p>
<pre><code>tuple(arr)
</code></pre>
<p>So for the whole dictionary you can probably do something like:</p>
<pre><code> new_dict = {key: tuple(arr) for key, arr in old_dict.ite... | python|arrays|dictionary|tuples|numpy-ndarray | 1 |
13,701 | 52,779,087 | How to create merged rows in pandas to_html | <p>I have below data frame</p>
<pre><code>UK | FOOD | Sales | 4000
UK | FOOD | Order | 6000
US | DRINK | Sales | 4300
US | DRINK | Order | 6600
</code></pre>
<p>I want to_html to merge similar value rows
and output should be as below:</p>
<pre><code>UK | FOOD | Sales | 4000
| Order | 6000
US | DRINK |... | <p>suppose your df looks like this,</p>
<pre><code> A B C D
0 UK FOOD Sales 4000
1 UK FOOD Order 6000
2 US DRINK Sales 4300
3 US DRINK Order 6600
df.loc[df.duplicated(subset=['A','B']),['A','B']]=''
# A B C D
# UK FOOD Sales 4000
# O... | python|html|pandas|dataframe | 0 |
13,702 | 52,503,816 | pandas merge_asof error when using float as key | <p>When using pandas merge_asof as in the following example</p>
<pre><code>import pandas as pd
left = pd.DataFrame({'a': [1.1, 5.5, 10.9], 'left_val': ['a', 'b', 'c']})
right = pd.DataFrame({'a': [1.0, 2.8, 5.4, 5.55, 7.4], 'right_val': [1, 2, 3, 6, 7]})
pd.merge_asof(left, right, on='a', direction='nearest', toler... | <p>Looks like the tolerance parameter is only allowed for integer and timedelta values hence the error, it runs fine without.</p>
<p>Maybe you can fix it with a post-processing step to say:</p>
<pre><code>right["b"] = right["a"]
df_result = pd.merge_asof(left, right, on='a', direction='nearest')
df_result.loc[abs(df_... | python|pandas|merge | 2 |
13,703 | 46,558,114 | How to conditionally combine two numpy arrays of the same shape | <p>This sounds simple, and I think I'm overcomplicating this in my mind.</p>
<p>I want to make an array whose elements are generated from two source arrays of the same shape, depending on which element in the source arrays is greater.</p>
<p>to illustrate:</p>
<pre><code>import numpy as np
array1 = np.array((2,3,0))... | <p>We could use NumPy built-in <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.maximum.html" rel="nofollow noreferrer"><code>np.maximum</code></a>, made exactly for that purpose -</p>
<pre><code>np.maximum(array1, array2)
</code></pre>
<p>Another way would be to use the NumPy ufunc <a href=... | python|arrays|numpy | 20 |
13,704 | 46,217,510 | Better way to identify duplicates in a group in a Pandas dataframe? | <p>I have a dataframe</p>
<pre><code> x c
0 0 1
1 3 2
2 1 1
3 2 1
4 3 1
5 4 1
6 1 0
7 3 1
8 2 1
9 1 2
</code></pre>
<p>I would like to produce</p>
<pre><code> c x duplicated
0 1 0 False
1 2 3 False
2 1 1 False
3 1 2 True
4 1 3 True
5 1 4 False
6 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="noreferrer"><code>duplicated</code></a> only - by default it verify all columns:</p>
<pre><code>d['duplicated'] = d.duplicated(keep=False)
print (d)
x c duplicated
0 0 1 False
1 3 2 False
2... | python|pandas|dataframe | 5 |
13,705 | 58,587,373 | Observing relationship between different variables of a dataframe using pairplot and correlation method | <p>I have taken the Pima diabetes data from Kaggle for manipulating and creating the data. However, I wanted to plot the relationship between two different variable of the dataframe that I have imported the pima data to. I am able to achieve it using the below query. </p>
<pre><code>sns.pairplot(pima_data)
</code></pr... | <p>Are you trying to plot the linear regression on top of each scatter plot?</p>
<pre><code>iris = sns.load_dataset("iris")
g = sns.PairGrid(iris)
g = g.map_diag(plt.hist)
g = g.map_offdiag(sns.regplot)
</code></pre>
<p><a href="https://i.stack.imgur.com/JpTsF.png" rel="nofollow noreferrer"><img src="https://i.stack.... | python|pandas|numpy|seaborn | 0 |
13,706 | 68,901,153 | expected scalar type Long but found Float in PyTorch, using nn.CrossEntropyLoss() | <p>I wanted to make a label torch tensor. I chose two different ways which the first one makes an error in the part of calculating loss with <code>nn.CrossEntropyLoss()</code>. I want to know why this happens, although the tensor results are the same.</p>
<p>The <strong>first</strong> method:</p>
<pre><code>labels = to... | <p>To fix your <strong>first method</strong>, you should change the type by calling <code>labels = labels.long()</code> to transform the data type:</p>
<pre class="lang-py prettyprint-override"><code>labels = torch.hstack((torch.zeros(100),torch.ones(100),1+torch.ones(100)))
labels = labels.long()
</code></pre> | python|deep-learning|pytorch | 0 |
13,707 | 68,940,305 | How to calculate mean square error when eager execution is disabled in TensorFlow? | <p>When calculating MSE using tensorflow, I get the error <em><strong>AttributeError: 'Tensor' object has no attribute 'numpy'</strong></em>
The reason is that I need to disable eager execution (<code>tf.disable_eager_execution()</code>).
Question: How to calculate mean square error when eager execution is disabled in ... | <p>You can't and shouldn't. When eager execution is disabled, the calculations and objects are leaving Python. The goal of this is to train a model with an optimized backend rather than "slow" Python. As a side effect, the objects and values aren't accessible to Python. This is fine when you train a model, wh... | python|tensorflow|keras|tensorflow2.0|mean-square-error | 0 |
13,708 | 69,008,542 | How to find sum of values in a column after mapping from another dataframe? | <p>I have two dataframes as follows:</p>
<pre><code>df1 = pd.DataFrame({'Name': ["cat", "dog", "fish"],
'Set1': ["ad, cd, bd", "bd", "jk, md"],
'Set2': ["kl, kd", "ad, kd", "kd"],
'Set3': ["kd, ad", "jk&... | <p>Create a function that splits each cell, get rid of whitespace, convert the text to numbers via df2, and sum :</p>
<pre><code>def func(val):
# val = map(str.strip, val.split(","))
val = [ent.strip() for ent in val.split(",")]
val = map(mapper.get, val)
return sum(val)
mapper =... | python|pandas|dataframe | 3 |
13,709 | 69,026,189 | Pytorch data pipeline | <p>I am trying to implement a bounded buffer like solution where data generator and the model work as two separate processes. The data generator preprocess the data and stores in a shared queue (with predefined max size to limit the memory usage). The model on the other hand consumes data from this queue at its own pac... | <p>Since you work with pytorch you should use the <a href="https://pytorch.org/tutorials/beginner/basics/data_tutorial.html" rel="nofollow noreferrer">Dataset and Dataloader</a> approach. This handles all problems with multiprocessing, shared memory and so on for you.</p>
<p>You can have <a href="https://pytorch.org/do... | python-3.x|pytorch|multiprocessing | 1 |
13,710 | 69,069,277 | Cannot load tflite model, Did not get operators or tensors in subgraph 1 | <p>I have converted a tf model to tflite, and applied quantization in the process, but I cannot load it. The error was raised when I try to do <code>interpreter = tf.lite.Interpreter(tflite_model_path)</code>, the error message was:</p>
<pre><code>ValueError: Did not get operators or tensors in subgraph 1.
</code></pre... | <p>I figured out the cause in my case. It was because I have dropout layers in my model, and I'm using an input tf.bool tensor to explicitly control the training/inference mode of the dropouts layers. Dropout is not currently supported in tflite, and because I'm explicitly controlling the dropout behaviour, the tflite ... | tensorflow|tensorflow-lite|quantization | 0 |
13,711 | 69,011,496 | 'pandas' has no attribute 'tslib' | <pre><code>df['tick'] = np.where(df.Length < .05, df.index, pd.tslib.NaT)
</code></pre>
<p>AttributeError: module 'pandas' has no attribute 'tslib'
when I run this one it shows me that pandas tslib is not found how can I resolve it</p> | <p>You have to just use <code>pd.NaT</code>:</p>
<pre><code>df['tick'] = np.where(df.Length < .05, df.index, pd.NaT)
</code></pre>
<p>As mentioned in <a href="https://github.com/yhat/ggpy/issues/617" rel="nofollow noreferrer">this</a> GitHub thread:</p>
<blockquote>
<p><code>FutureWarning: pandas.tslib is deprecated... | python|pandas | 1 |
13,712 | 44,695,537 | Inception adding new layers | <p>I want to retrain the inception model with 1003 classes where the first 1000 classes are same as imagenet(inception model). So I took with inception model and extracted the final layer weights and added 3 more columns to it. I popped the final layer created another layer with 1003 classes and with the weights I have... | <p>It sounds like you are trying to do some transfer learning (i.e. using the inception v3 model to classify a different set of images than it was originally trained to do). There is a great tutorial on this subject here
<a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#0" rel="nofollow nor... | tensorflow|pre-trained-model | 0 |
13,713 | 60,937,811 | Exactly match 2 rows in a tensor Tensorflow | <p>I want to calculate accuracy where I want to count number of rows which are exactly equal in 2 equal shaped tensors.</p>
<pre><code>A = [2 1 0
0 1 9
1 3 4]
B = [2 1 1
0 1 9
1 3 4]
Accuracy = 2/3 = 0.67
</code></pre>
<p>How can I do this in TF Ops</p> | <pre><code>import tensorflow as tf
A = [[2, 1, 0],
[0, 1, 9],
[1, 3, 4]]
B = [[2, 1, 1],
[0, 1, 9],
[1, 3, 4]]
x = tf.constant(A)
y = tf.constant(B)
result = tf.math.equal(x, y) # this compares elementwise
print(result.numpy()) # printing it as numpy array
</code></pre>
<p>It prints:</p>
<pre... | tensorflow | 2 |
13,714 | 61,051,153 | matplotlib scatter plot with full year date-time index | <p>I have a pandas series with a datetime index and values from the year 2015.
Not all dates have data, so dropna() was employed to look at attained data.
Part of the data is displayed below, there are roughly 50 dates with observations in the
whole series.</p>
<pre><code> date value
2015-02-09 8.3
2015-0... | <p>Pandas has its own plotting method for this, which is a wrapper for the matplotlib function:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
<name of your series>.plot(xlim=[pd.to_datetime('2015-01-01'),
pd.to_datetime('2015-12-31')])
</code></pre>
<... | python|pandas|matplotlib | 1 |
13,715 | 71,723,155 | Not able to work with Miniconda on Windows 10 | <p>I have been trying to use a Conda Environment and I am working with Python 3.10.2. I want to install Pandas and SciPy through Miniconda. I downloaded it but when I tried running <code>conda install pandas</code> on the command prompt it says that "Conda is not recognised as an internal or an external command, a... | <p>Conda probably wasn't added as a path variable. Locate the conda.exe <a href="https://helpdeskgeek.com/windows-10/add-windows-path-environment-variable/" rel="nofollow noreferrer">add it to the path</a>.</p>
<blockquote>
<p>Can you also suggest an alternate way to download Pandas?</p>
</blockquote>
<p>You could use ... | python|pandas|miniconda | 0 |
13,716 | 71,557,987 | How to consider datetime in outlier detection with pandas rolling in Python | <p>Considering the following dataframe:</p>
<pre><code> Temperature Datetime
1 24.72 2021-01-01 10:00:00
2 25.76 2021-01-01 11:00:00
3 40 2021-01-01 12:00:00
4 25.31 2021-01-01 13:00:00
5 26.21 ... | <p>In my opinion, you should use the datetime capabilities to compute your moving average. Something like computing the average temperature of the n hours around the given time, then compare your current temperature using a threshold.</p>
<p>Something like:</p>
<pre><code>df['Datetime'] = pd.to_datetime(df['Datetime'])... | python|pandas|dataframe | 1 |
13,717 | 69,828,344 | Dropping duplicates in a dataframe while keeping the oldest record | <p>My dataframe looks like this (it says the time format is <code>datetime64[ns, UTC]</code>):</p>
<pre><code>name job feedback question time
a j1 False q1 2021-09-06 09:25:03.659000+00:00
a j1 True q1 2021-09-06 09:35:03.659000+00:00
a j1 ... | <p>Your intuition was correct, you can <code>sort_values</code>:</p>
<pre><code>deduped = (df.sort_values(by='time')
.drop_duplicates(subset=["name", "job", "question"], keep="first")
)
</code></pre>
<p>output:</p>
<pre><code> name job feedback question ... | python|pandas|dataframe | 3 |
13,718 | 69,797,728 | Extract EPSG code from GeoDataFrame.crs result | <p>Let's say I have a <code>GeoDataFrame</code> with a <code>CRS</code> set.</p>
<pre><code>gdf.crs
</code></pre>
<p>gives me</p>
<pre><code><Projected CRS: EPSG:25833>
Name: ETRS89 / UTM zone 33N
Axis Info [cartesian]:
- [east]: Easting (metre)
- [north]: Northing (metre)
Area of Use:
- undefined
Coordinate Oper... | <p><code>.crs</code> returns a pyroj.CRS object. This should get you the EPSG code from the object:</p>
<pre><code>gdf.crs.to_epsg()
</code></pre>
<p><a href="https://pyproj4.github.io/pyproj/stable/api/crs/crs.html#pyproj.crs.CRS.to_epsg" rel="noreferrer">pyproj docs</a></p> | python|geopandas|pyproj | 6 |
13,719 | 72,393,092 | Groupby with max on string dtype and keep all columns | <p>Trying to group by <code>DocumentNo</code> and return the <code>Max</code> of the <code>Concat</code> column. However I want the <code>Revision</code> column (any other columns I add to this df) to be included in final output.</p>
<p>This is an example input:</p>
<pre><code>DocumentNo Revision Conca... | <p>This should works:</p>
<pre><code>df.groupby("DocumentNo").apply(lambda d:d.loc[d["Concat"]==d["Concat"].max()])
</code></pre>
<p>Probably a faster way exists.</p> | python|pandas|dataframe | 0 |
13,720 | 50,498,091 | Plot aggregate groupby Count data in SeaBorn Python? | <p>how to use groupby function in the y-axis? the below code doesn't display what i expect, due to y = df.groupby('column1')['column2'].count()</p>
<pre><code>import seaborn as sns
import pandas as pd
sns.set(style="whitegrid", color_codes=True)
sns.stripplot(x="column1", y = df.groupby('column1')['column2'].count()... | <p>Seaborn just doesn't work that way. In seaborn, you specify the x and y columns as well as the data frame. Seaborn will do the aggregation itself.</p>
<pre><code>import seaborn as sns
sns.striplot('column1', 'column2', data=df)
</code></pre>
<p>For the count, maybe what you need is <code>countplot</code></p>
<pre... | python|pandas|matplotlib | 3 |
13,721 | 50,347,679 | Left join tables (1:n) using Pandas, keeping number of rows the same as left table | <p>How do I left join tables with 1:n relationship, while keeping the number of rows the same as left table and concatenating any duplicate data with a character/string like ';'.</p>
<p><b>Example: </b> <br> Country Table</p>
<pre><code>CountryID Country Area
1 UK 1029
2 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by <code>Series</code> created by <code>groupby</code> + <code>join</code> for new column in <code>df1</code> if performance is important:</p>
<pre><code>df1['Cities'] = df1['Cou... | python|pandas|join|group-by|left-join | 1 |
13,722 | 50,553,000 | proto_text/gen_proto_text_functions.runfiles [for host] failed | <p>command:</p>
<pre><code>bazel build --config=opt --config=cuda //tensorflow/tools/pip_package:build_pip_package --verbose_failures
</code></pre>
<p>Error:</p>
<pre><code>tensorflow/tensorflow/tools/proto_text/BUILD:33:1: Creating runfiles tree bazel-out/host/bin/tensorflow/tools/**proto_text/gen_proto_text_functi... | <p><a href="https://gist.github.com/HawkAaron/575fc12e6598a7a5f93423ee9677847f" rel="nofollow noreferrer">Here is the more evident compiling instructions</a></p>
<p>And if you want to install tf bindings, please refer to <a href="https://gist.github.com/HawkAaron/093f128d4f51b417d7885f839091d41a" rel="nofollow norefer... | tensorflow | 0 |
13,723 | 45,461,921 | Computing daily occurrence for non-numeric column in pandas dataframe | <p>I have the foll. dataframe (hourly time stamp index):</p>
<pre><code> relative_humidity condition fid
2017-08-02 10:00:00 0.49 Chance of a Thunderstorm 1
2017-08-02 11:00:00 0.50 Chance of a Thunderstorm 1
2017-08-02 12:00:00 ... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> with <code>index[0]</code>, because data are sorted and first value is top:</p>
<pre><code>d = {'level_1':'date'}
df1 = df.groupby(['fid', pd.Grouper(freq=... | python|pandas | 2 |
13,724 | 62,574,645 | Compare words and return Pandas DataFrame entry | <p>I am planning to set up a simple function to see if words from a wordlist can be found in a Pandas DataFrame <code>common_words</code>. In case of a match, I would like to return the corresponding DataFrame entry, while the DF has the format <code>life balance 14</code>, <code>long term 9</code>, <code>upper managem... | <p>I may be misunderstanding, but is this because you are only printing the searched term?
So would something similar to the below work better?</p>
<pre><code># Check for matches between wordlist and Pandas dataframe
def wordcheck():
wordlist = ["work balance", "good management", "work life... | python|pandas|dataframe|nlp | 1 |
13,725 | 62,694,035 | How to add missing dates in pandas | <p>I have the following dataframe:</p>
<pre><code>data
Out[120]:
High Low Open Close Volume Adj Close
Date
2018-01-02 12.66 12.50 12.52 12.66 20773300.0 10.842077
2018-01-03 12.80 12.67 12.68 12.76 29765600.0 10.927719
20... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a>, working also if need some custom start and end datimes:</p>
<pre><code>df = df.reindex(pd.date_range(start, end, freq ='D'))
</code></pre>
<p>Or <a href=... | python|pandas|datetime | 4 |
13,726 | 54,318,915 | When using groupby with multiple index columns or index | <p>I have a dataframe like below : </p>
<pre><code>idx=pd.MultiIndex.from_arrays([[1,1,1,2],[1,1,2,2]])
df=pd.DataFrame(columns=idx,index=[1,2,3]).fillna(1)
</code></pre>
<p>Now I want to find the sum base on two levels of the columns , first come into my mind is <code>groupby</code> and <code>sum</code> </p>
<pre><... | <p>I think this has to do with <code>transform</code> is coded to work on columns from a dataframe. Even though you are grouping on rows, transform is still only passing columns to the function.</p>
<pre><code>def f(x):
print(x)
df.groupby(df.columns,axis=1).transform(f)
</code></pre>
<p>Output:</p>
<pre><code... | python|pandas | 1 |
13,727 | 73,775,951 | how do i send emsil csv attachment with python pandas without exporting to csv file ithut using to_csv | <p>I got the below script to work to export to csv file by reading it from mysql table. But I need this csv attachment not to save to local. instead attach it in email and send it</p>
<p>any idea?</p>
<pre><code>import pandas as pd
import pymysql
from sqlalchemy import create_engine
from urllib.parse import quote
impor... | <p>I use StringIO:</p>
<pre><code>from io import StringIO
def create_csv(df: pd.DataFrame) -> str:
with StringIO() as buffer:
df.to_csv(buffer, index=False)
return buffer.getvalue()
</code></pre> | python|mysql|pandas | 0 |
13,728 | 73,806,372 | In python, if ID matches, move row to column while summing specific columns | <p>I have data with Spouses on separate rows, but each spouse shares the same ID. These IDs, in some cases, are on several rows. When IDs match, I need to move the spouse row to a column, so both spouses share one row. I will also then need to sum values.</p>
<p>Input</p>
<pre><code> ID Position Title First Last ... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>m = df.Position.eq("Spouse")
df.loc[m, ["SpTitle", "SpFirst", "SpLast"]] = df.loc[
m, ["Title", "First", "Last"]
].values
df[["Value1", "Value2", "Value3"... | python|pandas|dataframe|group-by | 1 |
13,729 | 71,307,466 | Pandas swap substrings in column names | <p>I try to swap substrings in the column names of a DataFrame</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>K_1[0,0]</th>
<th>K_1[0,1]</th>
<th>K_1[1,20]</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>34</td>
<td>77</td>
</tr>
<tr>
<td>99</td>
<td>42</td>
<td>23</td>
</tr>
</tbody>
</t... | <p>You can use <code>DataFrame.rename</code> with a callable that employs a regular expression.</p>
<pre><code>import re
df = df.rename(lambda c: re.sub('(.*)(\d+),(\d+)(.*)', r'\1\3,\2\4', c), axis=1)
</code></pre> | python|pandas|string|dataframe | 1 |
13,730 | 71,165,693 | How to concatenate columns of dataframes in a dictionary to a new dataframe | <p>I have a dictionary of eight very similar looking dataframes. I'd like to pick the equally named column from all these dataframes and concatenate them into a new dataframe, where the columns get the name of the key to the dataframe which they are from.
In small it looks like this:</p>
<pre><code>d1 = {'DE': [1, 2, 3... | <p>You can first add a technology column to each df and then combine the separate dfs using <code>pd.concat</code> into a single long df. You can then use <code>pd.pivot</code> to make the columns be the technology</p>
<pre><code>d1 = {'DE': [1, 2, 3], 'BE': [3, 4, 5], 'AT': [5, 6, 7]}
df1 = pd.DataFrame(data=d1)
df1['... | pandas|dataframe | 0 |
13,731 | 71,367,672 | insert missing rows in a Dataframe and fill with previous row values for other columns | <p>I have a dataframe with a column named DateTime with datetime values populated every 5 seconds. But few rows are missing which can be identified by seeing time difference between previous and current row. I want to insert the missing rows and populate other column with previous row values.</p>
<p>My Sample dataframe... | <p>An alternative, using an outer join:</p>
<pre class="lang-py prettyprint-override"><code>t = pd.date_range(df.DateTime.min(), df.DateTime.max(), freq="5s", name="DateTime")
pd.merge(pd.DataFrame(t), df, how="outer").ffill()
</code></pre>
<p>Output:</p>
<pre class="lang-py prettyprint-ov... | python|python-3.x|pandas|dataframe | 3 |
13,732 | 52,052,952 | pandas.IntervalIndex.mid for half open IntervalIndex | <p>I have to deal with Series with an half open interval as index, like this one:</p>
<pre><code>import pandas as pd
index = pd.interval_range(5,50,9, closed='left')
values = [8, 8, 14, 4, 6, 12, 8, 3, 2]
s = pd.Series(values, index)
s
</code></pre>
<p><em>output</em>:</p>
<pre><code>[5, 10) 8
[10, 15) 8
... | <p>For an IntervalIndex closed to the left you can use <code>np.floor</code> to get the expected index as follows:</p>
<pre><code>np.floor(index.mid)
</code></pre>
<p>Result:</p>
<pre><code>Float64Index([7.0, 12.0, 17.0, 22.0, 27.0, 32.0, 37.0, 42.0, 47.0], dtype='float64')
</code></pre>
<hr>
<p>For a more general... | python|pandas | 0 |
13,733 | 52,091,625 | unable to parse date in python pandas | <p>I have column date values as below in the dataframe</p>
<pre><code>Jan 2009
Feb 2003
2017-09-01 00:00:00
</code></pre>
<p>but when I use </p>
<pre><code>np.where(df['Date'].astype(str).apply(len) == 8,pd.to_datetime(df['Date'],format="%b %Y"),pd.to_datetime(df['Date']))
</code></pre>
<p>it fails with the below e... | <p>I think there are some datetimes in format <code>YYYYMMDD</code>, so length is <code>8</code> so not matched <code>%b %Y</code>:</p>
<pre><code>print (df)
Date
0 20170901
1 Jan 2009
2 Feb 2003
3 2017-09-01 00:00:00
</code></pre>
<p>For me working only <a href=... | pandas|date | 1 |
13,734 | 52,112,721 | Python Group BY Cumsum | <p>I have this DataFrame :</p>
<pre><code>Value Month
0 1
1 2
8 3
11 4
12 5
17 6
0 7
0 8
0 9
0 10
1 11
2 12
7 1
3 2
1 3
0 4
0 5
</code></pre>
<p>And i want to create new variable "Cumsum" like this : <... | <p>Try:</p>
<pre><code>df['Cumsum'] = df.groupby((df.Month == 1).cumsum())['Value'].cumsum()
print(df)
Value Month Cumsum
0 0 1 0
1 1 2 1
2 8 3 9
3 11 4 20
4 12 5 32
5 17 6 49
6 0 7 49
7 0 8 ... | python|pandas|group-by|cumsum | 2 |
13,735 | 52,300,735 | Pandas: growing a series backwards using growth rate of another series | <p>I have missing data at the start of a DataFrame for one series, and I want to fill those NAs by growing back the series using the growth rate of another.</p>
<pre><code>df = pd.DataFrame({'X':[np.nan, np.nan, np.nan, 6, 6.7, 6.78, 7, 9.1],
'Y':[5.4, 5.7, 5.5, 6.1, 6.5, 6.80, 7.1, 9.12]})
... | <p>You could let</p>
<pre><code>first_non_nan = df.X.isnull().idxmin()
changes = df.Y[:first_non_nan+1].pct_change()
while first_non_nan > 0:
df.X[first_non_nan-1] = df.X[first_non_nan]/(changes[first_non_nan]+1)
first_non_nan -= 1
</code></pre>
<p>Result:</p>
<pre><code>In [48]: df
Out[48]:
X ... | python|pandas | 0 |
13,736 | 60,546,294 | Python, Rearanging a numpy array by column 0 value, signed integers | <p>I've got a folder with a dataset which is poorly sorted, and id like to rearrange the information that I'm pulling from it as I'm reading it. Therefore I am wondering, is there an easy way to sort following input:</p>
<pre><code>[['-10' '10']
['-10' '20']
['-15' '10']
['-15' '20']
['-5' '10']
['-5' '20]
... | <p>How about using pandas dataframe?</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
data = [['5', '10'], ['4', '20']]
dataframe = pd.DataFrame(data).sort_values(by=0) #define by as index
print(dataframe)
#Output:
# 0 1
#1 4 20
#0 5 10
</code></pre> | python|numpy | 0 |
13,737 | 60,350,862 | Fill missing values in pandas dataframe | <p>I have a pandas dataframe with two columns : locationid, geo_loc.
locationid column has missing values.</p>
<p>I want to get the geo_loc value of the missing locationid row,
then search this geo_loc value in geo_loc column and get the loction id.</p>
<pre><code>df1 = pd.DataFrame({'locationid':[111, np.nan, 145, n... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for Series with same size like original filled by aggregate values <code>max</code>:</p>
<pre><code>df1['locationid']=df1.locationid.fillna(... | python|pandas|dataframe|machine-learning|data-science | 2 |
13,738 | 60,421,046 | Counting length of intersection of a list with pandas column of lists | <p>I have a list of unique random integers and a dataframe with a column of lists, like below:</p>
<pre><code>>>> panel
[1, 10, 9, 5, 6]
>>> df
col1
0 [1, 5]
1 [2, 3, 4]
2 [9, 10, 6]
</code></pre>
<p>The output I would like to have is the length of the overlapping between... | <p>Owing to the variable length data per row, we need to iterate (explicitly or implicitly i.e. under the hoods) staying within Python. But, we can optimize to a level where per iteration compute is minimized. Going with that philosophy, here's one with array-assignment and some masking -</p>
<pre><code># l is input l... | python|pandas|numpy|intersection|set-intersection | 3 |
13,739 | 59,792,736 | Checking duplicated when filling SQL Table using SQLAlchemy/Pandas to_SQL | <p>I would like to dump data into my mysql database. If I want to add addtional data, I am using the same cvs file as shown below but extended with the additional line. </p>
<p>If i restart my code the data just gets included again plus the additional line. This means my data doubles plus one. </p>
<p>How can I check... | <p>I solved it in such a way but maybe there is something nicer?</p>
<pre><code>import sqlalchemy as sqlal
import pandas as pd
mysql_engine = sqlal.create_engine('mysql+mysqlconnector://xxx/Test_Schema',poolclass=sqlal.pool.NullPool)
mysql_engine.raw_connection()
if not mysql_engine.dialect.has_table(mysql_engine, ... | python|mysql|pandas|sqlalchemy | 0 |
13,740 | 59,494,970 | Pandas Merge Causing Data to go to Wrong Columns | <p>I have two dataframes:</p>
<p>df1:</p>
<pre><code> ID CODE CD1 CD2
0 11526.0 1A NWZ
1 11527.0 1C NWZ
</code></pre>
<p>df2</p>
<pre><code> CD_Code CID_CODE OC_NME OC_CDE
0 Mal3 11529 6A Main Area
1 Mal2 11526 6B Side Area
<... | <p>What is the column you want to merge on? <code>CID_CODE</code> and <code>ID CODE</code> have all the same value 11526. If you try to append these two dataframes it won´t be able to know how to merge them since there is no condition expecified.</p>
<p>Please explain more clearly what is what you want to merge.</p>
... | python|pandas|dataframe|merge | 0 |
13,741 | 59,561,628 | How to use Pandas mask method on the part of Data Frame | <p>With the data frame constructed as below, but with many more objects (structured as <code>object1</code> columns) I want to remove (replace with <code>np.nan</code>) all values of <code>var1</code>, <code>var2</code>, <code>var3</code> when there are smaller than 0 or greater than 100. </p>
<pre><code>example_df = ... | <p>I think you need replace filtered DataFrame <code>z</code>, because boolean mask is from filtered <code>DataFrame</code>:</p>
<pre><code>print (z.mask((z < 0) | (z > 100)))
object1 object
var1 var2 var1 var2 var3
0 34.405150 40.470001 NaN ... | python|pandas | 2 |
13,742 | 59,669,266 | Concatenate Pandas column name to column value | <p>Is there any efficient way to concatenate Pandas column name to its value. I will like to prefix all my DataFrame values with their column names.</p>
<p>My current method is very slow on a large dataset:</p>
<pre class="lang-py prettyprint-override"><code>
import pandas as pd
# test data
df = pd.read_csv(pd.com... | <p>here is a way without loops:</p>
<pre><code>pd.DataFrame([df.columns]*len(df),columns=df.columns)+"_"+df.astype(str)
</code></pre>
<hr>
<pre><code> date value data
0 date_01/01/2019 value_30 data_data1
1 date_01/01/2019 value_40 data_data2
2 date_02/01/2019 value_20 data_data1
3 ... | python|pandas | 2 |
13,743 | 61,649,484 | Rolling max excluding current observation in Pandas 1.0 | <p>Using Pandas 1.0 I need to generate a rolling max with a window of the previous 3 observations, excluding the current observation. In R this is achieved by</p>
<pre><code>library(tidyverse)
test_df = data.frame(a = 1:5, b = c(40, 37, 60, 45, 40))
test_df <- test_df %>% mutate(
rolling_max=rollapply(b, ... | <p>This seems to do what you need:</p>
<pre><code>test_df.rolling(2, min_periods=1).max()
</code></pre> | python|pandas|rolling-average | 3 |
13,744 | 61,966,045 | dropna ( ) in multi-header dataframe | <p>I created a dataframe using <code>groupby</code> and <code>pd.cut</code> to calculate the mean, std and number of elements inside a bin. I used the <code>agg()</code>and this is the command I used:</p>
<pre><code>df_bin=df.groupby(pd.cut(df.In_X, ranges,include_lowest=True)).agg(['mean', 'std','size'])
</code></pre... | <p>Let us try pull all the <code>mean</code> out, find the null </p>
<pre><code>df_bin=df_bin_temp[df_bin_temp.loc[:,pd.IndexSlice[:,'mean']].notnull().all(1)]
X Y
m s i m s i
0 10.425 NaN 1 0.003786 NaN 1
</code></pre>
<p>Or we do </p>
<pre><code>df_bin=df_bin... | python|pandas | 1 |
13,745 | 58,072,120 | Entering List Values in Pandas Columns | <p>Given a list as follows:</p>
<pre><code>l = [['43.195', '-22.17', '-43.17', '-22.198', '-43.198', '22.197'], ['43.196', '-22.14', '-43.179', '-22.188', '-43.188', '22.192']]
</code></pre>
<p>I need to add the values from this list to two separate columns of a dataframe. Example: Values where sublist indices of l a... | <p>This will using <code>reshape</code> </p>
<pre><code>pd.concat([pd.Series([x[::2],x[1::2]]).str.join(sep=',') for x in l],1).T
Out[280]:
0 1
0 43.195,-43.17,-43.198 -22.17,-22.198,22.197
1 43.196,-43.179,-43.188 -22.14,-22.188,22.192
</code></pre> | python|pandas | 1 |
13,746 | 55,037,810 | TensorFlow: Sample Integers from Gumbel Softmax | <p>I am implementing a program to sample integers from a categorical distribution, where each integer is associated with a probability. I need to ensure that this program is differentiable, so that back propagation can be applied. I found <code>tf.contrib.distributions.RelaxedOneHotCategorical</code> which is very clos... | <p>You can do a dot product of the relaxed one hot vector with a vector of <code>[1 2 3 4 ... n]</code>. The result is going to give you the desired scalar.</p>
<p>For instance if your one hot vector is <code>[0 0 0 1]</code>, then <code>dot([0 0 0 1],[1 2 3 4])</code> will give you 4 which is what you are looking for... | python|tensorflow|tensorflow-probability | 0 |
13,747 | 54,981,462 | Converting Keras model as tensorflow model gives me error | <p>Hi I am trying to save my 'saved models' (h5 files) as tensorflow file.This is the code I used.</p>
<pre><code>import tensorflow as tf
def tensor_function(i):
tf.keras.backend.set_learning_phase(0) # Ignore dropout at inference
model = tf.keras.models.load_model('/home/ram/Downloads/AutoEncoderModels_ch2/1... | <p>For me the following two options work:</p>
<p><strong>Option 1:</strong> Add <code>tf.keras.backend.clear_session()</code> at the beginning of your <code>tensor_function</code> and use a 'with' block:</p>
<pre><code>def tensor_function(i):
tf.keras.backend.clear_session()
tf.keras.backend.set_learning_phas... | python|tensorflow|keras | 4 |
13,748 | 54,752,271 | Plots getting replaced instead of showing a new plot | <p>I am trying to create multiple plots in my Jupyter notebook. However, when I create one, it replaces the one before it instead of creating a brand new graph. Ex.</p>
<pre><code>#plotting revenue_adj vs vote_average data
df.plot.scatter(x='revenue_adj',y='vote_average',s=.5,title='Average Movie Vote per Budget',figs... | <p>Remember, the plotting functions of pandas use actually matplotlib.</p>
<p>So you can use matplotlib figure() or subplots() functions to create new figures:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure()
df.plot.scatter()
fig = plt.figure()
df.plot.scatter()
# | or using subplots()
fig, ax = ... | pandas|jupyter-notebook | 1 |
13,749 | 54,877,126 | How to Convert Detected Object to COCO dataset Json | <p>I follow Object Detection Demo in <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb</a>:</p>
<pre><code># Actual det... | <p>This is what you are looking for. The last code snippet:</p>
<p><a href="https://lijiancheng0614.github.io/2017/08/22/2017_08_22_TensorFlow-Object-Detection-API/" rel="nofollow noreferrer">https://lijiancheng0614.github.io/2017/08/22/2017_08_22_TensorFlow-Object-Detection-API/</a></p> | json|python-3.x|tensorflow|object-detection-api | 0 |
13,750 | 73,354,810 | Pandas: How to alter entry in current row dependant on selection of all rows up to current row | <p>Trying to learn pandas using English football scores.</p>
<p>Here is part of a list of football matches in date order.
"FTR" is the Full Time Result: "A" - win for the away team, "H" - win for the home team, "D"- a draw.</p>
<p>I created columns "HTWTD" - home team w... | <p>IIUC, you can use <code>.eq()</code> to return a boolean series of True or False for the condition and then use <code>.cumsum()</code> to cumulatively get the sum of the <code>True</code> values per <code>HomeTeam</code> and <code>AwayTeam</code> group result with a <code>.groupby</code>:</p>
<pre><code>df['home_win... | pandas | 0 |
13,751 | 67,332,196 | Why storing results of a 'for loop' doesn't work? | <p>I have two dataframes:</p>
<pre><code>daily = pd.DataFrame({'Date': pd.date_range(start="2021-01-01",end="2021-04-29")})
pc21 = pd.DataFrame({'Date': ["21-01-2021", "11-03-2021", "22-04-2021"]})
pc21['Date'] = pd.to_datetime(pc21['Date'])
</code></pre>
<p>what I wan... | <p>Don't go for that much complex code just write this one liner code.</p>
<pre><code>daily["Daily"]= daily.Date.isin(pc21.Date).astype(int)
</code></pre> | python|pandas|dataframe|for-loop | 1 |
13,752 | 67,574,792 | How to create a column name dynamically? when we groupby and sum multiple columns? | <p>I am trying to dynamically create a column name with some suffix added. I can do it in for loop but I think it will be inefficient. Is there a way to do it dynamically instead.</p>
<pre><code>from pandas import Timestamp
import pandas as pd
df = pd.DataFrame({'B': range(1,6),'A':['A','A','A','B','B'],'D':[2,3,4,5,6]... | <p>We can group and calculate rolling sum on multiple columns in on go by passing the list of column names on which to calculate rolling sum, then assign the calculated rolling sum to the columns inside a dataframe after adding the required prefix</p>
<pre><code>c = pd.Index(['B', 'D'])
df[c + '_2days'] = df.groupby('A... | python|pandas|dataframe | 6 |
13,753 | 67,264,876 | how to fill rows with help of index pandas? | <p><strong>how to fill rows with help of index pandas?</strong></p>
<p>I have dataframe like</p>
<pre><code> Alert number Age Job Loan
0 0 58 4 0
2 2 44 9 0
4 4 35 4 0
6 6 41 0 0
8 8 29 0 0
</code></pre>
<p>I have ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with sorting by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</cod... | python|pandas|dataframe|indexing|sklearn-pandas | 0 |
13,754 | 60,261,724 | Python MultiLevel Index on DataFrame. Access first row of first index level to apply function | <p>I have a multi-level index dataframe. Level 1 index contains a unique key, level 2 index contains a date for the level 1 index.</p>
<p>Code:</p>
<pre><code>import pandas as pd
from dateutil.relativedelta import relativedelta
from datetime import datetime
fake_data=pd.DataFrame([(x,pd.to_datetime('04/01/2020')+re... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.get_level_values.html" rel="nofollow noreferrer"><code>MultiIndex.get_level_values</code></a> for extract second level and add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.quarter.html"... | python|pandas|dataframe|indexing | 2 |
13,755 | 65,242,255 | Doing rather complicated calculations on each group after groupby | <p>I have a dataframe like</p>
<pre><code>import pandas as pd
A = ['x' , 'x', 'y', 'y', 'y']
B = [1, 3, 2, 1, 4]
C = [2, 3, 7, 2, 1]
df = pd.DataFrame({'A' : A, 'B' : B, 'C' : C })
df
</code></pre>
<p>and unfortunately I couldn't do this calculation on each group after <code>df.groupby(['A'])</code>: multiply <code>B</... | <p>You can do an <code>apply</code>:</p>
<pre><code>df.groupby('A').apply(lambda x: (x['B']*x['C']).sum()/x['B'].sum())
</code></pre>
<p>Or similarly:</p>
<pre><code>df.groupby('A').apply(lambda x: np.average(x['C'],weights=x['B']) )
</code></pre>
<p>Output:</p>
<pre><code>A
x 2.750000
y 2.857143
dtype: float64
<... | python|pandas|dataframe | 2 |
13,756 | 50,075,175 | on Keras with Tensorflow backend, fitting a LSTM and some dense layers in parallel on different fractions of input | <p>I am working on a regression forecast where I have some complex 3D sequences and some features explaining some key characteristics of the sequences. They are held on two matrices of such shapes:</p>
<pre><code>X1.shape, X2.shape
((9000, 300, 3), (9000, 106))
</code></pre>
<p>I want to feed them to a Model instance... | <p>I think this should work </p>
<pre><code># First input
input1=Input(shape=(300,3))
x=LSTM(50, return_sequences=True)(input1)
x=GlobalMaxPool1D(x)
x=Dense(n)(x)
# Second Input
input2=Input(shape=(106))
y=Dense(n)(input2)
# Merge
merged=Concatenate([x,y])
merged=Dense(1)(merged)
# Define model with two inputs
mode... | python|tensorflow|merge|keras|lstm | 2 |
13,757 | 49,832,444 | Pandas data frame logic implementation | <p>I have a dataset having columns:</p>
<pre><code> `subscribe_date` `package_id` `subscription_name` `user_id` `subscription_status`
</code></pre>
<p>subscription_status has values <strong>cancelled</strong>, <strong>active</strong>, <strong>lapsed</strong>, <strong>expired</strong>, <strong>revoked</strong>,... | <p>You can group the rows by <code>user_id</code>, check whether each row of <code>churn</code> is equal to <code>"yes"</code>, transform all the rows of that group accordingly:</p>
<pre><code>import numpy as np
df.churn = np.where(df.groupby('user_id')['churn'].transform( \
lambda x: (x == 'yes').any()), 'yes', d... | python-3.x|pandas | 1 |
13,758 | 49,964,702 | python: Initial condition in solving differential equation | <p>I want to solve this differential equation:
y′′+2y′+2y=cos(2x) with initial conditions:</p>
<ol>
<li><p>y(1)=2,y′(2)=0.5</p></li>
<li><p>y′(1)=1,y′(2)=0.8</p></li>
<li><p>y(1)=0,y(2)=1</p></li>
</ol>
<p>and it's code is:</p>
<pre><code>import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot... | <p>Your initial conditions are not, as they give values at two different points. These are all boundary conditions.</p>
<pre class="lang-py prettyprint-override"><code>def bc1(u1,u2): return [u1[0]-2.0,u2[1]-0.5]
def bc2(u1,u2): return [u1[1]-1.0,u2[1]-0.8]
def bc3(u1,u2): return [u1[0]-0.0,u2[0]-1.0]
</code></pre>
<p>... | python|numpy|scipy|differential-equations | 8 |
13,759 | 63,919,085 | Remove special characters and substrings from strings in column | <p>I am fairly new to all of this. I am using Python and the pandas library to work with a large dataset that looks like this e.g.:</p>
<pre><code> date text
0 Jul 31 2020 "test sentence numerouno"
1 Jul 31 2020 (second sentence) unonumero
2 Jul 31 2020... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>str.replace</code></a> with the following pattern:</p>
<pre><code>df['text'] = df['text'].str.replace(r'[^ A-Za-z]+|uno','')
print(df.text)
0 test sentence numero
1 ... | python|pandas|substring | 1 |
13,760 | 63,922,074 | Return a matching value from 2 dataframes (1 dataframe with single value in cell, 1 with a list in a cell) into 1 dataframe | <p>I have 2 dataframes:</p>
<pre><code>df1
ID Type
2456-AA Coolant
2457-AA Elec
df2
ID Task
[2456-AA, 5656-BB] Check AC
[2456-AA, 2457-AA] Check Equip.
</code></pre>
<p>I'm trying return the matched ID's 'Type' from df1 to df2. With the result looking something... | <p>Use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>to_dict</code></a> of pandas to convert <code>df1</code> to a dictionary, so we can efficiently translate <code>id</code> to <code>type</code>.</p>
<p>Then, apply lamda that for ... | python|pandas|dataframe | 1 |
13,761 | 64,076,939 | slicing a dataframe via the startswith method | <p>Input:</p>
<pre><code>df = pd.DataFrame({'A':['jfgh',23,'START',34,42,56], 'B':['cvb',7,'rtwf',65,87,23]})
</code></pre>
<p>Output:</p>
<pre><code> A B
0 jfgh cvb
1 23 7
2 START rtwf
3 34 65
4 42 87
5 56 23
</code></pre>
<p>I would like to automatically extract the slice ... | <p>Change this:</p>
<pre><code>if df['A'].startswith('START'):
</code></pre>
<p>to this:</p>
<pre><code>if str(df.loc[index,'A']).startswith('START'):
</code></pre>
<p><strong>Full code:</strong></p>
<pre><code>for index in range(len(df)):
if str(df.loc[index,'A']).startswith('START'):
df1 = df[index+1:len(... | python|pandas | 1 |
13,762 | 63,861,230 | Pandas accumulate time consecutively as long as condition is true | <p>Whish to have time duration/accumulation of time diff as long as "state" == 1 is active and else 'off'</p>
<pre><code> timestamp state
2020-01-01 00:00:00 0
2020-01-01 00:00:01 0
2020-01-01 00:00:02 0
2020-01-01 00:00:03 1
2020-01-01 00:00:04 1
2020-01-01 00:00:05 1
2... | <p>You can check with <code>groupby</code> with <code>cumsum</code> for the additional groupkey</p>
<pre><code>g = df.loc[df['state'].ne(0)].groupby(df['state'].eq(0).cumsum())['timestamp']
s1 = g.diff().dt.total_seconds()
s2 = g.apply(lambda x : x.diff().dt.total_seconds().cumsum())
df['tdiff'] = 'off'
df.loc[df['stat... | python|pandas|performance|numpy|time-series | 2 |
13,763 | 63,750,600 | how to create a function using python with dataframe to drop NaN values on a dynamic column name? | <p>i want to create function to drop NaN values but i need this function to be dynamic means that the end user can select the required column name and not being pre selected column.</p>
<p>Header names:</p>
<pre><code>['event_type', 'date', 'event_city','event_mouhafaza', 'number_person', 'groups']
</code></pre>
<h1>th... | <p>You can take from user the pandas column name that he/she wants to drop <code>NAs</code> from. As in code I can see that is in <code>self.drop_nan_value</code>...so just modify your <code>drop_nan</code> function as below -</p>
<pre class="lang-py prettyprint-override"><code>def drop_nan(self):
self.df = self.df... | python|pandas|qlistwidget | 0 |
13,764 | 46,665,530 | rowbind elements of list into pandas data frame by grouping | <p>I'm wondering what is the pythonic way of achieving the following:
Given a list of list:</p>
<pre><code>l = [[1, 2],[3, 4],[5, 6],[7, 8]]
</code></pre>
<p>I would like to create a list of pandas data frames where the first pandas data frame is a row bind of the first two elements in <code>l</code> and the second a... | <p>You could store them in <code>dict</code> like</p>
<pre><code>In [586]: s = pd.Series(l)
In [587]: k = 2
In [588]: df = {k:pd.DataFrame(g.values.tolist()) for k, g in s.groupby(s.index//k)}
In [589]: df[0]
Out[589]:
0 1
0 1 2
1 3 4
In [590]: df[1]
Out[590]:
0 1
0 5 6
1 7 8
</code></pre> | python|pandas | 2 |
13,765 | 46,761,892 | Replacing values in numpy ndarray | <p>I have a very large list of lists containing numpy ndarrays where I need to map letters to an integer value.</p>
<p>This is along the lines of what I was thinking might work, but it doesn't seem to catch all arrays. </p>
<pre><code>import numpy as np
x = [np.array(['a','b','c']),np.array(['d','e']),np.array(['a',... | <p>You can try this:</p>
<pre><code>x = [np.array(['a','b','c'], dtype="<U4"),np.array(['d','e'], dtype="<U4"),np.array(['a','e'], dtype="<U4")]
dict_x = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e':5}
for i in x:
i[ i == 'a'] = dict_x.get('a')
x = array(['1', 'b', 'c'],
dtype='<U1'), array(['d', 'e'],... | python|arrays|numpy|dictionary | 1 |
13,766 | 63,229,218 | Wrong predictions after converting from official tf2_image_retraining.ipynb to tfjs_graph_model? | <p>I have used <a href="https://github.com/tensorflow/hub/tree/master/tensorflow_hub/tools/make_image_classifier" rel="nofollow noreferrer">make_image_classifier</a> to make my own classifier and converted that to Tensorflow.js with success, giving me confidence rates like A: 0.67XXX, B: 0.10XXX, C: 0.23XXXX (together ... | <p>There is a newer version of the TF Hub model available: <a href="https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/5" rel="nofollow noreferrer">https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/5</a>. It might be worth a try to see if using it fixes the issue.</p> | tensorflow|tensorflow.js|tensorflow-hub | 1 |
13,767 | 63,130,257 | How to make mask for variable length sequences, which are then padded, in tensorflow2 for RNN | <p>Trying implement a mask for a sequence of timeperiods, with zero-padding, to an LSTM network.
Each sequence of timeperiods is of varying length, hence requiring padding & masking.
I am trying to model sequences of length 96(timeperiods), and features=33. Simplified data (7 timeperiods and 3 features) are shown:<... | <p>Have possibly resolved this. Problem lies in how I am building the array of sequences.
Each of my sequences consists of:
[array([1,2,3]),array([2,3,4]), array([4,5,6]), array([0,0,0]), , array([0,0,0]), , array([0,0,0]),, array([0,0,0])]
a list of arrays...</p>
<p>when it should be a single array, like:
array([[1,2,... | tensorflow|padding|recurrent-neural-network|masking | 0 |
13,768 | 62,957,350 | Split column with separator | <pre><code>| A | B
| a;b;c | 1;2;3
| a;b;c;d | 1
</code></pre>
<p>In order to split the column , I am using</p>
<pre><code>new = df["A"].str.split(";", n=5, expand=True).
df['A1'] = new[0]
df['A2'] = new[1]
df['A3'] = new[2]
df['A4'] = new[3]
df.drop(columns=["A"]... | <p>There's no need to specify the number of splits as it will by default split on every instance of the separator. The result will be be a DataFrame where the columns are a RangeIndex, so add the column as a prefix. Loop over each Series (as it's Series.str.split) and then <code>concat</code> to join the results.</p>
<... | python|pandas|split | 4 |
13,769 | 68,014,463 | Pandas : Finding correct time window | <p>I have a pandas dataframe which gets updated every hour with latest hourly data. I have to filter out IDs based upon a threshold, i.e. PR_Rate > 50 and CNT_12571 < 30 for 3 consecutive hours from a lookback period of 5 hours. I was using the below statements to accomplish this:</p>
<pre><code>df_thld=df[(df['... | <p>Please excuse me, if I have misinterpreted your problem. As I understand the issues you have a dataframe which is updated hourly. An example of this dataframe is illustrated below as <strong>df</strong>. From this dataframe, you want to filter only those rows which satisfy the following two conditions:</p>
<ol>
<l... | python-3.x|pandas|dataframe|datetime | 0 |
13,770 | 67,863,567 | selecting subsets of data in Pandas | <p>I have a data set containing 5 rows × 1317 columns. attached you can se how the data set looks like. The header contains numbers which are wavelengths. However I only want to select the columns from a specific range of wavelength.
The wavelengths numbers which I am interested are stored in an array (c) with the size... | <p>If your array <code>c</code> only has values that are also a column heading (that is, <code>c</code> doesn't have any additional values), you may be able to just make it a list and use <code>df[c]</code>, where <code>c</code> is that list.</p>
<p>For example, with what is shown in your current picture, you could do:... | python|pandas|dataframe|header | 0 |
13,771 | 67,884,912 | Concatenating/merging files vertically in pandas | <p>I can concatenate all the files in a directory with NumPy vertical stack. But it takes a long time compared to pandas (~30 seconds to merge while pandas consume only ~3 seconds to merge)</p>
<pre><code>import numpy as np
from glob import glob
files = sorted(glob('ILU-545*.txt'))
print(files)
array = np.loadtxt(f... | <p>Ok, Here is a blended way to stack vertically the files and finally the output is numpy array. It is
import os
import time
import glob
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
path = "C:/Users/sys/PycharmProjects/test1"
start = time.time()</p>
<pre><code>allFiles = glob.glob(o... | python-3.x|pandas|list|time-series|numpy-ndarray | 0 |
13,772 | 61,542,899 | How to generate a dataframe (to later be exported to a CSV) in Pandas using a list of regex results? | <p>I am constructing a script that utilizes regex to search through a document I wrote and pull out the name, address, and description for businesses in the document. From there I am trying to setup a dataframe in Pandas using a dictionary with 'Name', 'Address', and 'Description' as keys while the results from the r... | <p>You need to add to the loop an append method, like that:</p>
<pre><code>df = df.append(pd.DataFrame([[Name,Age,Address,Qualification]], columns=df.columns))
</code></pre>
<p>This code will append the new line to the end of the df</p> | python|pandas | 0 |
13,773 | 61,386,594 | Memory used by numpy arrays larger than RAM? | <p>I have read very large tdms files containing sensor data into lists of numpy arrays. The structure is the following:
The data from several files is stored in instances of an object called file_data. The object has properties for each sensor type which are basically lists of numpy arrays (one for each single sensor o... | <p>I guess you use <a href="https://nptdms.readthedocs.io/en/stable/reading.html" rel="nofollow noreferrer">npTDMS</a>.</p>
<p>The used <code>numpy.array</code> type is not just a simple array where all array elements are always stored in memory.
While the data type and number of elements is known (by reading meta dat... | python|numpy|ram|labview | 0 |
13,774 | 68,761,654 | Replacing NONE with Nan - but it Reappears in Subsequent Output of Code | <p>I am trying to replace None (not recognized as a string) with nan -- and fill those nans with the mode of the field, but when I further condense the field -- None appears back in the output. What am I missing?</p>
<pre><code>final_df.Current_Housing_Living_Status__c.unique()
Ouput: array([nan, 'Living with family'... | <p>Inside your <code>reduce_housing_status</code> function you forgot to add a return statement when <code>x in Homeless</code>:</p>
<pre><code>elif x in Homeless:
'Homeless'
</code></pre>
<p>Which means you're implicitly returning <code>None</code></p> | python|pandas|dataframe | 1 |
13,775 | 68,700,558 | raise ValueError("name for name_scope must be a string." | <p>I have defined doubled conv layers in Keras, to use it as a reference in the Unet architecture, like this:</p>
<pre><code>class ConvBlock(keras.Model):
def __init__(self,in_channels):
super(ConvBlock,self).__init__()
self.in_channels = in_channels
self.conv = keras.Sequential(
layers.Conv2D(fil... | <p><code>tf.keras.keras.Sequential</code> takes list of layers, please try the following:</p>
<pre><code> self.conv = keras.Sequential([
layers.Conv2D(filters=self.in_channels,kernel_size=(3,3),strides=(1,1),padding="same",use_bias=False),
layers.Conv2D(filters=self.in_channels,kernel_s... | python|tensorflow | 0 |
13,776 | 52,978,829 | Change value of a randomly chosen entry of a sparse matrix row | <p><code>vec</code> is one row of a sparse matrix.</p>
<pre><code>vec = sparse.csc_matrix([[0,0,1,1,0,1,0,1]])
</code></pre>
<p>How can I randomly choose 2 entries with value '1' and change its value to 8?</p>
<p>I have tried </p>
<pre><code>a,b,c = sparse.find(vec==1)
idx = numpy.random.choice(vec[a,b],2)
vec[idx]... | <p>This converts your sparse row to a boolean mask for your operations.</p>
<pre><code>ones = np.stack(np.where((vec==1).toarray())).T # [[i,j],[i,j]..]
chosen = np.random.choice(len(ones), 2) # [1,3]
for index in chosen:
vec[tuple(ones[index])] = 8
</code></pre>
<p>Since this is by row I think you'll not run int... | python|numpy | 0 |
13,777 | 65,848,682 | Error: nothing to repeat when counting occurences in dataframe | <p>I try to count the occurences of each emoji (in the emoji library) in my dataframe.
My approach:</p>
<pre><code>emoji_cnt = [[] for i in range(len(list(emoji.UNICODE_EMOJI.keys())))]
j = 0
for key, value in emoji.UNICODE_EMOJI.items():
emoji_cnt[j].append(key)
j = j+1
for k in emoji_cnt:
s = df["... | <p>So found a way.
I had to use thge module for regular expressions.
so:</p>
<pre><code>import re
.
.
.
emoji_cnt = [[] for i in range(len(list(emoji.UNICODE_EMOJI.keys())))]
j = 0
for key, value in emoji.UNICODE_EMOJI.items():
emoji_cnt[j].append(key)
j = j+1
for k in emoji_cnt:
s = df["Message&quo... | python|pandas|dataframe|spyder|python-3.8 | 0 |
13,778 | 65,626,845 | How subtract value of one column based on another column, grouped by other columns? | <p>I would like to get difference between two values (newest minus oldest) grouped by ISIN and variable. For example,
for variable <code>a</code> and <code>b</code> I should get -1 and for variable <code>c</code> I should get 11.</p>
<pre><code> check = pd.DataFrame({
'date':[1,2,1,2,1,2],
'ISIN':[1,1... | <p>I think the following should do the trick:</p>
<pre><code>import pandas as pd
check = pd.DataFrame({
'date': [1,2,1,2,1,2],
'ISIN': [1,1,2,2,3,3],
'variable': ['a','a','b','b','c','c'],
'value': [8,9,8,9,21,10]
})
result = check.groupby(['ISIN', 'variable'])['date'].apply(
lambda x: check.l... | python|python-3.x|pandas|pandas-groupby | 0 |
13,779 | 63,457,531 | Different output with equal input for python program when using iminuit: undefined behavior? | <p>I encountered this wiered bugs that the iminuit cannot converge on a naive linear model. However, the real problem is, if I uncomment the line "#bins = np.linspace(0,4,25)", the result of the program is different, and it can converge.</p>
<p>If "same input" does not produce "same output"... | <p>The bug is solved. Although it <strong>looks</strong> the same using <code>print</code>, the types are different:</p>
<pre class="lang-py prettyprint-override"><code>data = pd.read_feather('test.feather').rho2.to_numpy()
N,bins = np.histogram(data,bins=24,range=(0,4))
</code></pre>
<p>vs</p>
<pre class="lang-py pret... | python|pandas|iminuit | 0 |
13,780 | 63,466,024 | Pandas - Comparing two Dataframes and finding rows that have changed | <p>I have two snapshots of a Dataframe taken at different time. I am trying to find rows that are different in these two Dataframes. Technically any row can change.</p>
<p>Snapshot 1:</p>
<pre><code>prod_id, prod_name, sale, price_per_unit
prod_a, prod_name_a, 10, 20
prod_b, prod_name_b, 4, 3
prod_c, prod_name_c, 3, 10... | <p>You can compare all values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ne.html" rel="nofollow noreferrer"><code>DataFrame.ne</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html" rel="nofollow noreferrer"><code>DataFram... | pandas | 1 |
13,781 | 63,407,280 | Find columns with a specific word out of a list | <p>I have a data frame in this format :</p>
<p><strong>Id comments</strong></p>
<pre><code>23 triangles are not perfect
43 angles are present
50 available together
56 get them added
</code></pre>
<hr />
<p>I want to extract columns which contain only the words 'angles' and 'get'</p>
<p>Expected Output:</p>
<p><str... | <p>Use word boundaries by <code>\b\b</code> for get only exact matches with <code>|</code> for regex or:</p>
<pre><code>L = ['angles','get']
pat = '|'.join(r"\b{}\b".format(x) for x in L)
df_comments = df_comments[df_comments['comments'].str.contains(pat)]
print (df_comments)
Id comments
1 43 ... | python|python-3.x|pandas | 2 |
13,782 | 53,414,065 | Error: float() argument must be a string or a number, not 'Polygon' when trying to find points in polygons | <p>I have a list of named polygons:</p>
<pre><code>import pandas as pd
import geopandas as gp
from shapely.geometry import Polygon
from shapely.geometry import Point
import matplotlib.path as mpltPath
df = gp.GeoDataFrame([['a', Polygon([(1, 0), (1, 1), (2,2), (1,2)])],
['b', Polygon([(1, 1), (2,2... | <p>I didn't get the "true/false column", but this should do the job:</p>
<pre><code>points.apply(lambda row: (row['id'], list(map(lambda e: e[0], list(filter(lambda p: p[1].contains(row['geometry']), df.values))))), axis=1)
</code></pre>
<p>For each point you get the polygons that contains it, output:</p>
<pre><code... | python|python-3.x|pandas|matplotlib | 1 |
13,783 | 53,426,787 | How to replace a float value with NaN in pandas? | <p>I'm aware about the replace function in pandas: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html</a></p>
<p>But I've done this simple test and it is not workin... | <p>Problem is float precision, so use function <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html" rel="nofollow noreferrer"><code>numpy.isclose</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>mask</... | python|pandas|replace|nan | 6 |
13,784 | 67,101,743 | numpy select question multiple conditions | <p>I'm looking for a way to code a numpy select statement that does the same as an SQL case statement. I have a dataframe name df1 with the following columns:
up1, up2, sc1, sc2, st1, st2</p>
<p>My SQL script would look like:
CASE sc1
when "UP_MJB" then st1
when "UP_MSCI" then st2
else "&quo... | <p>Let's assume df be the pandas dataframe that has your data</p>
<pre><code>conds = [(df['sc1']=='UP_MJB'),(df['sc1']=='UP_MSCI')]
actions = [df['st1'],df['st2']]
df['new_col'] = np.select(conds,actions,default=df['sc1'])
</code></pre>
<p><code>default</code> parameter is used if none of the case is satisfied. In thi... | numpy | 0 |
13,785 | 67,039,036 | Changing category names in a pandas data frame | <p>I was wondering if there was any way to change the category names in a pandas dataframe, I tried to use the <code>labels.rename_categories({'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'})</code> but that didn't work unfortunately.</p>... | <h3>TL;DR</h3>
<ol>
<li><p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.cat.rename_categories.html" rel="nofollow noreferrer"><code>Series.cat.rename_categories</code></a> for <strong>categorical</strong> variables.</p>
</li>
<li><p>Use <a href="https://pandas.pydata.org/docs/reference/api/pa... | python|pandas|rename|categories | 7 |
13,786 | 47,531,584 | NumPy where as range indices | <p>I have a numpy array like that:</p>
<pre><code>a = numpy.array([1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0])
</code></pre>
<p>The goal is to find the ranges of zeros and ones, start and end indices. I want to use this ranges in another numpy array which contains time stamps to find out how much time each zero phase takes.... | <p>Here's one approach -</p>
<pre><code>def start_stop(a, val=0):
n = np.concatenate(([False], a==val,[False]))
idx = np.flatnonzero(np.diff(n))
# or idx = np.flatnonzero(n[1:] != n[:-1])
return idx[::2], idx[1::2]-1
</code></pre>
<p>Shorter way -</p>
<pre><code>def start_stop_v2(a, val=0):
idx =... | python|arrays|numpy|indexing | 1 |
13,787 | 47,522,787 | Race condition when using tf.assign in Tensorflow | <p>How do you deal with the race condition when using tf.assign()?
For example, if my code is the following:</p>
<pre><code>y = tf.Variable(6,trainable=False,name='y');
x = tf.Variable(0,trainable=False,name='x');
assign_op = tf.assign( x, 2 );
divide_op = y/assign_op;
answer = sess.run([divide_op]);
</code></pre>
<... | <p>You want to look into control_dependencies flow control functions:</p>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/Graph#control_dependencies" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/Graph#control_dependencies</a></p>
<pre><code>with tf.control_dependencies([assign_op]... | machine-learning|tensorflow|graph|race-condition | 0 |
13,788 | 68,259,621 | creating dictionary from dataframe | <p>I have below dataframe</p>
<pre><code>a = [1,2,2,3,5]
b = [10,20,30,40,50]
df = pd.DataFrame(list(zip(a,b)), columns=['a','b'])
</code></pre>
<p>I want to generate dictionary like below</p>
<pre><code>{1:10, 2:[20,30], 3:40, 5:50}
</code></pre> | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html" rel="nofollow noreferrer"><code>groupby aggregate</code></a> + <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.to_dict.html" rel="nofollow noreferrer"><code>Series.to_dict</code></a>:</p... | python|pandas|dataframe|dictionary | 2 |
13,789 | 68,426,491 | Linear regression in python (tensorflow) | <p>I am running a code i saw on buitin website on linear regression with tensorflow and it keeps giving me an error, I don't know what is wrong with the code. first i thought it was my ide , then when i switched to jupyter lab it showed me error at this point</p>
<pre><code>from __future__ import absolute_import, divis... | <p>Well, just as the interpreter complains - you have a mismatch in shapes between the inputs to <code>mean_square</code> - your <code>X</code> / samples vector is 17 elements and your <code>Y</code> / targets vector is 18 elements, as you can verify.</p> | tensorflow|machine-learning|data-science|linear-regression|tensorflow2.0 | 0 |
13,790 | 68,294,220 | Pandas: Rolling average starts again on new Multi-Index value | <p>I have the below Dataframe:</p>
<pre><code>df = pd.DataFrame({'Team':['A','A','A','A','B','B','B','B'],
'Date':list(pd.date_range(start='1/1/2021', periods=8)),
'Score':[7,3,3,6,7,3,7,5],
}).set_index(['Team', 'Date'])
</code></pre>
<p>I want to add a rolling a... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>df.group_by</code></a> (and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.values.html" rel="nofollow noreferrer"><code>df.values</code></a> when assigning to... | python|pandas | 1 |
13,791 | 68,123,215 | "ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor" - Getting this error when i concatenate vgg16 base to my own FC layer | <p>I have this model where I concatenated vgg16 base model to 1 FC layer followed by my output layer.
This is what the whole model looks like.
<a href="https://i.stack.imgur.com/4N8HI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4N8HI.png" alt="enter image description here" /></a></p>
<p>And if I ... | <p>You should firstly define an intermediate model from your <code>VGG16</code> that returns all the desired outputs (in your case: <code>block5_conv3</code> and the final output)</p>
<pre><code>vgg16 = VGG16(input_shape=(96,96,3), weights='imagenet', include_top=False)
extraction_model = Model(
inputs = [vgg16.inp... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
13,792 | 68,196,236 | Creating a Pandas Dataframe from an API Endpoint in a Jupyter Notebook | <p>I am trying to convert API into pandas DataFrame.</p>
<p>sample API : <a href="https://api.fda.gov/drug/event.json?search=(receivedate:%5B20040101+TO+20210629%5D)+AND+PREDNISOLONE" rel="nofollow noreferrer">https://api.fda.gov/drug/event.json?search=(receivedate:[20040101+TO+20210629])+AND+PREDNISOLONE</a></p>
<p>He... | <ul>
<li>given <a href="https://docs.python-requests.org/en/master/api/#requests.Response" rel="nofollow noreferrer">response.json()</a> has already called <code>json.loads()</code> you should not be calling it yourself</li>
<li>simplest way to get JSON into a dataframe is <a href="https://pandas.pydata.org/pandas-docs... | python|pandas|dataframe|api | 0 |
13,793 | 59,096,629 | Is there a Python Pandas function to rename values in a column, if the values replesent lists with text inside instead of a single word or number? | <p>I have a dataset with three columns, "year" "category" and "laureate". The column "year" has values of numbers 2019, 2018 etc... the "category" column has values of words - medicine, physics, engineering etc... but the laureates column looks like this:</p>
<pre><code>laureates
[{id:something, name:something, surnam... | <p>You can try this:</p>
<pre><code>df.laureates.fillna(0) != 0
</code></pre>
<p>output:</p>
<pre><code> laureates
0 True
1 True
2 True
3 False
4 False
5 True
6 False
</code></pre>
<p>and if that works:</p>
<pre><code>df.laureates = df.laureates.fillna(0) != 0
</code></... | python|pandas | 0 |
13,794 | 59,366,002 | Array entry used in function turns from nan to 0 numpy python | <p>I made a simple function that produces a weighted average of several time series using supplied weights. It is designed to handle missing values (NaNs), which is why I am not using numpy's supplied average function.</p>
<p>However, when I feed it my array containing missing values, the array has its nan values repl... | <p>Where you call</p>
<pre><code>loc = np.where(np.isnan(N_Tseries)) # get location of nans
Weights[loc] = 0
N_Tseries[loc] = 0
</code></pre>
<p>You remove all NaNs and set them to zeros.</p>
<p>To reverse this you could iterate over the array and replace zeros with NaNs.
However, this would also set regular... | python-3.x|numpy | 0 |
13,795 | 45,891,638 | Using tuple in a numpy shape argument | <p>First post :) Don't shoot me if I do something wrong!</p>
<p>Is there a more shorthand way to define the shape in the below? It works, but is a bit long winded and not dynamic.</p>
<pre><code>def neural_net_image_input(image_shape):
"""
Return a Tensor for a batch of image input
: image_shape: Shape of... | <p>Use tuple addition:</p>
<pre><code>shape=(None,)+image_shape
# or if you want to allow lists and other sequences for image_shape:
shape=(None,)+tuple(image_shape)
</code></pre>
<p>or on recent Python versions with iterable unpacking generalizations:</p>
<pre><code>shape=(None, *image_shape)
</code></pre> | python|python-3.x|numpy | 3 |
13,796 | 45,748,016 | how to split and concat pandas dataframe | <p>I have a <code>datetime</code> index DataFrame of pandas like this:</p>
<pre><code> A B C A_1 B_1
2017-07-01 00:00:00 1 34 e 9 0
2017-07-01 00:05:00 2 34 e 92 2
2017-07-01 00:10:00 3 34 e 23 3
2017-07-01 00:15:00 4 34 e 2 5
2017-07-01 00:20:00 5 34 e... | <h1>EDIT</h1>
<p>After doing some research <code>lreshape</code> is not documented well and <code>pd.wide_to_long</code>, which is in the current API, does the same as lreshape with more flexibility.</p>
<p><a href="https://github.com/pandas-dev/pandas/issues/2567" rel="nofollow noreferrer">https://github.com/pandas-de... | python|pandas|time-series | 6 |
13,797 | 50,914,406 | Difference in execution time of first and subsequent tensor evaluations | <p>I have implemented a <a href="https://github.com/azag0/tfmbd/blob/master/tfmbd/tfmbd.py#L30-L101" rel="nofollow noreferrer">relatively simple physics model</a> in tensorflow (one matrix diagonalization, a few matrix inversions, bunch of tensor algebra). The building of the graph (in python) takes 3 seconds. For a ty... | <p>The first time a graph is run with specific fetches (and/or feeds), optimization passes run to rewrite the graph (these can be configured to some extent by passing a <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/protobuf/rewriter_config.proto" rel="nofollow noreferrer">RewriterConfig<... | python|tensorflow | 1 |
13,798 | 50,928,329 | Getting x_test, y_test from generator in Keras? | <p>For certain problems, the validation data can't be a generator, e.g.: <a href="https://github.com/keras-team/keras/blob/ce56322aadc6a861db21e598720c2dce03747ec3/keras/callbacks.py#L865" rel="nofollow noreferrer"><code>TensorBoard</code> histograms</a>:</p>
<blockquote>
<p>If printing histograms, validation_data m... | <p>Python 2.7 and Python 3.* solution:</p>
<pre><code>from platform import python_version_tuple
if python_version_tuple()[0] == '3':
xrange = range
izip = zip
imap = map
else:
from itertools import izip, imap
import numpy as np
# ..
# other code as in question
# ..
x, y = izip(*(validation_seq[i] f... | python|numpy|keras|marshalling|keras-2 | 5 |
13,799 | 66,519,907 | Pandas sort function not recognizing column | <p>I'm trying to organize my df by state alphabetically but when I sort by state using <code>sort_values</code>, nothing happens. I believe there is an issue with how the data is getting pulled because I get a KeyError that 'state' is not recognized. Should I use the <code>rename</code> function instead of renaming the... | <p>You are trying to i) sort_values when your target is the index; and ii) you are not assigning the sorted result. Go with:</p>
<pre><code>merged_US_states_visitation.sort_index(inplace=True)
</code></pre> | python|pandas|dataframe | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.