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 |
|---|---|---|---|---|---|---|
374,100 | 66,680,661 | Find the movies that have more than one genre in movielens project - Pandas | <p>Hi I need to find the movies that have more than one genre in movielens project where the genre is not a single column instead of its multiple columns like genre1, genre 2, etc and I tried using the item.sum(axis=1) but it didn't fetch me the required result.</p>
<p>I also tried the following code based on a solutio... | <p>Asuming you use the MovieLens 100k data set (obtained from <a href="https://grouplens.org/datasets/movielens/" rel="nofollow noreferrer">https://grouplens.org/datasets/movielens/</a>).</p>
<p>It comes with a file called 'u.genre' which contains movie information including one hot encoded genres.</p>
<p>Load the data... | pandas | 1 |
374,101 | 66,680,557 | Matplotlib & Pandas DateTime Compatibility | <p><strong>Problem</strong>: I am trying to make a very simple bar chart in Matplotlib of a Pandas DataFrame. The DateTime index is causing confusion, however: Matplotlib does not appear to understand the Pandas DateTime, and is labeling the years incorrectly. How can I fix this?</p>
<p><strong>Code</strong></p>
<pre><... | <p>The problem is with mixing <code>df.plot.bar</code> and <code>matplotlib</code> here.</p>
<p><code>df.plot.bar</code> sets tick locations starting from 0 (and assigns labels), while <code>matplotlib.dates</code> expects the locations to be the number of days since 1970-01-01 (more info <a href="https://matplotlib.or... | python|pandas|datetime|matplotlib | 1 |
374,102 | 66,702,153 | ModuleNotFoundError: No module named 'pandas' when working with Tensorflow | <p>i am trying to make a face mask recognition here, whenever i try to create my TF record an import problem pops up, i have tried to install pandas with condas and with pip3 the problem is that when i just import pandas it runs without problem but when i start the generate_tfrecord.py this problem shows up,
here is my... | <p>Try running <code>pip install pandas</code> in your CMD it might solve your problem.</p> | python|tensorflow|anaconda | 1 |
374,103 | 66,695,391 | Execution of Inference Workloads on Coral Dev Board in CPU, GPU and TPU simultaneously | <p>I am currently working on executing inference workloads on Coral Dev Board with TensorFlow Lite. I am trying to run inference on CPU,GPU and TPU simultaneously to reduce inference latency.</p>
<p>Could you guys help me understand how I can execute inference on all the devices simultaneously? I could divide the layer... | <p>As of now, if you compile your CPU TFLite model with the edgeTPU compiler (<a href="https://coral.ai/docs/edgetpu/compiler/" rel="nofollow noreferrer">https://coral.ai/docs/edgetpu/compiler/</a>) then the compiler tries to Map the operations on the TPU only (as long as the operations are supported by the TPU)</p>
<p... | tensorflow|keras|google-coral | 0 |
374,104 | 66,429,900 | Numpy random number generators and lambda functions | <p>I'm trying to create a list of random variables <code>wtfuns</code> that I can call as: <code>wtfuns[i](size=1000)</code> to return a list of 1000 samples of the particular random variable. For this, I am using lambda functions as follows:</p>
<pre><code>wtfuns = []
pvals = [0.3,0.5,0.7]
for p in pvals:
wtfuns.a... | <p>Yes, your first definition captures a reference to <code>p</code>. As <code>p</code> changes, the function changes. The solution is to use a trick that turns the lambda into a closure:</p>
<pre><code> wtfuns.append(('bernoulli p='+str(p),lambda p=p,**x: binom(p,**x)))
</code></pre>
<p>The "p=p" thing ... | python|numpy|random | 1 |
374,105 | 66,402,926 | How to create empty column with a specific number in dataframe python? | <p>I am new to python and I want to know how to create empty column with a specific number. Let's say I want to create 20 columns. What I tried:</p>
<pre><code>import pandas as pd
num =20
for i in range(num):
df = df + pd.DataFrame(columns=['col'+str(i)])
</code></pre>
<p>But I got the unwanted result:</p>
<pre><... | <p>Assuming you wish to create an empty dataframe, the solution is to remove the for loop, and use a list comprehension for the column names:</p>
<pre><code>import pandas as pd
num =20
df = pd.DataFrame(columns=['col'+str(i) for i in range(num)])
</code></pre> | python|pandas|dataframe | 2 |
374,106 | 66,569,767 | Changing multiple column names by column number in Pandas? | <p>I am borrowing this example from <a href="https://www.geeksforgeeks.org/how-to-rename-columns-in-pandas-dataframe/" rel="nofollow noreferrer">here</a>. I have a dataframe like this:</p>
<pre><code># Import pandas package
import pandas as pd
# Define a dictionary containing ICC rankings
rankings = {'test': ['I... | <p>Just use <code>rename()</code> method and pass the <code>dictionary</code> of old values and new values as key-value pair in <strong>columns</strong> parameter:-</p>
<pre><code>rankings_pd=rankings_pd.rename(columns={'test':'tes_after_change','odi':'odi_after_change'})
</code></pre>
<p><strong>Edit</strong> by <a hr... | python|pandas | 8 |
374,107 | 66,705,131 | Custom data generator build from tf.keras.utils.Sequence doesn't work with tensorflow model's fit api | <p>I implemented a sequence generator object according to guidelines from <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence" rel="nofollow noreferrer">link</a>.</p>
<pre><code>import tensorflow as tf
from cv2 import imread, resize
from sklearn.utils import shuffle
from cv2 import imread, resiz... | <p>seniors. I am very sorry for the late response. I have found the fix for this issue.
All I need to change is to convert data_x to dtype='float32' at function self.<strong>getitem</strong>(). To replicate the issue just change the dtype as 'object'.</p>
<p>Besides that, please allow me to share that <em>class ActionD... | python|tensorflow|keras|sequence-generators | 1 |
374,108 | 66,720,113 | how does memory allocation occur in numpy array? | <pre><code>import numpy as np
a = np.arange(5)
for i in a:
print("Id of {} : {} \n".format(i,id(i)))
</code></pre>
<p><strong>>>>></strong></p>
<p>Id of 0 : 2295176255984</p>
<p>Id of 1 : 2295176255696</p>
<p>Id of 2 : 2295176255984</p>
<p>Id of 3 : 2295176255696</p>
<p>Id of 4 : 22951762559... | <p>I'm a fan of Code with Mosh. He teaches all such kind of things on his youtube channel as well as udemy. I've purchased his udemy course on Data structures and Algorithms which goes deep into how something works.
For example, while teaching about an array, he shows how to make an array so as to understand the underl... | python|numpy|memory|numpy-ndarray | 0 |
374,109 | 66,655,683 | Tensorflow Addon's Cohen Kappa Return 0 for all epochs | <p>I was having an issue with tensorflow_addons's CohenKappa metric. I'm trying to train an image classification model, but I frame this problem as a regression problem. So, I trained the model with MSE loss. However, I need to know the classification performance and I want to use CohenKappa. Gladly, Tensorflow support... | <p>Nevermind, after several moments I discovered where I was wrong. tensorflow addons isn't supporting tf.data yet, so the quick fix for this is stated on this github issue: <a href="https://github.com/tensorflow/addons/issues/2417" rel="nofollow noreferrer">https://github.com/tensorflow/addons/issues/2417</a></p> | tensorflow|metrics|kappa | 0 |
374,110 | 66,459,171 | How to convert this to a list or numpy array | <pre><code>cm = [[406402 30 0 0 11 6 0 0 0 0
200 0 0 0 0]
[ 89 269 0 0 0 0 0 0 0 0
0 0 0 0 0]
[ 9 0 25854 0 0 0 0 0 0 0
0 0... | <p>You can't directly convert this to np.array. You need add commas between elements and rows. For example:</p>
<pre><code>import numpy as np
np.array([[1,2],[3,4]])
</code></pre> | python|numpy | 0 |
374,111 | 66,606,544 | How to convert long data to wide in pandas? | <p>Similar question:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/52534500/long-wide-data-to-wide-long">Long/wide data to wide/long</a></li>
</ul>
<p>(I got duplicate index error when using the method given in that link)</p>
<h1>MWE</h1>
<pre><code>df_long = pd.DataFrame({'name': ['A', 'B', 'A', 'B'],
... | <pre><code>df_long.pivot_table("value",["name"], "variable")
variable height width
name
A 10 1
B 20 2
</code></pre> | python|pandas | 1 |
374,112 | 66,640,280 | Calculating a period as long as a criteria is met in a dataframe | <p>here is my dataframe:</p>
<pre><code> date value negative trigger period
125652 2020-01-12 07:00:00+00:00 21.688670 False False NaN
125653 2020-01-12 07:05:00+00:00 1.456942 False False NaN
125654 2020-01-12 07:10:00+00:00 -22.268280 True False ... | <p>First, you can identify the groups of continuous positive/negative values with this:</p>
<pre class="lang-py prettyprint-override"><code>df['grp'] = df.negative.diff().cumsum().fillna(0)
</code></pre>
<p>I explained the reasoning behind this neat little trick <a href="https://stackoverflow.com/questions/66209794/get... | python|pandas|dataframe | 0 |
374,113 | 66,759,689 | pandas How to find the group with the maximum value and delete the group | <p>I have dataframe like this:</p>
<pre><code>import numpy as np
import pandas as pd
dataA = [["2005-1-20", "9:35", 5], ["2005-1-20", "9:40", 8], ["2005-1-20", "9:45", 7],
["2005-1-20","9:50", 4], ["2005-1-20", "10:00"... | <p>This is my solution, it only removes one, even if two dates have the highest value.</p>
<pre><code>#Filter, so that you only have the values you want to compare
only_data_at_ten = df[ df.minute == '10:00']
#Find the highest value by sorting ascending and getting the last value
date_to_remove = only_data_at_ten.sort... | python|pandas|dataframe | 1 |
374,114 | 66,476,198 | How to remove certain values a Python Numpy Array | <p>I'm new to this, so this is probably a basic question, but how do I remove values from my array that are less than 0?</p>
<p>So, if</p>
<pre><code>a=np.random.randint(-10,11,(10,10))
</code></pre>
<p>How would I create an array with only the positive values from a?
thanks</p> | <pre><code>import numpy as np
a=np.random.randint(-10,11,(10,10))
np.where(a > 0, a, 0)
</code></pre> | python|arrays|numpy|random | 1 |
374,115 | 66,453,901 | Converting a pandas column from an array of string Quarters and Years to a datetime column | <p>I have the following dataframe</p>
<pre><code> Date Data
0 [Q1, 10] 8.7
1 [Q2, 10] 8.4
2 [Q3, 10] 14.1
3 [Q4, 10] 16.2
4 [Q1, 11] 18.6
5 [Q2, 11] 20.4
6 [Q3, 11] 17.1
7 [Q4, 11] 37.0
8 [Q1, 12] 35.1
9 [Q2, 12] 2... | <p>First create quarter <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.PeriodIndex.html" rel="nofollow noreferrer"><code>PeriodIndex</code></a>, then convert to datetimes by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.PeriodIndex.to_timestamp.html" rel="nofollow ... | python|pandas|datetime|time-series | 1 |
374,116 | 66,538,664 | User Defined Aggregate Function in PySpark SQL | <p>How to implement a User Defined Aggregate Function (UDAF) in PySpark SQL?</p>
<pre><code>pyspark version = 3.0.2
python version = 3.7.10
</code></pre>
<p>As a minimal example, I'd like to replace the AVG aggregate function with a UDAF:</p>
<pre><code>sc = SparkContext()
sql = SQLContext(sc)
df = sql.createDataFrame(... | <p>A Pandas UDF can be used, where the definition is compatible from <code>Spark 3.0</code> and <code>Python 3.6+</code>. See the <a href="https://issues.apache.org/jira/browse/SPARK-28264" rel="nofollow noreferrer">issue</a> and <a href="https://spark.apache.org/docs/latest/api/python/user_guide/arrow_pandas.html" re... | pandas|apache-spark|pyspark|apache-spark-sql|user-defined-functions | 3 |
374,117 | 66,387,247 | How to remove a zero frequency artefact from FFT using numpy.fft.fft() when detrending or subtracting the mean does not work | <p>I am trying to calculate the FFT of the following data : <a href="http://www.mediafire.com/file/91olqnm6i9qh5bl/data.txt/file" rel="nofollow noreferrer">data.txt</a></p>
<pre class="lang-py prettyprint-override"><code>y_array = np.loadtxt('data.txt',dtype='complex')
plt.plot(np.real(y_array))
</code></pre>
<p><a hre... | <p>If you subtract the mean, then what's left isn't a 0 Hz artifact, but some low frequency spectrum (perhaps between 2 to 10 Hz in your plot, depending on your dimensions). Try a high pass filter.</p>
<p>Also, since it's complex data, make sure you subtracted the complex mean.</p> | python|numpy|scipy|signal-processing|fft | 0 |
374,118 | 66,656,620 | What is my problem with the implementation of multivariate_gauss pdf? | <p>I use python to calculate the multivariate_gauss distribution, but I don't know what's wrong.
The code is here</p>
<pre><code># calculate multi-d gaussian pdf
def mul_gauss(x, mu, sigma) -> float:
d = len(x[0])
front = 1 / math.sqrt(((2 * math.pi) ** d) * np.linalg.det(sigma))
tmp = (np.array(x) - np.... | <p>In line 5 of your main you call the <code>.pdf()</code> on the object instead as a method.
Here is a fix:</p>
<pre><code># calculate multi-d gaussian pdf
import math
import numpy as np
from scipy import stats
def mul_gauss(x, mu, sigma) -> float:
d = x[0].shape[0]
coeff = 1/np.sqrt((2 * math.pi) ** d *... | python|numpy|math|gaussian | 2 |
374,119 | 66,683,088 | How to fix the error: ValueError: endog and exog matrices are different sizes | <p>I'm trying to write a program in python that uses a query in SQL to collect data and make a regression model. When I try to actually create the model, however, it gives me this error.</p>
<pre><code>import pyodbc
import pandas
import statsmodels.api as sm
import numpy as np
server = 'ludsampledb.database.windows.ne... | <p>Avoid <code>reshape</code> calls which may be transposing data causing mismatched sizes. Pandas DataFrames and Series (each column of DataFrame) are extensions of numpy 2D and 1D arrays. Also, <code>sm.OLS</code> can directly receive pandas objects.</p>
<pre class="lang-py prettyprint-override"><code>x = data.reinde... | python|sql|pandas|numpy | 0 |
374,120 | 66,468,250 | Split a column with a number and name into two different columns 'ID' and 'Name' | <p>I am converting a text file to csv.
In the csv file Im getting a column having a number and name in it (e.g 1: Aki ) , I want to seperate them both in two different columns.</p>
<p>samle data</p>
<pre><code>1: Aki
2: Aki
3: Kano
</code></pre>
<p>code tried</p>
<pre><code>df_output.columns = ['Name', 'date', 'Descri... | <p>Use <code>str.extract</code> here:</p>
<pre class="lang-py prettyprint-override"><code>df_output['ID'] = df['name'].str.extract(r'^(\d+)')
df_output['name'] = df['name'].str.extract(r'^\d+: (.*)$')
</code></pre> | python|pandas | 4 |
374,121 | 66,705,839 | Invert order and color of hue categories using Seaborn | <p>So when I am plotting a box graph and I am using a cotagory in "hue" I get a default order of the categories (Yes and No in my case). I want the boxes to be presented in the reverse order (No Yes) and with the reverse colors. This is my code:</p>
<pre><code>fig=plt.figure(figsize=(12,6))
df2=df[df["AM... | <p>As mentioned above this does the job if you want to explicitly specify the order of the boxes and the hue_order:</p>
<pre><code>fig=plt.figure(figsize=(12,6))
df2=df[df["AMT_INCOME_TOTAL"]<=df["AMT_INCOME_TOTAL"].median()]
ax = sns.boxplot(x="NAME_FAMILY_STATUS", y="AMT_INCOME_T... | python|pandas|matplotlib|plot|seaborn | 1 |
374,122 | 66,479,033 | Pandas read excel returning type object when time is 00:00 | <p>In more recent versions of Pandas (I am using 1.2.3) when reading times from an excel file, there is a problem when the time is 00:00:00. Below script, where filepath is the route to my excel file, which contains a column with a header named 'Time'.</p>
<pre><code>import pandas as pd
df = pd.read_excel(filepath)
pr... | <p>I can reproduce this behavior (pandas 1.2.3); it leaves you with a mix of <code>datetime.datetime</code> and <code>datetime.time</code> objects in the 'time' column.</p>
<hr />
<p><em><strong>One way</strong></em> around can be to import the time column as type string; you can explicitly specify that like</p>
<pre><... | python|excel|pandas|datetime | 3 |
374,123 | 66,362,203 | Less Expensive Tuple Loop | <p>this loop is currently working, I'm just asking for feedback on how to make it less expensive. Learning python, so all feedback is welcome! Also, not working with bananas, made 2 new tables for the purpose of this example.</p>
<p>If you care for more detail about how/why I'm using this, read below.</p>
<pre><code>i... | <ul>
<li><p>Is this an actual bottleneck in the application? It doesn't seem like it should be expensive enough to warrant optimisation.</p>
</li>
<li><p>If it is an problem, the loop can either append to a list, or <code>yield</code> the values (from a helper function), then only contruct a tuple once.</p>
<pre><code>... | python|pandas|dataframe | 2 |
374,124 | 66,413,127 | Python Pandas split list by delimiter into own columns | <p>new to python and still learning. Have tried many posts already but none are working. Might need help with the syntax etc. 2 parts to my question:</p>
<p>First part - I want to split column 'resources' by every unique value and make new columns from them. Similar to the picture below with the columns highlighted yel... | <p>For your first question, use <code>str.get_dummies</code>:</p>
<pre><code>dummies = df['Resources'].str.get_dummies(sep=";")
df = pd.concat([df, dummies], axis=1)
CustID Resources 100 200 30 50
0 222 100;200;30;50 1 1 1 1
</code></pre>
<hr />
<p>For the second question, the <cod... | python|pandas|list | 1 |
374,125 | 66,708,320 | Check pandas DataFrame values with pydantic | <p>I have DataFrame, and would like to add a new column to it with rows filled by JSONs, that consists of values from other columns. like that:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>a_field</th>
<th>b_field</th>
<th>json</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>... | <p>If I get the question right, you can parse it something like this:</p>
<pre><code>from pydantic import BaseModel
import json
class JSON(BaseModel):
num: int
name: str
obj = JSON(**json.loads('{"num":1, "name":"abc"}'))
assert obj.json() == '{"num": 1, "name... | python|pandas|pydantic | 2 |
374,126 | 66,747,278 | Why does the export of a styled pandas dataframe to Excel not work? | <p>I would like to apply the same background color to cells that have for each PEOPLE instance the name and the related name. I have tried to <code>df.style.applymap</code>, it does not return an error but it does not seem to work. Anyone has any ideas why? Thank you.</p>
<pre><code> clrs = list(mcolors.CSS4_COLORS.... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html" rel="nofollow noreferrer">Here</a> is some more info on <code>df.style</code>. Here I'm using some simple example because I don't have your data available:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy... | python|excel|pandas|dataframe|pandas-styles | 3 |
374,127 | 66,549,990 | How do I change the values of a column with respect to certain conditions using pandas? | <p>The data frame contains 5 columns named V, W, X, Y, Z.</p>
<p>I'm supposed to change the values in column X from a dataset according to:</p>
<ul>
<li>if 1 to 100, change to 1</li>
<li>if 101 to 200, change to 2</li>
<li>if 201 to 300, change to 3</li>
</ul>
<p>otherwise, change to 4</p>
<p>What's the most efficient ... | <p>Using an example <code>df</code> and @Pygirl's idea:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'a': np.random.randint(0, 400, 10), 'b': np.random.randint(0, 400, 10), 'X': np.zeros(10)})
</code></pre>
<p>gives us:</p>
<pre><code>| | a | b | X |
|---:|----:|----:|----:|
| 0 | 23... | python|pandas | 0 |
374,128 | 66,682,344 | Numpy array bigger than the total size of images it is made up of | <p>I am trying to convert a directory of RGB images to a numpy array but the resulting array is way bigger than the sum of sizes of all the images put together. What is going on here?</p> | <p>That's because image files are usually compressed, which means that the stored data will be smaller than the original file containing all pixel data, when you open a image using PIL, for example, you'll get access to all RGB values of all pixels, so, there's more data 'cus it's uncompressed.</p> | python|python-3.x|numpy | 2 |
374,129 | 66,699,658 | Comparing 2 Structured Arrays that contain values of different types and NaNs | <p>So I have 2 structured Numpy Arrays:</p>
<pre><code>a = numpy.array([('2020-01-04', 'Test', 1, 1.0),
('2020-01-05', 'Test2', 2, NaN)],
dtype=[('Date', 'M8[D]'), ('Name', 'S8'), ('idx', 'i8'), ('value', 'f8')])
b = numpy.array([('2020-01-04', 'Test', 2, 1.0),
('2... | <p>Here's the workaround I was able to use to solve this. This is not pretty but does check for all the elements, compare and provide the answer. You can expand this to find a way to change the answer to True if np.Nan == np.Nan.</p>
<pre><code>import numpy as np
a = np.array([('2020-01-04', 'Test', 1, 1.0),
... | python|arrays|numpy | 0 |
374,130 | 16,246,324 | Applying a function on every row of numpy array | <p>I have a (16000000,5) numpy array, and I want to apply this function on each row.</p>
<pre><code>def f(row):
#returns a row of the same length.
return [row[0]+0.5*row[1],row[2]+0.5*row[3],row[3]-0.5*row[2],row[4]-0.5*row[3],row[4]+1]
</code></pre>
<p>vectorizing would operate slow.</p>
<p>I tried going like t... | <pre><code>In [104]: arr=np.random.rand(1000000,5)
In [105]: %timeit a=np.column_stack((arr[:,0]+0.5*arr[:,1],arr[:,2]+0.5*arr[:,3],arr[:,3]-0.5*arr[:,2],arr[:,4]-0.5*arr[:,3],arr[:,4]+1))
10 loops, best of 3: 86.3 ms per loop
In [106]: %timeit a2=map(f,arr)1 loops, best of 3: 10.2 s per loop
In [98]: a2=map(f,arr)
... | python|numpy | 2 |
374,131 | 16,415,730 | Python indexing 2D array | <p>How can i do indexing of a 2D array column wise. For example- </p>
<pre><code>array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39],
[40, 41, 42, 43, 44],
[45, 4... | <p>If you want [5] to give 20, you must be starting to count from 1. Since Python starts counting from 0, that's a habit to break now: it'll only cause headaches.</p>
<p>I'm not sure what output format you want because numpy doesn't support ragged arrays, but maybe</p>
<pre><code>>>> idx = np.array([5, 10, ... | python|numpy | 2 |
374,132 | 16,420,673 | Pythonic way to access certain parts of an array | <p>I have a 2D numpy array containing x (data[:,0]) and y(data[:,1]) information for a plot.</p>
<p>I’d like to fit a curve to the data, but only using certain parts of the data to determine the fitting parameters (e.g. using data in the range x = x1 -> x2, and x3 -> x4). My plan to do this is to create a new numpy ar... | <p>To get a boolean array out of two others, use <code>&</code> to compare element-wise:</p>
<pre><code>index_range1 = np.where((data[:,0] > x1) & (data[:,0] < x2))
index_range2 = np.where((data[:,0] > x3) & (data[:,0] < x4))
</code></pre>
<p>Using <a href="http://docs.scipy.org/doc/numpy/refe... | python|arrays|numpy | 2 |
374,133 | 16,043,299 | Substitute for numpy broadcasting using scipy.sparse.csc_matrix | <p>I have in my code the following expression:</p>
<pre><code>a = (b / x[:, np.newaxis]).sum(axis=1)
</code></pre>
<p>where <code>b</code> is an ndarray of shape <code>(M, N)</code>, and <code>x</code> is an ndarray of shape <code>(M,)</code>. Now, <code>b</code> is actually sparse, so for memory efficiency I would l... | <p>If <code>b</code> is in CSC format, then <code>b.data</code> has the non-zero entries of <code>b</code>, and <code>b.indices</code> has the row index of each of the non-zero entries, so you can do your division as:</p>
<pre><code>b.data /= np.take(x, b.indices)
</code></pre>
<p>It's hackier than Warren's elegant s... | python|numpy|scipy|sparse-matrix | 12 |
374,134 | 57,303,955 | Should the embedding layer be changed during training a neural network? | <p>I'm a new one for the field of deep learning and Pytorch.</p>
<p>Recently when I learn one of the <a href="https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html#sphx-glr-beginner-nlp-advanced-tutorial-py" rel="nofollow noreferrer">pytorch tutorial example for NER task</a>, I found the embedding of nn.Em... | <p>One can either learn embeddings during the task, finetune them for task at hand or leave as they are (provided they have been learned in some fashion before).</p>
<p>In the last case, with standard embeddings like word2vec one eventually finetunes (using small learning rate), but uses vocabulary and embeddings prov... | python|pytorch | 2 |
374,135 | 57,404,020 | comparing date time values in a pandas DataFrame with a specific data_time value and returning the closet one | <p>I have a date column in a pandas DataFrame as follows:</p>
<pre><code>index date_time
1 2013-01-23
2 2014-01-23
3 2015-8-14
4 2015-10-23
5 2016-10-28
</code></pre>
<p>I want to compare the values in <code>date_time column</code> with a specific date, for example <code>date_x = 2015-... | <p>Here is one way using <code>searchsorted</code>, and all my method is assuming the data already order , if not doing the <code>df=df.sort_values('date_time')</code></p>
<pre><code>df.date_time=pd.to_datetime(df.date_time)
date_x = '2015-9-14'
idx=np.searchsorted(df.date_time,pd.to_datetime(date_x))
df.date_time.ilo... | python|pandas | 2 |
374,136 | 57,354,545 | Number formatting after mapping? | <p>I have a data frame with a number column, such as:</p>
<pre><code>CompteNum
100
200
300
400
500
</code></pre>
<p>and a file with the mapping of all these numbers to other numbers, that I import to python and convert into a dictionary:</p>
<pre><code>{100: 1; 200:2; 300:3; 400:4; 500:5}
</code></pre>
<p>And I am ... | <p>There is problem missing values for non matched values after <code>map</code>, possible solution is:</p>
<pre><code>print (df)
CompteNum
0 100
1 200
2 300
3 400
4 500
5 40
accounts1 = {100: 1, 200:2, 300:3, 400:4, 500:5}
s = df['CompteNum'].astype(str)
s1 = df['Compt... | python|pandas|dictionary|replace | 0 |
374,137 | 57,684,467 | Create Multilevel DataFrame by reading in data from multiple files using read_csv() [SOLVED] | <p>I have 10 files with the following identical format and column names (values are different across different files): </p>
<pre><code> event_code timestamp counter
0 9071 1165783 NaN
1 9070 1165883 NaN
2 8071 1166167 NaN
3 7529 NaN 0.0
4 8529 NaN ... | <p>I think you should use a pivot table or the pandas groupby function for this task. Neither will give you exactly what you have requested above, but it will be simpler to use. </p>
<p>Using your code as a starting point:</p>
<pre><code>col_names = ['event_code','timestamp', 'counter']
data = pd.DataFrame()
for i i... | python|pandas | 0 |
374,138 | 57,421,804 | Aggregate dataframe columns by hourly index | <p>So I have a pandas dataframe that is taking in / out interface traffic every 10 minutes. I want to aggregate the two time series into hourly buckets for analysis. What seems to be simple has actually ended up being quite challenging for me to figure out! Just need to bucket into hourly bins</p>
<pre><code>times = l... | <p>I believe this should do what you want:</p>
<pre><code>df = pd.DataFrame()
df['datetime'] = times
df['datetime'] = pd.to_datetime(df['datetime'])
df.set_index('datetime',inplace=True) # This won't try to remap your rows
new_df = df.groupby(pd.Grouper(freq='H')).mean()
</code></pre>
<p>That last line groups your da... | python|pandas | 0 |
374,139 | 57,658,038 | Print a dataframe to a specific column/row location like (1,2) using xlwings | <p>Trying to find out how to print to a specific column/row similar to how
pd.to_excel(startcol = 1, startrow = 1) works. I have to do this in an open excel workbook, and found the library xlwings. I'm currently using openpyxl, how would I do this in xlwings? I read the documentation printing to specific cells like A1... | <p>You can easily print a pandas dataframe to excel using xlwings. The range object takes a row and a column number as arguments (or just a cell reference as a string). Consider the following code:</p>
<pre><code>import xlwings as xw
import pandas as pd
row = 1
column = 2
path = 'your/path/file.xlsx'
df = pd.DataFra... | python|pandas|xlwings | 3 |
374,140 | 57,525,309 | Make multiple plots at once | <p>I have a df that looks like this:</p>
<pre><code> date group score origin ...
0 1 group1 1 0 ...
1 1 group2 2 1 ...
2 2 group2 5 2 ...
3 2 group1 ... | <p>Try using <a href="https://seaborn.pydata.org/generated/seaborn.FacetGrid.html" rel="nofollow noreferrer"><code>seaborn.FacetGrid</code></a> for simple control over these types of plots:</p>
<pre><code>g = sns.FacetGrid(df, row='origin', hue='group')
g.map(sns.lineplot, 'date', 'score')
</code></pre>
<p>[out]</p>
... | python|python-3.x|pandas|matplotlib|seaborn | 3 |
374,141 | 57,474,267 | Efficient and elegant way to fill values in pandas column based on each groups | <pre><code>df_new = pd.DataFrame(
{
'person_id': [1, 1, 3, 3, 5, 5],
'obs_date': ['12/31/2007', 'NA-NA-NA NA:NA:NA', 'NA-NA-NA NA:NA:NA', '11/25/2009', '10/15/2019', 'NA-NA-NA NA:NA:NA']
})
</code></pre>
<p>It looks like as shown below</p>
<p><a href="https://i.stack.imgur.com/bngk0.png" rel="nofollow norefer... | <p>First use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <code>errors='coerce'</code> for convert non datetimes to missing values, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.co... | python|python-3.x|pandas|dataframe|pandas-groupby | 2 |
374,142 | 57,694,732 | Python uses wrong Package version | <p>Hi i try to launch the <code>object_detection_tutorial</code> on my PC. When i run the following code to load a (frozen) <code>Tensorflow</code> model into memory. </p>
<pre><code>detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_FROZEN_GRAP... | <p>Looks like the module is not installed correctly. Try creating a new environment using conda and set up Object Detection in it. It should resolve your issue. </p>
<p>Also, as best practices, it is always better to work on a conda environment than working on the base environment. </p>
<p>Please use below command to... | python|tensorflow|pip|object-detection | 0 |
374,143 | 57,505,365 | how to plot a scatter plot for the following data in python? | <p>I did splitting among trained and testing data using the function train_test_split() and get the following.</p>
<p><code>print(X_train)</code>
<code>
+--------------------+
| fre loc |
+--------------------+
| 1.208531 0.010000 |
| 0.169742 0.010000 |
| 0.119691 0.010000 |
| 0.151515 0.010000 |
| 0.6... | <p>Try out scatter plots for different data sets you created and deferant results you obtained. Then of course you will see the patterns.</p>
<p>Here is a code snippet I used for creating scatter plots. Hope it helps if you are new to visualization.
Here I take inputs for x and y from two separate files as xdata.txt a... | python-3.x|pandas|dataframe|matplotlib|plot | 1 |
374,144 | 57,531,811 | Filtering rows in DataFrame with dependent conditions | <p>Apologies if this has already been asked: </p>
<p>I want to remove all rows with values between 15-25 in one column AND have a specific string in another column. </p>
<p>For example: </p>
<pre><code>options = ['pizza', 'pasta']
df2 = df[(~df['columnA'].between(15, 25)) & df.loc[~df['columnB'].isin(options)]... | <p>The easiest to understand is negating the entire condition, like <code>~((...) & (...))</code>:</p>
<pre><code>df[~((df['columnA'].between(15, 25)) & (df['columnB'].isin(options)))]</code></pre>
<p>Or you can use <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="nofollow noreferrer"><em>De Morgan... | python|pandas | 2 |
374,145 | 57,487,272 | Calculate the sum of the numbers separated by a comma in a dataframe column | <p>I am trying to calculate the sum of all the numbers separated by a comma in a dataframe column however I keep getting error. This is what the dataframe looks like:</p>
<pre><code>Description scores
logo
graphics
eyewear 0.360740,-0.000758
glasses 0.360740,-0.000758
picture -0.000646
tutorial ... | <p>There are times when using Python seems to be very effective, this might be one of those.</p>
<pre><code>df['scores'].apply(lambda x: sum(float(i) if len(x) > 0 else np.nan for i in x.split(',')))
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
</code></pre> | python-3.x|pandas|dataframe|lambda|apply | 2 |
374,146 | 57,485,157 | Tensorflow: Save metrics every certain steps | <p>I have trained a model and want to access the standard metrics plus a custom metric, every 100 steps. </p>
<pre><code>def top3error(features, labels, predictions):
return {'top3error': tf.metrics.mean(tf.nn.in_top_k(predictions=predictions['logits'],
targ... | <p>you can use tensorflow summaries. You can also use that to visualize your metric in tensorboard.</p>
<p>check this out-><a href="https://stackoverflow.com/questions/42164772/tensorflow-estimator-api-summaries">Tensorflow Estimator API: Summaries</a></p> | tensorflow|hook|metrics | 0 |
374,147 | 57,532,688 | Indexing 3d numpy array with 2d array | <p>I would like to create a numpy 2d-array based on values in a numpy 3d-array, using another numpy 2d-array to determine which element to use in axis 3.</p>
<pre><code>import numpy as np
#--------------------------------------------------------------------
arr_3d = np.arange(2*3*4).reshape(2,3,4)
print('arr_3d shape=... | <p>The shape of the result from fancy index and broadcasting is the shape of the indexing array. You need passing 2d array for each axis of <code>arr_3d</code></p>
<pre><code>ax_0 = np.arange(arr_3d.shape[0])[:,None]
ax_1 = np.arange(arr_3d.shape[1])[None,:]
arr_3d[ax_0, ax_1, arr_2d]
Out[1127]:
array([[ 3, 6, 8],... | python|numpy|multidimensional-array|indexing | 5 |
374,148 | 57,619,816 | Hashing_trick in Keras. How it works? | <p>Needs basic understanding of one hot or hashing trick in keras.</p>
<pre><code>from keras.preprocessing.text import hashing_trick
from keras.preprocessing.text import text_to_word_sequence
# define the document
text = 'The quick brown fox jumped over the lazy dog dog.'
# estimate the size of the vocabulary
words = ... | <p>This is an example of a <a href="https://en.wikipedia.org/wiki/Hash_table#Collision_resolution" rel="nofollow noreferrer">hashing collision</a>. The hash function is just a function computed on the input words. For example, Java's default hash function does something like multiplying the first character by 1, the ... | python-3.x|tensorflow|keras|deep-learning | 0 |
374,149 | 57,403,919 | Dimensionality of strided convolution with stride 2 and max pooling layer | <p>This question is NOT about the benefit of strided convolution vs max pooling. This post is intended as a canonical source on how to compute the dimensionality of strided convolution and max-pooling when the <strong>input image size is NOT the same for width and height while padding is SAME</strong>.</p>
<p><strong>... | <p>You can get the shape of the resulting tensors the following way. </p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
input_im = tf.placeholder(tf.float32, shape=[None, 320, 240, 3])
x = tf.layers.conv2d(input_im, filters=64, kernel_size=3, strides=1, padding='SAME')
print('After conv1', x... | python|tensorflow|deep-learning | 1 |
374,150 | 57,321,495 | How to sort date by descending order and time by ascending order using Pandas | <p>My <code>df</code> looks like this. It is an <code>hourly</code> dataset.</p>
<pre><code>time Open
2017-01-03 09:00:00 5.2475
2017-01-03 08:00:00 5.2180
2017-01-03 07:00:00 5.2128
2017-01-02 09:00:00 5.4122
2017-01-02 08:00:00 5.2123
2017-01-02 07:00:00 5.2475
2017-01-01 0... | <p>If need sorting by dates and times create new columns for sorting by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="noreferrer"><code>DataFrame.assign</code></a>, then sort by both columns with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/p... | python-3.x|pandas|dataframe | 9 |
374,151 | 57,506,227 | How to join several time series with MultiIndex Data Frame? | <p>I am trying to merge several time series dataframes into one very large dataframe with a MultiIndex.</p>
<p>Suppose I have these DataFrames.</p>
<pre class="lang-py prettyprint-override"><code>In [1]: dates = pd.DatetimeIndex(["2019-1-1", "2019-1-2", "2019-1-3"], name="Date")
In [2]: df_a = pd.DataFrame(np.random.... | <p>Okay, so currently I'm working with this bit of code.</p>
<pre class="lang-py prettyprint-override"><code>idx = pd.IndexSlice
df.loc[idx[:, "A"], :] = df.loc[idx[:, "A"], :].fillna(df_a)
df.loc[idx[:, "B"], :] = df.loc[idx[:, "B"], :].fillna(df_b)
df.loc[idx[:, "C"], :] = df.loc[idx[:, "C"], :].fillna(df_c)
</code>... | python|pandas | 0 |
374,152 | 57,418,397 | How to combine a wide and a long dataframe in pandas? | <p>I have the following dataframe</p>
<pre><code>data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18], 'Height':[23, 43, 123, 12], 'Hair_Width':[21, 11, 23, 14]}
df = pd.DataFrame(data)
df
Name Age Height Hair_Width
0 Tom 20 23 21
1 nick 21 43 11
2 krish 19 123... | <p>Just add <code>Hair_Width</code> as another <code>id_var</code> when you <code>melt</code>, no need to do anything after.</p>
<hr>
<pre><code>df.melt(id_vars=['Name', 'Hair_Width'], value_vars=['Age', 'Height'])
</code></pre>
<p></p>
<pre><code> Name Hair_Width variable value
0 Tom 21 Age ... | python|python-3.x|pandas|dataframe|melt | 6 |
374,153 | 57,403,572 | Colab not recognizing local gpu | <p>Im trying to train a Neural Network that I wrote, but it seems that colab is not recognizing the gtx 1050 on my laptop. I can't use their cloud GPU's for this task, because I run into memory constraints </p>
<pre class="lang-py prettyprint-override"><code>print(cuda.is_available())
</code></pre>
<p>is returning F... | <p>Indeed you gotta select the local runtime accelerator to use GPUs or TPUs, go to <code>Runtime</code> then <code>Change runtime type</code> like in the picture:</p>
<p><a href="https://i.stack.imgur.com/azdlm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/azdlm.png" alt="runtime"></a></p>
<p>An... | python-3.x|pytorch|google-colaboratory | 1 |
374,154 | 57,726,283 | How do I build an array using numpy.repeat where each element is 1% over the previous one? | <p>I have an initial value of salary=500. I want it to increment by 1% every year so my array would look like <code>[500,550,605,665.5]</code> etc. Essentially multiplying <code>1.1</code> to each previous value. </p>
<p>I was using a loop for this, but was curious if it could be done using <code>numpy.arange</code> a... | <p>Use <code>1.1</code> as the base to create an <em>exponential-array</em> and scale it with the starting value -</p>
<pre><code>In [52]: 500*(1.1**np.arange(4)) # 4 is number of output elements
Out[52]: array([500. , 550. , 605. , 665.5])
</code></pre> | python|arrays|numpy | 2 |
374,155 | 57,667,455 | appending Dict to nested list per request made | <p>I am currently scraping through an XML API response. I am looking to gather a piece of information for each request and create a dictionary each time I find this piece of data. Each request can have several IDs. So one response can have 2 IDs while the next response might have 3 IDs. For example, let's say the first... | <p>It has to do with the order of your initializing and appending that is causing you to not get the outcome you are wanting. You are overwriting your <code>dataDict</code> after each iteration, and inserting the appended list which is not overwritten, thus leaving you with a final list that has appended ALL <code>aIDs... | python-3.x|pandas|beautifulsoup|python-requests | 1 |
374,156 | 57,682,831 | What happens if Keras Tensorflow's `Model.fit`'s target/output is `None`? | <p>I was looking at this code: <a href="https://github.com/keras-team/keras/blob/master/examples/variational_autoencoder.py#L198" rel="nofollow noreferrer">https://github.com/keras-team/keras/blob/master/examples/variational_autoencoder.py#L198</a>, where <code>Model.fit()</code> is called without an output or target T... | <p>In the Keras documentation for <a href="https://keras.io/models/model/#fit" rel="nofollow noreferrer">model.fit</a> the following is stated:</p>
<blockquote>
<ul>
<li>y: Numpy array of target (label) data (if the model has a single output), or list of Numpy arrays (if the model has multiple outputs).
If outpu... | python|tensorflow|keras|autoencoder | 2 |
374,157 | 57,527,756 | Cutting Sheets on Unique Values in each column | <p>On a quarterly basis I have to cut a master file that is sent to me from the hire ups based on a few specified columns which are Region, City, and Department. I wrote a script that does the cutting for me but unfortunately I cant figure out a way how to run only 1 iteration of same script versus same scripts changed... | <p>This produces a dataframe for each unique combination of three attributes. Replace <code>print(sub_df)</code> with the operations you need (select columns, write to csv)</p>
<pre><code>from io import StringIO
import pandas as pd
df = pd.read_csv(StringIO(
"""Region,City,Department,value
R1,C1,D1,1
R1,C1,D2,2
R1,C2... | python|pandas | 0 |
374,158 | 57,463,064 | Exporting dataframes within a dict to separate csv files | <p>I have a dictionary with a year for each key and a dataframe for each value. I need to export these dataframes as CSV files with the key (being the year) as the file name. I've tried running a for loop changing the variable name but doesn't seem to work.
Could someone please outline another method of doing this. Tha... | <p>Not that different than Charles answer but as <a href="/help/minimal-reproducible-example">mcve</a> and we can even pass integers as year instead of strings.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import os
fldr = 'dataframes'
os.makedirs(fldr, exist_ok=True)
diz = {key:pd.util.tes... | python|pandas | 1 |
374,159 | 57,631,182 | How to query pandas dataframe for regular expression? | <p>I have df:</p>
<pre><code>{'col1': {0: 'vJAaIAM',
1: 'K0jQAF',
2: '00qvP1IIU',
3: 'tFCJ2',
4: '0d2fIAB'},
'col2': {0: 6294.0,
1: 859485.0,
2: 7362.0,
3: 6273921.0,
4: 114506.0}}
</code></pre>
<p>and I am looking to query this dataframe for all rows that have capital 'A' and here is what I have:</p... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><strong><code>.str.contains('A')</code></strong> [pandas-doc]</a> here:</p>
<pre><code>>>> df[df['col1'].str.contains('A')]
col1 col2
0 vJAaIAM 6294.0
1 ... | python|pandas|dataframe | 2 |
374,160 | 57,320,779 | 'numpy.ndarray' object has no attribute 'drop' | <p>I have a dataset with four inputs named X1, X2, X3, X4.
Here I created the lstm model to predict next X1 value with the previous values of four inputs. </p>
<p>Here I changed the time into minutes and then I set the time as index.</p>
<p>Then I created the x_train, x_test , y_test and y_train. Then I wanted to dr... | <p>Because you extracted the values of your Pandas dataframe, your data have been converted into a NumPy array and thus the column names have been removed. The time column is the first column of your data, so all you really need to do is index into it so that you extract the second column and onwards:</p>
<pre><code>... | python|pandas|numpy|machine-learning|lstm | 1 |
374,161 | 57,418,236 | Aggregating rows in python pandas dataframe | <p>I have a dataframe documenting when a product was added and removed from basket. However, the <code>set_name</code> column contains two sets of information for the color set and the shape set. See below:</p>
<pre><code> eff_date prod_id set_name change_type
0 20150414 20770 MONO COLOR ... | <p>Your code looks fine apart from having to reset your index, but we can simplify it quite a bit (in particular remove the need for <code>iterrows</code> which can be painfully slow, using a <code>pivot</code> with a small trick to get your column names.</p>
<p>This answer assumes that you only have these two options... | python|pandas|dataframe | 1 |
374,162 | 57,500,021 | How to ignore a missing value in a file in a sum in Python | <p>I'm trying to get the quantities of some products in 6 Excel file, but in some of them, may not have the product, while in the others has.
Ex: in the arq1 exists the bj code, but in the arq2 doesn't. So when it makes the sum it doesn't give me the right number. As you can see below:</p>
<pre><code>import pandas as... | <p>Try taking the value from the result Series, so that you don't have to worry about index. Assuming <code>Cod.Artigo</code> is unique, you can do:</p>
<pre><code>bj_xl = list_arq[i][list_arq[i]['Cod.Artigo']=='PTTGBCH01023']['Unidades'].values[0]
m_xl = list_arq[i][list_arq[i]['Cod.Artigo']=='PTTGBCM01B05']['Unidad... | python|python-3.x|pandas | 1 |
374,163 | 57,544,806 | Pandas - Align matching column values to row | <p>I have what appears to be a simple problem, that I was not able to find a solution to. Namely, I have a table, where first column contains the list of all available applications, while other columns represent users and the list of applications they have:</p>
<p><a href="https://i.stack.imgur.com/yeDxH.png" rel="nof... | <p>Here is an approach with some numpy tools. Here, <code>apply</code> loops through the columns of interest, <code>np.isin</code> performs a search over your first column (dat.Applications) and returns True if the respective element is contained in the current column. This boolean array is then converted to the respec... | python|pandas|dataframe | 2 |
374,164 | 57,483,013 | Python saying "no module named tflearn" but i imported it | <p>I used Pip install TFlearn and ran my code on my Raspberry Pi but it says</p>
<blockquote>
<p>no module named tflearn</p>
</blockquote>
<p>video:<a href="https://www.youtube.com/watch?v=wypVcNIH6D4&t=3s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=wypVcNIH6D4&t=3s</a></p>
<p>code:</p>
<pr... | <p>Basic preliminary checks:
run
<code>pip freeze</code> to get a list of packages installed. Ideally tflearn should be there. If not, it indicates that the package has not been installed properly.</p> | python|tensorflow|raspberry-pi|tflearn | 0 |
374,165 | 57,591,480 | Python Pandas sum a constant value in Columns If date between 2 dates | <p>Let's assume a dataframe using datetimes as index, where we have a column named 'Score', initialy set to 10:</p>
<pre><code> score
2016-01-01 10
2016-01-02 10
2016-01-03 10
2016-01-04 10
2016-01-05 10
2016-01-06 10
2016-01-07 10
2016-01-08 10
</code></pre>
<p>I want to substract a fixed value (l... | <p>Use index slicing:</p>
<pre><code>df.loc['2016-01-03':'2016-01-06', 'score'] -= 1
</code></pre> | python|pandas | 5 |
374,166 | 57,303,687 | Create column o difference between two pandas DF | <p>I have <strong>firstDF:</strong></p>
<pre><code>rs Chr MapInfo Name SourceSeq
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A3 B3 C3 D3
4 A4 B4 C4 D4
5 A5 B5 ... | <p>Solution is change mask - compare <code>secondDF.Name</code> by column from <code>firstDF</code>, from sample data it is <code>MapInfo</code> column, in real data seems <code>Name</code> column for boolean mask with same size and index values like <code>secondDF</code>, because is filtered <code>secondDF</code> Data... | python|pandas | 1 |
374,167 | 57,457,504 | how can I make limit on cumsum in dataframe and minus to all values | <p>when I do cumsum with dataframe with lots of datas there's some errors and bugs, so I want to make limit on cumsum data and minus limit value to all datas. Like below</p>
<pre><code>A B IntA IntB
1 2 1 2
2 4 3 6
3 6 6 12
4 8 10 20
5 2 15 ... | <p>Ok finally I think I got it. It would have been easy with <code>.apply</code> but it should scale better without and it's also more fun :-)</p>
<pre><code>df= pd.DataFrame({
'A': [1, 2, 3, 4, 5, 6, 7],
'B': [2, 4, 6, 8, 2, 4, 8]
})
cumsumA= df['A'].cumsum()
cumsumB= df['B'].cumsum()
tensA= (cumsumA //... | python|pandas | 0 |
374,168 | 57,350,598 | fastest way to insert multiple rows into a dataframe given a list of indexes (python) | <p>I have a dataframe and I would like to insert rows at specific indexes at the beginning of each group within the dataframe. As an example lets say I have the following dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame(data=[['A',1,1],['A',2,3],['A',5,4],['B',3,4],... | <p>You can do this by grouping by <code>group</code>, iterating over each group, and constructing a DataFrame via concatenation of each the first row of a group to the group itself, then the concatenation of all those concatenations.</p>
<p><strong>Code:</strong></p>
<pre><code>import pandas as pd
df = pd.DataFrame(... | python|pandas|dataframe|insert|concat | 2 |
374,169 | 57,540,443 | Loading python TensorFlow Layers models into JavaScript | <p>The core <code>TensorFlow</code> libraries provide the ability to convert a model created in <code>Python</code> to be saved into a <code>JSON</code> file describing the graph and weights to be executed in a browser environment.</p>
<p>In the examples you are required to load the whole <code>TensorFlow</code> libra... | <p>The Tensorflow.js API combines four packages:</p>
<ul>
<li><a href="https://github.com/tensorflow/tfjs/tree/master/tfjs-core" rel="nofollow noreferrer">tfjs-core</a>: Functionality like mathematical functions and backend support</li>
<li><a href="https://github.com/tensorflow/tfjs/tree/master/tfjs-layers" rel="nofo... | javascript|python|tensorflow|webpack|tensorflow.js | 1 |
374,170 | 57,342,970 | How to remove elements different than numbers of a Scipy Sparse Matrix? | <p>I have a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html" rel="nofollow noreferrer">COO sparse matrix</a> in which every element is a dictionary. I want to filter that matrix by some conditions, nevertheless when I try to multiply the matrix by the filter I get an exception... | <p>It is possible to filter a <code>coo_matrix</code>, nevertheless it isn't straightforward. First you must create your <code>filter mask</code> with `True/False' values and then use it to index the matrix's column, rows and data vectors.</p>
<pre><code>In [22]: mask = [True, False, False, True, False, False]
In [23... | python|numpy|scipy|sparse-matrix | 0 |
374,171 | 57,405,672 | How to get numpy.zeros() and (numpy.ones() * 255) to produce a black and white image respectively? | <p>I am new to Python + OpenCV, so this might be a basic question for most of you, as I couldn't find a good/ satisfactory solution for this online.</p>
<p>So I am trying to create an Image by separately creating R-G-B layers<br>
R - Layer of 0s<br>
G - Layer of 255s<br>
B - Layer of 255*Identity matrix</p>
<pre><cod... | <p>Try using</p>
<pre><code>Blue = np.eye(6, dtype = int) * 255
plt.imshow(Blue, cmap='gray', vmin=0, vmax=255)
plt.show()
</code></pre>
<p>for more reference <a href="https://stackoverflow.com/questions/3823752/display-image-as-grayscale-using-matplotlib">this answer</a></p> | python|numpy|opencv|matplotlib | 5 |
374,172 | 57,659,946 | Python: how to find right combination between two pandas dataframe? | <p>I have two dataframes <code>df1</code> and <code>df2</code>. </p>
<p><code>df1</code> contains the information of the link between an <code>ID</code> and a <code>Code</code></p>
<pre><code>df1
ID Code
0 48 3
1 47 2
2 50 0
3 49 1
</code></pre>
<p><code>df2</code> contains the informa... | <p>You need to perform merge with selective columns from the referenced <code>df2</code>. After that, you can concat the merged results. </p>
<pre><code>m1 = df1.merge(df2.reset_index(), left_on=['ID', 'Code'], right_on=['index', 'Code1'])[['ID', 'Code', 'd1']].rename(columns={'d1': 'd'})
m2 = df1.merge(df2.reset_inde... | python|pandas | 0 |
374,173 | 24,438,273 | Aggregation on pandas datetime series only returns as datetime series | <p>I have a dataframe like</p>
<pre><code>test = pd.DataFrame({'date': ['2013-10-14 21:46:40', '2013-07-17 02:55:06', '2013-01-28 20:25:17'], 'category': [1, 1, 2]})
test['date'] = pd.to_datetime(test['date'])
category date
0 1 2013-10-14 21:46:40
1 1 2013-07-17 02:55:06
... | <p>use <code>'size'</code>; this is currently an API bug (in that the <code>len</code> should just be translated directly to <code>size</code>), see <a href="https://github.com/pydata/pandas/issues/7570" rel="nofollow">here</a></p>
<pre><code>In [5]: test.groupby('category')['date'].agg(['size', min, max])
Out[5]:
... | python|datetime|numpy|pandas | 2 |
374,174 | 24,107,440 | Python Pandas calucate Z score of groupby means | <p>I have a dataframe like this:</p>
<pre><code>df = pd.DataFrame({'Year' : ['2010', '2010', '2010', '2010', '2010', '2011', '2011', '2011', '2011', '2011', '2012', '2012', '2012', '2012', '2012'],
'Name' : ['Bob', 'Joe', 'Bill', 'Bob', 'Joe', 'Dave', 'Bob', 'Joe', 'Bill', 'Bill', 'Joe', 'Dave', 'Da... | <p>There is a <code>zscore</code> functionality in <code>scipy</code>, but be careful the default delta-degree-of-freedom is 0 in <code>scipy.stats.zscore</code>:</p>
<pre><code>In [171]:
import scipy.stats as ss
S=(df[df.Year == '2010'].groupby(['Year', 'Name'])['Score'].mean())
pd.Series(ss.zscore(s, ddof=1), S.inde... | python-2.7|pandas|group-by | 1 |
374,175 | 24,195,815 | Averaging time series of different lengths | <p>I have a number of lists (time series)</p>
<pre><code>dictionary = {'a': [1,2,3,4,5], 'b': [5,2,3,4,1], 'c': [1,3,5,4,6]}
</code></pre>
<p>that I would like to average on another:</p>
<pre><code>merged = {'m': [2.33,2.33,3.66,4.0,4.0]}
</code></pre>
<p>Is there a smart way to find this?</p>
<p>What if the lists... | <p>Given that you tagged this with numpy and scipy, I'm assuming it's OK to use scientific python functions. A terse way to accomplish the first task is then</p>
<pre><code>$ ipython --pylab
>>> dictionary = {'a': [1,2,3,4,5], 'b': [5,2,3,4,1], 'c': [1,3,5,4,6]}
>>> map(mean, np.array(dictionary.valu... | python|numpy|scipy | 2 |
374,176 | 24,007,762 | Python Pandas - Using to_sql to write large data frames in chunks | <p>I'm using Pandas' <code>to_sql</code> function to write to MySQL, which is timing out due to large frame size (1M rows, 20 columns).</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html<... | <p>Update: this functionality has been merged in pandas master and will be released in 0.15 (probably end of september), thanks to @artemyk! See <a href="https://github.com/pydata/pandas/pull/8062">https://github.com/pydata/pandas/pull/8062</a></p>
<p>So starting from 0.15, you can specify the <code>chunksize</code> a... | python|mysql|sql|pandas|sqlalchemy | 29 |
374,177 | 24,028,281 | Pandas series operations very slow after upgrade | <p>I am seeing a huge difference in performance between pandas 0.11 and pandas 0.13 on simple series operations.</p>
<pre><code>In [7]: df = pandas.DataFrame({'a':np.arange(1000000), 'b':np.arange(1000000)})
In [8]: pandas.__version__
Out[8]: '0.13.0'
In [9]: %timeit df['a'].values+df... | <p>This was a very odd bug having to do (I think) with a strange lookup going on in cython. For some reason</p>
<pre><code>_TYPE_MAP = { np.int64 : 'integer' }
np.int64 in _TYPE_MAP
</code></pre>
<p>was not evaluating correctly, ONLY for <code>int64</code> (but worked just fine for all other dtypes). Its possible the... | python|pandas | 2 |
374,178 | 24,071,202 | Improve the speed of loop performance | <p>I am trying to build a sample for my Markov chain Monte Carlo code using <strong>pyMC</strong>. So with the sampled parameters of the model, each time the output is built by calling <code>getLensing</code> <strong>instance</strong> from <strong>nfw class</strong> and compared to the observed data. My problem is that... | <p>Here is some code. I'd be amazed if the timings went from 60 to 59 minutes though.</p>
<pre><code>import numpy as np
z_h=0.15
z=np.arange(z_h, 1.5,0.001) #start the range from what you need (not exactly
z=z[1:] # needed because you said if (z[i]>z_h), range gives (z[i]>=z_h)
value=np.array([])
for j in rang... | numpy|scipy|multiprocessing|cython|pymc | 0 |
374,179 | 43,834,533 | How to quantize the values of tf.Variables in Tensorflow | <p>I have a training model like</p>
<pre><code>Y = w * X + b
</code></pre>
<p>where Y and X are output and input placeholder, w and b are the vectors<br>
I already know the value of w can only be 0 or 1, while b is still tf.float32.<br><br>
How could I quantize the range of variable w when I define it?<br>
or<br>
Can... | <p>There is no way to limit your variable during the activation. But what you can do is to limit it after each iteration. Here is one way to do this with <a href="https://www.tensorflow.org/api_docs/python/tf/where" rel="noreferrer"><code>tf.where()</code></a>:</p>
<pre><code>import tensorflow as tf
a = tf.random_uni... | variables|tensorflow|rate | 6 |
374,180 | 43,596,570 | convert pandas lists into dummy variables | <p>I have a pandas dataFrame which contains list of variables which I want to convert to dummy variables. Basically I want to convert:</p>
<p><a href="https://i.stack.imgur.com/weBPw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/weBPw.png" alt="enter image description here"></a></p>
<p>to this:</p>
<p><a... | <pre><code>df = pd.DataFrame({0: [['hello', 'motto'], ['motto', 'mania']]})
print(df)
0
0 [hello, motto]
1 [motto, mania]
</code></pre>
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.join.html" rel="noreferrer"><strong><code>str.join</code></strong></a> follo... | pandas | 9 |
374,181 | 43,532,878 | Pandas bins with additional bin of ==0 | <p>I am trying to use the pandas bins with the range like below</p>
<pre><code>tipBins = [1,5,10,15,20,25,30].
</code></pre>
<p>Also for some rides tip would be zero that doesn't fall under any range.
How to supply that value zero in the pandas bins.I need a partition of bins like below</p>
<pre><code>==0
1-5
5-10
1... | <p>If you are sure the <em>tipPercentage</em> won't contain any negative numbers, you can add a negative number in the <code>tipBins</code>, for instance:</p>
<pre><code>tipBins = [-1,1,5,10,15,20,25,30]
</code></pre>
<p><em>Example</em>:</p>
<pre><code>v = [0, 4, 7, 20, 26]
tip_data_names = ["No Tip", '1-5','5-... | python|pandas|numpy|dataframe | 1 |
374,182 | 43,728,629 | TensorFlow Saver unworked | <p>I am trying to save all variables of the model, but instead the error "<em>FailedPreconditionError: Attempting to use uninitialized value beta1_power</em>" raised.
I havn't defined beta1_power variable. I don't know what it is.</p>
<pre><code>saver = tf.train.Saver()
saver.save(save_path="/home/eldmitro/MNIST",ses... | <p>You should first initialize the variables then to save them. You can initialize the variables either by restoring form a checkpoint or</p>
<pre><code>sess.run(global_variables_initializer())
</code></pre>
<p>You cannot save variables being uninitialized. </p>
<p>Then do this: </p>
<pre><code>saver = tf.train.Sav... | python|python-2.7|machine-learning|tensorflow|computer-vision | 0 |
374,183 | 43,783,280 | Python Compare 2 CSV's delete differences | <p>I have 1 CSV that is heavily manipulated, it looks something like this:</p>
<p><code>"ID","Vulnerability","Report Category","IP","DNS","NetBIOS","OS",
"x","Title","Category Type","x.x.x.x","DNS Name","Net Name","Windows"</code></p>
<p>The 2nd CSV looks like this:</p>
<p><code>"IP","DNS","NetBIOS","OS","Title","x.... | <p>You already know you can use pandas so just load both csv files into dataframes and then join the tables and delete where they match.</p>
<p>For example:</p>
<pre><code>csv2 = pd.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14]})
csv1 = pd.DataFrame(data = {'col1' : [1, 3, 4], 'col2' : [10... | python|python-3.x|pandas | 0 |
374,184 | 43,763,117 | Python Pandas If value in column D equals Windows Print Server | <p>I have a table that looks like this<br/>
"IP","DNS","NetBIOS","OS"<br/>
"x.x.x","name","name","Windows 2012"<br/>
"x.x.x","name","name","HP JetDirect"<br/> </p>
<p>I am trying to find a way using Pandas to have the code look in the OS column, if it equals "Windows" (anything after the "Windows" does not matter), i... | <p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a>:</p>
<... | python|python-3.x|pandas | 1 |
374,185 | 43,711,311 | How to calculate class scores when batch size changes | <p>My question is at the bottom, but first I will explain what I am attempting to achieve.</p>
<p>I have an example I am trying to implement on my own model. I am creating an adversarial image, in essence I want to graph how the image score changes when the epsilon value changes.</p>
<p>So let's say my <code>model</c... | <p>You can choose to not choose a batch size by setting it to <code>None</code>. That way, any batch size can be used.</p>
<p>However, keep in mind that this non-choice could com with <a href="https://stackoverflow.com/questions/42547456/are-there-any-downsides-of-creating-tensorflow-placeholders-for-variable-sized-v"... | python-3.x|matplotlib|machine-learning|tensorflow | 1 |
374,186 | 43,735,722 | KNN Algorithm from scratch python | <p>I am trying to execute a KNN algorithm from scratch, but I am getting a really strange error saying "KeyError: 0"</p>
<p>I assume this implying I have an empty dictionary somewhere, but I don't understand how that can be. I might just add for the sake of clarity that the data works fine in the black box KNN algorit... | <p>EDIT: You may have an extra character at the beginning of your csv files. Try specifying the encoding in the read_csv() calls. See "encoding" in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.... | python|algorithm|pandas|machine-learning|knn | 0 |
374,187 | 43,754,344 | Tensorflow Auto Tagging | <p>I want to know how to make an auto-tagging for images.</p>
<p>I have tried tensorflow and trained the model several times.
For start, It was quite good for classification.
But now, I need to do auto-tagging.</p>
<p>Using tensorflow the prediction sum result will be always 1.</p>
<p>For example something like this... | <p>Take a look at the last layer you made. As you say the sum of your predictions is always one, this sounds like you applied softmax (<a href="https://en.wikipedia.org/wiki/Softmax_function" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Softmax_function</a>).
If you remove this, you get activations for ever... | image|image-processing|tensorflow|tagging | 0 |
374,188 | 43,754,753 | Resample a MultiIndexed Pandas DataFrame and apply different functions to columns | <p>In the case where you do not have MultiIndexed columns, you can do <code>df.resample(freq).agg(some_dict)</code> where some_dict is in the form <code>{column_name: function}</code> in order to apply a different function to each column (See demonstration below or see <a href="https://stackoverflow.com/questions/10020... | <p>I just came up with an idea that works using <code>apply</code> with a <code>lambda</code></p>
<pre><code>In [1]:
df.resample('H').apply(lambda x: agg_dict[x.name](x))
Out[1]:
A B
one two one two
2017-01-01 00:00:00... | python|python-3.x|pandas|numpy|dictionary | 2 |
374,189 | 43,722,660 | Extend lists within a pandas Series | <p>I have a pandas series that looks like this: </p>
<pre><code>group
A [1,0,5,4,6,...]
B [2,2,0,1,9,...]
C [3,5,2,0,6,...]
</code></pre>
<p>I have similar series that I would like to add to the existing series by extending each of the lists. How can I do this?</p>
<p>I tried</p>
<pre><code>for x in ser... | <p>Consider the series <code>s</code></p>
<pre><code>s = pd.Series([[1, 0], [2, 2], [4, 1]], list('ABC'), name='group')
s
A [1, 0]
B [2, 2]
C [4, 1]
Name: group, dtype: object
</code></pre>
<p>You can extend each list with a similar series simply by adding them. <code>pandas</code> will use the underlying... | python|pandas | 5 |
374,190 | 43,691,241 | Can not fetch an image from mnist tfrecord using tf-slim framework | <p>I used DatasetDataProvider to get an image from tfrecord. I can 'print(image)', but when using 'sess.run(image)' to fetch it, the program seem to fall into a infinite loop. I have no knowledge of whether I have make a mistake.</p>
<p>print(image) get</p>
<pre><code> Tensor("Reshape_3:0", shape=(28, 28, 1), dtype=... | <p>The <code>slim.dataset_data_provider</code> uses TensorFlow <a href="https://www.tensorflow.org/programmers_guide/threading_and_queues" rel="nofollow noreferrer">input queues</a> under the hood. Therefore, it's important to (after creating your session) add the following 2 lines to kick off the queue runners:</p>
<... | tensorflow | 3 |
374,191 | 43,689,633 | Enabling XLA JIT from tf.slim | <p>One way of turning on the Tensorflow XLA JIT is to use <code>tf.OptimizerOptions.ON_1</code> flag, by passing it to the TF session, similar to the following lines in python:</p>
<pre><code>config = tf.ConfigProto()
config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
sess = tf.Sessio... | <p><code>slim.learning.train</code> takes a <code>session_config</code> argument to which you can pass the <code>ConfigProto</code>.</p> | python|tensorflow | 3 |
374,192 | 43,651,802 | How to Combine 2 integer columns in a dataframe and keep the type as integer itself in python | <p>I have 2 columns df[year] and df[month]. It has values ranging from 2000 to 2017 and month values 1 - 12.</p>
<p>How to combine these to another column which would contain the combined output.</p>
<p>Eg: </p>
<pre>Year Month Y0M
2000 1 200001
2000 2 200002
2000 3 200003
2000 10 200010
</pre... | <p>Maybe something like <code>df[year] * 100 + df[month]</code> would help.</p> | python|pandas|dataframe | 3 |
374,193 | 43,605,963 | How to join 2 cell in 1 cell in header? | <p><a href="https://i.stack.imgur.com/LsDl2.png</img" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LsDl2.png</img" alt="enter image description here"></a></p>
<p>Above is my dataframe, and I wish to get this out put on header</p>
<p><a href="https://i.stack.imgur.com/wYSlr.png" rel="nofollow no... | <p>You can use:</p>
<pre><code>a = ['201701', '', '201705', '', '201707']
b = ['PHI', 'Actual', 'Actual', 'PHI', 'Actual']
data = [[np.nan, np.nan, np.nan, 8, np.nan]]
df = pd.DataFrame(data, index=['ClassCold'], columns = pd.MultiIndex.from_arrays([a,b]))
print (df.columns)
MultiIndex(levels=[['', '201701', '201705',... | python|pandas | 2 |
374,194 | 43,680,870 | Feed CNN features to LSTM | <p>I want to build an end-to-end trainable model with the following proprieties:</p>
<ul>
<li>CNN to extract features from image</li>
<li>The features is reshaped to a matrix</li>
<li>Each row of this matrix is then fed to LSTM1</li>
<li>Each column of this matrix is then fed to LSTM2</li>
<li>The output of LSTM1 and ... | <p>Consider building your CNN model with Conv2D and MaxPool2D layers, until you reach your Flatten layer, because the vectorized output from the Flatten layer will be you input data to the LSTM part of your structure.</p>
<p>So, build your CNN model like this:</p>
<pre><code>model_cnn = Sequential()
model_cnn.add(Con... | tensorflow|keras|lstm | 0 |
374,195 | 43,802,038 | Writing dataframe to csv column wise | <p>I need to write a dataframe to a csv file, for that I've done the following:</p>
<pre><code>..............................................
temp_df = pd.DataFrame(variance.values,df.columns.values)
temp_df.to_csv('var.csv')
...................................
</code></pre>
<p>this working fine, but I still need one... | <pre><code>In [129]: df
Out[129]:
col1 col2
0 Feature0 2.665797e+04
1 Feature1 4.025351e+04
2 Feature2 3.221147e+09
3 Feature3 2.777271e-02
4 Feature4 5.959389e+00
5 Feature5 2.665600e+02
6 Feature6 7.342482e+02
7 Feature7 3.073636e+02
8 Feature8 5.667790e-04
9 Feature9 5.205740e-04
... | python|csv|pandas | 2 |
374,196 | 43,551,015 | stop gradient with n/a label in tensorflow | <p>I'm implementing a Convolutional Neural Network in Tensorflow with python.
I'm in the following scenario: I've got a tensor of labels <strong>y</strong> (batch labels) like this:</p>
<pre><code>y = [[0,1,0]
[0,0,1]
[1,0,0]]
</code></pre>
<p>where each row is a <strong>one-hot</strong> vector that r... | <p>If you don't want some samples to contribute to the gradients you could just avoid feeding them to the network during training at all. Simply remove the samples with that label from your training set.</p>
<p>Alternatively, since the loss is computed by summing over the KL-divergences for each sample, you could mult... | python|tensorflow|conv-neural-network | 2 |
374,197 | 43,693,969 | Flatten xml into pandas dataframe, deeply nested | <p>I'm thinking this might be very easy, and I simply not figured it out yet.</p>
<p>The objective is to 'flatten' into a pandas DataFrame.</p>
<p><a href="https://www.gleif.org/lei-files/20170427/GLEIF/20170427-GLEIF-concatenated-file.zip" rel="nofollow noreferrer">Here is one xml</a> (A direct download of a 60~ MB ... | <p>I was facing a similar problem. I had xml from ebscohost about research articles returned from a search.</p>
<p>Using xmltodict <a href="https://github.com/martinblech/xmltodict" rel="nofollow noreferrer">https://github.com/martinblech/xmltodict</a></p>
<pre><code>import xmltodict
with open(filename) as fd:
d... | python|xml|pandas | 4 |
374,198 | 43,791,970 | Pandas: assigning columns with multiple conditions and date thresholds | <p>Edited:</p>
<p>I have a financial portfolio in a pandas dataframe df, where the index is the date and I have multiple financial stocks per date.</p>
<p>Eg dataframe:</p>
<pre><code>Date Stock Weight Percentile Final weight
1/1/2000 Apple 0.010 0.75 0.010
1/1/2000 IBM 0.011 0.4 0
1/1/... | <p>This solution is more explicit and less pandas-esque, but it involves only a single pass through all rows without creating tons of temporary columns, and is therefore possibly faster. It needs an additional state variable, which I wrapped it into a closure for not having to make a class. </p>
<pre><code>def closure... | python|pandas|dataframe|finance|portfolio | 6 |
374,199 | 43,574,675 | how to perform the equivalent of a correlated subquery in pandas | <p>I have a CSV file from the Kaggle Titanic competition as follows. The record format of this file is described by the following columns:
PassengerId, Survived, Pclass, Name, Sex, Age, SibSp, Parch, Ticket, Fare, Cabin, Embarked.
I want to analyze the data in this file and check whether passengers traveling in a gro... | <p>Let's see if this matches:</p>
<pre><code>df.groupby(['Ticket']).filter(lambda x: x.Ticket.count()>1)[['Ticket','PassengerId','Survived']]
</code></pre>
<p>Or with Jezrael's suggestion:</p>
<pre><code>df.groupby(['Ticket']).filter(lambda x: len(x)>1)[['Ticket','PassengerId','Survived']]
</code></pre>
<p>I ... | python|pandas | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.