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
365,100
60,027,825
Stable baselines saving PPO model and retraining it again
<p>Hello I am using Stable baselines package (<a href="https://stable-baselines.readthedocs.io/" rel="nofollow noreferrer">https://stable-baselines.readthedocs.io/</a>), specifically I am using the PPO2 and I am not sure how to properly save my model... I trained it for 6 virtual days and got my average return to aroun...
<p>The way you saved the model is correct. The training is not a monotonous process: it can also show much worse results after a further training.</p> <p>What you can do, first of all is to write logs of the progress:</p> <pre class="lang-py prettyprint-override"><code>model = PPO2(MlpPolicy, envs, tensorboard_log="....
python|tensorflow|reinforcement-learning|stable-baselines
2
365,101
60,034,119
How can I convert the python code that combines low frequency categories/values to a function that can be applied to any pandas dataframe column?
<p>For this <a href="https://stackoverflow.com/questions/47418299/python-combining-low-frequency-factors-category-counts">solution</a> Is there an easy way to define this code within a function such that i can apply it to any dataframe column. </p>
<p>Solution should be simplify with <code>normalize=True</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_counts</code></a>:</p> <pre><code>def replace_thresh(df, col, thresh, new_val): s = df[col].value_count...
python|pandas|data-science
1
365,102
59,914,752
Pandas: why doesn't dot product work even after choosing the correct number of columns?
<p>I'm trying to take the dot product of a pandas DataFrame and Series. However, even when I restrict the pandas DataFrame to have the same number of columns as the Series, I still get</p> <blockquote> <p>ValueError: matrices are not aligned.</p> </blockquote> <pre><code>import pandas as pd df1 = pd.DataFrame([[0, ...
<p>It's the indices that don't match! If you convert both <code>df2</code> and <code>s</code> to arrays it works:</p> <pre><code>&gt; df2.iloc[:, 1:len(df2.columns)].values @ s.values array([-2, 5]) </code></pre> <p>Also If you have the index of s start with 1:</p> <pre><code>&gt; s.index = [1,2,3,4] &gt; df2.iloc[...
python|pandas
1
365,103
60,201,578
How to transform data from paginated API to pandas DataFrame in python
<p>I need to get some data from a REST API for the creation of a web-map. I want to have a look first at the data and that's why I try to transform json into pandas dataframe. When it is just one page from API my code (below) works well, but when I'm looping through all pages and storing results in a list it gives me a...
<p>The issue is solved. There were some strings that got into the list of responses from API along with dicts. Checked and deleted them with the following code: </p> <pre><code>all(isinstance(x, dict) for x in api_dataset) #check if there only dicts for x in api_dataset: if type(x) == str: api_dataset.r...
python|json|pandas|api
0
365,104
60,094,850
multi hot encoding in tensorflow using tf.data.Dataset
<p>I have a problem with the TF api tf.data.Dataset.from_tensor_slices()</p> <p>The code below works well :</p> <pre><code>features = {'letter': [['A','A'], ['C','D'], ['E','F'], ['G','A'], ['X','R']]} letter_feature = tf.feature_column.categorical_column_with_vocabulary_list( "letter", ["A", "B", "C...
<p>Elaborating Richard_wth's comment for the <strong>benefit of the community</strong>.</p> <p>The Error, <code>TypeError: Expected binary or unicode string, got ['A', 'A', 'A']</code> can be resolved by making the changes mentioned below:</p> <pre><code>1. tf.data.Dataset.from_tensor_slices((dict(X), tf.one_hot(y, d...
tensorflow|tensorflow-datasets|tensorflow-estimator
1
365,105
60,120,849
Outputting attention for bert-base-uncased with huggingface/transformers (torch)
<p>I was following <a href="https://www.aclweb.org/anthology/P19-1328/" rel="noreferrer">a paper</a> on BERT-based lexical substitution (specifically trying to implement equation (2) - if someone has already implemented the whole paper that would also be great). Thus, I wanted to obtain both the last hidden layers (onl...
<p>I think it's too late to make an answer here, but with the update from the huggingface's transformers, I think we can use this</p> <pre><code>config = BertConfig.from_pretrained('bert-base-uncased', output_hidden_states=True, output_attentions=True) bert_model = BertModel.from_pretrained('bert-base-uncased', con...
python|attention-model|huggingface-transformers|bert-language-model
5
365,106
60,275,633
MinMaxScaling vs L1/L2-Normalization
<p>I'm wondering about the difference or the application of the different types of rescaling data.</p> <p>So far, I'm aware that standardization assumes the data has a gaussian distribution. So if this is the case we should standardize and get values in normal distribution N~(0,1). </p> <p>If our model does not has a...
<p>Regularization doesn't apply to rescaling data.</p>
python|tensorflow|neural-network|statistics|data-science
1
365,107
60,092,755
Pandas filtering with multiple conditions
<p>I'm trying to filter data with multiple conditions using <strong>.isin</strong></p> <p>I've created a dataframe with data like this.</p> <pre><code> col_a col_b col_c abc yes a abc no b abc yes a def no b def yes a def no b def ...
<p>You need:</p> <pre><code>fil_1 = test['col_a'].isin(['abc','def','ghi']) fil_2 = test['col_b'].isin(['yes']) fil_3 = test['col_c'].isin(['a']) </code></pre> <p>or</p> <pre><code>test.isin({'col_a': ['abc','def','ghi'], 'col_b': ['yes'], 'col_c' :['a']}).all(axis = 1) </code></pre> <hr> <pr...
python|pandas|numpy
1
365,108
60,325,789
Use groupby and find ratio
<p>Input:</p> <pre><code> Boro Completed? 0 M Y 1 M Y 2 Q N 3 Q Y 4 Q Y </code></pre> <p>Desired output:</p> <pre><code> Boro Completed? Ratio 0 M Y 1 1 M Y 1 2 Q N 0.67 3 Q Y 0.67 4 Q ...
<p>We do <code>transform</code> </p> <pre><code>s=df['Completed?'].ne('N').groupby(df['Boro']).transform('mean') Out[66]: 0 1.000000 1 1.000000 2 0.666667 3 0.666667 4 0.666667 Name: Completed?, dtype: float64 df['ratio']=s </code></pre>
python|pandas
0
365,109
60,049,444
why pandas create DataFrame in the order of sorted key? I did not do the sort
<p>code:</p> <pre><code>import pandas as pd data = pd.DataFrame({'Temp':[0,20,40,60],'Pressure':[0.0002,0.0012,0.0060,0.0300]}) print(data) </code></pre> <p>outcome:</p> <pre><code> Pressure Temp 0 0.0002 0 1 0.0012 20 2 0.0060 40 3 0.0300 60 </code></pre> <p>However, I want this:</p> <...
<p>That's because you are using <code>python3.5</code> or lower, so dictionaries don't maintain insertion order, in your case use an OrderedDict like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from collections import OrderedDict data = pd.DataFrame(OrderedDict({'Temp':[0,20,40,60],'...
python|pandas
0
365,110
60,330,089
python: creating a new column with values based on another column and then concat.?
<p>I've been browsing through the form, and I don't think if this has been asked before. </p> <p>I'm new to python, and I'm trying to make a script so I don't have to do manual fixes to a .csv file. I have two states where the downloaded .csv file does not give numeric values or GEOID for districts. </p> <p>I want th...
<p>Update: Resolved my own issue! In case anyone else has the same issue: </p> <p>I made a standalone table with values associated to the district, state and chamber, along with the values I wanted to add (GEOID and corrected values that would be understood by a shapefile). </p> <p>I then coded for that file to be jo...
python|pandas
1
365,111
59,936,299
Load Pandas dataframe into Hive with int64 datatype
<p>I'm getting an error when loading a pandas dataframe that contains a column with a datatype as int64 into a hive table.</p> <p>When I exclude the int64 datatypes the data loads to hive, but it fails when I include the data types. An extract of the data values for B and C are <code>12,12345678</code> </p> <p>Pandas...
<p>change datatype from int to bigint in the create table statement</p>
pandas|hadoop|hive
0
365,112
60,046,650
Pandas conditionally set column value
<p>I have the following excel</p> <pre><code> A B 'Text1' NaN 'Text2' 'Text7' 'Text3' 'Text8' 'Text4' NaN 'Text5' NaN </code></pre> <p>I would like to set a third column conditionally</p> <p>Set C column as A + '_' + B only if B is not empty. If B is empty set C to A</p> <pre><code> A ...
<p><strong>Are you looking for something like this ?</strong></p> <pre><code>df.fillna(value=0, inplace=True) df['C'] = df.A + df.B import numpy as np df.replace(0, np.nan, inplace=True) A B C 0 1 NaN 1.0 1 2 4.0 6.0 2 3 5.0 8.0 3 4 NaN 4.0 4 5 NaN 5.0 </code></pre>
python|pandas
0
365,113
59,913,283
Convert 1D array in to row or column vector in Numpy
<p>I am confused by NumPy concepts of array and vector, let's say we have a 1-D array as below. From the 'shape' method, I can see the dimension. <code>(10,)</code> means 1 dimension with 10 elements. </p> <pre><code>a = np.arange(10) print(a) a.shape [0 1 2 3 4 5 6 7 8 9] (10,) </code></pre> <p>Now I got to know a ...
<p>Please note that <strong>DIMENSION</strong> word may take different sense in different context. For example in linear algebra (1, 1) is a vector in the 2D space and (1, 1, 1) is the vector in the 3D space and both of them are 1D arrays in programming langages. The collection of 3D vectors is matrix in linear algebra...
python-3.x|numpy
2
365,114
60,016,845
Numpy get column of two dimensional matrix as array
<p>I have a matrix that looks like that:</p> <pre><code>&gt;&gt; X &gt;&gt; [[5.1 1.4] [4.9 1.4] [4.7 1.3] [4.6 1.5] [5. 1.4]] </code></pre> <p>I want to get its first column as an array of <code>[5.1, 4.9, 4.7, 4.6, 5.]</code> However when I try to get it by <code>X[:,0]</code> i get </p> <pre><code>&gt;&gt; ...
<p>With regular numpy array:</p> <pre><code>In [3]: x = np.arange(15).reshape(5,3) In [4]: x Out[4]: ar...
numpy
0
365,115
60,098,020
How to read file in pandas with unfix whitespace/s separation?
<p>I have a <em>textfile</em> that contains 2 columns of data. They are separated with unfix number of whitespace/s. I want to load it on a <em>pandas</em> DataFrame.</p> <p>Example:</p> <pre><code> 306.000000 1.125783 307.000000 0.008101 308.000000 -0.005917 309.000000 0.003784 310.00000...
<p>Use <code>read_csv</code>:</p> <pre><code>df = pd.read_csv('file.txt', sep='\\s+', names=['Wavelength', 'Reflectance'], header=None) </code></pre>
python|pandas
3
365,116
60,330,687
Numpy function output increases with every run
<p>Minimum working example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np datatest = np.array([[1, 2, 3], [1, 1, 2], [3, 3, 3]]) def sumcols(data): temp = np.empty(data.shape[0]) for i in range(data.shape[0]): for j in range(data.shape[1]): temp[i] += data[i,j] ...
<p>Want to see something even more fun? If you change the definition of <code>sumcols</code> to:</p> <pre><code>def sumcols(data): temp = np.empty(data.shape[0]) temp2 = np.empty(data.shape[0]) for i in range(data.shape[0]): for j in range(data.shape[1]): temp2[i] += data[i,j] retur...
python|arrays|numpy
1
365,117
60,030,949
How do I get words left and right of an underscore from a strings in another column? Python
<p>I have concatenated all .csvs in my directory into one big dataframe and one of the columns is the filename of each file.</p> <p>These are my file names:</p> <pre><code>['Accelerometer-2011-05-30-09-36-50-brush_teeth-f1.txt', 'Accelerometer-2011-05-30-08-35-11-brush_teeth-f1.txt', 'Accelerometer-2011-06-02-10-...
<p>I agree with the comments. Depending on the stability of the naming pattern, you don't need regex at all. You could solve it like this:</p> <pre><code>mylist = ['Accelerometer-2011-05-30-09-36-50-brush_teeth-f1.txt', 'Accelerometer-2011-05-30-08-35-11-brush_teeth-f1.txt', 'Accelerometer-2011-06-02-10-45-50-wash_f...
python|regex|pandas|dataframe
1
365,118
60,267,625
Conditional flag based on Groupby Python
<p>I want to use conditional statements to create flag based on id and precedence order -</p> <p>Dataframe -</p> <pre><code> df=pd.DataFrame({'id':[1,1,1,1,2,3,3,3], 'var':['Apple','Banana','Orange','Mango', 'Mango', 'Banana','Orange','Mango'], 'flag':[1,1,1,1,1,1,1,1]}) </code></pre> <p>Precedence ord...
<p>We can loop through each chunk of the <code>GroupBy</code> object and set the <code>flag</code> column to the value required where rows meet the certain condition using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a>.</p> ...
python|pandas|numpy
1
365,119
60,237,939
How do I correctly define a function having numpy arrays as argument and return type?
<p>As I see it, there are two options.(Here numpy is imported as np)</p> <p><strong>1. Using a lambda expression</strong></p> <p>This can be used when we are dealing with a simple function. Say I want to implement the function f:(x,y) = (x^2, x+y). Then I would expect some like this to work: </p> <p><code>f = lambda...
<p>It really doesn't matter whether you use <code>lambda</code> or <code>def</code>, or do the calculation with locally defined variables. If using functions, the number of input arguments has to match the definition.</p> <p>But let's demonstrate with simple interactive examples</p> <p>Define two variables:</p> <pr...
python|arrays|numpy
1
365,120
60,197,584
How to sort a 3D numpy array according to a column?
<p>For a 2d array, a, we can sort using</p> <pre><code>a = a[a[:, 0].argsort] </code></pre> <p>if we want to sort by column 0. How to do a similar thing for a 3d matrix? If we have </p> <pre><code> a = [[[ 1., 2., 10.], [ 4., 5., 6.], [ 2., 3., 4.]], [[ 2., 3., 4.], [ 4., ...
<p>I hope this can help:</p> <pre><code>COL = 0 DIM0 = 3 a[:, a[:, :, COL].argsort()][np.diag_indices(DIM0)] </code></pre>
python|numpy|sorting
1
365,121
65,199,897
Weighted categorical cross entropy
<p>please I'm trying to build an NLP classifier on top of BERT but I'm struggling with data imbalance. I'm looking for an implementation of weighted CategoricalCrossEntropy. I've already seen a solution using <code>class_weight</code> parameter on <code>fit</code> function but it doesn't &quot;fit&quot; well with my da...
<p>The <code>__call__</code> method of <a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/CategoricalCrossentropy" rel="nofollow noreferrer"><code>tf.losses.CategoricalCrossentropy</code></a> accepts three arguments:</p> <pre><code>y_pred y_true sample_weights </code></pre> <p>And the <code>sample_weig...
python|tensorflow|keras|loss-function
4
365,122
65,265,161
How to understand "torch.randn()" size* parameter arguments?
<p>From what I understand, <code>torch.randn(layers/depth, rows, columns)</code>, which can be seen when executing: <code>torch.randn(2, 3, 3)</code> ==&gt; 2 layers (3x3) matrix:</p> <pre><code>tensor([[[ 1.4838, 1.2926, 1.6147], [ 0.7923, 0.6414, -0.2676], [-0.1949, 0.3859, -0.6940]], [[ 0.2454, -1...
<p>Each number you are introducing refers to a dimension of the matrix. It is hard for humans to visualize more than 3 dimensions, but computers are fine with it.</p> <p>In this particular case, you can think about the extra dimension as something like a batch size.</p>
python|python-3.x|pytorch|torch
1
365,123
65,159,909
Dot-product a list of Matrices in numpy
<p>Let's generate a 'list of three 2x2 matrices' that I call M1, M2 and M3:</p> <pre><code>import numpy as np arr = np.arange(4*2*2).reshape((3, 2, 2)) </code></pre> <p>I want to take the dot product of all these matrices:</p> <pre><code> A = M1 @ M2 @ M3 </code></pre> <p>What's the easiest and fastest way to do this? ...
<p>You are probably looking for <a href="https://numpy.org/doc/stable/reference/generated/numpy.linalg.multi_dot.html" rel="nofollow noreferrer"><code>np.linalg.multi_dot</code></a>:</p> <pre><code>arr = np.arange(3*2*2).reshape((-1, 2, 2)) np.linalg.multi_dot(arr) </code></pre> <p>Will give you the dot product between...
python|numpy|linear-algebra|numpy-ndarray|numpy-einsum
1
365,124
65,311,194
Trouble sorting pandas columns by label, no methods seem to work for me?
<p>As part of a larger project I need to gather a large amount of data, fix any nan values, organise them then plot them. Pandas seems like an ideal package to do this with. I'm having difficulty getting my latest test batch to behave, however.</p> <p>My column labels are all numbers, so it shouldn't be difficult to so...
<p>Am I right that you want to sort your index twice? If your data_table is correct after the line <code>df.from_dict(nested_dict)</code> than this should do it for you.</p> <pre><code>data_table = data_table.sort_index(axis=0).sort_index(axis=1) data_table </code></pre> <p>Please try it.</p>
python|pandas
1
365,125
65,182,649
Logistic Regression Cifar10- image classification using tensorflow 1.x
<p>I'm trying to implement a simple logistic regression for image classification using the Cifar10 dataset. I'm only allowed to use TensorFlow 1.x for the training. (I am allowed to use Keras and other libraries for manipulating the data)</p> <p>My problem is that the model I built does not learn ... All epochs give va...
<p>So you got three problems</p> <ol> <li><p>Uncomment these two lines:</p> <pre><code># x_train /= 255 # x_test /= 255 </code></pre> </li> </ol> <p>You should normalize your input.</p> <ol start="2"> <li><p>The loss is not the mean of the log losses, but only the sum (you are working with mutually exclusive classes)</...
tensorflow|machine-learning|deep-learning|logistic-regression|tensorflow1.15
1
365,126
65,254,115
Pandas filtering by column list
<p>I want to create a function that returns a data frame that is DataFrame 'data' filtered to include only the columns specified by my list good_columns.</p> <pre><code>def filter_by_columns(data,columns): data = data[[good_columns]] #this is running an error when calling for my next line for: filter_data = filete...
<p>Instead of creating a function, you can the following:</p> <p>Assuming your main <code>dataframe</code> is called <code>df</code>, you can create a new one with only the columns you specify using the below code,</p> <pre><code>cols_to_keep = ['c1','c2','c3'] # just enter the column names you want to keep data = df[[...
python|pandas|dataframe
1
365,127
65,361,534
Python Pandas create new columns from existing one avoiding row iteration
<h2>Heading ##I have this df['title'] column:</h2> <pre><code>Apartamento en Venta Proyecto Nuevo de Apartamentos Proyecto Nuevo de Apartamentos Lote en Venta Casa Campestre en Venta Proyecto Nuevo de Apartamentos </code></pre> <p>Based on this column I want to create three new ones:</p> <pre><code>df['...
<p>You can make a function and use the .apply function- might be faster although you are still iterating.</p> <pre><code>def property_split(row): if row['delta_points'] == 'apartment: return 1 else: return 0 df['apartment'] = df.apply (lambda row: property_split(row), axis=1) </c...
python|pandas
1
365,128
65,451,427
Display 2 decimal places, and use comma as separator in pandas?
<p>Is there any way to replace the dot in a float with a comma and keep a precision of 2 decimal places?</p> <p>Example 1 : 105 ---&gt; 105,00</p> <p>Example 2 : 99.2 ---&gt; 99,20</p> <p>I used a lambda function <code>df['abc']= df['abc'].apply(lambda x: f&quot;{x:.2f}&quot;.replace('.', ','))</code>. But then I have ...
<p>Let us try</p> <pre><code>out = (s//1).astype(int).astype(str)+','+(s%1*100).astype(int).astype(str).str.zfill(2) 0 105,00 1 99,20 dtype: object </code></pre> <p>Input data</p> <pre><code>s=pd.Series([105,99.2]) </code></pre>
python-3.x|pandas|dataframe
1
365,129
65,089,695
How do change a data type of all columns in python
<p>I am using pandas data frames. The data contains 3032 columns. All the columns are 'object' datatype. How do I convert all the columns to 'float' datatype?</p> <p><a href="https://i.stack.imgur.com/TNolH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TNolH.jpg" alt="enter image description here"...
<p>If need convert integers and floats columns use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferre...
python|pandas
3
365,130
65,466,781
Pickle data not loading
<p>Here I the data I try to save as a &quot;pickle file&quot;</p> <pre><code>import pandas as pd import pickle as pkl df_1 = pd.DataFrame({'TIME': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'speed': [2, 3, 7, 6, 13, 24, 31, 64, 100, 202], 'altitude': [10, 2, 1, 8, 5, 3, 7, 8, 13, 6], 'angle': [10, 2, 1, 8, 3...
<p><code>pkl.load</code> returns the loaded object. Your code immediately discards it. You should assign in to a variable:</p> <pre><code>loaded = pkl.load(f) </code></pre>
python|pandas|tuples|pickle|spyder
2
365,131
65,304,056
Convert " 24OCT2020:00:00:00" format into datetime
<p>I have column of strings as <code> 24OCT2020:00:00:00</code>. I want to convert it to date-time. I have tried - <code>data[&quot;START_DATE&quot;] = pd.to_datetime(data[&quot;START_DATE&quot;])</code> but getting following error - <code>ParserError: Unknown string format: 24OCT2020:00:00:00</code>. Help me in this r...
<p>Add parameter <code>format</code> with <code>%d%b%Y:%H:%M:%S</code> for match <code>ddmmmyyyy:HH:MM:SS</code>, for months is use <code>%b</code> for first 3 letters of months names:</p> <pre><code>data = pd.DataFrame({'START_DATE':['24OCT2020:00:00:00','25OCT2020:00:00:00']}) data[&quot;START_DATE&quot;] = pd.to_dat...
python|pandas|datetime|python-datetime
3
365,132
65,310,095
Getting nan as loss value
<p>I have implemented focal loss in Pytorch with using of this <a href="https://arxiv.org/pdf/1708.02002.pdf" rel="nofollow noreferrer">paper</a>. And ran into a problem with loss - got nan as loss function value.</p> <p>This is implementation of focal loss:</p> <pre><code>def focal_loss(y_real, y_pred, gamma = 2): ...
<p>This version is working:</p> <pre><code>def focal_loss(y_real, y_pred, eps = 1e-8, gamma = 0): probabilities = torch.clamp(torch.sigmoid(y_pred), min=eps, max=1-eps) return torch.mean((1 - probabilities)**gamma * (y_pred - y_real * y_pred + torch.log(1 + torch.exp(-y_pred)))) </code></pre>
deep-learning|pytorch|loss-function
1
365,133
65,277,703
image normalization and TPU
<p>I'm trying to incorporate image normalization in my keras model to run on Google's cloud TPU. Therefore I inserted a line into my code:</p> <pre><code>with strategy.scope(): input_shape=(128,128,3) image_0 = Input(shape=input_shape) **image_1 = tf.image.per_image_standardization(image_0)** ... </...
<p>From the TensorFlow Model Garden reference for ResNet, the mean and standard deviation of a dataset is often calculated beforehand and each batch is standardized via mean subtract and dividing by the standard deviation. See <a href="https://github.com/tensorflow/models/blob/master/official/vision/image_classificatio...
tensorflow|tpu|data-augmentation
0
365,134
65,275,736
Numpy select elements with a condition along axis
<p>I have a 2D numpy array x as:</p> <pre><code>[ [ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 23, 24], [25, 26, 27], [28, 29, 30], [31, 32, 33], [34, 35, 36], [37, 38, 39], [40, 41, 42], [43, 44, 45], [46, 47, 48], ...
<p>One way would be this:</p> <pre><code>import numpy as np # x is your array x1 = (x &lt; 25).sum(axis = 1) rows = np.where(x1 &gt; 0)[0] </code></pre> <p>The row indices are in <code>rows</code> as <code>array([0, 1, 2, 3, 4, 5, 6, 7])</code>.</p> <p>You can also use <code>nonzero</code> as:</p> <pre><code>rows = np....
python|numpy|conditional-statements|numpy-ndarray
5
365,135
65,086,213
Python: How do I check if the last three number of a variable to be 000 or not?
<p>Incorporating with excel, I'm looking for a solution that would check if a company code ends with a 000 or not (anything else) by implementing if statements. The output should be a True or false statement. I do not know how exactly to start. I thought of using switches, but I do not exactly know how to implement a f...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.endswith.html" rel="nofollow noreferrer"><code>Series.str.endswith</code></a> for test some column, here <code>column</code>:</p> <pre><code>#if necessary convert file to DataFrame df = pd.read_excel(file) df['test'] = df['colu...
python|excel|pandas|xlsxwriter
3
365,136
65,155,534
Sum series in pandas dataframe in two ways
<p>I am training on pandas and how to sum a series in a DataFrame. And I could use two ways using list and normal variable. The code is like that</p> <pre><code>import pandas as pd url = 'http://bit .ly/imdbratings' df = pd.read_csv(url , chunksize=250) result = [] for chunk in df: result.append(sum(chunk['duratio...
<p>The chunk is changing while calling. In my opinion this is an unexpected behavior and it has to be investigated.</p> <p>If you print a number for each iteration you can see that you do npt enter the seconde code block and that's why your <code>total</code>variable stays at zero.</p> <p>Try to run:</p> <pre><code>url...
python|pandas|series
1
365,137
65,204,305
Pandas : add a prefix to data following a certain position
<p>I try to add a prefix in front of &quot;Label&quot; type data under certain conditions.</p> <p>Example of my actual data :</p> <pre><code> Label Word 9 O 10 PERSON J 11 PERSON Chirac 12 O Les 13 O ...
<p>Let's create two boolean masks where the first boolean mask <code>m1</code> represent the condition where <code>Label</code> is not equal to <code>O</code> while the other boolean mask <code>m2</code> represent the condition where <code>Label</code> is not equal <code>O</code> and previous <code>Label</code> equals ...
python-3.x|pandas
1
365,138
65,184,997
Fill pandas column using values from list
<p>This is my list:</p> <pre><code>my_list = [ 2002-01-11 22:15:00, 2002-02-12 10:30:00, 2002-03-14 02:30:00, 2002-04-12 22:15:00 ] </code></pre> <p>I have DataFrame:</p> <pre><code> dt_object diff 0 2002-01-01 00:00:00 -160.95041 1 2002-01-01 00:15:00 -160.81016 2 2002-01-...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a></p> <pre><code>df['hit'] = df['dt_object'].isin(my_list) </code></pre>
python|pandas
1
365,139
65,093,349
How to find a specific value in a numpy array?
<p>I have my np array list with tuples like np.array[(0,1), (2,5),...]</p> <p>Now I want to search for the index of a certain value. But I just know the left side of the tuple. The approach I have found to get the index of a value (if you have both) is the following:</p> <pre><code>x = np.array(list(map(lambda x: x== (...
<p>As stated in <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html#numpy.where" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.where.html#numpy.where</a>, it is preferred to use <code>np.nonzero</code> directly. I would also recommend reading up on NumPy's use o...
python|arrays|python-3.x|numpy
1
365,140
65,298,735
TensorFLow Transfer Learning loading TFRecordDataset
<p>I'm trying to follow the transfer learning, Jupyter notebook, tutorial to classify images of horses:</p> <p><a href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/images/transfer_learning.ipynb" rel="nofollow noreferrer">https://github.com/tensorflow/docs/blob/master/site/en/tutorials/images/trans...
<p>I recommend this repo: <a href="https://github.com/zzh8829/yolov3-tf2" rel="nofollow noreferrer">https://github.com/zzh8829/yolov3-tf2</a> to try and fine tune <code>yolov3</code>. It has a complete tutorial (<a href="https://github.com/zzh8829/yolov3-tf2/blob/master/docs/training_voc.md" rel="nofollow noreferrer">h...
python|tensorflow|jupyter-notebook|transfer-learning|image-classification
0
365,141
65,121,925
What are the RGB and HEX codes of the 3 color conditional format in Excel?
<p>I would like to write a script to apply the standard available three color conditional formatting to the cells. Specifically, I would like the HEX codes of the colors Excel uses. I didn't see them listed on the Web.</p> <p>I only found <a href="https://stackoverflow.com/questions/27611260/what-is-the-rgb-code-for-th...
<p>In Excel 2016 at least the colors for the cells are:</p> <p>Red:</p> <ul> <li>HEX: <code>#f8696b</code></li> <li>RGB: <code>(248,105,107)</code></li> </ul> <p>Yellow:</p> <ul> <li>HEX: <code>#ffeb84</code></li> <li>RGB: <code>(255,235,132)</code></li> </ul> <p>Green:</p> <ul> <li>HEX: <code>#63be7b</code></li> <li>R...
python|excel|pandas
2
365,142
65,114,591
How to create offsets from start in pandas, given length of segments and offsets in segment?
<p>The title may not be the most informative.</p> <p>I have the following working code I want to vectorize [no for loops] using native pandas.<br /> Basically, it should return for each row its cumulative offset from <code>0</code>, given the length of each segment, and a relative offset within that segment.</p> <pre><...
<p>Let's try <code>mask</code> on the duplicated, then cumsum:</p> <pre><code>df['offset_from_start'] = (df['length'].mask(df.duplicated('id'),0) .cumsum() + df['offset'] ) </code></pre> <p>Output:</p> <pre><code> id length offset offset_from_start ...
python|pandas|numpy|dataframe|cumsum
3
365,143
65,274,777
How to encode string in tf.data.Dataset?
<p>So I am trying to encode a string in a tensorflow dataset in order to use it to train a pretrained RoBERTa model. The training_dataset is a tensorflow dataset made from a pandas dataframe that looks like this: <a href="https://i.stack.imgur.com/qnGHs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com...
<p><code>training_dataset</code> has features and outputs, and in your <code>map</code> function, you're only using one variable. Try:</p> <pre><code>training_dataset = training_dataset.map(lambda x, y: (tokenizer.encode(x), y)) </code></pre>
python|tensorflow|tokenize
0
365,144
65,221,079
What do the logits and probabilities from RobertaForSequenceClassification represent?
<p>Being new to the &quot;Natural Language Processing&quot; scene, I am experimentally learning and have implemented the following segment of code:</p> <pre class="lang-py prettyprint-override"><code>from transformers import RobertaTokenizer, RobertaForSequenceClassification import torch path = &quot;D:/LM/rb/&quo...
<p>You have initialized a <code>RobertaForSequenceClassification</code> model that per default (in case of <code>roberta-base</code> and <code>roberta-large</code> which have no trained output layers for sequence classification) tries to classify if a sequence belongs to one class or another. I used the expression &quo...
python|nlp|pytorch|text-classification|huggingface-transformers
4
365,145
65,091,448
'str' object has no attribute '_keras_mask' error when using tf.keras.Sequential
<h3>Background</h3> <p>I am using Tensorflow for the first time following a tutorial on featurization with the new Google Recommenders package: <a href="https://www.tensorflow.org/recommenders/examples/featurization" rel="nofollow noreferrer">https://www.tensorflow.org/recommenders/examples/featurization</a></p> <p>I r...
<p>Try using</p> <pre><code>wine_title_model.predict([&quot;Susana Balbo Signature Malbec&quot;]) </code></pre>
tensorflow|keras|deep-learning
1
365,146
65,205,818
Drop Duplicates based on condition of two columns
<p>I have this table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>Hello</td> <td>A</td> <td>C</td> </tr> <tr> <td>Hello</td> <td>B</td> <td>C</td> </tr> <tr> <td>Hello</td> <td>C</td> <td>C</td> </tr> </tbody> </table> </div> ...
<p>You can try</p> <pre><code>df = df[df.C.eq(df.B) | ~df.A.duplicated(keep=False)] </code></pre>
python|python-3.x|pandas|dataframe|duplicates
5
365,147
65,247,830
How to use different convolution layers in different branches of tf.map_fn?
<p>I tried to establish a simple multi-head attention layer in tensorflow1.14. Each head contains three different <code>conv1d</code> layers. And I want to use tf.map_fn to compute parallel.</p> <pre><code>import tensorflow as tf n_head = 50 # heads counts conv1d = tf.layers.conv1d normalize = tf.contrib.layers.insta...
<p>In that case, you don't ant to use <code>tf.map_fn</code>. <code>tf.map_fn</code> will evaluate your function once, and run your different inputs through the same function, effectively using the same convolution layers for each input.</p> <p>You can achieve what you want with a simple for loop :</p> <pre><code># Cre...
python|tensorflow|deep-learning|conv-neural-network
1
365,148
65,411,191
How to use bert layer for Multiple instance learning using TimeDistributed Layer?
<p>I want to perform Multiple Instance Learning Using Bert. A bag of instances contain 40 sentences. Each Sentence should output a label, and the final label should be average of all the labels.</p> <p>I have tried using bert layer from tensorflow_hub. But I have no idea how to use it with TimeDistributed.</p> <p><code...
<p>Disclaimer: I'm not an expert, thus there are probably some issues to figure out, but it should give you a hint. Except for the BERT encoder, you should use some preprocessing for your text:</p> <pre><code>bert_preprocess = hub.KerasLayer(&quot;https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3&quot;) bert_en...
tensorflow|keras|bert-language-model
0
365,149
65,229,666
Vectorized method for mapping a list from one Dataframe row to another Dataframe row
<p>Given a dataframe <code>df1</code> table that maps ids to names:</p> <pre class="lang-py prettyprint-override"><code> id names a 535159 b 248909 c 548731 d 362555 e 398829 f 688939 g 674128 </code></pre> <p>and a second dataframe <code>df2</code> which contains lists of ...
<p>I think vecorize this is really hard, one idea for improve performance is map by dictionary - solution use <code>if y in d</code> for working if no match in dictioanry:</p> <pre><code>df1 = df1.set_index('names') d = df1['id'].to_dict() df2['ids2'] = [[d[y] for y in x if y in d] for x in df2['names']] </code></pre>...
python|pandas|dataframe|vectorization
2
365,150
65,240,827
How can I get the minimum value of a column when other column is null?
<p>It's a pretty direct question, let's say I have:</p> <pre><code>id grade coldate 123 100 2020-01-01 444 45 2020-02-01 NULL 55 2020-03-01 NULL 70 2020-04-01 </code></pre> <p>I want the worst grade considering only when the id is null. So even though 444 has ...
<p>Try this oneliner:</p> <pre><code>df.loc[df['id'].isna(), 'grade'].min() </code></pre> <p>Output:</p> <pre><code>55 </code></pre> <p>Use <code>loc</code> with booleans series where column, 'id', <code>isna</code> and get the <code>min</code> value for column, 'grade'.</p>
pandas|dataframe|filter|missing-data
2
365,151
65,419,467
How to read a column of datatype json and convert into list using Pandas?
<p>I am trying to read a text file with two columns in Pandas. One of the column datatypes is JSON. I want to convert this column into a list of lists or just a list.</p> <p>Input:</p> <pre><code>bank time ABC {&quot;Monday&quot;:[[&quot;9:00&quot;,&quot;18:00&quot;]],&quot;Tuesday&quot;:[[&quot;9:00&quot;,&quot...
<p>Use <code>List Comprehension</code> with <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>In [2020]: def myfunc(row): ...: return [[k] + v[0] for k,v in row.items()] ...: In [2022]: df...
python|json|pandas|dataframe
1
365,152
65,450,738
New column keep formatting xlwings
<p>I want to keep the formatting of columns (lines, colors, bold text) to follow when I read/write tables to/from excel-files through <code>xlwings</code>. Here's an example, I start with connecting to an empty excel-file <code>Book1.xlsx</code>;</p> <pre><code>import xlwings as xw book = xw.Book('Book1.xlsx') sheet = ...
<p>You can copy and paste the formatting to the new columns. See the example:</p> <pre><code>import xlwings as xw book = xw.Book(r&quot;Book1.xlsx&quot;) sheet = book.sheets[&quot;Sheet1&quot;] sheet.range(&quot;B1&quot;).expand(&quot;down&quot;).copy() sheet.range(&quot;B1&quot;).expand(&quot;table&quot;).paste(past...
python|pandas|xlwings
3
365,153
65,157,419
CNN Cannot Identify Image File
<p>I have made a simple CNN to recognize three types of fish. I am trying to use CNN to classify the image that was not included in training or validation sets. The image is grunts-saltwater.jpg and is on Gdrive. Here is the code for predicting on existing CNN model:</p> <pre><code>grunts_url = &quot;https://drive.goog...
<p>I managed to resolve the issue. I do not think I was referring to source URL correctly. Here is an example that worked.</p> <pre><code>gruntfish_url = &quot;https://upload.wikimedia.org/wikipedia/commons/5/54/Blue_Stripe_Grunt._Haemulon_sciurus.jpg&quot; gruntfish_path = tf.keras.utils.get_file('Grunt.', origin=grun...
tensorflow|machine-learning|keras|deep-learning|prediction
0
365,154
65,477,554
How to place custom layer inside a in-built pre trained model?
<p>We're trying to add a custom layer inside a pre-trained imagenet model. For a sequential or non-sequential model, we can easily do that. But here are some requirements.</p> <p>First of all, we <strong>don't wanna disclose</strong> the whole imagenet model and deal with the <strong>desired inside layer</strong>. Let'...
<p>I don't have access to the paper so I just build an example like the one your draw:</p> <pre><code>import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, models class ConvBlock(layers.Layer): def __init__(self, kernel_num=32, kernel_size=(3,3), strides=(1,1), padding='same'): ...
python|tensorflow|keras|deep-learning
2
365,155
65,417,497
Saving Custom Model cannot be done with `model.save()`
<p>My python version 3.6.5 <br />tensorflow version 2.3.0</p> <p>Simple Custom Model</p> <pre><code>import tensorflow as tf import tensorflow.keras as keras class x(keras.layers.Layer): def build(self, input_shape): self.add_weight() inputs = keras.layers.Input(1) outputs = x()(inputs) model = keras.models...
<p>This seems to be a bug in tensorflow. Simply give a name to the weights you create and the problem is gone:</p> <pre><code>self.add_weight(name='name') </code></pre>
python|tensorflow|keras|save
9
365,156
65,066,658
Get all bold words from excel column with Pandas
<p>Is it possible to get words that are bold in the excel fields when using Pandas function pd.read_excel for reading the file?</p> <p>I get all rows with function df.itertuples().</p> <p>I want in each row to get all words that are bold in the second column. Is this possible?</p>
<p>You would need additional package.</p> <pre><code>from styleframe import StyleFrame df = StyleFrame.read_excel('test.xlsx', read_style=True, use_openpyxl_styles=False) for text in df[&quot;Colname&quot;]: # replace Colname if text.style.bold: print(text) </code></pre> <p>reference <a href="htt...
python|excel|pandas
1
365,157
65,121,614
PyTorch: How to multiply via broadcasting of two tensors with different shapes
<p>I have the following two PyTorch tensors A and B.</p> <pre><code>A = torch.tensor(np.array([40, 42, 38]), dtype = torch.float64) tensor([40., 42., 38.], dtype=torch.float64) </code></pre> <pre><code>B = torch.tensor(np.array([[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]], [[4,5,6,7,8],[4,5,6,7,8],[4...
<p>When applying broadcasting in pytorch (as well as in numpy) you need to start at the <em>last</em> dimension (check out <a href="https://pytorch.org/docs/stable/notes/broadcasting.html" rel="nofollow noreferrer">https://pytorch.org/docs/stable/notes/broadcasting.html</a>). If they do not match you need to reshape yo...
python|pytorch|reshape|matrix-multiplication|shapes
4
365,158
65,165,451
How to make 2D jagged array using NumPy
<p>I want to make a 2D array that in the first row has 2 elements, in the second row has 4 elements, and in the third row has 6. Below is my code:</p> <pre><code>jagged_array = np.array([ [None, None], [None, None, None, None], [None, None, None, None, None, None] ]) print(jagged_array) print(jagged_array.ndim) print...
<p>Based on this <a href="https://stackoverflow.com/questions/14916407/how-do-i-stack-vectors-of-different-lengths-in-numpy">StackOverflow</a> answer:</p> <blockquote> <p>NumPy does not support jagged arrays natively. gives an array that may or may not behave as you expect.</p> </blockquote> <p>A workaround using <a hr...
python|arrays|numpy|2d
1
365,159
65,470,865
Trouble with importing simple .txt file to Python
<p>I am unable to get Python to read a simple table shown in the image <a href="https://i.stack.imgur.com/eJzGF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJzGF.png" alt="enter image description here" /></a></p> <p>Below is the code I am using, and I have the code file saved in the same folder a...
<pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- &quot;&quot;&quot; Created on Tue Dec 29 11:38:07 2020 @author: bob &quot;&quot;&quot; import pandas as pd number_list = pd.read_table('simple_table.txt') print('printing : ',number_list.shape) </code></pre> <p>run it:</p> <pre><code>printing : (9, 1) </co...
python-3.x|pandas
0
365,160
65,479,784
Convert code from previous TensorFlow version to new TensorFlow 2.0
<p>How can I convert this code to the newest TensorFlow version 2.0?</p> <pre><code>def create_placeholders(n_x,n_y): X=t.placeholder(tf.float32,[n_x,None],name='X') Y=tf.placeholder(tf.float32,[n_y,None],name='Y') return X,Y </code></pre>
<p>there is no need for placeholders anymore. Yon can simply assume that you have a tensor variable</p> <pre><code>def create_placeholders(n_x,n_y): X=tf.Variable(dtype=tf.float32,initial_value=[n_x,None],name='X',dtype=tf.flot32) Y=tf.Variable(dtype=tf.float32,initial_value=[n_y,None],name='Y',dtype=tf.flot32) ...
python|tensorflow|anaconda
0
365,161
65,071,191
How to get the size of groups as well as other aggregations in pandas?
<p>When using pandas, I often have the need to compute aggregations over groups (sums and means being the most frequent) as well as getting the size of the groups.</p> <p>I have come across several ways to achieve this goal, however none of them feels simple enough as compared to the simplicity of my requirement.</p> <...
<p>I think reset index is not necessary, if use some newer pandas version use named aggregation, here for count is possible use any column, so change <code>client</code> to <code>margin</code>:</p> <pre><code>df1 = df.groupby('client').agg(revenue=(&quot;revenue&quot;,&quot;sum&quot;), ma...
python|pandas|pandas-groupby
2
365,162
65,175,559
Calculate 14-day rolling average on data with two hierarchies
<p>I am trying to calculate the 14 day rolling average for retail data with multiple different hierarchies. The 'Store' dataframe looks like this:</p> <pre><code>Store | Inventory-Small | Inventory-Medium | Date | Purchases-Small | Purchases-Medium ---------------------------------------------------------...
<p>I believe it's working fine as long as you sort <em>inplace</em> and remove 'Date' from <code>groupby</code>:</p> <pre class="lang-py prettyprint-override"><code>Store.sort_values(['Store','Date'], ascending=(False,False), inplace=True) Store['Rolling_Purchase_S'] = Store.groupby(['Store'])['Purchases-Small'].transf...
python|pandas
1
365,163
65,197,027
Sorting pandas value based on another dataframe values
<p>I have a <code>df_1</code> like this:</p> <pre><code>A apple, iphone, android facebook, apple macbook, laptop firestick, hulu, netflix android, laptop laptop </code></pre> <p>And <code>df_2</code> like this:</p> <pre><code>A B apple 1 macbook 2 facebook 3 firestick 4 ...
<p>You can create dictionary and matching values if exist, then get maximal value else missing value:</p> <pre><code>d = df_2.set_index('A')['B'].to_dict() def f(x): d1 = {y:d[y] for y in x.split(', ') if y in d} return min(d1, key=d1.get) if len(d1) &gt; 1 else np.nan </code></pre> <p>Or:</p> <pre><code>impo...
python|pandas|dataframe
2
365,164
65,423,636
Pandas | Filter DF rows with Integers that lie between two Integer values in another Dataframe
<p>I got two Dataframes. The goal is to filter out rows in DF1 that have an Integer value that lies between any of the Integers in the [&quot;Begin&quot;] and [&quot;End&quot;] columns in any of the 37 rows in DF2.</p> <p>DF1:</p> <pre><code>INDEX String IntValues 1 &quot;string&quot; 8080...
<p>Try this:</p> <pre><code>df_final=[] for i,j in zip(df2[&quot;Begin&quot;],df2[&quot;End&quot;]): x=df1[(df1[&quot;IntValues&quot;] &gt;=i ) &amp; (df1[&quot;IntValues&quot;] &lt;= j)] df_final.append(x) df_final=pd.concat(df_final,axis=0).reset_index(drop=True) df_final=df_final.drop_duplicates() </co...
pandas|dataframe|filter|conditional-statements
1
365,165
65,401,672
Reshape data after boolean indexes filtering
<p>I have a data set called <code>DATA</code> which regroup several 3D tables from <code>N=173</code> files of individual shape <code>(4, 4, 64)</code> so at the end the numpy array called <code>DATA</code> has shape <code>(173, 4, 4, 64)</code>. In each individual file I have a column which is a boolean column to spec...
<p>Masked Array is your solution</p> <p>In many circumstances, datasets can be incomplete or tainted by the presence of invalid data. For example, a sensor may have failed to record a data, or recorded an invalid value. The numpy.ma module provides a convenient way to address this issue, by introducing masked arrays.</...
python|arrays|python-3.x|dataframe|numpy-ndarray
1
365,166
65,397,532
'numpy.ndarray' object has no attribute 'set_xlabel'
<pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt #reading data data = pd.read_csv('Malicious_or_criminal_attacks_breakdown-Top_five_industry_sectors_July-Dec-2019.csv',index_col=0,engine='python') df = pd.DataFrame(data) #df list for data df.values.tolist() #construction of group ba...
<p><code>Ax</code> is an array of subplots because you created more than one. So in order to set the titles of the subplots, you need to iterate through them as well. You could fix this fairly easily like so:</p> <pre><code>fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(14, 5), dpi=100) for i in range(n_groups): ...
python-3.x|numpy|matplotlib
0
365,167
65,429,414
Tensorflow 2.2 not respecting thread settings (inter_op, intra_op, and OMP_NUM_THREADS)
<p>I am running a tensorflow application that sets inter_op, intra_op and OMP_NUM_THREADS, however, it completely ignores these settings and seems to run with the defaults. Here's how I'm setting them:</p> <pre><code>import tensorflow as tf print('Using Thread Parallelism: {} NUM_INTRA_THREADS, {} NUM_INTER_THREADS...
<p>You might want to checkout the new way of using TensorFlow v2, as they eventually gave up <code>tf.session</code> and started to do <a href="https://www.tensorflow.org/guide/effective_tf2#functions_not_sessions" rel="nofollow noreferrer">&quot;Functions, not sessions&quot;</a> (you may realise you should probably us...
python|tensorflow|machine-learning|keras|artificial-intelligence
1
365,168
65,357,159
Remove all special characters in pandas dataframe
<p>I'm having trouble removing all special characters from my pandas dataframe. Can you help me out?</p> <p>I have tried something like this:</p> <pre><code>df = df.replace(r'\W+', '', regex=True) </code></pre> <p>because I've found it in a recent post. But when I execute, the special character &quot; ' &quot; for exam...
<p><code>[^0-9a-zA-Z ]</code> matches Unicode letters and digits, this will remove too much.</p> <p>Use</p> <pre class="lang-py prettyprint-override"><code>df = df.replace(r'[^\w\s]|_', '', regex=True) </code></pre> <p>See <a href="https://regex101.com/r/YIYfPq/2" rel="nofollow noreferrer">proof</a></p> <p><strong>Expl...
python|regex|pandas|replace|special-characters
4
365,169
65,132,450
Converting Pandas Python to Pyspark
<p>I have code written in pandas that I am being asked to convert to pyspark, but I'm not that familiar with pyspark. I think I've got most of it, but I have a few lines that I can't convert.</p> <p>The first finds the next start date of an ID field if it exists (the data is sorted so that it is sequential)</p> <pre><c...
<p><code>df.shift(-1).column</code> in pandas is equivalent to</p> <pre><code>import pyspark.sql.functions as F from pyspark.sql.window import Window F.lag('column').over(Window.orderBy('another_column')) </code></pre> <p>You need to specify an ordering because Spark doesn't have a concept of index like pandas. As you...
python|pandas|apache-spark|pyspark|apache-spark-sql
1
365,170
65,332,849
Conditional groupby in python
<p>I'm working with a dataframe called <code>Ozon</code>. It has a column called <code>O3</code> and a DatetimeIndex. Now I created a new dataframe so that I would get the mean ozon values for each day:</p> <pre><code>dailymeanozon = ozon.groupby(pd.Grouper(freq='1D')).mean() </code></pre> <p>This works fine, however f...
<p>There are several ways to solve this, but this might be one of the simplest: Count the number of measurements per day, and use that information to filter the daily mean dataframe. The <code>.count</code> function from <code>pandas</code> has the property that it only counts rows that are not <code>None</code>, which...
python|pandas|group-by
1
365,171
65,220,437
training of a fully convolutional network with images of arbitrary size
<p>I have built a fully convolutional network that I feed subnetwork A with MFCC coefficients The wav files where MFCCs are calculated from have variable duration, so every wav ends up to a list of MFCCs with variable length. I made an implementation and try to feed the sub network A with batch size=1.</p> <pre><code> ...
<p>If you want variable input size this is how to do it, <em>but that won't work with Dense connections</em></p> <p>If you want this to work with Dense connections you'll need to provide a set input size, since this creates a relationship between the image size and how many connections are coming out of it</p> <p>Also,...
python|tensorflow|variables|keras
0
365,172
65,395,309
How to sum a column on condition if value is in another list
<p>I am trying to sum a column based on if the unique identifier is within another list I have defined. (The list is a subset of all of the unique identifiers). So I am trying to do it like this:</p> <pre><code>sum = data.loc[data['unique_identifier'] in somelist, 'number'].sum() </code></pre> <p>But I get back a TypeE...
<p>You are probably looking for <code>.isin(values)</code>: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html</a></p> <pre><code>sum = data.loc[data['unique_identifier'...
python|pandas
2
365,173
65,370,572
append same string to list of strings in a column pandas
<p>I have a df:</p> <pre><code> a b c 0 'd' 1 ['f', 'h'] 1 'f' 2 ['u', 'v'] 2 'g' 3 ['i', 'o'] </code></pre> <p>I want to append df['a'] to each element of df['c'] column. expected output:</p> <pre><code> a b c d 0 'd' 1 ['f', 'h'] ['fd', 'hd'] 1 'f' 2 ['u', 'v'] ['uf', '...
<p>We can use <code>explode</code> to unnest your list, then add the strings together and finally use <code>groupby</code> on the index and use <code>agg(list)</code> to get your list back:</p> <pre><code>ex = df.explode('c') ex['c'] = ex['c'] + ex['a'] df['c'] = ex.groupby(ex.index)['c'].agg(list) </code></pre> <pre>...
python|pandas
2
365,174
65,319,546
Reshaping a 3D array to a 2D array to produce a DataFrame: keep track of indices to produce column names
<p>The following code generates a <code>pandas.DataFrame</code> from a 3D array over the first axis. I manually create the columns names (defining <code>cols</code>): is there a more built-in way to do this (to avoid potential errors e.g. regarding C-order)?</p> <p>--&gt; I am looking for a way to guarantee the respect...
<p>Try this and see if it fits your use case:</p> <p>Generate columns via a combination of <a href="https://numpy.org/doc/stable/reference/generated/numpy.indices.html" rel="nofollow noreferrer">np.indices</a>, <a href="https://numpy.org/doc/stable/reference/generated/numpy.dstack.html" rel="nofollow noreferrer">np.dst...
python|python-3.x|pandas|numpy-ndarray
2
365,175
65,252,120
Replace unknown values with NaN in pandas dataframe
<p>I have an excel sheet which I imported to pandas dataframe. There are unknown values in the dataframe with value = '\N' I want to replace this with np.Nan.</p> <p>I got to know how to replace it for one column. Is there a way I can iterate it through the entire dataframe and replace all the occurences of '\N' with N...
<p>You can also call .replace() on the entire dataframe instead of a single column.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame([[1, 2], [3, r&quot;\N&quot;]]) df.replace(r&quot;\N&quot;, np.nan, inplace=True) </code></pre>
python|pandas
1
365,176
65,361,591
Pandas read .csv separated by whitespace but columns with names that contain spaces
<p>I have a .csv file that have to read. It is separated by a whitespace but the column names also have spaces. Something like this:</p> <pre><code>column1 another column final column value ONE valueTWO valueTHREE </code></pre> <p>I have been trying to read it withthis but it confuses with the spaces of the column na...
<p>I'd suggest you ignore the header altogether and instead pass the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>names</code></a> argument. That way you can use the whitespace separator for the rest of the file:</p> <pre class="lang-py pretty...
pandas|csv|whitespace|separator
3
365,177
65,141,828
Pythonic way to middle slicing
<p>I have an exercise which is requesting me to slice the three middle items of a list. I can use something like e.g.</p> <pre><code> foods = ['pizza', 'salad', 'pasta', 'poison', 'meat', 'cake', 'chocolate'] #slicing the middle three items in the list middle_foods = len(foods[:]) / 2 middle_foods = int(...
<p>You've got the right idea, you can clean things up a bit though:</p> <pre><code>midx = len(foods) // 2 print(*foods[midx-1:midx+2]) </code></pre>
python|numpy-slicing
2
365,178
65,443,850
Data Analysis with Pandas throws nothing
<p>Write a function called proportion_of_education which returns the proportion of children in the dataset who had a mother with the education levels equal to less than high school (&lt;12), high school (12), more than high school but not a college graduate (&gt;12) and college degree.</p> <p>This function should retur...
<p>Type this in the first cell below the question to read the data</p> <pre><code>import pandas as pd df=pd.read_csv('assets/NISPUF17.csv',index_col=0) df </code></pre> <p>In next cell</p> <pre><code>def proportion_of_education(): # your code goes here cat=pd.value_counts(df['EDUC1']) total=sum(cat) a_d...
python|pandas|data-analysis
0
365,179
65,450,997
Element error: Expecting 12 elements, new element value is 8
<p>I have a dataframe with 5 columns and 100 values. I am trying to do a basic descriptive analysis on the data before I go further. I am doing this by creating a function where the different descriptive information is found and stored in a new dataframe, but I am getting an element error.</p> <pre><code> import numpy ...
<p>The problem is at this line:</p> <pre><code>details.columns = cols </code></pre> <p>cols has 8 elements, while df has 12 columns, so it cannot assign the new column names. If you want to change some column names but not all of them, you must add the rest of the 12 column names of the df, into cols.</p> <p>To make th...
python|pandas
2
365,180
65,346,496
How to add new columns according to other columns in pandas?
<p>I looked over other questions but couldn't find what I wanted. Here is my short dataset</p> <pre><code> Year Region value 0 2016 London 31720.0 1 2016 Beijing 502631.0 2 2016 Tokyo 817262.0 3 2016 Bangkok 1021768.0 4 2016 Akihabara 894094.0 5 2017 London ...
<p>Based on the comments, I have assumed that <code>lat</code> and <code>long</code> are mapping to the city in the same order as they occur in the main dataframe i.e. London maps to 14.6937 and -17.44406.</p> <p>I can extract the cities for a given year and create a new dataframe having city, long and lat details.</p>...
pandas|dataframe
1
365,181
65,256,663
How can I take the log of a column in Python using Numpy?
<p>I have the the following <code>df</code>:</p> <pre><code>0 4.20 1 6.30 2 74.90 3 83.45 4 17.19 5 74.34 6 1717.73 7 139.05 8 753.36 9 4.54 10 60.07 Name: exports, dtype: float64 </code></pre> <p>I would like take logs of the whole column, but when I try:...
<p>This error means that you have used np as name for some other variable (of type integer)</p> <p>You can run</p> <pre><code>del np </code></pre> <p>and</p> <pre><code>import numpy as np </code></pre> <p>again, and it will work</p>
python|numpy
1
365,182
65,058,520
how to extend the numpy array in loop
<pre><code>import numpy as np attendance = np.array([1,0,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,1,1,1,1,1,1,0,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,1,1,1,1]) name_list = np.array([&quot;Ali&quot;,&quot;Ahmad&quot;,&quot;Beng&quot;,&quot;Chris&quot;,&quot;Sita&quot;,&quot;Marion&qu...
<p>Try this</p> <pre><code>C = np.concatenate((name_list.reshape(-1,1),attendance), axis=1) print(C) </code></pre> <p>Output</p> <pre><code>[['Ali' '1' '0' '0' '1' '1' '1' '0'] ['Ahmad' '1' '0' '1' '1' '1' ...
python|arrays|numpy|for-loop
0
365,183
49,924,427
In a dataframe group rows containing a list over one column
<p>I have the following dataframe (df) (All columns contain lists, except type, contains strings)</p> <pre><code>Type Components names Zebra [hand,arm,nose] [bubu,kuku] Zebra [eyes,fingers] [gaga,timber] Zebra [paws] [] Lion [teeth] [scar] Tiger [fingers] [figgy] </cod...
<p><strong>Option 1</strong><br> <code>groupby</code> + <code>sum</code><br> Not optimised, does not account for duplicates</p> <pre><code>df.groupby('Type', sort=False, as_index=False).sum() Type Components names 0 Zebra [hand, arm, nose, eyes, fingers, paws] ...
python|pandas|dataframe|pandas-groupby
1
365,184
50,112,001
In pandas Series data, how do you get the keys based on data the function returns?
<p>I have a working script that creates an array of each line of text in a file. This data is passed to a pandas <code>Series()</code>. The function <code>startswith("\n")</code> is used to return boolean <code>True</code> or <code>False</code> for each string, to determine if it begins with <code>\n</code> (a blank li...
<p>Your question seems actually simpler than the one in the title. You're trying to get the indices for the values for which some predicate evaluated positively, not pass the index to a function.</p> <p>In Pandas, the last block </p> <pre><code>i = 0 for b in s.str.startswith("\n"): if b == 0: print s[i],...
python|pandas
1
365,185
50,187,932
Changing value in data frame column in a loop python
<p>I am new to Python pandas library and using data frames. I am using Jupyter. I kind of lost with this syntax.</p> <p>I want to loop through rows and set new value to column <strong>new_value</strong>. I thought I would do it like this, but it raises an error.</p> <pre><code>df_merged['new_value'] = 0 for i, row i...
<p>You can use just this:</p> <pre><code>df_merged['new_value'] = df.index </code></pre> <p>You can also use <code>apply</code> method.</p> <pre><code>df_merged['new_value'] = df_merged.apply(lambda row : row.name, axis=1) </code></pre> <blockquote> <p>I am getting this error : A value is trying to be set on a co...
python|pandas|dataframe
3
365,186
50,009,587
Is it possible to use vectorization for a conditionnal count of rows in a Pandas Dataframe?
<p>I have a Pandas Dataframe with data about calls. Each call has a unique ID and each customer has an ID (but can have multiple Calls). A third column gives a day. For each customer I want to calculate the maximum number of calls made in a period of 7 days.</p> <p>I have been using the following code to count the num...
<p>IIUC this is a convoluted, but I think effective solution to your issue. Note that the order of your dataframe is modified as a result, and that your <code>Day</code> column is modified to a timedelta dtype:</p> <p>Starting from your dataframe <code>df</code>:</p> <pre><code> CallID Day PersonID 0 6 2...
python|pandas|dataframe|vectorization
0
365,187
49,884,600
Efficient way to apply pandas operation many times to identically indexed objects
<p>I am performing a fixed point iteration which requires multiple evaluations of function <code>f</code> i.e.</p> <pre><code>x &lt;- f(x) </code></pre> <p>In programming terms, <code>x</code> is a Pandas series indexed by a multiindex. The function <code>f</code> is not able to work elementwise on <code>x</code>. It...
<p>Perhaps this is not exactly what you're looking for, but it should be more efficient. Simply get rid of <code>SITU</code>, squeeze both to actual Series, and take advantage of the fact that Pandas operations are naturally index-aligned.</p> <pre><code>from itertools import repeat def f(x_, z_, rpt=10): for _ ...
python|pandas|numpy
0
365,188
49,877,422
keras conv1d input data reshape
<p>I am trying to use 1-dimensional CNN for binary Classification in Keras. I have a machine which continuously performs an action and my goal is to classify if that action is normal or anomalous.</p> <p>To monitor the behaviour of each action, there are 4 sensors that collect 100 measurements. Thus, for each action, ...
<p>Using number of sensors seems logical, and should not be a problem and considering multiple measurements as size also seems right. So, you can try training this model and check the results. </p> <p>Another way that I'll recommend is to use different convolutions for all the sensors. So you'll have 4 convolutions e...
python|tensorflow|keras|conv-neural-network
1
365,189
50,154,667
remove initial NaNs from dataframe whilst keeping others in place
<p>Please help! I have done some research and these questions are linked however I can't massage this to work: <a href="https://stackoverflow.com/questions/48598215/multiple-shifts-on-dataframe">Multiple shifts on dataframe</a> <a href="https://stackoverflow.com/questions/23105197/shift-entire-column-on-a-pandas-datafr...
<p>Maybe something like</p> <pre><code>In [57]: df.apply(lambda x: x.shift(-x.notnull().values.argmax()), axis=1) Out[57]: A B C D 1 10.0 11.0 23.0 90.0 2 5.0 NaN 56.0 NaN 3 11.0 3.0 NaN 11.0 4 56.0 NaN NaN NaN </code></pre> <hr> <p>This works by shifting over as many cells...
python-3.x|numpy|dataframe|nan
0
365,190
49,845,685
Tensorflow: NaN for custom softmax
<p>Simply exchanging the <strong>nn.softmax</strong> function for a combination which uses <strong>tf.exp</strong>, keeping everything else like it was, causes not only the gradients to contain NaN but also the intermediate variable <strong>s</strong>. I have no idea why this is. </p> <pre><code>tempX = x tempW = W te...
<h1>Answer</h1> <p><code>tf.exp(s)</code> easily overflows for large <strong>s</strong>. That's the main reason that <code>tf.nn.softmax</code> doesn't actually use that equation but does <em>something equilivent</em> to it (according to the docs).</p> <h1>Discussion</h1> <p>When I rewrote your softmax function to ...
python|tensorflow
1
365,191
50,103,182
Numpy, vectorized function on multiple label masks
<p>I have the following code for replacing each value of an image with the median (or any other function) value based on masks from a labels image created in a segmentation step. It feels as if the for loop can be vectorized. What is the best approach do do this?</p> <p>I looked at building a separate index array for ...
<p>I don't know about vectorizing the innermost loop. The call to <code>median</code> calculates over a different number of elements each time, which would make it hard to put all of the calls into a single array.</p> <p>On the other hand there's some fairly low hanging fruit in terms of how you're choosing the elemen...
python|numpy|vectorization
1
365,192
49,855,241
Speed up extraction of coordinates from DICOM structure set
<p>Using <code>numpy.reshape</code> helped a lot and using <code>map</code> helped a little. Is it possible to speed this up some more?</p> <pre><code>import pydicom import numpy as np import cProfile import pstats def parse_coords(contour): """Given a contour from a DICOM ROIContourSequence, returns coordinates...
<p>Eliminating the loop in <code>MultiVal.__init__</code> and using <code>numpy.fromstring</code> provides more than 4 times speedup. I will post on the pydicom github see if there is some interest in taking this into the library code. It is a little ugly. I would welcome advice on further improvement.</p> <pre><code>...
python|python-3.x|numpy|pydicom
0
365,193
50,084,051
Use returned values of a custom function in loss, based on model predictions
<p>I'm trying to build a model like this in TensorFlow.<br> The model has &quot;a function&quot; inside the loss function(as A) or before it(as B) which should make an image using the CNN(CNN+Dens layers) estimation of some parameters.<br> Imagine the input images to be some rectangles with different sizes and coordina...
<p>I think you need to add the full code here. For a better answer. From the error, it seems like you need to add tf.global_variables_initializer() before you start doing(Training) anything since some variables are not initialized. Also it seems you want to create a new loss function based A_Function and images. </p> ...
python|tensorflow|deep-learning
0
365,194
50,031,277
Nested if statements with .loc in pandas / python
<p>I am using if in a conditional statement like the below code. If address is NJ then the value of name column is changed to 'N/A'.</p> <pre><code>df1.loc[df1.Address.isin(['NJ']), 'name'] = 'N/A' </code></pre> <p>How do I do the same, if I have 'nested if statements' like below?</p> <pre><code># this not code just...
<p>Separate assignments, <a href="https://stackoverflow.com/a/50031316/9209546">as shown</a> by @MartijnPeiters, are a good idea for a small number of conditions.</p> <p>For a large number of conditions, consider using <code>numpy.select</code> to separate your conditions and choices. This should make your code more r...
python|python-3.x|pandas|if-statement|dataframe
4
365,195
49,845,113
TensorFlow : Tried to convert 'input' to a tensor and failed. Error: None values not supported
<p>I am trying to make my first Convolutional Neural Network using Tensorflow and python(3.6). Here is the relevant part of my code :</p> <pre><code>def init_weights(shape): init_random_dist = tf.truncated_normal(shape , stddev = 0.1) return tf.Variable(init_random_dist) def init_bias(shape): init_bias_vals = tf...
<p>Function <code>max_pool_2by2</code> does not return any value so <code>convo_1_pooling</code> is <code>None</code> then.</p>
python|python-3.x|tensorflow|conv-neural-network
1
365,196
49,970,141
Using numpy reshape to perform 3rd rank tensor unfold operation
<p>I am trying to use the reshape command in numpy python to perform the unfold operation on a 3rd-rank/mode tensor. I'm not sure whether what I'm doing is correct. I found this paper online <a href="http://www.public.asu.edu/%7Ejye02/CLASSES/Fall-2007/NOTES/tensor.pdf" rel="nofollow noreferrer">Tensor Decomposition</a...
<p><strong>TL;DR:</strong> assuming you are using the default (C-)ordering of elements, then tensor.reshape(N, M*P) corresponds to the unfolding of tensor along its first mode according to the definition used in, for instance, TensorLy.</p> <hr> <p>The long answer is more subtle. There are more than one definition of...
python|numpy|image-processing|linear-algebra|tensor
8
365,197
49,836,933
Encode integer pandas dataframe column to padded 16 bit binary
<p>I would like to encode integers stored in a pandas dataframe column into respective 16-bit binary numbers which correspond to bit positions in those integers. I would also need to pad leading zeros for numbers with corresponding binary less than 16 bits. For example, given one column containing integers ranging from...
<h2>Setup</h2> <p>Consider the data frame <code>df</code> with column <code>'A'</code></p> <pre><code>df = pd.DataFrame(dict(A=range(16))) </code></pre> <h2>Numpy broadcasting and bit shifting</h2> <pre><code>a = df.A.values n = int(np.log2(a.max() + 1)) b = (a[:, None] &gt;&gt; np.arange(n)[::-1]) &amp; 1 pd.Data...
python|pandas|numpy|binary
2
365,198
49,900,836
pandas Dataframe using loc to insert a row Value Error is raised if the first argument ist not a list?
<p>This is a working minimal example of the problem:</p> <pre><code>import pandas as pd example = pd.DataFrame(index=pd.np.arange(2) , columns=['A', 'B', 'C']).astype('object') example.loc[0] = [['a'], 'b', [1,2,3]] example.loc[1] = ['a', 'b', [1,2,3]] </code></pre> <p>I get a <code>ValueError: setting an array eleme...
<p>You are pushing on the boundaries of Pandas. It isn't good at handling higher level objects. So we have to be careful.</p> <p>In you case, Pandas doesn't see that it is an array of objects right away and fails when it gets to the sequence.</p> <h3>Work Around</h3> <p>Wrapped in a series object </p> <pre><code>...
python|python-3.x|pandas
3
365,199
49,941,426
AttributeError: 'collections.OrderedDict' object has no attribute 'eval'
<p>I have a model file which looks like this</p> <pre><code>OrderedDict([('inp.conv1.conv.weight', (0 ,0 ,0 ,.,.) = -1.5073e-01 6.4760e-02 1.9156e-01 1.2175e-01 3.5886e-02 1.3992e-01 -1.5903e-01 8.2055e-02 1.7820e-01 (0 ,0 ,1 ,.,.) = ...
<p>It is not a model file, instead, this is a state file. In a model file, the complete model is stored, whereas in a state file only the parameters are stored.<br> So, your <code>OrderedDict</code> are just values for your model. You will need to create the model and then need to load these values into your model. So,...
python|deep-learning|pytorch
42