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 |
|---|---|---|---|---|---|---|
373,600 | 56,502,924 | How to create new pandas DataFrame with group by values? | <p>I have data with 3 locations. I would like to group by my locations and create new pandas DataFrame.</p>
<p>I have pandas DataFrame as follows:</p>
<pre><code>Day Time LocationA LocationB
1 8 XX YY
1 8 XX ZZ
1 8 XX ZZ
1 9 YY ZZ
1 9 XX ... | <p>In your case using <code>melt</code> then <code>groupby</code> + <code>stack</code> </p>
<pre><code>yourdf=df.melt(['Day','Time']).groupby(['Day','Time','variable']).value.value_counts().unstack(level=2,fill_value=0).reset_index()
yourdf
Out[405]:
variable Day Time value LocationA LocationB
0 1 8... | python|pandas|pandas-groupby | 4 |
373,601 | 56,577,979 | Change the default colors of a mosaic plot | <p>I want to change the color of this mosaic plot to make it printable in black in white but can't find a way to change this parameter</p>
<p><a href="https://i.stack.imgur.com/lOMAT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lOMAT.png" alt="the mosaic plot"></a></p>
<pre><code>from statsmodel... | <p><a href="http://www.statsmodels.org/stable/generated/statsmodels.graphics.mosaicplot.mosaic.html" rel="nofollow noreferrer">The documentation</a> mentions a <code>properties=</code> argument:</p>
<blockquote>
<p><strong>properties function (key) -> dict, optional</strong></p>
<p>A function that for each t... | python|pandas|matplotlib|mosaic-plot | 2 |
373,602 | 56,531,511 | How to append column values of one dataframe to column of another dataframe | <p>I'm working with 2 dataframes, A & B. Dataframe A is populated with values, while dataframe B is empty except for a header structure
I want to take the value of column in dataframe A, and append them to the corresponding column in dataframe B. </p>
<p>I've placed the values of the dataframe A column I want to a... | <p>Create the dataframe with the data already in it...</p>
<pre><code>dataframeB = pd.DataFrame(dataframeA['A'], columns = ['x'])
</code></pre>
<p>Then you can add columns in from the other dataframe:</p>
<pre><code>dataframeB['y'] = dataframeA['B']
</code></pre>
<p>Result:</p>
<pre><code> x y
1 2
1 2
</c... | python|pandas|dataframe | 0 |
373,603 | 56,488,402 | How to replace misspelled words in a pandas dataframe | <p>I have 2 pandas DataFrames. One containing a list of properly spelled words:</p>
<pre class="lang-sh prettyprint-override"><code>[In]: df1
[Out]:
words
0 apple
1 phone
2 clock
3 table
4 clean
</code></pre>
<p>and one with misspelled words:</p>
<pre class="lang-sh prettyprint-override"><code>[In]: df2
[Out... | <p>If want match first value returned by <code>get_close_matches</code>, the cutoff parameter can be adjusted based on your desired threshold, use <code>next</code> with <code>iter</code> for possible add value if no match - here <code>np.nan</code>:</p>
<pre><code>x = [next(iter(x), np.nan)
for x in map(la... | python|python-3.x|pandas|numpy|dataframe | 5 |
373,604 | 56,705,686 | i tried installing tensorflow using 'pip install tensorflow ' in anaconda prompt and command prompt. its showing following output | <p>Found existing installation: wrapt 1.10.11
Cannot uninstall 'wrapt'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.</p> | <p><strong>(1)</strong> First try to install wrapt manually using following command</p>
<pre><code>pip install wrapt --upgrade --ignore-installed
</code></pre>
<blockquote>
<p>make sure that you use "--ignore-installed" flag when install 'wrapt' as above mentioned command</p>
</blockquote>
<p><strong>(2)</strong> ... | python-3.x|tensorflow|anaconda | 2 |
373,605 | 56,786,677 | TensorFlow 1.14.0 is not using GPU | <p>I set up TensorFlow using <code>pip install --user tensorflow-gpu</code> on my Ubuntu 19.04 laptop. All dependencies like CUDA, CUDNN are installed to and working. But still, when importing TensorFlow and checking <code>tf.test.is_gpu_available()</code> gives me False. I have tried completely uninstalling and reinst... | <p>My particular problem was that <strong>TensorFlow 1.14.0</strong> were seeking for <strong>CUDA 10.0</strong> binary, while I had only <strong>10.1</strong> installed. For some reason CUDA 10.0 could not be installed on my <strong>Ubuntu 19.04</strong> so I installed <strong>18.04</strong> instead and followed stand... | python|tensorflow | 14 |
373,606 | 56,750,631 | Broadcasting two dataframe | <p>I have 2 dataframes as follow:</p>
<p>1st dataframe <code>data</code>:</p>
<pre><code> 2019-06-19 2019-06-20 2019-06-21 2019-06-22 2019-06-23 2019-06-24 2019-06-25
currency
... | <pre><code>data=pd.DataFrame({'currency':['BCH','BTC'],'2019-06-19 ':['485.424079','202.204572'],'2019-06-20':['485.424079','256.085103']})
sys_bal=pd.DataFrame({'currency':['1WO','ABX'],'2019-06-19 ':['1997308','241444'],'2019-06-20':['1996908','241444']})
</code></pre>
<p>EDIT: if you receiving <code>'dict' object h... | python|pandas|datetime | 0 |
373,607 | 56,562,576 | How to add values to columns if field is NaN upon split() | <p>How to set the values of fields to NaN using Pandas.</p>
<p>I have a spreadsheet file as an input and one of the columns has empty values which I filled with NaN values.</p>
<p>I am trying to split the first name with the suffix. I did use str.split().
But since there are NaN-value fields.</p>
<p>I encountered th... | <p>You can go about it like this:</p>
<pre><code>input_data = [['John III', 'Snow'], ['', ''], ['John', 'Snow']]
split_data = [[k for j in i for k in j.split()] for i in input_data]
#[['John', 'III', 'Snow'], [], ['John', 'Snow']]
df = pd.DataFrame(split_data).fillna('')
# 0 1 2
#0 John III Snow
#1 ... | python|pandas|numpy | 0 |
373,608 | 56,672,331 | Plotting a Tensor in Python | <p>I am following the tutorial from <a href="https://www.tensorflow.org/beta/tutorials/generative/dcgan" rel="nofollow noreferrer">https://www.tensorflow.org/beta/tutorials/generative/dcgan</a></p>
<p>I want to be able to see the image that is being generated using plt.imshow() but for some reason the line </p>
<pre>... | <p>In TensorFlow 1.xx you need to <a href="https://www.tensorflow.org/guide/graphs#executing_a_graph_in_a_tfsession" rel="nofollow noreferrer">evaluate</a> output tensor.</p>
<pre class="lang-py prettyprint-override"><code>generator = make_generator_model()
noise = tf.random.normal([1, 100])
generated_image = generato... | python|tensorflow|matplotlib|machine-learning | 1 |
373,609 | 56,649,500 | Is there any difference between using Dataframe.columns and Dataframe.keys() to obtain the column names? | <p>For the sake of curiosity is there any practical difference between getting the column names of a DataFrame (let's say df) by using df.columns or df.keys()? </p>
<p>I've checked the outs by type and it seems to be exactly the same. Am I missing something or these two methods are just as redundant as it seems? Is on... | <p>Doesn't look like there's a practical difference and if there is, I'd really like to know what it is. You probably saw in the documentation that <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.columns.html" rel="nofollow noreferrer">DataFrame.columns</a> has the column labels and... | python-3.x|pandas|dataframe | 4 |
373,610 | 56,681,786 | How to ignore Null values in a CSV columns with pandas while processing the text? | <p>I have a CSV file and each word in a sentence is represented in cell, with a null cell between each sentence. </p>
<p><a href="https://i.stack.imgur.com/XtrCn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XtrCn.png" alt="CSV snippet file"></a></p>
<p>My problem is in <strong>run_id</strong> co... | <p>To skip the blank rows (which contain both None values and empty strings) , why not just do: </p>
<pre><code>df = df[df.word.apply(lambda x : len(x)>0)]
</code></pre> | python|pandas|csv|nlp | 1 |
373,611 | 56,583,049 | Calculate Percent-Change (over time) of pandas column values based on other column value | <p>I'm working with an example dataset:</p>
<pre><code> date name point
0 4/24/2019 Martha 3617138
1 4/25/2019 Martha 3961918
2 4/26/2019 Martha 4774966
3 4/27/2019 Martha 5217946
4 4/24/2019 Alex 62700321
5 4/25/2019 Alex 66721020
6 4/26/2019 Alex 7174513... | <p>You can use <code>apply</code> with <code>last</code> and <code>first</code> value approached through <code>.values</code> to calculate the percentage change over the whole group:</p>
<pre><code>df.groupby('name',sort=False).apply(lambda x: (x['point'].values[-1] - x['point'].values[0]) / x['point'].values[-1] * 10... | python|pandas|dataframe|pandas-groupby | 1 |
373,612 | 56,545,152 | Is there a way to take the values from one column in a dataframe and append them to different dataframe's column in pandas python | <p>I'm working with 2 dataframes A & B of different shapes</p>
<p>Dataframe A has 193 rows and 33 columns
Dataframe B has 2 rows and 196 columns</p>
<p>I want to be able to take a column from Dataframe A "Province or State" and have its values append on to Dataframe B's column "State".</p>
<p>I've tried the foll... | <p>I was able to accomplish this by setting the row count of DataFrameB to 193 using the following method:</p>
<pre><code>num_rows = 93
for x in np.arange(0, num_rows):
dataframeB.loc[x] = [np.NaN for n in range(96)]
</code></pre>
<p>Then, I set dataframeB's State column to equal DataframeA's Province or state co... | python|pandas|dataframe|data-science | -1 |
373,613 | 56,862,204 | Image data cannot be converted to float | <p>I have a code for predicting dog breed after training on CNN model, I get the class index from the below function. I want to display an random image from the class <code>idx</code> folder obtained from the function.</p>
<pre><code> class_name = [item for item in loaders['train'].dataset.classes]
def predic... | <p>So, I tried to reproduced the error in your code <a href="https://github.com/gprashmi/Dog_breed_classifier/blob/master/dog_breed_classifier-5.ipynb" rel="nofollow noreferrer">here</a> and was successful in doing that. You are getting error because of these lines in your code:</p>
<pre><code>a = random.choice(os.lis... | python|image|image-processing|pytorch | 2 |
373,614 | 56,741,087 | How to fix RuntimeError "Expected object of scalar type Float but got scalar type Double for argument"? | <p>I'm trying to train a classifier via PyTorch. However, I am experiencing problems with training when I feed the model with training data.
I get this error on <code>y_pred = model(X_trainTensor)</code>:</p>
<blockquote>
<p>RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #... | <p>Reference is from <a href="https://github.com/pytorch/pytorch/issues/2138" rel="noreferrer">this github issue</a>.</p>
<p>When the error is <code>RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'</code>, you would need to use the <code>.float()</code> function sinc... | python|neural-network|deep-learning|classification|pytorch | 158 |
373,615 | 25,830,584 | Graphs in python using matplotlib | <p>I wanted to plot <code>y=(x+2)(x−1)(x−2)</code> for x going from −3 to 3 using a dashed red line. When I wrote the following code, nothing shows up.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = eval(formula)
plt.plot(x, y)
... | <p>Make sure <code>graph(..)</code> call is outside the <code>graph</code> function definition (IOW, indent correctly):</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = eval(formula)
plt.plot(x, y, 'r--') # `r--` for dashed red line... | python|numpy|matplotlib | 1 |
373,616 | 25,791,053 | ANOVA and HSD tests from Python dataframe | <p>I'm looking for a method to perform an ANOVA and HSD tests from a dataframe in Python. I tried to read some examples on forums and tutorials but i didn't achieve to apply it to my work.</p>
<p>Here is a simple Pandas dataframe:</p>
<pre><code>Date Density Hour Repetition Glucose
A HD AM 1 6.7
... | <p><code>pairwise_tukeyhsd</code> only allows a single group variable, it is for oneway ANOVA. It is possible to make all pairwise comparisons for all fully interacted groups after creating a group index for all different explanatory variables. For example <code>group1 = (A, HD, AM, 1)</code>, <code>group2 = (A, HD, AM... | python|pandas|statistics|statsmodels|anova | 0 |
373,617 | 25,717,686 | NumPy Tensor / Kronecker product of matrices coming out shuffled | <p>I'm trying to compute the <s>tensor product</s> (update: what I wanted was actually called the <a href="http://en.wikipedia.org/wiki/Kronecker_product" rel="nofollow"><em>Kronecker</em> product</a>, and this naming confusion was why I couldn't find <code>np.kron</code>) of multiple matrices, so that I can apply tran... | <p>From the answers to <a href="https://stackoverflow.com/q/23592229/2379410">this</a> and <a href="https://stackoverflow.com/q/16330971/2379410">this</a> question, I learned what you want is called the "<a href="http://en.wikipedia.org/wiki/Kronecker_product" rel="nofollow noreferrer">Kronecker product</a>". It's actu... | python|numpy|matrix | 3 |
373,618 | 25,923,587 | Pandas to form clusters based on diff column | <p>I am trying to use Pandas to eliminate some near duplicates in a data frame based on the difference in a column representing time in seconds. For example:</p>
<pre><code>import pandas as pd, numpy as np
df=pd.DataFrame([1200,1201,1233,1555,1650,5561,5562],columns=['Time'])
df['Dif']=df.Time.diff()
df['Coef']=np.ran... | <p>You could do a groupby here, by enumerating the groups:</p>
<pre><code>In [11]: (df['Time'].diff() > 2).cumsum()
Out[11]:
0 0
1 0
2 1
3 2
4 3
5 4
6 4
Name: Time, dtype: int64
</code></pre>
<p><em>Note: if this was a datetime column rather than 2 you'd want to compare to a timedelta.</em></p... | python|pandas | 5 |
373,619 | 25,820,071 | Pandas column.sum() without having the index values multiply | <p>I have a pd like this:</p>
<p><img src="https://i.stack.imgur.com/kKsAP.png" alt="pd"></p>
<p>When I take the .sum() of the columns, Pandas is multiplying each row entry by the index value. </p>
<p>I need just a raw count at the end of each column, not a "sum" per se. What is the best way?</p> | <p>To find the sum of the values, use <code>.sum()</code>. To find a count of the non-empty cells, use <code>.count()</code>. To find a count of the cells which have a value greather than 0, try <code>df[df>0].count()</code>.</p>
<pre><code>In [29]: df=pd.read_table('data.csv', delim_whitespace=True)
In [30]: df
O... | python|pandas | 2 |
373,620 | 25,792,086 | Pandas merge return empty dataframe | <p>I have two dataframes</p>
<pre><code>current_bin.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 16 entries, 0 to 15
Data columns (total 3 columns):
id 16 non-null object
fpd 16 non-null float64
avgSpeedBinID 16 non-null object
dtypes: float64(1), object(2)
</code></... | <p>The <code>avgSpeedBinID</code> in the current bin dataframe is type <code>str</code> and in avg is <code>int</code>.
Just cast the <code>str</code> one into an <code>int</code> and the merge will work.</p>
<pre><code>current_bin['avgSpeedBinID'] = current_bin['avgSpeedBinID'].astype(int)
avg.merge(current_bin, on=... | python|pandas | 23 |
373,621 | 25,773,245 | Ambiguity in Pandas Dataframe / Numpy Array "axis" definition | <p>I've been very confused about how python axes are defined, and whether they refer to a DataFrame's rows or columns. Consider the code below:</p>
<pre><code>>>> df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], columns=["col1", "col2", "col3", "col4"])
>>> df
col1 col2 col3 col4
0... | <p>It's perhaps simplest to remember it as <em>0=down</em> and <em>1=across</em>. </p>
<p>This means:</p>
<ul>
<li>Use <code>axis=0</code> to apply a method down each column, or to the row labels (the index).</li>
<li>Use <code>axis=1</code> to apply a method across each row, or to the column labels.</li>
</ul>
<p>H... | python|arrays|pandas|numpy|dataframe | 182 |
373,622 | 25,455,067 | Pandas DataFrame datetime index doesn't survive JSON conversion and reconversion | <p>I have the following snippet of Python code:</p>
<pre><code>import pandas as pd
# print normal index
print data.index
# convert from df to JSON and back
data_json = data.to_json()
df = pd.read_json(data_json)
df.index = pd.to_datetime(df.index)
print df.index
</code></pre>
<p>for some reason running this returns... | <p>The error here is that <code>to_json</code> saves dates with ms resolution by defaul, while <code>to_datetime</code> converts with nanosecond resolution by default. To fix, either of these (but not both!) would work.</p>
<pre><code>pd.to_datetime(df.index, unit='ms')
#OR
data_json = data.to_json(date_unit='ns')
</... | python|json|datetime|pandas | 12 |
373,623 | 25,813,529 | Joining same-key dictionaries into a dataframe in pandas | <p>How to create a pandas <code>DataFrame</code> out of two and more dictionaries having common keys? That is, to convert</p>
<pre><code>d1 = {'a': 1}
d2 = {'a': 3}
...
</code></pre>
<p>into a dataframe with columns <code>['d1', 'd2', ...]</code>, rows indexed like <code>"a"</code> and values determined by the respec... | <pre><code>import pandas as pd
d1 = {'a': 1, 'b':2}
d2 = {'a': 3, 'b':5}
df = pd.DataFrame([d1, d2]).T
df.columns = ['d{}'.format(i) for i, col in enumerate(df, 1)]
</code></pre>
<p>yields</p>
<pre><code>In [40]: df
Out[40]:
d1 d2
a 1 3
b 2 5
</code></pre> | python|dictionary|pandas | 9 |
373,624 | 25,459,982 | Trouble with grouby on millions of keys on a chunked file in python pandas | <p>I have a very big CSV file (tens of Gigas) containing web logs with the following columns: <code>user_id</code>, <code>time_stamp</code>, <code>category_clicked</code>. I have to build a scorer to identify what categories users like and dislike. Note that I have more than 10 millions users.</p>
<p>I first cut it in... | <p>Here's a soln for scaling this problem arbitrarily. This is in effect a high-density version of this question <a href="https://stackoverflow.com/questions/15798209/pandas-group-by-query-on-large-data-in-hdfstore">here</a></p>
<p>Define a function to hash a particular group value to a smaller number of groups. I wou... | python|csv|pandas|bigdata | 5 |
373,625 | 26,198,477 | Transposing a numpy matrix causes cv's draw functions to throw errors | <p>I've been running into a few problems using cv to display images from numpy matrices when I transpose them.</p>
<p>Consider the following code.</p>
<pre><code>import cv2, numpy as np
...
ones = np.ones((100,100))
onesT = np.copy(ones.T)
onesCT = np.copy(ones.T, order='C')
cv2.circle(ones, (50,50), 3, (0), thicknes... | <p>At one level of abstraction, all those matrices are the same. But at a lower level, two of them have their data stored using the C convention (<a href="http://en.wikipedia.org/wiki/Row-major_order" rel="nofollow">row-major order</a>) for arrays, and the other (<code>onesT</code>) uses the Fortran convention (column... | python|opencv|numpy | 1 |
373,626 | 26,101,008 | pandaslooping through grouped data for a plot | <p>I did the following:</p>
<pre><code>for grp, val in df_grp:
ax1.plot(val.concentration,val.capacity,'o', label = grp)
ax1.set_xlim(0,2.5)
plt.legend(loc=1, bbox_to_anchor=[0,0,1.5,1])
</code></pre>
<p>How do i get rid of the brackets, the 'u' and the quotation marks ?</p>
<p><img src="https://i.stack.im... | <p>Because you are using the groups as labels, the labels are actually the <code>str</code> property of <code>tuple</code> representing each group, a quick work around:</p>
<pre><code>In [42]:
print df
v1 v2 v3
0 A 11 1
1 A 11 2
2 A 30 3
3 A 30 4
4 B 45 5
5 B 45 6
6 B 12 7
7 B 12 8... | matplotlib|pandas | 1 |
373,627 | 26,242,438 | Save data from plot to numpy array | <p>I'm wondering how could I save the data content of a plot generated using <strong>Matplotlib</strong> to a Numpy array.</p>
<p>As a example, suppose I generated a contour plot with the following <a href="http://matplotlib.org/examples/pylab_examples/contour_demo.html" rel="nofollow noreferrer">code</a>:</p>
<pre><... | <p>For recent versions of matplotlib, you can use <code>pickle</code> to save the whole plot or just selected pieces, and even show the plot again from the pickled data:</p>
<pre><code>import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import pickle
if 0: # to generate the file
del... | python|arrays|numpy|matplotlib | 4 |
373,628 | 26,245,862 | Reducing pandas series with multiple nan values to a set gives multiple nan values | <p>I'm expecting to get <code>set([nan,0,1])</code> but I get <code>set([nan, 0.0, nan, 1.0])</code>:</p>
<pre><code>>>> import numpy as np
>>> import pandas as pd
>>> l= [np.nan,0,1,np.nan]
>>> set(pd.Series(l))
set([nan, 0.0, nan, 1.0])
>>> set(pd.Series(l).tolist())
set(... | <p>Not all nans are identical:</p>
<pre><code>In [182]: np.nan is np.nan
Out[182]: True
In [183]: float('nan') is float('nan')
Out[183]: False
In [184]: np.float64('nan') is np.float64('nan')
Out[184]: False
</code></pre>
<p>Therefore,</p>
<pre><code>In [178]: set([np.nan, np.nan])
Out[178]: {nan}
In [179]: set([... | python|numpy|pandas|set|nan | 14 |
373,629 | 26,422,869 | All pairs of numbers between 2 arrays | <p>I am trying to get all pairs of numbers between two arrays using numpy without success.
Basically what I need is an outer product where the numbers instead of being multiplied are put in an array, i.e.:</p>
<pre><code>a = np.array([1, 2])
b = np.array([3, 4])
np.Func(a, b)
>>> [[[1,3], [1,4]]
[[2,3],... | <p>You could also take the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html#numpy.transpose" rel="nofollow"><code>transpose</code></a> of the meshgrid:</p>
<pre><code>>>> np.transpose(np.meshgrid(a, b))
array([[[1, 3],
[1, 4]],
[[2, 3],
[2, 4]]])
</code... | python|arrays|numpy|combinations | 3 |
373,630 | 26,044,349 | How Do I Use Excel's Format Painter Across a Whole Workbook | <p>Every week I generate a large excel sheet using Python/Pandas. However, the xls writer in Pandas does not allow one to format the excel sheets likely because of the proprietary format. Currently, I have to go worksheet by worksheet in the newly generated file and copy the formatting from the sheet the week before ... | <p>I'd do it that way:</p>
<pre><code>import win32com.client
xlPasteFormats = -4122
xlPasteSpecialOperationNone = -4142
excelInstance = win32com.client.gencache.EnsureDispatch ("Excel.Application")
workbook = excelInstance.Workbooks.Item(1)
worksheet = workbook.Worksheets(1)
worksheet2 = workbook.Wo... | python|excel|pandas|formatting|vba | 2 |
373,631 | 26,335,732 | Pandas: how to use query to select closest values | <p>I'm using Pandas 0.13.0 and I try to get the two closest values as follow.</p>
<p>The index is sorted with increasing and unique values.</p>
<pre><code>import pandas as pd
import Quantities as pq
f = {
'A': [ 0.0, 0.1, 0.2, 0.5, 1.0] * pq.m,
'B': [10.0, 11.0, 12.0, 15.0, 20.0] * pq.kPa,
'C': [ a... | <p>Unless I misunderstood your question I get output you wanted without using <code>query</code>:</p>
<pre><code>value_to_find = 0.15
Min = df['A'] <= value_to_find
Max = df['A'] >= value_to_find
idx_Min = df.ix[Min, 'A'].idxmax()
idx_Max = df.ix[Max, 'A'].idxmin()
df.ix[idx_Min:idx_Max, ['A','B']]
A B... | python|pandas | 5 |
373,632 | 66,983,666 | How can I calculate the percentage of empty values in a pandas dataframe? | <p>I have a dataframe <code>df</code>, from which I know there are empty values, i.e. '' (blank spaces).
I want to calculate the percentage per column of those observations and replace them with <code>NaN</code>.</p>
<p>To get the percentage I've tried:</p>
<pre><code>for col in df:
empty = round((df[df[col]] == '')... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isna.html" rel="nofollow noreferrer"><code>Series.isna</code></a> for test missing values (but not empty spaces):</p>
<pre><code>nans = round(df[col].isna().sum()/df.shape[0]*100, 1)
</code></pre>
<p>Solution should be ... | python|pandas | 2 |
373,633 | 67,164,667 | How to use PyTorch to softmax only the upper triangular elements of a matrix? | <p>Given input like:</p>
<pre><code>tensor([[[1.9392, -1.9266, 0.9664],
[0.0000, -1.9266, 0.9664],
[0.0000, -0.0000, 0.9664]]])
</code></pre>
<p>My desired output is:</p>
<pre><code>tensor([[[0.4596, 0.0096, 0.1737],
[0.0000, 0.0096, 0.1737],
[0.0000, -0.0000, 0.1737]]])
</code>... | <p>You can access the upper triangular elements with <code>torch.triu_indices</code>:</p>
<pre class="lang-py prettyprint-override"><code>t = tensor([[1.9392, -1.9266, 0.9664],
[0.0000, -1.9266, 0.9664],
[0.0000, -0.0000, 0.9664]])
idx = torch.triu_indices(*t.shape)
soft = F.softmax(t[idx[0]... | python|matrix|pytorch|tensor|softmax | 4 |
373,634 | 66,944,445 | Convert Date headers followed by AM & PM time cells to whole Timestamp column | <p>How to convert 'Time & Date' column to timestamp? As you can see there's a header cell for each date followed by AM & PM times. I would like to have a whole timestamp column.</p>
<pre><code>Time & Date Country ... Consensus Forecast
15 4:00 PM DE ... NaN ... | <p>Your <code>Time & Date</code> column represents two different things, so it needs to be two different columns to start with. If there's a way to cut out that step I would love to see it, but I'm guessing you need to expand it into two columns before combining again before using <code>pandas.to_datetime()</code> ... | pandas|date|header|timestamp | 1 |
373,635 | 66,887,785 | How to visualize nested `tf.keras.Model (SubClassed API)` GAN model with plot_model? | <p>Models implemented as subclasses of <code>keras. Model</code> can generally not be visualized with <code>plot_model</code>. There is a workaround as described <a href="https://stackoverflow.com/questions/61427583/how-do-i-plot-a-keras-tensorflow-subclassing-api-model">here</a>. However, it only applies to simple mod... | <p>Whenever you pass each <code>generator</code> and <code>discriminator</code> to <code>GANModel</code>, they act like an encompassed child layer consisting of <code>n</code> times layers. So, if you plot only the <code>generator</code> model by the <code>GANModel</code> instances, it will show as follows (same goes ... | python|tensorflow|keras | 1 |
373,636 | 66,766,808 | how make a list an element of all rows of a df? | <p>I have a data frame and I have a list. How I can make a new column in my df and have the list in all rows?</p>
<p><code>list_skill=[A,B,C,D]</code></p>
<p>df</p>
<pre><code> col new_list
pdf [A,B,C,D]
dog [A,B,C,D]
dev [A,B,C,D]
</code></pre> | <h3><code>np.tile</code></h3>
<pre><code>df['new_list'] = np.tile(list_skill, (len(df), 1)).tolist()
</code></pre>
<hr />
<pre><code> col new_list
0 pdf [A, B, C, D]
1 dog [A, B, C, D]
2 dev [A, B, C, D]
</code></pre> | python|pandas|dataframe | 0 |
373,637 | 67,009,661 | Error calculating gradient on function imported from R using reticulate | <p>I'm working on a problem right now where I am trying to use the optimizers from Tensorflow probability in Python to solve a simple optimization problem I've already defined in R.</p>
<p>Here are the steps:</p>
<p><strong>Step 1: Define the original Python problem for solving the Rosenbrock banana function:</strong><... | <p><code>tfp.math.value_and_gradient</code> will unpack the list into multiple arguments and diff with respect to each of them. You'll have to wrap in <code>np.array</code> or <code>tf.convert_to_tensor</code>.</p>
<p>Also, it's unclear how you will get a gradient for <code>rosenbrock_for_r</code>. You may have to use ... | python|r|tensorflow|reticulate|tensorflow-probability | 1 |
373,638 | 67,055,939 | how do I perform the explained operation in pandas? | <p>this is my df</p>
<pre><code>idx = pd.date_range('2020-01-01',periods=26,freq='D')
vals = [0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,1,0,0,0,1,1]
pd.DataFrame(vals,index=idx)
</code></pre>
<p><a href="https://i.stack.imgur.com/51cRh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/51cRh.png" alt="ent... | <p>We can <code>group</code> the <code>index</code> of the dataframe on the sequential blocks of <code>1's</code> and aggreagte using <code>first</code> and <code>last</code> to calculate the periods where the value turns/stays <code>1</code>.</p>
<pre><code>m = df[0].eq(1)
m[m].index.to_series().groupby((~m).cumsum())... | python|pandas|dataframe|date | 5 |
373,639 | 67,082,682 | Creating dummy variables for ordinals in pandas dataframe | <p>I am trying to create dummy variables in python in the pandas dataframe format. I have a variable called "Weight Group" and I want to transform the variables like so:</p>
<p>Before transformation:</p>
<pre><code> Weight_Group
0 1
1 5
2 4
3 2
4 2
5 3
6 1
</code></pre>
... | <p>You can call <code>pd.get_dummies()</code> and then replace your <code>0</code> tallies with <code>NaN</code> and use <code>bfill()</code> (plus a bit of extra cleanup for display):</p>
<pre><code>pd.get_dummies(df['Weight_Group'], prefix='WD').replace(0,np.nan).bfill(axis=1).fillna(0).astype(int)
</code></pre>
<p>Y... | python|pandas|dataframe|dummy-variable | 3 |
373,640 | 66,786,498 | Pandas- update value in a specific column based on duplicate rows | <p>I have a pandas database of apartment building sales, one column is the price and another column is the date sold. Some of these sales were for multiple properties, however the price listed for each property reflects the total sale price of multiple properties. These bundle deals can be further identified by the dat... | <p>Try:</p>
<pre><code>df['Price'] *= (df['Tax Assessed Value'] /
df.groupby(['Price', 'Date Sold'])['Tax Assessed Value'].transform('sum')
)
</code></pre>
<p>but I think you need to identify exactly what you mean by duplicates</p> | python|pandas | 1 |
373,641 | 66,818,027 | add list of lists to pandas dataframe, where each item of the list is a new column | <p>I have 10 list of lists (variable length) looking like this, but each inside list is of the same length.</p>
<pre><code>[[0.2908717393875122, 0.012684155255556107, -0.0040715765208005905], [0.02942436747252941, 0.011299843899905682, 0.009102505631744862], [0.0382646806538105, 0.004623611457645893, 0.0047760489396750... | <pre><code>lst=[[0.2908717393875122, 0.012684155255556107, -0.0040715765208005905], [0.02942436747252941, 0.011299843899905682, 0.009102505631744862], [0.0382646806538105, 0.004623611457645893, 0.004776048939675093]]
</code></pre>
<p>Just simply use:-</p>
<pre><code>df[['V1','V2','V3']]=lst
</code></pre>
<p>Now if you ... | python|python-3.x|pandas|list|dataframe | 1 |
373,642 | 67,069,271 | Want to create a function with def, but ValueError returned | <p><strong>What I wanna do</strong></p>
<p>I want to do RFM analytics for purchase data of a e-commerce site.</p>
<p>I processed the data into RFM format, so I want to rank every ID depending on the values of each column (Money, Recency and Frequency).</p>
<p>However, I got the error message as below.</p>
<pre><code> -... | <p>If working with scalars use <code>and</code> instead <code>&</code> with remove last level of <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.droplevel.html" rel="nofollow noreferrer"><code>MultiIndex.droplevel</code></a>.</p>
<p>So use:</p>
<pre><c... | python|python-3.x|pandas|dataframe | 1 |
373,643 | 67,172,162 | How to count the sale of each day according stocks with pandas | <p>I want to count the sale of each day. The values in the original table are stocks but not sale.
I use excel to solve the problem,But now I have millions of products ,so I want to solve the problem with pandas.</p>
<p><a href="https://i.stack.imgur.com/VRGuP.png" rel="nofollow noreferrer"><img src="https://i.stack.im... | <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.diff.html" rel="nofollow noreferrer">pandas.DataFrame.diff()</a> is enough.</p>
<pre class="lang-py prettyprint-override"><code>df['STOCK'] = df['STOCK'].diff()
df.rename(columns={'STOCK': 'SALE'}, inplace=True)
df.rename(columns={'ID1_stock': 'I... | python|pandas | 1 |
373,644 | 66,850,213 | Understanding shapes in keras layers | <p>I am learning Tensorflow and Keras to implement <code>LSTM</code> <code>many-to-many</code> model where the length of input sequence is equal to the length of the output sequence.</p>
<p>Sample Code:</p>
<p>Inputs:</p>
<pre><code>voc_size = 10000
embed_dim = 64
lstm_units = 75
size_batch = 30
count_classes = 5
</cod... | <p>The Dense can do 3D operation, it will flatten the the input to shape (batch_size * time_steps, features) and then apply a dense layer and reshape it back to orignal (batch_size, time_steps, units). In keras's <a href="https://keras.io/api/layers/core_layers/dense/" rel="nofollow noreferrer">documentation</a> of Den... | tensorflow|keras|deep-learning|neural-network|tensorflow2.0 | 1 |
373,645 | 66,969,738 | How to return all indexes in multiindex on ANY condition | <p>I am trying to wrap my head around multilevel indices.</p>
<p>Specifically, i am trying to get all level 0 indicies that fullfill an 'ANY' criteria.
But i can't for the life of me, understand how to get it to work.</p>
<p>For instance, in the dataframe below, we want all indicies that have a '3' in the column 'test_... | <p>Try with</p>
<pre><code>out = df.loc[df.index.isin(df.index[df['test_variable_2'].eq(3)])]
Out[529]:
event_name test_variable_1 test_variable_2 test_variable_3
subject_id
1 pre_event NaN 3.0 ... | python|pandas|dataframe|multi-level | 4 |
373,646 | 67,155,624 | Keras LSTM loading data from CSV "expected ndim=3, found ndim=2. Full shape received: (None, 150)" | <p>I am a beginner with LSTMs so sorry if this is a basic question. I've been trying to make a simple LSTM model that loads data from a csv text file for training</p>
<pre><code> trainX = pd.read_csv("Train\\X_Data.txt", header=None, delim_whitespace=True).to_numpy()
trainY = pd.read_csv("Train\\Y... | <p><code>trainX.shape = (35, 150)</code> which means that you have <code>35</code> samples of <code>150</code>. But you need to pass the data with the <code>batch_size</code> in the first position according to Keras. So you would have to expand the <code>2D</code> input to <code>3D</code>:</p>
<pre><code>trainX = tf.ex... | python|tensorflow|machine-learning|keras|lstm | 1 |
373,647 | 66,954,976 | How to plot same colors for same values in a map? | <p>I'm creating a colorbar with the function make_colormap. Source: <a href="https://stackoverflow.com/questions/16834861/create-own-colormap-using-matplotlib-and-plot-color-scale">Create own colormap using matplotlib and plot color scale</a>.
Also i'm plotting many maps with <code>for month, data in normals.groupby('M... | <p>You could apply a <a href="https://matplotlib.org/stable/tutorials/colors/colormapnorms.html" rel="nofollow noreferrer"><code>norm</code></a>. Using the same norm for all plots would make the colors consistent. It is unclear what the range of your <code>data['PP']</code> column is. Here is an example of the changes ... | pandas|matplotlib | 2 |
373,648 | 67,177,973 | How can I avoid this for loop in pytorch? Is there a function for efficient computation? | <p>I have the following code in my Pytorch neural net:</p>
<pre><code>cos = nn.CosineSimilarity(dim=1)
d = torch.zeros(batch_sz, n, n).to(device="cuda")
for i in range(n):
for j in range(n):
d[:, i, j] = cos(q[:, i, :], k[:, j, :])
</code></pre>
<p><code>q</code> and <code>k</code> are both of... | <p>I am not sure how to vectorize using <code>nn.CosineSimilarity</code> but you could use this vectorized implementation. It computes the cosine similarity in the same way as PyTorch's internal module.</p>
<pre><code>import torch
import torch.nn as nn
import time
# some dummy inputs
n=20
m=30
batch_sz = 10
k = torch... | performance|pytorch | 0 |
373,649 | 67,086,769 | Conditional mapping to a dataframe based on multiple columns | <p>I have a dataframe where I need to map categories based on value-based conditions on two separate columns. Total rows to do this are about a million.</p>
<p>Sample dataframe is:</p>
<pre><code>df = pd.DataFrame({'col1':['B','A','A','B','C','B','C','C','A'],
'col2':[10,30,40,20,60,30,70,80,50]})
</code... | <p>You can chain masks by <code>|</code> for bitwise <code>OR</code>:</p>
<pre><code>df['result'] = (df['col1']=='A') & (df['col2']>30) |
(df['col1']=='B') & (df['col2']>10) |
(df['col1']=='C') & (df['col2']>60)
</code></pre>
<p>Or:</p>
<pre><code>df['result'] = np.wh... | python-3.x|pandas|dataframe|numpy|mapping | 1 |
373,650 | 67,120,888 | How can I do a sjoin iteratively over features in a shapefile with geopandas, then encode categorical data? | <p>I have two shapefiles (<a href="https://drive.google.com/drive/folders/1pbvKvhIIvhqHfcMe9g6qtsjbZ6SzZrqt?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/drive/folders/1pbvKvhIIvhqHfcMe9g6qtsjbZ6SzZrqt?usp=sharing</a>) - one point layer, and one polygon layer. The point layer represents customers and ... | <p>You do not need a join, the <code>intersects</code> method is enough. Your target structure can be achieved using:</p>
<pre><code>points_in_locations = points.copy()
for idx, row in polygons.iterrows():
is_in_polygon = points.intersects(row.geometry)
points_in_locations[f"location {idx + 1}"] = is_... | python|pandas|geopandas | 1 |
373,651 | 66,921,943 | PyTorch Tensor Operation for adding the maximum of the previous row to the next | <p>Follow-Up question to <a href="https://stackoverflow.com/questions/66919743/pytorch-dynamic-programming-as-tensor-operation">PyTorch: Dynamic Programming as Tensor Operation</a>.</p>
<p>Could the following be written as a tensor operation instead of a loop?</p>
<pre class="lang-py prettyprint-override"><code>a = tor... | <p>Not entirely sure why you're trying to do this, but yes, this is possible. It's basically the same as your last question:</p>
<pre><code>max_vals, _ = a.max(axis=1, keepdim=True)
additions = max_vals.cumsum(0)[:-1]
a[1:, :] += additions
</code></pre>
<p>This is because the marginal addition from one row to the next ... | python|pytorch|dynamic-programming|tensor | 2 |
373,652 | 67,003,191 | Pandas all rows into one row of pd.series | <p>I have a pandas DataFrame loaded from a csv file like below:</p>
<pre><code>0 1 2 3 4 5
0 -1.140625 -1.828125 0.671875 -1.031250 -0.390625 -0.203125
1 -1.203125 -1.843750 0.687500 -0.953125 -0.281250 -0.156250
2 -1.187500 -1.781250 0.656250 -0.843750 -0.218750 -0.1718... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>DataFrame.unstack</code></a> with default index, convert to DataFrame and transpose:</p>
<pre><code>df = df.unstack().reset_index(drop=True).to_frame().T
</code></pre>
<p>Or use <a hr... | python|pandas | 0 |
373,653 | 66,766,006 | Can't load a dataset from torchvision | <p>I'm trying to load the <a href="https://www.yf.io/p/lsun" rel="nofollow noreferrer">LSUN dataset</a> following PyTorch's <a href="https://pytorch.org/vision/stable/datasets.html#lsun" rel="nofollow noreferrer">code</a>. I used their other datasets but this one seems to give me errors.</p>
<pre><code>import torch
imp... | <p>Unlike most other <a href="https://pytorch.org/vision/stable/datasets.html#lsun" rel="nofollow noreferrer">datasets offered by Torchvision</a>, LSUN doesn't appear to have a <code>download</code> argument. You can manually download the files to the specified directory from here:</p>
<p><a href="https://www.yf.io/p/l... | python|pytorch|torchvision | -1 |
373,654 | 67,124,432 | Max Pooling across MRI Slices | <p>I am trying to implement a Machine Learning Model for MRI scan diagnosis.
I have Inputs of shape (x, 256, 256, 3), where we have 3 color channels and where x is the number of slices in a sequence.
I read the <a href="https://journals.plos.org/plosmedicine/article?id=10.1371/journal.pmed.1002699" rel="nofollow norefe... | <p>After thinking about this problem I have found one solution which could work</p>
<pre><code> vgg16 = VGG16(weights='imagenet', include_top=False, input_shape=(256, 256, 3)) #
average_pool = Sequential(name='AveragePool')
average_pool.add(layers.AveragePooling2D(input_shape=(8, 8, 512)))
average_pool... | python|tensorflow|machine-learning|keras | 0 |
373,655 | 67,005,853 | Extract Month and the week of the month | <p>I am currently working on the pandas DataFrame with DateTime object. Is there a way to extract the month-weekofthemonth from pandas datetime object?</p>
<pre><code>data = pd.DataFrame(pd.date_range(' 1/ 1/ 2020', periods = 7, freq ='D'))
0 2000-01-01
1 2000-01-02
2 2000-01-03
3 2000-01-04
4 2000-01-05
5 2000-... | <p>Based on <a href="https://stackoverflow.com/questions/25249033/week-of-a-month-pandas">Week of a month pandas</a></p>
<pre><code>data[0].apply(lambda d: f'{d.month:02}-{(d.day-1) // 7 + 1:02}')
</code></pre>
<p>should give</p>
<pre><code>0 01-01
1 01-01
2 01-01
3 01-01
4 01-01
5 01-01
6 01-01
7 ... | python|pandas|datetime | 1 |
373,656 | 66,959,856 | Python: plotting several arrays in a single plot using for loop | <p>I have several arrays (more than this, about 20 x arrays and 20 y arrays) but this is an example</p>
<pre><code>xa1=[0,...3000]
ya1=[0,...3000]
xa2=[0,...3000]
ya2=[0,...3000]
xa3=[0,...3000]
ya3=[0,...3000]
</code></pre>
<p>I want to plot these arrays in a single plot using a for loop</p>
<p>I try first making an a... | <p>Based on your syntax xarr[i] is not an array but a list with one item in it and THAT item is an array. Matplotlib won't like that.</p>
<p>Try initializing xarr as a list instead, i.e. [xa1,xa2,xa3], and the same for yarr: you don't need them to be arrays, just a list OF arrays for the for-loop to iterate through.</... | python|arrays|numpy|loops | 0 |
373,657 | 66,909,817 | Custom function with multiple argument and one return value in map_fn for tensor object in Tensorflow | <p>I have two tensors t1 and t2 (shape=(64,64,3), dtype=tf.float64). I want to execute a custom function "func" which takes two tensors as input and returns one new tensor.</p>
<pre><code>@tf.function
def func(a):
t1 = a[0]
t2 = a[1]
return tf.add(t1, t2)
</code></pre>
<p>I am using map_fn of tensorf... | <p>The "elems" parameter of "map_fn" unpacks the argument passed to it along axis 0. So, in order to pass multiple tensors in the custom function,</p>
<ol>
<li>We have to stack them together.</li>
<li>Add an extra dimension along axis 0.</li>
</ol>
<pre><code># t1 and t2 has shape [2, 3]
val = tf.st... | python|tensorflow|tensor|xor|custom-function | 0 |
373,658 | 66,829,855 | matplotlib: share x axis from one subplot with y axis from another | <p>I want to project 3D data onto XY, XZ, YZ subplots with interactive shared axes.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(3, 1, constrained_layout=True)
n = 10000
pts = {
'X': np.random.normal(0, 1, n),
'Y': np.random.normal(0, 2, n),
'Z': np.random.normal... | <p>A quick (and possibly very stupid) fix I found is to sort of do the axis sharing manually. In other words, if both x and y axes you want to share have the same size in figure (i.e. both of them span e.g. 10 cm), you can manually set them to have equal limits, ticks and tick labels. In your case it would be something... | python|numpy|matplotlib|plot | 0 |
373,659 | 67,119,378 | How to create a new dataFrame based on some column values? | <p>I have a dataframe which has a column Flag whose values are either True or False. I want to create a new dataframe whose column Flag's values must be all True.</p>
<pre><code>df = {'Name':['Tom', 'nick', 'krish', 'jack'],
'Age':['12', '23', '25', '16'],
'Flag':[True, False, False, True]}
</code></pre>
<p... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>boolean</code> column, so compare by <code>True</code> is not necessary:</p>
<pre><code>df = pd.DataFrame(df)
</code></pre>
<p>You can select ... | python|pandas | 3 |
373,660 | 67,038,376 | Difference between torch.Size([64]) and (64,)? | <p>I created a Pytorch dataset class to store 64 lines of text. The file only has text, no label so I artificially generated an index list y (just to follow along with a tutorial https://medium.com/swlh/how-to-use-pytorch-dataloaders-to-work-with-enormously-large-text-files-bbd672e955a0#4fe0). After I created the datas... | <p>In a way they are same thing. You are printing shape of a one dimensional tensor. Shape written in tutorial is shape format of one dimensional numpy array.</p>
<p>If shape of y is printed after converting it into numpy array, mentioned format will appear. You can see both format with following code.</p>
<pre><code>p... | python|pytorch | 0 |
373,661 | 66,932,811 | Return key on fuzzy match of element in dictionary list | <p>I have a dataframe like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Cost Category</th>
<th>Vendor</th>
</tr>
</thead>
<tbody>
<tr>
<td>2021-03-22</td>
<td>-</td>
<td>FamilyMart</td>
</tr>
<tr>
<td>2021-03-04</td>
<td>-</td>
<td>FAMILY MART</td>
</tr>
<tr>
<td>2021... | <p>With <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><strong><code>Series.apply()</code></strong></a>, <code>fuzz_m()</code> receives one <code>Vendor</code> value at a time, so you can use that <code>dictionary</code> directly as <code>extractOne(value, dict... | python|pandas|numpy | 1 |
373,662 | 66,782,065 | How to update the a specific set of indices of a multi-dimensional tensor in Tensorflow | <p>I have this multi-dimensional tensor of shape [1,32,32,155], of which I want to update
the [:,:,:,0:27] indices.</p>
<p>In pytorch, one would do this simply with index assign i.e [:,:,:,0:27] = [1,32,32,27].
Index assign is currently not supported in Tensorflow. Therefore, my first attempt was to do the following:</... | <p>Use slice and <code>concat</code>:</p>
<pre><code>feat = tf.random.uniform([1, 32, 32, 155])
updates = tf.zeros([1, 32, 32, 27])
result = tf.concat((feat[:,:,:,27:], updates), -1)
</code></pre> | python|tensorflow|keras|tensorflow2.0 | 1 |
373,663 | 67,173,820 | Trouble Finding Spectrum Peaks on Python/ Google Colab | <p>I have a spectrum (of an oil sample) as a 2D array in a cvs file that i want to find the peaks for in wavelengths 600 - 1800 cm-1. I've tried the scipy.signal.find_peaks but that takes a 1D array and I have a 2D array with the wavelengths and corresponding peak values.
any help would be appreactiated since im very b... | <p><code>scipy.signal.find_peaks()</code> only takes a one-dimensional array containing the peaks. So you should be able to just select the column in your DataFrame with the peaks as so:</p>
<pre><code># note that find_peaks returns an array of peak indices, and a dictionary of properties
ind, properties = scipy.signa... | python|matlab|numpy|data-analysis|spectra | 0 |
373,664 | 67,033,501 | How to plot a scatter plot over a map separated by divisions? | <p>I want to plot a scatter plot over a map separated by divisions. So far I have tried the following.</p>
<pre><code>import os
import matplotlib.pyplot as plt
import pandas as pd
import geopandas as gpd
import numpy as np
fPath = 'shape/bgd_adm_bbs_20201113_SHP/bgd_admbnda_adm2_bbs_20201113.shp'
bgd = gpd.read_file(f... | <p>This is as simple as plotting data on same axis</p>
<ul>
<li>have data of healthcare facilities, then get GIS data for these facilities</li>
<li>get map GEOJSON and plot on axis</li>
<li>scatter data on same axis, using healthcare facility type as color</li>
</ul>
<pre><code>import requests, io
import pandas as pd
... | pandas|dataframe|matplotlib|geopandas | 2 |
373,665 | 67,157,966 | Create boolean flag in pandas from signal's crossings | <p>I would like to create a flag with a function and applying it to one column in a pandas dataframe.
The intention of the function is to set the value 1 when the signal crosses upwards over -1 and resets the value to 0 when the signal crosses 1 downwards.
Here is my code example:
I just cant get the function to work</... | <p>We can first detect the <code>-1</code> and <code>+1</code> crossings whilst considering they should cross-up and cross-down, respectively. This can be done via shifting the signal to left and right by 1 and comparing against <code>-/+ 1</code> with the crossing behaviour in mind:</p>
<pre class="lang-py prettyprint... | python|pandas|function | 2 |
373,666 | 67,046,540 | Plot a bar plot by using Seaborn | <p>I am new in data visualization. I am practicing Seaborn and I am trying to plot a barplot with this dataframe. I want the chart has 3 bars on each symbol, however, the output has only 1 bar on each symbol. May I know how to fix it?</p>
<p>Part of the DataFrame...</p>
<pre><code> returns_7d returns_30d return... | <p>I think <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html" rel="nofollow noreferrer">pandas.DataFrame.plot()</a> is all your need.</p>
<pre class="lang-py prettyprint-override"><code>df.plot(kind='bar')
</code></pre>
<p><a href="https://i.stack.imgur.com/2ATa8.png" rel="n... | python|pandas|dataframe|seaborn | 1 |
373,667 | 66,821,212 | Web scraping data table with python Selenium, BeautifulSoup and Pandas failed | <p>I am trying to web scrape/extract the table in the following website using python. (This is a dynamic table, so i cant just save the html in an html file, since it will get updated every so often).
<a href="https://www.eib.org/en/about/procurement/index.htm" rel="nofollow noreferrer">https://www.eib.org/en/about/pro... | <p>Try the url that actually has the table in the response. Can find this by searching the Network tab in the Dev Tools:</p>
<pre><code>import pandas as pd
url = 'https://www.eib.org/tools/jsp/calls.jsp?&lang=en&language=en&l=en&url=/about/procurement/index.htm&forceLanguage=en&_=1616778335822'... | python|pandas|selenium|selenium-webdriver|beautifulsoup | 0 |
373,668 | 66,990,389 | TensorFlow Lite: Update existing model or add new one in deployed app | <p>I'm creating a mobile app (with Flutter, for more details) that will need to do some offline inference using TensorFlow Lite models. The fact this needs to be offline means the models need to be shipped with the APP.</p>
<p>I know how to deploy the models with the APP (see <a href="https://itnext.io/working-with-ten... | <p>I'm sorry, but are you saying you want to update the app (one part of the app) without internet connection (or network connection)? The act of updating the app from the Play Store/ App Store requires an internet connection.</p>
<ul>
<li><p><strong>Manually install new application updates.</strong> This would be upda... | flutter|tensorflow-lite | 0 |
373,669 | 66,986,927 | Python : Flatten xml to csv with nested child tags | <p>There are multiple XML files that I would like to flatten, I am looking for a generic function or logic to convert the xml to a flat file. Most of the answers include hard-coded tags. Closest one being <a href="https://stackoverflow.com/questions/56343492/python-flatten-xml-to-csv-with-parent-tag-repeated-in-child">... | <p>Normally the <em>xml</em> nodes that hold a value should be the corresponding columns. As I see in your <em>xml</em> example "child", "child2", "childid", and so on, should be columns.</p>
<p>Based on the above <em>xml</em> I've made this piece of code that should be sufficiently generi... | python-3.x|xml|pandas|logic | 0 |
373,670 | 66,962,022 | How to get values from other rows based on multiple conditions in Pandas? | <p>I have the following df -</p>
<pre><code> +--------+--------+--------------------+------------+--------------------+----------+----------+
| GameID | TeamID | Team | OpponentID | Opponent | Location | score |
+--------+--------+--------------------+------------+-----------------... | <p>You can make use of <code>merge()</code> method:</p>
<pre><code>resultdf=df.merge(df[['GameID','OpponentID','score']], left_on=['GameID','TeamID'], right_on=['GameID','OpponentID'], how='left')
</code></pre>
<p>Now make use of <code>drop()</code> method:</p>
<pre><code>result.drop(columns=['OpponentID_y'])
</code><... | python|pandas | 1 |
373,671 | 66,846,030 | TypeError: linear(): argument 'input' (position 1) must be Tensor, not str | <p>so ive been trying to work on some example of bert that i found on github as its the first time im trying to use bert and see how it works. The respiratory im working with is the following: <a href="https://github.com/prateekjoshi565/Fine-Tuning-BERT/blob/master/Fine_Tuning_BERT_for_Spam_Classification.ipynb" rel="n... | <p>I've been working on this repo too.
Motivated by the answer provided on this <a href="https://stackoverflow.com/questions/65082243/dropout-argument-input-position-1-must-be-tensor-not-str-when-using-bert">link</a>. There is a class probably named Bert_Arch that inherits the nn.Module and this class has a overriden m... | python|pytorch|bert-language-model | 9 |
373,672 | 66,935,613 | Problem with combining multiple excel files in python pandas | <p>I am quite new to python programming. I need to combine 1000+ files into one file. each file has 3 sheets in it and I need to get data only from sheet2 and make an final excel file. I am facing a problem to pick a value from specific cell from each excel file on sheet2 and create a column. python is picking the valu... | <p>I <code>df.iloc[2][4]</code> refers to the 2nd row and 4th column of the 1st sheet. You have imported with <code>sheet_name=1</code> and never activated a different sheet, though you mentioned all of the <code>.xlsm</code> have 3 sheets.</p>
<p>II <em>your scoping could be wrong. Why define <code>df</code> outside o... | python|excel|pandas | 0 |
373,673 | 66,873,597 | Look up the matching element from another data frame and return its id- python | <p>i have a orders dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>items</th>
<th>chat_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>curd,vada,rice</td>
<td>74374374h4473</td>
</tr>
<tr>
<td>idly,sambar</td>
<td>7949759459h34</td>
</tr>
</tbody>
</table>
</div>
<p>I have another unique... | <p>Id you have dataframe <code>df_orders</code>:</p>
<pre><code> items chat_id
0 curd,vada,rice 74374374h4473
1 idly,sambar 7949759459h34
</code></pre>
<p>and dataframe <code>df_menu</code>:</p>
<pre><code> id items
0 1 idly
1 2 vada
2 3 rice
3 4 curd
4 5 sambar
</cod... | python|pandas|dataframe|data-science | 0 |
373,674 | 67,133,802 | Combining csv files columns together Pandas Python | <p>I am trying to combine <code>file1-3.csv</code> so that I could get the expected result. I want to combine all the rows together on all 3 file, but disregard the 1st column as it is the same on all 3 files. How can i do this with pandas.</p>
<p>Code:</p>
<pre><code>import pandas as pd
file1 = pd.read_csv('STDOutpu... | <p>You can use <code>pd.join</code> like:</p>
<pre><code>q1_2 = file1.join(file2, lsuffix='_Q1', rsuffix='_Q2')
file1-3 = q1_2.join(file3, rsuffix='_Q3')
</code></pre>
<p>Or if the 'element' column is the same for all three data frame, and there are no conflicting column names, you can use <code>pd.merge</code>:</p>
<... | python|pandas|csv|format|multiple-columns | 1 |
373,675 | 67,176,489 | convert from saved model to quant. tflite, 'Quantization not yet supported for op: CUSTOM' | <p>I read similar question, <a href="https://stackoverflow.com/questions/64621991/tensorflow-tf2-quantization-to-full-integer-error-with-tfliteconverter-runtime">Tensorflow (TF2) quantization to full integer error with TFLiteConverter RuntimeError: Quantization not yet supported for op: 'CUSTOM'</a><br />
Howev... | <p>Can you try to use the flags</p>
<pre><code>converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
converter.experimental_new_quantizer = True
</code></pre>
<p>instead.</p>
<p>"TFLITE_BUILTINS_INT8" indicates a fully quantized op set and we don't have the quantized kernel for the custom op.... | tensorflow-lite|quantization | 1 |
373,676 | 67,077,583 | Correctly Load Binary Mask/GIF with PIL and Imageio | <p>I have to load a gif containing a binary mask in Python.</p>
<p><a href="https://i.stack.imgur.com/IQpDA.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IQpDA.gif" alt="inputmask" /></a></p>
<pre><code>import numpy as np
from PIL import Image
import imageio
from matplotlib import pyplot as plt
... | <p>If you do this:</p>
<pre><code>im = Image.open('mask.gif')
print(im)
</code></pre>
<p><strong>Output</strong></p>
<pre><code><PIL.GifImagePlugin.GifImageFile image mode=P size=683x512 at 0x7FC0C86FF430>
</code></pre>
<p>you will see that your image is a <strong>palette</strong> image - because <code>mode=P</co... | python|numpy|python-imaging-library|python-imageio | 2 |
373,677 | 67,154,206 | pandas groupby then filter by date to get mean | <p>Using pandas dataframes and I'm attempting to get the average number of purchases in the last 90 days for each row(not including the current row itself) based on CustId and then add a new column "PurchaseMeanLast90Days".</p>
<p>This is the code I tried, which is incorrect:</p>
<pre><code>group = df.groupby... | <p>You can do a rolling computation:</p>
<pre><code>df["Date"] = pd.to_datetime(df["Date"], dayfirst=False)
df["PurchaseMeanLast90Days"] = (
(
df.groupby("CustId")
.rolling("90D", min_periods=1, on="Date", closed="both")["Pur... | python|pandas|dataframe|filter|mean | 1 |
373,678 | 67,133,991 | Introducing noise to a binary class | <p>I have a dataset that I'm running classification on and the class itself is binary (0, 1). Essentially I want to introduce some noise to the class column, that is, randomly invert 5% of the classes. I.e. if I had 1000 rows of data I would want to invert the class of 50 of these.</p>
<p>My variables are like</p>
<pre... | <p>There is a way you can do this in a somewhat long one line with <code>np.where</code>. At the moment, I can't seem to remember it. But, I have done a version of this in the past and it's worked just fine. All you're doing is changing one value to something outside of your choices, like a placeholder, changing the ot... | python|numpy | 0 |
373,679 | 66,831,349 | Filter rows by criteria and select multiple columns from a dataframe with python pandas | <p>If I have the following dataframe subset</p>
<pre><code> A B C D E Date
R0 xy 78 io 16 73 2021-03-25
R1 xx 27 ya 80 1 2021-04-20
R2 xx 53 ya 27 44 2021-06-20
R3 xx 65 io 30 84 2021-08-22
R4 xv 9 ui 62 1 2021-08-01
</code></pre>
<p>How can I do with pand... | <p>You just need boolean making for this:</p>
<pre><code>mask=(df['A']=='xx') & (df['C']=='ya')
</code></pre>
<p>Finally:-</p>
<pre><code>result=df[mask]
</code></pre>
<p>Now if you print <code>result</code> you will get your desired output</p> | python|pandas | 0 |
373,680 | 67,168,867 | (Pandas) correct lambda expression to sort column by value @ index position 1 | <p>I am attempting to sort <code>SrcWell</code> by the value's index position 1. I understand there is a keyword argument <code>key</code>, which is similar in behavior to <code>key</code> in <code>sorted</code>, however I receive a ValueError when attempting to sort using <code>key</code>. Here is an example CSV file ... | <p>Try using .str accessor and slicing:</p>
<pre><code>df.sort_values(by="SrcWell", key=lambda x: x.str[1])
</code></pre>
<p>Output:</p>
<pre><code> SrcPlate SrcWell
0 PS000000123456 A4
3 PS000000123456 H6
4 PS000000123456 G6
5 PS000000123456 F6
1 PS000000123456 B7
2 PS0... | python|python-3.x|pandas|numpy | 2 |
373,681 | 66,991,355 | How can I substring to specific character in pandas? | <p>For example, I have 2 columns(1,2), and in table 2 I want to fetch everything until " character.</p>
<p>I wanted to do something like this:</p>
<pre><code>df.columns = ['1','2']
a = df['2'].str[:' " ']
print(a)
</code></pre>
<p>but is not possible since I need a number</p>
<pre><code> column 2 example... | <p>Split the string on <code>"</code> and pick the <code>first</code> element.</p>
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a>:</p>
<pre><code>df['2'].str.split('"').str[0]
</code></pre> | python|pandas|substring|jupyter | 1 |
373,682 | 66,934,896 | Looking to find the sum of a unique member's payment based of whether some dates fall in between a certain time in python | <p>this is my first time asking on the community although I have used the website for help extensively in the past. I was not able to find a solution on this specific problem and I am fairly amatuer at python so having a hard time putting the logic in code although I think the logic is clear enough. I am using python v... | <p>I found a way around it. Essentially, rather than trying to iterate through all the rows, I transformed my data into long form first in Google sheets via transpose and filter (I filtered for all payout months for a member and transposed the results into the rows. I then pushed that into colab and through pd.melt tra... | python|pandas|numpy|loops|group-by | 0 |
373,683 | 66,841,646 | Get new column with groupby and return the maximum to entire group | <p>I want to add a new column with the maximum next_crossing_down for the entire x street.
I have this:</p>
<pre><code>cars = pd.DataFrame({'x': [1,1,1,1,1,1,1,2,2,2,2],
'y': [7,None,13,14,22,None,9,13,14,15,16],
'next_crossing_down': [5,None,10,10,20,None,5,10,10,10,15]})
... | <p>Are you looking for <code>pandas.DataFrame.transform</code>?</p>
<pre><code>import numpy as np
cars['next_crossing_down_max']= cars.groupby(['x'])['next_crossing_down'].transform('max')
cars['next_crossing_down_max'] = np.where(cars['next_crossing_down'].isnull(),
np.nan,
... | python|pandas | 2 |
373,684 | 66,900,782 | Can I use the column name as condition? | <p>I have a pandas dataframe which contains around a hundred columns.
Most of these columns are dates and I want to iterate through all these.</p>
<p>Here is an example :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">date</th>
<th style="text-align: center;">nbDa... | <p><em>Ensure your date columns are converted to datetime for this to work</em></p>
<p>The basic steps I've used are:</p>
<ol>
<li>get pandas to identify the date columns</li>
<li>shift the "date" column by nbDays</li>
<li>compare the shifted date column to the dates in the columns</li>
</ol>
<pre><code>from ... | python|pandas|numpy | 1 |
373,685 | 66,861,558 | Pandas - Boolean value conditional statement not being picked up in function | <p>New to python.</p>
<p>I have a dataset containing a date column formatted as yyyy-mm-dd (%Y%m%d) as datetime64 type. The dataset spans 2 years 2019-2020. I'm trying to write a function that will add the quarter based on the date. I can't get the if statements to recognize the data so everything is coming back as 'Q4... | <pre><code> if 'date' < '2019-04-01':
</code></pre>
<p>This compares two character strings. Nothing in your posted code makes <em>any</em> reference to a data frame.</p>
<p>See <a href="https://stackoverflow.com/questions/50459301/how-to-convert-dates-to-quarters-in-python#50459364">here</a> for converting a dat... | python|pandas | 1 |
373,686 | 66,990,266 | InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [80,16] and labels shape [1280] | <p>I am trying to make an image classifier CNN using TensorFlow. I am trying to load the dataset using a <code>ImageDataGenerator</code>. Like this:</p>
<pre><code>from tensorflow.keras.preprocessing.image import ImageDataGenerator
image_datagen = ImageDataGenerator(rescale=1/255)
IMAGE_DIMS=(200,200)
train_generator ... | <p>This resolution follows from <a href="https://stackoverflow.com/questions/49161174/tensorflow-logits-and-labels-must-have-the-same-first-dimension">this</a> thread.</p>
<pre><code>train_generator = image_datagen.flow_from_directory(
'/Users/Anu/Documents',
target_size=IMAGE_DIMS,
batch_size=80,
class... | python|tensorflow|keras|computer-vision|tensorflow2.0 | 0 |
373,687 | 66,885,220 | How to get coordinates of best object detected with tensorflow 2? | <p>The accepted answer of <a href="https://stackoverflow.com/questions/48915003/get-the-bounding-box-coordinates-in-the-tensorflow-object-detection-api-tutorial">this question</a> says how tensorflow draws the bounding boxes of the detected object however does not show or explain how to retrieve these coordinates. Coul... | <p>You can use most of the code in <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/auto_examples/plot_object_detection_saved_model.html#putting-everything-together" rel="nofollow noreferrer">this</a> documentation here.</p>
<p>Just add the below code for getting the bounding box coord... | python|tensorflow|tensorflow2.0|object-detection-api | 1 |
373,688 | 66,958,544 | Why is matrix multiplication with Numba slow? | <p>I try to find an explanation why my matrix multiplication with Numba is much slower than using NumPy's dot function. Although I am using the most basic code for writing a matrix multiplication function with Numba, I don't think that the significantly slower performance is due to the algorithm. For simplicity, I cons... | <p>The native <code>NumPy</code> implementation works with vectorized operations. If your CPU supports these, the processing is <em>much</em> faster. Current microprocessors have on-chip matrix multiplication, which pipelines the data transfers and vector operations.</p>
<p>Your implementation performs k^3 loop itera... | python|numpy|numba | 2 |
373,689 | 67,053,314 | Why arr.flat.base is different from the a.ravel().base? | <p>I am trying to dig a bit into how Numpy works internally, and I am confused about some stuff regarding the <code>base</code> and the array flattening.</p>
<pre><code>import numpy as np
a = np.arange(12, dtype=int).reshape((3, 4))
</code></pre>
<p>So, we have this easy array. Then I try to use <code>flat</code> and <... | <pre><code>In [82]: a = np.arange(5)
In [83]: b = a.reshape(5,1)
In [84]: c = b.ravel()
In [85]: biter=b.flat
</code></pre>
<p>Now check the databuffer location:</p>
<pre><code>In [86]: a.__array_interface__['data']
Out[86]: (44761168, False)
In [87]: b.__array_interface__['data']
Out[87]: (44761168, False)
In [88]: c.... | python|numpy|numpy-ndarray | 1 |
373,690 | 66,966,170 | pandas.read_csv: keep column as integer while having NaN values | <p>I just converted to Python from R, and now I'm trying to read in data from a csv file.
I was very annoyed with all my integer columns being treated as floats, and after some digging I see that this is the problem:
<a href="https://stackoverflow.com/questions/11548005/numpy-or-pandas-keeping-array-type-as-integer-whi... | <p>You can try using:</p>
<pre><code>df = pd.read_csv('./file.csv', dtype='Int64')
</code></pre>
<p>Edit: So that doesn't work for strings. Instead, try something like this:</p>
<pre><code>for col in df.columns[df.isna().any()].tolist():
if df[col].dtype == 'float':
df[col] = df[col].astype('Int64')
</code>... | python|pandas | 1 |
373,691 | 66,910,047 | Groupby pandas but perform calculation on multiple columns | <p>I have a dataframe like below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">name</th>
<th style="text-align: center;">date</th>
<th style="text-align: center;">col1</th>
<th style="text-align: center;">col2</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-a... | <p>I think, <a href="https://numpy.org/doc/stable/reference/generated/numpy.trim_zeros.html" rel="nofollow noreferrer"><code>np.trim_zeros</code></a> is what you are looking for:</p>
<pre class="lang-py prettyprint-override"><code>>>> import numpy as np; import pandas as pd
>>> df = pd.DataFrame.from_... | python|pandas | 4 |
373,692 | 66,910,807 | How to flag an anomaly in a data frame (row wise)? | <p>Python newbie here, I will like to flag sporadic numbers that are obviously off from the rest of the row.
In simple terms, flag numbers that seem not to belong to each row. Numbers in 100s and 100000s are considered 'off the rest'</p>
<pre><code>import pandas as pd
# intialise data of lists.
data = {'A':['R1', 'R... | <p>I used two conditions here one to check less than 1000 and another one for greater than 99999. Based on this condition, the code will highlight outliers in red color.</p>
<pre><code># Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
... | python|pandas|dataframe|export-to-excel | 2 |
373,693 | 66,947,283 | Creating a Pandas Dataframe and Assigning Values Based on Another Dataframe | <p>I have a dataframe that looks like this:</p>
<pre><code>df1
ticker period calendarDate updated dateKey assetsAverage
WMT Q 2021-01-01 2021-03-31 2021-04-02 100000000
</code></pre>
<p>What I want to do is take these values and put them into another dataframe that looks lik... | <p>Do this.</p>
<pre><code>df2 = df1.copy()
df2.columns = ['ticker', 'period', 'Calendar Date', 'Updated', 'Date Key', 'Assets Average']
</code></pre> | pandas|python-3.6 | 0 |
373,694 | 47,328,397 | Keras ValueError: Error when checking model target: expected dense_18 | <p>I am all done, just stuck in training my NN model in KERAS.
Here is my situation.</p>
<ol>
<li><p>I have a folder, i have 30 CSV files in there , all different name.</p></li>
<li><p>Now, I am doing classification. </p></li>
<li>Each CSV file (5000,3 after reading in an array dfs as shown below is a single training ... | <p>Your labels array is of shape <code>(30,3)</code>, while your model is expecting it to be <code>(None, 5000, 3)</code>. -- Always check the <code>model.summary()</code> to understand what is going on with shapes.</p>
<p>The Dense layers work only on the last dimension, leaving all other dimensions untouched. Since ... | python|python-3.x|numpy|neural-network|keras | 2 |
373,695 | 47,097,161 | Creating filtered Table to remove #N/A in python | <p>I am wanting to create a filtered table to remove #N/A from my table. This can be achieved easily in vba by setting columns 9 to between values of -100 and 100 which should automatically remove #N/A and make the table look like the ideal table. Though I am wanting to do this with python any idea on how this can be... | <p>IIUC you can do it this way:</p>
<pre><code>pd.read_excel(filename).dropna(how='any').to_excel(filename, index=False)
</code></pre> | python|excel|pandas|excel-2010|openpyxl | 0 |
373,696 | 47,514,376 | How to select most recent value pulled using wb api | <p>I currently have this: </p>
<pre><code> industry population
country date
Australia 2017-01-01 NaN NaN
2016-01-01 24.327571 18.898304
2015-01-01 25.396251 18.835267
2014-01-01 27.277007 18.834835
United States2017-0... | <p>Solution is use custom function with <code>bfill</code> and <code>iloc</code> for select first row in group:</p>
<pre><code>df = df.groupby(level=0).apply(lambda x: x.bfill().iloc[0])
print (df)
industry population
country
Australia 24.327571 18.898304
United Sta... | pandas|dataframe|indexing|pandas-groupby | 1 |
373,697 | 47,339,611 | Looping for specific values on a df | <p>On one side I have a massive <code>df</code>:</p>
<pre><code>df1
A B C ....
2005-11-01 5.3 22 6
2005-11-02 5.4 21 4
2005-11-03 5.2 17 7
....
</code></pre>
<p>On the other hand I have a smaller df with the following structure;</p>
<pre><code>df2
dat... | <p>By using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow noreferrer"><code>lookup</code></a></p>
<pre><code>df.lookup(df2.date,df2.index)
Out[1003]: array([ 5.4, 22. , 7. ])
</code></pre>
<p>After assign it back </p>
<pre><code>df2['Value']=df.lookup... | python|pandas | 2 |
373,698 | 47,480,137 | merging multiple data sets with similar columns names | <p>I have a multiple data sets represents multiple economic indicators.
Every data set have 5 columns with the same columns names for every data set.
The columns names are [Date Time, Actual, Consensus, Previous, Revised].
The thing is I want to merge these data sets into a single one to prepare it for future work.
I ... | <p>Still using <code>pd.concat</code></p>
<pre><code>pd.concat([df,df,df],keys=['yourkey1','yourkey2','yourkey3'],axis=1)
Out[234]:
yourkey1 yourkey2 yourkey3
C1 C2 C1 C2 C1 C2
0 1 10 1 10 1 10
1 2 20 2 20 2 20
2 3 3 ... | pandas|dataset | 1 |
373,699 | 47,141,359 | How to calculate factorial in tensorflow? | <p>I am new to tensorflow, I am trying to find a function that calculates the n!.
I saw that one can use the gamma function, which was possible with theano, but did not work for tensorflow.</p>
<pre class="lang-py prettyprint-override"><code>factorial = theano.tensor.gamma(v)
</code></pre>
<p>I am using a for loop t... | <p>Try this: <code>tf.exp(tf.lgamma(x + 1))</code>.</p>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/lgamma" rel="noreferrer"><code>tf.lgamma</code></a> computes the log of the absolute value of Gamma(x) element-wise, so the exponent will give you the raw Gamma(x) value:</p>
<pre><code>>>> sess.... | python|tensorflow|factorial | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.