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 |
|---|---|---|---|---|---|---|
19,400 | 69,797,150 | Why do we need to redefine pandas DataFrame after changing columns? | <p>I just wondered why Pandas DataFrame class functions do not change their instance.
For example, if I use pd.DataFrame.rename(), dropn(), I need to update the instance by redefining it. However, if its class is list, you can delete an element by a pop() method without redefining it. The function changes its intrinsic... | <p>Pandas has made this option available to users. The 'inplace' parameter in the functions you mentioned works for this. If you set the inplace parameter to True, it will perform the operation on the original DataFrame. I leave some useful links about it.</p>
<p><a href="https://towardsdatascience.com/learn-how-to-use... | python|pandas|numpy|styles | 0 |
19,401 | 69,926,083 | How to evaluate model while the data splitted manually in deep learning? | <p>I split my dataset separated with my model file.
So in my model file, I just run the model and set which is train, val, and test.
My model already has good results, but I struggled when I want to evaluate and predict the model.</p>
<p>Here's my code to set which is train, val, and test file.</p>
<pre><code>train_dat... | <p>I do not think you should be passing both your <code>train_generator</code> and <code>test_generator</code> when evaluating your model. Maybe try this:</p>
<pre class="lang-py prettyprint-override"><code>score = model.evaluate(test_generator, verbose=1)
</code></pre>
<p>Unlike the the method <code>model.fit</code> t... | tensorflow|keras|deep-learning|sequence|evaluate | 1 |
19,402 | 72,331,669 | Is there a way to create a list of values out of existing column value in pandas? | <p>Let's say I have the following pandas dataframe:</p>
<p><a href="https://i.stack.imgur.com/wOwuR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wOwuR.png" alt="sample_df" /></a></p>
<p>I would like to create a new column with the value of ColB and -1 * ColB. The resulting dataframe should look li... | <p>You Can do it like that Direct and clear way</p>
<pre><code>def Test(Col1,Col2):
for i in range(len(Col1)):
yield [Col1[i],-1*Col2[i]]
z=Test(data["ColB"],data["ColB"])
data["ColC"]=list(z)
</code></pre> | python|pandas | 2 |
19,403 | 72,256,978 | How to modify tensor inside custom layer tensorflow? | <p>I have this custom layer that I get an error when I use it inside the model.</p>
<pre><code>class NormalLayer(tf.keras.layers.Layer):
def __init__(self, color_space):
super(NormalLayer, self).__init__()
self.color_space = color_space
def call(self, image):
if self.color_space=="HSV":
... | <p>Try something like this:</p>
<pre><code>import numpy as np
import tensorflow as tf
class NormalLayer(tf.keras.layers.Layer):
def __init__(self, color_space):
super(NormalLayer, self).__init__()
self.color_space = color_space
def call(self, image):
if self.color_space=="HSV":
retur... | python|tensorflow|keras|model|normalization | 1 |
19,404 | 50,423,089 | Select columns names containing a key word in pandas | <p>I have a datafame like this</p>
<pre><code>d = {'col1': ['a', '2/1'], 'col2': ['b', 'c']}
df = pd.DataFrame(data=d)
</code></pre>
<p>I want to know which columns contain the key '/'
since in column 'col1', the first row contains the key char '/', I hope the function could return 'col1'.</p> | <p>You can use a list comprehension with <code>pd.Series.str.contains</code>.</p>
<pre><code>res = [col for col in df.select_dtypes(include=[object]) if
df[col].str.contains(r'/').any()]
print(res) # ['col1']
</code></pre>
<p>In this example, I explicitly isolate columns of <code>object</code> type, since nu... | python|string|pandas|dataframe|series | 0 |
19,405 | 50,655,991 | How to install the cocoapi package on windows required for object detection on tensorflow? | <p>I created a conda environment on Anaconda for installing TensorFlow. After that I followed the steps given <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md" rel="nofollow noreferrer">here</a>. After that I faced problems while installing the cocoapi package. S... | <p>I had the same problem and after a couple of rounds it finally worked after performing the following steps:</p>
<p>1- removed previous installation of visual sudio</p>
<p>2- downloaded Build Tools for Visual Studio 2017 from: <a href="https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2017" rel=... | tensorflow|anaconda|object-detection | 0 |
19,406 | 54,400,697 | How do I pivot with first and 2nd level aggregation at same table | <p>How do I pivot with first and 2nd level aggregation at same table, that is Category and Sub Category</p>
<p>Here's my data</p>
<pre><code>Name Category Sub-Category sum
yuew Food Snack 100
dhjs Food Snack 50
jdsd Food Drink 60
kjkd Food... | <p>Use <code>sum</code> per first level first, then create <code>MultiIndex</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>append</code></a> to original and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.D... | python|pandas | 1 |
19,407 | 54,595,256 | RandomShuffleQueue functionality with tf.data.Dataset | <p>I want to replace my old <code>RandomShuffleQueue</code> approach with the <code>tf.data.Dataset</code>. For some background: I am generating data on runtime, putting it in the queue and then taking it out randomly. </p>
<p>I don't see a way to do that with the <code>tf.data.Dataset</code>, because I would always n... | <p>If I understood you correctly, it sounds like a perfect match for <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator" rel="nofollow noreferrer"><code>Dataset.from_generator()</code></a>. You can add <code>Dataset.shuffle()</code> afterwards, if you would like to make a buffer and take... | python|tensorflow|keras | 1 |
19,408 | 54,554,711 | How to import several csv files from a folder, within a multiplatform environment | <p>I would like Python to import several CSV files that are in one folder and concatenate them. As I am working on a Mac and Windows, I need a solution that works for both. Also, I need Python to read the CSV in a specific way: separation by ;</p>
<p>This is my current situation, I have to manually add the files in th... | <p>I just solved it by combining a few other answers with this</p>
<pre><code>loading = pd.concat([pd.read_csv(f, delimiter=";") for f in loading_files.glob('Loading*.csv')], ignore_index = True)
</code></pre> | python|python-3.x|pandas|csv | 1 |
19,409 | 54,273,680 | Strange behavior of linear regression in PyTorch | <p>I am facing a peculiar problem and I was wondering if there is an explanation. I am trying to run a linear regression problem and test different optimization methods and two of them have a strange outcome when comparing to each other. I build a data set that satisfies y=2x+5 and I add a random noise to that.</p>
<p... | <p>This has to do with the fact that you are drawing the training samples themselves from a <em>random distribution</em>.</p>
<p>By doing so, you inherently randomized the ground truth to some extent. Sure, you will get values that are inherently <em>distributed</em> around <code>2x+5</code>, but you do not guarantee ... | linear-regression|pytorch | 0 |
19,410 | 54,504,386 | Pandas read_csv only first comma | <p>I have a csv database that looks like this:</p>
<pre><code>Date,String
2010-12-31,'This, is, an example string'
2011-12-31,"This is an, example string"
2012-12-31,This is an example, string
</code></pre>
<p>I am trying to use pandas, because I believe it is one of the most widespread libraries to working with this... | <p>You can cheat by passing a regex for the <code>sep</code> argument of <code>read_csv</code>. The regex I used is <code>^([^,]+),</code> which grabs the first comma. I also used the <code>engine</code> argument in order to avoid a pandas warning (since the default C engine does not support a regex sep) and the <code>... | python|string|pandas|csv|multiple-columns | 9 |
19,411 | 73,669,581 | Access denied to subclassed Keras model when loaded from a .py script | <p>I have the following subclassed Keras model which I have already trained. I want to be able to call all the methods in B_frame_CNN (e.g., get_embedding()) on the loaded model. The following code works perfectly and does what I need when run in an ipython notebook.</p>
<pre><code>import tensorflow as tf
class B_fram... | <p>In case anyone stumbles upon the same problem, here is the workaround I found:</p>
<pre><code>bframe_model = tf.keras.models.load_model("D:\\brain_cancer_oct\saved_models\CNN_bframe")
bframe_cnn = BFrameCNN(3, 'relu', 'same')
bframe_cnn.set_weights(bframe_model.get_weights())
bframe_embedding_cnn = bframe_... | python|tensorflow|keras | 0 |
19,412 | 73,830,802 | Pandas rolling max loss between 2 columns with condition | <p>Having a pandas dataframe with multiple columns, I would like to get the max difference between column <code>'high'</code> and subsequent values column <code>'low'</code> over <code>n</code> observations, for each row.</p>
<pre><code>
close high low open
0 12.65 13.16 12.63 12.80
1 12.46 12.... | <p>Probably not the fastest solution but you can define a custom function that cross merges the indexes - with the indexes of <code>high</code> being <code>leq</code> than that of <code>low</code>:</p>
<pre><code>def greater_cartesian(df, n):
idx_frame = df.index[:n].to_frame()
product = idx_frame.m... | python|pandas|rolling-computation | 0 |
19,413 | 71,108,960 | Select values with condition count() Python | <p>I want select all data of values have two type 'E' in data values. In this data, we can have many <code>type 'S'</code> but it's only one value of <code>type 'E'</code>.</p>
<p>For example: ID: 1114 have two <code>'Type'</code>: <code>'E'</code> in values so show all values of 1114.</p>
<p>dataframe 1:</p>
<pre><cod... | <p>For count number of <code>E</code> values create helper column <code>tmp</code> and caout values by <code>sum</code>:</p>
<pre><code>df = (df[df.assign(tmp = df['Type']=='E')
.groupby(['date','Id'])['tmp'].transform('sum').gt(1)])
</code></pre> | python|pandas|dataframe | 1 |
19,414 | 71,350,817 | Python large DataFrame - calculate standard deviation of expanding returns | <p>I am currently working with a super large dataframe (CRSP Daily Stock File), which consists of daily returns for over 16k firms with 8.5m lines of data in total. Running a for loop would take about 2 weeks in Python.</p>
<p>The goal is to calculate the volatility of returns (standard deviation) for every firm. For e... | <p>As I understand that the standard deviation is based on the daily returns which you have already got in the DataFrame. Let me know if I am wrong on this.</p>
<ol>
<li>Convert to Time Series DataFrame</li>
</ol>
<p>The best way to do this is to convert all data to a Timeseries DataFrame:</p>
<h1>Convert values in dat... | python|pandas|dataframe|time-series|pandas-groupby | 0 |
19,415 | 52,054,299 | Pandas - Conditional drop duplicates | <p>I have a Pandas 0.19.2 dataframe for Python 3.6x as below. I want to <code>drop_duplicates()</code> with the same <code>Id</code> based on a conditional logic.</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(1)
df = pd.DataFrame({'Id':[1,2,3,4,3,2,6,7,1,8],
'Name':['A', 'B', 'C', ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for aggregated values with same size as original DataFrame with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.s... | python-3.x|pandas|duplicates | 3 |
19,416 | 60,615,218 | Separate tensorflow dataset to different outputs in tensorflow2 | <p>I have a dataset with 3 tensor outputs of data, label and path:</p>
<pre><code>import tensorflow as tf #tensroflow version 2.1
data=tf.constant([[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,0]],name='data')
labels=tf.constant([0,1,0,1,0,1,0,1,0,1],name='label')
path=tf.constant(['p0','p1','p2','p3','p4... | <p>The solution I found does not look very "pythonic" but it works.
I used the <code>map()</code> method:</p>
<pre><code>data= my_dataset.map(lambda x,y,z:x)
labels= my_dataset.map(lambda x,y,z:y)
paths= my_dataset.map(lambda x,y,z:z)
</code></pre>
<p>After this separation, the order of the labels stays the same. </p... | python-3.x|tensorflow2.0|tensorflow-datasets | 0 |
19,417 | 60,627,275 | Index out of range error while training dataset | <p>I am trying to train MaskRCNN to detect and segment apples using the dataset from this <a href="https://arxiv.org/abs/1909.06441" rel="nofollow noreferrer">paper</a>, </p>
<p><a href="https://github.com/nicolaihaeni/MinneApple.git" rel="nofollow noreferrer">github link to code being used</a></p>
<p>I am simply fol... | <p>fixed this by creating a dummy folder called 'masks' in the "test" folder.. just copy paste the one from 'train' with all the masks.. the train and predict scripts wont really use it, so shoudnt be any issues here.. </p>
<p>also look at <a href="https://stackoverflow.com/questions/60795375/unable-to-load-model-weig... | python|machine-learning|computer-vision|pytorch|conv-neural-network | 0 |
19,418 | 60,581,157 | Vectorized method to compute Hankel matrix for multi-input, multi-output data sequence | <p>I'm constructing a Hankel matrix and wondered if there's a way to further vectorize the following computation (i.e. without for loops or list comprehensions).</p>
<pre><code># Imagine this is some time-series data
q = 2 # Number of inputs
p = 2 # Number of outputs
nt = 6 # Number of timesteps
y = np.array(range(... | <p>You can use <code>stride_tricks</code>:</p>
<pre><code>>>> from numpy.lib.stride_tricks import as_strided
>>>
>>> a = np.arange(20).reshape(5,2,2)
>>> s0,s1,s2 = a.strides
>>> as_strided(a,(3,2,3,2),(s0,s2,s0,s1)).reshape(6,6)
array([[ 0, 2, 4, 6, 8, 10],
[ 1... | python|arrays|numpy | 1 |
19,419 | 72,807,669 | how to insert a list value into a dataframe by row and column number? | <p>How do I insert a list value to a dataframe on a specific row and column?</p>
<p>For example say I have the dataframe</p>
<pre><code> source col 1 col 2
0 a xxx xxx
1 b xxx xxx
2 c xxx xxx
3 a xxx xxx
</code></pre>
<p>My list i... | <p><em>Assuming we're looking at pandas dataframes:</em></p>
<p>I think the <code>df.at</code> operator is what you're looking for:</p>
<pre><code>df = pd.read_csv("./test.csv")
list_value = [5,"text"]
string_to_input = ""
for val in list_value:
string_to_input += str(val) + " &... | python|pandas|dataframe|numpy|datatables | 1 |
19,420 | 59,856,217 | model.fit(...) and "Failed to convert a NumPy array to a Tensor" | <p>I'm using TensorFlow 2.0 for text classification.</p>
<p>The structure of the data looks more-or-less like this:</p>
<h3>1st Approach:</h3>
<pre class="lang-py prettyprint-override"><code>x: List[List[int]] # list of sentences consisting of a list of word IDs for each word in the sentence
y: List[int] # binary tr... | <p>The reason I've documented this mess is that the underlying problem isn't related to the error messages.</p>
<p>The underlying problem is that the input data (<code>x</code>) requires padding.</p>
<p>Sentences naturally have varying lengths. TensorFlow's <code>model.fit(...)</code> does not like that. To get it to... | python|numpy|tensorflow|tensorflow2.0 | 2 |
19,421 | 59,766,210 | TensorFlow / PyTorch: Gradient for loss which is measured externally | <p>I am relatively new to Machine Learning and Python. </p>
<p>I have a system, which consists of a NN whose output is fed into an unknown nonlinear function F, e.g. some hardware. The idea is to train the NN to be an inverse F^(-1) of that unknown nonlinear function F. This means that a loss L is calculated at the ou... | <p>AFAIK, all modern deep learning packages (<a href="/questions/tagged/pytorch" class="post-tag" title="show questions tagged 'pytorch'" rel="tag">pytorch</a>, <a href="/questions/tagged/tensorflow" class="post-tag" title="show questions tagged 'tensorflow'" rel="tag">tensorflow</a>, <a href="/question... | tensorflow|neural-network|pytorch|gradient|backpropagation | 2 |
19,422 | 59,552,596 | pandas dataframe grouping by class and timestamp | <p>I have a dateframe that looks like this:</p>
<pre><code>timestamp class
2019-07-01 00:59:56 A
2019-07-01 11:24:19 B
2019-07-01 12:41:34 B
2019-08-01 05:22:11 A
2019-08-01 07:05:06 A
</code></pre>
<p>now I need to know how many rows of each class do I have on a particular day. </p>... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>Series.dt.date</cod... | python|pandas|class|dataframe|timestamp | 2 |
19,423 | 62,012,673 | Confusion regarding batch size while using DataLoader in pytorch | <p>I am new to pytorch.
I am training an ANN for classification on the MNIST dataset.</p>
<p><code>train_loader = DataLoader(train_data,batch_size=200,shuffle=True)</code></p>
<p>I am confused. The dataset is of 60,000 images and I have set batch size of 6000 and my model has 30 epochs.
Will every epoch see only 6000... | <p>Every call to the dataset iterator will return batch of images of size <code>batch_size</code>. Hence you will have 10 batches until you exhaust all the <code>60000</code> images.</p> | neural-network|pytorch|batchsize | 2 |
19,424 | 61,805,575 | Why saved_model_cli works and loading saved_model.pb does not? | <p>I received a new Tensorflow Saved Model today (saved_model.pb + variables/) and I'm trying to predict images with it.</p>
<p>I have no clues about input and output but I can use <strong>saved_model_cli show</strong> to get some.</p>
<p>Using <strong>saved_model_cli</strong>, I was able to get prediction for one in... | <p>Well, this was a problem with the loading of model.</p>
<pre><code>import tensorflow as tf
import settings
import numpy as np
from PIL import Image
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.framework import convert_to_constants
def get_func_from_saved_model(saved_model_dir):
... | python|tensorflow|tensorflow2.0 | 0 |
19,425 | 61,653,856 | Pandas - Subplotting each groupby series against Date column where count of rows in each group is different | <p>I have a csv file which I have read into a Pandas Dataframe. The dataframe (say 'cdata') has the below columns</p>
<p><a href="https://i.stack.imgur.com/lO4Yd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lO4Yd.png" alt="Dataframe extract"></a></p>
<p>I want to be able to group this data by St... | <p>You are plotting the daily confirmed number and not the cumulative sum of confirmed. You can add a new column with the cumulative sum and plot it instead.</p>
<p>Also, be sure to set the 'Date' column as a date type and sort it before calculating the cumulative sum, you can do something like this:</p>
<pre><code>#... | python|pandas|dataframe|matplotlib|plot | 1 |
19,426 | 58,070,936 | Training from remote resources | <p>All,</p>
<p>I've researched this some and haven't found a clear answer anywhere.</p>
<p>Using Keras with TF backend, how can you train a model using assets (like images for example) that are not local, but remote assets. </p>
<p>For example, if you have 1M images on s3 that are labeled but not organized by folder... | <p>This would be possible by mirroring Keras' generator API. You can make a standard python generator that has an index of image URLs, and yields batches of images loaded from those URLs.</p>
<p>However, I would not recommend this approach. Loading images from the web introduces extra latency, which has the potential ... | tensorflow|keras | 0 |
19,427 | 57,821,753 | How can I convert this SQL code to equivalent pandas code involving a lag function? | <p>I have a pandas dataframe that contains a patient's ID and hospital admit time. I want to filter out the rows where a patient's admission occurs within 30 days of the previous admission (but include the first admission). With SQL I was able to do this using the <code>lag</code> function:</p>
<pre><code>case
-- ma... | <p>Try this one:</p>
<pre class="lang-py prettyprint-override"><code>>>> import pandas as pd
>>> import numpy as np
>>> df=df.sort_values(by=["id", "admit_time"]) #in case your data is not sorted
>>> df_2=df.join(df.groupby("id").min(), on="id", how="left", rsuffix="_min")
>>&... | python|pandas|lag | 0 |
19,428 | 54,709,178 | How to handle words that are not in word2vec's vocab optimally | <p>I have a list of ~10 million sentences, where each of them contains up to 70 words.</p>
<p>I'm running gensim word2vec on every word, and then taking the simple average of each sentence. The problem is that I use min_count=1000, so a lot of words are not in the vocab. </p>
<p>To solve that, I intersect the vocab a... | <p>You could use <a href="https://github.com/facebookresearch/fastText" rel="noreferrer">FastText</a> instead of Word2Vec. FastText is able to embed out-of-vocabulary words by looking at subword information (character ngrams). Gensim also has a FastText implementation, which is very easy to use:</p>
<pre><code>from ge... | python|numpy|optimization|gensim|word2vec | 8 |
19,429 | 54,793,685 | pandas - select group from groupby(by=[group1, group2]) | <p>I'm grouping dataframe by 2 groups <code>native-country</code> and <code>salary</code>, but output on <code>hours-per-week</code> is too large to find specific country.</p>
<pre><code>df.groupby(by=['native-country', 'salary'])['hours-per-week']
</code></pre>
<p>How to select group by country name, e.g. 'Japan' ?<... | <p>Why are you using a <code>groupby</code> at all if you're not trying to perform any aggregations/transformations? Just do: </p>
<pre><code>df.query("'native-country' == 'Japan'")\
.loc[:, ["native_country", "salary", "hours-per-week"]]
</code></pre> | python|pandas | 2 |
19,430 | 54,897,832 | Feeding large numpy arrays into TensorFlow estimators via tf.data.Dataset | <p>TensorFlow's <a href="https://www.tensorflow.org/guide/datasets#consuming_numpy_arrays" rel="nofollow noreferrer"><code>tf.data.Dataset</code> documentation on consuming numpy arrays</a> states that in order to use numpy arrays in combination with the <code>Dataset</code> API, the arrays have to be small enough (<... | <p>You can use <code>np.split</code> and <code>from_generator</code> prior to creating dataset object.</p>
<pre><code>chunks = list(np.split(array, 1000))
def gen():
for i in chunks:
yield i
dataset = tf.data.Dataset.from_generator(gen, tf.float32)
dataset = dataset.shuffle(shuffle_buffer_size)
...
</cod... | python|arrays|numpy|tensorflow|tensorflow-estimator | 3 |
19,431 | 54,849,443 | How to change the A3C Tensorflow example to play Atari games? | <p>I followed the <a href="https://medium.com/tensorflow/deep-reinforcement-learning-playing-cartpole-through-asynchronous-advantage-actor-critic-a3c-7eab2eea5296" rel="nofollow noreferrer">Tensorflow tutorial</a> which implemented A3C in order to do well in the cartpole environment, and wanted to use it as a starting ... | <p>I am afraid you are going to need to change lots of things: first, to deal with inputs that are images you would need to add convolutional layers. Second, traditionally images of atari games are downsampled from 210x160x3 to 64x64(tiny grayscale images)or something like that. So if you are a beginner I think it migh... | python|tensorflow|deep-learning|reinforcement-learning|openai-gym | 1 |
19,432 | 54,808,117 | Pytorch resumes training after every training session | <p>I have a dataset which is partitioned into smaller datasets. </p>
<p>I want to train 3 models for each partition of the dataset, but I need all training sessions to start from the same initialised network parameters. </p>
<p>so it looks like this:</p>
<pre><code>modelList = []
thisCNN = NNet()
for x in range(3):... | <p>Every time you pass <code>thisCNN</code> to <code>trainMyNet</code> you are passing the same network. So, the weights will be updated in the same place. You should declare <code>thisCNN</code> inside your for loop:</p>
<pre><code>for x in range(3):
thisCNN = NNet()
train = torch.utils.data.DataLoader(Subset... | python|machine-learning|deep-learning|computer-vision|pytorch | 2 |
19,433 | 54,982,711 | How to split a column after pivoting the table? | <p>I have a dataset that originally looks like this</p>
<pre><code>ContextID VariableID Timestamp Timestampms Value
7304693 516 2018-07-11 10:49:36 153 1.00000001335143e-10
7304693 516 2018-07-11 10:49:36 291 1.00000001335143e-10
7304693 516 2018-07-11 10:49:36 455 1.00000001335143e-10
7304693 517... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</... | python-3.x|pandas|pivot | 2 |
19,434 | 55,022,228 | How to assign an ID for each start_url in scrapy from dataframe | <p>Lets say I have a dataframe as such:</p>
<pre><code> id url
1 www.google.com
2 www.youtube.com
3 www.google.com
4 wwww.facebook.com
</code></pre>
<p>If I want to iterate each url in the dataframe. So what I'll do is:</p>
<pre><code>start_urls = list(df['url'])
def parse(self,response)... | <p>You could try <code>iterrows</code>:</p>
<pre class="lang-py prettyprint-override"><code>for index, row in df.iterrows():
print(index, row['url'])
parsed_response = parse(response)
df.loc[index, 'scrapy_content'] = parsed_response
</code></pre>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/g... | python|pandas|web-scraping|scrapy | 3 |
19,435 | 54,994,620 | Pandas: Drop columns where first n rows are all NaN | <p>I have a Pandas DataFrame, <code>df</code>, and I'd like to drop columns between index 100 and 200 where the first 1000 rows are all NaN. Here's my incorrect attempt:</p>
<pre><code>df.iloc[:1000, 100:200] = df.iloc[:1000, 100:200].dropna(axis='columns', how='all')
</code></pre>
<p>How might I do this correctly?<... | <p>Try with <code>thresh</code> </p>
<blockquote>
<p>:Require that many non-NA values.</p>
</blockquote>
<pre><code> df.iloc[:1000, 100:200].dropna(axis='columns', thresh =1)
</code></pre> | pandas | 3 |
19,436 | 49,648,035 | Experience Replay is making my agent worse | <p>I have 'successfully' set up a Q-network for solving the 'FrozenLake-v0' env of the OpenAI gym (at least, I think.. not 100% sure how I score - I get 70 to 80 out of 100 successful episodes after 5k episodes of training without Experience Replay). I'm still quite new to these kinds of programming problems, but I do ... | <p>By inspecting the code in your link, I get the impression that:</p>
<ul>
<li><code>e</code> is the <code>epsilon</code> parameter of the <code>epsilon</code>-greedy strategy</li>
<li><code>batch_train</code> appears to be the parameter that decides whether or not to use Experience Replay?</li>
</ul>
<p>Assuming th... | python|tensorflow|reinforcement-learning|q-learning|openai-gym | 1 |
19,437 | 73,400,240 | Incremental counter if the value is the same before the point | <p>I have the following STRING column on a pandas DataFrame.</p>
<pre><code>HOURCENTSEG(string-column)
070026.16169
070026.16169
070026.16169
070026.16169
070052.85555
070052.85555
070109.43620
070202.56430
070202.56431
070202.56434
070202.56434
</code></pre>
<p>As you can see we have many elements where the time overl... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> with splitted values by <code>.</code> and selected first sublist, last add zeros by <a href="http://pandas.pydata.org/pandas-docs/stable/refer... | python|pandas | 1 |
19,438 | 67,573,296 | Select columns that a Pandas dataframe was grouped by | <p>I have a pandas dataframe <code>flsa</code>:</p>
<pre><code>flsa[:10]
auc topics ww top-n fold
0 0.668729 11 entropy 10 1
1 0.609736 11 entropy 10 2
2 0.654445 11 entropy 10 3
3 0.612886 11 entropy 10 4
4 0.596460 11 entropy 10 ... | <p>You can use <code>as_index=False</code> in your <code>groupby()</code> statement to preserve the columns of groupby fields, as follows:</p>
<pre><code>mean_flsa_auc = flsa.groupby(['topics','ww'], as_index=False).mean('auc').drop('fold', axis = 1).drop('top-n', axis=1)
</code></pre>
<p>By default, <code>groupby()</... | python|python-3.x|pandas|dataframe|pandas-groupby | 1 |
19,439 | 67,557,828 | A Problem aboud using multi-gpu with a two-stage CNN model | <p>I design a CNN model which has two stages. First stage is generating proposals like <code>RPN</code> in Faster RCNN and the second feeds these proposals into the following part.</p>
<p><strong>It causes error in the second step.</strong></p>
<p>Accroding the below error information, it seems like the second input is... | <p>I know where I am wrong. Here’s my second stage to feed input</p>
<pre><code>cls, offset = self.model([proposal, fm], stage='two')
</code></pre>
<p><code>proposal</code> is the ROI whose shape is <code>[N, 5]</code>, the 1th dim is the batch index. e.g. The batch size is 4, the range of index is <code>[0,1,2,3]</cod... | python|pytorch|conv-neural-network | 1 |
19,440 | 60,003,994 | Compute distances in kmeans Lloyds algorithm | <p>I'm trying to compute the distance between each point of matrix <code>X</code> (shape N,D) and matrix <code>mu</code> (shape K,D) using numpy:</p>
<pre class="lang-py prettyprint-override"><code>np.array([[np.linalg.norm(x - m) for m in mu] for x in X])
</code></pre>
<p>This is very slow. Is there a faster way to ... | <p>We can extend the dimensions of one matrix to a third dimension and then calculate the distance:</p>
<pre class="lang-py prettyprint-override"><code>np.linalg.norm(X - mu[:,None], axis=-1, ord=2).T
</code></pre> | python|numpy | 0 |
19,441 | 60,299,176 | Search into pandas dataframe column for which input value is smaller than the next index column value | <p>I want to search a dataframe to find a value correspond to index row and column value. However, I am struggling because the column header values are the upper bound of a range where the previous column header value is the lower bound ( but the uppper bound of its other neightbor column value). </p>
<p>I cannot find... | <p>First convert columns to integers by <code>rename</code> if necessary:</p>
<pre><code>data_frame_test = data_frame_test.set_index('location').rename(columns=int)
print (data_frame_test)
200 1000 2000
location
1 342 322 249
2 690 120 990
S 103 193 ... | python|pandas | 1 |
19,442 | 60,003,249 | Extracting numeric value from a string of a dataframe's column and replace the string with that numerical value | <p>say if columns 'A' contains values for first 3 rows: 4.5 mg, 5.8 mg, 6.3 mg
what i want is: After extracting it should look like: 4.5 , 5.8 , 6.3</p>
<p>Any help?
Beside , i can't figure out how to show my dataframe in stackoverflow. So I am really sorry for the question's body formation.</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>Series.str.extract</code></a> with casting to floats:</p>
<pre><code>df = pd.DataFrame({'A':'4.5 mg, 5.8 mg, 6.3 mg'.split(', ')})
df['new'] = df['A'].str.extract(r'(\d\.\d)+').ast... | pandas|python-3.6 | 2 |
19,443 | 60,013,674 | Why do we search for RidgeCV alphas on a logarithmic scale? | <p>Everybody says you should provide a logarithmically scaled range of values for RidgeCV to search over in estimating the optimal alpha value. Why is this? </p> | <p>Because you want to try a larger range of alpha values. Bear in mind that taking a large set of alphas to perform CV will be costly (regarding computational resources), thus, with a <code>np.logspace(-3, 5, 10)</code> you will try 10 alphas with really different magnitudes, from <code>10**-3</code> up to <code>10**5... | numpy|scikit-learn|data-science | 1 |
19,444 | 60,062,250 | Replace empty dictionaries and lists from within pandas dataframe with Null | <p>I have a dataframe that has lists and dictionaries contained within the columns. How would I write a function that I can apply to columns that need to have the empty dictionaries and lists replaced with Null?</p>
<pre><code>def transform_empty_cells(column):
df.loc[(df.column == [] or {}),'column'] = 'Null'
</... | <p>Let us try use <code>bool</code>, since empty <code>dict</code> and <code>list</code> will be converted to False</p>
<pre><code>df.loc[~df.column.astype(bool),'column']='null'
</code></pre>
<p>More columns </p>
<pre><code>df=pd.DataFrame({'Data':[[],[1]],'dct':[{},{1:2}]})
s=df.where(df.astype(bool))
s
Out[24]:
... | python|pandas|list|dictionary|null | 0 |
19,445 | 65,132,632 | pandas: while loop to simultaneously advance through multiple lists and call functions | <p>I want my code to:</p>
<ul>
<li>read data from a CSV and make a dataframe: "source_df"</li>
<li>see if the dataframe contains any columns specified in a list:
"possible_columns"</li>
<li>call a unique function to replace the values in each column whose header is found in the "possible_column... | <pre><code>def yes_no_fix():
destination_df['yes/no'] = destination_df['yes/no fixed'].replace("No","0").replace("Yes","1")
def true_false_fix():
destination_df['true/false'] = destination_df['true/false fixed'].replace('False', '1').replace('True', '0')
fix_functions_li... | python|python-3.x|pandas|while-loop | 1 |
19,446 | 65,118,608 | Some of my dataframe values include dictionaries, while others contain values. How do I remove the dictionaries? | <p>My dataframe is as such:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A': ['a', 'b', {'$numberDouble': 'NaN'}],
'B': ['c', {'$numberDouble': 'NaN'}, 'd'],
'C': [{'$numberDouble': 'NaN'},'e','f']})
</code></pre>
<p>How do I replace all the {'$num... | <p>Use can use applymap with an if/else statement</p>
<p><code>df.applymap(lambda x: np.nan if isinstance(x, dict) else x)</code></p>
<pre><code> A B C
0 a c NaN
1 b NaN e
2 NaN d f
</code></pre> | python|pandas | 4 |
19,447 | 65,262,268 | How do I turn categorical column values into different column names? | <p>I'm not sure how to approach this problem since I'm a beginner with pandas.</p>
<p>I have this dataframe:</p>
<pre><code> col1 col2
0 a 1
1 a 2
2 a 3
3 b 4
4 b 5
5 b 6
6 c 7
7 c 8
8 c 9
</code></pre>
<p>and I want to turn it into a dataframe or a matrix like ... | <p>Let's <code>groupby</code> the dataframe on <code>col1</code> and create key-value pairs inside <code>dict</code> comprehension:</p>
<pre><code>pd.DataFrame({k: [*g['col2']] for k, g in df.groupby('col1')})
</code></pre>
<p>Alternatively, you can use <code>groupby</code> + <code>cumcount</code> to create a sequentia... | python|pandas|dataframe|matrix | 1 |
19,448 | 65,415,585 | Pythonic method to read dates in a pandas df to create a list of scores for heatmap? | <p>I am trying to figure out a way to generate a 'z score' from a pandas df for use in a calendar heatmap.</p>
<p><a href="https://i.stack.imgur.com/Nz64D.png" rel="nofollow noreferrer">Here is an general example of what I'm trying to emulate</a>. It shows day of the week along 'x' axis and weeks along the 'y' axis. Ea... | <p>Only data creation is answered.
Process flow:</p>
<ol>
<li>From each row of the original data frame, create a data frame with a start date to an end date and add it to the new data frame. (Creation of vertical data)</li>
<li>Add a workload column.</li>
<li>Aggregate the amount of work by date</li>
<li>Add the missin... | python|pandas|dataframe|plotly-dash | 0 |
19,449 | 65,159,980 | How to exclude some columns from a pandas dataframe with python | <p>I have a dataframe with shape(1000, 200).</p>
<p>Having 1000 rows and 200 columns, how do i find the most frequent value in each row and add the value to a new column.</p>
<p>I want to exclude first 5 columns from the final result.</p>
<p>The code:</p>
<pre><code> df['Mode'] = df.mode(axis=1).iloc[:, 0]
</code>... | <p>You need value_counts().idxmax() and make sure axis=1</p>
<p>Code:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(low=1,high=6,size=(5,35)), columns=range(35))
print(df)
df['freq'] = df.apply((lambda x: (x[5:].mode())), axis=1)
print(df)
</code></pre>
<p>Output:</p>
<pre><... | python|python-3.x|pandas|dataframe|indexing | 1 |
19,450 | 65,474,321 | How to load more images to memory with flow_from_directory | <p>When I was training my model with data loaded by flow_from_directory with tensorflow, I accidentally deleted a few images from my training set directory, and it soon gave me the warning that it cannot find the file.</p>
<p>so it seems like it is actually reading the images during training, but since my dataset is no... | <p>You can change some of the parameters like <code>batch_size</code> in <code>flow_from_directory</code> which is default to <code>32</code>.<br />
And also after creating dataset you can increase the batch size and prefetch batches number also here <code>dataset.batch(batch_size).prefetch(1)</code><br />
If your data... | python|tensorflow|machine-learning|deep-learning|tensorflow2.0 | 0 |
19,451 | 65,429,488 | Python int comparison not working properly in pandas | <p>I am developing a function for calculating a number for a document based on evaluations on a dataset. I chose pandas since it seemed to be the most efficient way of using a big dataset.
My columns are: citing (identifiers), cited (identifiers), creation (string YYYY-MM or YYYY).<br />
I need to add to a set all the ... | <p>You can locate all rows matching your criterias in (almost) a single shot. In fact, this is more efficient as you will compute the criteria against all rows in one shot, instead of looping over each values.</p>
<pre><code>ix = df[
df.creation.astype(str).str[:4].astype(int).isin({year-1, year-2})
].index
ident... | python|python-3.x|pandas|dataframe|series | 1 |
19,452 | 65,186,815 | Python pandas group by filter records as per logic | <p>I have the pandas dataframe:
<a href="https://i.stack.imgur.com/jp6CW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jp6CW.png" alt="enter image description here" /></a></p>
<p>From it, i need pick all the resources based on below logic:</p>
<ol>
<li>Resources who are with Status as "Accept&... | <p>You can try following code:</p>
<pre><code>#create dataframe
d = [['T1','A','Engineer','accept'],['T2','B','Doctor','accept'],['T2','A','Engineer','Reject'],['T1','A','Engineer','Reject']]
df = pd.DataFrame(d)
df.columns = ['Resource','Company','Role','Status']
df_= df.loc[df['Status']=="accept",]
#group... | python-3.x|pandas|pandas-groupby | 0 |
19,453 | 63,956,426 | Create Dataframe column that uses a dictionary to map the corresponding key,value in a dataframe | <p>Looking to create a dataframe column that will take data from a dictionary and search DF for the value. Example below:</p>
<p>DF1:</p>
<pre><code>ColA ColB ColC ColD
Dog 4.5 1.3 6.4
Cat 154 89 2
Frog 8 x 9
</code></pre>
<p>Dictionary = {'Dog':'ColC', 'Cat':'ColB'... | <p>You can use lookup:</p>
<pre><code>df['new_col'] = df.set_index('ColA').lookup(Dictionary.keys(), Dictionary.values())
</code></pre>
<p>Output:</p>
<pre><code> ColA ColB ColC ColD new_col
0 Dog 4.5 1.3 6.4 1.3
1 Cat 154.0 89 2.0 154
2 Frog 8.0 x 9.0 9
</code></pre> | python|pandas|dataframe | 5 |
19,454 | 64,154,566 | cleaning up table data from a webscraper | <p>I have a webscraper that pulls table data and sometimes it's uneven in the data it gets, it pulls the data into a table like so</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expe... | <p>I don't know why it didn't hit me, but editing the question it hit me, just instantiate a new empty list, iterate over it and call the original function</p>
<pre><code>new2 = []
for i in range(len(np_arrays)):
new2.append(clean_data(np_arrays[i], feature_list))
print(new2)
</code></pre>
<p>[{'MLS Number': '22124... | python|numpy|selenium|dictionary | 1 |
19,455 | 63,976,189 | Pad around 2D array with 1D array in clockwise manner - NumPy / Python | <p>Lets say there are two arrays:</p>
<pre><code>inner_array = np.array([[3, 3, 3],
[6, 6, 6],
[9, 9, 9]])
outer_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
</code></pre>
<p>What is the cleanest way to create array that looks like this:</p>
... | <p>Here's one way with choosing the starting position as additional arg -</p>
<pre><code>def fill_around(inner_array, outer_array, origin=0):
outer_array = np.roll(outer_array, origin)
m,n = inner_array.shape
out = np.pad(inner_array,(1,1))
s = np.split(outer_array, np.cumsum([n+2,m,n+2]))
out[... | python|python-3.x|numpy | 5 |
19,456 | 46,840,707 | Efficiently find centroid of labelled image regions | <p>I have a segmented image as a 2 dimensional matrix of unique labels 1 ... k. For example:</p>
<pre><code>img =
[1 1 2 2 2 2 2 3 3]
[1 1 1 2 2 2 2 3 3]
[1 1 2 2 2 2 3 3 3]
[1 4 4 4 2 2 2 2 3]
[4 4 4 5 5 5 2 3 3]
[4 4 4 5 5 6 6 6 6]
[4 4 5 5 5 5 6 6 6]
</code></pre>
<p>I am trying to det... | <p>This computation requires accumulation, I don't know how efficient that is on a GPU. This is the sequential algorithm in psuedo-code:</p>
<pre><code>int n[k] = 0
int sx[k] = 0
int sy[k] = 0
loop over y:
loop over x:
i = img[x,y]
++n[i]
sx[i] += x
sy[i] += y
for i = 1 to k
sx[i] /= n[i... | numpy|image-processing|gpu|image-segmentation|pytorch | 2 |
19,457 | 63,307,053 | TypeError: 'Image' object does not support item assignment | <p>I am running the model below and after splitting the image and trying to assign the image back I get the error message stating.</p>
<pre><code> sample[:, :, 0] = 0
TypeError: 'Image' object does not support item assignment
</code></pre>
<p>I have tried different approaches to assigning the image back to the sampl... | <p>You are directly operating on a PIL object. you have to convert it to a numpy array first and then manipulate the values:</p>
<pre><code>sample = Image.open(path)
sample = np.asarray(sample, dtype=np.uint8)
</code></pre> | python|opencv|pytorch | 6 |
19,458 | 63,250,852 | Pandas correlation matrix iterate | <p>I have this correlation matrix in pandas df:</p>
<pre><code> YAR.OL NHY.OL TSLA MSFT STB.OL DNB.OL SBO.OL
YAR.OL 1.000000 0.505583 0.164433 0.233010 0.387104 0.421862 0.116018
NHY.OL 0.505583 1.000000 0.183107 0.205349 0.445840 0.465982 0.135244
TSLA 0.164433 0.183107... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>to_dict</code></a> with "rec... | python|pandas | 1 |
19,459 | 67,619,211 | Keras Model Training - Is it possible to pass an generator with 1 or more inputs | <p>I'm currently working on a Visual Question Answering subject.
I've made a model as follow :</p>
<pre><code>Layer (type) Output Shape Param # Connected to
==================================================================================================
input_3 (Inp... | <p>Yes, you should use something like the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer"><code>tf.data.Datasets</code></a> API</p>
<p>if you have a 2 input model, you will do something like this:</p>
<pre><code>x = tf.data.Dataset.from_tensor_slices((img_path_array, quest... | tensorflow|keras|input | 0 |
19,460 | 67,682,328 | In Pandas, how to Shift date index to next calendar date | <p>I have a set of financial data that only have data during weekdays. I want to find the next entry for each row on the next calendar date. So any Monday would find Tuesday, Tuesday would get Wednesday, BUT Friday would be blank because next day is Saturday which the market is not open. Same apply to holidays.</p>
... | <p>It seems you need shifting values with set <code>NaN</code> if difference of dayofweek is negative:</p>
<pre><code>df['date'] = pd.to_datetime(df['date'])
s = df['date'].shift(-1)
df['next_calendarday'] = s.mask(s.dt.dayofweek.diff().lt(0))
</code></pre>
<hr />
<pre><code>print (df)
date day_of_week day... | python|pandas | 1 |
19,461 | 68,611,747 | pandas dataframe merge at the end | <p>How can I merge two dataframes into one, saving only the different rows?</p>
<p>I have tried (with an outer join) the <code>pd.join</code> and the <code>.merge</code> but they seem to mess with the dataframe columns and they don't solve the problem.</p>
<p>My df looks like:</p>
<pre><code>Time (my index) | Open | Hi... | <p>First you can to merge with outer and indicator=True (which return merge infos, for exemple if the value is only on the right df, only on the left df, or on both</p>
<pre class="lang-py prettyprint-override"><code>merged = pd.merge(df1, df2, left_index=True, right_index=True, how='outer', indicator=True)
</code></pr... | python|pandas|dataframe|pandas-groupby | 1 |
19,462 | 68,798,078 | how to insert dataframe into SQl server database in pandas | <p>I would like to insert entire row from a dataframe into sql server in pandas.</p>
<p>I can insert using below command , how ever, I have 46+ columns and do not want to type all 46 columns.</p>
<pre><code> server = 'server'
database = 'db'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DAT... | <p>Along with below statement mention column names</p>
<p>insert into table1 (col1,col2,...conN)
select col1,col2,..colN from df</p>
<p>Ignore Identity columns</p> | python|sql|pandas | 0 |
19,463 | 53,347,661 | Deeplab v3+ Shape mismatch in tuple component | <p>I have trained deeplab v3+ on <code>ADE20K</code>dataset,and got the trained <code>ckpt</code>jlogs and <code>events</code>logs.But when I run <code>eval.py</code>and <code>vis.py</code>on <code>ADE20K</code>,I got the following errors about shape:</p>
<pre><code>Shape mismatch in tuple component 1. Expected [513,5... | <p>Make sure the arguments used in your sh-script match the arguments required by your current code version.</p>
<p>Not long ago you had to pass two separated values for the crop size buy the current implementation uses </p>
<pre><code>--eval_crop_size="513,513" \
</code></pre>
<p>or </p>
<pre><code> --vis_crop_siz... | python|tensorflow|reshape|image-segmentation|deeplab | 0 |
19,464 | 52,953,231 | Numpy aggregate into bins, then calculate sum? | <p>I have a matrix that looks like this:</p>
<pre><code>M = [[1, 200],
[1.8, 100],
[2, 500],
[2.5, 300],
[3, 400],
[3.5, 200],
[5, 200],
[8, 100]]
</code></pre>
<p>I want to group the rows by a bin size (applied to the left column), e.g. for a bin size 2 (first bin is values from 0-2, second bin from 2-4, thir... | <h2>With <code>pandas</code>:</h2>
<p>Make a <code>DataFrame</code> and then use integer division to define your bins:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(M)
df.groupby(df[0]//2)[1].sum()
#0
#0.0 300
#1.0 1400
#2.0 200
#4.0 100
#Name: 1, dtype: int64
</code></pre>
<p>Use <code>.toli... | python|python-3.x|pandas|numpy | 7 |
19,465 | 53,056,765 | Translate str to int in pandas | <p>I have one column like this:</p>
<pre><code>day
2018-10-30
2018-9-25
2018-9-30
</code></pre>
<p>I want to translate day to int day like this:</p>
<pre><code>intday
20181030
2018925
2018930
</code></pre>
<p>Here is my code:</p>
<pre><code>f = lambda x : int(x[0]) * 10000 + int(x[1]) * 100 + int(x[2])
train_df['i... | <p>What i recommend </p>
<pre><code>pd.to_datetime(df.day).dt.strftime('%Y%m%d').astype(int)
Out[56]:
0 20181030
1 20180925
2 20180930
Name: day, dtype: int32
</code></pre> | pandas | 7 |
19,466 | 53,013,084 | appending key-value in pandas from columns | <p>I have following data. I need to form a dictionary from this. There are 20 columns with y1_bin, y2_bin, .....y20_bin. In this toy data, I have shown three columns only. </p>
<pre><code> Firm y1 y2 y3 prob_y1 prob_y2 prob_y3 y1_bin y2_bin y3_bin
0 A 1 2 7 0.006897 0.000421 0.00272... | <p>You could try something like this:</p>
<pre><code>df = pandas.DataFrame([
{'Firm': 'A', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
{'Firm': 'A', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
{'Firm': 'B', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
{'Firm': 'B... | python|pandas | 0 |
19,467 | 53,225,184 | Split an array in python using indexes from a list | <p>I have a 2d array of size 3 by 7 in numpy:</p>
<pre><code>[[1 2 3 4 5 6 7]
[4 5 6 7 8 9 0]
[2 3 4 5 6 7 8]]
</code></pre>
<p>I also have a list that contains indexes of splitting points:</p>
<pre><code>[1, 3]
</code></pre>
<p>Now, I want to split the array using the indexes in the list such that I get:</p>
<p... | <p>You can use a list comprehension with slicing, using <code>zip</code> to extract indices pairwise.</p>
<pre><code>A = np.array([[1, 2, 3, 4, 5, 6, 7],
[4, 5, 6, 7, 8, 9, 0],
[2, 3, 4, 5, 6, 7, 8]])
idx = [1, 3]
idx = [0] + idx + [A.shape[1]]
res = [A[:, start: end+1] for start, end in ... | python|python-3.x|list|numpy|indexing | 2 |
19,468 | 53,342,795 | How can I check whether I use CPU or GPU in TensorFlow? | <p>I've read that</p>
<pre><code>os.environ["CUDA_VISIBLE_DEVICES"] = ''
</code></pre>
<p>takes care that tensorflow will run on CPU and that</p>
<pre><code>os.environ["CUDA_VISIBLE_DEVICES"] = '0'
</code></pre>
<p>takes care that tensorflow will run on GPU 0.</p>
<p>How can I check, which device is used?</p>
<p>... | <p>You should be able to do this by turning on the tensorflow logging statements. There's a few ways to do this. You can do it with a bash environment variable with..</p>
<pre><code>export TF_CPP_MIN_LOG_LEVEL=1
</code></pre>
<p>or from within your code with..</p>
<pre><code>tf.logging.set_verbosity(tf.logging.INF... | tensorflow|gpu|cpu | 1 |
19,469 | 65,798,589 | formatting json data in horizontal order | <p>i have a json file. i am trying to format the data of the json file into horizontal order.</p>
<p>json file</p>
<pre><code>"DataBody":
{
"data": [
{
"name": "Test",
"unit": "",
"format": &quo... | <p>If it's purely for looks, you could turn the lists you want to lie horizontally into strings, i.e.:</p>
<pre><code>for i in dict['DataBody'][['datab']:
dict['DataBody'][['datab'][i] = str(dict['DataBody'][['datab'][i])
</code></pre>
<p>This isn't particularly helpful if you want to parse the data later, but it w... | python|json|pandas | 0 |
19,470 | 65,582,869 | How to make clusters of Pandas data frame? | <p>I am trying to make a cluster of the following pandas data frame and trying to give the names.
E.g - "Personal Info" is cluster name and it consist of (PERSON,LOCATION,PHONE_NUMBER,EMAIL_ADDRESS,PASSPORT,SSN, DRIVER_LICENSE) and also addition of there Counts. which will be 460.</p>
<p><strong>Clusters:</st... | <p>You can create an inverse dictionary and map:</p>
<pre><code>d = {'personal_info': ['PERSON','LOCATION','PHONE_NUMBER','EMAIL_ADDRESS','PASSPORT','SSN','DRIVER_LICENSE'],
'finance':['CREDIT_CARD','BANK_NUMBER','ITIN','IBAN_CODE'],
'info': ['NHS'],
'network':['IP_ADDRESS','DOMAIN_NAME'],
'others':['CR... | python|pandas|dataframe|numpy | 2 |
19,471 | 65,699,732 | How to get the corresponding values of a list | <p>I have 2 lists A & B. I want to check the list A for input "Nein" and if that is true, then I want to get the corresponding text from the list B and use the output (eg:A) as an input in the next command. And this has to iterate over the entire list (else, pass the loop).</p>
<p>I used pandas to extract... | <p>We could combine the two lists into a dictionary, and extract the value of a particular key, given the conditions are satisfied.</p>
<p>The code below demonstrates the process of zipping two lists and converting into a dictionary.</p>
<pre><code>dict(zip(a,b))
</code></pre>
<p>Implementing the above to your code:</p... | python|pandas|dataframe|loops | 2 |
19,472 | 65,614,546 | Count values in dict of pandas series | <p>I have a pandas series of dicts like this:</p>
<pre><code>print(df['genres'])
0 {'0': '1', '1': '4', '2': '23'}
1 {'0': '1', '1': '25', '2': '4', '3': '37'}
2 {'0': '9'}
print(type(df['genres']))
<class 'pandas.core.series.Series'>... | <p>Try:</p>
<pre><code>pd.DataFrame(list(df.genres)).stack().value_counts().to_dict()
</code></pre>
<p>Output:</p>
<pre><code>{'1': 2, '4': 2, '37': 1, '9': 1, '23': 1, '25': 1}
</code></pre> | python|pandas|count | 0 |
19,473 | 63,466,180 | How is the name of this Dataframe method? | <p>I am looking for a way to categorize numerical data in the following way</p>
<p>Given</p>
<pre><code> A B C
0 2 4 2
1 3 4 4
2 4 2 1
3 5 2 5
</code></pre>
<p>transform to :</p>
<pre><code> Category Value
0 A 2
1 A 3
2 A 4
3 A 5
4 B 4
... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer">That is melt function of pandas.</a></p> | python|pandas | 0 |
19,474 | 63,489,180 | convert a df into a specific dictionary of dictionary in pandas | <p>I have a df as shown below</p>
<pre><code>Params Value
teachers 49
students 289
R 3.7
holidays 165
OS 18
Em_from 2020-02-29T20:00:00.000Z
Em_to 2020-03-20T20:00:00.... | <p>Use:</p>
<pre><code>s = df['Params'].str.split('_')
m = s.str.len().eq(1)
d1 = df[m].set_index('Params')['Value'].to_dict()
d2 = df[~m].assign(Params=s.str[-1]).agg(tuple, axis=1)\
.groupby(s.str[0]).agg(lambda s: dict(s.tolist())).to_dict()
dct = {**d1, **d2}
</code></pre>
<p>Result:</p>
<pre><code>{'E... | python-3.x|pandas|dataframe|dictionary | 1 |
19,475 | 63,432,267 | Sklearn - scaler.fit_transform - ValueError: Expected 2D array, got scalar array instead: | <p>I have a task to create a 30x40 feature matrix with random integers between 1 & 100:</p>
<pre><code>import numpy as np
matrix= np.random.randint(1,100,size=(30,40))
</code></pre>
<p>Next I need to rescale the elements in the matrix to be between the range 5-10:</p>
<pre><code>from sklearn import preprocessing
sc... | <p>I think you need to define the feature range when you create an instance of MinMaxScaler like this:</p>
<pre><code>scaler = preprocessing.MinMaxScaler(feature_range=(5, 10))
</code></pre>
<p>And then you could fit and transform the data like this:</p>
<pre><code>matrix1 = scaler.fit_transform(matrix)
</code></pre>
<... | python|arrays|numpy|scikit-learn | 0 |
19,476 | 63,553,242 | Pandas: Get abs() mean() in Aggregate function | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer">From the docs</a> it is possible to <code>.aggregate</code> a <code>dataframe.groupby</code> object like this:</p>
<pre><code>df = pd.DataFrame([[1, 2, 3],
[-4, 5, 6],
... | <p>Yes we can pass <code>lambda</code></p>
<pre><code>my_agg = {'A' : ['mean', 'min', lambda x : abs(x.mean())], 'B' : ['mean', 'max']}
df.agg(my_agg)
Out[194]:
A B
<lambda> 1.333333 NaN
max NaN 8.0
mean 1.333333 5.0
min -4.000000 NaN
</code></pre> | python-3.x|pandas|pandas-groupby|dask|dask-dataframe | 3 |
19,477 | 53,732,300 | PyTorch - Incorrect labeling using torchvision.datasets.ImageFolder | <p>I have structured my dataset in the following way:</p>
<pre><code>dataset/train/0/456.jpg
dataset/train/1/456456.jpg
dataset/train/2/456.jpg
dataset/train/...
dataset/val/0/878.jpg
dataset/val/1/234.jpg
dataset/val/2/34554.jpg
dataset/val/...
</code></pre>
<p>So I used <code>torchvision.datasets.ImageFolder</code... | <p>Someone helped me out with this. ImageFolder creates its own internal labels. By printing <code>image_datasets['train'].class_to_idx</code> you can see what label is paired to what internal label. Using this dictionary, you can trace back the original label.</p> | python|pytorch|torchvision | 8 |
19,478 | 72,025,855 | Set tuple pair of (x, y) coordinates into dict as key with id value | <p>The data looks like this:</p>
<pre><code>d = {'location_id': [1, 2, 3, 4, 5], 'x': [47.43715, 48.213889, 46.631111, 46.551111, 47.356628], 'y': [11.880689, 14.274444, 14.371, 13.665556, 11.705181]}
df = pd.DataFrame(data=d)
print(df)
location_id x y
0 1 47.43715 11.880689
1 ... | <p>I think this</p>
<pre><code>result = dict(zip(zip(df['x'], df['y']), df['location_id']))
</code></pre>
<p>should give you what you want? Result:</p>
<pre><code>{(47.43715, 11.880689): 1,
(48.213889, 14.274444): 2,
(46.631111, 14.371): 3,
(46.551111, 13.665556): 4,
(47.356628, 11.705181): 5}
</code></pre> | python|pandas|dataframe|dictionary|tuples | 3 |
19,479 | 55,419,869 | Is there a way to show the type of every column in Python? | <p>I use <code>dtype</code> to show the types of the columns, but most of the types will appear as <code>object</code> and you need to check it individually by using the <code>type()</code> method to know, for example, if it is an <code>str</code> actully.</p>
<p>Is there a better way to get it str or <code>numpy.int6... | <p>dtypes is the right answer but it seems that you have mixed dtypes in your columns. As soon as pandas sees a columns with multiple types in it, it automatically casts it into object dtype.</p>
<p>Can you post the result of <code>df_18.air_pollution_score.apply(type).unique()</code> ?</p> | python|pandas | 0 |
19,480 | 66,966,492 | Is there a way to use bert-large as a text classification tool without fine-tuning? | <p>I'm currently have a task of converting a keras BERT-based model for any text classification problem to the .pb file. For this I already have a function, that takes in the keras model, but the point is that when I'm trying to download any pre-trained versions of BERT they always end up without any top layers for cla... | <p>You have to do some sort of additional work with BERT for text classification otherwise it won't know what labels you require classification to.</p>
<p>The simplest way to do this if you want to avoid fine-tuning is to do something like:</p>
<pre><code>model = TFBertModel.from_pretrained("bert-large-uncased&quo... | python|tensorflow|keras|nlp|bert-language-model | 0 |
19,481 | 66,960,952 | add range to Pandas describe() method | <p>I'm trying to do this</p>
<p>this original describe method for Pandas</p>
<pre><code> sepal_len sepal_wid petal_len petal_wid
count 5.000000 5.000000 5.000000 5.0
mean 4.860000 3.280000 1.400000 0.2
std 0.207364 0.258844 0.070711 0.0
min 4.600000 3.000000 1.... | <p>you can do with <code>loc</code> in one line</p>
<pre><code>ds.loc['range'] = ds.loc['max'] - ds.loc['min']
print(ds)
sepal_len sepal_wid petal_len petal_wid
count 5.000000 5.000000 5.000000 5.0
mean 4.860000 3.280000 1.400000 0.2
std 0.207364 0.258844 0.070711 0.0... | python|pandas|dataframe|nan | 4 |
19,482 | 47,269,283 | Split Excel worksheet using Python | <p>I have excel files (hundreds of them) that look like this (sensor output):</p>
<pre><code>Column1 Column2 Column3
Serial Number:
10004
Ref. Temp:
25C
Ref. Pressure:
1KPa
Time Temp. Pres.
1 21 1
2 22 1.1
3 23 1.2
. ... | <ul>
<li>Make two copies of the worksheet.</li>
<li>In copy A, start a loop, going on the first column looking for the word <code>Time</code>. Once it finds it, let it delete anything before it. </li>
<li>Remember the row in a variable.</li>
<li>In copy B, delete anything after the remembered row to row number <code>2^... | excel|python-2.7|numpy|dataframe | 1 |
19,483 | 47,445,394 | Adding an animation to a random walk plot [Python] | <p>I have written a code that plots random walks. There are <code>traj</code> different random walks generated and each consists of <code>n</code> steps. I would like to animate their moves. How can I do that?<br>
My code below: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplo... | <p>As it stands now, you generate traj in one shot. I mean that <code>traj</code> in <code>traj = np.cumsum(temp1, axis = 0)</code> already contains all the "story" from the beginning to the end. If you want to create an animation that is in "real time", you should not generate <code>traj</code> in one shot, but iterat... | python|numpy|animation|matplotlib|random | 3 |
19,484 | 68,393,583 | How to stack data in plot without breaking normalization | <p>I need to work with huge csv files looking something like this</p>
<pre><code>x y1 y2 y3 y4 y5 y6 y7 y8 y9
5.01 0.11 0.12 0.12 0.12 0.12 0.12 0.11 0.12 0.11
5.04 0.11 0.12 0.12 0.12 0.12 0.12 0.11 0.11 0.11
5.07 0.... | <p>I prepared four data frames for simple line graphs and used them as data frames. By using fig, we can get the legend and handle from each axis and add them to the list. Finally, we set the labels and handles retrieved by <code>fig.legend()</code>.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
im... | python|pandas|matplotlib | 0 |
19,485 | 68,157,163 | How do I train two sets of data given both files separately? | <p>I am doing a project in which I need to estimate the age of an individual, given an X-Ray of their hand. I am given a testing set, which contains a large collection of images (in a folder on my computer), all NUMBERED, and I am also given a CSV file that corresponds each image number with 2 pieces of information: th... | <p>The approach is simple create a map between the image_data and the label. After that you can create two lists/np.array and use the same to pass the train and label info to you model. Following code should help in getting the same.</p>
<pre><code>import os
import glob
dic = {}
# assuming you have .png format files e... | python|tensorflow|keras|image-classification | 0 |
19,486 | 59,158,778 | Multi-indexing failure | <p>I'm trying to create multi-indexing to my database, based on 2 columns: plant and date.
I want the column of "plant" to be the first one to be the outisde one and then the date.
I worked but for some reason the dates are not "aggregated" into one cell, like you can see here:</p>
<p><a href="https://i.stack.imgur.co... | <p>This failure is expected output of <code>MultiIndex</code>, it <code>'remove'</code> (actually not display) only all levels without last, so here first level if duplicates.</p>
<p>If create 3 levels DataFrame it display like you need:</p>
<pre><code>df_indices.set_index(['plant', 'date', 'Hour'], inplace=True)
</c... | python|pandas|indexing|multi-index | 2 |
19,487 | 59,460,324 | Get rows n index prior to all the rows that meet the criteria | <p>I have written a program that find specific candlestick patterns based on a stock's day data (open, high, low, close) using pandas. Now I want to see what is the average price change one, two, or three days after a pattern appears. How could I get the rows after a pattern? Say I want all rows with a hammer candle I ... | <p>I figured out the answer, if anybody runs into a similar issue here is what I did.
To get the row before or after the filter (hammer == True) shift must be applied before the filter.</p>
<pre><code>data.shift()[data['Hammer'] == True]
</code></pre>
<p>For my particular situation, the following code solved the iss... | python|pandas|jupyter-notebook|candlestick-chart | 0 |
19,488 | 59,166,578 | Reading multiple CSVs separately and saving them into a dictionary of dataframes in parallel in Python | <p>I have a Python function (shown below) that reads in multiple csv files from S3 and saves them separately as Pandas DataFrames in a dictionary. Is there a way to parallelize this process so that multiple items in <code>tables</code> can be read simultaneously instead of one-by-one? </p>
<pre><code># Load libraries
... | <p>Except using map functions i don't see how you could optimize it better. If you are trying to do one API call to your bucket there might a search parameter to that endpoint on AWS API? </p> | python|pandas|parallel-processing|multiprocessing|dask | 0 |
19,489 | 59,113,354 | create correlation-matrix-like data frame in pandas | <p>I have a df with correlation values for <code>A</code> and <code>B</code></p>
<pre><code>df = pd.DataFrame({'x':['A','A','B','B'],'y':['A','B','A','B'],'c':[1,0.5,0.5,1]})
</code></pre>
<p>I'm trying to create a correlation-matrix-like data frame from <code>df</code> of the kind <code>DataFrame.corr</code> would g... | <p>You just need specifying <code>values</code> to get rid of multiindex</p>
<pre><code>corr = df.pivot_table(columns='y',index='x', values='c')
Out[41]:
y A B
x
A 1.0 0.5
B 0.5 1.0
</code></pre>
<p>If you also want to get rid of axis name, chain <code>rename_axis</code></p>
<pre><code>corr = (df.pivot_ta... | python|pandas | 3 |
19,490 | 59,279,419 | Getting the current age using datetime library | <p>I have a column of a user's DOB data in datetime64[ns] format, and would like to calculate their current age. Every time I parse this date and try to subtract the same with the present date, it throws me an error of str and datetime data format invalidity. </p>
<pre><code>from datetime import datetime
main_file['AD... | <p>It's because that <code>datetime.now().strftime("%H:%M:%S")</code> returns a string object</p>
<p>Below should work:</p>
<pre><code>now = datetime.now()
main_file['Age'] = (now - main_file['AD_DOB']).days/365.0
</code></pre> | python-3.x|pandas|datetime | 1 |
19,491 | 45,947,061 | Pandas conditionaly return value at corresponding position in another column | <p>I am new to python and programming in general.</p>
<p>I am trying to figure out how to return a comma separated value at the corresponding position within a different column in pandas and store this output in a new column. See my example below</p>
<pre><code>key_list = [cat, dog, pig]
A B
--------------... | <p>I use <code>np.core.defchararray.split</code> in a <code>lambda</code> to help split the column's values. I could have used <code>pd.Series.str.split</code>, But I opted for this.</p>
<p>Then I use the <code>lambda</code> and iterate through row by row to create a list of dictionaries. That list of dictionaries c... | python|pandas | 1 |
19,492 | 46,105,302 | Pandas assigning random string to each group as new column | <p>We have a dataframe like</p>
<pre><code>Out[90]:
customer_id created_at
0 11492288 2017-03-15 10:20:18.280437
1 8953727 2017-03-16 12:51:00.145629
2 11492288 2017-03-15 10:20:18.284974
3 11473213 2017-03-09 14:15:22.712369
4 9526296 2017-03-14 18:56:04.665410
5 9526296... | <p>In pandas (R's <code>mutate</code>) is <code>transform</code></p>
<pre><code>df['code']=df.groupby('customer_id').transform(lambda x:pd.util.testing.rands_array(8,1))
df
Out[314]:
customer_id created_at code
0 11492288 2017-03-15 L6Odf65d
1 8953727 2017-03-16 fwLpgLnt
2 11492288 2017-03-... | python|r|pandas|dplyr|pandas-groupby | 8 |
19,493 | 50,970,063 | Adding Rows in pandas data frame based on multilevel index | <p>i have a dataframe like :</p>
<pre><code>(multilevel)index aaa,aaa,aaa,bbb,bbb,bbb,ccc,ccc
Column 1, 1 , 1 , 0, 1, 0, 1 , 1
</code></pre>
<p>i want to add rows based on index so that i get:</p>
<pre><code> index aaa, bbb, ccc
column 3, 1, 2 ... | <p>Perhaps you can do something like this by transposing?</p>
<pre><code>import pandas as pd
df = pd.DataFrame([['aaa', 'aaa', 'aaa','bbb', 'bbb', 'bbb', 'ccc', 'ccc'],
[1, 1, 1, 0, 1, 0, 1, 1]], index = ['index', 'column'])
</code></pre>
<p>So, I would first take transpose, group them, and then t... | python|python-3.x|pandas | 1 |
19,494 | 66,757,752 | Optimizing Pandas function for faster results Python | <p>I am trying to decrease the processing time of the <code>std</code> function below. Is there a module I could import that could decrease the processing time for this function? It calculates the standard deviation each of the the iterating 10000 values one by one. Although the <code>std</code> function is fast I am l... | <h3>Numba</h3>
<p>Use a single pass algorithm</p>
<pre><code>from numba import njit
@njit
def std(a, k):
n = len(a)
m = n - k + 1
k_ = k
mu = np.zeros(m, np.float64)
var = np.zeros(m, np.float64)
mu[0] = a[:k].sum() / k
var[0] = ((a[:k] - mu[0]) ** 2).sum() / k_
for i in range(1, m):... | python|arrays|pandas|dataframe|numpy | 2 |
19,495 | 66,383,507 | Calculation of days until next and since last holiday based on date in Data Frame in Python Pandas? | <p>I have Data Frame like below:</p>
<pre><code>import pandas as pd
df = pd.DataFrame()
df["date"] = pd.date_range("2015", periods=5)
</code></pre>
<p>And list of holidays like: <code>holidays = ["30.12.2014", "02.01.2015", "10.10.2015"]</code></p>
<p>And I would like t... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a> here with default <code>direction='backward'</code> and <code>direction='forward'</code> for add column and then subtract with convert timedeltas to days by <a href="ht... | python|pandas|dataframe|days | 3 |
19,496 | 66,363,241 | Is there a good way to modify some values in a pytorch tensor while preserving the autograd functionality? | <p>Sometimes I need to modify some of the values in a pytorch tensor. For example, given a tensor <code>x</code>, I need to multiply its positive part by 2 and multiply its negative part by 3:</p>
<pre class="lang-py prettyprint-override"><code>import torch
x = torch.randn(1000, requires_grad=True)
x[x>0] = 2 * x[x... | <p>How about like following?</p>
<pre><code>import torch
x = torch.randn(1000, requires_grad=True)
x = torch.where(x>0, x*2, x)
x = torch.where(x<0, x*3, x)
y = x.sum()
y.backward()
</code></pre> | python|pytorch|tensor | 2 |
19,497 | 66,547,831 | How to make custom validation_step in tensorflow 2 Tensorflow 2 / Keras? | <p>I have a question regarding the validation Data.
I have this neural network and I divided my data into train_generator, val_generator, test_generator.</p>
<p>I made a custom model with a custom fit.</p>
<pre><code>class MyModel(tf.keras.Model):
def __init__(self):
def __call__(.....)
def train_step(..... | <p>You have to add a test_step(self, data) function to your MyModel class as you can see it here: <a href="https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit#providing_your_own_evaluation_step" rel="nofollow noreferrer">Providing your own evaluation step</a></p> | python-3.x|machine-learning|nlp|tensorflow2.0|tf.keras | 3 |
19,498 | 57,371,721 | How to Move Weekly Files with Timestamp to Network Drive (Sharepoint Folder) | <p>I've generated some results, wrote to csv and appended a now timestamp to it:</p>
<pre><code>df.to_csv("results.csv", index=False)
os.rename("results.csv", time.strftime("results_" + "%Y%m%d%H%M.csv"))
</code></pre>
<p>So now I have a file - <strong>results_201908061552</strong></p>
<p>Previously without the time... | <p>You can use <a href="https://docs.python.org/3/library/glob.html" rel="nofollow noreferrer">glob</a> to match file names (using a wildcard). This will move all the files starting with 'results' and ending with the '.csv' extension.</p>
<pre><code>import glob
for file in glob.glob('results*.csv'):
print(file)
... | python|pandas | 0 |
19,499 | 70,423,773 | Select number of values from column based on condition in a different df column | <p>I am working on creating a dummy dataset for testing a cloud storage and dashboard system for a university. I am currently trying to assign courses to each student id for a given term. this would be the course enrollment step in real life. Most students take a full load, 4 classes, and some take 3,2 or 1 class, with... | <p>This, you can use <code>apply</code> to ensure the courses are not repeated within each student:</p>
<pre><code>selection = student_master['num_classes'].apply(lambda x: np.random.choice(course['course_id'], x, replace=False) )
</code></pre> | pandas|random | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.