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 |
|---|---|---|---|---|---|---|
6,800 | 73,742,393 | Returning only last item and splitting into columns | <p>I'm having a couple of issues - I seem to be only returning the last item on this list. Can someone help me here please? I also want to split the df into columns filtering all of the postcodes into one column. Not sure where to start with this. Help much appreciated. Many thanks in advance!</p>
<pre><code>import req... | <p>IIUC, you need to replace the loop with:</p>
<pre><code>df = pd.DataFrame({'info': [e.getText(separator=u', ')
.replace('Find out more »', '')
for e in company_elements]})
</code></pre>
<p>output:</p>
<pre><code> ... | python|pandas|dataframe | 0 |
6,801 | 73,726,019 | How to creating recursive JSON hierarchy tree? | <p>You can see the name of parent is color start with child_id 0
and children is red and blue that binds id from color.</p>
<p>I like to get the data in the table to make it into Json how to do?</p>
<p><a href="https://i.stack.imgur.com/cXtCb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cXtCb.png"... | <p>Consider it as a tree and apply simple traversal on the dictionary, which is converted from df by <code>df.to_dict()</code>. Type annotations are added. Hope you can understand.</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, field, asdict
from pprint import pprint
from typing ... | python|pandas | 1 |
6,802 | 52,129,595 | Why the size of numpy array is different? | <p>I have two numpy <code>a,b</code> the shape of them are (100,2048), and I used <code>sys.getsizeof(a) = 112</code> and same with array b.</p>
<p>I have question, when I use <code>c = np.concatenate((a,b),axis=0)</code>, the shape of c is (200,2048), but the <code>sys.getsizeof(c) = 1638512</code></p>
<p>Why?</p> | <p><code>getsizeof</code> has limited value. It can be way off for lists. For arrays it's better, but you have to understand how arrays are stored.</p>
<pre><code>In [447]: import sys
In [448]: a = np.arange(100)
In [449]: sys.getsizeof(a)
Out[449]: 896
</code></pre>
<p>But look at the <code>size</code> of a <code>... | numpy | 1 |
6,803 | 52,370,380 | Python: Find unique value in 2 dataframe and avoid duplicates | <p>I Have two dataframe</p>
<pre><code>df1 = [1, 2, 3, 4, 5]
df2 = [1, 2, 3, 7, 9]
</code></pre>
<p>I want to get a new Df with only [4,5]
(I wrote number, but the real list are two lists of emails)
Then I will turn save DataFrame into CSV file</p>
<p>How can i do it? </p> | <pre><code>df1 = [1, 2, 3, 4, 5]
df2 = [1, 2, 3, 7, 9]
[x for x in df1 if x not in df2]
</code></pre> | python|pandas | 2 |
6,804 | 60,540,666 | Object detection, faster-rcnn | <p>I have a problem when I try to generate tf.record. Although I have set train and test folders properly when I try to generate tf.record using this code,</p>
<pre><code>python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record
</code></pre>
<p>my train.recor... | <p>did you generate .csv file properly? Might want to look at <a href="https://towardsdatascience.com/creating-your-own-object-detector-ad69dda69c85" rel="nofollow noreferrer">https://towardsdatascience.com/creating-your-own-object-detector-ad69dda69c85</a>. there is a good flow on how to do it.</p> | tensorflow|deep-learning|gpu|object-detection|faster-rcnn | 0 |
6,805 | 60,584,206 | How to turn pandas table values into a specific json format? | <p>For example, let's look at the following PANDAS table:
<a href="https://i.stack.imgur.com/sHynv.png" rel="nofollow noreferrer">sample_pandas</a></p>
<p>Question: How can I create a json file that returns this:</p>
<pre><code>{"data":
[
[a1, a2, a3],
[b1, b2, b3],
[c1, c2, c3]
]
}
</code></pre>
<p>I know in pan... | <p>From <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html" rel="nofollow noreferrer">this</a> post, you can:</p>
<pre><code>df = pd.DataFrame('your input')
your_json = df.to_json(orient='split')
</code></pre> | python|json|pandas|list | 0 |
6,806 | 72,714,075 | Remove part of a datetime index in a pandas.core.indexes.datetimes.DatetimeIndex | <p>I wanted to remove the year and minute part of the date-values in the index of a pandas df:</p>
<pre><code>DatetimeIndex(['2022-05-16 14:31:14', '2022-05-16 16:31:15',
'2022-05-16 18:31:16', '2022-05-16 20:31:17',
'2022-05-16 22:31:18', '2022-05-17 00:31:19',
'2022-05-17 ... | <p>This is not possible <strong>if you want to keep the datetime type</strong>, you necessarily need to convert to string using <code>strftime</code>:</p>
<pre><code>df.index.strftime('%m-%d %H')
</code></pre>
<p>output:</p>
<pre><code>Index(['05-16 14', '05-16 16', '05-16 18', '05-16 20', '05-16 22', '05-17 00',
... | python|pandas|datetime|numpy-ndarray|datetime-format | 1 |
6,807 | 72,748,871 | How to unflatten an array | <p>I have an array that I would like to unflatten in python? for example, I have this array</p>
<pre><code>1 5 3
2 2 1
3 0 1
</code></pre>
<p>where the first column is the weight - which tells how many times to repeat the current row, so the final array should be</p>
<pre><code>1 5 3
2 2 1
2 2 1
3 0 1
3 0 1
3 0 1
</cod... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat()</code></a> for this:</p>
<pre><code>import numpy as np
chain = np.array([
[1, 5, 3],
[2, 2, 1],
[3, 0, 1]
])
np.repeat(chain, chain[:, 0], axis=0)
</code></pre>
<p>Thi... | python-3.x|numpy|numpy-ndarray | 2 |
6,808 | 59,861,818 | Keras LSTM layers in Keras-rl | <p>I am trying to implement a DQN agent using Keras-rl. The problem is that when I define my model I need to use an LSTM layer in the architecture:</p>
<pre><code>model = Sequential()
model.add(Flatten(input_shape=(1, 8000)))
model.add(Reshape(target_shape=(200, 40)))
model.add(LSTM(20))
model.add(Dense(3, activation=... | <p>The <code>keras-rl</code> library does not have explicit support for TensorFlow 2.0, so it will not work with such version of TensorFlow. The library is sparsely updated and the last release is around 2 years old (from 2018), so if you want to use it you should use TensorFlow 1.x</p> | keras|tensorflow2.0|reinforcement-learning|keras-rl | 1 |
6,809 | 61,620,087 | Spliting using pandas with comma followed by space or just a space | <p>This is my df</p>
<pre><code>"33, BUffalo New York"
"44, Charleston North Carolina "
], columns=['row'])
</code></pre>
<p>My intention is to split them by a comma followed by a space or just a space like this</p>
<pre><code>33 Buffalo New York
44 Charleston North Carolina
</code></pre>
<p>My command is as follow... | <p>As explained in the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer">pandas docs</a>, your split command does what it should if you just remove the square brackets. This command works:</p>
<pre><code>new_df = df["row"].str.split(",\s|\s", n=... | python|pandas | 2 |
6,810 | 61,740,032 | How to convert convex hull vertices into a geopandas polygon | <p>Iam using DBSCAN to cluster coordinates together and then using convexhull to draw 'polygons' around each cluster. I then want to construct geopandas polygons out of my convex hull shapes to be used for spatial joining.</p>
<pre><code>import pandas as pd, numpy as np, matplotlib.pyplot as plt
from sklearn.cluster i... | <p>Instead of generating polygon directly, I would make a MultiPoint out of your coordinates and then generate convex hull around that MultiPoint. That should result in the same geometry, but in properly ordered manner.</p>
<p>Having <code>z</code> as list of lists as you do:</p>
<pre><code>from shapely.geometry impo... | geopandas|convex-hull | 3 |
6,811 | 61,639,026 | Having issue with adding visible gpu devices: 0 | <p>I m using my gpu for computation on my laptop where I have seen that gpu 0 is for my integrated graphic card and 1 is my nvidia 1050 external graphic card . (from the task manager)
i just want to make sure during the compilation my pycharm compiler uses gpu 1 but I am unable to do so.</p>
<p>Here is the log details... | <p>Your integrated graphics card won't be used for computation.<br>
TensorFlow officially supports NVIDIA gpus.<br>
See <a href="https://www.tensorflow.org/install/gpu#hardware_requirements" rel="nofollow noreferrer">hardware requirements</a>.</p>
<p>This is why you see only gpu 0 as available device.<br>
<code>2020-0... | python|opencv|tensorflow2.0 | 1 |
6,812 | 61,619,032 | Got small output value error between .h5 model and .pb model | <p>I tried both on <code>tf-gpu1.4+keras2.1.3</code> and on <code>tf-gpu1.12+keras2.2.4</code> and the problem always happens.</p>
<p>The problem is: <strong>After I converted the keras.application.ResNet50() model into freeze graph model in .pb format, I feed in the same picture into the converted .pb model but the ... | <p>I removed the <code>K.set_learning_phase(0)</code> and the problem is solved. Maybe it could be better to let Keras to handle with the K.learning_phase() by iteself.
For my experiment, use the value of Keras.model.predict() as the correct outcome:</p>
<pre><code>with K.set_learning_phase(0) and without convert_vari... | python-3.x|tensorflow|keras|deep-learning | 0 |
6,813 | 57,933,011 | torchtext data build_vocab / data_field | <p>I want to ask you some about torchtext.</p>
<p>I have a task about abstractive text summarization, and I build a seq2seq model with pytorch.</p>
<p>I just wonder about data_field constructed by build_vocab function in torchtext.</p>
<p>In machine translation, i accept that two data_fields(input, output) are neede... | <p>You are right in the case of summarization and other tasks, it makes sense to build and use the same vocab for input and output</p> | pytorch|torchtext | 0 |
6,814 | 55,109,304 | Subtract from all columns in dataframe row by the value in a Series when indexes match | <p>I am trying to subtract 1 from all columns in the rows of a <code>DataFrame</code> that have a matching index in a <code>list</code>.</p>
<p>For example, if I have a DataFrame like this one:</p>
<pre><code>df = pd.DataFrame({'AMOS Admin': [1,1,0,0,2,2], 'MX Programs': [0,0,1,1,0,0], 'Material Management': [2,2,2,2... | <p>Using <code>reindex</code> with you <code>sr</code> then subtract using <code>values</code> </p>
<pre><code>df.loc[:]=df.values-sr.reindex(df.index,fill_value=0).values[:,None]
df
Out[1117]:
AMOS Admin MX Programs Material Management
0 1 0 2
1 1 0 ... | python-3.x|pandas|dataframe | 1 |
6,815 | 55,017,076 | Pandas: Sort Two Columns Together in a Pair | <p>I'm trying to sort two pandas dataframe columns. I understand that Python has its own built-in function:</p>
<pre><code>.sort()
</code></pre>
<p>But I'm wondering if Pandas has this function too and if it can be done with two columns together, as a pair.</p>
<p>Say for example I have the following dataset:</p>
<... | <p>Just use:</p>
<pre><code>df.sort_values('feature')
</code></pre>
<p>For resetting index:</p>
<pre><code>df=df.sort_values('feature').reset_index(drop=True)
print(df)
sum feature
0 -3.2120 0
1 -1.4720 1
2 2.8481 2
3 5.1269 3
</code></pre> | python|pandas | 2 |
6,816 | 49,594,048 | C++ - Python Embedding with numpy | <p>I would like to call a python function from C++ and get the return value. I've been able to do that with an easy multiply python function using <a href="https://docs.python.org/2/extending/embedding.html" rel="nofollow noreferrer">this</a> website's example code in section 5.3. To compile my program, I would run <co... | <p>This is happening because your environment is mixing two different Python installations. You can see it jump between them here:</p>
<pre><code>File "/home/osboxes/.local/lib/python2.7/site-packages/numpy/testing/__init__.py"
File "/home/osboxes/miniconda2/lib/python2.7/unittest/__init__.py"
</code></pre>
<p>So yo... | python|c++|numpy|python-embedding | 2 |
6,817 | 73,410,732 | Python PIL: open many files and load them into memory | <p>I have a dataset containing 3000 images in train and 6000 images in test. It's 320x320 rgb png files. I thought that I can load this entire dataset into memory (since it's just 100mb), but then I try to do that I'm getting "[Errno 24] Too many open files: ..." error. Code of loading looks like that:</p>
<p... | <p><code>Image.open</code> is lazy. It will not load the data until you try to do something with it.</p>
<p>You can call the image's <a href="https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.load" rel="nofollow noreferrer"><code>load</code> method</a> to explicitly load the file contents. Th... | python|numpy|python-imaging-library | 1 |
6,818 | 73,413,857 | Split out nested json/dictionary from Pandas dataframe into separate columns | <p>I have a problem that I cannot find a solution for - so here comes the request for assistance.</p>
<p>I receive an export from a DB that looks like this (of course, more than one line in reality):</p>
<pre><code>"created_at","country","query_success","query_result"
"2022-... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>import json
dfs = pd.concat([pd.json_normalize(json.loads(d)) for d in df["query_result"]])
dfs = pd.DataFrame(dfs.values, columns=dfs.columns, index=df.index)
df = pd.concat([df, dfs], axis=1)
df.pop("query_result")
print(df.to_markdown(... | python|json|pandas | 3 |
6,819 | 73,262,040 | Merge rows in pandas dataframe and sum them | <p>suppose I have a dataframe as below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>First</td>
<td>some date</td>
</tr>
<tr>
<td>first</td>
<td>some date</td>
</tr>
<tr>
<td>FIRST</td>
<td>some date</td>
</tr>
<tr>
<td>First</td>
<... | <p>try:</p>
<pre class="lang-py prettyprint-override"><code>df.groupby(df.Name.str.lower()).count()
</code></pre>
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code> Name Date
Name
first 4 4
</code></pre>
<p>After that you can select the columns that you want like <code>['Date']<... | python|pandas|dataframe | 2 |
6,820 | 67,281,205 | Numpy: Select by index array along an axis | <p>I'd like to select elements from an array along a specific axis given an index array. For example, given the arrays</p>
<pre><code>a = np.arange(30).reshape(5,2,3)
idx = np.array([0,1,1,0,0])
</code></pre>
<p>I'd like to select from the second dimension of <code>a</code> according to <code>idx</code>, such that the ... | <p>You could use fancy indexing</p>
<pre><code>a[np.arange(5),idx]
</code></pre>
<p>Output:</p>
<pre><code>array([[ 0, 1, 2],
[ 9, 10, 11],
[15, 16, 17],
[18, 19, 20],
[24, 25, 26]])
</code></pre>
<p>To make this more verbose this is the same as:</p>
<pre><code>x,y,z = np.arange(a.shape[0]... | numpy|indexing|numpy-ndarray | 2 |
6,821 | 67,426,438 | Pandas - How can I group by one numeric column and filter rows from each group by the median of each group? | <p>I have a dataset consisting of one ID, one categorical variable "A" and one numerical variable "B".<br />
I want to group by "A" and filter the rows <strong>from each group</strong> to get only the rows that are avobe or equal to the median of "B" (the median should be calcula... | <pre><code>out = df[df.groupby("A")["B"].transform(lambda x: x >= x.median())]
print(out)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code> ID A B
0 1 Category 1 0.5
3 4 Category 1 0.6
4 5 Category 2 0.4
</code></pre> | python|pandas|pandas-groupby|data-science | 4 |
6,822 | 67,268,888 | How Do I Create New Pandas Column Based On Word In A List | <p>So I have a list and a dataframe. I want to take the the word from the list and make it the title of the column. if the word is the row its added to the newly created column. If its not in the row leave blank or NA.
Should I use iloc?</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
wordlis... | <p>Create a search pattern then use <code>Series.str.extractall</code> to get the words. Then turn each unique word into a dummy and aggregate back to the original row index, and join back to the original DataFrame.</p>
<pre><code>import pandas as pd
pat = f'({"|".join(query)})'
#(is|not)
df_dummies = pd.ge... | python-3.x|pandas|dataframe|if-statement | 4 |
6,823 | 60,001,273 | Pandas consolidating unique elements based on three different columns combined and adding signature | <p>I have a dataframe like below. I would like to get the unique occurances of rows combining three of the values of the columns and then add a 4th column that is a hash of the three columns, using pandas and matching the type below</p>
<p>Here is the dataset:</p>
<pre><code>Type LocationA LocationB LocationC Mo... | <p>You can use <code>transform</code> method for counting identical rows:</p>
<p><code>df['Occurences'] = df.drop(columns=['Model']).groupby(['Type', 'LocationA', 'LocationB', 'LocationC'])['Type'].transform('count')</code></p> | python|pandas|statistics|pandas-groupby | 0 |
6,824 | 60,240,552 | Pandas DataFrame to Dict with (Row, Column) tuple as keys and int value at those location as values | <p>I am trying to make the following DataFrame</p>
<pre><code> A B C D E
A 0 7324 11765 6937 10424
B 7324 0 17791 3532 5902
C 11765 17791 0 17184 20608
D 6937 3532 17184 0 6550
E 10424 5902 20608 6550 0
</code></pre>
<p>to look something... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> and then convert to dict:</p>
<pre><code>df.stack().to_dict()
</code></pre>
<hr>
<pre><code>{('A', 'A'): 0,
('A', 'B'): 7324,
('A', 'C'): 11765,
('A', 'D'): 6937,
('... | pandas|dataframe|tuples | 1 |
6,825 | 65,470,206 | I got different output shape with different Deep Learning model declaration | <p>I am new in this field, and still tinkering with other's codes to see how they work. This code is from <a href="https://github.com/mwitiderrick/stockprice" rel="nofollow noreferrer">https://github.com/mwitiderrick/stockprice</a>
I tried to declare the model in another format as follow</p>
<pre><code>model = Sequenti... | <p>Remove <code>return_sequences=True</code> from the fourth LSTM layer</p> | python|tensorflow|keras|deep-learning|lstm | 0 |
6,826 | 65,112,913 | Find row indices from two 2d arrays with close values | <p>I have an array <code>a</code></p>
<pre><code>a = np.array([[4, 4],
[5, 4],
[6, 4],
[4, 5],
[5, 5],
[6, 5],
[4, 6],
[5, 6],
[6, 6]])
</code></pre>
<p>and an array <code>b</code></p>
<pre><cod... | <p>Instead of <code>==</code>, use <code>np.linalg.norm</code> on <code>a - b[:, np.newaxis]</code> to get the distance of each row in <code>a</code> to each row in <code>b</code>.</p>
<p>If <code>a</code> and <code>b</code> have many rows, this will use lots of memory: e.g., if each has 10,000 rows, the <code>vecdiff<... | python|arrays|numpy | 0 |
6,827 | 65,400,427 | Issue with plotting markers in scattermapbox | <p>Currently, my issue is that I can't seem to get the markers to be in the correct spot for my Scattermapbox (they should be in the USA at the east coast). I zoom all the way out of the map and I see that the markers are in Antarctica, which is not where I want them to be. The longitude and latitude may be the issue, ... | <p>Your code is right. Typically, this happens when you're providing bad GPS coordinates. Check if your longitude and latitude values are swapped in the CSV or if they're legit GPS coordinates.</p> | python|pandas|dataframe|plotly-dash | 1 |
6,828 | 50,208,189 | Dynamic outlier detection using window in Pandas | <p>I want to implement outlier detection which will use a window to check whether the next element is an outlier or not. Let's say we use a window of length 3 on pd.Series like this: [0,1,2,3,4]. I would calculate median and mad (or mean and std) on [0,1,2] and check whether 3 is an outlier.<br>
I implemented a for-loo... | <p>Say you start with</p>
<pre><code>s = pd.Series([1, 2, 1, 4, 2000, 2])
</code></pre>
<p>Then using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="noreferrer"><code>rolling</code></a>, the following will show you that the 5th element is 200 away from a length-3 w... | python|pandas|series | 5 |
6,829 | 50,027,652 | Tensorflow Error: Attempting to use uninitialized value beta1_power_18 | <p>This is my code in tensorflow for simple neural network:</p>
<pre class="lang-python prettyprint-override"><code>import tensorflow as tf
import numpy as np
class Model:
def __init__(self,input_neuron=2,hidden_neuron=10,output_neuron=2):
self.input_neuron = input_neuron
self.hidden_neuron = hidd... | <p>You do the <code>self.sess.run(tf.global_variables_initializer())</code> in the __init__ of your <code>Model</code> class, but only in the <code>train()</code> method do you set up the <code>tf.train.AdamOptimizer()</code>. The latter also creates some variables that need to be initialized. Move the </p>
<pre><code... | python|tensorflow|neural-network | 2 |
6,830 | 64,079,437 | Count number of times each item in list occurs in a pandas dataframe column with comma separates vales | <p>I have a list :</p>
<pre><code>citylist = ['New York', 'San Francisco', 'Los Angeles', 'Chicago', 'Miami']
</code></pre>
<p>and a pandas Dataframe df1 with these values</p>
<pre><code>first last city email
John Travis New York a@email... | <p>Try this:</p>
<p>Fix data first:</p>
<pre><code>df1['city'] = df1['city'].str.replace('Franciso', 'Francisco')
</code></pre>
<p>Use this:</p>
<pre><code>(df1['city'].str.split(', ')
.explode()
.value_counts(sort=False)
.reindex(citylist, fill_value=0))
</code></pre>
<p>Output:</p>... | pandas|dataframe|csv|grouping | 4 |
6,831 | 63,916,308 | TensorFlow JS - saving min/max values alongside model and loading back in beside prediction data | <p>I'm working on building a ML model using TensorFlow JS. New to JS and ML. I have a working model that makes decent predictions. However when I save the model and load it into a client side UI I also need the original min/max values to normalise to the same amount (I think this is right otherwise I won't be getting t... | <p>Your JSON file contains the tensor metadata, but not the data itself. In <code>downloadJ</code>, instead define <code>values</code> by</p>
<pre class="lang-js prettyprint-override"><code>let values = {
tensor: {
shape: normalisedFeature.tensor.shape,
data: normalisedFeature.tensor.dataSync()
},
min: no... | javascript|json|ajax|tensorflow|machine-learning | 1 |
6,832 | 63,251,539 | How to print a specific information from value_count()? | <pre><code>import pandas as pd
data = {'qtd': [0, 1, 4, 0, 1, 3, 1, 3, 0, 0,
3, 1, 3, 0, 1, 1, 0, 0, 1, 3,
0, 1, 0, 0, 1, 0, 1, 0, 0, 1,
0, 1, 1, 1, 1, 3, 0, 3, 0, 0,
2, 0, 0, 2, 0, 0, 2, 0, 0, 2,
... | <p>Does this solve your problem? The [0] indicates the index you wish to print, in this case the very first occurrence in your column of a data frame.</p>
<pre><code>print('The total with zero occurences is:', df['qtd'].value_counts()[0])
</code></pre>
<p>The output of the code above will be:</p>
<pre><code>The total w... | pandas | 2 |
6,833 | 63,231,519 | Pandas Add Rows Based on Existing Date Value for Past 2 Days | <p>I have a pandas data frame:</p>
<pre><code>Name Date
Bob 2020-05-17
Alice 2020-04-01
</code></pre>
<p>Below is the expected result: for each Name group, I'd like to keep the original row with 2 more rows of past 2 days' value in Date</p>
<pre><code>Name Date
Bob 2020-05-17
Bob 2020-05-16
Bo... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>pd.date_range</code></a> in a list comprehension to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>assign<... | python|pandas | 1 |
6,834 | 68,025,094 | Python 3 - I need to create a new df with ceil and floor for each system | <p>everyone.</p>
<p>So I have a data frame that cointains every failure described per system, failure event, start time and end time.
I need to round the start time to the lowest ten minute and the end time to the upper ten minute.</p>
<p>For example:</p>
<pre><code>system event start end
A... | <p>Assuming your <code>start</code> and <code>end</code> columns are already of type <code>datetime</code>, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>.dt.floor</code></a> and <a href="https://pandas.pydata.org/pandas-docs... | python|pandas|numpy|math | 1 |
6,835 | 61,501,600 | Shape mismatch with Tensorflow Dataset and Network | <p>I am getting an error relating to shapes whilst defining a very simple network using Tensorflow 2.</p>
<p>My code is:</p>
<pre><code>import tensorflow as tf
import pandas as pd
data = pd.read_csv('data.csv')
target = data.pop('result')
target = tf.keras.utils.to_categorical(target.values, num_classes=3)
data_set... | <p>Add <code>.batch()</code> at the end of the dataset:</p>
<pre><code>data_set = tf.data.Dataset.from_tensor_slices((data.values, target)).batch(8)
</code></pre> | python|tensorflow|keras | 1 |
6,836 | 68,866,712 | ValueError: y should be a 1d array, got an array of shape (1, 375) instead | <p>Im made a code which deletes curse words but it says</p>
<p>ValueError: y should be a 1d array, got an array of shape (1, 375) instead.</p>
<p>As you can see i tried to reshape it but it didn`t work. And i wrote all of the error below the code.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import... | <p>you reshaped it to (1, n) which is 2d array. It expects to receive 1d array</p> | python|pandas|sklearn-pandas | 1 |
6,837 | 68,837,151 | Replace parts of a string with values from a dataframe in python | <p>I have a variable called payload with contains different key value pairs. I need to get values from a dataframe and replace the values in the payload variable. The payload variable is used to pass data to an api call so it needs to follow a structure as shown below:</p>
<pre><code>payload = "{\"title\"... | <p>You could aggregate rows to their json representation as that seems to be what you want. Limit first to the desired columns, aggregate, and iterate on the result:</p>
<pre><code>>>> for payload in df[['title', 'id', 'body', 'author']].agg(pd.Series.to_json, axis='columns'):
... print(payload)
...
{"... | python|pandas|string|dataframe|replace | 1 |
6,838 | 68,727,260 | Find each keyword in a text file and record with file name | <p>I have downloaded ~100 stored procs as .txt files from SQL Server. From these txt files I am looking to record every iteration of a keyword beginning with "XXX". So every time the word occurs in the script, it is placed into a dataframe with the name of the file next to it.</p>
<p>For example:</p>
<blockqu... | <p>As I don't have your data, I provide a solution that generates a dataset for a directory containing some python scripts, and I am looking for words starting with <code>n</code>.</p>
<p>First we need a list of all relevant files in that directory, so we can access them one-by-one and avoid manually copying and pastin... | python|pandas|list|append|inner-join | 0 |
6,839 | 53,086,026 | pandas to_datetime couldn't parse string into dates and return strings | <p>I have a <code>Series</code> <code>s</code> as</p>
<pre><code>10241715000
201709060
11202017
112017
111617
102417
110217
1122018
</code></pre>
<p>I tried the following code to convert <code>s</code> into <code>datetime</code>;</p>
<pre><code>pd.to_datetime(s.str[:7], format='%-m%d%Y',... | <p>It should be -7 not 7 for <code>str</code> slice </p>
<pre><code>pd.to_datetime(s.astype(str).str[-7:], format='%m%d%Y', errors='coerce')
Out[189]:
0 NaT
1 NaT
2 2017-01-20
3 2017-01-01
4 NaT
5 NaT
6 NaT
7 2018-11-02
Name: a, dtype: datetime64[ns]
</code></pre>
<... | python-3.x|pandas|strftime|string-to-datetime | 2 |
6,840 | 52,965,474 | How to make cuda unavailable in pytorch | <p>i'm running some code with cudas, and I need to test the same code on CPU to compare running time. To decide between regular pytorch tensor and cuda float tensor, the library I use calls torch.cuda.is_available(). Is there an easy method to make this function return false? I tried changing the Cuda visible devices w... | <p>You can make <code>torch.cuda.is_available()</code> return False by overwriting it. Just run the following code as the first thing in your program:</p>
<pre><code>import torch
torch.cuda.is_available = lambda : False
</code></pre> | cuda|pytorch | 4 |
6,841 | 65,555,199 | Keras model.predict gives inconsistent values | <p>I have trained a basic classifier when tested on <code>model.evaluate</code> it produces the same metrics every time.</p>
<p>When using <code>model.predict</code> to check the validation data, I get different values each time the <code>model.predict</code> line is run. I can't figure out for me why this is happening... | <p>try setting shuffle = False in validation_gen and test_gen . Not sure why evaluating gives the same answer but predict does not. Maybe evaluate resets the generator and predict doesn't. What you normally want is to go through the test samples or validation samples exactly once. Let's say you have 500 samples. You c... | python|tensorflow|machine-learning|keras|deep-learning | 0 |
6,842 | 65,646,020 | What distinguishes a command from needing () vs not? | <p>I recently spent way too long debugging a piece of code, only to realize that the issue was I did not include a () after a command. What is the logic behind which commands require a () and which do not?</p>
<p>For example:</p>
<pre><code>import pandas as pd
col1=['a','b','c','d','e']
col2=[1,2,3,4,5]
df=pd.DataFra... | <p>Because <em>functions</em> need parenthesis for their arguments, while <em>variables</em> do not, that's why it's <code>list.append(<item>)</code> but it's <code>list.items</code>.</p>
<p>If you call a function without the parenthesis like <code>list.append</code> what returns is a description of the function,... | python|pandas|function|methods | 4 |
6,843 | 65,666,834 | How do you see how accurate TensorFlow an image classification model is for each class? | <p>I'm following through the image classification tutorial on the tensor flow website: <a href="https://www.tensorflow.org/tutorials/images/classification" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/classification</a></p>
<p>The model classifies flowers into one of 5 classes: daisy, dandelion... | <p>You could do that simply by using classification report in sklearn.</p>
<p>Refer <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html" rel="nofollow noreferrer">Documentation</a></p> | python|tensorflow|image-classification | 1 |
6,844 | 53,409,481 | What is the default kernel-size, Zero-padding and stride for keras.layers.Conv2D? | <p>What are the default Kernel-Size, Zero-Padding, and Stride arguments in Conv2D (keras.layers.Conv2D)? What happens if these arguments are not specified?</p> | <p>You can find the documentation here: <a href="https://keras.io/layers/convolutional/" rel="noreferrer">https://keras.io/layers/convolutional/</a></p>
<p>In python you can give default values for parameters of a function, If you don't specify these parameters while calling the function, defaults are used instead. </... | tensorflow|keras|deep-learning|conv-neural-network|zero-padding | 6 |
6,845 | 53,645,033 | How to put multiple CSV dataset to fit the model in Keras? | <p>I want to use RNN in <strong>Keras</strong> to train the model to predict the movement trajectory. </p>
<p>I have multiple CSV files. Those have the same features(columns), but have different numbers(rows). Example of one file's shape is (1078, 8) and another file is (666, 8). Each file represents one trajectory.</... | <p>You can concatenate data with numpy, for exam:</p>
<pre><code>CSV1 = np.random.uniform(0, 1, (666, 8))
CSV2 = np.random.uniform(0, 1, (1078, 8))
input_data = np.concatenate((CSV1,CSV2))
</code></pre> | numpy|keras|rnn | 0 |
6,846 | 53,608,653 | How to select all but the 3 last columns of a dataframe in Python | <p>I want to select all but the 3 last columns of my dataframe.</p>
<p>I tried :</p>
<pre><code>df.loc[:,-3]
</code></pre>
<p>But it does not work</p>
<p>Edit : title</p> | <p>Select everything <strong>EXCEPT the last 3 columns</strong>, do this using <code>iloc</code>: </p>
<pre><code>In [1639]: df
Out[1639]:
a b c d e
0 1 3 2 2 2
1 2 4 1 1 1
In [1640]: df.iloc[:,:-3]
Out[1640]:
a b
0 1 3
1 2 4
</code></pre> | python|pandas|dataframe | 38 |
6,847 | 72,078,621 | Python Dataframe process two columns of lists and find minimum | <p>I have a data frame consisting of lists as elements. I want to subtract a value from each list and find the index of the minimum. I want to find the value corresponding to each list in another column.</p>
<p>My code:</p>
<pre><code>df = pd.DataFrame({'A':[[1,2,3],[1,3,5,6]]})
df
A B
0 [1, 2, 3]... | <p>With <code>apply</code>:</p>
<pre><code>df["B_new"] = df.apply(lambda row: row["B"][np.argmin(abs(np.array(row["A"])-val))], axis=1)
>>> df
A B B_new
0 [1, 2, 3] [10, 20, 30] 20
1 [1, 3, 5, 6] [10, 30, 50, 60] 10
</code></pre> | python|pandas|dataframe|numpy|mapping | 3 |
6,848 | 55,258,712 | How to export model with my own customized functions using tensorflow-serving? | <p>I have a new requirement when using the <a href="https://github.com/tensorflow/serving" rel="nofollow noreferrer">tensorflow-serving</a> to export my model, what if I just only need to know the number on my input image rather than test this model with large test data? What should I do to achieve that or it's impossi... | <p>If I understand your question correctly, after saving the Trained Model, instead of running the Model on the Test Data, you want to use the Inference for Predicting on a Single Instance. </p>
<p>If my understanding is correct, Yes, it is possible. Please find the below code snippet for inference. </p>
<pre><code>p... | tensorflow|tensorflow-serving | 0 |
6,849 | 56,576,597 | Addressing strange plotting results using pandas and dates | <p>When plotting a time series with pandas using dates, the plot is completely wrong, as are the dates along the x-axis. For some reason the data are plotted against dates not even in the dataframe. </p>
<p>This is for plotting multiple sensors with independent clocks and different sampling frequencies. I want to plot... | <p>This issue is resolved by not using parse_dates when loading the file, but instead creating the datetime vector like this:</p>
<pre><code>import pandas as pd
from scipy.signal import savgol_filter
columns = ['Timestamp', 'Date', 'Clock', 'DC3', 'HR', 'DC4']
data = pd.read_csv('Exampledata.DAT',
se... | python|pandas|csv|plot | 1 |
6,850 | 56,696,417 | Binning data and plotting | <p>I have a dataframe of essentially random numbers, (except for one column), some of which are <code>NaN</code>s. MWE:</p>
<pre><code>import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import pandas as pd
randomNumberGenerator = np.random.RandomState(1000)
z = 5 * randomNumberGenerator.ran... | <p>For binning in pandas is used <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a>, so solution is:</p>
<pre><code>sources= pd.DataFrame({'z': z})
sources['A'] = A
sources['B'] = B
sources['C'] = C
sources['D'] = D
#sources= sources.dropn... | pandas|matplotlib|subplot|binning | 0 |
6,851 | 68,431,570 | Why do I get a different image at the same index? | <p>I have the following code portion:</p>
<pre><code>images = []
image_labels = []
for i, data in enumerate(train_loader,0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
inputs, labels = inputs.float(), labels.float()
images.append(inputs)
image_la... | <p>My best bet is that you have your <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader" rel="nofollow noreferrer"><code>DataLoader</code></a>'s <code>shuffle</code> option set to <code>True</code>, in which case it would result in different images appearing at index <em>7</em>. Every time y... | python|image|image-processing|pytorch | 1 |
6,852 | 68,388,739 | ValueError: y_true takes value in {'True', 'False'} and pos_label is not specified in ROC_curve | <pre><code>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5, random_state=2)
# generate a no skill prediction (majority class)
ns_probs = [0 for _ in range(len(y_test))]
# fit a model
model = KNeighborsClassifier(n_neighbors = 3)
model.fit(x_train, y_train)
# predict probabilities
lr_probs = m... | <pre><code>y_test = y_test.map({'True': 1, 'False': 0}).astype(int)
</code></pre>
<p>Adding this code helped me to solve my problem.</p> | machine-learning|scikit-learn|computer-vision|sklearn-pandas | 0 |
6,853 | 68,273,787 | How to .apply() a layer to the outputs of a model (transfer learning) | <p>I am trying to finetune a CNN in tensorflow.js. To do this, I would like to add a head to the final layer of the pretrained model. The equivalent code in python tensorflow is as follows, where we add an average pooling layer to the pretrained efficientnet.</p>
<pre class="lang-py prettyprint-override"><code>import t... | <p>Well, turns out, with a minimal example, it works. Simply inputting <code>model.outputs</code> into <code>layer.apply()</code> works.</p>
<pre class="lang-js prettyprint-override"><code>const tf = require(@tensorflow/tfjs)
const getModel = async function () {
const baseModel = await tf.sequential();
baseMod... | javascript|tensorflow.js|tfjs-node | 0 |
6,854 | 68,305,980 | Running out of memory when using Dask arrays | <p>I need to perform some computations on a tensor larger than memory, but first I need to construct it from <code>NumPy</code> arrays (parts) that fit in memory.</p>
<p>I'm computing these <code>NumPy</code> arrays, then converting them to <code>Dask</code> arrays, and putting them on a <code>list</code>. My final ten... | <p>There is no way for dask to "reduce" the size of an array you present to it already in memory. No chunking will help you. <strong>If</strong> your data fit into memory, maybe you wouldn't need Dask at all.</p>
<p>Instead, you need to load/create data as required in each chunk. For your simple example, you ... | python|arrays|numpy|dask | 0 |
6,855 | 59,402,902 | How to sort Panda table according to another Panda table | <p>The following question appeared during my last round of my interview and unfortunately i couldn't do it.
I have the first table as: </p>
<pre><code>ticker AAPL MSFT WMT
date
2015-12-31 101.696810 52.829107 58.379766
2016-01-04 101.783763 52.181598... | <p>Your original dataframe and the volatility dataframe have different indexes, but you say you want to sort original <code>df</code> by the position of volatility table. Therefore, it only makes sense that you want the result in the format of the underlying numpy ndarrays of these 2 dataframes. Assume original datafra... | python-3.x|pandas | 1 |
6,856 | 56,916,504 | Adanet running out of memory | <p>I tried training an AutoEnsembleEstimator with two DNNEstimators (with hidden units of 1000,500, 100) on a dataset with around 1850 features (after feature engineering), and I kept running out of memory (even on larger 400G+ high-mem gcp vms). </p>
<p>I'm using the above for binary classification. Initially I had t... | <p>Three hypotheses:</p>
<ol>
<li><p>You might have too many DNNs in your ensemble, which can happen if <code>max_iteration_steps</code> is too small and <code>max_iterations</code> is not set (both of those are constructor arguments to <code>AutoEnsembleEstimator</code>). If you want to train each DNN for <code>N</co... | python|tensorflow|tensorflow-estimator|adanet | 1 |
6,857 | 57,008,278 | Cannot create a virtual raster from a stack array in rasterio | <p>I Need to know how to create a virtual raster. I iterated over a folder, which contains some binary rasters (1, 0). Those rasters I append it into a numpy array using numpy.concatenate. Then I would like to create a virtual raster using the number of raster concatenated as the number of bands that this raster will h... | <p>VRT is a read-only format, you can not write arrays to VRT. To create a VRT file you only reference the existing, on-disk raster files. E.g. using gdal.BuildVRT in Python with your list of raster files as in <a href="https://gis.stackexchange.com/questions/268419/trying-to-run-gdalbuildvrt-in-command-line">example 3... | python|numpy|rasterio | 1 |
6,858 | 56,936,189 | Reparametrization in tensorflow-probability: tf.GradientTape() doesn't calculate the gradient with respect to a distribution's mean | <p>In <code>tensorflow</code> version <code>2.0.0-beta1</code>, I am trying to implement a <code>keras</code> layer which has weights sampled from a normal random distribution. I would like to have the mean of the distribution as trainable parameter.</p>
<p>Thanks to the "reparametrization trick" already implemented i... | <p>It seems that <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/MultivariateNormalDiag" rel="nofollow noreferrer">tfp.distributions.MultivariateNormalDiag</a> is not differentiable with respect to its input parameters (e.g. <code>loc</code>). In this particular case, the following wou... | python|tensorflow|keras|tensorflow-probability | 1 |
6,859 | 46,097,150 | How to Elaborate Rows in Pandas | <p>I would like to transform the below pandas dataframe:</p>
<pre><code>dd = pd.DataFrame({ "zz":[1,3], "y": ["a","b"], "x": [[1,2],[1]]})
x y z
0 [1, 2] a 1
1 [1] b 3
</code></pre>
<p>into :</p>
<pre><code> x y z
0 1 a 1
1 1 b 3
2 2 a 1
... | <p>Use:</p>
<pre><code>#get lengths of lists
l = dd['x'].str.len()
df = dd.loc[dd.index.repeat(l)].assign(x=np.concatenate(dd['x'])).reset_index(drop=True)
print (df)
x y zz
0 1 a 1
1 2 a 1
2 1 b 3
</code></pre>
<p>But if order is important:</p>
<pre><code>df1 = pd.DataFrame(dd['x'].values.tolist()... | python|pandas|functional-programming | 2 |
6,860 | 50,914,641 | How to reduce the time to write pandas dataframes as table in Amazon Redshift | <p>I am writing python pandas data frame in Amazon Redshift using this -</p>
<pre><code>df.to_sql('table_name', redshiftEngine, index = False, if_exists = 'replace' )
</code></pre>
<p>Although my dataframes have couple of thousand rows and 50-100 columns only, its taking 15-20 minutes to write one table. I wonder if ... | <p>A better approach is use <code>pandas</code> to store your dataframe as a CSV, upload it to S3 and use the <code>COPY</code> functionality to load into Redshift. This approach can easily handle even hundreds of millions of rows. In general, Redshift write performance is not great - it's meant for processing data loa... | python|python-3.x|pandas|dataframe|amazon-redshift | 2 |
6,861 | 50,704,358 | Pandas Replace is giving me a strange error | <p>Pandas is giving a weird output when using a dictionary to replace values within a dataframe: </p>
<pre><code>import pandas as pd
df = pd.read_csv('data.csv')
print(df)
Course
English 21st Century
Maths in the Golden Age of History
Science is cool
Mapped_Items = ['Math', 'English', 'Science', 'History']
pat = '... | <p>Your logic seems overcomplicated. You don't need regex, and <code>pd.Series.replace</code> is inefficient with a dictionary, even if it could work on a series of lists. Here's an alternative method:</p>
<pre><code>import pandas as pd
from io import StringIO
mystr = StringIO("""Course
English 21st Century
Maths in ... | python|pandas|dataframe | 3 |
6,862 | 66,736,995 | How to prepare imagenet dataset to run resnet50 (from official Tensorflow Model Garden) training | <p>I'd like to train a resnet50 model on imagenet2012 dataset on my local GPU server, following exactly this Tensorflow official page: <a href="https://github.com/tensorflow/models/tree/master/official/vision/image_classification#imagenet-preparation" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/... | <p>Were you able to get the output of for:</p>
<pre><code>python imagenet_to_gcs.py \
--raw_data_dir=$IMAGENET_HOME \
--local_scratch_dir=$IMAGENET_HOME/tf_records \
--nogcs_upload
</code></pre>
<p>in the following format?</p>
<pre><code>${DATA_DIR}/train-00000-of-01024
${DATA_DIR}/train-00001-of-01024
...
${DAT... | tensorflow|imagenet|tensorflow-model-garden | 3 |
6,863 | 57,533,942 | What exactly is compute_gradients returning and how does it depend on batch_size? | <p>Please excuse my rookie understanding of TensorFlow, Thanks in advance for the help!</p>
<p>I am trying to compute the gradients using <code>compute_gradients()</code> wrt the embedding inputs of my loaded model.</p>
<p>My batch_size is 250 and embd_size is 300.</p>
<p>I want to compute the gradients of all my in... | <p>I found out that the dimensions that gradients returns from <code>compute_gradients()</code> is correct according to my <code>x_train</code> dimensions, which is <code>(250,200,300)</code> not <code>(250,300)</code> that I thought earlier. The computed <code>IndexedSlices</code> object has a <code>values</code> prop... | tensorflow | 0 |
6,864 | 57,685,809 | Multiple conditions - Selecting rows in pandas dataframe | <p>i have x and y coordinates as:</p>
<pre><code>x = (16764.83, 16752.74, 16743.1)
y = (107347.67, 107360.32, 107362.96)
</code></pre>
<p>its basically like three points <code>(x1, y1), (x2, y2) and (x3, y3)</code></p>
<p>in the dataframe:</p>
<pre><code>print (bf)
XMORIG YMORIG ZMORIG XC YC... | <p>You can zip bot list and filter in list comprehension for list of <code>DataFrame</code>s and then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> together, also change absolute values for Series with difference of <code>i</code... | python|python-3.x|pandas|dataframe | 2 |
6,865 | 51,883,275 | Removing Multilevel Index | <p>So essentially I am trying to concatenate two data frames in a Jupyter notebook and to do this I am first setting the index for each data frame to be the date. When I do this it looks like I get a multilevel index with the "3_mo" category in an extra dimension. Do I have to change this somehow?</p>
<p>Once... | <p>You can use <code>df.reset_index(inplace=True)</code> to make the change in the existing dataframe itself.</p> | python|pandas|dataframe|indexing | 0 |
6,866 | 51,696,441 | Labels (annotate) in pandas area plot | <p>Is it possible to put data labels (values) in pandas/matplotlib stacked area charts? </p>
<p>In stacked bar plots, I use the below</p>
<pre><code>for label in yrplot.patches:
yrplot.annotate(label.get_height(), (label.get_x()+label.get_width()/2.,label.get_y()+label.get_height()/2.),
ha='cente... | <p>The annotations can be manually added to the stacked area chart, using the cumulative sum of the values to compute the y positions of the labels. Also, I suggest not to draw the annotation if the height of the stack is very small.</p>
<pre><code>rs = np.random.RandomState(12)
values = np.abs(rs.randn(12, 4).cumsum(... | python|pandas|matplotlib | 3 |
6,867 | 37,600,029 | Pandas duplicated indexes still shows correct elements | <p>I have a pandas <code>DataFrame</code> like this:</p>
<pre><code>test = pd.DataFrame({'score1' : pandas.Series(['a', 'b', 'c', 'd', 'e']), 'score2' : pandas.Series(['b', 'a', 'k', 'n', 'c'])})
</code></pre>
<p>Output:</p>
<pre><code> score1 score2
0 a b
1 b a
2 c k
3 d n
4 e ... | <p>This is into the internals (i.e., don't rely on this API!) but the way it works now is that there is a <code>Grouping</code> object which stores the groups in terms of positions, rather than index labels.</p>
<pre><code>In [25]: gb = test.groupby('score1')
In [26]: gb.grouper
Out[26]: <pandas.core.groupby.BaseG... | python|pandas | 0 |
6,868 | 41,983,874 | Interval intersection in pandas | <h3>Update 5:</h3>
<p>This feature has been released as part of pandas 20.1 (on my birthday :] )</p>
<h3>Update 4:</h3>
<p>PR has been merged!</p>
<h3>Update 3:</h3>
<p><a href="https://github.com/pandas-dev/pandas/pull/15309" rel="nofollow noreferrer">The PR has moved here</a></p>
<h3>Update 2:</h3>
<p>It seems... | <p>This feature is was released as part of pandas 20.1</p> | python|pandas|interval-tree | 3 |
6,869 | 37,998,243 | Perform full Merge between the columns of two data frames, based on starting alphabet | <p>I want to perform full merge between the values of two columns (Name) of two different data frames. Merge should only be done between Names starting with same alphabet. For eg. ABC should be merged with all Names of other data frame which start with letter 'A'. And this should be done for all letters 'A' to 'Z'. I a... | <p>I'd create a column of 'FirstLetter' and <code>[merge][1]</code> on that.</p>
<pre><code>import pandas as pd
import numpy as np
from string import ascii_uppercase
df1 = pd.DataFrame(np.random.choice(list(ascii_uppercase), (5, 3)))
df1 = df1.apply(lambda x: pd.Series([''.join(x)], index=['Name']), axis=1)
df1['Firs... | python|pandas | 0 |
6,870 | 37,790,839 | Reducing dimensions for supervised learning | <p>I have this type of numpy array. Here i have shown 2 elements of the array. I have converted a .jpeg file to numpy array.</p>
<pre><code>[[[130 130 130 ..., 255 255 255]
[255 255 255 ..., 255 255 255]
[255 255 255 ..., 255 255 255]
...,
[255 255 255 ..., 255 255 255]
[255 255 255 ..., 255 255 255]
[ 68... | <p>The problem with your code is simple, you are not sending the list in the required format.... The format which <code>.fit</code> requires is a 2 dimensional array. What you are sending is a 3 dimensional... There was no need of using dimensionality reduction because its totally a different issue...(for preventing ov... | python|numpy|scikit-learn|scikit-image | 1 |
6,871 | 37,879,104 | How does numpy polyfit work? | <p>I've created the "Precipitation Analysis" example Jupyter Notebook in the Bluemix Spark service.</p>
<p>Notebook Link: <a href="https://console.ng.bluemix.net/data/notebooks/3ffc43e2-d639-4895-91a7-8f1599369a86/view?access_token=effff68dbeb5f9fc0d2df20cb51bffa266748f2d177b730d5d096cb54b35e5f0" rel="nofollow">https:... | <p>The question has been answered on Developerworks:-
<a href="https://developer.ibm.com/answers/questions/282350/how-does-numpy-polyfit-work.html" rel="nofollow">https://developer.ibm.com/answers/questions/282350/how-does-numpy-polyfit-work.html</a></p>
<p>I will try to explain each of this:-</p>
<p>index = chile[ch... | numpy|apache-spark|ibm-cloud|linear-regression | 0 |
6,872 | 37,820,918 | Use more than one thread when calling intel's mkl directly from python | <p>I call intel's math kernel library from python. So far, it is using just one cpu, instead of all 12 cpu, according to linux's top command. How to make it use all 12 cpu?</p>
<p>I have tried setting three environmental variables (OMP_NUM_THREADS, MKL_NUM_THREADS, MKL_DOMAIN_NUM_THREADS) to 12.</p>
<p>I have also tr... | <p>It seems some of the python distributions (e.g., <a href="https://www.continuum.io/why-anaconda" rel="nofollow">anaconda</a>) will respond to the environmental variables, while others (CentOS 7 default) not. Never dig into it further.</p> | python|numpy|scipy|intel|intel-mkl | 1 |
6,873 | 37,663,064 | cudnn compile configuration in TensorFlow | <p>Ubuntu 14.04, CUDA Version 7.5.18, nightly build of tensorflow</p>
<p>While running a <code>tf.nn.max_pool()</code> operation in tensorflow, I got the following error:</p>
<blockquote>
<p>E tensorflow/stream_executor/cuda/cuda_dnn.cc:286] Loaded cudnn
library: 5005 but source was compiled against 4007. If usi... | <p>Go in the directory of TensorFlow source code, then execute the configuration file: <code>/.configure</code>.</p>
<p>Here is an example from the <a href="https://www.tensorflow.org/versions/master/get_started/os_setup.html#installation-for-linux" rel="nofollow">TensorFlow documentation</a>:</p>
<pre><code>$ ./conf... | tensorflow|cudnn | 2 |
6,874 | 37,743,574 | Hard limiting / threshold activation function in TensorFlow | <p>I'm trying to implement a basic, binary <a href="http://www.scholarpedia.org/article/Hopfield_network" rel="noreferrer">Hopfield Network</a> in TensorFlow 0.9. Unfortunately I'm having a very hard time getting the activation function working. I'm looking to get the very simple <code>If net[i] < 0, output[i] = 0, ... | <p>a bit late, but if anyone needs it, I used this definition </p>
<pre><code>def binary_activation(x):
cond = tf.less(x, tf.zeros(tf.shape(x)))
out = tf.where(cond, tf.zeros(tf.shape(x)), tf.ones(tf.shape(x)))
return out
</code></pre>
<p>with x being a tensor</p> | python|python-3.x|tensorflow | 14 |
6,875 | 64,423,428 | Merging two data frames in a loop but TypeError: unhashable type: 'list' after first loop | <p>I am trying to merge a two data frames that has where one df_1 has dataset information and df_2 is in a loop that has the nlp text in a list.</p>
<pre><code>df_1 = pd.DataFrame({'text':['A','B','C'],'other_info':['12','24','34'],'nlp_text':[[('together', 'RB'),('subsidiary', 'NN')],np.NaN,np.NaN]}.reset_index()
df_... | <p>you still have some problems in df_1.</p>
<ol>
<li>a dictionary has no attribute reset_index</li>
<li>did you see <code>C'</code>? in <code>'text':['A','B',C']</code></li>
</ol>
<p><a href="https://i.stack.imgur.com/Hut3z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hut3z.png" alt="output" /></... | python|pandas|nlp | 0 |
6,876 | 47,929,811 | Jupyter uses wrong version of numpy | <p>I am trying to import <code>pandas</code> in a Jupyter notebook and having trouble because it's using an old version of <code>numpy</code>. I believe I've traced the issue to the fact that I have two versions installed:</p>
<p><strong>Version 1.8.0rcl</strong> is in:
<code>/System/Library/Frameworks/Python.framewor... | <p>Please read <a href="https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/" rel="nofollow noreferrer">this long post</a> from Jake Van der Plas describing how importing works and why you think Jupyter is using the wrong numpy.</p>
<p>Once you get how things works, you should be able to ... | python|pandas|numpy|jupyter|sys.path | 1 |
6,877 | 47,588,720 | Faster way to associate two pandas DataFrames? | <p>I have two pandas Dataframes:</p>
<blockquote>
<p>automate</p>
</blockquote>
<pre><code>index id user_id merchant_id marketing_email_id start_date end_date email_status created_at
0 133198 133199 10939 88 681 2016-06-29 2016-07-06 1 2016-06-29 11:26:46
1 578787 578788 226281 745 1636 ... | <p>Hmm, yeah thats a hard one. The only recommendation I have is maybe sorting both dataframes by the date/time, then ...well here is some pseudo code:</p>
<pre><code>dfautomate2 = dfautomate.sortby(start_date)
dfvisit = dfvisit.sortby(created_at)
listofawesome = []
for visit in dfvisit:
for event_range in dfautom... | python|pandas|numpy | 0 |
6,878 | 47,846,236 | How to use crop huge batch of images in tensorflow | <p>I am trying to use below function to crop large number of images 100,000s. I am doing this operation serially, but its taking lot of time. What is the efficient way to do this?</p>
<pre><code> tf.image.crop_to_bounding_box
</code></pre>
<p>Below is my code:</p>
<pre><code> def crop_images(img_dir, list_image... | <p>I'll give a simplified version of one of the examples from Tensorflow's Programmer's guide on reading data which can be found <a href="https://www.tensorflow.org/versions/r1.0/programmers_guide/reading_data#batching" rel="nofollow noreferrer">here</a>. Basically, it uses Reader and Filename Queues to batch together ... | python|image-processing|tensorflow | 1 |
6,879 | 58,747,301 | Calculate average and mean based on two column data in pandas | <p>I have a dataframe looks like this:</p>
<pre><code>df
Speed Zone
1.33 Zone 1
0.37 Zone 1
0.52 Zone 1
1.17 Zone 1
8.36 Zone 2
4.46 Zone 2
2.16 Zone 2
4.45 Zone 2
5.50 Zone 3
5.29 Zone 3
3.49 Zone 3
1.11 Zone 3
0.89 Zone 4
2.16 Zone 5
0.83 Zone 5
1.17 Zone 5
</code></... | <p>Did you try:</p>
<pre><code>df.groupby("Zone").agg("mean")
</code></pre>
<p>You might also want to look at the <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer">documentation of agg</a>.
You can specify different aggregati... | python|pandas | 1 |
6,880 | 70,310,632 | Counting the occurrence of words in a dataframe column using a list of strings | <p>I have a list of strings and a dataframe with a text column. In the text column, I have lines of text. I want to count how many times each word in the list of strings occurs in the text column. I am aiming to add two columns to the dataframe; one column with the word and the other column having the number of occurre... | <p>Function to find the number of matches for a given pattern:</p>
<pre><code>def find_match_count(word: str, pattern: str) -> int:
return len(re.findall(pattern, word.lower()))
</code></pre>
<p>Then loop through each of the strings, and apply this function to the <code>'word'</code> column:</p>
<pre><code>for c... | python|pandas|dataframe|text | 2 |
6,881 | 56,348,572 | I keep getting UnicodeErrors opening a CSV file although adding utf-8 encoding | <p>I know the questions sounds generic but here is my problem.
I have a csv file that will always cause UnicodeErrors and errors like csv.empty although I am opening the file with utf-8
like this</p>
<pre class="lang-py prettyprint-override"><code> with open(csv_filename, 'r', encoding='utf-8') as csvfile:
</code><... | <p>Pandas will load the contents of the csv file into a dataframe</p>
<p>The csv module has methods like reader and DictReader that will return generators that let you move through the file.</p>
<p>With Pandas:</p>
<pre><code>import pandas as pd
df=pd.read_csv('file.csv')
df.to_csv('new_file.csv',index=False)
</cod... | python|pandas|csv | 0 |
6,882 | 55,886,262 | How to merge/concatenate two dataframe whose two columns with partially string matched? | <p>I used Chicago crime data for my analysis, but there is no community name given, so I collected community name in chicago from online source. However, Redfin real estate data collected by Region/ neighborhood instead of community name. when I tried to merge prepossessed Chicago crime data with Redfin real estate dat... | <p>A quick look at the two datasets, it appears that <code>Chicago.Region</code> is of form <code>Chicago, IL - region_name</code> while <code>Redfin.community_name</code> is <code>region_name</code>. So I tried:</p>
<pre><code>areas = ['Chicago, IL - ' + s for s in redfin.community_name.unique()]
# check if areas i... | python|pandas | 2 |
6,883 | 64,626,936 | Python pandas drop_duplicates() inaccuracy | <p>I am working on a project that consists of compiling some .tsv files and I am attempting to clean up one of the files and this is what I have so far.</p>
<p>The data file is far too large to paste the output into here so here are a couple photos explaining my current issue.</p>
<p><a href="https://i.stack.imgur.com/... | <p>If you want to keep one record of each duplicate (instead of all duplicates) you should not use <code>keep=False</code>. Citing the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer">documentation for drop_duplicates</a></p>
<blockquot... | python|pandas | 1 |
6,884 | 64,728,739 | Can I create column where each row is a running list in a Pandas data frame using groupby? | <p>Imagine I have a Pandas DataFrame:</p>
<pre><code># create df
df = pd.DataFrame({'id': [1,1,1,2,2,2],
'val': [5,4,6,3,2,3]})
</code></pre>
<p>Lets assume it is ordered by 'id' and an imaginary, not shown, date column (ascending).
I want to create another column where each row is a list of 'val' at... | <p>Let us try</p>
<pre><code>df['new'] = df.val.map(lambda x : [x]).groupby(df.id).apply(lambda x : x.cumsum())
Out[138]:
0 [5]
1 [5, 4]
2 [5, 4, 6]
3 [3]
4 [3, 2]
5 [3, 2, 3]
Name: val, dtype: object
</code></pre> | python|pandas|list|data-science|aggregation | 8 |
6,885 | 64,730,471 | I want to change the specific prediction of my CNN-model to a probability | <p>I trained a model to categorize pictures in two different types. Everything is working
quite good, but my Model can only do a specific prediction (1 or 0 in my case), but I am interested to have a prediction which is more like a probability (For example 90% 1 and 10% 0).
Where is the part of my code which I should c... | <p>short answer :
change <strong>sigmoid</strong> activation function in the last layer to <strong>softmax</strong></p>
<p>why ?</p>
<p>because sigmoid output range is 0.0 to 1.0, so to make a meaningful interpretation of this output, you choose an appropriate threshold above which represents the positive class and any... | python|tensorflow|keras|deep-learning|neural-network | 2 |
6,886 | 39,742,275 | Efficiently collect links in dataframe | <p>Say I have a dataframe of type</p>
<pre><code>individual, location, food
1 A a
1 A b
1 B a
1 A c
2 C a
2 C b
</code></pre>
<p>where individuals are creating links between location an... | <p>You can pick up some efficiency by using numpy's <code>meshgrid</code>. </p>
<pre><code>import itertools
import numpy as np
def foo(group):
list1 = group.location.unique()
list2 = group.food.unique()
return pd.DataFrame(data=list(itertools.product(list1, list2)), columns=['location', 'food'])
def bar(g... | python|pandas | 2 |
6,887 | 39,720,332 | Pandas `read_json` function converts strings to DateTime objects even the `convert_dates=False` attr is specified | <p>I have the next JSON:</p>
<pre><code>[{
"2016-08": 1355,
"2016-09": 2799,
"2016-10": 2432,
"2016-11": 0
}, {
"2016-08": 1475,
"2016-09": 1968,
"2016-10": 1375,
"2016-11": 0
}, {
"2016-08": 3097,
"2016-09": 1244,
"2016-10": 2339,
"2016-11": 0
}, {
"2016-08": 1305,
"2016-09": 1625,
"2016-10": 3038,
"2016-11": 0
}, {
... | <p>You need parameter <code>convert_axes=False</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html" rel="nofollow"><code>read_json</code></a>:</p>
<pre><code>df = pd.read_json('file.json', convert_axes=False)
print (df)
2016-08 2016-09 2016-10 2016-11
0 1355 279... | python|json|python-3.x|pandas|jupyter-notebook | 3 |
6,888 | 39,857,428 | Pandas - Selecting multiple dataframe criteria | <p>I have a DataFrame with multiple columns and I need to set the criteria to access specific values from two different columns. I'm able to do it successfully on one column as shown here:</p>
<pre><code>status_filter = df[df['STATUS'] == 'Complete']
</code></pre>
<p>But I'm struggling to specify values from two colu... | <p>Your code has two very small errors: 1) need parentheses for two or more criteria and 2) you need to use the ampersand between your criteria:</p>
<pre><code>status_filter = df[(df['STATUS'] == 'Complete') & (df['READY TO INVOICE'] == 'No')]
</code></pre> | python|pandas|dataframe | 4 |
6,889 | 44,086,217 | Overriding keras predict function | <p>I have Keras model that accepts inputs which have 4D shapes as (n, height, width, channel).</p>
<p>However, my data generator is producing 2D arrays as(n, width*height). So, the predict function of Keras is expecting inputs as 4D. I have no chance to change the data generator because the model will be tested by som... | <p>You don't override the predict, you simply add a <code>Reshape</code> layer at the beginning of your model.</p>
<p>With the functional API:</p>
<pre><code>from keras.layers import *
inp = Input((width*heigth,))
first = Reshape((width,height,1))(inp)
..... other layers.....
model = Model(inp, outputFromTheLastLaye... | python|numpy|keras | 1 |
6,890 | 69,494,548 | check if either of two substrings exist in a string | <p>I am using the following code to replace all <code>-</code> and remove all <code>,</code> from my dataframe columns</p>
<pre><code>df[['sale_price','mrp', 'discount', 'ratings', 'stars']]=df[['sale_price','mrp', 'discount', 'ratings', 'stars']].applymap(lambda r: np.nan if '-' in str(r) else str(r).replace(',', ''))... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> with <code>regex=True</code> by substrings defined in dictionary:</p>
<pre><code>df = pd.DataFrame([['10,4','-','nan',5,'kkk-oo']],
colu... | python|pandas|string | 1 |
6,891 | 69,453,679 | Calculating the angle between two vectors using a needle-like triangle | <p>I implemented a function (<code>angle_between</code>) to calculate the angle between two vectors. It makes use of needle-like triangles and is based on <a href="https://people.eecs.berkeley.edu/%7Ewkahan/Triangle.pdf" rel="nofollow noreferrer">Miscalculating Area and Angles of a Needle-like Triangle</a> and <a href=... | <blockquote>
<p>I just tried the case of setting vectorB as a multiple of vectorA and - interestingly - it sometimes produces nan, sometimes 0 and sometimes it fails and produces a small angle of magnitude 1e-8 ... any ideas why?</p>
</blockquote>
<p>Yea and I think that's what your question boils down to. Here is the ... | python|numpy|geometry|numeric|floating-accuracy | 2 |
6,892 | 40,861,341 | Extracting sentences using pandas with specific words | <p>I have a excel file with a text column. All I need to do is to extract the sentences from the text column for each row with specific words.</p>
<p>I have tried using defining a function. </p>
<pre><code>import pandas as pd
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
###########... | <p>Here's how:</p>
<pre><code>In [1]: df['text'].apply(lambda text: [sent for sent in sent_tokenize(text)
if any(True for w in word_tokenize(sent)
if w.lower() in searched_words)])
0 [Snakes are venomous., Anaconda is venomous.]... | python|pandas|nltk | 3 |
6,893 | 54,219,055 | How to remove rows from Pandas dataframe if the same row exists in another dataframe but end up with all columns from both df | <p>I have two different Pandas data-frames that have one column in common. I have seen similar questions on Stack overflow but none that seem to end up with the columns from both dataframes so please read below before marking as duplicate.</p>
<p>Example:</p>
<p>dataframe 1</p>
<pre><code>ID col1 col2 ...
1 9 ... | <p>Looks like a simple <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="noreferrer"><code>drop</code></a> will work for what you want:</p>
<pre><code>df1.drop(df2.index, errors='ignore', axis=0)
col1 col2
ID
1 9 5
2 8 4
</code></pre>
... | python|pandas | 9 |
6,894 | 54,166,293 | How to replace this SQL query with date ranges by something more Pythonic | <p>I have two pandas data frames:</p>
<pre><code># DataFrame A
ID Date equity
1078604 2000-03-31 145454
1078604 2000-06-30 138536
1078604 2000-09-30 143310
</code></pre>
<p>The frame above contains >200,000 rows of firms with their IDs and their equity values at quarter end.</p>
<pre><code># DataFram... | <p>If I understand Correctly:</p>
<p>Lets assume the first dataframe(creating a working example by changing the values in ID and the dates a little):</p>
<pre><code>>>df
ID Date equity
0 1139710 2000-03-31 145454
1 1139710 2000-06-30 138536
2 1022764 2000-09-30 143310
</code></pre>
<p... | python|sql|pandas | 0 |
6,895 | 38,328,213 | Counting Unique Values of Categories of Column Given Condition on other Column | <p>I have a data frame where the rows represent a transaction done by a certain user. Note that more than one row can have the same user_id. Given the column names <strong>gender</strong> and <strong>user_id</strong> running:</p>
<pre><code>df.gender.value_counts()
</code></pre>
<p>returns the frequencies but they ar... | <p>You want to use panda's <code>groupby</code> on your dataframe:</p>
<pre><code>users = {'A': 'male', 'B': 'female', 'C': 'female'}
ul = [{'id': k, 'gender': users[k]} for _ in range(50) for k in random.choice(users.keys())]
df = pd.DataFrame(ul)
print(df.groupby('gender')['id'].nunique())
</code></pre>
<p>This yi... | python|pandas | 4 |
6,896 | 66,050,671 | Remove a specific value from each row of a column | <p>Im trying to remove the .0 present at the end of each number in the column M1 bis.</p>
<pre><code>us_m1.head()
DATE M1 M1bis
0 1975-01-06 273.4 273400.0
1 1975-01-13 273.7 273700.0
2 1975-01-20 273.8 273800.0
3 1975-01-27 273.7 273700.0
4 1975-02-03 275.2 275200.0
</code></p... | <p><code>us_m1['M1bis'] = us_m1['M1bis'].astype(int)</code> will change each to int and remove the value.</p> | pandas|dataframe | 1 |
6,897 | 66,120,086 | calculate difference in value between rows across group in python | <p>I have a data frame like this</p>
<pre><code> time text
0 1
1 2 r
2 4 e
3 6 d
4 7
5 8 b
6 9 a
7 12 g
8 15
import pandas as pd
import numpy as np
sample = pd.DataFrame({'time':[1,2,4,6,7,8,9,12,15],'text':[' ','r','e','d',' ','b','a','g','']})
</code></pre>
<p>And I want t... | <ul>
<li>create a column used for grouping rows - breaks every time a space is in <em>text</em> column</li>
<li><code>groupby()</code> the above derived column</li>
<li>use a <code>lambda</code> function to generate the text you want</li>
</ul>
<p>This does not match your result as you have used row 4 in boy <strong>re... | python|pandas | 2 |
6,898 | 65,915,301 | How to calculate the distance between two points on lines in python | <p>I have two lines. namely <code>(x1,y1)</code> and <code>(x2,y2)</code>. I need to calculate the distance between the points. see my code snippets below</p>
<pre><code>import numpy as np
import plotly.express as px
import plotly.graph_objects as go
x1= np.array([525468.80914272, 525468.70536016])
y1= np.array([17551... | <p>You can solve this with <code>math</code> library</p>
<pre><code>import math
distancePointA = math.sqrt(((x1[0] - x2[0]) ** 2) + ((y1[0] - y2[0]) ** 2))
distancePointB = math.sqrt(((x1[1] - x2[1]) ** 2) + ((y1[1] - y2[1]) ** 2))
</code></pre> | python|python-3.x|dataframe|numpy|math | 3 |
6,899 | 46,623,897 | How to, for all the null values (NaN) in column, get the respective values which exist in a different dataframe? | <p>I have a dataframe with NaN values which i need to assign. The way i need to assign these values depend on the column 'code'. The NaN values exist in a different dataframe and the same column 'code'.</p>
<p>My initial dataframe with NaN values but not in all rows (third row has values for column 'capital' and 'coun... | <p>IIUC</p>
<p>Option 1</p>
<pre><code>df1.columns=df2.columns
pd.concat([df1,df2],axis=0).dropna(axis=0)
</code></pre>
<p>Option 2 </p>
<pre><code>df1.set_index('code').captial.fillna(df2.set_index('col2').captial)
Out[184]:
code
0 B
1 C
2 A
3 D
4 E
Name: captial, dtype: object
</code></pre>
<p>Da... | python|pandas|dataframe|mapping|vlookup | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.