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 |
|---|---|---|---|---|---|---|
9,900 | 58,465,937 | How to use the first layers of a pretrained model to extract features inside a Keras model (Functional API) | <p>I would like to use the first layers of a pre-trained model --say in Xception up and including the add_5 layer to extract features from an input. Then pass the output of the add_5 layer to a dense layer that will be trainable.</p>
<p>How can I implement this idea?</p> | <p>Generally you need to reuse layers from one model, to pass them as an input to the rest layers and to create a Model object with input and output of the combined model specified. For example alexnet.py from <a href="https://github.com/FHainzl/Visualizing_Understanding_CNN_Implementation.git" rel="nofollow noreferrer... | python|tensorflow2.0|transfer-learning|keras-2|pre-trained-model | 1 |
9,901 | 69,118,850 | Convert a date with string format to timestap in a loop | <p>I have a dict with dates, some are timestamps, some date as string.
I would like to iterate over a dict. If the val is as sting, convert it to a timestamp. If not only print it.</p>
<pre><code>import pandas as pd
ts = pd.Timestamp('2017-01-01T12')
date = '2017-01-01'
timedict = {
"timestamp": ts,
&quo... | <p>Something like this?</p>
<p>Using <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow noreferrer"><code>datetime</code></a> to parse and format the string</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
import pandas as pd
ts = pd.Timestamp("2017-01-01T12&q... | python|pandas|date|timestamp | 2 |
9,902 | 69,259,069 | Transpose rows of a Multi-index df into columns | <p>I have a df that looks like this:</p>
<pre><code> pid time
id vid
id1 vis_id1 pid1 t_0
vis_id1 pid2 t_1
id2 vis_id2 pid1 t_3
vis_id2 pid2 t_4
vis_id2 pid3 t_5 ... | <p>We can enumerate groups using <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby cumcount</code></a> based on level=0, add as an additional level of the index (<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.... | python|pandas|dataframe|pivot|multi-index | 0 |
9,903 | 69,188,132 | How to convert all float64 columns to float32 in Pandas? | <p>Is there a generic way to convert all float64 values in a pandas dataframe to float32 values? But not changing uint16 to float32? I don't know the signal names in advance but just want to have no float64.</p>
<p>Something like:</p>
<pre><code>if float64, then convert to float32, else nothing?
</code></pre>
<p>The st... | <p>Try this:</p>
<pre><code>df[df.select_dtypes(np.float64).columns] = df.select_dtypes(np.float64).astype(np.float32)
</code></pre> | python|pandas|type-conversion|dtype | 3 |
9,904 | 68,876,300 | How to insert values of one tensor into another? | <p>I am trying to insert tensor y into the tensors x final dimension (y_dim). The final tensor should be of size (100, 16, 16, 1) where the values of y are placed in each of 100 x 0dimension</p>
<pre><code>import torch
y_dim = 1
x = torch.randn(100, 16, 16, y_dim)
#OR x = torch.randn(100, 16, 16)
y = torch.randn(100)
... | <p>I think you are missing something in your understanding of tensors and dimensions. The easiest thing is to consider your tensor <code>x</code> as a batch containing <code>100</code> maps of width and height <code>16</code>, <em>i.e.</em> <code>100</code> <code>16x16</code>-maps. So you are manipulating a tensor cont... | python|pytorch | 1 |
9,905 | 69,106,204 | probleme of neural network :mat1 and mat2 shapes cannot be multiplied | <p>I implemented a simple neuron network like this:</p>
<pre class="lang-py prettyprint-override"><code>import torch
from torch import nn
class Simple_NN(nn.Module):
'''
Multilayer Perceptron.
'''
def __init__(self, input_dim):
super().__init__()
self.input = input_dim
#self.out = out_dim
sel... | <p>As you didn't provide more details, here's 2 possible ways to solve this:</p>
<ol>
<li><p>If the <code>batch_size=2</code>, the <code>input_dim</code> should be 6, not 2:</p>
<pre class="lang-py prettyprint-override"><code>model = Simple_NN(input_dim = outputs.shape[1]) # change [0] to [1]
</code></pre>
</li>
<li><... | python|neural-network|pytorch|runtime-error | 0 |
9,906 | 60,819,177 | Calling a multiple argument function generated by 'lambdify' on numpy array | <p>I wrote an expression f in SymPy as shown in the code and then converted into a function using <code>lambdify</code>. Then, I vectorzed it using <code>np.vectorize(f)</code>to be able to apply it on a numpy array.</p>
<pre><code>import numpy as np
from math import exp
a = Symbol('a')
x = Symbol('x')
b = Symbol('b')... | <pre><code>In [8]: print(f.__doc__)
Created with lambdify. Signature:
func(x, arg_1)
Expression:
(exp(x*(-a - b)) + 4 - 2*exp(-c*x) - 2*exp(-a*x))*exp(x*(-a - b - c))
Source code:
def _lambdifygenerated(x, _Dummy_166):
... | python|numpy|vectorization|sympy | 2 |
9,907 | 71,452,274 | explode the pandas nested array in python | <p>I am reading data from MongoDB and dropping in s3. Reading the data using Athena.</p>
<p>This is my collection which contains Items columns which is an array. How to explode that into separate columns when saving that to s3.</p>
<pre><code>{"_id":{"$oid":"11111111"},
"receiptId&quo... | <p>You could use <code>json_normalize</code>:</p>
<pre><code>out = pd.json_normalize(data, ['items'], list(data.keys() - {'items'}), record_prefix = 'items.')
</code></pre>
<p>Another option is to create a DataFrame with <code>data</code>; then <code>explode</code> and build a DataFrame separately with "items"... | python-3.x|pandas|dataframe|json-normalize|pandas-explode | 1 |
9,908 | 71,569,951 | Iterate dataframe and assign value to each row- I get the same value while I want different ones | <p>I'm using the library isbntools to assign book titles to isbns. From a dataframe that has isbns, I want to create a column named title and assign the title to the corresponding isbn. Problem is I get the same title.</p>
<p>Example dataframe:</p>
<p><code>isbn</code></p>
<p><code>01234567</code></p>
<p>Desidred outpu... | <p>Use:</p>
<pre><code># isbnlib is already installed as a dependency of isbntools
import isbnlib
def get_title(isbn):
try:
return isbnlib.meta(isbn)['Title']
except isbnlib.NotValidISBNError:
return None
df['Title'] = df['isbn'].astype(str).map(get_title)
</code></pre>
<pre><code>>>>... | python|python-3.x|pandas|dataframe | 0 |
9,909 | 71,661,634 | How to get only column value of a dataframe (without reference formula) | <p>I want to get only column value of csv file rather then reference formula.</p>
<pre><code> df_csv = pd.read_csv(file_name)
print(df_csv["column_head"])
</code></pre>
<p>the output is not the value. It is a csv reference formula.</p>
<pre><code>0 =ROUND(IF(J2,I2/J2,0),4)
1 =ROUND(IF(J3,I3/J3,0),4)
</... | <p>Something seems to be wrong with the format of the file you read from.
I checked on a spreadsheet containing formulas for some cells. here as an example:</p>
<p><a href="https://i.stack.imgur.com/ApniF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ApniF.png" alt="XLTest" /></a></p>
<p>The 'D' co... | python|pandas|dataframe|csv | 1 |
9,910 | 71,608,715 | Having trouble expanding/normalizing a dataframe column of dictionary values into a dataframe/ other columns | <p><img src="https://i.stack.imgur.com/qciwZ.png" alt="enter image description here" /></p>
<p>I'm trying to expand a dataframe column of dictionaries into it's own dataframe/other columns. I have already tried using json_normalize, iteration, and list comprehension but for some reason it just returns a blank dataframe... | <p>The issue is the elements in the 'Ambience' are strings not dictionaries. You just need to convert to dictionaries first before using <code>json_normalize</code>. You can do this using the <code>literal_eval</code> function within the ast Python package.</p>
<pre><code>yelp_df['Ambience'] = yelp_df['Ambience'].appl... | python|json|pandas|dataframe | 1 |
9,911 | 42,562,199 | How to find common name from index(first) column using python? | <p>find common name from index(first) column using python and sum it's following column from same row.</p>
<h2>For example I have below two csv.</h2>
<pre><code>df1
Name sub1 sub2 sub3
X 1 2 5
Y 4 5 6
df2
Name sub1 sub2 sub3
A 3 5 3
Y 3 ... | <p>Pandas merge with on = 'Name' will give you only the rows with common name. You can then drop unnecessary columns and find mean of sub3 like this.</p>
<pre><code>df_result = pd.merge(df2, df1, on = 'Name')
df_result['sub3'] = df_result[['sub3_x', 'sub3_y']].mean(axis = 1)
df_result = df_result.drop(['sub3_x','sub1_... | python|pandas | 1 |
9,912 | 43,383,151 | Convert boolean DataFrame to binary number array | <p>I have a boolean pandas DataFrame, as follow</p>
<pre><code>aaa = pd.DataFrame([[False,False,False], [True,True,True]])
</code></pre>
<p>I want to convert it to a binary number array, for this DataFrame "aaa",
the result is [000,111]</p>
<p>How can I implement this conversion?</p>
<p>Any help will be greatly app... | <p>You can do:</p>
<pre><code>aaa = pd.DataFrame([[False,False,False],
[True,True,True]])
aaa=aaa.astype(int)
</code></pre>
<p>Then <code>aaa</code> is</p>
<pre><code> 0 1 2
0 0 0 0
1 1 1 1
</code></pre>
<p>If you want to get the array <code>['000','111']</code> you can do:<... | python|pandas | 5 |
9,913 | 43,220,729 | access elements from matrix in numpy | <p>I have a matrix A mXn and an array of size m
The array indicates the index of column which has to be index from A.
So, an example would</p>
<pre><code>A = [[ 1,2,3],[1,4,6],[2,9,0]]
indices = [0,2,1]
</code></pre>
<p>The output I want is</p>
<p><code>C = [1,6,9]</code> (corresponding values from each row of mat... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">advanced indexing</a>:</p>
<pre><code>A = np.array([[ 1,2,3],[1,4,6],[2,9,0]])
indices = np.array([0,2,1])
# here use an array [1,2,3] to represent the row positions, and combined with indices ... | python|numpy | 3 |
9,914 | 43,401,393 | What is a _Head object in Tensorflow? | <p>Looking at the docs for <a href="https://www.tensorflow.org/versions/r1.1/api_docs/python/tf/contrib/learn/DNNLinearCombinedEstimator" rel="nofollow noreferrer">DNNLinearCombinedEstimator</a>, I see the first param is a _Head object:</p>
<blockquote>
<p>Args:</p>
<p>head: A _Head object.</p>
</blockquote>
<... | <p>I found this: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/estimators/head.py#L53" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/estimators/head.py#L53</a></p>
<blockquote>
<p>Interface fo... | tensorflow | 4 |
9,915 | 43,227,040 | Why does transposing a numpy array rotate it 90 degrees? | <p>I am trying to read images from an <code>lmdb</code> <code>dataset</code>, augment each one and then save them into another <code>dataset</code> for being used in my trainings.<br>
These images axis were initially changed to <code>(3,32,32)</code> when they were being saved into the <code>lmdb dataset</code>, So in ... | <p>First, look closely. The transoposed array is not rotated but mirrored on the diagonal (i.e. X and Y axes are swapped).</p>
<p>The original shape is <code>(3,32,32)</code>, which I interpret as <code>(RGB, X, Y)</code>. However, <code>imshow</code> expects an array of shape <code>MxNx3</code> - the color informatio... | python|numpy|matplotlib|scipy|caffe | 10 |
9,916 | 72,186,590 | Cartesian product for values in a single row pandas df | <p>I have a df with 14 columns and 20,000 rows. I would like to create a two column dataframe that represents each unique pairing for the data entries within each single row. Example:</p>
<pre><code>#sample df:
data = {'first': ['red', 'blue', 'yellow'],
'second': ['blue', 'pink', 'orange'],
'third'... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import combinations
combo = df.apply(lambda row: list(combinations(row, 2)), axis=1).explode().to_list()
pd.DataFrame(combo, columns=["pairA", "pairB"])
</code></pre> | python|pandas|dataframe | 1 |
9,917 | 72,147,167 | Add a comma after two words in pandas | <p>I have the following texts in a df column:</p>
<pre><code>La Palma
La Palma Nueva
La Palma, Nueva Concepcion
El Estor
El Estor Nuevo
Nuevo Leon
San Jose
La Paz Colombia
Mexico Distrito Federal
El Estor, Nuevo Lugar
</code></pre>
<p>What I need is to add a comma at the end of each row but the condition that it is onl... | <p>Given:</p>
<pre><code> words
0 La Palma
1 La Palma Nueva
2 La Palma, Nueva Concepcion
3 El Estor
4 El Estor Nuevo
5 Nuevo Leon
6 San Jose
7 La Paz Colombia
8 Mexico Distrito Fed... | python|pandas|conditional-statements | 0 |
9,918 | 72,185,667 | intersection of two geopandas GeoSeries gives warning "The indices of the two GeoSeries are different." and few matches | <p>I am using geopandas for finding intersections between points and polygons.
When I use the following:</p>
<pre><code>intersection_mb = buffers_df.intersection(rest_VIC)
</code></pre>
<p>I get this output with a warning basically saying there are no intersections:</p>
<pre><code>0 None
112780 None
112781 ... | <p><a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoSeries.intersection.html" rel="nofollow noreferrer"><code>geopandas.GeoSeries.intersection</code></a> is an <em>element-wise</em> operation. From the intersection docs:</p>
<blockquote>
<p>The operation works on a 1-to-1 row-wise manner</p>
</b... | geospatial|intersection|geopandas | 2 |
9,919 | 50,245,076 | How can I rename a column that contains special (Greek) characters | <p>I have a dataframe and in early in my script I name my columns using: </p>
<pre><code>beta = 1.17
names =np.arange((beta-0.05),(beta+0.05),.01)
dfs.columns = [r'$\beta$'+str(i) for i in names]
</code></pre>
<p>Later in the script I want to replace <code>r'$\beta$'</code> with <code>ats</code>.</p>
<p>I have tried... | <p>You need escape special regex characters <code>$</code>:</p>
<pre><code>beta = 1.17
names =np.arange((beta-0.05),(beta+0.05),.01)
dfs = pd.DataFrame(0, columns=names, index=[0])
dfs.columns = [r'$\beta$'+str(i) for i in names]
dfs.columns = dfs.columns.str.replace(r'\$\\beta\$', "ats")
print (dfs)
ats1.119999... | pandas|dataframe|replace | 2 |
9,920 | 50,302,790 | How to feed tensorflow image value of shape (3,3) into targets which has shape (?, 2) | <p>I am trying to feed a value of shape 3,3 into a tensor of shape (?, 2). My question is how do I reshape my (3,3) value so it is compatible with the latter.</p>
<p>Here is my main training loop:</p>
<pre><code>for epoch in range(epochs):
batches = dg.get_mini_batches(batchSize,(128,128), allchannel=False)
f... | <p>You can't.</p>
<p>A tensor with shape <code>(3,3)</code> can't be reshaped (using <code>tf.reshape</code>) into a tensor with shape <code>(?,2)</code> where <code>?</code> is an unknown dimension and <code>2</code> is fixed.</p>
<p>This is because you have <code>3 x 3 = 9</code> elements and <code>9/2 = 4.5</code>... | python|tensorflow | 2 |
9,921 | 50,550,126 | TF DATA API: How to produce tensorflow input to object set recognition | <p>Consider this problem: select a random number of samples from a random subject in an image dataset (like ImageNet) as an input element for Tensorflow graph which functions as an object set recognizer. For each batch, each class has a same number of samples to facilitate computation. But a different batch would have ... | <p><em>There is a very similar answer by @mrry <a href="https://stackoverflow.com/questions/50356677/how-to-create-tf-data-dataset-from-directories-of-tfrecords">here</a>.</em></p>
<h1>Sampling balanced batches</h1>
<p>In face recognition we often use triplet loss (or similar losses) to train the model. The usual way... | tensorflow|tensorflow-datasets | 5 |
9,922 | 45,684,199 | Error when importing tensorflow in Spyder | <p>I just installed tensorflow on the new laptop.</p>
<p>(Anaconda 4.3.24, Python 3.6.1, TensorFlow: 1.2.1, GPU: NVIDIA 1060 6GB)</p>
<p>Four problems currently.</p>
<p><strong>{1} "Failed to load the native TensorFlow runtime" error in Spyder</strong></p>
<pre><code>File "D:/Programs/Codes-Python/OpenCVtest.py", l... | <p>For your {1} question, because you activate Tensorflow in {2}, I guess your Spyder is installed in different enviroment. Maybe you could try to change the python interpreter of Spyder from Preference->Console->Advanced settings.
For {4}, did you install Nvidia Cuda tool?
Hope this will help.</p>
<p>Best,
Robin</p> | python|tensorflow|anaconda|gpu|spyder | 0 |
9,923 | 45,421,820 | How can I read in from a file, then write out to another file only if certain values are in a range? | <p>This is a sample from my peaks_ef.xpk file, which I am reading in. </p>
<pre><code>label dataset sw sf
1H 1H_2
NOESY_F1eF2f.nv
4807.69238281 4803.07373047
600.402832031 600.402832031
1H.L 1H.P 1H.W 1H.B 1H.E 1H.J 1H.U 1H_2.L 1H_2.P 1H_2.W 1H_2.B 1H_2.E 1H_2.J 1H_2.U vol int stat comment flag0 flag8 flag9
0 {1.H2'} ... | <p>by using </p>
<pre><code>shift1=df["1H.P"]
shift2=df["1H_2.P"]
</code></pre>
<p>you are condensining your filter to only one serires, that being your column, when instead you want to filiter on the entire dataframe, for your sake, it will be easier to see as its own function.</p>
<pre><code>def fil(df,oneLow,oneH... | python|pandas|dictionary | 0 |
9,924 | 45,473,434 | Pandas: How can I find col, index where Nan value exists? | <pre><code>In [3]: import numpy as np
In [4]: b = pd.DataFrame(np.array([
...: [1,np.nan,3,4],
...: [np.nan, 4, np.nan, 4]
...: ]))
In [13]: b
Out[13]:
0 1 2 3
0 1.0 NaN 3.0 4.0
1 NaN 4.0 NaN 4.0
</code></pre>
<p>I want to find column name and index where <code>Nan</code> value... | <p>You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> to find the indices where <code>pd.isnull(b)</code> is True:</p>
<pre><code>import numpy as np
import pandas as pd
b = pd.DataFrame(np.array([
[1,np.nan,3,4],
[n... | python|pandas | 5 |
9,925 | 62,672,198 | Error while creating comma separated list from data-frame to pass into SQL query | <p>I am trying to create a comma separated list to pass SQL query.</p>
<p><strong>my code</strong></p>
<pre><code>sql1 = '''select carrier_name, carrier_account, invoice_number, invoice_amount, currency, invoice_date
from invoice_summary where invoice_number in {}'''.format(tuple(data1['invoice_number'].values.tolist()... | <p>Try using <code>join</code> and put the parenthesis inside the string:</p>
<pre><code>sql1 = '''select carrier_name, carrier_account, invoice_number, invoice_amount, currency, invoice_date
from invoice_summary where invoice_number in ({})'''.format(','.join(["'{}'".format(x) for x in data1['invoice_number'... | python|pandas|dataframe | 1 |
9,926 | 62,529,574 | Python df returning NaN instead of values | <p>I'm trying to import a csv file into python but the values won't show.</p>
<pre><code>data = pd.read_csv("test.csv", header=None)
df=pd.DataFrame(data, columns=['time','x','y'])
print(df)
</code></pre>
<p>Output shows as:</p>
<pre><code>time x y
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN Na... | <p>pandas.read_csv() already returns a DataFrame. So you can do it like this:</p>
<pre><code>df = pd.read_csv('/test.csv', header=None, sep = ';')
df.columns = ['time','x','y']
</code></pre> | python|pandas|dataframe | 0 |
9,927 | 62,751,139 | Plotting several plots in matplotlib based on conditions from two columns in dataframe Python? | <p>I have the following dataframe. You can see that each island_id has 1 or more location_id. This dataframe is a very small sample of the real dataframe (13,000,000rows and 4columns).</p>
<pre><code>df = {'location_id': [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8],
'timestamp':['2020-05-26 22:00:52','2020-05-... | <p><code>.groupby</code>, and <code>filter</code> 'location_id' whose count equals or more than three into a new datframe.</p>
<pre><code>df2=df.groupby('island_id').filter(lambda x:x.location_id.nunique()>=2)
</code></pre>
<p>Plot</p>
<pre><code>g=df2.groupby(['location_id','island_id'])
for x, df in g:
df.plo... | python|pandas|matplotlib | 1 |
9,928 | 54,612,188 | one_shot_iterator, placeholder, cannot capture placeholder | <p>I try to make a <code>one_shot_iterator</code> from a data set.</p>
<p>I use placeholder to use less GPU memory and expect that I only have to initialize the iterator for only once.</p>
<p>But I get error:</p>
<pre><code>Traceback (most recent call last):
File "test_placeholder.py", line 18, in <module>
... | <p>Check out the guide for <a href="https://www.tensorflow.org/guide/datasets#creating_an_iterator" rel="nofollow noreferrer">importing data</a></p>
<p>"A one-shot iterator is the simplest form of iterator, which only supports iterating once through a dataset, with no need for explicit initialization. One-shot iterato... | python|tensorflow | 1 |
9,929 | 54,524,856 | Get "RuntimeError: generator raised StopIteration" while trying to update a Pandas dataframe | <p>I have a Pandas dataframe and want to compute bigrams with the following code:</p>
<pre><code>from nltk import bigrams
df['tweet_bigrams'] = df['tweet_tokenized'].apply(lambda x: list(bigrams(x)))
</code></pre>
<p>It was working fine in Jupyter. However, when I tried to run it on Linux terminal, I keep receiving t... | <p>Update your NLTK. You need version 3.4 (or higher, for future readers). Old versions relied on <code>StopIteration</code> handling that changed in Python 3.7.</p> | python|python-3.x|pandas | 2 |
9,930 | 54,570,428 | Rescale matrix by summating over pixels | <p>Is there a quick way to rescale a matrix by simply adding adjacent pixels?</p>
<p>So for a <code>X=N*M</code> matrix you get a <code>Y=(N/n) *(N/m)</code> where <code>n * m</code> is the area I should add the pixel in.</p>
<p>I've been doing that manually (via script) but I think there has to be somewhere a way to... | <p>A pure numpy way would be to reshape the matrix into more axes and sum over the appropiate axes.</p>
<pre><code>Y = X.reshape(X.shape[0]/n, n, X.shape[1]/m, m).sum((1, 3))
</code></pre> | python|numpy|matrix|resize | 2 |
9,931 | 54,424,532 | How can create calculated field in Python similar to excel? | <p>I want to migrate pivot tables from Excel to python, for using visualizations and others. I use two calculated fields in excel, so I want to know if is possible using similar idea with Pandas ?
Thanks.</p> | <p>Not sure what your data looks like, but this definitely possible with pandas. </p>
<p>Here's an example:</p>
<pre><code># example dataframe
df = pd.DataFrame({'age': [17, 23, 4, 27],
'name': ['John', 'Mark', 'Alice', 'Alice']})
</code></pre>
<p><strong>Output1</strong></p>
<pre><code> age ... | python|pandas | 2 |
9,932 | 73,764,681 | numpy array replace value with a conditional loop | <p>I have a numpy array,</p>
<pre><code>myarray= np.array([49, 7, 44, 27, 13, 35, 171])
</code></pre>
<p>i wanted to replace the values if it is greater than <code>45</code>, so i applied the below code</p>
<pre><code>myarray=np.where(myarray> 45,myarray - 45, myarray)
</code></pre>
<p>but this is applied only once ... | <p>Well the subtraction happens only once, since you did the operation only once, hence 171 - 45 => 126 and the operation has completed. Try using the modulo operator if you wanna do it this way.</p>
<pre><code>myarray = np.array([49, 7, 44, 27, 13, 35, 171])
myarray = np.where(myarray> 45, myarray % 45, myarray... | python|arrays|numpy | 2 |
9,933 | 52,055,014 | Fill NAs forwards or backwards if values in other columns are the same | <p>Given this example:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
"date": ["20180724", "20180725", "20180731", "20180723", "20180731"],
"identity": [None, "A123456789", None, None, None],
"hid": [12345, 12345, 12345, 54321, 54321],
"hospital": ["A", "A", "A", "B", "B"],
"result": [70, N... | <p>Use <code>groupby</code> and <code>apply</code> in combination with <code>ffill</code> and <code>bfill</code>:</p>
<pre><code>df['identity'] = df.groupby(['hid', 'hospital'])['identity'].apply(lambda x: x.ffill().bfill())
</code></pre>
<p>This will fill NaNs forward <em>and</em> backwards while separating the valu... | python|pandas|missing-data|fillna | 1 |
9,934 | 52,140,392 | import tensorflow SyntaxError: invalid syntax | <p><a href="https://i.stack.imgur.com/3vX2a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3vX2a.png" alt="enter image description here"></a></p>
<p>Using Virtualenv on Mac I have encountered the showing SyntaxError when I
import tensorflow
I tried many times uninstall but now working... please h... | <p>Tensorflow is not supported on Python 3.7. You'll need to use python3.6 or earlier.</p>
<p>async which was fine as a variable name in earlier versions of Python, is a keyword in Python 3.7. This is why it is failing to import.</p> | macos|tensorflow | 2 |
9,935 | 52,421,855 | Group rows where columns have values within range in pandas df | <p>I have a pandas df: </p>
<pre><code>number sample chrom1 start chrom2 end
1 s1 1 0 2 1500
2 s1 2 10 2 50
19 s2 3 3098318 3 3125700
19 s3 3 3098720 3 3125870
20 s4 3 3125694 3 3126976
20 s1 3 3125694 3 3126976
20 s1 3 3125695 3 3126976
20 s5 3 3125700 3 3126... | <p>Interval overlaps are easy in <a href="https://github.com/biocore-ntnu/pyranges" rel="nofollow noreferrer">pyranges</a>. Most of the code below is to separate out the starts and ends into two different dfs. Then these are joined based on an interval overlap of +-10:</p>
<pre><code>from io import StringIO
import pan... | python|python-2.7|pandas | 0 |
9,936 | 60,402,309 | Pandas Groupby at least 1 of 2 columns match | <p>I have a pandas df with a column for Names and 2 columns for 2 possible birth years. I want to groupby the name and birthyears, if at least one of the birthyear columns match.</p>
<pre><code>FullName BirthYr1 BirthYr2
Smith, Joe 1985 1986
Dolan, Tom 1991 1992
Smith, Alex 1984 1985
Smith, Jo... | <p>This feels overcomplicated, but I think it achieves what you're looking for. Assuming your starting DataFrame is named <code>df</code>:</p>
<pre><code># "Melt" the birth year columns such that each value is given its own
# row. Throw away the redundant column names BirthYr1 and BirthYr2,
# since their values are e... | python|pandas | 1 |
9,937 | 60,606,292 | Dataframe groupby to new dataframe | <p>I have a table as below.</p>
<pre><code>Month,Count,Parameter
March 2015,1,40
March 2015,1,10
March 2015,1,1
March 2015,1,25
March 2015,1,50
April 2015,1,15
April 2015,1,1
April 2015,1,1
April 2015,1,15
April 2015,1,15
</code></pre>
<p>I need to create a new table from above as shown below.</... | <p>IIUC, just check for <code>Parameter < 30</code> and then groupby:</p>
<pre><code>(df.assign(le_30=df.Parameter.le(30))
.groupby('Month', as_index=False) # pass sort=False if needed
[['Count','le_30']].sum()
)
</code></pre>
<p>Or</p>
<pre><code>(df.Parameter.le(30)
.groupby(df['Month']) # pass sort=... | python|pandas|dataframe | 0 |
9,938 | 60,378,262 | How to keep the dimensions when using the basic arithmetic operations with Numpy | <p>Recently I encounter a dimension problem and has to reshape the array after each calculation. For example,</p>
<pre><code>a=np.random.rand(2,3,4)
t=2
b=a[:,1,:] + a[:,2,:]*t
</code></pre>
<p>The second axis of <code>a</code> is reduced automatically and <code>b</code> becomes a 2x4 array. How to keep the shape of ... | <p>Convert the integer indies into lists:</p>
<pre><code>>>> b = a[:,[1],:] + a[:,[2],:]*t
>>> b.shape
(2, 1, 4)
</code></pre> | python|numpy | 1 |
9,939 | 60,341,348 | Merge multiple dataframes without common columns | <p>I have 2 datasets.</p>
<pre><code>dict1 =pd.DataFrame({'Name' : ['A','B','C','D'], 'Score' : [19,20,11,12]})
list1 =pd.DataFrame(['Math', 'English', 'History', 'Science'])
concat_data = pd.concat([dict1,list1])
</code></pre>
<p>output :</p>
<pre><code>Name Score 0
0 A 19.0 NaN
1 B 20.0 ... | <p>All you need to do is pass the correct <code>axis</code>. The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer">default behavior for concat</a> is <code>axis=0</code> which means the operation takes place index-wise or row-wise, while you are needing th... | python|pandas|dataframe | 1 |
9,940 | 60,713,502 | Reshaping dataframe with multiple IDs | <p>I need helo creating the format transformation:</p>
<p><a href="https://i.stack.imgur.com/7fiW5.png" rel="nofollow noreferrer">See here</a></p>
<p>I have created pd.wide_to_long but I cannot find an example identical to mine?</p>
<p>Can you help?</p> | <p>Use:</p>
<pre><code>df.set_index(['City','Var']).rename_axis(columns='Year').stack().unstack('Var')
</code></pre> | python|pandas | 1 |
9,941 | 59,733,941 | Create a new col in pandas with element of other columns | <p>Hel lo, I would need help.</p>
<p>I have a dataframe such as :</p>
<p>table: </p>
<pre><code>Col1 Col2 Col3 Sign
Loc1 1 60 -
Loc2 10 90 +
Loc3 40 100 +
Loc4 20 40 -
</code></pre>
<p>and from this table I want to create a <code>Newcol</code> with elements in others columns such as : <... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofollow noreferrer"><code>Series.astype</code></a> for convert to strings and for add <code>1</code> compare by <code>+</code> and convert value to integer with <a href="http://pandas.pydata.org/pandas-docs/stable... | python-3.x|pandas | 2 |
9,942 | 59,777,735 | Generate equally-spaced values including the right end using NumPy.arange | <p>Suppose I want to generate an array between 0 and 1 with spacing 0.1. In R, we can do </p>
<pre><code>> seq(0, 1, 0.1)
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
</code></pre>
<p>In Python, since <code>numpy.arange</code> doesn't include the right end, I need to add a small amount to the <code>stop</code>... | <p>You should be very careful using <code>arange</code> for floating point steps.
<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow noreferrer">From the docs</a>:</p>
<blockquote>
<p>When using a non-integer step, such as 0.1, the results will often not be consistent. It ... | python|numpy | 4 |
9,943 | 61,650,749 | Sorting pandas column based on number in the suffix after underscore | <p>I have a Dataframe with the below set of columns:</p>
<pre><code>bill_id, product_1, product_20, product_300, price_1, price_20, price_300, quantity_1, quantity_20, quantity_300
</code></pre>
<p>I would like this to be sorted in the below sequence based on the number after the underscore at the end of each column ... | <p>Use <code>sorted</code> with lambda function by number after <code>_</code> by all columns without first and then change order by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a>:</p>
<pre><code>c = 'bill_i... | pandas|sorting | 2 |
9,944 | 57,750,706 | simultaneously update theta0 and theta1 to calculate gradient descent in python | <p>I am taking the machine learning course from coursera. There is a topic called gradient descent to optimize the cost function. It says to simultaneously update theta0 and theta1 such that it will minimize the cost function and will reach to global minimum. </p>
<p>The formula for gradient descent is </p>
<p><a hre... | <p>What it means is that you use the previous values of the parameters and compute what you need on the right hand side. Once you're done, update the parameters. To do this the most clearly, create a temporary array inside your function that stores the results on the right hand side and return the computed result when ... | python|numpy|machine-learning|linear-regression|gradient-descent | 5 |
9,945 | 54,958,194 | How do I convert a number to thousand separator using comma? | <p>I have a pandas dataframe, some rows are number, i want to convert them to thousand separator. Tried this <code>thousands=','</code>but not working, tried other solutions but how can i convert whole dataframe into thousand separator before <code>to_csv</code> </p>
<p><strong>Example what i want:</strong>
convert <c... | <p>You could manually add the commas like this (only works with numbers smaller than 1,000,000,000):</p>
<pre><code>thousandSeperatedStrings=[]
for x in df:
string=""
if(x>=1000000):
x=x%1000000000
string=str(int(x/1000000))+","
x=x%1000000
string=string+str(int(x/100000))
... | python|pandas | 1 |
9,946 | 49,590,478 | Are the libtensorflow_jni and libtensorflow_jni_gpu jar dependencies mutually exclusive? | <p>If we add both the libtensorflow_jni and the libtensorflow_jni_gpu to the maven pom or perhaps something like this:</p>
<pre><code><dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow</artifactId>
</dependency>
<dependency>
<groupId>org.tenso... | <p>I believe i have an answer of my question. </p>
<p>Based on the <code>libtensorflow_jni</code> and <code>libtensorflow_jni_gpu</code> jars structure and the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/java/src/main/java/org/tensorflow/NativeLibrary.java" rel="nofollow noreferrer">Native... | java|tensorflow|native | 0 |
9,947 | 49,635,436 | Shapely point geometry in geopandas df to lat/lon columns | <p>I have a geopandas df with a column of shapely point objects. I want to extract the coordinate (lat/lon) from the shapely point objects to generate latitude and longitude columns. There must be an easy way to do this, but I cannot figure it out.</p>
<p>I know you can extract the individual coordinates like this:</p... | <p>If you have the latest version of geopandas (0.3.0 as of writing), and the if <code>df</code> is a GeoDataFrame, you can use the <code>x</code> and <code>y</code> attributes on the geometry column:</p>
<pre><code>df['lon'] = df.point_object.x
df['lat'] = df.point_object.y
</code></pre>
<p>In general, if you have a... | python|gis|latitude-longitude|geopandas|shapely | 29 |
9,948 | 49,511,742 | how to find tfslim output node names | <p>After training some model with tensorflow and slim, I am trying to freeze the model and weights. But it's quite hard for me to find out the output nodes name, which is necessary for <code>freeze_graph.freeze_graph()</code>.</p>
<p>my output layers looks like:</p>
<pre><code> conv4_1 = slim.conv2d(net,num_outputs=2... | <p>Output Node names for the 3 of the inception models are given below:</p>
<p>inception v3 : InceptionV3/Predictions/Reshape_1 <br/>
inception v4 : InceptionV4/Logits/Predictions <br/>
inception resnet v2 : InceptionResnetV2/Logits/Predictions</p> | tensorflow|tensorflow-slim | 1 |
9,949 | 73,367,863 | How to create 1 row dataframe from a dataset in pandas | <p>I have a .csv file with many rows and columns. For analysis purposes, I want to select a row number from the dataset and pass it as a dataframe in pandas.</p>
<p>Instead of writing the column names and input values inside a dict, how can I make it faster?
Right now I have:</p>
<pre><code>df= pd.read_csv('filename.cs... | <pre class="lang-py prettyprint-override"><code>df2 = df.iloc[rownum:rownum + 1, :]
</code></pre> | python|python-3.x|pandas|dataframe | 0 |
9,950 | 73,325,035 | Most efficient way to take max of classifier scores in Python and / or PySpark | <p>I have a dataframe with the scores of a two-class classification model...</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Observation</th>
<th>Class</th>
<th>Probability</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0</td>
<td>0.5013</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0.4987</td... | <p>To select some rows in a df by some rule you can use .loc or .query:</p>
<p>timing: 300 µs ± 6 µs per loop</p>
<pre><code>df.loc[df['Class']==0]
</code></pre>
<p>timing: 1.17 ms ± 53 µs per loop</p>
<pre><code>df.query('Class == 0')
</code></pre> | pandas|dataframe|pyspark|data-science | 0 |
9,951 | 67,503,053 | ValueError in Custom Keras Layer | <p>I implemented a custom layer for Minibatch Standard Deviation:</p>
<pre><code>class MinibatchStd(Layer):
def __init__(self, group_size=4, epsilon=1e-8):
super(MinibatchStd, self).__init__()
self.epsilon = epsilon
self.group_size = group_size
def call(self, input_tensor):
n, h, w, c =... | <p>There are two ways to get tensor shapes for some tensor (say <code>x</code>): <code>x.shape</code> and <code>tf.shape(x)</code>. These two are fundamentally different: The former simply returns a python list of the shape, and the latter adds an op in the dynamic computation graph, including placeholders for <code>No... | python|tensorflow|keras|tensorflow2.0|tf.keras | 1 |
9,952 | 67,438,792 | How to calculate roc auc score from positive unlabeled learning? | <p>I'm trying to adapt some code for positive unlabeled learning from <a href="https://github.com/phuijse/bagging_pu/blob/master/PU_Learning_simple_example.ipynb" rel="nofollow noreferrer">this example</a>, which runs with my data but I want to also calculate the ROC AUC score which I'm getting stuck on.</p>
<p>My data... | <p><code>y_pred</code> must be a single number, giving the probability of the positive class <code>p1</code>; currently your <code>y_pred</code> consists of both probabilities <code>[p0, p1]</code> (with <code>p0+p1=1.0</code> by definition).</p>
<p>Assuming that your positive class is class <code>1</code> (i.e. the se... | python|numpy|machine-learning|scikit-learn|auc | 2 |
9,953 | 60,095,584 | pandas pivot_table: can I display sub-totals in the output? | <p>Suppose I have a very simple dataframe, like so:</p>
<pre><code>data={"Label": (1,1,1,2,2,2,2,3,3), "Value": ("a","b","b","b","c","a","b","a","c")}
df = pd.DataFrame(data = data)
</code></pre>
<p>I can generate a pivot table as follows, by writing <code>pd.pivot_table(testdf,index=["Label", "Value"],values=["Value... | <p>You won't find an explicit equivalent in pandas, but you can always chain multiple functions together. I'll give a <code>groupby</code> example:</p>
<pre><code>import pandas as pd
data={"Label": (1,1,1,2,2,2,2,3,3), "Value": ("a","b","b","b","c","a","b","a","c")}
df = pd.DataFrame(data = data)
df["Top_Level_Count... | pandas|pivot-table | 1 |
9,954 | 60,157,722 | Python - Defining a chunk function to encode genomic data | <p>I'm trying to encode genomes from strings stored in a dataframe to an array of corresponding numerical values. </p>
<p>Here is some of my dataframe (for some reason it doesn't give me all 5 columns just 2):</p>
<pre><code>Antibiotic ... Genome
0 isoniazid ... cc... | <p>You have <code>chunk_filter = preprocess(chunk)</code>, but your <code>preprocess()</code> function returns nothing, so <code>chunk_filter</code> is always meaningless. Modify your preprocess function to store the result of the <code>apply()</code> call, then return that value. For example:</p>
<pre><code>def prepr... | python|pandas|preprocessor|chunks | 1 |
9,955 | 60,120,828 | Fetch value of a specific key from nested dictionary in pandas with python | <p>I am iterating through the rows in pandas dataframe printing out nested dictionaries from the specific column. My nested dictionary looks like this:</p>
<pre><code>{'dek': "<p>Don't forget to buy a card</p>",
'links': {'edit': {'dev': '//patty-menshealth.feature.net/en/content/edit/76517422-96ad-4b5c-a... | <p>Apologies about not directly addressing the original question, but maybe it's worth "flattening" the nested column using <code>json_normalize</code>.</p>
<p>For example, if your example data is named <code>dictionary</code>:</p>
<pre><code>from pandas.io.json import json_normalize
# Flatten the nested dict, resul... | python|pandas|dictionary|nested | 2 |
9,956 | 59,951,043 | To extract distinct values for all categorical columns in dataframe | <p>I have a situation where I need to print all the distinct values that are there for all the categorical columns in my data frame
The dataframe looks like this :</p>
<pre><code>Gender Function Segment
M IT LE
F IT LM
M HR LE
F HR LM
</code></pre>
<p>The output s... | <p>using <code>nunique</code> then passing the series into a new datafame and setting column names. </p>
<pre><code>df_unique = df.nunique().to_frame().reset_index()
df_unique.columns = ['Variable','DistinctCount']
</code></pre>
<hr>
<pre><code>print(df_unique)
Variable DistinctCount
0 Gender 2
1... | python-3.x|pandas|pandas-groupby | 5 |
9,957 | 65,311,782 | Failed Qiskit installation with Anaconda on Windows | <p>I'm attempting to install Qiskit via pip and Anaconda on my machine. Here's my process</p>
<p>1.) Install Anaconda
2.) Open Anaconda 3 prompt
3.) Create a virtual environment using <code>conda create -n <environment-name> python=3</code> command (I've created the environment on different occasions using -n and... | <p>The issue is that you're running on Python 3.9. The currently released versions of Qiskit did not have support for Python 3.9 and therefore didn't include precompiled binaries for 3.9 environments. So what is happening is that pip is trying to build Qiskit from source, as a fallback because compatible binaries were ... | python|numpy|pip|anaconda|qiskit | 3 |
9,958 | 65,280,541 | operating on pairs of columns in R (or numpy) | <p>I have two matrices: A (k rows, m columns), B(k rows, n columns)</p>
<p>I want to operate on all pairs of columns (one from A and one from B), the result should be a matrix C (m rows, n columns) where C[i,j] = f(A[,i],B[,j])
now, if the function f was the sum of the dot product, then the whole thing was just a simpl... | <p>In <code>R</code>, we can <code>split</code> them into <code>list</code> and apply the function <code>f</code> with a nested <code>lapply/sapply</code></p>
<pre><code>lapply(asplit(A, 2), function(x) sapply(asplit(B, 2), function(y) f(x, y)))
</code></pre>
<hr />
<p>Or using <code>outer</code> after converting to <... | r|numpy|matrix | 1 |
9,959 | 65,303,876 | Reshape Pandas DatafRames by binary columns value | <p>Can't figure out how to reshape my DataFrame into new one by several binary columns value.</p>
<p>Input:</p>
<pre><code>data code a b c
2016-01-07 foo 0 0 0
2016-01-12 bar 0 0 1
2016-01-03 gar 0 1 0
2016-01-22 foo 1 1 0
2016-01-26 bar 1 1 0
</code></pre>
<p... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with filtering <code>1</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code... | python|pandas|dataframe|numpy|reshape | 2 |
9,960 | 65,364,061 | Create dynamic ranges and calculate mean | <p>I would like to create an additional column with averages based on column A, using dynamic ranges.</p>
<pre><code>import numpy as np
import pandas as pd
test = {'A' : [100, 120, 70, 300, 190, 70, 300, 190, 70],
'B' : [80, 50, 64, 288, 172, 64, 288, 172, 64],
'C' : ['NO', 'NO', 'YES', 'NO', 'YES'... | <p>Let's try:</p>
<pre><code>s = df['A'].cumsum().shift(fill_value=0)
df['Dyn_Ave'] = np.where(df['C'] == 'YES',
(s - s.reindex(df['D']).values) / (np.arange(len(df)) - df['D']),
np.nan)
</code></pre>
<p>Output:</p>
<pre><code> A B C D Dyn_Av... | python|pandas|dataframe|mean | 2 |
9,961 | 65,390,694 | Running TensorFlow with XLA tf.function throws error | <p>When I'm trying to compile this <a href="https://www.tensorflow.org/xla/tutorials/jit_compile" rel="nofollow noreferrer">code</a>, getting the below error.</p>
<pre><code>File "xla_test.py", line 25, in <module>
@tf.function(jit_compile=True)
TypeError: function() got an unexpected keyword argume... | <p>Without switching to tf-nightly just use:</p>
<pre><code>@tf.function(experimental_compile=True)
</code></pre>
<p>From the <a href="https://www.tensorflow.org/api_docs/python/tf/function#args_1" rel="nofollow noreferrer">tensorflow docs</a>:</p>
<blockquote>
<p>experimental_compile If True, the function is always c... | tensorflow2.0|tensorflow-xla | 1 |
9,962 | 50,037,654 | Tensorflow: load images into memory only when needed | <p>I am using TensorFlow V1.7 with the new high-level Estimator interface. I was able to create and train my own network with my own dataset. </p>
<p>However, the policy I use to I load images just doesn't seem right to me.
The approach I have used so far (largely inspired by the MNIST tutorial) is to <strong>load all... | <p>It's advised to use the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer">Dataset</a> module, which provides you the ability (among other things) to use queues, prefetching of a small number of examples to memory, number of threads and much more.</p> | python|image|memory|tensorflow|load | 2 |
9,963 | 64,126,592 | tensorflow versioning mis-match in python | <p>I have no idea, why my python is acting so weirdly. I had tensorflow-2.3, as that doesn't go with cuda-10.1, so I had to go back to tensorflow-2.1. So my commands were :</p>
<pre><code>pip uninstall tensorflow tensorflow-gpu
pip install tensorflow==2.1.0 tensorflow-gpu==2.1.0
</code></pre>
<p>But when I try to use t... | <p>You are installing to python3.6.
But your “python” command is executing python3.7
Try typing python3.6</p>
<p>PS: Use conda for python environment management.</p> | python|tensorflow|tensorflow2.0 | 1 |
9,964 | 63,869,177 | Fetch Bitcoin Data Information through Pandas DataReader | <p>I am wanting to ask if Pandas DataReader may be used to extract Bitcoin information from blockchain.com ?</p>
<p>I am aware we may use it together with Alpha Vantage API Key to extract stocks through:</p>
<pre><code>import pandas as pd
import pandas_datareader as dr
reader = dr.DataReader('AAPL', 'av-daily', start =... | <p>Querying Bitcoin prices with <code>pandas_datareader</code> should be straightforward:</p>
<pre><code>import pandas_datareader as pdr
btc_data = pdr.get_data_yahoo(['BTC-USD'],
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2020, 12, 2))['Close']
</co... | python|pandas|bitcoin|alpha-vantage | 6 |
9,965 | 46,862,722 | Import statments when using Tensorflow contrib keras | <p>I have a bunch of code written using Keras that was installed as a separate pip install and the import statements are written like <code>from keras.models import Sequential</code>, etc..</p>
<p>On a new machine, I have Tensorflow installed which now includes Keras inside the <em>contrib</em> directory. In order to... | <p>Try this with recent versions of tensorflow:</p>
<pre><code>from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import LSTM, TimeDistributed, Dense, ...
</code></pre> | python|tensorflow|keras | 2 |
9,966 | 46,758,620 | Convert string to float pandas | <p>Simple question: I have a dataset, imported from a csv file, containing a string column with numeric values. After the comma are decimal places. </p>
<p>I want to convert to float. Basically,it's just this:</p>
<pre><code>x = ['27,10083']
df = pd.DataFrame(x)
df.astype(float)
</code></pre>
<p>Why does this not wo... | <p>Assign output with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>replace</code></a>:</p>
<pre><code>df = df.replace(',','.', regex=True).astype(float)
</code></pre>
<p>If want specify columns for converting:</p>
<pre><code>cols = ['col1','col2... | python|pandas | 15 |
9,967 | 62,909,908 | Why I have this problem with index range?why does it not work? | <p>I have got this error when try split my one column to few columns. But it split on just on one or two columns.If you wanna split on 3,4,5 columns it writes:</p>
<pre><code>ValueError Traceback (most recent call last)
/usr/local/Cellar/jupyterlab/2.1.5/libexec/lib/python3.8/site-package... | <p>Pandas does not support "unstructured text", you should convert it to a standard format or python objects and then create a dataframe from it</p>
<p>Imagine that you have a file with this text named <code>data.txt</code>:</p>
<pre><code>Contract № 12345679 Number of phone: +7984563774
Total price for month... | python|pandas|numpy|jupyter-notebook | 0 |
9,968 | 63,238,862 | Animate label with bar chart - matplotlib | <p>The code below animates a bar chart and associated label values. The issue I'm having is positioning the label when the integer is negative. Specifically, I want the label to be positioned on top of the bar, not inside it. It's working for the first frame but the subsequent frames of animation revert back to plottin... | <blockquote>
<p>It's working for the first frame.</p>
</blockquote>
<p>You call <code>autolabel(rects, ax)</code> in the first plot, so the label is well placed.</p>
<blockquote>
<p>The subsequent frames of animation revert back to plotting the label inside the bar chart for negative integers.</p>
</blockquote>
<p>The ... | python|pandas|matplotlib|animation | 1 |
9,969 | 62,978,582 | ValueError: only one element tensors can be converted to Python scalars | <p>I'm following <a href="https://medium.com/datadriveninvestor/deep-learning-and-medical-imaging-how-to-provide-an-automatic-diagnosis-f0138ea824d" rel="nofollow noreferrer">this tutorial</a>.</p>
<p>I'm at the last part where we combine the models in a regression.</p>
<p>I'm coding this in jupyter as follows:</p>
<pr... | <p>Only a tensor that contains a single value can be converted to a scalar with <code>item()</code>, try printing the contents of <code>prediction</code>, I imagine this is a vector of probabilities indicating which label is most likely. Using <code>argmax</code> on <code>prediction</code> will give you your actual pre... | python|python-3.x|deep-learning|pytorch | 1 |
9,970 | 67,644,706 | Pandas "read_excel" : How to read multi-line cell from "ods" file? | <p>I've a simple "ods" file (Test01.ods) with the below data in "sheet1" :-</p>
<p><a href="https://i.stack.imgur.com/1lLUk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1lLUk.png" alt="enter image description here" /></a></p>
<p>also I saved it as "xlsx" (Test01.xlsx)... | <p>As per <a href="https://github.com/pandas-dev/pandas/issues/41625" rel="nofollow noreferrer">this issue</a> in Pandas's Github, this is an issue with the upstream "odfpy" package, our options are one of the following:</p>
<ol>
<li>fix upstream (ideal) in odfpy</li>
<li>modify the _get_cell_string_value met... | python|pandas|ods|odf | 0 |
9,971 | 61,390,861 | Resolving a Multi index in a Dataframe for better clarity | <p>So, I split the sentences in a row into single words, and thus, the rows of my dataframe got lengthened. however, I am not satisfied with the new indexes. </p>
<pre><code>0 0 I
1 don
2 '
3 t
4 think
5 any
</code></pre... | <p>Do I understand right that you want to swap the levels of your Multiindex?</p>
<p>Maybe this helps you:</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.swaplevel.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex... | python|pandas|csv|dataframe|indexing | 1 |
9,972 | 61,200,977 | Need to create list using list value which are present in dataframe column | <p>This is my dataframe:</p>
<pre><code>prod_sheet:
Product ID
0 Prod1 00P000000000101
1 Prod2 00P000000000105
2 Prod3 00P000000000109
3 Prod4 00P000000000119
4 Prod5 00P000000000120
L=[Prod2,Prod4,Prod5]
</code></pre>
<p>Id for product which are present in list</p>
<pre><code>needed_list=[0... | <p>Use if order is important list comprehension:</p>
<pre><code>L=['Prod5','Prod4','Prod3']
s = prod_sheet.set_index('Product')['ID']
needed_list = [s[p] for p in L]
print (needed_list)
['00P000000000120', '00P000000000119', '00P000000000109']
</code></pre>
<p>If order is not important use:</p>
<pre><code>needed_li... | python|pandas|list|dataframe | 0 |
9,973 | 61,376,922 | How to get the index of a particular row using column values in numpy? | <p>So if I have the following array arr:</p>
<pre><code>>>> arr
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
</code></pre>
<p>Now if I want to acquire the first row, I would do so... | <p>I think you want to check if the rows are equal to a given array. In which case, you need <code>all</code>:</p>
<pre><code>np.where((arr == [0,1,2,3,4]).all(1))
# (array([0, 3]),)
</code></pre> | python|numpy|indexing|numpy-slicing | 2 |
9,974 | 68,604,281 | How to take two out of order CSV's and match by ID columns from each CSV and Inject the mac address to the matched ID from another CSV? | <p>How to take two out of order CSV's and match by ID columns from each CSV and Inject the mac address to the matched ID from another CSV?</p> | <blockquote>
<p>Takes two CSV's groups two columns from first dict <code>Unique Card ID</code>
and <code>mac</code></p>
<p>then compares it to see if there is a match from second dict for
<code>Bluetooth code</code></p>
<p>If a match is found, it will inject the first dict <code>mac</code> into the
empty column</p>
<p>... | python|pandas|dataframe|csv | 0 |
9,975 | 68,759,373 | How to get new records from second dataframe? | <p>df1:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>StationName</th>
<th>RunID</th>
<th>ScheduledDate</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td>
<td>12345</td>
<td>2021-08-12</td>
</tr>
<tr>
<td>BBB</td>
<td>23456</td>
<td>2021-08-12</td>
</tr>
<tr>
<td>DDD</td>
<td>91273</td>
<td>20... | <p>use <code>merge()</code> with <code>indicator=True</code> and <code>query()</code> to filter out result and <code>drop()</code> to drop extra column:</p>
<pre><code>out=(df1[['RunID']].merge(df2,on='RunID',how='outer',indicator=True)
.query("_merge=='right_only'").drop(columns='_merge'))... | python|pandas | 1 |
9,976 | 65,528,954 | Display number of images per class using Pytorch | <p>I am using Pytorch with FashionMNIST dataset I would like to display 8 image sample from each of the 10 classes. However, I did not figure how to split the training test into train_labels since I need to loop on the labels(class) and print 8 of each class.
any idea how I can achieve this?</p>
<pre><code>classes = ('... | <p>If I understand you correctly you want to group your dataset by labels then display them.</p>
<p>You can start by constructing a dictionnary to store examples by label:</p>
<pre><code>examples = {i: [] for i in range(len(classes))}
</code></pre>
<p>Then iterate over the trainset and append to the list using the labe... | pytorch|tensor|pytorch-dataloader | 1 |
9,977 | 65,796,919 | valueerror: time data does not match dataframe of pandas | <p>df having data as below in pandas</p>
<pre><code>"val1" 6972.75 01-AUG-18 08.11.51.319 AM
"val2" 6974.25 01-OCT-18 08.12.22.322 AM
</code></pre>
<p>I am using the code</p>
<p><code>pd.to_datetime(df['TIME'], format="%d-%m-%Y %H.%M.%S.%f")</code></p>
<p>when i am running the code its gi... | <p>Your format is all messed up. You used the incorrect format for the month and year and you can deal with the AM/PM with <code>%p</code>. (Most of the formats can be found under the <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes" rel="nofollow noreferrer"><code>datetime</c... | python|pandas|dataframe|datetime|runtime-error | 2 |
9,978 | 65,906,171 | Is there a way to retrieve the specific parameters used in a random torchvision transform? | <p>I can augment my data during training by applying a random transform (rotation/translation/rescaling) but I don't know the value that was selected.</p>
<p>I need to know what values were applied. I can manually set these values, but then I lose a lot of the benefits that torch vision transforms provide.</p>
<p>Is th... | <p>I'm afraid there is no easy way around it: Torchvision's random transforms utilities are built in such a way that the transform parameters will be sampled when called. They are <em>unique</em> random transforms, in the sense that <em>(1)</em> parameters used are not accessible by the user and <em>(2)</em> the same r... | python|pytorch|affinetransform|data-augmentation|torchvision | 4 |
9,979 | 63,656,858 | pandas combine stock data if it falls between specific time only in dataframe | <p>I have minute-by-minute stock data from 2017 to 2019.
I want to keep only data after 9:16 for each day
therefore I want to convert any data between 9:00 to 9:16 as value of 9:16
ie:</p>
<p><strong>value of 09:16 should be</strong></p>
<ul>
<li><code>open</code> : value of 1st data from 9:00 - 9:16 , here 116.00</li>... | <hr />
<pre><code>d = {'date': 'last', 'open': 'last',
'high': 'max', 'low': 'min', 'close': 'last'}
# df.index = pd.to_datetime(df.index)
s1 = df.between_time('09:00:00', '09:16:00')
s2 = s1.reset_index().groupby(s1.index.date).agg(d).set_index('date')
df1 = pd.concat([df.drop(s1.index), s2]).sort_index()
</cod... | python|pandas|dataframe|stock | 5 |
9,980 | 63,640,051 | Remove rows from a panda dataframe with unsorted index | <p>This is how my data looks:</p>
<pre><code>print(len(y_train),len(index_1))
index_1 = pd.DataFrame(data=index_1)
print("y_train: ")
print(y_train)
print("index_1: ")
print(index_1)
</code></pre>
<p>Output:</p>
<pre><code>1348 555
y_train:
1677 1
1519 0
1114 0
690 1
1012 1
.... | <p>Note that <code>y_train.iloc[index_1[0]]</code> retrieves rows from <em>y_train</em>
taking indicated integer positions.</p>
<p>When you run <code>y_train.iloc[index_1[0]].index</code>, you will get
<strong>indices</strong> of these rows.</p>
<p>So do drop these rows, you can run:</p>
<pre><code>y_train.drop(y_train... | python|pandas|numpy | 1 |
9,981 | 53,757,429 | Crop a square shape around a centroid (numpy) | <p>I have an numpy array image which contain circles. I extracted the whole x,y centroids (in pixels) of these circles (a numpy array as well). Now, I want to crop a square around each x,y centroid.
Can someone instruct me how to solve it?
Note that I didn't find any question in Stack that deals with crop around a sp... | <p>If your centroid has indices <code>i,j</code> and you want to crop a square of size <code>2*w+1</code> around it on a numpy array <code>a</code>, you can do </p>
<pre><code>a[i-w:i+w+1,j-w:j+w+1]
</code></pre>
<p>This is provided your indices are always more than <code>w</code> from the boundary. </p>
<p>If they'... | python|numpy|coordinates|crop|centroid | 2 |
9,982 | 72,128,434 | Group Dataframe rows while deleting specific columns | <p>I have a dataframe with several columns. I want to group rows based on multiple column values.</p>
<p>My source dataframe looks like this:</p>
<pre><code>category code color property_value price
A xx01 white 128 $10.00
B xx01 white 128 $5.00
... | <p>This seems more like a drop duplicate operation than a grouping operation:</p>
<pre><code># suppose your DataFrame is df
df = df[['category', 'property_value', 'price']].drop_duplicates(keep='first')
</code></pre> | python|pandas|dataframe|grouping | 1 |
9,983 | 71,886,048 | Look in df list, return Boolean if all list elements have a substring | <p>I have a dataframe with a string column that contains a sequence of author names and their affiliations.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>'Smith, Jane (University of X); Doe, Betty (Institute of Y)'</td>
</tr>
<tr>
<td>'Walter, ... | <p>You can use <code>str.extractall</code> to extract all the universities in parentheses and check if matches with <code>University of X</code>.</p>
<pre class="lang-py prettyprint-override"><code>df['T/F'] = df['Address'].str.extractall(r"\(([^)]*)\)").eq('University of X').groupby(level=0).all()
</code></p... | python|pandas | 1 |
9,984 | 66,789,485 | Foward filling moving limit | <p>I have a dataframe with a lot of blanks. The first table on the image. I want to reach the right table. My idea is to use ffill() with a moving limit. The limit would adjust to what is on the right.
So first we count the consecutive elements on the right and fill level2 (yellow) and then do the same for the level1 (... | <p>Assuming the empty cells are empty strings (<code>""</code>), you can try:</p>
<pre><code>df[df == ""] = np.nan
m = ~df["Level 1"].isna()
df.loc[m, "Level 2"] = ""
df.loc[m, "Level 3"] = ""
df.loc[:, ["Level 1", "Level 2"]] = d... | python|pandas|dataframe|variables|fill | 0 |
9,985 | 67,177,129 | How to speed up for loop subsetting a DataFrame by a given value in a column and applying a formula in Python | <p>I was wondering whether there was a way to speed up this code:</p>
<pre><code>
alphas = []
origins = flows["OrigCodeNew"].unique()
for origin in origins:
df = flows[flows["OrigCodeNew"] == origin]
alpha = sum(df["DestSal"] ** gamma * df["Dist"] ** beta])
alphas.a... | <p>You didn't provide any sample data or expected outputs, so it is hard to answer this question.</p>
<p>Theoretically, you should be able to groupby and then use transform, which will assign the group value to each row in the group. If you are more comfortable using agg, you can calculate the group value and then join... | python|pandas|dataframe|pandas-groupby | 0 |
9,986 | 66,868,480 | DF column with only numeric values | <p>I have DF with two columns. Both contains numeric values together with symbols and letters.</p>
<p>I need to create two new columns with numbers only. Nothing can be dropped or deleted- it is important to keep the initial order the same.</p>
<p>I tried</p>
<pre><code>> df["PRIMARY"]=df['PRIMARY PHONE'].... | <p>You are looking for <code>map</code>:</p>
<pre class="lang-py prettyprint-override"><code>def extract_num(s):
return "".join(x for x in str(s) if x.isdigit())
df["PRIMARY"] = df["PRIMARY PHONE"].map(extract_num)
</code></pre> | python|pandas | 2 |
9,987 | 66,875,831 | Federated reinforcement learning | <p>I am implementing <strong>federated deep Q-learning</strong> by PyTorch, using multiple agents, each running DQN.
My problem is that when I use multiple replay buffers for agents, each appending experiences at the corresponding agent, <strong>two elements of experiences in each agent replay buffer, i. e., "curr... | <p>I just found what is causing the problem. I should have used copy.deepcopy() for experiences:</p>
<pre><code>experience = copy.deepcopy((current_state, action, np.array([reward]), next_state, done))
self.buffer.append(experience)
</code></pre> | python|pytorch|reinforcement-learning|deque|federated-learning | 1 |
9,988 | 67,071,953 | Incompatible Shapes Keras NN | <p>I am trying to make use of NN for 28x28 grey scale images. My training data is shaped as follows:</p>
<p>Reshape data</p>
<pre><code>out:
x_train.shape
(24000, 28, 28, 1)
y_train.shape
(24000, 1)
</code></pre>
<p>Define the keras model</p>
<pre><code>model = Sequential()
model.add(layers.Conv2D(28, (1, 1), activatio... | <p>The last Conv2D layer output [14*14] cannot be compared with the target shape [1] to calculate the loss. Hence the error. Generally, Conv2D layers need to be flattened and passed through a DNN (the part that you have commented) for the model architecture to be complete. The units(neurons) in the last Dense layer is ... | python|tensorflow|machine-learning|keras|neural-network | 2 |
9,989 | 47,327,713 | Pandas calculate average number of words in groupby | <p>Lets say I have a dataframe that looks like this:</p>
<pre><code>df = pd.DataFrame({'id': [1,1,1,1,2,2,2,3,4,4,4,4,4],
'feedback': ['one word', np.nan, np.nan, 'test',
'second', np.nan, 'test 2',
np.nan,
... | <p>Try this:</p>
<pre><code>In [96]: df.assign(avg_words=df['feedback'].str.split().str.len()) \
...: .groupby('id') \
...: .agg({'id': 'count','feedback': 'count', 'avg_words': 'mean'}) \
...: .rename(columns={'id':'count', 'feedback':'complete'}) \
...: .reset_index()
Out[96]:
id count c... | python|pandas|aggregate|pandas-groupby | 1 |
9,990 | 47,394,572 | Simple network for arbitrary shape input | <p>I am trying to create an autoencoder in <code>Keras</code> with <code>Tensorflow</code> backend. I followed <a href="https://blog.keras.io/building-autoencoders-in-keras.html" rel="nofollow noreferrer">this tutorial</a> in order to make my own. Input to the network is kind of arbitrary i.e. each sample is a 2d array... | <p>Numpy does not know how to handle a list of arrays with varying row sizes (see <a href="https://stackoverflow.com/questions/3386259/how-to-make-a-multidimension-numpy-array-with-a-varying-row-size">this answer</a>). When you call np.array with traceTmp, it will return a list of arrays, not a 3D array (An array with ... | python|numpy|tensorflow|deep-learning|keras | 3 |
9,991 | 68,178,765 | convolutional layer - trainable weights TensorFlow2 | <p>I am using TF2.5 & Python3.8 where a conv layer is defined as:</p>
<pre><code>Conv2D(
filters = 64, kernel_size = (3, 3),
activation='relu', kernel_initializer = tf.initializers.GlorotNormal(),
strides = (1, 1), padding = 'same',
)
</code></pre>
<p>Using a batch of 60 CIFAR-10 dataset as input:</p>
<... | <p>This is the formula used to compute the number of trainable parameters in a conv layer = [{(m x n x d) + 1} x k]</p>
<p>where,
m -> width of filter; n -> height of filter; d -> number of channels in input volume; k -> number of filters applied in current layer.</p>
<p>The 1 is added as bias for each filt... | python-3.x|tensorflow2.0 | 0 |
9,992 | 68,317,044 | What is the advantage of output_shape argument in Keras Lambda layer | <pre><code>def euclidean_distance(vects):
x, y = vects
sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
return K.sqrt(K.maximum(sum_square, K.epsilon()))
def eucl_dist_output_shape(shapes):
shape1, shape2 = shapes
return (shape1[0], 1)
input_a = Input(shape=(28,28,), name="left_input")
ve... | <ol>
<li>If you are using TF term frequency for similarity measure for of two
vector then these points i suggest you for the Lambda Layer?<br />
1)The main purposes of lambda layer to do some operation on previous
layer. but do not want to add any trainable weight to it. 2) Lambda
layer is an easy way to customize a l... | keras|tensorflow2.0|tf.keras|keras-layer | 0 |
9,993 | 59,441,993 | Changing json file format | <p>The script scrapes prices, addresses, suburbs and postcodes of houses and then writes them to a csv file.</p>
<p>The csv file is imported into panda (only postcode and price) and groupby the mean price of the postcode.
This groupby list is written to a json.</p>
<p>The csv file looks like this in excel</p>
<pre><... | <p>Add column name for aggregate <code>"Price"</code> or <code>" Price"</code> for <code>Series</code>:</p>
<pre><code>grouped = df.groupby(['Postcode'])["Price"].mean()
#grouped = df.groupby(['Postcode'])[" Price"].mean()
grouped.to_json('average_house_price.json')
</code></pre> | python|json|pandas | 1 |
9,994 | 57,242,167 | How to remove duplicates based on two columns removing the the largest of 3rd column in pandas dataframe? | <p>Suppose I have a pandas dataframe that is like this:</p>
<pre><code>df=
A B 6 2
A C 4 2
D F 9 3
K L 8 9
A B 4 3
D F 8 2
</code></pre>
<p>How can I say, if columns A and B have duplicates remove the ones that have the largest column C?</p>
<p>So for instance we can see lines 1 and 5 have the same... | <p>Try sorting the column in descending order on which you need to find max value using
<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>pd.sort_values</code></a></p>
<p>Then drop_duplicates using <a href="https://pandas.pydata.org/p... | python|python-3.x|pandas | 1 |
9,995 | 45,782,683 | Faster method for changing row entries? | <p>I have a pandas dataframe as follows:</p>
<pre><code>In [55]: df.head()
Out[55]:
Country Energy Supply Energy Supply per Capita % Renewable
0 Afghanistan 3.210000e+08 10.0 78.669280
1 Albania 1.020000e+08 35.0 100.000000
2 Algeria1... | <p>You can utilize Pandas built-in string operation, str.replace()</p>
<pre><code>df['Country'] = df['Country'].str.replace('\d','')
</code></pre> | pandas|python-3.5 | 1 |
9,996 | 45,837,456 | Generic string comparison with numpy | <p>If you have multiple numpy arrays of different string types, such as:</p>
<pre><code>In [411]: x1.dtype
Out[411]: dtype('S3')
In [412]: x2.dtype
Out[412]: dtype('<U3')
In [413]: x3.dtype
Out[413]: dtype('>U5')
</code></pre>
<p>Is there any way that I can check whether they are <em>all</em> strings without ... | <p>One way would be to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.issubdtype.html" rel="nofollow noreferrer"><code>np.issubdtype</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#scalars" rel="nofollow noreferrer"><code>np.character</code></a>:</p>
<pr... | python|numpy | 4 |
9,997 | 51,101,791 | Get indices from array where element in row satisfies condition | <p>I want to find the indexes of an array which satisfy a condition.</p>
<p>I have a numpy.ndarray B:
(m = number of rows = 8 and
3 columns)</p>
<pre><code>array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 1.],
[ 0., 1., 1.],
[ 0., 1., 0.],
[ 1., 1., 0.],
[ 1., 1., 1.],
[ 1., 0., 1.... | <p>There is a vectorized way to do that with numpy. 1st we create a mask for where <code>a</code> equals 1:</p>
<pre><code>mask=a.T==1.0
</code></pre>
<p>2nd mask will tell if next element also equals 1. Since we only want elements that satisfy both conditions we multiply both masks:</p>
<pre><code>mask_next=np.ones... | python|arrays|list|numpy|conditional-statements | 1 |
9,998 | 66,491,926 | Pandas apply unique random number to nan else go to next row | <pre><code>import pd as pandas
import random
import numpy as np
data = {'Item_No':['001', '002', '003','004', '005', '006','007','008','009'],
'Group_code':[331, 332, 333, 333, 333, 331, 331, nan, nan]}
df = pd.DataFrame(data)
</code></pre>
<p>I would like to apply a unique random number to 'nan' and keep ... | <p><strong>Step 0:-</strong></p>
<p>Your Dataframe:-</p>
<pre><code>data = {'Item_No':['001', '002', '003','004', '005', '006','007','008','009'],
'Group_code':[331, 332, 333, 333, 333, 331, 331, np.nan, np.nan]}
df = pd.DataFrame(data)
</code></pre>
<p><strong>Step 1:-</strong></p>
<p>Firstly define a functi... | python|pandas|numpy | 0 |
9,999 | 66,572,414 | pandas.read_html returns wrong table contents | <p>I try to scrape two tables (assets and liabilities) from :</p>
<p><a href="https://www.marketwatch.com/investing/stock/aapl/financials/balance-sheet" rel="nofollow noreferrer">https://www.marketwatch.com/investing/stock/aapl/financials/balance-sheet</a></p>
<p>The first table looks like this:
<a href="https://i.stac... | <p>let's look at selenium for this one, you might be able to do it with bs4 and some fun request stuff</p>
<pre><code>from selenium import webdriver
import time
url = "https://www.marketwatch.com/investing/stock/spg/financials/balance-sheet"
driver = webdriver.Firefox()
driver.get(url)
time.sleep(10)
tables ... | python|pandas|web-scraping | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.