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 |
|---|---|---|---|---|---|---|
350,100 | 60,215,539 | Using pandas and pyplot to group on multiple columns, get the value counts, and plot this information | <p>I am analyzing some data runs from an Agent Based Model that (TL;DR) simulates the life cycle of a species to predict survival rates given certain input parameters. I am struggling with how to use pandas and pyplot to accomplish this, and would love some suggestions. I have a csv that looks like this;</p>
<pre><cod... | <p>I wasn't sure what you wanted to do with the "runs" in your example. If you need to consider each run separately, here is my take on it:</p>
<pre><code>mix = pd.MultiIndex.from_product([df['run'].unique(), df['day'].unique(), df['Lifestate'].unique()], names=['run','day','Lifestate'])
new = df.groupby(['run','day'... | python|pandas|dataframe|matplotlib | 1 |
350,101 | 59,946,601 | Groupby consecutive occurrences of two column values in pandas | <p>I have a pandas dataframe with this structure:</p>
<pre><code>ID loc start end a_cn b_cn
A 1 123 123 1 1
A 1 125 125 1 1
A 1 235 235 1 1
A 1 456 456 2 0
A 1 556 556 2 0
A 1 586 5... | <p>You can compare both columns with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ne.html" rel="nofollow noreferrer"><code>DataFrame.ne</code></a> for <code>!=</code> by shifted rows of both columns and then add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pa... | python|pandas | 3 |
350,102 | 60,000,477 | Select last row from each column of multi-index Pandas DataFrame based on time, when columns are unequal length | <p>I have the following Pandas multi-index DataFrame with the top level index being a group ID and the second level index being <code>when</code>, in ISO 8601 time format (shown here without the time):</p>
<pre><code> value weight
when ... | <p>Where original <code>DataFrame</code> given in the question is <code>df</code>:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df.sort_index(inplace=True)
result = df.loc[pd.IndexSlice[:, :when], :].groupby('id').tail(1)
result['age'] = when - result.index.get_level_values(level=1)
</code... | pandas|dataframe|time-series|multi-index | 0 |
350,103 | 60,138,797 | How to do addition of 2 rows in pandas where the column has mixed datatype? | <p>I have a DataFrame that looks as follow:</p>
<hr>
<pre><code> 0 1 2
Time Blocks Left Blocks Added
0 NaN Monday Tuesday
1 NaN 2020-01-01 2020-01-02
2 01:00:00 44 1420
3 02:00:00 55 1520
4 0... | <p>I think better is working with DataFrame with MultiIndex in columns, not mixing data with metadata:</p>
<pre><code>df = df.set_index(0)
t = df.iloc[:3].apply(tuple).tolist()
df.columns = pd.MultiIndex.from_tuples(t)
df = df.iloc[3:].astype(int).rename_axis(None)
print (df)
Blocks Left Blocks Added
... | python|python-3.x|pandas|csv | 0 |
350,104 | 60,321,607 | Python loop through tuple list adding a value from pandas data frame | <p>I am trying to loop through a list of tuples adding a value to the end of each one that corresponds to a value in a column in a pandas data frame.</p>
<pre><code>df1 = [(1,2),(4,5),(8,9)]
df2 = pd.DataFrame({'Alpha': [2, 4, 8],
'Beta': ["a","b","c"]})
df3 = []
for i in df1:
print(i)
for ... | <p>Use <code>zip</code>, list comprehension solution:</p>
<pre><code>df3 = [j + (i,) for i,j in zip(df2["Beta"], df1)]
</code></pre>
<p>Your solution should be changed:</p>
<pre><code>for i,j in zip(df2["Beta"], df1):
j = j + (i,)
df3.append(j)
</code></pre>
<hr>
<pre><code>print(df3)
[(1, 2, 'a'), (4, 5, ... | python|python-3.x|pandas|tuples | 2 |
350,105 | 60,152,337 | Unable to read xlsb file using pandas | <p>I am trying to read an xlsb file from local using pandas' read_excel but I am getting error.
My code:</p>
<pre><code>import pandas as pd
df3 = pd.read_excel('a.xlsb', engine = 'pyxlsb')
</code></pre>
<p><br />
Error:</p>
<pre><code>---------------------------------------------------------------------------
ValueE... | <p>First install pyxlsb and run the below code.After running the code, you'll have your data stored in df1.</p>
<pre><code>pip install pyxlsb
import pandas as pd
from pyxlsb import open_workbook
df=[]
with open_workbook('some.xlsb') as wb:
with wb.get_sheet(1) as sheet:
for row in sheet.rows():
... | python|pandas|xlsb | 3 |
350,106 | 60,314,478 | how to write a keras custom loss function when you need the input value to calculate loss? | <p><img src="https://miro.medium.com/max/855/1*TdkNFoecrvBZZbLOHGse0Q.png" alt="perceptual losses"></p>
<p>I'm trying to duplicate a fast style transfer paper (see diagram above) using the method described in <a href="https://www.tensorflow.org/guide/keras/train_and_evaluate#part_i_using_built-in_training_evaluation_l... | <p>Since you didn't show the model, I'm not very sure about the problem. But you can try some of the followings:</p>
<ol>
<li>You said:</li>
</ol>
<blockquote>
<p>I also tried to pre-calculate y_true in the tf.data.Dataset, but while it worked fine under eager execution, it caused an error during model.fit()</p>
</bloc... | python|deep-learning|tensorflow2.0|style-transfer | 0 |
350,107 | 60,257,829 | Python Pandas - Find rows where element is in row's array | <p>I want to find all rows where a certain value is present inside the column's list value.</p>
<p>So imagine I have a <code>dataframe</code> set up like this:</p>
<pre><code>| placeID | users |
------------------------------------------------
| 134986| [U1030, U1017, U1123, U1044..... | <p>The way you have stored data looks fine to me. You do not need to change the format of storing data.</p>
<p>Try this :</p>
<pre><code>df1 = df[df['users'].str.contains("U1030")]
print(df1)
</code></pre>
<p>This will give you all the rows containing specified user in <code>df</code> format.</p> | python|pandas|dataframe|machine-learning|data-science | 2 |
350,108 | 60,231,929 | Getting non-zero data and positions from 2D array in Python | <p>I have a 2D array, and I hope I can get all of the non-zero data and their position. But now I just can get the non-zero data position.</p>
<p>Is there any way that I can get the value and the position at the same time?</p>
<pre><code>import numpy as np
groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, ... | <pre><code>print(list(zip(*np.nonzero(groupMatrix),groupMatrix[groupMatrix!=0])))
</code></pre>
<p>This is certainly not the most efficient solution (it replicates the search for nonzero elements), but it works just fine.</p> | python|numpy | 2 |
350,109 | 60,255,593 | Bokeh Gives me an Empty Plot with ColumnDataSource | <p>I'm a newbie on Bokeh. Been playing around with it successfully and have managed to plot beautiful charts.. But I think some of my basics are still flawed.</p>
<p>I tried the following simple example, and I end up with an empty plot.
I believe this is due to the x axis data being strings? But I'm unable to figure ... | <p>I believe Bokeh needs an x-range defined in some cases with vBar (especially when categoricals are strings), correct me if I'm wrong!</p>
<p>By adding x_range=scores_df['Name'] to the figure;</p>
<pre><code>fig = figure(title='my chart', plot_width=300, plot_height=300, y_range=(0,100), x_axis_label='Name', y_axis... | python|pandas|bokeh | 1 |
350,110 | 59,987,725 | Use part of first row and part of second row as column headers in python pandas | <p>I have a smiliar question to <a href="https://stackoverflow.com/questions/35719952/delete-part-of-a-row-in-pandas-shift-up-part-of-a-row-align-column-headings">this one</a>.</p>
<p>But somehow the solotion is not working, my dataframe looks like:</p>
<pre><code> Unnamed: 0 Unnamed: 1 Unnamed: 2 Unnamed: 3 ... | <p>I think you can convert first 4 values of first row to list and add to all columns names:</p>
<pre><code>df.columns = df.iloc[0,:4].tolist() + df.columns[4:].tolist()
#alternative
#df.columns = np.concatenate([df.iloc[0,:4], df.columns[4:]])
df = df.iloc[1:].reset_index(drop=True)
print (df)
D B Hil V Gesamt: ... | python|pandas | 1 |
350,111 | 60,110,426 | python pandas json_normalize in 1.0.0 with meta path specified - expects iterable | <p>I have the data</p>
<pre><code>[{"state": "Florida",
"shortname": "FL",
"info": {"governor": "Rick Scott"},
"counties": [{"name": "Dade",
"population": 12345,
"Attributes": [
{
"capture_date":... | <p>Check your version of pandas. If it pandas 1.0.0 then it is most likely related to:
<a href="https://github.com/pandas-dev/pandas/issues/31507" rel="nofollow noreferrer">json_normalize in 1.0.0 with meta path specified - expects iterable #31507</a></p>
<p>I had exactly the same issue as I reinstalled my dev environ... | python|json|pandas|normalize | 2 |
350,112 | 60,048,905 | accessing Pandas dataframe by Excel cell index | <p>I have imported an Excel spreadsheet into a dataframe. I wish to access data as though it was an Excel
reference: e.g. df.get("A1") instead of df.iloc[0,0]. Does a nice method already exist for accessing dataframe data with Excel indexing - something like my imaginary get function above?</p> | <p>You could write a simple function to do the conversion from Excel index to numerical index:</p>
<pre class="lang-py prettyprint-override"><code>import regex as re
def index_transform(excel_index):
match = re.match(r"^([a-z]+)(\d+)$", excel_index.lower())
if not match:
raise ValueError("Invalid inde... | python|excel|pandas|dataframe | 2 |
350,113 | 60,235,746 | Getting started with denoising elements of a 200x200 numpy array | <p>I have a 200x200 numpy array that has a shape in it which I can see when I graph it using matplotlib's <code>imshow()</code> function. However, there is also a lot of noise added in that picture. I am trying to use openCV to emphasize the shape and denoise the image. But it keeps throwing error messages that I don't... | <p>I solved the problem using Scikit Image. They have very accessible documentation page for new comers and the error messages are a lot easier to understand. As for my problem I had to use <a href="https://scikit-image.org/docs/dev/api/skimage.restoration.html" rel="nofollow noreferrer">Scikit Image's restoration libr... | python|numpy|opencv|scipy | 0 |
350,114 | 60,324,052 | Python Pandas - Group and join lines with multiple columns | <p>I working with a dataframe that have some rows that needed to be groupped (with a join) using a key.</p>
<p>Basically I have this dataframe:</p>
<pre><code>d = {'process': [1, 2, 2, 3, 3], 'notes_txt': ['TESTE 1', 'TESTE A ', 'TESTE A ', 'TESTE B ', 'TESTE B '],'notes_cont': ['Process 1: 0 errors', 'Process 1:', ... | <p>IIUC, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a></p>
<pre><code>df.groupby(['process','notes_txt'],as_index = False).agg({'notes_cont':''.join,
... | python|pandas | 3 |
350,115 | 59,943,718 | Convert an n x 1 dataframe to an a x b sized grid based on month, year | <p>I have a pandas dataframe with a datetime index that I'd like to reorient as a grid from a pandas time-series dataframe. </p>
<p>My dataframe looks like this:</p>
<pre><code>DATE VAL
2007-06 0.008530
2007-07 -0.067069
2007-08 0.026660
2007-09 0.016237
2007-10 0.025145
2007-11 ... | <p>First convert <code>DATE</code> to datetimes and reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.... | python|python-3.x|pandas|numpy | 3 |
350,116 | 60,287,555 | Is there any way to Read BeautifulSoup output with pandas to read Tables? | <p>I have tried this Way</p>
<pre><code>data = web_soup.findAll("table", {"id": "product-review-table"})```
print(pd.read_html(data))
</code></pre>
<p>Error Returned:
TypeError: Cannot read object of type 'ResultSet</p>
<p>data contain a complete table. I want to read only specific table from Url, By passing url to ... | <p><strong>Short Answer</strong>:</p>
<pre><code>pd.read_html(str(data))
</code></pre>
<p><strong>Longer answer</strong>:</p>
<p>The input to <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.read_html.html" rel="nofollow noreferrer"><em><code>read_html()</code></em></a> can be a string.... | python-3.x|pandas|beautifulsoup | 1 |
350,117 | 60,106,181 | When I try to reshape my training data I get this error.... ValueError: cannot reshape array of size 568 into shape (28,28,3) | <p>This is the where I read in the images:</p>
<pre><code>train = []
imgsize = 28
for image_name in image_name_list:
im = cv2.imread(path_string + image_name +'.jpg')
new = cv2.resize(im,(imgsize, imgsize))
train.append(new)
</code></pre>
<p>In a tutorial I was using, I'm not sure why we w... | <p>Reshaping an array of size 568 into 28x28x3 doesn't seem possible...?
28x28x3=2352</p> | python|opencv|tensorflow | 1 |
350,118 | 60,269,201 | Pivot-table in pandas: aggfunc sum during date range | <p>I have a pandas dataframe like the following:</p>
<pre><code># Date Name RG
#-----------------------------------
# 1: 2013-04-25 NameA 1
# 2: 2013-04-25 NameB 3
# 3: 2013-04-25 NameC 1
# 4: 2013-04-25 NameD 2
# 5: 2013-04-25 NameE 1
# --... | <p>I found the answer myself. Before pivoting, it is necessary to generate the cumsum for the selected period by following procedure:</p>
<pre><code>for index, row in df.iterrows():
currentDate = row['Date']
previousDate = row['Date'] - pd.DateOffset(months=12)
name = row['Name']
mask = (df['Date'] >... | python|pandas|numpy | 0 |
350,119 | 60,028,101 | assert_frame_equal asserting for two same pandas dataframe | <p>I am doing 2 pandas dataframe comparison and this is where my assertion is failing.</p>
<p><code>pd.testing.assert_frame_equal</code></p>
<p>This is the assertion error</p>
<pre><code>E AssertionError: DataFrame.iloc[:, 8] (column name="xxxxx") are different
E
E DataFrame.iloc[:, 8] (column name="xxxxx") valu... | <p>I had the same issue. In the end, I used the option <code>check_dtype=False</code> from <code>assert_frame_equal</code>, and the assert works.</p>
<p>... types, who need them?</p> | pandas|dataframe | 1 |
350,120 | 60,043,871 | operation over groupby object returns single values for all columns of new dataframe | <p>I have been spending the entire day trying to figure this issue out and nothing from Stackoverflow about the topic is making it. </p>
<p>I am making calculations over groupby objects but the output is off. I am assuming that there is something wrong with my use of the apply method but cannot figure out what
Here is... | <p>IIUC - although the results don't seem to be even close:</p>
<pre class="lang-py prettyprint-override"><code>data1=data1.sort_values("Date", axis=0, ascending=False)
data1["obs"]=data1.groupby("Id").cumcount()
data2=data1.loc[data1["obs"]<5].groupby("Id").apply(lambda x: pd.Series({"trendup": x["Quantity"].is_m... | python|pandas | 1 |
350,121 | 60,077,092 | Design model architecture for CNN | <p>I want to design CNN for dataset that have 300 classes. I have tested with following model for two classes. It gives good accuracy.</p>
<pre><code>model = Sequential([
Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH ,3)),
MaxPooling2D(),
Conv2D(32, 3, padding='same', activation='... | <p>In order to perform a training on a dataset of more than 2 classes, you need to use the categorical_crossentropy loss and the softmax activation layer for your last Dense layer. </p>
<p>The number of neurones of your last Dense will determine the number of classes you want to predict, so if you have 300 classes it... | tensorflow|machine-learning|keras|conv-neural-network | 0 |
350,122 | 59,912,299 | How to create loop to correct the gender in datatframe | <p>I got new column of 'gender' of df summarized as below after using gender_guesser.detector package. I want change 'mostly_female' to 'female'; and change 'mostly_male" & 'andy' to 'male'; I wrote codes as below, but generate error. How to fix it? Thanks a lot!
unknown 1125
male 321
female ... | <p>You could use <code>map</code> method by passing replacement value for every key you need.</p>
<pre><code>df['gender'] = df['gender'].map({
'mostly_female': 'female',
'mostly_male': 'male',
'andy': 'male',
'unknown': np.random.choice(['female', 'male'], size=1)
})
</code></pre> | python|pandas|dataframe|machine-learning | 2 |
350,123 | 60,019,708 | Understanding the logic behind numpy code for Moore-Penrose inverse | <p>I was going through the book called <em>Hands-On Machine Learning with Scikit-Learn, Keras and Tensorflow</em> and the author was explaining how the pseudo-inverse (Moore-Penrose inverse) of a matrix is calculated in the context of Linear Regression. I'm quoting verbatim here:</p>
<blockquote>
<p>The pseudoinverse i... | <p>It's almost certainly an adjustment for numerical error. To see why this might be necessary, look what happens when you take the <code>svd</code> of a rank-one 2x2 matrix. We can create a rank-one matrix by taking the outer product of a vector like so:</p>
<pre><code>>>> a = numpy.arange(2) + 1
>>>... | python|numpy|matrix | 2 |
350,124 | 59,973,873 | Generate random numbers from a list of numbers | <p>I have a list of numbers:</p>
<pre><code>data = [15, 30, 45]
</code></pre>
<p>how to generate a list of N numbers taken randomly from this <code>data</code> list? To get result as:</p>
<pre><code>new_data = [15,15, 30, 45, 15,45, 30, 15, 45, 30, 45, 45, 45, 15, ...]
np.random.randint(15, high=45, size=N) # does... | <p><code>numpy.random.choice</code> can do this:</p>
<pre><code>import numpy
data = [15, 30, 45]
N = 20
new_data = numpy.random.choice(data, N)
print(new_data)
</code></pre>
<p><a href="https://ideone.com/ECqtJ3" rel="nofollow noreferrer">https://ideone.com/ECqtJ3</a></p> | python|numpy|random | 1 |
350,125 | 59,921,918 | How to iterate through the duplicates dataframe? | <p>Hellow, everyone!
I have a CSV file, which contains only dublicates value from my main database. I have a three column(Year, Rate and Color), which need to be group. Color column is a Python-list in each cell</p>
<pre><code>Name Year Rate Color
Name1 2017 4.5 ['yellow', 'green', blue']
Name1 - ... | <p>You could group by the Rate variable and use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#aggregation" rel="nofollow noreferrer"><code>aggregation</code></a>:</p>
<pre><code>df = df.groupby('Rate').agg({'Name':'first','Year':'first','Rate':'first','Color':'first'})
</code></pre>
<p... | python|pandas | 0 |
350,126 | 60,034,021 | Most efficient way to compare two panda data frame and update one dataframe based on condition | <p>I have two dataframe df1 and df2. df2 consist of "tagname" and "value" column. Dictionary "bucket_dict" holds the data from df2.</p>
<pre><code>bucket_dict = dict(zip(df2.tagname,df2.value))
</code></pre>
<p>In a df1 there are millions of row.3 columns are there "apptag","comments" and "Type" in df1. I want to mat... | <p>You can do this by calling an apply on your <code>comments</code> column along with a <code>loc</code> on your <code>bucketing_df</code> in this manner -</p>
<pre><code>def find_type(a):
try:
return (bucketing_df.loc[[x in a for x in bucketing_df['tagname']]])['value'].values[0]
except:
retu... | python-3.x|pandas | 0 |
350,127 | 60,056,966 | Iterate over two images pixel by pixel in Numpy (with a random condition) | <pre><code>import random
def sp_noise(image,prob):
'''
Add salt and pepper noise to image
prob: Probability of the noise
'''
output = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
... | <p>You can call <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.random.html" rel="noreferrer"><code>np.random.random</code></a> with an additional <code>size</code> parameter to get a whole array of random floats. Then, use <a href="https://docs.scipy.org/doc/numpy/reference/generated/... | python|numpy|image-processing|vectorization | 6 |
350,128 | 60,117,220 | StatsModels formula Polynomial Regression does not match numpy polyfit coefficients | <p>My polynomial regression using statsmodels formula does not match nupy polyfit coefficients.</p>
<p>Link to data <a href="https://drive.google.com/file/d/1fQuCoCF_TeXzZuUFyKaHCbD1zle2f1MF/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1fQuCoCF_TeXzZuUFyKaHCbD1zle2f1MF/view?usp=sharing</... | <p>Polynomials can become very badly scaled if the underlying data is not in a small range around zero.
As a consequence, computation become numerically unstable and the results can be dominated by numerical noise.</p>
<p><a href="http://jpktd.blogspot.com/2012/03/numerical-accuracy-in-linear-least.html" rel="nofollo... | python|numpy|regression|statsmodels|non-linear-regression | 1 |
350,129 | 60,216,244 | comparing two lists elements in python | <p>I have 2 lists which consider versions '2.0.0', Im comparing their element and get the list of [True, True, True] meanings, how can i take from list of [True, True, True] meanings, only one meaning True, or if it will be 1 False in that list, how can i get False, globally, i need to override magic methor <strong>eq<... | <p>You are looking for <a href="https://numpy.org/doc/1.18/reference/generated/numpy.all.html" rel="nofollow noreferrer"><code>numpy.all</code></a></p>
<pre><code>numpy.all(a == b)
</code></pre> | python|list|numpy | 2 |
350,130 | 60,294,970 | How can I do dataframe subtraction? | <p>I have the following dataframe:
Col1 is the payment.</p>
<pre><code>Col1 Value
Item1 100
Item2 200
Item3 300
</code></pre>
<p>and Col2 is the Project cost</p>
<pre><code>Col2 Value
Project1 200
Project2 300
Project3 400
</code></pre>
<p>I basically want to match Col1 with the project... | <p>here, you can find logic, comments are added for explaination:</p>
<pre><code># making list of project requirement and item value to iterate
item_cost = list(zip(payment['Col1'], payment['value']))
requirment = list(zip(project_cost['Col2'], project_cost['value']))
d = {}
for project, cost in requirment:
item_... | python|pandas|dataframe | 1 |
350,131 | 60,293,600 | Pytorch custom Dataset class giving wrong output | <p>I am trying to use this class I built for a dataset but it saying that it should be a PIL or ndarray. Im not quite sure whats wrong with it. Here is the class that I am using</p>
<pre><code>class RotateDataset(Dataset):
def __init__(self, image_list, size,transform = None):
self.image_list = image_list... | <p>As discussed in the comments, the problem was applying transform on <code>label</code> as well. The <code>label</code> should instead simply be written as tensor:</p>
<pre><code>return self.transform(img), torch.tensor(label)
</code></pre> | python|pytorch | 1 |
350,132 | 60,019,795 | Python taking too much of memory | <p>I am importing sparse matrices from .npz file. Below is the script of the code. The sparse matrices (Dx, Dy, ..., M) have 373248x373248 size with 746496 stored elements. </p>
<pre><code>if runmode == 2:
data = np.load('Operators2.npz', allow_pickle=True)
Dx = data['Dx']
Dy = data['Dy']
Dz = da... | <p>Make a sparse matrix:</p>
<pre><code>In [38]: M = sparse.random(1000,1000,.2,'csr')
</code></pre>
<p>save it 3 different ways:</p>
<pre><code>In [39]: from scipy import io
In [40]: np.savez('Msparse.... | python|numpy|memory|memory-management|out-of-memory | 1 |
350,133 | 60,134,022 | Pandas string.contains doesn't work if searched string contains the substring at the beginning of the string | <p>I'm using str.contains to search for rows where the column contains a particular string as a substring</p>
<pre><code>df[df['col_name'].str.contains('find_this')]
</code></pre>
<p>This returns all the rows where 'find_this' is somewhere within the string. However, in the rare but important case where the string in... | <p>TLDR: Experiment with pandas.Series.str.normalize(), trying different Unicode forms until the issue is solved. 'NFKC' worked for me.</p>
<p>The problem had to do with the format of the data in the column that I was doing the...</p>
<pre><code>df['column'].str.contains('substring')
</code></pre>
<p>...operation o... | python|string|pandas|substring|contains | 0 |
350,134 | 65,445,585 | Predictions using Logistic Regression in Pytorch return infinity | <p>I started watching a tutorial on PyTorch and I am learning the concept of logistic regression.</p>
<p>I tried it using some stock data that I had. I have <code>inputs</code>, which contains two parameters <code>trade_quantity</code> and <code>trade_value</code>, and <code>targets</code> which has the corresponding s... | <p>To me, this looks more like linear regression than logistic regression. You are trying to fit a linear model onto your data. It's different to a binary classification task where you would need to use a special kind of activation function (a <a href="https://en.wikipedia.org/wiki/Sigmoid_function" rel="nofollow noref... | pytorch | 0 |
350,135 | 65,127,746 | Pandas Boxplot Highlight Specific Values in DF | <p>I have a df called "YMp" and I have made a boxplot for the data with the dates 1991 - 2019 but I need to show the current year (2020) values as colored points or values with a legend showing the year 2020 over-plotted on the boxplot.</p>
<p>The data looks like this -</p>
<pre><code>month 01 02 03 ... | <p>Try catching the axis instance and plot again:</p>
<pre><code>ax = df.boxplot()
ax.scatter(np.arange(df.shape[1])+1, df.loc[2000], color='r')
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/wtv2f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wtv2f.png" alt="enter image descrip... | pandas|highlight|boxplot | 1 |
350,136 | 65,188,835 | pytorch tensors cat on dim =0 not worked for me | <p>I have a problem with <code>cat</code> in pytorch. I want to concatenate tensors on dim=0, for exampe, I want something like this</p>
<pre><code>>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.6580, -1.0969, -0.4614],
[-0.1034, -0.5790, 0.1497]])
>>> torch.cat((x, x, x), 0)
tensor([[ ... | <p>The problem was what tmp_tensor had shape ([7]) so I could to concatenate only on one dimension. The solution was that I shold to add one new string <code>tmp_tensor = torch.unsqueeze(tmp_tensor, 0)</code> and now tmp_tensor([1,7]) and I could using <code>torch.cat</code> without problem</p>
<pre><code>def create_ba... | python|pytorch|cat | 0 |
350,137 | 65,297,464 | I'm trying to scrape a table from a website but I keep getting an IndexError and can't progress | <p>I'm rather new to coding and not sure what the issue is here.</p>
<p>I'm trying to scrape all of the player statistics from the LoL 2020 World Championship for a class project but I keep getting and Index Error and I don't know how to fix it. Here is the code I'm using:</p>
<pre><code>import pandas as pd
import re
f... | <p>Try to remove <code>"jquery-tablesorter"</code> class name from your selector - it appends during page rendering:</p>
<pre><code>table = webpage.select("table.wikitable.sortable.spstats.plainlinks.hoverable-rows")[0]
</code></pre> | python|html|pandas|web-scraping | 0 |
350,138 | 65,429,177 | Separate numpy 2-dimension array to two 2-dimension array | <p>I merged 2 dimension array.</p>
<pre><code>print(L.shape) #(89, 88201)
print(R.shape) #(89, 88201)
C = np.append(L,R,axis=1)
print(C.shape) #(178, 88201)
</code></pre>
<p>Now, want to separate the array <code>C</code>
to <code>(89, 88201)</code> as before.</p>
<p>How can I make it???</p> | <p>Try this:</p>
<pre><code>L = C[0:89, :]
R = C[89:, :]
</code></pre> | python|numpy | 2 |
350,139 | 65,242,446 | a bar chart based on the total numbers for each year in Pandas | <p>I have two columns in which there are different numbers in different rows for each year.</p>
<p><a href="https://i.stack.imgur.com/enmir.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/enmir.jpg" alt="enter image description here" /></a></p>
<p>First, I need to display the sorted values based on t... | <p>Try:</p>
<pre><code>sum_by_years = (df.groupby('Year')['Goals scored'].sum()
.sort_values(ascending=False)
)
sum_by_years.plot.barh()
</code></pre> | pandas | 0 |
350,140 | 65,175,677 | Pandas Python How to make 2 values with equal len? | <p>Hi anyone can help on this? i got error when i run this:</p>
<pre><code>conditions5 = [
(data1['Payment Mode'] == '03')
]
choices5 = data1['Value Date']
data1['Valid From Date'] = np.select(conditions5, choices5, default ='')
data1
</code></pre>
<p>Error:
List of cases must be same length as list of condition... | <p>Try <code>np.where</code>:</p>
<pre><code>data1['valid from date'] = np.where(conditions5, data1['Value Date'], '')
</code></pre> | python|arrays|pandas|numpy|pandas-loc | 0 |
350,141 | 65,470,525 | Fill a matplotlib contour plot | <p>With the following code I have obtained the following contour map:</p>
<pre><code>fig, ax = plt.subplots()
x = np.arange(431)
y = np.arange(225)
Y, X = np.meshgrid(y, x)
values = df["Appearance_percentage"].values
values2d = np.reshape(values, (431, 225))
ax.set_ylim(225, 0)
plt.style.use('seaborn-white')... | <p>Just replace <code>plt.contour</code> with <code>plt.contourf</code>, where the "f" at the end means "fill".</p>
<p>Here is an example:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = np.arange(100)
y = np.arange(100)
Y, X = np.meshgrid(y, x)
values = np.outer(x, y)
fig, a... | python|numpy|matplotlib|contour | 2 |
350,142 | 65,460,252 | Cumsum with groupby | <p>I have a dataframe containing:</p>
<pre><code> State Country Date Cases
0 NaN Afghanistan 2020-01-22 0
271 NaN Afghanistan 2020-01-23 0
... ... ... ... ...
85093 NaN Zimbabwe 2020-11-30 9950
... | <pre class="lang-py prettyprint-override"><code>arrays = [['California', 'California', 'Texas', 'Texas'],
['USA', 'USA', 'USA', 'USA'],
['2020-01-22','2020-01-23','2020-01-22','2020-01-23'], [5,10,4,12]]
df = pd.DataFrame(list(zip(*arrays)), columns = ['State', 'Country', 'Date', 'Cases'])
df
S... | python|pandas|dataframe|pandas-groupby | 0 |
350,143 | 65,087,492 | How to filter dataframe and make a subset at once pandas | <p>I am trying to make a subselection of a dataframe based on some columns, while at the same time filtering the dataframe based on a different column. In SQL it looks like this:</p>
<pre><code>SELECT col1, col2, col3,
FROM table
WHERE colume_4 = some_value
</code></pre>
<p>I know how to do it in two steps, but I prefe... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> with combination with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean inde... | python|pandas | 1 |
350,144 | 65,132,119 | Pandas query for byte string literal on Linux results in AttributeError ... no attribute 'visit_Bytes' | <p>I'm trying to write a pandas query for a byte string literal. This works OK on Windows, but I get an exception on Red Hat Ent. Linux. Here's the code:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1, 2, b'3'], [4, 5, b'6'], [7, 8, b'9']],
columns=['num1', 'num2', 'byteStr'])
print(df)
print... | <p>You can always decode <code>byte objects</code> to literal strings and then <code>query</code>, like this:</p>
<pre><code>In [4516]: df.byteStr = df.byteStr.str.decode("utf-8")
In [4517]: df
Out[4517]:
num1 num2 byteStr
0 1 2 3
1 4 5 6
2 7 8 9
In [4519]: df.... | python|linux|pandas | 1 |
350,145 | 65,470,063 | Flask/jinjas - url_for - from pandas iterated data (itertuples) | <p>Iterating over a pandas dataframe gives a HTML table.
As well as simply displaying the first column of the dataframe, I want it to be a link to the app.route(‘account’) via an tag.</p>
<pre><code><table>
{% for row in df.itertuples() %}
<tr>
<td><a href="{{ url_for('account',table_name='{{... | <p>Could you give the following code a try?</p>
<pre><code><td><a href="{{ url_for('account',table_name=row[1]) }}">{{ row[1] }}</a></td>
</code></pre>
<p>My understanding is when the "parser" detect curly braces, it enters "python-execution" mode. So for <code>{{ u... | python|pandas|flask|jinja2 | 1 |
350,146 | 65,415,068 | Python pandas summarize round trip in dataframe | <p>I have a dataframe (~30 000 rows) count of trips by station code.</p>
<pre><code>|station from|station to|count|
|:-----------|:---------|:----|
|20001 |20040 |55 |
|20040 |20001 |67 |
|20007 |20080 |100 |
|20080 |20007 |50 |
</code></pre>
<p>how is it possible to get d... | <p>Here is a simple solution which handles the cases without round trip.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"station from":[20001,20040,20007,20080, 2, 3],
"station to":[20040,20001,20080,20007, 1, 4],
... | python|pandas|dataframe | 2 |
350,147 | 65,200,489 | How to run multiple experiments in parallel and select best cases for refinement in deep reinforcement learning? | <p>I am working on a custom environment using gym and currently trying to parallelize the training of my D3QN model as it is taking a lot of time to finish an episode.</p>
<p>Is there a way to parallelize the training and take only best cases for refinement using Keras and tensorflow?</p>
<pre><code> def run(self):
... | <p>you can only do this if you have multiple GPU. one GPU can only focus on 1 task, since your model is already slow so you need to upgrade your hardware, you either need more GPUs to train single model(opposite of your question). or you can get better GPU to train model.</p>
<p><a href="https://keras.io/guides/distrib... | python|tensorflow|keras|deep-learning|reinforcement-learning | 0 |
350,148 | 65,195,574 | KeyError when using panda's assign function | <p>I have data frame below and I wish to create new variables "profit_loss" and "profit_margin" based on revenue & budget.</p>
<pre><code> revenue budget
0 1513528810 150000000
1 378436354 150000000
2 295238201 110000000
3 2068178225 200000000
4 15062493... | <p>You need <code>lambda</code> for working with new created column like here <code>profit_loss</code>:</p>
<pre><code>df = d.assign(profit_loss = (d['revenue'] - d['budget']),
profit_loss_margin = lambda x: (x['profit_loss'] * 100 / x['revenue']),
financial_status = lambda x: x['profit_l... | python|python-3.x|pandas|dataframe | 2 |
350,149 | 65,469,183 | Pandas: Remove values that meet condition | <p>Let's say I have data like this:</p>
<pre><code>df = pd.DataFrame({'category': ["blue","red","blue", "blue","green"], 'val1': [5, 3, 2, 2, 5], 'val2':[1, 3, 2, 2, 5], 'val3': [2, 1, 1, 4, 3]})
print(df)
category val1 val2 val3
0 blue 5 1 2
1 ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html#pandas.DataFrame.mask" rel="nofollow noreferrer">mask</a>:</p>
<pre><code>df.iloc[:, 1:] = df.iloc[:, 1:].mask(df.iloc[:, 1:] < 3)
print(df)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> category val1 ... | python|pandas|dataframe | 4 |
350,150 | 65,244,069 | How to display x axes value for each matplotlib subplot with secondary y axes | <p>I want to show x axis value on each subplot that uses a secondary_y axis. The output generated by this code shows x values only in the bottom two subplots. This code replicates a major project that uses a 7x3 subplot matrix</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df1 = ... | <p>At the end of your for loop and outside of the loop (after <code>i=i+1</code>), you can add back the x label to the first row with <code>.tick_params(labelbottom=True)</code> on each column of the first row.</p>
<pre><code>axes[0,0].tick_params(labelbottom=True)
axes[0,1].tick_params(labelbottom=True)
</code></pre>
... | python|pandas|matplotlib|subplot | 0 |
350,151 | 65,085,991 | Bert model show up InvalidArgumentError Condition x <= y did not hold element wise | <p>i am training a Bert.</p>
<p>Can anyone shed light on the meaning of the following error message?</p>
<pre><code>Condition x == y did not hold element wise
</code></pre>
<p>Here is Reference colab <a href="https://colab.research.google.com/github/singularity014/BERT_FakeNews_Detection_Challenge/blob/master/Detect_f... | <p>Maximum sequence length is limited to 512 for BERT. Try to feed short sequence to your model. If it works - check you data: there is a long sequence somewhere.</p> | tensorflow|machine-learning|nlp|bert-language-model | 0 |
350,152 | 65,422,286 | Filter group for a specific date | <p>I have a table with a user_id and a date</p>
<pre><code>|user_id|date_2check|
---------------------
| 1 | 2020-02-01|
| 2 | 2020-01-05|
</code></pre>
<p>And then a table with historical data</p>
<pre><code>|row_id|user_id|everyday_checkin|
---------------------------------
| 1 | 1 | 2020-01-01 |
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> for possible compare <code>date</code>s from another <code>DataFrame</code> and compare by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Ser... | python|pandas | 1 |
350,153 | 65,163,527 | Creating a Dataframe out of several API GET results appended into one single list | <p>I have a list with several 16 API GET results appended and i'm struglling into turning them into a dataframe. The raw results looks like this:</p>
<p>['{"total":17,"result":[{"categories":[],"created_at":"2020-01-05 13:42:19.576875","icon_url":"https:/... | <p>This is an extension of your earlier post, but now that you've shown the response, modify the original question's answer like this. Instead of creating a list of responses, you can create the 16 dataframes then concatentate.</p>
<pre><code>df_list = [] #capture list of dataframes
for s in list(r.keys()): # replace ... | json|pandas|api|dataframe | 1 |
350,154 | 65,063,938 | Converting dataframe with data on two different levels to nested dictionary | <p>As mentioned in the title, I have data from two different levels where the first a higher level and lower level and the data on the higher level has multiple records from the lower data attached to it (i.e. a 1:n relationship). I have joined the two dataframes which hold this together to create a single dataframe wi... | <p>I think standard <code>pandas</code> methods are not really suited for this. I would simply iterate over the data.frame to build your desired output.</p>
<p>I guess your output shoud be a list of dicts and not a dict of dicts. Here is how a solution could look like:</p>
<pre><code>result = []
for id in df.id.unique(... | python|pandas|dictionary | 1 |
350,155 | 65,348,332 | divide two different sized dataframes by all options | <p>I have dataframes question.
I have two dataframes:
They both have one column and a lot of rows.</p>
<p>I want to divide the first df rows by the first row of the second df, then divide the first df rows by the second row of the second df, and the third and forth till the end...</p>
<p>For example:</p>
<p>df1 is:</p>... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.ufunc.outer.html" rel="nofollow noreferrer">np.divide.outer</a>:</p>
<pre><code>import numpy as np
res = np.divide.outer(df1['A'].values, df2['A'].values).reshape(-1, order='F')
out = pd.DataFrame(data=res, columns=['A'])
print(out)
</code></pre>
<... | python|pandas|dataframe | 2 |
350,156 | 65,168,077 | Convert a column of data type Int64 with <NA> values to object with nan values | <p>A tutorial had this dataframe <code>sequels</code> as follows:</p>
<pre><code> title sequel
id
19995 Avatar nan
862 Toy Story 863
863 Toy Story 2 10193
597 Titanic nan
24428 The Avengers nan
<class 'pandas.core.frame.DataFrame'>
Index... | <p>I don't think you would want to. The reason you are seeing this is the tutorial is based on an older version of Pandas than what you are using.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_guide/in... | python|pandas|pickle | 2 |
350,157 | 65,230,110 | Unable to insert data into Snowflake database table using pandas to_sql() method | <p>I have a database <code>SFOPT_TEST</code> on my Snowflake instance. The database has two schemas <code>AUDITS</code> and <code>PARAMS</code>.</p>
<p>The schema <code>AUDITS</code> has a table created like this using SQLAlchemy <code>declarative_base()</code>-</p>
<pre><code>class AccountUsageLoginHistory(Base):
... | <p>If you are used to MSSQL or Oracle this may seem confusing, but Snowflake does not allow you to ignore the column on insert when you have a not null constraint (this is the only constraint that Snowflake enforces). However, since you are using the sequence to add default values you can set the column to nullable and... | python|pandas|snowflake-cloud-data-platform | 1 |
350,158 | 65,102,743 | how to filter float64 values in pandas | <p>I have a csv file that I want to filter with pandas. This is what the csv file looks like</p>
<pre><code>Name Employee ID
Jane Doe 00101848707829
Jason Smith 0030201689375900
Jason Bourne 0017501001410513
...
</code></pre>
<p>I want only that data where the <code>Employee ID</code> starts wi... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply</code></a>:</p>
<pre><code>df_filter = df[df['Employee ID'].apply(lambda x: str(x).startswith('001'))]
</code></pre>
<p>OR, use <a href="https://pandas.pydata.org/docs... | python|pandas|dataframe | 2 |
350,159 | 65,430,620 | Problem with getting reproducible results, set seed Tensorflow object detection API | <p>I am using object detection API with tensorflow v1.12. I am having troubles getting reproducible results - each time I run my code I am getting different results. Is there any way to set random seed at training / prediction level? I tried to set seed in model_main.py, but it didn't help.</p>
<pre class="lang-py pret... | <p>Getting repeatable results in tensorflow is a very difficult problem. If you search on Stack Overflow you will find numerous questions on this issue. Bottom line is you have to track down and seed EVERY source of randomness that ran be present either in your model or in the way you generate the data pipeline. This i... | python|tensorflow|object-detection | 0 |
350,160 | 65,276,407 | if unique_id's are equal then compare current row end value with next row start in pandas dataframe | <pre><code>data = [
['30', '12', '42'],
['30','30','100'],
['10', '70','300'],
['10','200','700'],
['20','800','900'],
['20','600','1000'],
['40','600','1200'],
['40','1100','1300'],
['90','2010','2100']
]
df= pd.DataFrame(data, columns=['unique_id', 'start_frame', 'end_frame'])
print(df)
</code></pre>
<p>expected out... | <p>Here is one way how you can do it:</p>
<pre><code>import pandas as pd
data = [
['30', '12', '42'],
['30','30','100'],
['10', '70','300'],
['10','200','700'],
['20','800','900'],
['20','600','1000'],
['40','600','1200'],
['40','1100','1300'],
['90','2010','2100']
]
df= pd.DataFrame(data, columns=['unique_id', 'star... | pandas|dataframe | 0 |
350,161 | 65,317,013 | How to filter out the stocks whose price has been increasing for 3 consecutive days | <p>I want to filter out the the strong performance stocks among a bunch of companies by the attribute of price increasing for 3 consecutive days. Below the code so far. Appreciate if any help.</p>
<p>In other words, i want get a list of stock names whose price has been been increasing continuously for the past 3 days... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>def compute_consecutive_increase(tick_data, window_size=3):
# Make sure the time series is sorted by date (assuming that date is the index)
tick_data = tick_data.sort_index()
# Put side-by-side the comparison of current day ('t-0') w... | python|pandas|data-analysis | 0 |
350,162 | 65,300,532 | How Do I Write A Function That Counts Identical and Different IDs in Two Columns of Different Sizes | <p>Given a reference dataframe A of one column "ID" (50,000 rows),
and dataframes B, C, D, with column "ID" with 45,000 rows, 55,000, 70,000 rows respectively,
with each instance of "ID" being a large(seventeen digit) integer value,
with many identical values in all of the columns but not ... | <p>you can try <code>.isin()</code>. Example with pd.Series:</p>
<pre><code>A = pd.Series([196, 202, 443, 781, 557])
B = pd.Series([781, 488, 712, 202, 482, 311])
if len(A) >= len(B):
matches = A.isin(B)
else:
matches = B.isin(A)
mismatches = ~matches
print('matches: {}, mismatches: {}'.format(sum(matche... | python|python-3.x|pandas | 0 |
350,163 | 65,096,687 | Convert several units to TB as well as perform calculation using Python | <p>I have a dataset, df, where I wish to convert several columns from bytes to TB and MB to TB.</p>
<pre><code>Free Total
30,000,000,000,000.00 40,000,000
40,000,000,000,000.00 50,000,000
</code></pre>
<p><strong>Bytes to TB - divide by 1024/1024/1024/1024 Megabytes to TB - divide by 1024/1024</s... | <p>Borrowing from <a href="https://stackoverflow.com/a/6633912/3218693">this answer using atof()</a> to avoid reinventing the wheel:</p>
<pre><code>from locale import atof, setlocale, LC_NUMERIC
setlocale(LC_NUMERIC, '')
# 'en_US.UTF-8'
df["Free_TB"] = df["Free"].apply(atof).div(1e12)
df["Tota... | python|pandas|numpy | 1 |
350,164 | 65,259,432 | Day Month extraction pandas python | <p>so recently I was doing a project where I need it to extract day and month together from a date in a dataframe in <strong>python</strong> without the year, I ended up doing by manipulating string, but I was wondering if there is a quicker way to do it using the pandas and datetime librairie , only day and month toge... | <p>I believe you need this:</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
datetime.strptime('2012-05-27', '%Y-%m-%d').strftime("%m-%d")
</code></pre> | python|pandas|dataframe|datetime | 0 |
350,165 | 65,320,503 | Reindex Pandas DataFrame with interpolated values | <p>I have a pandas DataFrame with a DateTimeIndex and the columns "Threshold", "Path":</p>
<pre class="lang-py prettyprint-override"><code> Path Threshold
2020-12-11 04:00:25.729 0.000104 -1.107422
2020-12-11 04:00:25.731 0.000387 -1.107422
2020-12-11 04:00:25.733 0... | <p>One idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a>:</p>
<pre><code>a = np.arange(df["Path"].min(), df["Path"].max(), 0.05)
df1 = pd.merge_asof(df.reset_index(),
pd.D... | python|pandas|dataframe|numpy | 1 |
350,166 | 65,175,268 | 1D Wasserstein distance in Python | <p>The formula below is a special case of the Wasserstein distance/optimal transport when the source and target distributions, <code>x</code> and <code>y</code> (also called marginal distributions) are 1D, that is, are vectors.</p>
<p><a href="https://i.stack.imgur.com/aKURS.jpg" rel="nofollow noreferrer"><img src="htt... | <p>Note that when <em>n</em> gets large we have that a sorted set of <em>n</em> samples approaches the inverse CDF sampled at 1/n, 2/n, ..., n/n. E.g.:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
plt.plot(norm.ppf(np.linspace(0, 1, ... | python|scipy|statistics|transport|numpy-random | 2 |
350,167 | 65,079,545 | Compare dataframe columns: TypeError: Cannot interpret 'StringDtype' as a data type | <p>I am trying to compare two dataframes columns and types to check for equality, the rows are expected to be different.</p>
<p>I am using pandas version 1.1.2</p>
<pre><code>pd.__version__
'1.1.2'
if (df1.columns.difference(df2.columns).empty) and
(df1.dtypes == df2.dtypes).all()
</code></pre>
<p>But ... | <p>I stumbled upon this late, but you might be able to convert them to dictionaries and compare them</p>
<pre><code>if (dict(df1.dtypes) == dict(df2.dtypes)):
return True
return False
</code></pre>
<p><a href="https://docs.python.org/3/library/stdtypes.html#mapping-types-dict" rel="nofollow noreferrer">http... | pandas | 0 |
350,168 | 65,145,069 | Efficiently filling torch.Tensor at equal index positions | <p>I have a 6 dimensional all-zero pytorch tensor <code>lrel_w</code> that I want to fill with 1s at positions where the indices of the first three dimensions and the indices of the last three dimensions match. I'm currently solving this trivially using 3 nested for loops:</p>
<pre><code>lrel_w = torch.zeros(
input_s... | <p>You can try this one.</p>
<pre class="lang-py prettyprint-override"><code>import torch
c, m, n = input_size[0], input_size[1], input_size[2]
t = torch.zeros(c, m, n, c, m, n)
i, j, k = torch.meshgrid(torch.arange(c), torch.arange(m), torch.arange(n))
i = i.flatten()
j = j.flatten()
k = k.flatten()
t[i, j, k, i, j,... | python|machine-learning|pytorch|tensor | 3 |
350,169 | 65,256,719 | How to deal with 'dynamic' dataframes using pandas? | <p>Let's say I have the following table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>X</th>
<th>Y</th>
<th>Z</th>
<th>mm</th>
<th>ff</th>
<th>cc</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>0.2</td>
<td>0.4</td>
<td>0.3</td>
</tr>
<tr>
<td></td>
<td></td>
<td></t... | <p>You can use <code>df.iterrows()</code> or you can also iterate through the normal loop and neglect the values which are equal to <code>NaN</code>. The NaN values are empty and filled by dataframe.</p> | python|pandas | 0 |
350,170 | 65,215,896 | troubles with 'WHERE...IN' clause | <p>I'm trying to run the following query through pandasql, but the output I get is not what I was expecting. I was expecting to get a table with exactly 800 rows as I am selecting the only employee_day_transmitters of the table employee_days_transmitters, but what I get is a table with more than 800 rows. What's wrong?... | <p>You are using <code>DISTINCT</code> in the CTE, so I suspect you have duplicates for the combination of the columns <code>employeeId, theDate, transmitterId</code> and this why you get more than 800 rows.<br/>
You select 800 rows in the CTE but when you use the operator <code>IN</code> in your main query, all the ro... | python|sqlite|pandasql | 0 |
350,171 | 65,109,613 | Mapping duplicate rows to originals with dictionary - Python 3.6 | <p>I am trying to locate duplicate rows in my <code>pandas</code> dataframe. In reality, <code>df.shape</code> is <code>438796, 4531</code>, but I am using this toy example below for an <a href="https://stackoverflow.com/help/minimal-reproducible-example">MRE</a></p>
<pre><code>| id | ft1 | ft2 | ft3 | ft4 | ft5 | ... | <p>Working with dictionaries in columns is really complicated, here is one possible solution:</p>
<pre><code># Declare columns I am interested in
cols = ['ft1', 'ft2', 'ft4', 'ft5']
# Create a subset of my dataframe with only the columns I care about
sub_df = df[cols]
#mask for first dupes
m = sub_df.duplicated()
#cr... | python|pandas|dataframe|duplicates | 2 |
350,172 | 65,324,814 | How could I count all the genres in my DataFrame? | <p>I have a DataFrame called df_imdb:</p>
<p><a href="https://i.stack.imgur.com/9TVxP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9TVxP.jpg" alt="enter image description here" /></a></p>
<p>Each row contains the information about a movie, This DataFrame has a column name 'genres' that shows the g... | <p>The data is a list of dictionaries, multiple options here:</p>
<p>Option 1: Pure pandas, convert the values associated with key <code>name</code> to a <code>Series</code> and use <code>value_counts</code></p>
<pre><code>df = pd.DataFrame({'genres':[[{'id': 53, 'name': 'Thriller'}, {'id': 28, 'name': 'Action'}, {'id'... | python-3.x|pandas|list|dataframe|dictionary | 3 |
350,173 | 65,073,600 | Keras Dense layer is showing too many parameters on kaggle | <pre class="lang-py prettyprint-override"><code>def my_model():
inputs = keras.Input(shape=(height,width,3))
x = layers.Conv2D(32,3)(inputs)
x = layers.BatchNormalization(input_shape=(32,32,3))(x)
x = keras.activations.tanh(x)
x = layers.MaxPooling2D(pool_size=(2,2))(x)
x = layers.Conv2D(filters... | <p>It is normal, you have a 1,107,072 neurons fully connected to 64 neurons. So the number of parameters is equal to :</p>
<ul>
<li>input_length * output_length + output_length = 1,107,072 * 64 + 64 = 70,852,672.</li>
</ul>
<p>If it's too much for your problem, you should reduce the size before the <code>flatten()</cod... | python|tensorflow|keras|deep-learning|conv-neural-network | 1 |
350,174 | 65,337,607 | TypeError: 'NoneType' object is not subscriptable for circle detection with opencv | <p>I'm trying to detect circles from my webcam input and draw over the detected objects using this code:</p>
<pre><code>circles = cv2.HoughCircles(roi_gray2, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
for i in circles[0,:]:
cv2.circle(roi_color2, tuple(i[0]), tuple(i[1]), (255,255,2... | <pre><code>circles = cv2.HoughCircles(roi_gray2, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
if circles is not None:
for i in circles[0,:]:
cv2.circle(roi_color2, tuple(i[0]), tuple(i[1]), (255,255,255), 1)
</code></pre>
<p>Is a workaround like you requested.</p>
<hr />
<p>Ho... | python|numpy|opencv | 1 |
350,175 | 65,060,020 | Pandas left join with wildcard string match | <p>I'm new to using pandas. I'm trying to search for a substring in one dataframe using a string from a different dataframe.</p>
<p><img src="https://i.stack.imgur.com/k4uwS.png" alt="screenshot of dataframes" /></p>
<p>Then, I want to merge those two dataframes based upon this match. When merging, for the rows in one ... | <p>As you are new, here are some hints for asking such a question:</p>
<p>As pointed out in the comments, you should add a minimal example such as below, that everybode can import, look at and play around with.</p>
<p>Also you should provide the ways you already tried to do so.</p>
<p>First of, wildcard merges to my kn... | python|pandas|dataframe | 1 |
350,176 | 65,284,671 | How do I divide one column in one df by another column in a different df in pandas? | <p>Here's my <a href="https://i.stack.imgur.com/X6XfT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X6XfT.png" alt="example" /></a></p>
<p>If I have two dataframes (say df4avg and df5avg) with identical corrected wavelengths and different count rates, and I want to divide the df4avg count rate by d... | <p>If you want to add the <code>ratio</code> column in the <code>df4avg</code> Dataframe then</p>
<pre><code>df4avg['ratio'] = df4avg['COUNT_RATE'] / df5avg['COUNT_RATE']
</code></pre> | python|pandas | 1 |
350,177 | 65,271,691 | How can we append or concat multiple files with mostly similar schemas but not all | <p>I am trying to combine a bunch of text files, all tab delimited, into one file, and save it as in CSV format. Some of the schemas are the same, but fields in newer files don't always exist in older files. Also, I want to add the file name in the last column in each row.</p>
<p>Field names could be like this in al... | <p>Use <code>os.path.basename(f)</code> to extract file name. And to save a new column assign with <code>[]</code> not with <code>list.append</code>.</p>
<pre class="lang-py prettyprint-override"><code>import os
...
all_df = []
for f in all_files:
df = pd.read_csv(f, delimiter='\t')
df['file'] = os.path.base... | python|pandas | 1 |
350,178 | 65,099,281 | Perform inner join using python and re-order original columns | <p>I have two datasets, df1 and df2, where:</p>
<p>I would like to perform an 'inner-join' on the <strong>date</strong> and <strong>name</strong> columns
however, I wish to re-order some of the columns as well.</p>
<p>df1</p>
<pre><code>name freeG totalG sku date
a 4 10 hi 10/10/2020
b... | <pre><code>new = pd.merge(df1, df2, how='inner',on=['name', 'date'])#merge
new['total']=new.freeS.add(new.usedS)#compute total
new1 = new[['date', 'name', 'freeG', 'totalG', 'sku', 'usedS', 'freeS', 'total']] # align columns
new1
</code></pre> | python|pandas|join|merge | 2 |
350,179 | 65,416,039 | How to perform a CSV concatenation in Python as effectively as this awk command? | <p>I'm trying to automate a file concatenation process in Python which works as effectively as the bash command line process I've been using. My bash CLI process uses <code>awk</code> to merge the files, and the Python I've tried using for this uses <code>pandas</code>.</p>
<p>For example, let's say I have a directory... | <p>You can try <code>to_csv</code> with a file stream:</p>
<pre><code>first = True
# open a file
with open('a.csv', 'w') as f:
# loop through the csv's
for pth in csv_paths:
df = pd.read_csv(pth)
# write to the stream
# only write the first header
df.to_csv(f, header=f... | python|pandas|bash|awk | 2 |
350,180 | 65,065,444 | Calculate correlation matrix between types | <p>I have dataframe <code>df</code> which includes 3 columns as follow (tab separeted):</p>
<pre><code>X Y types
0.3422 0.3214 pen
-0.1784 0.8621 pen
0.9932 0.1347 pencil
0.2847 -0.7634 pen
-0.6548 -0.2981 ruler
0.4792 0.3782 pencil
0.9231 -0.2949 ruler
</code></pre>
<p>Th... | <p>IIUC, you could do:</p>
<pre><code>res = df.groupby('types').mean().T.corr()
</code></pre>
<p><strong>Output</strong></p>
<pre><code>types pen pencil ruler
types
pen 1.0 1.0 1.0
pencil 1.0 1.0 1.0
ruler 1.0 1.0 1.0
</code></pre>
<p>You can change the correlation m... | python|pandas|correlation | 2 |
350,181 | 65,294,592 | ValueError: malformed node or string: 0 in Pandas | <p>I have a column where the values are saved as a dictionary and I used the code below to untangle the values into two separate columns, however, I am struggling with the rows that have Null values (See error msg below):
df</p>
<pre><code>product_id product_ratings
2323 {"average_rating": 4.2, ... | <p>Try to convert to dictionary, else return dictionary with default values:</p>
<pre><code>def try_literal_eval(e):
try:
return ast.literal_eval(e)
except ValueError:
return {'average_rating': 0, 'number_of_ratings': 0}
res = pd.DataFrame(df['product_ratings'].apply(try_literal_eval).tolist()... | python|pandas | 2 |
350,182 | 65,253,498 | How can i copy a python dataframe in Excel sheet with conditions in cells colors? | <p>Please, i need your help.</p>
<p>I want to copy an Excel dataframe in a Excel sheet but only on white cells, i use actuall xl wings.
<a href="https://i.stack.imgur.com/gz8er.png" rel="nofollow noreferrer">pandas dataframe</a>
<a href="https://i.stack.imgur.com/ULTNY.png" rel="nofollow noreferrer">excel sheet</a></p>... | <p>The picture of your excel sheet shows red cells without any content. That means the following solution should work.<br>
Just copy the dataframe as you already do in your question, and then delete the content of the cells with red background colour. Just add the following lines to your code:</p>
<pre><code>for cell i... | python|excel|pandas|dataframe|xlwings | 0 |
350,183 | 49,833,618 | pandas - how to convert all columns from object to float type | <p>I trying to convert all columns with '$' amount from object to float type.</p>
<p>With below code i couldnt remove the $ sign.</p>
<p>input: </p>
<pre><code>df[:] = df[df.columns.map(lambda x: x.lstrip('$'))]
</code></pre> | <p>You can using <code>extract</code></p>
<pre><code>df=pd.DataFrame({'A':['$10.00','$10.00','$10.00']})
df.apply(lambda x : x.str.extract('(\d+)',expand=False).astype(float))
Out[333]:
A
0 10.0
1 10.0
2 10.0
</code></pre>
<p>Update</p>
<pre><code>df.iloc[:,9:32]=df.iloc[:,9:32].apply(lambda x : x.str.extr... | pandas|type-conversion | 2 |
350,184 | 49,919,650 | Retrieval of single entry by np.datetime index value failing, but not failing by range | <p>I have a pandas dataframe, whose index is based on the numpy datetime type.</p>
<p>I can easily access a range of dataframe entries:</p>
<pre><code>for t in df.index.values:
print(df[:t])
</code></pre>
<p>However have problems (KeyError) whenever I try to access a specific value.</p>
<pre><code>for t in df.i... | <p>Try this:</p>
<pre><code>for t in df.index:
print(df.loc[t])
</code></pre> | python|pandas|numpy|time-series | 0 |
350,185 | 50,030,887 | Distributed tensorflow : What is the job of chief worker? | <p>I am using a version of the distributed tensorflow example <a href="https://www.tensorflow.org/deploy/distributed" rel="nofollow noreferrer">https://www.tensorflow.org/deploy/distributed</a>
Here is my code in "mnist_trainer.py".</p>
<pre><code>import math
import tensorflow as tf
from tensorflow.examples.tutorials.... | <p>According to <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/train_and_evaluate" rel="nofollow noreferrer">the TensorFlow documentation for <code>tf.estimator.train_and_evaluate</code></a>:</p>
<blockquote>
<p>…[T]he chief worker also does the model training job, similar to other non-chief... | tensorflow | 0 |
350,186 | 49,822,933 | 'Reuse' a single tensorflow model in different graphs? | <p>Currently, I am working with a pretrained VGG model in Tf-Slim library. My motivation is to generate adversarial examples for a given image for this netowrk. The summary of task is:</p>
<pre><code>x= tf.placeholder(shape=(None, 32, 32,3), dtype=tf.float32)
for i in range(2):
logits= vgg.vgg_16(x, is_training=Fa... | <p>In tfslim/models/research/slim/nets/vgg.py:</p>
<p>add a reuse parameter in the vgg16 or vgg19 definition</p>
<pre><code>def vgg_16(inputs,
num_classes=1000,
is_training=True,
dropout_keep_prob=0.5,
spatial_squeeze=True,
scope='vgg_16',
fc_conv_padd... | tensorflow|deep-learning|keras|tensorflow-slim | 1 |
350,187 | 50,065,798 | filtering grouped pandas dataframe by all records being the same | <p>I'm looking to filter a grouped pandas dataframe to groups where all the values in the group are the same.</p>
<p><strong>reproducible data:</strong></p>
<pre><code>df = pd.DataFrame({'group':['A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
'value3':[24, 45, 34, 55, 44, 33, 1, 2, ... | <p>You just need add <code>all</code> </p>
<pre><code>df.groupby('group').filter(lambda x: (x.value3 == x.value3.mean()).all())
Out[409]:
group value3
9 C 98
10 C 98
11 C 98
</code></pre> | python|pandas | 4 |
350,188 | 49,923,958 | Tensorflow custom activation function | <p>I implemented a network with TensorFlow and created the model doing the following in my code:</p>
<pre><code>def multilayer_perceptron(x, weights, biases):
layer_1 = tf.add(tf.matmul(x, weights["h1"]), biases["b1"])
layer_1 = tf.nn.relu(layer_1)
out_layer = tf.add(tf.matmul(layer_1, weights["out"]), bia... | <p>I try to answer my own question. Here is what I did and what seems to work:</p>
<p>First I define a custom activation function:</p>
<pre><code>def custom_sigmoid(x, beta_weights):
return tf.sigmoid(beta_weights*x)
</code></pre>
<p>Then I create weights for the activation function:</p>
<pre><code>beta_weights... | tensorflow|activation-function | 4 |
350,189 | 49,980,801 | PyTorch 3 reshaping error | <p>When training a CNN using PyTorch in Python, I get the following error:</p>
<pre><code>RuntimeError: invalid argument 2: size '[-3 x 3136]' is invalid for input with 160000 elements at /opt/conda/conda-bld/pytorch-cpu_1515613813020/work/torch/lib/TH/THStorage.c:41
</code></pre>
<p>This is related to the x.view lin... | <p>I will assume your input images are probably of size <code>200x200px</code> (by <code>size</code> I mean here <code>height x width</code>, not taking the number of channels into account).</p>
<p>While your <code>nn.Conv2d</code> layers are defined to output tensors of the same size (with 32 channels for <code>conv1... | python|size|reshape|pytorch | 1 |
350,190 | 50,085,252 | How to replace string in different position in sentence by another column | <p>I have problem how to replace string in another position than 0 in sentence using my function.</p>
<p>I want to replace string in col2 from string in col1 (always lowercase)</p>
<p>For example I want try replace:</p>
<pre><code>input: Hello Aaa1 my very good friend
output: Hello NNP my very good friend
</code></p... | <p>Using re</p>
<pre><code>import re
inp = "Hello Aaa1 my very good friend"
output = "Hello NNP my very good friend"
re.sub("Aaa1", "NNP", output)
</code></pre>
<p>Using pandas </p>
<pre><code>import pandas as pd
df = pd.DataFrame(data={"col": [inp]})
df["col"].str.replace("Aaa1", "NNP")
</code></pre> | python|python-3.x|pandas | 0 |
350,191 | 50,151,417 | Numpy find indices of groups with same value | <p>I have a numpy array of zeros and ones:</p>
<p><code>y=[1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1]</code></p>
<p>I want to calculate the indices of groups of ones (or zeros). So for the above example the result for groups of ones should be something similar to:</p>
<p><code>result=[(0,2), (8,9), (16,19)]</code></p>... | <p>We can do something like this that works for any generic array -</p>
<pre><code>def islandinfo(y, trigger_val, stopind_inclusive=True):
# Setup "sentients" on either sides to make sure we have setup
# "ramps" to catch the start and stop for the edge islands
# (left-most and right-most islands) respectiv... | python|arrays|numpy | 9 |
350,192 | 49,842,290 | is it efficient to have a global variable when using multiprocessing? | <p>Please consider this cool setup:</p>
<pre><code>from multiprocessing import Pool, cpu_count
import pandas as pd
import numpy as np
def helper(master_df):
max_index = master_df['key'].max()
min_index = master_df['key'].min()
#note how slave is defined before running the multiprocessing
return slave.... | <p>This surprisingly depends on the operating system, as <a href="http://rhodesmill.org/brandon/2010/python-multiprocessing-linux-windows/" rel="nofollow noreferrer"><code>multiprocessing</code> is implemented differently in Windows and Linux</a>.</p>
<ul>
<li><p>In Linux, under the hood, processes are created via a <... | python|pandas|multiprocessing|python-multiprocessing | 4 |
350,193 | 49,873,805 | Python export csv with pandas | <p>I have a problem after exporting the dataframes into a csv file. </p>
<pre><code>start = __datetime(startTime)
end = __datetime(endTime)
delta = end - start
durationList.append(delta)
dataFrame = {"Duration": durationList}
outPutFile = pd.DataFrame(dataFrame, columns=["Duration"])
outPutFile.to_csv('Extract data... | <p>One solution is to convert your series to a <code>datetime</code> object, then use <code>pd.Series.dt.strftime</code>.</p>
<p>CSV files are not type sensitive, so converting to string is a reliable way of ensuring your output is in the format you expect.</p>
<pre><code>df = pd.DataFrame({'Duration': ['00:00:00.001... | python|pandas | 0 |
350,194 | 50,075,961 | Breaking TensorFlow gradient calculation into two (or more) parts | <p>Is it possible to use TensorFlow's <code>tf.gradients()</code> function in parts, that is - calculate the gradient from of loss w.r.t some tensor, and of that tensor w.r.t the weight, and then multiply them to get the original gradient from the loss to the weight?</p>
<p>For example, let <code>W,b</code> be some we... | <p><code>tf.gradients</code> will sum over the gradients of the input tensor. To avoid it you have to split the tensor into scalars and apply <code>tf.gradients</code> to each of them:</p>
<pre><code>import tensorflow as tf
x = tf.ones([1, 10])
w = tf.get_variable("w", initializer=tf.constant(0.5, shape=[10, 5]))
ou... | tensorflow|automatic-differentiation | 1 |
350,195 | 49,827,603 | Is there a way to extract the k diagonals of an (k,n,n) tensor in TensorFlow or Keras? | <p>In the post <a href="https://stackoverflow.com/questions/33700049/get-the-diagonal-of-a-matrix-in-tensorflow">Get the diagonal of a matrix in TensorFlow</a> for an square matrix (n,n), one sugestion are use the function tf.diag_part(tensor). But if the tensor are dimensions (k,n,n) ? Exist any way to do that? The ne... | <p>You can use <code>tf.map_fn</code>, from the <a href="https://www.tensorflow.org/api_docs/python/tf/map_fn" rel="nofollow noreferrer">documentation</a>:</p>
<blockquote>
<p>Map on the list of tensors unpacked from elems on dimension 0.</p>
</blockquote>
<p>So you just need to map <code>tf.diag_part</code>:</p>
... | python|tensorflow|keras|diagonal | 0 |
350,196 | 49,945,462 | Tensorflow: No improvement in loss while training neural net | <p>I made this neural net but every time I run this it gives me different loss to start with which remains constant for the complete loop. I want to predict one value in 'yy' for every 3 values in 'xx' as input. Also how can I show my output? For example: I want to show an array having predictions as close as possible ... | <p>I am not sure what exactly you are trying to accomplish, but it seems to me this is a regression problem, not a classification problem. I think the following code is what you want. I have cleaned it up a little bit but still tried to keep it in a way you would recognize it. I would personally write this in a differe... | python|tensorflow|machine-learning|deep-learning|tensor | 1 |
350,197 | 49,862,270 | Does tf.zeros() return tf.get_variable()? | <p>Trying to understand the <code>SGD</code> optimization code in keras optimizers (<a href="https://github.com/keras-team/keras/blob/master/keras/optimizers.py" rel="nofollow noreferrer">source code</a>). In the <code>get_updates</code> module, we have:</p>
<pre><code># momentum
shapes = [K.int_shape(p) for p in par... | <p>I think you missed the right <code>K.zeros</code> function. Here's the source code in keras 2.1 (<a href="https://github.com/keras-team/keras/blob/keras-2/keras/backend/tensorflow_backend.py#L494" rel="nofollow noreferrer"><code>keras/backend/tensorflow_backend.py</code></a>):</p>
<pre class="lang-py prettyprint-... | python|tensorflow|machine-learning|keras|gradient-descent | 2 |
350,198 | 50,084,579 | Tensorflow, use a tf.estimator trained model within another tf.estimator model_fn | <p>Is there a way to use tf.estimator trained model A in another model B?</p>
<p>Here is situation,
Let say I have a trained 'Model A' with model_a_fn().
'Model A' gets images as input, and outputs some vector floating values similar to MNIST classifier.
And there is another 'Model B' which is defined in model_b_fn().... | <p>I've figured out one solution to this problem.</p>
<p>One can use this method if struggling with same problem.</p>
<ol>
<li>create a function which runs tensorflow.contrib.predictor.from_saved_model() -> call it 'pretrained_predictor()'</li>
<li>inside Model B's model_fn(), call above predefined 'pretrained_predic... | python|tensorflow | 1 |
350,199 | 50,189,331 | Line removal in image captcha using Python | <p>I had used this link - <a href="https://stackoverflow.com/questions/42736616/how-to-remove-line-from-captcha-completely">How to remove line from captcha completely</a> and edited the code provided to remove lines from a dummy captcha that I have given below</p>
<p><a href="https://i.stack.imgur.com/xFbjs.png" rel="... | <p>In this special case it seems density of lines is less than characters density.
so by applying some thresholding methods you can remove line:</p>
<p>For example the following line give you this:</p>
<p><a href="https://i.stack.imgur.com/Ofv0t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ofv0t... | python|numpy|opencv|image-processing | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.