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 |
|---|---|---|---|---|---|---|
2,600 | 66,052,235 | Filtering dataframe based on that if string is made from specific letters | <p>So i have Dataframe that look's like this</p>
<p><strong>note</strong> i put diffrent letters in * * for you to see easy</p>
<pre><code> id genome
0 639 ATGTTTGTTTTT*Y*TTGTTTTATATGTTTGTTTTTCTTGTTTTATATGTTTGTTTTTCTTGTTTTAT
1 640 ATGTTTGTTTTT*J*... | <p>It looks like your strings have leading/trailing spaces (look at those alignments in print out). So try:</p>
<pre><code>df['genome'] = df['genome'].str.strip()
df = df[~df['genome'].str.contains('[^ACTGN]')]
</code></pre>
<p>Or you can chain them if you don't want to modify your <code>genome</code> column:</p>
<pre>... | python|arrays|pandas|dataframe | 2 |
2,601 | 65,982,015 | tf.keras.preprocessing.sequence.pad_sequences in JavaScript | <p>How can we implement tf.keras.preprocessing.sequence.pad_sequences in TensorFlow.js?</p>
<pre><code>encoded_text = tokenizer.texts_to_sequences([input_text])[0]
pad_encoded = pad_sequences([encoded_text], maxlen=seq_len, truncating='pre')
</code></pre> | <p>The <a href="https://github.com/tensorflow/tfjs-models/tree/master/universal-sentence-encoder" rel="nofollow noreferrer">universal sentence encoder</a> can be used to convert text into tensors</p>
<pre><code>require('@tensorflow/tfjs');
const use = require('@tensorflow-models/universal-sentence-encoder');
use.load(... | javascript|tensorflow|keras|tensorflow.js | 1 |
2,602 | 52,606,908 | generic function for conditional filtering in pandas dataframe | <p>sample filtering condition:-</p>
<p><a href="https://i.stack.imgur.com/AMSBB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AMSBB.png" alt="enter image description here"></a>
Data</p>
<pre><code>x y z
1 2 1
1 3 2
1 2 5
1 3 1
</code></pre>
<p>now i want to filter the above specified ... | <p>You can create list of <code>conditions</code> and then <a href="https://stackoverflow.com/q/20528328"><code>np.logical_and.reduce</code></a>:</p>
<pre><code>x1 = df.x==1
y2 = df.y==2
z1 = df.z==1
y3 = df.y==3
m1 = np.logical_and.reduce([x1, y2, z1])
m2 = np.logical_and.reduce([x1, y3, z1])
</code></pre>
<p>Or <... | python|pandas|filter | 2 |
2,603 | 52,899,858 | Collapsing rows with NaN entries in pandas dataframe | <p>I have a pandas DataFrame with rows of data::</p>
<pre><code># objectID grade OS method
object_id_0001 AAA Mac organic
object_id_0001 AAA Mac NA
object_id_0001 AAA NA organic
object_id_0002 NA NA NA
object_id_0002 ABC Win NA
</code></pre>
<p>i.e. there ar... | <h3>Quick and Dirty</h3>
<p>This works and has for a long time. However, some claim that this is a bug that may be fixed. As it is currently implemented, <code>first</code> returns the first non-null element if it exists per column.</p>
<pre><code>df.groupby('objectID', as_index=False).first()
objectID gr... | python|pandas|dataframe|rows|nan | 6 |
2,604 | 58,439,491 | Why my code is giving me data in 1 column it should give me in two different column | <p>i need to know what is happening in my code? it should give data in separate columns it is giving me same data in a oath columns.</p>
<p>i tried to change the value of row variable but it didn't found the reason</p>
<pre><code>import requests
import csv
from bs4 import BeautifulSoup
import pandas as pd
import tim... | <p>because of this: </p>
<p><code>pd.Series(row, index=columns)</code> </p>
<p>try smthg like </p>
<p><code>pd.DataFrame([[locations[i], prices[i]]], index=columns))</code></p>
<p>However this could be done only once outside of your for loop</p>
<p><code>pd.DataFrame(list(zip(locations, prices)), index=columns))</... | pandas|series | 0 |
2,605 | 58,563,632 | How do I convert two DataFrame columns into summed Series? | <p>I have a pandas DataFrame that looks like this:</p>
<pre><code> date sku qty
0 2015-10-30 ABC 1
1 2015-10-30 DEF 1
2 2015-10-30 ABC 2
3 2015-10-31 DEF 1
4 2015-10-31 ABC 1
... ... ... ...
</code></pre>
<p>How can extract all of the data ... | <p>If you will work with all (or several) <code>sku</code>, then:</p>
<pre><code>agg_df = df.groupby(['sku','date']).qty.sum()
# extract some sku data
agg_df.loc['ABC']
</code></pre>
<p>Output:</p>
<pre><code>date
2015-10-30 3
2015-10-31 1
Name: qty, dtype: int64
</code></pre>
<p>If you only care for <code>A... | python|pandas|dataframe | 2 |
2,606 | 68,911,720 | Date stuck as unformattable in pandas dataframe | <p>I am trying to plot time series data and my date column is stuck like this, and I cannot seem to figure out what datatype it is to change it, as adding <code>verbose = True</code> doesn't yield any explanation for the data.</p>
<p>Here is a screenshot of the output <a href="https://i.stack.imgur.com/V1dS9.png" rel="... | <p>When you pass a Pandas Series into <code>pd.to_datetime(...)</code>, it parses the values and returns a new Series of dtype <code>datetime64[ns]</code> containing the parsed values:</p>
<pre class="lang-py prettyprint-override"><code>>>> pd.to_datetime(pd.Series(["12:30:00"]))
0 2021-08-24 12:30... | python-3.x|pandas | 0 |
2,607 | 68,893,658 | Exponential moving average on pandas | <p>I was having a bit of trouble making an exponential moving average for a pandas data frame. I managed to make a simple moving average but I'm not sure how I can make one that is exponential. I was wondering if there's a function in pandas or maybe another module that can help with this. Ideally the exponential movin... | <p>Use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html" rel="nofollow noreferrer"><code>ewm</code></a> method:</p>
<pre><code>df['SMA'] = df['Adj Close'].ewm(span=75, min_periods=1).mean()
</code></pre>
<p><em>NB. check carefully the parameters' documentation as there i... | pandas|numpy|yfinance | 0 |
2,608 | 69,270,418 | Chunk 2D array into smaller arrays, get the chunk means, and plot a heatmap | <p>I want to make a heatmap using seaborn. I have a 1920x1080 2D array that contains saliency values of each pixel of an image from 0-1 (0=lowest saliency-blue color, 1=highest saliency-red color). I have divided my image into smaller grids of 80x90 pixels. I am getting the image below:</p>
<p><a href="https://i.stack.... | <h2>Main Array</h2>
<ul>
<li>Remove <code>linewidth</code></li>
<li>Add <code>set_xticklabels</code> and <code>set_yticklabels</code></li>
</ul>
<pre class="lang-py prettyprint-override"><code># test data
np.random.seed(365)
data = np.random.random((1080,1920))
ax = sns.heatmap(data, cmap='jet')
ax.set_xticks(xticks) ... | python|numpy|seaborn|heatmap | 1 |
2,609 | 69,084,798 | In transformers of ViT model, last_hidden_state is not equal to hidden_states[-1] | <p>When input the same image, in Google ViT model output.last_hidden_state is not equal to output.hidden_states[-1] ?
I tried in Bert, the outputs are the same.</p>
<p>feature_extractor = ViTFeatureExtractor.from_pretrained('google/vit-base-patch16-224-in21k')</p>
<pre><code>model = ViTModel.from_pretrained('google/vit... | <p>The difference is that the layernorm is applied to the last_hidden_state.</p>
<p>The following is an excerpt of the last 15 lines or so of ViTModel's forward method. For sequence_output, which is assigned to last_hidden_state, layernorm is applied to the output from the encoder.</p>
<pre><code>sequence_output = enco... | python|pytorch|huggingface-transformers|transformer-model | 0 |
2,610 | 69,161,346 | RuntimeError: The layer has never been called and thus has no defined output shape | <p>I am trying to add attention to pretrained vgg16 network. I am trying to get the output shape of the last layer but it's throwing an error. This is the code,</p>
<pre><code>img_shape = (224,224,3)
in_lay = Input(img_shape)
base_pretrained_model = VGG16(input_shape = img_shape,
include_... | <p>Instead of</p>
<pre><code> pt_depth = base_pretrained_model.get_output_shape_at(0)[-1]
</code></pre>
<p>Try this one:</p>
<pre><code> pt_depth = base_pretrained_model.layers[-1].output_shape
</code></pre>
<p>Since, <em>include_top=False</em> the output will be: (None, 7, 7, 512) that is the shape of the last l... | tensorflow|conv-neural-network|transfer-learning | 0 |
2,611 | 69,080,534 | How do I create a prefetch dataset from a folder of images? | <p>I am trying to input a dataset from Kaggle into this <a href="https://www.tensorflow.org/tutorials/generative/cyclegan" rel="nofollow noreferrer">notebook</a> from the Tensorflow docs in order to train a CycleGAN model. My current approach is to download the folders into my notebook and loop through the paths of eac... | <pre><code> import pathlib
import tensorflow as tf
import numpy as np
@tf.autograph.experimental.do_not_convert
def read_image(path):
image_string = tf.io.read_file(path)
image = DataUtils.decode_image(image_string,(image_size))
return image
AUTO... | image|tensorflow|image-processing|tensorflow-datasets|kaggle | 1 |
2,612 | 44,591,704 | How to find largest amount based on entity within group? | <p>Let's say my DataFrame looks something like this:</p>
<pre><code>Bank Entity Amount
JPM NY 5000
JPM NY 300
BOA LA 10000
BOA China 3000
MS Japan 21000
</code></pre>
<p>I would like to output based on top entity, while keeping in mind that the Bank is different, so the DataFrame then ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.idxmax.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.idxmax</code></a> for indexes of max values and then select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html... | python|pandas|dataframe | 2 |
2,613 | 44,729,498 | Plotting data from multiple pandas data frames in one plot | <p>I am interested in plotting a time series with data from several different pandas data frames. I know how to plot a data for a single time series and I know how to do subplots, but how would I manage to plot from several different data frames in a single plot? I have my code below. Basically what I am doing is I am ... | <p>Quite straightforward actually. Don't let pandas confuse you. Underneath it every column is just a numpy array.</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df1 = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df2 = pd.DataFrame(np.random.randint... | python|pandas|plot | 7 |
2,614 | 42,410,237 | tensor flow character recognition with softmax results in accuracy 1 due to [NaN...NaN] prediction | <p>I am trying to use the softmax regression method discussed in <a href="https://www.tensorflow.org/get_started/mnist/beginners" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/mnist/beginners</a> to recognize characters. </p>
<p>My code is as follows. </p>
<pre><code>train_data = pd.read_csv('CharD... | <p>Here is the problem you are having: </p>
<ul>
<li>You set your initial weights and biases to 0 (this is wrong, as your
network does not learn). </li>
<li>The result is that y consists of all zeros</li>
<li>You take the log of y.. and a log of 0 is not defined... Hence the NaN. </li>
</ul>
<p>Good luck!</p>
<p>Edi... | tensorflow|softmax | 0 |
2,615 | 69,814,968 | Add Rows to Section of Dataframe | <p>I'm looking to add rows from first section of dataframe to other sections of the dataframe while changing the value in one column.</p>
<p>For example if I have this as my input dataframe:</p>
<pre><code>Type Color Size Dimensions
Circle Blue Large 2D
Circle Green Small 3D
Circle Black L... | <p>Try:</p>
<pre><code># circle rows
circles = df.query('Type=="Circle"')
pd.concat([df] + [circles.assign(Type=t) for t in df.Type.unique() if t!='Circle'])
</code></pre>
<p>Output:</p>
<pre><code> Type Color Size Dimensions
0 Circle Blue Large 2D
1 Circle Green Small 3D
... | python|pandas|dataframe | 1 |
2,616 | 69,782,374 | Count list member pairs within array | <p>Let's assume, I've got an array containing the following lists:</p>
<pre><code>data = [['a', 'b', 'c'],['a', 'b'],['c']]
</code></pre>
<p>What would be the best solution to count every pair occurrence by the number of lists they're in?</p>
<p>E.g. result should be:</p>
<pre><code>member_one_is member_two_is COUNT
... | <p>One approach using <a href="https://docs.python.org/3.8/library/collections.html#collections.Counter" rel="nofollow noreferrer"><code>collections.Counter</code></a> and <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow noreferrer"><code>itertools.combinations</code></a>:... | python|pandas|dataframe | 2 |
2,617 | 69,749,087 | Need help in compiling custom loss | <p>I am adding a custom loss to a VAE, as suggested here: <a href="https://www.linkedin.com/pulse/supervised-variational-autoencoder-code-included-ibrahim-sobh-phd/" rel="nofollow noreferrer">https://www.linkedin.com/pulse/supervised-variational-autoencoder-code-included-ibrahim-sobh-phd/</a></p>
<p>Instead of defining... | <p>There are several ways to implement VAE in Tensorflow. I propose an alternative implementation that can be found in <a href="https://www.tensorflow.org/guide/keras/custom_layers_and_models#putting_it_all_together_an_end-to-end_example" rel="nofollow noreferrer">custom_layers_and_models</a> in Tensorflow guide pages ... | tensorflow|keras | 1 |
2,618 | 69,848,005 | Does .loc in Python Pandas make inplace change on the original dataframe? | <p>I was working on a dataframe like below:</p>
<p>df:</p>
<pre><code>Site Visits Temp Type
KFC 511 74 Food
KFC 565 77 Food
KFC 498 72 Food
K&G 300 75 Gas
K&G 255 71 Gas
</code></pre>
<p>I wanted to change 'Type' column into 0-1 variable so I cou... | <p>Your 2nd method doesn't actually change the <code>dtype</code> of the series even though the values are all ints. You can see that by doing <code>df.dtypes</code> which would show the <code>Type</code> column is still of <code>object</code> dtype</p>
<p>You need to explicitly cast them to int using an <code>.astype(... | python|pandas|dataframe|pandas-loc | 1 |
2,619 | 69,738,324 | How can I insert several rows at given position in pandas DataFrame? | <p>I have a table of data that had to be recorded every 30 seconds but some of it was recorded with a larger time step.</p>
<p>So I want to write a program with pandas to check the time steps and if they are larger than 30, insert specific number of NaN rows, then fill the NaN cells with interpolation. but I don't know... | <p>There will be a lot of ways to solve this. If I understand correctly, you want to insert two rows everytime when <code>time_step</code> is 90. If you have more general cases as well, we would need to modify the solution a bit.</p>
<p>This is a very imperative requirement. For this case, I would work very directly wi... | python|pandas|dataframe | 0 |
2,620 | 69,930,461 | Any alternate approaches to calculate co-occurrence matrix in Python? | <p>I'm trying to calculate the co-occurrence matrix for a large corpus but it takes a very long time(+6hours). Are there any faster ways?</p>
<p>My approach:</p>
<p>consider this array as the <code>corpus</code> and each element of the corpus as <code>context</code>:</p>
<pre><code>corpus = [
'where python is used'... | <p>The provided algorithm is not efficient because it recompute <code>words.index(...)</code> a lot of time. You can <strong>pre-compute the indices</strong> first and then build the matrix. Here is a significantly better solution:</p>
<pre class="lang-py prettyprint-override"><code>words = list(set(' '.join(corpus).sp... | python|numpy|machine-learning | 1 |
2,621 | 43,175,382 | Python: create a pandas data frame from a list | <p>I am using the following code to create a data frame from a list:</p>
<pre><code>test_list = ['a','b','c','d']
df_test = pd.DataFrame.from_records(test_list, columns=['my_letters'])
df_test
</code></pre>
<p>The above code works fine. Then I tried the same approach for another list:</p>
<pre><code>import pandas as... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_records.html" rel="noreferrer"><code>DataFrame.from_records</code></a> treats string as a character list. so it needs as many columns as length of string.</p>
<p>You could simply use <a href="https://pandas.pydata.org/pandas-d... | list|python-3.x|pandas|dataframe | 128 |
2,622 | 72,154,349 | Getting 1970-01-01 after converting int to datetime | <p>I have an attribute like:</p>
<pre><code>df. CalculationDateKey.head()
0 20201231
1 20201130
2 20201031
3 20200930
4 20200831
Name: CalculationDateKey, dtype: int64
</code></pre>
<p>And I want to convert it into datetime.</p>
<p>I tried:</p>
<pre><code>pd.to_datetime(df['CalculationDateKey']).head()
<... | <p>Don't let Pandas infer your date format so specify it:</p>
<pre><code>>>> pd.to_datetime(df['CalculationDateKey'], format='%Y%m%d')
0 2020-12-31
1 2020-11-30
2 2020-10-31
3 2020-09-30
4 2020-08-31
Name: CalculationDateKey, dtype: datetime64[ns]
</code></pre> | python|pandas|numpy | 1 |
2,623 | 72,357,902 | How can I Get, Edit and Set Gradient Matrix in Training of Keras Model? | <p>I am creating a sparse neural network as described in the image below. Keras only provides a dense layer and we can't choose how many neurons we want to be connected to the previous layer. For implementing this using Keras, I am trying to implement the following approach:</p>
<p>1- Get the Gradient Matrix of each la... | <p>Instead of working with the gradients matrix manually, It's better to apply TensorFlow pruning techniques. We can apply pruning to each layer of the model by passing a parameter.</p>
<pre><code> pruning_params = {
'pruning_schedule':
PolynomialDecay(
initial_sparsity=0.1,
final_sparsity=0... | python|tensorflow|keras|deep-learning | 0 |
2,624 | 72,139,727 | Product and summation with 3d and 1d arrays | <p>Given a 3d array <strong><code>X</code></strong> with dimensions (<code>K,n,m</code>) that can be considered as a stack of <code>K</code> (<code>n,m</code>) matrices and a 1d vector <strong><code>b</code></strong> (dim <code>n</code>), the goal is to obtain the resulting vector <strong><code>r</code></strong> (dim <... | <p>This looks like a perfect usecase for <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html" rel="nofollow noreferrer">einsum</a>:</p>
<pre class="lang-py prettyprint-override"><code>r = np.einsum('kij,l,klj->i', x, b, x)
</code></pre>
<p>which will vectorize the operation, e.g. it's more op... | python|numpy|numpy-ndarray | 1 |
2,625 | 72,434,189 | Grouping rows in a Pandas DataFrame | <p>We're working with a really large Twitter DataBase containing around 4,9 million entries. Every entry can either be a tweet, or a reply to a tweet (or a reply to a reply of course). Since this data has been collected using the Twitter API tweets and their replies are not neatly grouped in the DataFrame but many entr... | <p>This seems like a pretty hard operation.
I think that i understand a little your issue (but not all of it, sadly).
In my opinion, you should firstly group the elements by the "in_reply_to_user" or "in_reply_to_status" (I don't know exactly the difference between the 2), and after that you should ... | python|pandas|twitter | 0 |
2,626 | 50,491,564 | Merge Two different dataframe with Pandas | <p>I am new to pandas, I need to complete the following task, is there an effective way to do it?
There are 2 different dataframes, dfa and dfb:
<a href="https://i.stack.imgur.com/K0Oq0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K0Oq0.png" alt="dfa"></a></p>
<p><a href="https://i.stack.imgur.co... | <p>It is expected, because duplicates per all 4 columns.</p>
<p>So need remove duplicates rows by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>drop_duplicates</code></a>:</p>
<pre><code>dfa = dfa.drop_duplicates(subset=['a_retry'... | python|pandas | 0 |
2,627 | 50,503,246 | How can I do feature mapping (pop) from JSON format to tabular format? | <p>Here's my data</p>
<pre><code> id var_map
0 7068 {'feature_1': 2.0, 'feature_2': 4.0, 'feature_3': 8.0, 'feature_4': 8.0}
1 7116 {'feature_1': '2', 'feature_2': 5.0, 'feature_3': 7.0}
2 7154 {'feature_1': 1.0, 'feature_2': 8.0, 'feature_3': 17.0}
</code></pre>
<p>Here's what I want</p>
<pre... | <p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pop.html" rel="nofollow noreferrer"><code>pop</code></a> with <code>DataFrame</code> contructor and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code... | python|json|pandas|dataframe | 3 |
2,628 | 62,545,426 | Filter rows from a pandas column binned by pandas.cut() | <p>I have a pandas series that I've got from <code>pandas.cut()</code>.</p>
<p>Given a value 'VALUE' I'd like a boolean series for all the rows whose interval comprises the given value.</p>
<p>For instance, if i have a value = 10 I'd like the rows with the bin (8, 12] to assume True and those with the bin (0, 8] assum... | <p>Yes there is one short cut</p>
<pre><code>m=pd.arrays.IntervalArray(df['COLUMN']).overlaps(pd.Interval(VALUE, VALUE))
</code></pre>
<p>Or</p>
<pre><code>m=pd.Index(df['COLUMN']).isin([VALUE])
</code></pre> | python|pandas | 3 |
2,629 | 62,885,709 | Which fmt option in numpy.savetxt keeps infinite integer precision? | <p>I have been using <code>numpy.savetxt</code> without specifying the <code>fmt</code> option, and sometimes when a particularly large integer is supposed to be saved, it is recorded with an <code>e</code> notation as a floating point number of some finite precision.
I would like all integers, no matter how many digit... | <p>Use <code>'%s'</code> or <code>'%r'</code>, which simply call <code>str</code> or <code>repr</code> on the elements of your array respectively.</p>
<p>Also, you're reading the wrong format string documentation. (It's the format string documentation the <code>numpy.savetxt</code> docs link to, but it's still wrong.) ... | python|numpy|precision | 4 |
2,630 | 62,546,306 | How to create a text file based on the unique values of a dataframe column? | <p>I have an excel table with 2 columns called ('NE' and 'Interface'), and what I want to do is: to edit a .txt-file template (which I already have, I show it below) with each Interface value. Then concatenate the txt-files which belongs to the same group of 'NE'.</p>
<p>This is my excel:</p>
<p><a href="https://i.stac... | <ul>
<li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">pandas.DataFrame.groupby</a> on the <code>NE</code> column.
<ul>
<li>This returns a <code>DataFrameGroupBy</code> object, where <code>i</code> is the unique groupby value from <code>... | python|excel|pandas|export|concatenation | 1 |
2,631 | 54,380,560 | Exporting /writing to Excel tabs from a Multi-Index Pandas DataFrame | <p>I'd like to split/slice a multi-index dataframe by the first index '0' into a dataframe for each level of the first index (for example below there would be 4 dataframes). I would then like to export each dataframe into a separate tab in EXCEL. The most important problem I'd like help on is how to write a loop or lis... | <p>Use</p>
<pre><code>for idx in df2.index.get_level_values('IDX1').unique():
temp = df2.loc[idx]
temp.to_excel(writer, sheet_name=idx)
</code></pre>
<p>Loop over all unique values of the index by using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_level_values.html" rel... | python|excel|list-comprehension|pandas-groupby | 2 |
2,632 | 73,819,961 | Pandas: Check values between columns in different dataframes and return list of multiple possible values into a new column | <p>I am trying to compare two columns from two different dataframes, and return all possible matches using python: (Kinda of an xlookup in excel but with multiple possible matches)</p>
<p>Please see the details below for sample dataframes and work I attempted.</p>
<p>An explanation of the datasets below: Mark does not ... | <p>You can always use a list comprehension with the <code>df.Series.isin</code> to do the work.</p>
<pre><code>result = [claimed[claimed['Car Brand'].isin([i])]['Owner Name'].to_numpy() for i in Marks['Car Brand']]
Marks['Possible Owners'] = result
Car Brand Owner Name Possible Owners
0 Jeep Mark [Fran... | python|pandas|list|dataframe | 1 |
2,633 | 73,554,325 | How to read data and write to variables from dictionary | <p>I have a dictionary like:</p>
<pre><code>mapping = {"Filename1": 999, "Filename2": "998"}
</code></pre>
<p>I have a process where I define a variable 'Filename1' with:</p>
<pre><code>import pandas as pd
read="Filename1"
code=999
df=pd.read_csv(f'{read}.csv')
df['new_col'] = ... | <p>How about</p>
<pre class="lang-py prettyprint-override"><code>for read, code in mapping.items():
df=pd.read_csv(f'{read}.csv')
df['new_col'] = code
df.to_csv(f'{read}_new.csv', index=False)
</code></pre>
<p>You haven't specified how you want to write the DataFrame to disk, but you could modify the last l... | python|pandas | 2 |
2,634 | 73,626,750 | Cannot plot or use .tolist() on pd dataframe column | <p>so I am reading in data from a csv and saving it to a dataframe so I can use the columns. Here is my code:</p>
<pre><code>filename = open(r"C:\Users\avalcarcel\Downloads\Data INSTR 9 8_16_2022 11_02_42.csv")
columns = ["date","time","ch104","alarm104","ch114&quo... | <p>So, the <code>df.ch104.values.tolist()</code> code beasicly turns your column into a 2d 1XN array. But what you want is a 1D array of size N.</p>
<p>So transpose it before you call <code>.tolist()</code>. Lastly call <code>[0]</code> to convert <strong>Nx1 array</strong> to <strong>N array</strong></p>
<pre><code>df... | python|pandas|dataframe|csv|matplotlib | 0 |
2,635 | 71,333,010 | Use dataframe column containing "column name strings", to return values from dataframe based on column name and index without using .apply() | <p>I have a dataframe as follows:</p>
<pre><code>df=pandas.DataFrame()
df['A'] = numpy.random.random(10)
df['B'] = numpy.random.random(10)
df['C'] = numpy.random.random(10)
df['Col_name'] = numpy.random.choice(['A','B','C'],size=10)
</code></pre>
<p>I want to obtain an output that uses 'Col_name' and the respective ind... | <p>Use <code>melt</code> to flatten your dataframe and keep rows where <code>Col_name</code> equals to <code>variable</code> column:</p>
<pre><code>df['output'] = df.melt('Col_name', ignore_index=False).query('Col_name == variable')['value']
print(df)
# Output
A B C Col_name output
0 0.20... | python|pandas|dataframe | 1 |
2,636 | 71,410,450 | python pandas print specific location of a datetime object | <p>I have looked at other solutions online but none of them work on my dataframe.
I want to get the exact location of a specific datetime object but this code produces this keyerror <code>KeyError: '2018-1-31'</code></p>
<pre><code>import pandas as pd
data=pd.DataFrame()
dti = pd.date_range("2018-01-01", ... | <p>'dti' is not the index, so you cannot use <code>loc</code> directly. You need to generate a boolean Series first:</p>
<pre><code>data.loc[data['dti'].eq('2018-1-31'), 'dti']
</code></pre>
<p>output:</p>
<pre><code>0 2018-01-31
Name: dti, dtype: datetime64[ns]
</code></pre>
<p>to get the index:</p>
<pre><code>data.... | python|pandas|datetime|location | 0 |
2,637 | 52,161,380 | Does condition selection preserve order in Pandas DataFrame? | <p>For example,</p>
<pre><code>df = pandas.DataFrame({'name':['a','b','c'], 'age':[10,20,30]})
name age
0 a 10
1 b 20
2 c 30
df[df['age'] > 10]
name age
1 b 20
2 c 30
</code></pre>
<p>My question is: Does Pandas make sure the index order is preserved?
Is any possible the result li... | <p>Yes, filtering preserve order of rows (also index values).</p>
<p>Need to sort by column <code>age</code> if need change ordering:</p>
<pre><code>df1 = df[df['age'] > 10].sort_values('age', ascending=False)
print (df1)
name age
2 c 30
1 b 20
</code></pre> | python|pandas|dataframe | 3 |
2,638 | 52,108,313 | How to split data to multiple rows in pandas on one condition? | <p>I have the data in the below dataframe as:-</p>
<pre><code>id name value year quarter
1 an 2.3 2012 1
2 yu 3.5 2012 2
3 ij 3.1 2013 4
4 ij 2.1 2013 1
</code></pre>
<p>to be converted to below dataframe i.e. get month from quarter and split row into 3. </p>
<pre><code>id name value year quarte... | <p>Create a quarter to month dataframe to merge on</p>
<pre><code>q2m = pd.DataFrame([
[(m - 1) // 3 + 1, m] for m in range(1, 13)],
columns=['quarter', 'month']
)
df.merge(q2m)
id name value year quarter month
0 1 an 2.3 2012 1 1
1 1 an 2.3 2012 1 2
2 1 an ... | python|pandas|date | 3 |
2,639 | 60,355,337 | How to 'quickly' add row data values in pandas with respect to a certain column? | <p>Please see the attached image below.
I have a data set which record value for each time instance (Time Stamp) in the data set.
Now, I want a single data record (for each column) for any given time. For example, the red box (for 'Time Stamp' 23054350) that I have made should sum up to be a single 'SMS in', 'SMS out'... | <p>Try this</p>
<pre><code>df.groupby('Time Stamp').sum()
</code></pre> | pandas|dataframe | 1 |
2,640 | 60,508,218 | Keras CNN Model accuracy remaining relatively the same and val_accuracy not improving | <p>I am trying to train a model to identify between malignant and benign images using Keras, however I am not achieving the results I had hoped for. The dataset is categorized well and gathered from the ISIC - Archive (<a href="https://www.isic-archive.com/" rel="nofollow noreferrer">https://www.isic-archive.com/</a>).... | <p>This line of code is the your source of problem: <code>model.add(Dense(2, activation='sigmoid'))</code>.</p>
<p>Either use:</p>
<ol>
<li><code>model.add(Dense(2, activation='softmax'))</code></li>
<li><code>model.add(Dense(1, activation='sigmoid'))</code></li>
</ol>
<p>Note that in case (1) you need to use 'cate... | python|tensorflow|machine-learning|image-processing|keras | 0 |
2,641 | 60,375,395 | Minimum if condition is met in pandas dataframe | <p>I have a data frame;</p>
<pre><code>Date Price Product
1/1/12 22 Pen
1/2/12 44 Paper
1/2/12 33 Paper
1/3/12 34 Paper
</code></pre>
<p>And I want to just have the min value if there are duplicates for Date and Product. </p>
<p>So the expected output is </p>
<pre><code>Date Pr... | <pre><code>df.sort_values('Price', ascending=False).groupby(['Date','Product'],sort=False).last()
Price
Date Product
1/2/12 Paper 33
1/3/12 Paper 34
1/1/12 Pen 22
</code></pre>
<p>Feedback from cs95 was accurate.</p> | pandas|min | 2 |
2,642 | 72,709,699 | How can I loop through every item of multiple list with special condition? | <p>I have 2 dataframes as below:</p>
<p>df1:</p>
<pre><code>df1 = pd.DataFrame({'feature1':['a1','a1','a1','b1','b1','b1'], 'value': [1,2,3,4,5,6]})
df1
</code></pre>
<p>df2:</p>
<pre><code>df2 = pd.DataFrame({'feature1':['c1','c1','c1','c2','c2','c2'], 'value2': [1,2,3,1,2,3]})
df2
</code></pre>
<p>My goal is to yield... | <p>Loops are basically <em>never</em> the answer when it comes to pandas.</p>
<p>Filtering after cross joining everything:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'feature':['a1','a1','a1','b1','b1','b1'], 'value': [1,2,3,4,5,6]})
df2 = pd.DataFrame({'feature':['c1','c1','c1','c2','c2','c2'], 'value': [... | python|pandas|list-comprehension | 1 |
2,643 | 72,495,177 | Convert string duration column to seconds | <p>In the dataframe, one of the columns is duration. It was given as a string.</p>
<pre><code>index duration
1 1 hour, 2 minutes, 21 seconds
2 1 hour, 2 minutes, 26 seconds
3 1 hour, 2 minutes, 41 seconds
4 1 hour, 4 minutes, 39 seconds
5 1 hour, 42 seconds
6 6 minute... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html?highlight=timedelta#pandas.Timedelta" rel="nofollow noreferrer"><code>pd.Timedelta</code></a> to parse each item:</p>
<pre><code>df['duration'] = df['duration'].apply(pd.Timedelta).dt.total_seconds().astype(int)
</code></pre>
<p>Output:<... | python|pandas|string|datetime | 1 |
2,644 | 72,493,838 | TensorFlow Error: dictionary update sequence element #0 has length 6; 2 is required | <p>I am new to Python and machine learning. I am getting an error whenever I run the following code:</p>
<pre><code>def make_input_fn(data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):
def input_function():
ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df))
if shuffle:
... | <p>You are getting this error because of your creating a dictionary in improper format.</p>
<p>For example:</p>
<pre><code>t1 = ('a','b','c','d')
t2 = (1,2,3,4)
dict(t1) #output: ValueError: dictionary update sequence element #0 has length 1; 2 is required
dict(zip(t1,t2)) #output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
</co... | python|tensorflow|machine-learning | 0 |
2,645 | 59,720,243 | Take elements of an array based on indexes in another array | <p>I have an array of values on one side:</p>
<pre><code>A = np.arange(30).reshape((3, 10))
Out: array([[ 0, 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]])
</code></pre>
<p>And an array of indexes referencing it where ... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.take_along_axis.html" rel="nofollow noreferrer"><code>np.take_along_axis</code></a>:</p>
<pre><code>np.take_along_axis(A, index.T, 1).T
array([[ 5, 10, 23],
[ 3, 17, 23]])
</code></pre> | python|arrays|numpy|indexing|take | 3 |
2,646 | 59,498,389 | How can use df.appen when I use eval | <p>j=88.87</p>
<p>I wnat to use eval to do like this:</p>
<pre><code>data_88_87=data_88_87.append(data[data['norm']==88.87])
</code></pre>
<p>but:</p>
<pre><code>eval('data_'+str(j).replace('.','_'))=eval('data_'+str(j).replace('.','_')).append(data[data['norm']==j])
File "<ipython-input-110-a69e45d994b1>"... | <p>You can use it as follows:</p>
<pre><code>j = 88.87
tempVar = "data_"+str(j).replace('.','_')
globals()[tempVar] = eval(globals()[tempVar]).append(data[data['norm']==88.87])
</code></pre>
<p>The above code will give you following output:</p>
<pre><code>data_88_87=data_88_87.append(data[data['norm']==88.87])
</cod... | python|pandas|eval | 1 |
2,647 | 59,694,536 | Need to split data into multiple columns based on character length of each row, using Python | <pre><code>df1.head(1)
Airline_data
0 CAK ATL 114.47 528 424.56 FL 70.19 ...
</code></pre>
<p>The above column named "Airline_data" contains all information combined into a single column. </p>
<p>This has to be splitted to multiple columns like ("City1","City2","Average Fare", ... etc )based on the to ... | <p>I think, the most intuitive way is to apply <em>str.extract</em> to the column of interest
(in your case <em>0</em>).</p>
<p>In order to have proper output column names, use named capturing groups
of respective sizes.
To capture the "wanted" fields, put between them either a space or a dot
(matching any char) with ... | python|pandas | 0 |
2,648 | 61,693,249 | Finding min. in list / 2D array and do calculation in Python | <p>I have a list, I would like to find the min. values in each row and do calculations: row - row.min - 1. </p>
<p>This is what I tried</p>
<pre><code>import numpy as np
list = [[1.2886089553007253e-15, 3.283665029781338e-16, 0.0, 3.4027301260438933e-16],\
[3.047580716284324e-15, 1.3787915767152193e-15, 3.50... | <p>To take the minimum from each row you actually want to take the minimum across the columns, ie. <code>axis=1</code>. Building on what @Patrick has done, to apply the subtraction we need to do some transposing to get broadcasting to work:</p>
<pre><code>import numpy as np
np.set_printoptions(precision=20)
list = [[... | python|arrays|list|numpy | 1 |
2,649 | 61,652,558 | apply function to dataframe column | <p>I have data frame x,</p>
<p><a href="https://i.stack.imgur.com/RIepC.png" rel="nofollow noreferrer">Please view the x dataframe here</a></p>
<p>We want to create new column using below function, which will add Complete columns value in start and create new column finish.</p>
<pre><code>import datetime
def date_by... | <p>Try to refactor your code. If you apply function only to one column, then you do it wrong. Additionally, for some reason you trying to call the function passing time to it. Why if you can just get it right in the function:</p>
<pre><code>import datetime
def date_by_adding_business_days(add_days):
business_days_... | python|pandas|function|dataframe|apply | 2 |
2,650 | 61,684,027 | ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' | <p>I am trying to run a linear regression model using TensorFlow. I have given the code below. However, I got the error as: ValueError: Shape must be at least rank 2 but is rank 1 for 'model_19/MatMul' (op: 'BatchMatMulV2') with input shapes: [1], ?.</p>
<p>From the error, it seems that the input to function model_lin... | <p><code>tf.matmul</code> expects rank 2 tensors, i.e, matrices. Instead you have flat vectors. Try <code>x.reshape(-1,1)</code> or <code>x.expand_dims(0)</code>. And it seems that you also need that for your weight matrix. </p> | python|tensorflow | 0 |
2,651 | 54,935,409 | Concat 2 Dataframes off of 2 columns of matching data but keep the remaining | <p>I have seen how you can merge 2 DFs off of 2 column IDs but it appears as though this creates duplicate values for every iteration. I want to know how to match up 2 columns as if it was a concatenated ID.</p>
<pre><code>df1
1 3 12
1 4 14
df2
1 3 12
1 4 12
Desired Output
id1 id2 df1 df2... | <p>I put together this quick code to re-produce your DataFrame examples and to produce the desired output:</p>
<pre><code>df1 = pd.DataFrame({'id1':[1,1],'id2':[3,4],'value1':[12,14]})
df2 = pd.DataFrame({'id1':[1,1],'id2':[3,4],'value2':[12,12]})
new_df = pd.merge(df1,df2,on=['id1','id2'])
</code></pre>
<p>This merg... | python|pandas | 1 |
2,652 | 54,915,946 | Select a dataframe using boolean selection, and then extract the value corresponding to a certain column | <p>Example dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a': [-3, -2, 0], 'b': [-2, 2, 5], 'c': [-1, 0, 7], 'd': [1, 4, 8]})
</code></pre>
<p>I'm trying to do something which I would expect to be fairly simple, and which is indeed immediate in other languages supporting the dataframe class, such a... | <p>You can't do this in one shot:</p>
<pre><code>In [11]: df.loc[df["a"]==0, "c"]
Out[11]:
2 7
Name: c, dtype: int64
In [12]: df.loc[df["a"]==0, "c"].iat[0]
Out[12]: 7
</code></pre> | python|pandas|boolean-expression | 2 |
2,653 | 49,594,592 | TensorFlow placeholder decoupling for external python code | <p>still learning Tensorflow and I'm trying to change a loss function in some code in Darkflow </p>
<p>The network outputs a given tensor with shape [49,3,2]. I would like to take the two elements in the last part of the tensor and process them with some code. I would then like to return the data back. So a bit like a... | <p>It seems the <code>tf.map_fn</code> function fits your needs. The <a href="https://www.tensorflow.org/api_docs/python/tf/map_fn" rel="nofollow noreferrer">documentation</a> explains you can apply a Python callable to a tensor or a sequence of tensors.</p>
<p>An extract of the current documentation, about the main a... | python|tensorflow|yolo|darkflow | 0 |
2,654 | 49,546,769 | Pandas Styler Hiding Index | <p>I basically want a table that has right-justified table cell entries and a minimum column width of 100. I have two ways to display a Pandas dataframe <code>df</code> in HTML:</p>
<pre><code>html = df.style.applymap(color_negative_red).set_precision(5).set_table_attributes(
'class = "dataframe table-bordered tab... | <p>I think <code>hide_index()</code> may help with dropping the index on your first method. From the <a href="https://pandas.pydata.org/pandas-docs/stable/style.html#Hiding-the-Index-or-Columns" rel="nofollow noreferrer">docs</a>,</p>
<blockquote>
<p>The index can be hidden from rendering by calling <code>Styler.hid... | python|pandas|dataframe|pandas-styles | 2 |
2,655 | 49,419,205 | Unexpected behavior with open() and numpy.savetext() functions | <h1>Problem</h1>
<p>I am trying to output statistics about a table, followed by more table data using Pandas and numpy.</p>
<p>When I execute the following code:</p>
<pre><code>import pandas as pd
import numpy as np
data = pd.read_csv(r'c:\Documents\DS\CAStateBuildingMetrics.csv')
waterUsage = data["Water Use (All... | <p>The issue, as pointed out by @hpaulj, is that the same open file is not being referenced. </p>
<p>Replacing</p>
<pre><code>np.savetxt(r'c:\Documents\DS\testFile', dept.values, fmt='%s')
</code></pre>
<p>With</p>
<pre><code>np.savetxt(hw1, dept.values, fmt='%s')
hw1.close()
</code></pre>
<p>Will write all infor... | python|pandas|numpy | 1 |
2,656 | 73,454,249 | Colon operator in List Slicing | <pre><code>mini_batch_X = shuffled_X[:, k * mini_batch_size:(k + 1) * mini_batch_size]
</code></pre>
<p>What is the semantics of the above line? what does the first colon mean?</p> | <p>Colon in a slicing operation will generate <code>slice(None, None, None)</code>, in numpy it means <code>take all indices for this dimension</code>.</p>
<p>A slice is <code>start:end:step</code>, usually step is omitted writing only <code>start:end</code>, but you can also omit start <code>:end</code> that will slic... | list|machine-learning|numpy-slicing|mini-batch | 0 |
2,657 | 73,500,816 | 'str' object has no attribute 'to_csv' | <p>I'm trying to save some data that I collected on a csv file.</p>
<p>And for that I'm using the following code, but I'm getting the error:</p>
<blockquote>
<p>'str' object has no attribute 'to_csv'</p>
</blockquote>
<p>I am using this line <strong>df = pd.to_numeric(df, errors='ignore')</strong> to change Nonetype ... | <p>The issue isn't (only) in <code>pd.to_numeric()</code>; right before that you're <code>str()</code>ing the df and assigning to <code>df</code>, so at that point you have no dataframe left, just a string describing it.</p>
<p>Additionally, you can't use <code>to_numeric</code> like that.</p>
<p>If you want to convert... | python|pandas|dataframe | 1 |
2,658 | 67,461,097 | Filling a dataframe column with values from another column, based on values from a third column | <p>I have a pandas dataframe like the following. I created the last 3 columns based on unique values from the column <code>RefIDPrefix</code>.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>RefIDPrefix</th>
<th>RefIDNumber</th>
<th>GO</th>
<th>PMID</th>
<th>Reactome</th>
</tr>
</thead>
<tb... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>df.pivot()</code></a> to build the columns from <code>RefIDPrefix</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel... | python|pandas|dataframe | 3 |
2,659 | 59,939,549 | Tensorflow Transformer Decoder output not giving the expected result | <p>I have designed an transformer model using tensorflow. The aim of the model is to generate a sequence of text which is ideally an question followed by an answer given an input sentence.</p>
<p>I have datapoints ( around 15k ) whose format is as below</p>
<pre><code>SOURCE SENTENCE: <@>A man in the distance i... | <p>15k examples are quite little for training a transformer model from scratch. Its typical use is in machine translation where the training corpora typically have millions of sentence pairs.</p>
<p>You can try to tune pre-trained models:</p>
<ul>
<li><p><a href="https://github.com/pytorch/fairseq/tree/master/example... | python|tensorflow|transformer-model|attention-model | 0 |
2,660 | 59,907,766 | pandas groupby datetime.date object is not consistent | <p>For example</p>
<pre><code>import datetime
data={'date':[datetime.date(2020,1,i) for i in range(11,13)],
'a1':range(11,13),
'a2':range(21,23)}
df=pd.DataFrame(data)
</code></pre>
<p>If we groupby only the date column, everything is ok</p>
<pre><code>g=df.groupby('date')
print(g.groups)
g.get_group(list(... | <p>IIUC you can try grouping like this:</p>
<pre><code>g=df.groupby([['date','a1']])
print(g.groups)
g.get_group(list(g.groups.keys())[0])
</code></pre> | python|pandas | 1 |
2,661 | 65,280,749 | Fill NaN values wit mean of previous rows? | <p>I have to fill the nan values of a column in a dataframe with the mean of the previous 3 instances.
Here is the following example:</p>
<pre><code>df = pd.DataFrame({'col1': [1, 3, 4, 5, np.NaN, np.NaN, np.NaN, 7]})
df
col1
0 1.0
1 3.0
2 4.0
3 5.0
4 NaN
5 NaN
6 NaN
7 7.0
</code></pre>
<p>And here is ... | <p>Probably not the most efficient but terse and gets the job done</p>
<pre><code>from functools import reduce
reduce(lambda d, _: d.fillna(d.rolling(3, min_periods=3).mean().shift()), range(df['col1'].isna().sum()), df)
</code></pre>
<p>output</p>
<pre><code>
col1
0 1.000000
1 3.000000
2 4.000000
3 5.00000... | python|pandas|nan|mean|fillna | 2 |
2,662 | 65,459,915 | Tensorflow '_pywrap_tensorflow_internal' module error | <p>I am facing this error since a long time now. I tried all the possible solutions on the internet. I am using tensorflow 1.14.0 for my project and am facing this error. Project date is due. Please help.
My PC spec:
i5/8gb ram/inbuilt graphics</p>
<pre><code>C:\Users\skshr\.virtualenvs\ThesisProject\Scripts\python.exe... | <p>Have you tried to delete TensorFlow and change your TF version? For example, to 1.15?</p> | python|python-3.x|tensorflow|virtualenv|tensorflow1.15 | 0 |
2,663 | 65,328,438 | Get Max Value of a Row in subset of Column respecting a condition | <p>I have a dataframe that looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>FakeDist</th>
<th>-5</th>
<th>-4</th>
<th>-3</th>
<th>-2</th>
<th>-1</th>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>37</td>
<td>14</... | <p>You can use <code>boolean indexing</code> with <code>loc</code> to filter the columns in the range <code>-2</code> to <code>2</code>, then use <code>idxmax</code> along <code>axis=1</code>:</p>
<pre><code>c = df.columns.astype(int)
df['MaxVal_Dist'] = df.loc[:, (c >= -2) & (c <= 2)].idxmax(1)
</code></pre>... | python|pandas | 2 |
2,664 | 65,124,919 | Column values are not updated when getting the values from another dataframe | <p>I have the following 2 data frames: df, and df_final:</p>
<p><a href="https://i.stack.imgur.com/iqvXe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iqvXe.png" alt="enter image description here" /></a></p>
<p>and</p>
<p><a href="https://i.stack.imgur.com/0ct2v.png" rel="nofollow noreferrer"><img ... | <p>It's easier than you think:</p>
<p><code>df_final['x1'] = df['x1']</code></p> | python|pandas|dataframe | 0 |
2,665 | 65,172,221 | How can i solve Type Error in using Numpy | <p>Why ı got a error? Could you help and modify my code please?</p>
<p>-TypeError: object of type <class 'float'> cannot be safely interpreted as an integer.</p>
<p>-TypeError: 'float' object cannot be interpreted as an integer</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def f(x):
retur... | <p>The first three arguments of <code>linspace</code> are the start, end, and the number of samples to generate - not the step size. Try <code>np.arange(interval1, interval, stepsize)</code>.</p>
<p>Alternatively, you could calculate the number of samples with: <code>num = round((interval-interval1) / stepsize)</code> ... | python|numpy|error-handling | 0 |
2,666 | 65,264,898 | How to apply cummulative sum in Numpy in slices with condition to previous value? | <p>I have a vector with signals with values of <code>1</code> or <code>-1</code>. I want to have a second vector that computes the cumulative sum of consecutive signals with the same value and restarts the cumulative sum every time the signal change. Here is an example:</p>
<pre><code>signal = [1 1 1 -1 -1 -1 -1]
c... | <p>For a <em>fast</em>, fully vectorized way (no loops), you can use a regular <code>np.cumsum()</code>, but on a copy of your array where you subtract the previous group sum at the start of each group:</p>
<pre><code>def group_cumsum(s):
# make a copy and ensure np.array (in case list was given)
s = np.array(s... | python|arrays|numpy | 4 |
2,667 | 65,165,800 | Print portion of null value | <p>I am working with titanic dataset. I wonder how to show portion of null value from a train set.</p>
<p>Here is my code: `</p>
<pre><code>train_count_of_missval_by_col = (train.isnull().sum())
print('----- all columns along with count of missing value')
print(train_count_of_missval_by_col)
print('----only columns whi... | <p>I am not sure if there is a specific operation for this. <code>info()</code> shows you the raw # and tells you the total rows but there are no parameters for the %. Also <code>.info()</code> returns as a <code>None</code> type object, so you can't access any data from that object.</p>
<p>I would suggest looping thro... | python|pandas|null | 0 |
2,668 | 49,960,132 | CuDNN library compatibility error after loading model weights | <p>I am trying to load NSynth weights and I am using tf version 1.7.0 </p>
<pre class="lang-py prettyprint-override"><code>from magenta.models.nsynth import utils
from magenta.models.nsynth.wavenet import fastgen
def wavenet_encode(file_path):
# Load the model weights.
checkpoint_path = './wavenet-ckpt/model.ckpt... | <p>As the error says, the Tensorflow version you are using is compiled for CuDNN 7.0.5 while your system has CuDNN 7.1.3 installed.</p>
<p>As the error also suggests, you can solve this problem:</p>
<ul>
<li>Either by installing CuDNN 7.0.5 (follow instructions here: <a href="https://developer.nvidia.com/cudnn" rel="... | tensorflow|magenta | 16 |
2,669 | 63,831,676 | Remove duplicated but with priority for keep first in pandas | <p>Here is a df:</p>
<pre><code>COL1 COL2 COL3
seqA NA 10
seqA Unknown 5
seqA Cow 50
seqB NA 2
seqC NA 2
seqC Unknown 2
seqC Bird 6
seqC Cow 1
seqD Unknown 30
seqD Shark 2
</code></pre>
<p>so the idea would bee to remove duplicated COL1 value and keep only one with the lowest <code>COL3</code>BUT only take ones with <... | <p>Let us do filter then <code>sort_values</code> + <code>drop_duplicates</code></p>
<pre><code>out = df[df.COL3.lt(10) | df.COL2.eq('Unknown')].sort_values('COL3').drop_duplicates('COL1').sort_index()
Out[47]:
COL1 COL2 COL3
1 seqA Unknown 5
3 seqB NaN 2
7 seqC Cow 1
9 seqD Shark... | python|pandas|dataframe | 2 |
2,670 | 64,137,179 | Numpy get values at indices given in array form | <p>I want to get the values at <code>indices</code> of <code>my_array</code>.</p>
<pre><code>indices = np.array([[[0],
[1],
[0]]])
my_array = np.array([[[1.1587323 , 1.75406635],
[1.05464125, 1.29215026],
[0.9784655 , 1.16957462]]])
</code></pre>
<p>I should get the following output:</... | <p>You can use <a href="https://numpy.org/devdocs/reference/generated/numpy.take_along_axis.html" rel="nofollow noreferrer"><code>np.take_along_axis</code></a>:</p>
<pre><code>np.take_along_axis(my_array, indices, axis=-1)
array([[[1.1587323 ],
[1.29215026],
[0.9784655 ]]])
</code></pre> | python|numpy|numpy-ndarray|numpy-slicing | 2 |
2,671 | 46,984,540 | Vectorize the midpoint rule for integration | <p>I need some help with this problem.
The midpoint rule for approximating an integral can be expressed as:</p>
<pre><code> h * summation of f(a -(0.5 * h) + i*h)
</code></pre>
<p>where h = (b - a)/2 </p>
<p>Write a function midpointint(f,a,b,n) to compute the midpoint rule using the numpy s... | <p>Issue with the posted code was that we needed accumulation into output : <code>value += ..</code> after initializing it as zero at the start.</p>
<p>You can vectorize by using a range array for the iterator, like so -</p>
<pre><code>I = np.arange(1,n+1)
out = (h*np.sin(a - (0.5*h) + (I*h))).sum()
</code></pre>
<p... | python|numpy | 2 |
2,672 | 46,916,171 | Tensorflow: classifier.predict and predicted_classes | <h3>System information</h3>
<ul>
<li>custom code: no, it is the one in <a href="https://www.tensorflow.org/get_started/estimator" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/estimator</a></li>
<li>system: Apple</li>
<li>OS: Mac OsX 10.13</li>
<li>TensorFlow version: 1.3.0</li>
<li>Python version: ... | <p>This looks like a numpy issue. <code>array([b'1'], dtype=object)</code> is one way numpy represents the string <code>'1'</code>.</p> | tensorflow|classification | 0 |
2,673 | 62,958,214 | Numpy where behavior | <p>Why is numpy.where returning two arrays when only one True value is found but when n True>1 return one array for each True. I would like it to always return one array for each true.</p>
<pre><code>import numpy as np
a = np.zeros((5,5),dtype=int)
print(a)
#[[0 0 0 0 0]
# [0 0 0 0 0]
# [0 0 0 0 0]
# [0 0 0 0 0]
# [... | <p><code>np.where</code> returns the row and column indices where the condition specified holds <code>True</code>. In the example your considered, coincidentally the row column indices directly matched the positions where the condition is satisfied. Hence take one more location as 1 to understand <code>np.where</code>.... | python|numpy | 1 |
2,674 | 63,045,478 | tensorflow dataset direct normalization | <pre><code>def get_dataset(file_path, **kwargs):
dataset = tf.data.experimental.make_csv_dataset(
file_path,
batch_size=5, # Artificially small to make examples easier to show.
label_name=LABEL_COLUMN,
na_value="?",
num_epochs=1,
ignore_errors=True,
**kwargs)
... | <p>I would to first read the CSV file with Pandas. Use the <code>map</code> function to normalize the column,</p>
<pre><code># Read the CSV
df = pd.read_csv( 'train.csv' )
# Normalize the "temp" column
df[ 'temp' ] = df[ 'temp' ].map( lambda x : x / SOME_NUMBER )
</code></pre>
<p>Now, save the modified CSV,<... | tensorflow|dataset|normalization | 0 |
2,675 | 67,861,409 | How to assign a new column that shows the total number of rows in a file | <p>Can anyone help? I want to assign a new column which counts how many rows do I have in a single file.
Here I have file name in each row, you can see that the first 9 rows are in a single file(...block_10.jpg) so I want a new column that shows the total rows in the file.
<a href="https://i.stack.imgur.com/Z7u41.png" ... | <pre><code>df_classification['count']=df_classification.groupby('filename')['Name'].transform('count').values
</code></pre>
<p>Thanks to someone who gave an answer but he deleted it because there was a small error. Please comment to take credit for the answer, sir!</p> | python|pandas|dataframe | 1 |
2,676 | 67,862,179 | IndexError: index 54 is out of bounds for axis 0 with size 48 | <p>I am trying to fetch the predicted sentiment score and determine whether the text is positive or negative. But while predicting the values I am getting an array sequence of scores and throws the following error.</p>
<pre><code>import json
f = open(("/content/trending_tweets.json"), "r+")
data = f... | <p>The <code>index</code> variable you use on line 20 is the index of the row in <code>user_timeline_data.iteritems</code> it is not an index from the prediction. The prediction is most likely an array with only one value, since you only predict one instance. So change the <code>index</code> on line</p>
<pre><code>if p... | python|pandas|dataframe|keras|sentiment-analysis | 0 |
2,677 | 67,848,962 | Selecting loss and metrics for Tensorflow model | <p>I'm trying to do transfer learning, using a pretrained <strong>Xception</strong> model with a newly added classifier.</p>
<p>This is the model:</p>
<pre><code>base_model = keras.applications.Xception(
weights="imagenet",
input_shape=(224,224,3),
include_top=False
)
</code></pre>
<p>The dataset ... | <h2>About the data set: <a href="https://www.tensorflow.org/datasets/catalog/oxford_flowers102" rel="noreferrer">oxford_flowers102</a></h2>
<p>The dataset is divided into a <strong>training set</strong>, a <strong>validation set</strong>, and a <strong>test set</strong>. The training set and validation set each consist... | tensorflow|machine-learning|keras|deep-learning|tensorflow2.0 | 8 |
2,678 | 68,019,521 | Calculating Cumulative Compound Interest | <p>I have the code below. It works correctly if the deposit is always > 0. However, if it's 0 for some months, then the pandas algorithm breaks. It doesn't return the correct value.</p>
<pre><code>import pandas as pd
deposit = [100] * 4
rate = [0.1] * 4
df = pd.DataFrame({ 'deposit':deposit, 'rate':rate})
df['int... | <pre><code>import pandas as pd
init_deposit = 100
init_rate = 0.1
deposit = [init_deposit] * 8
rate = [init_rate] * 8
df = pd.DataFrame({ 'deposit':deposit, 'rate':rate})
df.loc[2:4, ['deposit']] = 0
df['interest'] =0
df['total'] =0
df['total'].iloc[0] = init_deposit
for i in range(1, len(df)):
df['interest'].ilo... | python|pandas|dataframe | 0 |
2,679 | 61,195,547 | Show only integers in matplotlib x-axis tickmarks | <p>New to matplotlib and have created a simple line chart from a dataset constructed similar in principle to that below. We'll call that dataframe 'cardata'</p>
<pre><code>|------- |--------|------------|---------|
| id | year | some_var | count |
---------|----... | <p>boolean indexing, groupby and plot with the param xticks:</p>
<pre><code>g = df[df['year'] != 2020].groupby('year').count()['some_var']
g.plot(xticks=g.index)
</code></pre>
<p>One way of plotting labels is to use matplotlib and list comprehension. The code blow will plot the <code>y</code> value but it could reall... | python|pandas|matplotlib|jupyter-notebook|jupyter | 2 |
2,680 | 68,630,198 | Unable to read csv file in Google Colab | <p>I imported these libraries and trying to read a csv file on my desktop</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.read_csv('/Users/yoshithKotla/Desktop/canal/verymimi_M.csv')
</code></pre>
<p>But I get an error saying</p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory: '/Users/... | <p>You cannot read the local files present on your computer directly into the google colab environment.</p>
<p>To upload from your local drive, start with the following code:</p>
<pre><code>from google.colab import files
uploaded = files.upload()
</code></pre>
<p>It will prompt you to select a file. Click on “Choose Fi... | python|pandas|google-colaboratory | 1 |
2,681 | 52,910,939 | mark rows with timestamp between times | <p>I need to mark rows in a time series where the timestamps fall between given time-of-day blocks; when I have eg</p>
<pre><code>values = ([ 'motorway' ] * 5000) + ([ 'link' ] * 300) + ([ 'motorway' ] * 7000)
df = pd.DataFrame.from_dict({
'timestamp': pd.date_range(start='2018-1-1', end='2018-1-2', freq='s').tolis... | <p>One alternative using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow noreferrer"><code>between</code></a></p>
<pre><code>from datetime import time as t
values = ([ 'motorway' ] * 5000) + ([ 'link' ] * 300) + ([ 'motorway' ] * 7000)
df = pd.DataFrame.from_... | pandas|timestamp | 0 |
2,682 | 53,347,606 | Repeat numpy vector-matrix-vector multiplication | <p>I have a set of vectors (n), another set of vectors (s) and a set of 3x3 2D arrays (T).</p>
<pre><code>n = np.array([
[[1, 2, 3]],
[[2, 2, 3]],
[[3, 2, 3]],
[[4, 2, 3]],
[[5, 2, 3]],
[[6, 2, 3]]
])
s = np.array([
[[1, 1, 5]],
[[2, 2, 5]],
[[3, 3, 5]],
[[4, 4, 5]],
[[5, 5,... | <pre><code>np.einsum('imn,jnm,kmn->ijk', n, s, T)
</code></pre> | numpy | 2 |
2,683 | 53,129,440 | Create dataframe with specific length | <p>How can I create a new dataframe using pandas of 1000 length and assign values using for loop. I tried this way. But it doesn't work. </p>
<pre><code> f = {'ID': [],'CSE':[], 'Course Name':[]}
ff = pd.DataFrame(data=f)
for i in range(1000):
ff.loc['173'] = [151, 'CSE']
</code></pre>
<p>It gives output l... | <p>Use:</p>
<pre><code>for i in range(1000):
ff.loc[i] = ['173', 151, 'CSE']
</code></pre>
<p>Better and faster solution is create list of lists and then <code>Dataframe</code> by contructor:</p>
<pre><code>#loop
L = []
for i in range(10):
L.append(['173', 151, 'CSE'])
#list comprehension
#L = [['173', ... | pandas|loops|dataframe | 1 |
2,684 | 53,207,650 | python pandas lambda with 2 and more variables | <p>I have a dataframe where I'd like to add a column with conditional sum of values based on criteria in 2 (possibly 3) different columns. I'm trying to use lambda function such as:</p>
<pre><code>df['newColumn'] = df[['colA','colB']].apply(lambda x,y:
df.loc[df['colA']==x].loc[df['colB']==y]['Total Amount'].sum())
<... | <p>My guess is you want this:</p>
<pre><code>df = pd.DataFrame({'A': [1,1,2,2,3,3],
'B': [2,2,2,3,3,3],
'TotalAmount': [10,20,30,40,50,60]})
df['NewColumn'] = df.groupby(['A', 'B'])['TotalAmount'].transform('sum')
df
# A B TotalAmount NewColumn
#0 1 2 10 ... | python|pandas|lambda | 0 |
2,685 | 65,768,909 | Group numpy matrix based on value of particular column, only on row indices from given array | <p>I have a numpy matrix consisting of binary values. I have a list of row indices as well. Now I have to obtain indices from the matrix where the value for a particular column is 1, and the indices must be contained in the row indices list. What will be an efficient way of doing this? I'm currently doing:</p>
<pre><co... | <p>Maybe looping through the list of row indices is faster since you don't need to loop over all the rows of the matrix:</p>
<pre><code>result = [index for index in indices if dataset[index, col] == 1]
</code></pre> | python|list|numpy|matrix|numpy-slicing | 0 |
2,686 | 65,805,232 | The loss will be Nan when I use loss function defined by torch.nn.function.mse_loss | <p>The loss is always Nan when I use the loss function as follow:</p>
<pre><code>def Myloss1(source, target):
loss = torch.nn.functional.mse_loss(source, target, reduction="none")
return torch.sum(loss).sqrt()
...
loss = Myloss1(s, t)
loss.backward()
</code></pre>
<br>
<p>But when I use the followi... | <p><code>Myloss1</code> and <code>Myloss2</code> are indeed supposedly equivalent. They at least return the same values for all the tensors I have tried them on.</p>
<p>About the Nan, let's first try to find when it happens. The only possible culprit here is the <code>sqrt</code>, which is not differentiable in 0. And ... | pytorch | 0 |
2,687 | 63,637,135 | How to scan characters in strings to flag if the match is correct | <p>I have 2 columns of strings and I'd like to create a column with a "yes" or "no" if the first 3 characters of each string in their row match. Basically code that goes over the first 3 characters of column 1 row 1 and compares it with column 2 row 1 to see if the first 3 chars match; if yes then i... | <p>Here is a one-liner:</p>
<pre><code>df['Col3'] = (df['Col1'].str[:3] == df['Col2'].str[:3]).map(
{True: 'YES', False: 'NO'})
</code></pre>
<p>Rule of thumb: pretty much everything you do with pandas/numpy data is better in vector format, i.e. without using loops.</p>
<p>Step1: extract first three letters from al... | python|pandas|numpy|knime | 3 |
2,688 | 63,567,713 | IndexError: index is out of bounds - word2vec | <p>I have trained a word2vec model called <code>word_vectors</code>, using the Gensim package with size = 512.</p>
<pre><code>fname = get_tmpfile('word2vec.model')
word_vectors = KeyedVectors.load(fname, mmap='r')
</code></pre>
<p>Now, I have created a new Numpy array (also of size 512) which I have added to the word2v... | <p>The 1st time you do a <code>.most_similar()</code>, a <code>KeyedVectors</code> instance (in gensim versions through 3.8.3) will create a cache of unit-normalized vectors to assist in all subsequent bulk-similarity operations, and place it in <code>.vectors_norm</code>.</p>
<p>It looks like your addition of a new ve... | python-3.x|numpy|gensim|word2vec|index-error | 1 |
2,689 | 63,423,089 | How to swap two rows of a Pandas DataFrame? | <p>Suppose I have this dataframe :</p>
<pre><code> 0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
4 20 21 22 23 24
</code></pre>
<p>I want to swap the position of row 1 and 2.</p>
<p>Is there a native Pandas function that can do this?
Thanks!</p> | <p>Use <code>rename</code> with a custom dict and <code>sort_index</code></p>
<pre><code>d = {1: 2, 2: 1}
df_final = df.rename(d).sort_index()
Out[27]:
0 1 2 3 4
0 0 1 2 3 4
1 10 11 12 13 14
2 5 6 7 8 9
3 15 16 17 18 19
4 20 21 22 23 24
</code></pre> | python-3.x|pandas|dataframe | 4 |
2,690 | 63,569,977 | Custom Aggregate Function in Python | <p>I have been struggling with a problem with custom aggregate function in Pandas that I have not been able to figure it out. let's consider the following data frame:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'value': np.arange(1, 5), 'weights':np.aran... | <p>When you pass a callable as the aggregate function, if that callable is not one of the predefined callables like <code>np.mean</code>, <code>np.sum</code>, etc It'll treat it as a transform and acts like <code>df.apply()</code>.</p>
<p>The way around it is to let pandas know that your callable expects a vector of va... | python|pandas|numpy | 2 |
2,691 | 63,481,820 | Excel to JSON using Python, how do I format this data to my needs? | <p>So I want to read an excel file and extract the data into a JSON file using python.</p>
<p>The excel data is formatted as so:</p>
<pre><code>Header 1 | Header 2 | Header 3
x00 x01 x02
x10 x11 x12
. . .
. . .
</cod... | <p>Instead of "creating" JSON yourself, you can create a python dictionary and then let Python convert it to JSON String and store it in a file.</p>
<p>The first error was when you passed <code>len(df)-1</code> to <code>range</code> function. The range function automatically goes till <code>passedValue-1</cod... | python|json|excel|pandas|formatting | 3 |
2,692 | 53,698,082 | Return multiple columns based on date range using pandas | <p>I'm basically trying to calculate revenue to date using pandas. I would like to return N columns consisting of each quarter end. Each column would calculate total revenue to date as of that quarter end. I have:</p>
<pre><code>df['Amortization_per_Day'] = (2.5, 3.2, 5.5, 6.5, 9.2)
df['Start_Date'] = ('1/1/2018', '2/... | <h1>Solution</h1>
<p>Here's a complete solution:</p>
<pre><code>from datetime import datetime
import pandas as pd
df = pd.DataFrame()
df['Amortization_per_Day'] = (2.5, 3.2, 5.5, 6.5, 9.2)
df['Start_Date'] = ('1/1/18', '2/27/18', '3/31/18', '5/23/2018', '6/30/2018')
df['Start_Date'] = pd.to_datetime(df['Start_Date'... | python|pandas | 0 |
2,693 | 72,013,365 | How do i use the & to add two booleans? | <p>can anyone tell me why im getting:</p>
<p>TypeError: unsupported operand type(s) for &: 'float' and 'bool'</p>
<p>on this:</p>
<pre><code> quotesstock['crossup'] = (quotesstock['volatility']*5.5 > quotesstock['vix'] & quotesstock['volatility'].shift(-1, axis = 0) <= quotesstock['vix'].shift(-1, axis =... | <p>This is due to <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow noreferrer">Operator precedence</a>, <code>&</code> is more binding (more sticky) than <code><</code>, <code><=</code>, <code>></code>, <code>>=</code>, <code>!=</code>, <code>==</code> so ... | python|pandas | 1 |
2,694 | 56,641,691 | What are the purposes of each step in train-evaluate-predict in tensorflow? | <p>What do each of the stages do? I understand that for neural nets in nlp, the train will find the best parameters for the word embedding. But what is the purpose of the evaluation step? What is it supposed to do? How is that different from the prediction phase?</p> | <p>Training, evaluation and prediction are the three main steps of training a model ( basically in any ML framework ) and to <strong>move a model from research/development to production</strong>.</p>
<p><strong>Training:</strong></p>
<p>A suitable ML architecture is selected based on the problem which needs to be sol... | tensorflow|machine-learning|nlp | 2 |
2,695 | 47,270,722 | How to define a custom accuracy in Keras to ignore samples with a particular gold label? | <p>I want to write in Keras a custom metric (I am using the tensorflow backend) equivalent to <code>categorical_accuracy</code>, but where the output for samples with a particular gold label (in my case 0, from y_true) have to be ignored. For example, if my outputs were:</p>
<p>Pred 1 - Gold 0</p>
<p>Pred 1 - Gold 1<... | <p>You could try this approach:</p>
<pre><code>def ignore_accuracy_of_class(class_to_ignore=0):
def ignore_acc(y_true, y_pred):
y_true_class = K.argmax(y_true, axis=-1)
y_pred_class = K.argmax(y_pred, axis=-1)
ignore_mask = K.cast(K.not_equal(y_pred_class, class_to_ignore), 'int32')
... | tensorflow|keras|metrics | 1 |
2,696 | 59,221,557 | TensorFlow v2: Replacement for tf.contrib.predictor.from_saved_model | <p>So far, I was using <code>tf.contrib.predictor.from_saved_model</code> to load a <code>SavedModel</code> (<code>tf.estimator</code> model class). However, this function has unfortunately been removed in TensorFlow v2. So far, in TensorFlow v1, my coding was the following:</p>
<pre><code> predict_fn = predictor.from... | <p>Hope you have Saved the Estimator Model using the code similar to that mentioned below:</p>
<pre><code>input_column = tf.feature_column.numeric_column("x")
estimator = tf.estimator.LinearClassifier(feature_columns=[input_column])
def input_fn():
return tf.data.Dataset.from_tensor_slices(
({"x": [1., 2., 3., ... | python|tensorflow|tensorflow-serving|tensorflow2.0|tensorflow-estimator | 0 |
2,697 | 57,281,781 | Is there any method or function in python to name the sides of a 3-Dimensional Matrix, like in 2-D there is a Panda method Dataframedata | <p>I want to name/index the sides of the 3D matrix (Plane,row,column) in pythong code, like in 2D we can do it with the help od Panda methond Dataframe</p>
<blockquote>
<p>matrix = np.reshape((1, 2, 3, 4, 5, 6, 7, 8, 9), (3, 3))</p>
<blockquote>
<p>df = pd.DataFrame(matrix, columns=column_names, index=row_n... | <p>In pandas we can using multiple index </p>
<pre><code>matrix = np.reshape((1, 2, 3, 4, 5, 6, 7, 8), (2,2,2))
df=pd.concat([pd.DataFrame(x)for x in matrix],keys=np.arange(matrix.shape[2]))
df[0][0][0]
1
df[0][0][1]
3
</code></pre> | python|numpy|tensor | 0 |
2,698 | 50,845,372 | TensorFlow's map_fn only runs on CPU | <p>I'm running into a weird problem when trying to get TensorFlow's <code>map_fn</code> to run on my GPU. Here's a minimal broken example:</p>
<pre><code>import numpy as np
import tensorflow as tf
with tf.Session() as sess:
with tf.device("/gpu:0"):
def test_func(i):
return i
test_rang... | <p>The error actually stems from the fact that <code>np.arange</code> produces <code>int32</code>s by default but you specified a <code>float32</code> return type. The error is gone with</p>
<pre><code>import numpy as np
import tensorflow as tf
with tf.Session() as sess:
with tf.device("/gpu:0"):
def test... | python|python-3.x|tensorflow|gpu | 2 |
2,699 | 50,813,683 | How to reorder columns based on regex? | <p>Let's say I have a dataframe like this:</p>
<pre><code>df = pd.DataFrame({'foo':[1, 2], 'bar': [3, 4], 'xyz': [5, 6]})
bar foo xyz
0 3 1 5
1 4 2 6
</code></pre>
<p>I now want to put the column that contains <code>oo</code> at the first position (i.e. at 0th index); there is always only one ... | <p>Use list comprehensions only, join lists together and select by <code>subset</code>:</p>
<pre><code>a = [x for x in df.columns if 'oo' in x]
b = [x for x in df.columns if not 'oo' in x]
df = df[a + b]
print (df)
foo bar xyz
0 1 3 5
1 2 4 6
</code></pre> | python|regex|pandas | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.