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 |
|---|---|---|---|---|---|---|
351,800 | 62,118,763 | How to get the column names with value more than ZERO as the multilabels for each row | <p>I have a case where I have label names as columns of a DataFrame with value 0 or more like below.</p>
<pre><code>.net 2007 actionscript-3 activerecord air ajax
0 0 0 0 1 1 1
1 0 0 0 1 1 1
2 0 0 0 1 1 1
3 2 2 2 2 0 0
4 2 2 2 2 0 0
5 2 2 2 ... | <p>You can try this using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply</code></a></p>
<pre><code>df.apply(lambda x:' '.join(x.index[x!=0]) , axis=1)
</code></pre>
<p>Or
<code>df.T</code> is short hand for <code>df.transpose</... | python|pandas|data-science|multilabel-classification | 4 |
351,801 | 62,416,093 | Cannot import .csv file via pd.read_csv due to UTF-8 errors | <p>I tried a lot of solution both in R and Python and gave up.</p>
<p>I am trying to read a huge .csv file (1.6 GB). </p>
<p>I cannot even import it with <code>pandas</code> (managed to import with R). </p>
<p><a href="https://i.stack.imgur.com/yCP86.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com... | <p>you may need to include encoding = "ISO-8859-1" </p>
<p>for your reference:
<a href="https://stackoverflow.com/questions/18171739/unicodedecodeerror-when-reading-csv-file-in-pandas-with-python">UnicodeDecodeError when reading CSV file in Pandas with Python</a></p> | python|pandas|csv|import|utf-8 | 1 |
351,802 | 62,453,253 | Tensorboard add_image shows green image red | <p>I encountered a quite weird problem. After running some images through my neural network and trying to display the segmentation as follows:</p>
<pre><code>print(label.shape)
</code></pre>
<blockquote>
<p>torch.Size([1, 3, 321, 321])</p>
</blockquote>
<p>Now displaying the image with matplotlib shows everything ... | <p>I was facing this problem because, in the dataloader I was modifying my output labels to have a particular standard deviation and mean. But tensorboard is unaware of this modification to your labels.<br />
<strong>Solution</strong><br />
Before passing your image to <code>writer_semisuper.add_image</code>, you need ... | python|pytorch|tensorboard | 0 |
351,803 | 62,042,750 | Tensorflow Extended(TFX) code runs fine on Google Colab, but throws error when running on a local machine | <p>I have the following code using Tensorflow Extended(TFX)</p>
<pre><code>from tfx.utils.dsl_utils import csv_input
from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
examples = csv_input(os.path.join(base_dir, 'data/simple'))
example_gen = CsvExampleGen(input=examples);
</code></pre>
<p... | <p>Please use the latest version(0.29.0) available for tfx.
Working code to resolve the issue :-</p>
<pre><code>import os
import tfx
from tfx.utils.dsl_utils import external_input
from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
import tempfile
import urllib
_data_root = tempfile.mkdtemp(... | tensorflow|tfx | 0 |
351,804 | 62,439,483 | How to use or install pycocoevalcap? | <p>I'm new to use coco Datasets .. i got this error </p>
<pre><code># this requires the coco package, Link
from pycocoevalcap.bleu.bleu import Bleu
from pycocoevalcap.rouge.rouge import Rouge
from pycocoevalcap.cider.cider import Cider
ModuleNotFoundError: No module named 'pycocoevalcap'
</code></pre>
<p>i dow... | <p>So I used this command:</p>
<pre><code> pip install "git+https://github.com/salaniz/pycocoevalcap.git"
</code></pre>
<p>and it returned</p>
<pre><code> Collecting git+https://github.com/salaniz/pycocoevalcap.git
Cloning https://github.com/salaniz/pycocoevalcap.git to /tmp/pip-req-build-3u0sbfzy
Running... | python|tensorflow|module|pip|pycocotools | 3 |
351,805 | 62,088,372 | For loop to merge pandas dataframe with common columns | <p>I have 25 data frames, each of them have 7 ascending dates(as rows) and between 570-600 airport names as columns. The big problem is that, since the dataframes store the number of ascensions each airport has each day, the weeks that certain airports are inactive results in the dataframes having different orders and ... | <p>IIUC, You can try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat</code></a> along with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><code>df.sort_index... | python|pandas|dataframe | 2 |
351,806 | 62,320,080 | Custom convolutions and none type object in keras custom layer for gating operation | <p>I am trying to implement gated pooling layer in keras and this will need to first find the max and average pooling of the layer. After that it computes a region wise parameter using the same trainable mask across all the depth dimensions.</p>
<p>For example if input is size (batch, 28, 28, 6), the max and average p... | <p>this seems to work...</p>
<pre><code>class Gated_pooling(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(Gated_pooling, self).__init__(**kwargs)
self.mask = self.add_weight(name='mask', shape=(2,2,1,1),
initializer='truncated_normal',
... | python|tensorflow|keras|customization | 1 |
351,807 | 62,244,936 | How to find row and column of nonzero element in pandas dataframe | <p>I have a pandas dataframe which looks like this:</p>
<pre><code>Type All Fail Pass
A 0 0 0
B 1 0 0
C 0 0 0
</code></pre>
<p>Now, I want to get the column name of the nonzero element as well as the corresponding value in the <code>Type</code> col... | <p>See if this helps,</p>
<pre><code>df = df.set_index("Type")
result = df.where(df.select_dtypes(include="number") > 0) \
.fillna("") \
.to_dict(orient='index')
print({k:i for k, v in result.items() for i, j in v.items() if j})
</code></pre>
<p>output,</p>
<pre><code>{'B': 'All'}
</code></pre> | python|pandas | 1 |
351,808 | 62,432,059 | PANDAS find exact given string/word from a column | <p>So, I have a pandas column name <strong>Notes</strong> which contains a sentence or explanation of some event. I am trying find some given words from that column and when I find that word I am adding that to the next column as <strong>Type</strong></p>
<p>The problem is for some specific word for example <strong>Li... | <p>Use <code>\b</code> for word boundary in <code>regex</code>, and <code>.str.extract</code> to find pattern:</p>
<pre><code> df.Notes.str.extract(r'\b(lies|liar)\b')
</code></pre>
<p>To label those rows containing that word, do:</p>
<pre><code>df['Type'] = np.where(df.Notes.str.contains(r'\b(lies|liar)\b'), 'Lies... | python|pandas|text-mining | 1 |
351,809 | 62,286,178 | Create custom buckets for df based on column | <p>I want to add a new column with custom buckets (see example below)based on the price values in the price column.</p>
<ul>
<li><code>< 400 = low</code></li>
<li><code>>=401 and <=1000 = medium</code></li>
<li><code>>1000 = expensive </code></li>
</ul>
<p>Table</p>
<pre><code>product_id price
2 ... | <p><code>pandas</code> has it's own <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a> method. Specify the right bin edges and the corresponding labels.</p>
<pre><code>df['price_category'] = pd.cut(df.price, [-np.inf, 400, 1000, np.inf],
... | python|pandas|jupyter-notebook | 4 |
351,810 | 62,408,401 | Use variables to add columns in pandas dataframe | <p>I want to add columns according to my variables.
Like this:</p>
<pre><code>for key in areadict:
for key2 in methoddict:
df[key + key2] = ''
</code></pre>
<p>I want to use the combination of key and key2 as the name of the new columns.</p>
<p>And after adding columns, can I access the value by df[key+k... | <p>I made up two dicts to show you the behaviour:</p>
<pre><code>areadict = {'one': 1, 'two': 2, 'three': 3}
methoddict = {'_one': 11, '_two': 22, '_three': 33}
df = pd.DataFrame([0, 0, 0])
for key in areadict:
for key2 in methoddict:
df[key + key2] = areadict[key]
</code></pre>
<p>gives us:</p>
<pre><... | python|pandas|dataframe | 0 |
351,811 | 62,220,132 | Filtering Pandas Dataframe by the ending of the string | <p>I have a data frame called df and in one column 'Properties' I have listed properties of some product. These properties are a single sentence. Some of them have the same ending i.e. stock.</p>
<p>I was trying to do something like:</p>
<pre><code>df.loc[df['Properties'][-6:] == 'stock']
</code></pre>
<p>to filter ... | <p>Try this:</p>
<pre><code>df = df[df['Properties'].str.endswith('stock')]
</code></pre>
<p>If you want to try what you were trying, this would work:</p>
<pre><code>df = df[df['Properties'].str[-5:]=='stock']
</code></pre> | python|pandas|dataframe|sorting|filter | 4 |
351,812 | 62,200,366 | Unable to use FeatureColumn with category column in Keras Functional API | <p>I am using Keras Functional API from Tensorflow 2.2 to build a model that uses features columns. I followed the guide <a href="https://towardsdatascience.com/how-to-build-a-wide-and-deep-model-using-keras-in-tensorflow-2-0-2f7a236b5a4b" rel="nofollow noreferrer">here</a> and tutorial <a href="https://www.tensorflow.... | <p>There is no need to pass <code>Inputs</code> in the code, x = <code>layers.DenseFeatures(feature_columns)</code> because <code>feature_columns</code> already comprises the <code>Feature Columns</code> corresponding to all the <code>Features</code>.</p>
<p>Complete working code for Training the Model with <code>hear... | python|tensorflow|machine-learning|keras|tensorflow2.x | 0 |
351,813 | 62,371,709 | how to perform conditional area plotting with matplotlib? | <p>I have created the following dataframe based on a range of data.</p>
<pre><code>df['data_classification'] = df.myDatarange.apply(lambda a:'Very good' if a>=-90
else ('Good' if (a>= -100 or a<=-91)
else ('Moderate' if (a&g... | <p>Seaborn's <a href="https://seaborn.pydata.org/generated/seaborn.barplot.html" rel="nofollow noreferrer">barplot</a> can take a <code>hue</code> parameter to color each bar corresponding to the 'data_classification'. The new 'data_classification' column can be created quicker and easier to modify via <a href="https:/... | python|pandas|matplotlib|seaborn | 1 |
351,814 | 62,439,124 | How to save a new sheet to the beginning of an existing excel workbook? | <p>I found part of the answer from this post and it was very useful
<a href="https://stackoverflow.com/a/42375263/13765378">https://stackoverflow.com/a/42375263/13765378</a></p>
<p>However, every time I ran this code with new data, a new sheet gets added to the end of a workbook.
After a while, it is quite an effort t... | <p>This will help you.use the second line.this uses openpyxl module
help link <a href="https://openpyxl.readthedocs.io/en/stable/tutorial.html" rel="nofollow noreferrer">https://openpyxl.readthedocs.io/en/stable/tutorial.html</a></p>
<pre><code>ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
ws2 = wb.c... | excel|pandas|load|openpyxl | 0 |
351,815 | 62,310,407 | What are possible reasons that validation error doesn't change but train loss decreases? | <p>I use pre-trained ResNet to extract 1000 dimensional features for each image, then put these images into my self-built net to do classification tasks and use triplet loss function.</p>
<p>There is a part of my code:</p>
<pre><code>class Network(torch.nn.Module):
def __init__(self,n_feature = 1000, n_hidden_1 =... | <p>Seems your model is not able to generalise to val set. Which means the model is unable to find the differences between (anchor, positive) vs (anchor, negative). In such case, distance of (anchor, positive) - distance of (anchor, negative) ~= 0. And since your margin is set to be 1. The <strong>loss will stay at 1</s... | machine-learning|deep-learning|neural-network|pytorch | 0 |
351,816 | 62,364,639 | Recode in Python using the dictionary approach? | <p>I'm pretty new to python and I'm trying to work out how to use the dictionary for recoding a variable into a new one.</p>
<p>I'm looking to recode the existing values of 1 and 2 into 1 and 3 and 4 into 2:</p>
<pre><code>recode1 = {1 : 1, 2 : 1, 3 : 2, 4 : 2}
df['recode'].map(recode1)
</code></pre>
<p>It looks like a... | <pre><code>recode1 = {1 : 1, 2 : 1, 3 : 2, 4 : 2}
recode1[1]=recode1[1]
recode1[3]=recode1[2]
recode1[2]=recode1[4]
recode1
{1: 1, 2: 2, 3: 1, 4: 2}
</code></pre> | pandas | -1 |
351,817 | 62,372,828 | Apply a function on one dataframe using another | <p>I want to calculate distance of the members using node A and node B info provided in the other data frame.
Here's the code:</p>
<pre><code>import pandas as pd
import numpy as np
import math
def length(a, b):
x1 = nodes.loc[a]['x']
x2 = nodes.loc[b]['x']
y1 = nodes.loc[a]['y']
y2 = nodes.loc[b]['y']... | <p>You need to change multiple things actually as shown below:</p>
<pre><code>import pandas as pd
import numpy as np
import math
def length(a, b):
x1 = nodes[nodes['node'] == a]['x'].values[0]
x2 = nodes[nodes['node'] == b]['x'].values[0]
y1 = nodes[nodes['node'] == a]['y'].values[0]
y2 = nodes[nodes... | python|python-3.x|pandas | 0 |
351,818 | 62,216,861 | Python numpy error: only integer scalar arrays can be converted to a scalar index | <p>I'm trying to simulate a simple pendulum using pylot. For that, I created the class Pendulum and, in one of the methods, I keep getting the same error. </p>
<pre><code>def __init__(self, L = 1, M = 1, G = 9.8, origin = (0, 0), init = [60, 0]):
self.init_state = np.array(init, dtype = 'float')
self.params = ... | <p>The traceback shows that the error occurs in this line (from your code)</p>
<pre><code>File "C:\Users\Lucas\Desktop\Estudos\Python\Simple Pendulum.py", line 27, in
position x = np.cumsum(self.origin[0], L*np.sin(self.state[0]))
</code></pre>
<p>I don't see that use of <code>cumsum</code> in your code sample! The... | python|numpy | 0 |
351,819 | 62,415,540 | How to insert data into a existing dataframe, replacing values according to a conditional | <p>I'm looking to insert information into a existing dataframe, this dataframe shape is 2001 rows × 13 columns, however, only the first column has information.</p>
<p>I have 12 more columns, but these are not the same dimension as the main dataframe, so I'd like to insert this additional columns into the main one usin... | <p>Without a minimal working example it is hard to provide you with clear recommendations, but I think what you are looking for is the <code>.loc</code> a pd.DataFrame. What I would recommend you doing is the following:</p>
<ul>
<li>Selection of rows with <code>.loc</code> works better in your case if the dates are fi... | python|python-3.x|pandas|dataframe|conditional-statements | 0 |
351,820 | 62,271,262 | Creating list of list from row of others matrix | <p>I'm trying to create list from existing matrix:</p>
<pre><code>a = matrix([[ 0, 0, 0, ..., 82, 140, 165],
[ 0, 0, 0, ..., 30925, 30830, 27075],
[ 0, 0, 0, ..., 628, 678, 528],
...,
[ 0, 0, 0, ..., 988, 930, 878],
... | <pre><code>a = np.matrix([[1, 2, 3],
[12, 9, 0],
[2, 45, 2]])
b = np.matrix([[12, 9, 0],
[2, 67, 94],
[2, 45, 2]])
x = [list(t) for t in zip(a.tolist(),b.tolist())]
print(x)
Out:
[[[1, 2, 3], [12, 9, 0]], [[12, 9, 0], [2, 67, 94]], [[2, 45, 2], [2, 45, 2]]]
</co... | python|list|numpy|matrix | 0 |
351,821 | 62,445,039 | How to change the index of all the 1 in an 2d numpy array which only has 0s and 1s? | <p>I have a 2d numpy array(arr) which only has 0s and 1s.</p>
<p>For example, a 2d numpy array in shape(h,w).</p>
<p>I want to resize the array to shape(h // scale, w // scale), and I need to keep all the 1s.</p>
<pre class="lang-py prettyprint-override"><code># arr is a 2d numpy array
h, w = arr.shape
h_new, w_new ... | <p>Just reshape the array by splitting each dimension to grid <code>(SIZE // SCALE, SCALE)</code>. Next reduce all dimensions of size SCALE using <code>max()</code> to let <code>1</code> dominate the SCALExSCALE cell.</p>
<pre><code>arr.reshape(h//scale, scale, w // scale, scale).max(axis=(1,3))
</code></pre>
<p>Note... | python|python-3.x|numpy | 0 |
351,822 | 62,232,547 | Removing float values from lists within a Pandas Column | <p>I have a pandas dataframe with a column where each value is a list of elements. A combination of string and nan values (Which is indicating as dtype: float). Here are the first two elements: </p>
<pre><code>1 [nan, JavaScript, nan, nan, nan, nan, nan, nan...
2 [Java, nan, nan, nan, nan, nan, SQL, nan, nan,..... | <p>You can try a list comprehension with <code>pd.notnull()</code> </p>
<pre><code>df['cleaned_col_name'] = [[e for e in i if pd.notnull(e)] for i in df['col_name']]
</code></pre>
<p>Or create a dataframe from the column and <code>stack()</code> then aggregate back as list</p>
<pre><code>df['cleaned_col_name'] = pd.... | python|pandas|numpy | 0 |
351,823 | 62,249,864 | groupby python formatting output | <p>I am new to Python and learning a lot of new things everyday!.</p>
<p>I am running a group by code in pandas as follows and just noticed something interesting:-</p>
<pre><code>df = pd.DataFrame({'Hospital' : ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', 'C'],"Claim Type" : ['HHA', 'HS... | <p>When you put this <code>[{'avg spend'}]</code> you are basically passing a <code>set</code> inside []. Like @Che3steR pointed out, you need to pass a list <code>[['avg spend']]</code>. They both give the same result:</p>
<pre><code>df = df.groupby(['Hospital','Claim Type']).mean()[{'avg spend'}].round(2)
print(df)
... | python|pandas|group-by | 0 |
351,824 | 62,266,141 | NumPy: Create a multidimensional array from an iterable | <p>I have an iterable of tuples, and I'd like to build an <code>ndarray</code> from it. Say that the shape would be <code>(12345, 67890)</code>. What would be an efficient and elegant way to do so?</p>
<p>Here are a few options, and why I ruled them out:</p>
<ol>
<li><p><code>np.array(my_tuples)</code> starts allocat... | <p>Define a generator:</p>
<pre><code>def foo(m,n):
for i in range(m):
yield list(range(i,i+n))
</code></pre>
<p>timing several alternatives:</p>
<pre><code>In [93]: timeit np.array(list(foo(3000,4000)))
1.74 s ± 17.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)... | python|arrays|numpy | 1 |
351,825 | 62,433,979 | Using Pandas Series, Numpy Arrays and Python Lists efficiently | <p><strong>The task</strong>: I have a a series of daily closing stock prices and I want to achieve the following:
(i) Compute maximum percentage change between any two days within any 5-day window
(ii) Store these maximums on a 5-day rolling window basis
(iii) Compute 99th percentile of these maximums over all 5-day r... | <p>A couple of suggenstions:</p>
<ol>
<li><p>create <code>numpy</code> array from list:</p>
<p><code>my_max = np.vstack(my_max)</code><br>
potentially hstack, not sure about the dimensionality</p></li>
<li><p>use <code>numpy</code> also for quantiles:</p>
<p><code>print(np.quantile(my_max, 0.99, axis=?)</code><br>
a... | python|pandas|numpy|numpy-ndarray | 1 |
351,826 | 62,231,365 | How to generate a random number of a numpy array? | <p>There is a <code>numpy array</code> like following numpy array. I want to generate a random <code>integer</code> number for specific <code>string</code> of the numpy array.. How can I do this task?</p>
<pre><code># input
X = np.array([['a', 'p', 'b'],
['a', 'p', 'd'],
['c', 'p', 'd'],
... | <p>As you want to assign a random integer values for each unique value of the array, you can map the unique values to a dictionary.</p>
<p><strong>Update</strong></p>
<p>We need to create check if the random number is used as a value of the mapper. </p>
<pre><code>from random import randint
import numpy as np
# in... | python|list|numpy | 1 |
351,827 | 51,378,646 | Get the last value of the day in a datetimeindexed dataframe filtering by other column values | <p>I am having a dataframe like this:</p>
<pre><code>data= {'Timestamp': ['2018-07-16 14:31:03','2018-07-13 11:59:50','2018-07-13 11:41:07','2018-07-13 10:50:24','2018-07-12 15:33:59','2018-07-12 11:32:52','2018-07-04 13:10:30','2018-07-04 10:37:15' ],
'Maturity': [2019,2019, 2020,2020,2020,2020, 2021,2021],
... | <p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Grouper.html" rel="nofollow noreferrer"><code>Grouper</code></a> and <a href="http:/... | python-3.x|pandas|dataframe|filter|grouping | 1 |
351,828 | 51,494,516 | dataframe merger column operation | <p>I got a dataframe like this:</p>
<pre><code>A B C
1 1 1
2 2 2
3 3 3
4 1 1
</code></pre>
<p>I want to 'merge' the three columns to form a D column, the rule is: if there is at least one '1' in the row, then the value of D is '1' else is '0'. How can I achieve it?</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a> for compare values with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow noreferrer"><code>DataFrame.any</code></... | python|pandas|dataframe | 1 |
351,829 | 51,304,809 | 2d array as index in Pytorch | <p>I want to ‘grow’ a matrix using a set of rules. </p>
<p>Example of rules: </p>
<pre><code>0->[[1,1,1],[0,0,0],[2,2,2]],
1->[[2,2,2],[2,2,2],[2,2,2]],
2->[[0,0,0],[0,0,0],[0,0,0]]
</code></pre>
<p>Example of growing a matrix: </p>
<pre><code>[[0]]->[[1,1,1],[0,0,0],[2,2,2]]->
[[2,2,2,2,2,2,2,2,2],[... | <p>You could consider using <a href="https://pytorch.org/docs/master/torch.html#torch.index_select" rel="nofollow noreferrer"><code>torch.index_select()</code></a>, flattening your index tensor before reshaping the result:</p>
<p><strong>Code:</strong></p>
<pre class="lang-python prettyprint-override"><code>import to... | python|numpy|matrix|indexing|pytorch | 2 |
351,830 | 51,463,559 | Trying to understand why a compare does not work but a filter does (Panda) | <pre><code>dfclean = dfclean[dfclean['Count'] > 1]
</code></pre>
<p>I used this to clean out 'Count' values of < 1 from a data frame. The column 'Count' had vales from 0-3It worked well.</p>
<pre><code>dfsorted = dfbottom.groupby("ST").filter(lambda dfbottom:dfbottom.shape[0] > 1)
</code></pre>
<p>I used th... | <p>There is problem <code>.count</code> aggregate DataFrame.</p>
<p>Solution is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for return <code>Series</code> with same size as original <code>Dat... | python|pandas | 1 |
351,831 | 51,507,156 | How to succinctly map over a plane with numpy | <p>I have written code to plot the average squared error of a linear function over a given dataset, to visualise progress during a gradient descent training for the optimum regression line.</p>
<p>The relevant bits are these:</p>
<pre><code>def compute_error(f, X, Y):
e = lambda x, y : (y - f(x))**2
return su... | <p>I don't fully follow what you're trying to achieve here. However, this may help get you started with a numpy solution:</p>
<pre><code>X, Y = generate_random_data(slope=target_slope, intercept=target_intercept, n=180)
M, B = np.mgrid[-mn:+mn:1/density, -bn:+bn:1/density]
f = M.T*X + B.T
error = np.sum((f-Y)**2)
</c... | python|numpy | 1 |
351,832 | 51,235,708 | Parsing string to datetime while accounting for AM/PM in pandas | <p>I am trying to parse a string in this format <code>"2018 - 07 - 07 04 - AM"</code>
to pandas datetime using strftime format. However, It seems to me the format doesn't recognize the difference between <code>AM</code> and <code>PM</code>.</p>
<p>Here is what I tried:</p>
<pre><code>pd.to_datetime("2018... | <p>Since you're parsing a 12-hour time format, you will need <code>%I</code> instead of <code>%H</code>, otherwise the <code>%p</code> specifier has no effect.</p>
<pre><code>pd.to_datetime("2018 - 07 - 07 04 - PM", format='%Y - %m - %d %I - %p')
Timestamp('2018-07-07 16:00:00')
</code></pre>
<p>This behaviour is doc... | python|pandas|date|datetime | 24 |
351,833 | 51,232,664 | Pandas convert datatime format | <p>I have a pandas dataframe with a column of datetime object with the following format: </p>
<pre><code>df['TIME_M']=pd.to_datetime(df['TIME_M'],format='%Y%m%d %H:%M:%S.%f')
</code></pre>
<p>However, at the same time, I also want a column of datetime with the following format (without the %f): </p>
<pre><code>%Y%m%... | <p>First if need datetimes format is a bif different like need - <code>YYYY-MM-DD HH:MM:SS</code>.</p>
<p>If need datetimes without <code>%f</code> add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>floor</code></a>:</p>
<pre><code>df['TIME_... | python|pandas|datetime | 2 |
351,834 | 51,116,957 | Issues populating dictionary with float values from Excel Pandas | <p>I'm using an excel spreadsheet to populate a dictionary. Then I'm using those values to multiply the values of another data frame by reference, but it gives me errors when I try. I decided to make the excel spreadsheet out my dictionary to avoid errors, but I haven't been successful. I'm doing this because the dicti... | <p>There is problem some values outside of dictionary <code>d</code> (error say <code>R6B</code>, but there is possible more values), so not possible convert to floats.</p>
<p>You can find this value(s):</p>
<pre><code>#create Series from all Zone columns
vals = df.filter(like ='ZONE').replace(d).stack()
#for non num... | python|excel|pandas|dictionary|dataframe | 1 |
351,835 | 51,302,275 | Getting the wrong answer using Tensorflow's Premade Estimator for Linear Regression | <p>I am new to stack overflow and tensorflow. I was trying to redo the simple linear regression from Introduction to Machine Learning (Andrew Ng's Coursera class) using the premade linear regression estimator.</p>
<p>I've coded the linear regression model in python using numpy and scikit-learn and successfully found ... | <p>The Introduction to Machine Learning course did a batch gradient descent using all of the training examples at each iteration and then used multiple iterations to converge. The code above would only use one training example (batch=1) and the number of iterations (steps) is forever (based on tf.estimator.LinearRegre... | python|tensorflow|machine-learning|linear-regression | 0 |
351,836 | 51,479,146 | I am trying to convert all the .bin files in a folder to .txt files in Python | <p>I am trying to convert all the .bin files in a folder to .txt file in Python,
This is what I tried</p>
<pre><code> import glob
import errno
path = 'Dir_path'
files = glob.glob(path)
for name in files:
if name.endswith("bytes.bin"):
with open(name) as f:
data = np.... | <p>I think the issue is in:</p>
<pre><code> np.savetxt(r'name', df.values, fmt='%d')
</code></pre>
<p>All txt files are saved under the same filename <code>name</code>, and because of overwriting only the last file will be available on the disk.</p>
<p>You could change that to:</p>
<pre><code> ... | python|pandas|numpy|dataframe | 1 |
351,837 | 51,381,290 | How to calculate time difference between two pandas column | <p>My df looks like,</p>
<pre><code> start stop
0 2015-11-04 10:12:00 2015-11-06 06:38:00
1 2015-11-04 10:23:00 2015-11-05 08:30:00
2 2015-11-04 14:01:00 2015-11-17 10:34:00
4 2015-11-19 01:43:00 2015-12-21 09:04:00
print(time_df.dtypes)
start datetime64[ns]
stop datetime64[ns]
... | <p>You need omit <code>pd.Timedelta</code>, because difference of times return timedeltas:</p>
<pre><code>df_time['td'] = df_time['stop']-df_time['start']
print (df_time)
start stop td
0 2015-11-04 10:12:00 2015-11-06 06:38:00 1 days 20:26:00
1 2015-11-04 10:23:00 2015-11-... | python|pandas|dataframe|data-analysis | 4 |
351,838 | 51,340,573 | How to access dataset on Google ML Cloud Engine | <p>How to access my local dataset on jupyter notebook on google ML cloud engine?</p>
<p>I have created a VM on Google ML Cloud engine and also installed anaconda on the same VM.</p>
<p>How to access public and private image dataset from jupyter notebook?</p>
<p>I have uploaded very small dataset using upload button ... | <p>You may want to look into using <code>gsutil</code> that comes as part of the GCP SDK. This tool enables you to move local data to Google Cloud Storage so you can then access it through your notebooks.</p> | google-cloud-platform|jupyter-notebook|cloud|google-cloud-ml|tensorflow-datasets | 0 |
351,839 | 51,316,723 | How to reorder timestamps in multiple columns into a single column python | <p>I am trying to sort <code>timestamps</code> across multiple <code>columns</code> in a <code>pandas</code> <code>df</code> into a single time ordered <code>column</code>. </p>
<p>So for the df below I'd like to combine these to create one column </p>
<pre><code>import pandas as pd
d = ({
'' : ['Bar','Foo','Fub... | <p>IIUC</p>
<pre><code>df.columns=['',1,2,3]
df.melt('')
Out[99]:
variable value
0 Bar 1 8:00
1 Foo 1 8:29
2 Fubar 1 8:58
3 Bar 2 8:30
4 Foo 2 8:59
5 Fubar 2 9:28
6 Bar 3 9:00
7 Foo 3 9:29
8 Fubar 3 10:00
</... | python|pandas|sorting|dataframe|merge | 1 |
351,840 | 51,378,987 | Groupby two columns and print different quantiles as seperate columns | <p>Here is a reproducible example:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([['Type A', 'Event1', 1, 2, 3], ['Type A', 'Event1', 4, 5, 6], ['Type A', 'Event1', 7, 8, 9],
['Type A', 'Event2', 10, 11, 12], ['Type A', 'Event2', 13, 14, 15], ['Type A', 'Event2', 16, 17, 18], \
['Type B', 'Event1', 19, 20, 21]... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>:</p>
<pre><c... | python|python-3.x|pandas|pandas-groupby | 4 |
351,841 | 51,124,066 | CoxPHFitter: The input must have at least 3 entries | <p>I am trying to run <code>lifelines</code>' CoxPHFitter (python3) and i get this value error:</p>
<blockquote>
<p>The input must have at least 3 entries!</p>
</blockquote>
<p>i've read the function it connects to at stats but im not sure how to imply the error to the data i have so i could run it propely.
anybody wa... | <p>That problem happens in <a href="https://github.com/scipy/scipy/blob/master/scipy/stats/mstats_basic.py#L412" rel="nofollow noreferrer">https://github.com/scipy/scipy/blob/master/scipy/stats/mstats_basic.py#L412</a>, which lifelines uses as a pre-fitting check. According to the code, the input must have atleast leng... | pandas|statsmodels|cox-regression | 0 |
351,842 | 51,300,956 | How to split a string and assign as column name for a pandas dataframe? | <p>I have a dataframe which has a single column like this:</p>
<pre><code> a;d;c;d;e;r;w;e;o
--------------------
0 h;j;r;d;w;f;g;t;r
1 a;f;c;x;d;e;r;t;y
2 b;h;g;t;t;t;y;u;f
3 g;t;u;n;b;v;d;s;e
</code></pre>
<p>When I split it I am getting like this:</p>
<pre><code> 0 1 2 3 4 5 6 7 8
----------------------... | <p>I think need create new <code>DataFrame</code> by <code>expand=True</code> parameter and then assign new columns names:</p>
<pre><code>res = df.iloc[:,0].str.split(';', expand=True)
res.columns = df.columns[0].split(';')
print (res)
a d c d e r w e o
0 h j r d w f g t r
1 a f c x d e r t... | python|pandas|dataframe|series | 3 |
351,843 | 51,209,020 | epoch nanoseconds to normal time | <p>i have a data as </p>
<pre><code>name time
0 acn 1530677359000000000
1 acn 1530677363000000000
2 acn 1530681023000000000
3 acn 1530681053000000000
4 acn 1530681531000000000
5 acn 1530681561000000000
</code></pre>
<p>So I would like to change the <code>time</code> column to <code>datet... | <p>Vectorised, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a> with <code>unit='ns'</code>.</p>
<pre><code>df['datetime'] = pd.to_datetime(df['time'], unit='ns')
print(df)
name time ... | python|python-2.7|pandas|datetime|epoch | 3 |
351,844 | 51,453,073 | How to gradually train with more and more classes? | <p>I'm trying to create an incremental classifier that will get trained on data containing n classes for some set number of epochs, then n+m classes for a set number of epochs, then n+m+k, etc, where each successive set of classes contains the previous set as a subset.</p>
<p>In order to do this without having to trai... | <p>The error occurs because <code>tf.cond</code> takes a decision based on a single boolean — much like an <code>if</code> statement. What you want here is to make a choice per element of your tensor.</p>
<p>You could use <code>tf.where</code> to fix that problem, but then you will run into another one, which is that ... | python|tensorflow | 1 |
351,845 | 51,334,010 | Understanding DeprecationWarning errors when performing conditional indexing on a NumPy array (version 1.11.13, Python 2.7) | <p>I don't understand Deprecation Warning errors when performing conditional indexing on Numpy arrays and would appreciate some clarification, hoping that it will also benefit to the community. Let's consider a NumPy array called 'block', containing integers from 1 to 12:</p>
<pre><code>block = np.arange(1,13)
</code>... | <p>The correct code for what you're doing is:</p>
<pre><code>selection = block[~np.isin(block, [1, 4, 7])]
</code></pre> | python|numpy|indexing|numpy-slicing | 1 |
351,846 | 51,526,356 | Warning of divide by zero encountered in log2 even after filtering out negative values | <p>We get the error - "divide by zero encountered in log2"
if the value is less than zero. I am facing the error even when I exempt the non-positive values using where statement.</p>
<pre><code>a = pd.Series([1,0,5,6,8])
np.where(a<=0, 1, np.log2(a))
</code></pre> | <p>When you are computing the values that should be substituted when values in <code>a</code> are non-positive, <code>log2</code> is called and applied to <code>a</code>. This doesn't really affect your output though. To suppress this error, you could replace non-positive values with 1 first, and perform <code>log2</co... | python-3.x|python-2.7|pandas|numpy|series | 2 |
351,847 | 51,238,112 | GroupBy and aggregate function in Pandas | <p>I have a time series dataset as below. I would like to split this into multiple 20s bins, get the min and max timestamps in each bin and add a flag to each bin based on whether there is at least 1 successful result <em>(success: result = 0; failed: result = 1)</em></p>
<pre><code>data = [{"product": "abc", "test_t... | <p>Unstack <code>outptut_2</code> and then concatenate the two outputs:</p>
<pre><code>output_2 = (
output_2
.unstack(fill_value=0)
.rename(columns={0 : 'success', 1 : 'failed'}))
df = (pd.concat([output_1.test_tstamp, output_2], axis=1, keys=['test_tstamp', 'result'])
.assign(flag=output_2.... | python|pandas|pandas-groupby | 1 |
351,848 | 51,448,587 | How to randomly pick a certain amount of rows in CSV files and keep the others | <p>Say that I have a thousand rows of data in a csv file, each with 4 columns.</p>
<p>I'd like to randomly pick 950 rows of the data and keep the other 50 rows separately. I will further process these two datasets using python.</p>
<p>How do I do that in an easy way?</p>
<p>I use pandas to read in the csv files by c... | <p>The following should do the trick:</p>
<pre><code>train_file = "training_data_ez.csv"
train_features = pd.read_csv(train_file, usecols=['var', 'sq', 'sin'])
</code></pre>
<p>The <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.sample.html" rel="nofollow noreferrer"><code>pd.D... | python|python-3.x|pandas|csv | 4 |
351,849 | 51,389,216 | how to determine if a cell has multiple values and count the number of occurences | <p>I have a table as below where i need to count the number of times the type column has more than one value in it.</p>
<p>My logic at the moment is to go through each time and check if the type cell has more than one value in it and place a counter but i am not sure how to code this in Python correctly. </p>
<p><a h... | <p>Maybe you should try this one:</p>
<pre><code>df=pd.DataFrame({'type':['big,green','big','small,red']})
for i in df['type']: print(len(i.split(',')))
</code></pre> | python|pandas|multi-index | 0 |
351,850 | 51,325,032 | Converting exponential notation numbers to strings - explanation | <p>I have <code>DataFrame</code> from <a href="https://stackoverflow.com/q/51321769/2901002">this question</a>:</p>
<pre><code>temp=u"""Total,Price,test_num
0,71.7,2.04256e+14
1,39.5,2.04254e+14
2,82.2,2.04188e+14
3,42.9,2.04171e+14"""
df = pd.read_csv(pd.compat.StringIO(temp))
print (df)
Total Price test_nu... | <p>When you use pd.read_csv to import data and do not define datatypes,
pandas makes an educated guess and in this case decides, that column
values like "2.04256e+14" are best represented by a float value.</p>
<p>This, converted back to string adds a ".0". As you corrently write,
converting to int64 fixes this.</p>
<... | python|pandas|casting|floating-point|integer | 1 |
351,851 | 51,278,861 | Count occurrences in a Pandas series of floats | <p>I have a DataFrame:</p>
<pre><code>df.head()
Index Value
0 1.0,1.0,1.0,1.0
1 1.0,1.0
2 1.0,1.0
3 3.0,3.0,3.0,3.0,3.0,3.0,4.0,4.0
4 4
</code></pre>
<p>I'd like to count the occurren... | <p>Use <code>map</code> to floats and last columns to <code>integers</code>:</p>
<pre><code>df_counts = (df['Value'].apply(lambda x: pd.Series(Counter(map(float, x.split(',')))), 1)
.fillna(0)
.astype(int)
.rename(columns=int))
print (df_counts)
... | python|pandas|counter|series | 2 |
351,852 | 51,330,981 | How to extract the output of tensorflow model? | <p>I've been trying to train a model as usual with train/test data. I was able to have my accuracy, cost + the valid accuracy and cost. So I presume that the model is working and the result is enough with an 85%.</p>
<p>Now, after I finished with my train/test data, I have a csv file with the same type and structure of... | <p>The placeholder 'z' has nothing in it and nothing is assigned to it. So when you run the session, nothing needs to be done because 'z' depends on nothing in the model. I think you want,</p>
<pre><code>output =sess.run(y,feed_dict={x: y_pred})
</code></pre>
<p>Because 'y' is the output tensor.</p>
<p>Having said t... | python|tensorflow|machine-learning|python-3.6 | 1 |
351,853 | 51,525,031 | Apply filter and replace on same column together on pandas dataframe | <p>Below is sample dataframe</p>
<pre><code>df = pd.DataFrame([["aa_1_a", 9],["bb_2_b", 2], ["3_c", 7], ["dd_4_d", 5]], columns=['A', 'B'])
>>> df
A B
0 aa_1_a 9
1 bb_2_b 2
2 3_c 7 <-- invalid row based on some regex
3 dd_4_d 5
</code></pre>
<p>on column A I need to perform some regax... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><strong><code>pandas.Series.str.extract</code></strong></a> and then drop null rows:</p>
<pre><code>df.assign(A=df.A.str.extract(r'[a-z]{2}\_(\d+)\_[a-z]')).dropna()
A B
0 1 9
1 2 2... | python|pandas|dataframe | 5 |
351,854 | 51,242,338 | Parallelizing keras models in R using doParallel | <p>I'm trying to ensemble several neural networks using keras for R. In order to do so, I would like to parallelize the training of the different networks by using a <strong><em>"foreach"</em></strong> loop. </p>
<pre><code>models <- list()
x_bagged <- list()
y_bagged <- list()
n_nets = 2
bag_frac <-0.7
l... | <p>Although this question is quite old, I got the same issue so I'm posting the solution here. The problem is that the Keras model object can not be transferred to the workers before being serialised. A quick workaround would be to serialise the models before sending them to the workers and then unserialising them on t... | r|tensorflow|foreach|keras|doparallel | 4 |
351,855 | 51,269,276 | Dataframe is and object rather than a normal dataframe? | <p>I created a dataframe from the sum of another dataframe rows, but the result is an object, so I can't do any calculation with it. I'm using pandas in Jupyter.</p>
<p>Here is my code:</p>
<pre><code>df_sum = pd.DataFrame()
df_sum['Suma'] = df_consumption.groupby(['Country','Category'])['Mult'].agg('sum')
df_sum['Su... | <p>If you just want to convert it to a dataframe object, you can try using df_sum = df_sum.to_frame()</p> | python|pandas|jupyter-notebook|jupyter | 0 |
351,856 | 51,151,945 | How to reshape a 4d numpy array for training a model | <p>I am trying to train my already compiled CNN and LSTM model. However I keep getting the error </p>
<blockquote>
<p>ValueError: Error when checking input: expected
time_distributed_151_input to have 5 dimensions, but got array with
shape (4732, 32, 32, 3)</p>
</blockquote>
<p>My model summary looks a bit like... | <p>You can use this piece of code:</p>
<pre><code>x = np.array([[4732, 32, 32, 3]])
x.reshape(x.shape[0],-1)
</code></pre>
<p>I hope it works.</p> | python|arrays|numpy|tensorflow|lstm | 0 |
351,857 | 51,268,386 | Sum matrix elements group by indices in Python | <p>I have two matrix (same row and column): one with float values, which are grouped by indices in the other matrix. As a result, I want a dictionary or a list with the sums of the elements for each index.
Indices always start at 0.</p>
<pre><code>A = np.array([[0.52,0.25,-0.45,0.13],[-0.14,-0.41,0.31,-0.41]])
B = np.... | <p>You can make use of <strong><code>bincount</code></strong> here:</p>
<pre><code>a = np.array([[0.52,0.25,-0.45,0.13],[-0.14,-0.41,0.31,-0.41]])
b = np.array([[1,3,1,2],[3,0,2,2]])
N = b.max() + 1
id = b + (N*np.arange(b.shape[0]))[:, None] # since you can't apply bincount to a 2D array
np.sum(np.bincount(id.ravel(... | python|numpy|matrix|sum|indices | 3 |
351,858 | 51,153,854 | How to fix json_normalize when it cannot iterate over column to flatten? | <p>I have a dataframe that looks like this:</p>
<pre><code>ID phone_numbers
1 [{u'updated_at': u'2017-12-02 15:29:54', u'created_at': u'2017-12-0
2 15:29:54', u'sms': 0, u'number': u'1112223333', u'consumer_id':
12345, u'organization_id': 1, u'active': 1, u'deleted_at':
N... | <p>Use list comprehension with flatenning and adding new element <code>ID</code> to dictionary:</p>
<pre><code>df = pd.DataFrame({'ID': [1, 2], 'phone_numbers': [[{'a': '2017', 'b': '2017', 'sms': 1},
{'a': '2018', 'b': '2017', 'sms': 2}],
... | python|json|pandas | 6 |
351,859 | 51,424,857 | Numpy random seed valid for entire jupyter notebook | <p>I'm using functions from <code>numpy.random</code> on a Jupyter Lab notebook and I'm trying to set the seed using <code>numpy.random.seed(333)</code>. This works as expected only when the seed setting is in the same notebook cell as the code. For example, if I have a script like this:</p>
<pre><code>import numpy as... | <p>Because you're repeatedly calling randint, it generates different numbers each time. It's important to note that seed does not make the function consistently return the same number, but rather makes it such that the same <strong>sequence</strong> of numbers will be produced if you repeatedly run randint the same amo... | python|numpy|jupyter-notebook | 7 |
351,860 | 51,485,353 | Get count of duplicated values per category/group in pandas python | <p>I have a df1 like this:</p>
<pre><code>Type Name Identifier Number Amount
A xx 0001 12 0.89
xx 0001 56 0.78
zz 0002 33 0.56
yy 0020 44 0.45
yy 0020... | <p>IIUC, you can use this method. Filter the dataframe down to the duplicates, then groupby with nunique and sum, lastly, divide the two columns.</p>
<pre><code>df_out = df1[df1.duplicated(subset=['Type','Identifier'], keep=False)]\
.groupby('Type')['Identifier','Amount']\
.agg({'Identifier'... | python|pandas|dataframe|pandas-groupby | 1 |
351,861 | 51,425,127 | Pandas - Go through 2 columns (latitude and longitude) and find the distance between each coordinate and a specific place | <p>I have a data frame (called coordinates) containing 3 columns: index, Latitude, Longitude - it has roughly 1,000 rows. I have the coordinates of a specific place and want to find the distance between the place and all the coordinates in the data frame. Currently, I can use geopy.distance to find the distance between... | <p>See here a variation on the one of <a href="https://stackoverflow.com/users/1325117/sechilds">sechilds</a>. The <code>site_coords</code> are an input to the def. The apply function now uses 2 arguments: the <code>row</code> from the DataFrame and <code>site_coords</code>:</p>
<pre><code>import pandas as pd
import ... | python|pandas | 4 |
351,862 | 51,484,410 | Most efficient algorithm in Python to generate all 6x6 (0,1) matrices with sum in columns and rows lower than 2? | <p>I am working on a problem which requires me to find all 6x6 (0,1) matrices with some given properties:</p>
<ul>
<li>The sum of a row/column must be lower than 2.</li>
<li>The matrices are not symmetrical.</li>
</ul>
<p>I am using this code:</p>
<pre><code>import numpy as np
import itertools as it
n=6
li=[]
for ... | <p>You have trouble with your math, because if the row/column sum is less than 2, it could be <code>0</code> or <code>1</code> -- that means that in every row/column can be only one non-zero elememt, which is <code>7^6 = 117649</code> possible matrices.</p>
<p>100k matrices is pretty much doable by using a brute force... | python|algorithm|numpy|matrix | 2 |
351,863 | 48,197,555 | TF difference between including or not including optimizer in session run | <p>I have the following code (only 2 iterations and I am not retrieving new batchs in the below code for simplicity):</p>
<pre><code>for i in range(2):
if (i % reset_point) != 0 or i == 0:
char_id_batch, word_id_batch, pos_id_batch = Reader.retrieve_batch_sent(start, batch_size_counter, remote_or_not)
... | <p>First, <strong>note</strong>: you haven't shown the definition of <code>train_op</code>, <code>predicted_output</code>, or <code>accuracy</code>, so I am taking an educated (though fairly confident) guess at what these ops actually are in my answer below. But if you have defined them unusually, please refine the co... | tensorflow | 0 |
351,864 | 48,344,549 | How can I extract the indices from a pandas.DataFrame where values intersect another dataframe? | <p>I have two pandas dataframes:</p>
<pre><code>import pandas as pd
friends = pd.dataframe({
'name' : ['Alice', 'Jim', 'Edward'],
})
everyone = pd.dataframe({
'name' : ['Edward', 'Conrad', 'Lucy', 'Jim', 'Frank', 'Alice', 'Sam']
})
</code></pre>
<p>I can get a list of my friends, in the 'everyone' order, wi... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a><code>with</code>swapped indices with values:</p>
<pre><code>d = everyone['name'].to_dict()
d = {v:k for k, v in d.items()}
friends['everyone_id'] = friends['name'].map(d... | python|pandas|dataframe|indexing | 1 |
351,865 | 48,325,859 | Subclass pandas DataFrame with required argument | <p>I'm working on a new data structure that subclasses pandas DataFrame. I want to enforce my new data structure to have new_property, so that it can be processed safely later on.
However, I'm running into error when using my new data structure, because the constructor gets called by some internal pandas function with... | <p>This question has been answered by a brilliant pandas developer. See <a href="https://github.com/pandas-dev/pandas/issues/19300" rel="noreferrer">this issue</a> for more details. Pasting the answer here. </p>
<pre><code>class MyDataFrame(pd.DataFrame):
@property
def _constructor(self):
return MyData... | pandas|dataframe|subclass | 5 |
351,866 | 48,208,180 | Pandas: Combine subsetting and filtering | <p>Let's say that I have the following data frame.</p>
<pre><code>df = pd.DataFrame({'group':list('aaaabbbb'),
'hour':[1,3,3,2,5,6,6,2],
'id':[1,1,2,2,2,3,3,3]})
df
</code></pre>
<p>What I'd like to do is find the most common (mode) unique hour per group.</p>
<p>The following ge... | <p><code>value_count</code> is the way , but you can also try <code>mode</code></p>
<pre><code>df.loc[df.hour==3, ['group','hour']].groupby(['group']).hour.apply(lambda x : x.mode()).reset_index()
Out[519]:
group level_1 hour
0 a 0 3
</code></pre> | python|pandas | 2 |
351,867 | 48,175,842 | Pandas: function that uses multiple columns | <p>My dataframe df1:</p>
<pre><code>date, country, category, score, value
2017-01-01, US, 123, 555, 232.02
2017-01-01, US, 223, 10, 22.02
</code></pre>
<p>I have a lookup dataframe df2:</p>
<pre><code>category, factor_score_0_100, factor_score_101_500, factor_score_501_1000
123, 2.0, 3.0, 4.0
223, 5.4, 4.3, 3.2
</co... | <p>A little bit hack to get that using <code>IntervalIndex</code> + <code>lookup</code></p>
<pre><code>df2=df2.set_index('category')
df2.columns=df2.columns.str.split('_',expand=True)
idx=pd.IntervalIndex.from_arrays(df2.columns.get_level_values(2).astype(int),df2.columns.get_level_values(3).astype(int),closed='both')... | python|pandas | 0 |
351,868 | 48,361,263 | Solving linear equations in Python (not working using linalg.solve) | <p>Probably this is a very beginner question. I am new to python and such operation. But would appreciate any help.
I am trying to solve a system of linear equations in Python, using numpy linalg.</p>
<p>x+y+z = 2 </p>
<p>2x-6y-z=-1 </p>
<p>3x-2z=8</p>
<p>I tried to use linalg.solve() function </p>
<pre><code>a = ... | <p>The matrix <code>a</code> describing the left-hand side of the equation is set up the wrong way around;</p>
<pre><code> np.linalg.solve(a.T, b)
</code></pre>
<p>does what you want to do with the given <code>a</code>.</p>
<p>That your second approach does the job boils down to the fact that for any 2-dimensional <... | python|numpy|scipy|linear-algebra|algebra | 4 |
351,869 | 48,015,136 | Create new GeoJSON LineString from JSON objects using a property | <p>I would like to combine several Json objects into a GeoJSON feature collection with LineStrings</p>
<p>For example I have the following badly formatted json objects:</p>
<pre><code> {"lat":16.0269337,"lon":40.073042,"score":1,"ID":"13800006252028","TYPES":"Regional","N2C":"2","NAME":"Strada Statale della Val Sinni... | <p>I'm not an expert, but here's a first cut. <a href="https://gis.stackexchange.com/questions/220997/pandas-to-geojson-multiples-points-features-with-python">This post</a> was helpful to get the basics. There are probably more elegant approaches than mine to the each of the "Geo", "JSON", and pandas manipulation piec... | python|json|pandas|geojson|geopandas | 0 |
351,870 | 48,056,977 | Pandas merge TypeError: object of type 'NoneType' has no len() | <p>I'm experimenting with pandas merge left_on and right_on params.
According to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noreferrer">Documentation 1</a> and <a href="https://pandas.pydata.org/pandas-docs/stable/merging.html" rel="noreferrer">Documentation 2</a><... | <p>It seems you need:</p>
<pre><code>df = pd.merge(left_frame, right_frame, how='right', on='key')
</code></pre>
<p>because same left and right column names.</p>
<p>If columns names are different:</p>
<pre><code>df = pd.merge(left_frame, right_frame, how='right', right_on='key1', left_on='key2')
</code></pre>
<blockquo... | python|pandas | 12 |
351,871 | 47,991,005 | pandas combine group by and rows to columns | <p>I'm trying to transform this dataset:</p>
<pre><code>A B C
1 x1 a
1 x1 a
1 x1 b
2 x2 b
2 x2 a
</code></pre>
<p>into: </p>
<pre><code>A B C1 C2 C3
1 x1 a a b
2 x2 b a null
df = pd.DataFrame({ 'A': [1, 1, 1, 2, 2],
'B': ['x1', 'x1', 'x1', 'x2', 'x2'],
... | <p>Use <code>groupby</code> + <code>apply</code> -</p>
<pre><code>v = df.groupby(['A' ,'B']).C.apply(lambda x: x.tolist())
df = pd.DataFrame(v.tolist(), index=v.index)\
.rename(columns=lambda x: x + 1)\
.add_prefix('C')\
.reset_index()
df
A B C1 C2 C3
0 1 x1 a a b
1 2 x2 b a ... | python|pandas | 4 |
351,872 | 48,084,971 | Search for specific string in multiple excel files | <p>I'm new to python, so bear with me on this one.
I want to make a script that searches within all excel files in a specific folder, to see if they contain an '@' sign. If it finds a match it should write to a log.txt files with the name of the excel file. I don't have the name of the excel files in advance.</p>
<p>S... | <p>You should read through <a href="https://pandas.pydata.org/pandas-docs/stable/text.html#testing-for-strings-that-match-or-contain-a-pattern" rel="nofollow noreferrer">Pandas - Working with Text Data</a> specifically the section on strings that match or contain a pattern.</p>
<p>Unfortunately you cannot search a Dat... | python|excel|python-3.x|pandas | 2 |
351,873 | 48,190,601 | conv2d on non-rectangular image in Tensorflow | <p>I have dataset of images which are half black in a upper triangular fashion, i.e. all pixels below the main diagonal are black.</p>
<p>Is there a way in Tensorflow to give such an image to a conv2d layer and mask or limit the convolution to only the relevant pixels?</p> | <p>If the black translates to 0 then you don't need to do anything. The convolution will multiply the 0 by whatever weight it has so it's not going to contribute to the result. If it's not you can multiply the data with a binary mask to make them 0.</p>
<p>For all black pixels you will still get any bias term if you h... | tensorflow|machine-learning|computer-vision|deep-learning|convolution | 2 |
351,874 | 48,317,641 | SQL like summarize reports using Python Pandas | <p>I often produce in R single statement summarize reports using dplyr as the following:</p>
<pre><code>a <- group_by(data,x)
b <- summarise(a,
# count distinct y where value is not missing
y_distinct = n_distinct(y[is.na(y) == F]),
# count distinct z where va... | <p>Try something like this:</p>
<pre><code>In [18]: df
Out[18]:
x y z
0 1 2.0 NaN
1 1 3.0 NaN
2 2 NaN 1.0
3 2 NaN 2.0
4 3 4.0 5.0
In [19]: def nulls(s):
...: return s.isnull().sum()
...:
In [23]: r = df.groupby('x').agg(['nunique','size',nulls])
In [24]: r
Out[24]:
y ... | python|pandas | 4 |
351,875 | 48,038,535 | Get the values of the upper triangle of a matrix with their indexes | <p>Suppose we have a distance matrix as following: </p>
<pre><code>array([[ 0. , 0.2039889 , 0.25030506, 0.56118992],
[ 0.2039889 , 0. , 0.39916797, 0.6909994 ],
[ 0.25030506, 0.39916797, 0. , 0.63389566],
[ 0.56118992, 0.6909994 , 0.63389566, 0. ]])
</code... | <p>For the <em>upper</em> triangle, use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.triu_indices.html" rel="nofollow noreferrer">triu_indices</a> with diagonal offset 1 to exclude the main diagonal (based on the suggestion by closetCoder): </p>
<pre><code>a = # your array
idx = np.triu_indices... | python|arrays|numpy|matrix | 1 |
351,876 | 48,320,588 | What is h5 model in Keras? | <p>I came across an h5 model in Keras for image recognition.
But I am not sure what does the file extension refers to.</p>
<p>Can anyone explain it to me?</p> | <p>You mean a HDF5/H5 file, which is a file format to store structured data, its not a model by itself. Keras saves models in this format as it can easily store the weights and model configuration in a single file.</p> | tensorflow|model|keras | 18 |
351,877 | 48,111,639 | What is the difference in global_variables_initializer() and initialize_all_variables()? | <p>In Tensorflow, what is the difference in <code>global_variables_initializer()</code> and <code>initialize_all_variables()</code>? I had used both methods to initialize the variables.</p> | <p>If you look at <a href="https://www.tensorflow.org/api_docs/python/tf/initialize_all_variables" rel="nofollow noreferrer">the docs</a>, you will see that they do the same, but <code>tf.initialize_all_variables</code> is now deprecated in favour of <code>tf.global_variables_initializer</code>.</p> | python|tensorflow | 1 |
351,878 | 48,004,114 | how to use SavedModelBuilder to export a nlp model | <p>I trained a <strong>nmt</strong> model and I want to export the model and deploy it on tensorflow serving. But I have some problems that confused me a few days: </p>
<ul>
<li>The trained model contains all the info that <strong>SavedModelBuilder</strong> needs, including meta graph and variables, so why should we ... | <h2>Update 2018-05-30</h2>
<p>This answer is wrong!
I found the wright way to export the model, and works well with tf serving.
Visit my fork of <code>tensorflow/nmt</code> at <a href="https://github.com/luozhouyang/nmt" rel="nofollow noreferrer">tensorflow/nmt</a>, or go to the pull request: <a href="https://github.c... | tensorflow|nlp|tensorflow-serving | 1 |
351,879 | 48,046,500 | Array in Pandas Dataframe | <p>I'm currently testing Google Search Console API data with Pandas.</p>
<p>The data is structured like this:</p>
<pre><code>'rows': [{
'impressions': 307.0,
'clicks': 79.0,
'position': 1.013029315960912},
{'keys': ['spring break 2018', 'https://zrce.eu/partykalender/big-beach-spring-break/']},
... | <p>It would seem a little preprocessing is needed to fix your data. Let's combine the adjacent records, so that the data in <code>keys</code> is also read in - </p>
<pre><code>y = data['rows']
for i, j in zip(y[::2], y[1::2]):
i.update(dict(zip(['keyword', 'url'], j['keys'])))
</code></pre>
<p></p>
<p>Now, read ... | python|json|pandas | 1 |
351,880 | 48,161,758 | Rounding up 5-min data to a complicated hourly basis | <p>I have my data as below:</p>
<pre><code>Timestamp Outbound Utilization (%)
11/22/2017 9:55 12.356965
11/22/2017 10:00 14.4424725
11/22/2017 10:05 19.44614625
11/22/2017 10:10 49.3823
11/22/2017 10:15 51.21698
11/22/2017 10:20 50.67409188
11/22/2017 10:25 14.89324375
11/22/2017 10:30 27.191617... | <p>First, convert <code>Timestamp</code> to <code>datetime</code> - </p>
<pre><code>df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
</code></pre>
<p>Now, set <code>Timestamp</code> as the index and call <code>resample</code> with a <code>base</code> argument which specifies the offset from the begi... | python|pandas|datetime | 1 |
351,881 | 48,151,024 | Parsing SAS datetime to pandas dataframe | <p>I'm loading a CSV that was produced with SAS into a pandas DataFrame. In order to parse the SAS times I created a parser function like this:</p>
<pre><code>def parse_date(d):
try:
date = dt.timedelta(seconds=int(d)) + dt.datetime(1960, 1, 1)
return date
except ValueError:
print("Ther... | <p>You can try editing you except to:</p>
<pre><code>def parse_date(d):
try:
date = dt.timedelta(seconds=int(d)) + dt.datetime(1960, 1, 1)
return date
except ValueError:
return pd.NaT
</code></pre> | python|pandas|datetime|sas | 0 |
351,882 | 48,010,586 | Why Tensorflow did not increased speed after GPU upgrade? | <p>I have Tensorflow 1.4 GPU version installed. Cuda8 is installed too.</p>
<p>I trained my pretty simple GAN network on MNIST data.
I have AMD FX 8320 CPU, 16Gb system memory and SSD hard drive.</p>
<p>It took about 17 seconds per epoch on GeForce 720 GPU with 1GB memory.
The training utilized about 25% of GPU and 9... | <p>If you are training a simple GAN network it is fairly likely that your old GPU was not the bottleneck in the first place. So, improving it had no effect. If the amount of work done per <code>sess.run()</code> call very small, the overheads (executing your Python code, copying the input data to GPU, starting and runn... | gpu|tensorflow | 1 |
351,883 | 48,062,996 | Assign values to columns based on conditions in a pandas dataframe | <p>I have the below dataset:</p>
<pre><code>device_id A B C Current Class
1 70 35 40 C
2 45 90 34 B
</code></pre>
<p>Now each device has a score within each class( A,B,C) and it is currently a part of a certain class. Based on the class for which it has the h... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow noreferrer"><code>idxmax</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<pre><code>... | python|pandas|conditional-statements | 1 |
351,884 | 48,243,818 | Display column name different from dictionary key name in Pandas? | <p>I am new to Pandas and see that there are numerous ways to change column headers.
For example, the <code>set_axis</code> command works like this : </p>
<pre><code>>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.arange(3),columns=['a'])
>>> df
a
0 0
1 ... | <p>The solution posted by @JohnE looks like the best way to go. </p>
<p>I also would like to use a format string, and so add a few more details here : </p>
<pre><code>import pandas
df = pandas.DataFrame({'a' : [1,2,3],'b' : [4,5,6]})
di = {'a' : 'A (J/K*kg)', 'b' : 'B (N/m^2)'}
fstr = {di["a"] : '{:6.2f}', di["b"]:'... | pandas | 5 |
351,885 | 48,158,746 | Returning the integral of a vector | <p>I am trying to create a function, which returns a vector and then integrating it element by element. This is what I have so far</p>
<pre><code>def int1(b):
j = 1
for q in range(0,len(alpha)):
j = j + alpha[q]*(b**q)
p = np.exp(-j);
inu = np.zeros(len(alpha))
for q in range(0,len(alpha)):... | <p>The first argument of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html" rel="nofollow noreferrer"><code>quad</code></a> must be a function, something that call be called. Something that you can put (0.1) after and it will make sense. Does <code>int1(b)[2](0.1)</code> make sense... | python|numpy|scipy | 0 |
351,886 | 48,338,971 | Find Duplicates limited to multiple ranges - pandas | <p>Suppose our problem can be simplified like this:</p>
<pre><code>df = pd.DataFrame()
df['C_rows'] = ['C1', 'C2', 'C3', 'C2', 'C1', 'C2', 'C3', 'C1', 'C2', 'C3', 'C4', 'C1']
df['values'] = ['customer1', 4321, 1266, 5671, 'customer2', 123, 7344,'customer3', 4321, 4444, 5674, 'customer4']
</code></pre>
<p>with the tab... | <p>You can use transform and duplicated i.e </p>
<pre><code>df['g'] = df['values'].astype(str).str.contains('[A-z]').cumsum()
df['is_dup'] = df.groupby('g')['C_rows'].transform(lambda x : x.duplicated().any())
C_rows values g is_dup
0 C1 customer1 1 True
1 C2 4321 1 True
2 C3 ... | python|pandas | 3 |
351,887 | 48,439,669 | How to speedup tensorflow compile time? | <p>I am doing some customization to the tensorflow core, so I am compiling it several times. Currently, my problem is that each compilation takes about 25 minutes and I would like to reduce the compile time.
Each time, I compile using the instruction at this <a href="https://www.tensorflow.org/install/install_sources" ... | <p>SSD will increase the speed of compiling too. And you can use bazel option is --jobs to define number of jobs to work at the same time.</p> | tensorflow|compiler-optimization | 0 |
351,888 | 47,989,173 | Get top N largest rows of every group in a pandas DataFrame | <p>i have a dataframe</p>
<pre><code>val1 val1 distance
100 200 1.5
100 300 5.2
100 234 3.7
200 100 1.6
200 600 4.8
</code></pre>
<p>i want to find Top 2 distance rows for every <code>val1</code>.
i'e</p>
<p>for every <code>val1</code> get the top 2 minimu... | <p>It seems I was overanalysing your question, but a simple <code>sort_values</code>, followed by <code>groupby</code> + <code>head</code> should give you what you need.</p>
<pre><code>df.sort_values(['val1', 'distance']).groupby('val1').head(2)
val1 val2 distance
0 100 200 1.5
2 100 234 3.7
... | python|pandas|dataframe|group-by|pandas-groupby | 4 |
351,889 | 48,023,423 | Seperate columns into list after applying df.groupby() in pandas | <p>This was the original data. </p>
<p>ID     TIME     BYTES </p>
<p>1     13:00     10 </p>
<p>2     13:02     30 </p>
<p>3     13:03     40 </p>
<p>4     13:02     50 </p>
... | <p>The answer as given by @COLDSPEED.</p>
<pre><code>v = df.groupby('TIME')['BYTES'].sum();
a, b = v.index.tolist(), v.tolist()
</code></pre> | python-3.x|pandas|k-means|pandas-groupby|sklearn-pandas | 1 |
351,890 | 48,161,445 | Changing the fill_values in a SparseDataFrame - replace throws TypeError | <p>Current pandas version: <code>0.22</code></p>
<hr>
<p>I have a SparseDataFrame.</p>
<pre><code>A = pd.SparseDataFrame(
[['a',0,0,'b'],
[0,0,0,'c'],
[0,0,0,0],
[0,0,0,'a']])
</code></pre>
<p></p>
<pre><code>A
0 1 2 3
0 a 0 0 b
1 0 0 0 c
2 0 0 0 0
3 0 0 0 a
</code></pre>
... | <p><strong>tl;dr</strong> : That's definitely a bug.<br/>
But please keep reading, there is more than that...</p>
<p>All the following works fine with pandas 0.20.3, but not with any newer version:</p>
<pre><code>A.replace(0,np.nan)
A.replace({0:np.nan})
A.replace([0],[np.nan])
</code></pre>
<p>etc... (you get the i... | python|pandas|sparse-matrix|sparse-dataframe | 15 |
351,891 | 48,800,014 | object_detection - ImportError: cannot import name 'dataset_builder' | <p>I recently updated to tf 1.5 and while trying to invoke train.py under research/object_detection i hit an error saying</p>
<p>For more info:</p>
<pre><code>Traceback (most recent call last):
File "train.py", line 50, in <module>
from object_detection.builders import dataset_builder
ImportError: cannot ... | <p>if you notice in the code the dataset_builder is called from object_detection.builders, meaning that you have to execute the code from one directory up (from research directory). In my case, I just moved the train.py code to research directory and then issued it as normal and it worked!</p> | tensorflow|object-detection | 1 |
351,892 | 48,820,086 | Stack numpy array onto diagonal | <p>Given N 2d numpy arrays, is there a neat way in which I can 'stack' or 'bolt' them together on the diagonal, filling any new slots with 0? E.g. given:</p>
<pre><code>arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
</code></pre>... | <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.block_diag.html" rel="noreferrer">There's a function for that.</a></p>
<pre><code>scipy.linalg.block_diag(arr1, arr2)
</code></pre>
<p>It takes arbitrarily many parameters:</p>
<pre><code>scipy.linalg.block_diag(*list_of_arrays)
</code></p... | python|numpy|linear-algebra | 5 |
351,893 | 48,735,135 | Creating numpy functions and converting to tensor | <p>I am trying to create function using numpy something like f=(x-a1)^2+(y-a2)^2+a3</p>
<p>Where a1,a2,a3 are random generated numbers and x,y are parameters.</p>
<p>But I cant work with it, I want to find f(0,0) where [0,0] is [x,y] and [a1,a2,a3] were set before,but my code doesnt work.
And then I want to convert t... | <p>To create a TensorFlow function from a numpy function, you should use <code>tf.py_func</code>:</p>
<blockquote>
<p>Wraps a python function and uses it as a TensorFlow op.</p>
</blockquote>
<p>From the TensorFlow <a href="https://www.tensorflow.org/api_docs/python/tf/py_func" rel="nofollow noreferrer">API</a>:</p... | python|numpy|tensorflow|numpy-ufunc | 0 |
351,894 | 48,615,473 | pandas display categories incorrect displayed in matplotlib | <p>I am trying to represent categories in matplotlib and for some reason I have categories overlapping on x-axis, as well as missing categories, but y-axis values present. I marked this with red arrows in the picture from the bottom of the question.</p>
<p><strong>The data is contained in sales.csv file that looks lik... | <p><code>plt.scatter</code> seems to be happy to take strings as the x-coordinate and arrange them in alphabetical order. <code>plt.xticks</code>, however, wants a list matching the number of ticks and in the same order.</p>
<p>If you change:</p>
<pre><code>plt.xticks(sales_brute['city'], rotation=70)
</code></pre>
... | python|pandas|categories|display | 0 |
351,895 | 48,568,886 | Jupyter: ImportError: libcusolver.so.8.0: cannot open shared object file: No such file or directory | <p>While I run the following code in Jupyter notebook:</p>
<pre><code>import tensorflow as tf
a = tf.constant("hello world!")
sess = tf.Session()
print(sess.run(a))
</code></pre>
<p>I got the following error messages:</p>
<pre><code>ImportError: Traceback (most recent call last):
File "/home/ac/anaconda3/lib/pyt... | <p>The solution I found is following:</p>
<p>First, I installed the Jupyter extension nb_conda via <code>conda install nb_conda</code>, which will add the ability to view the current kernel environment in Jupyter. Then I realize the Jupyter doesn't use the correct environment I expected.</p>
<p>Second, install Jupyte... | python|tensorflow|jupyter | 0 |
351,896 | 48,748,172 | Pandas groupby with sum keeping a third column | <p>I have a data set that looks like this:</p>
<pre><code>Master Sec Amount
1234 98765 191
1234 98765 926
1234 98764 236
2345 76543 233
2345 76543 963
3456 54321 221
3456 54321 820
3456 43210 281
3456 32101 786
</code></pre>
<p>What I would like is to groupby the Mast... | <p>Here is one way. Since <code>groupby</code> returns a series, you can use this to map <code>Master</code>, and finally drop duplicate rows.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1234, 98765, 191],
[1234, 98765, 926],
[1234, 98764, 236],
[234... | python|pandas | 2 |
351,897 | 48,773,602 | Pandas groupby get first element of group where row matches criteria | <p>I have a dataframe where some rows have all the same values except for one column. I wish to remove duplicate rows, keeping only the first row in each group whose value in that column is 1, or one arbitrary row if no values in that column are 1. Example data:</p>
<pre><code>df = pd.DataFrame({'a': [1, 1, 1, 2, 2, 3... | <p>You can using <code>drop_duplicates</code></p>
<pre><code>df.sort_values(['a','c']).drop_duplicates(['a'],keep='last')
Out[748]:
a b c
1 1 1 1
4 2 4 0
6 3 6 1
</code></pre>
<p>If you want to use <code>groupby</code> </p>
<pre><code>df.sort_values(['a','c']).groupby('a',as_index=False).last()
Out[75... | python|pandas|group-by|aggregate | 3 |
351,898 | 48,711,305 | Python PANDAS: Stack by Enumerated Date to Create Records Vectorized | <p>I have a dataframe in the following general format:</p>
<pre><code>id,transaction_dt,units,measures
1,2018-01-01,4,30.5
1,2018-01-03,4,26.3
2,2018-01-01,3,12.7
2,2018-01-03,3,8.8
</code></pre>
<p>What I am trying to accomplish is stack and enumerate the 'transaction_dt' based on the value of 'units' field in same... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat</code></a> for duplicate indices by column <code>units</code> with <code>loc</code> for duplicates rows. Last per each indices get <code>count</code> by <a href="http://pandas.pyd... | python|pandas | 3 |
351,899 | 48,648,517 | filter pandas dataframe by two columns where one column is a list | <p>I'm trying to filter a pandas dataframe by seeing if one columns of strings exists in a column of a list of strings.</p>
<p><strong>reproducible example:</strong></p>
<pre><code>x = pd.DataFrame({'Letter':['a', 'b', 'c', 'd', 'e'],
'Alpha':[['a', 'z'], ['c', 'q', 'f'], 'c', 'e', ['e', 'q', 'm']]})
... | <p>You can use <code>apply()</code>:</p>
<pre><code>print(x[x.apply(lambda row: row.Letter in row.Alpha, axis=1)])
# Alpha Letter
#0 [a, z] a
#2 c c
#4 [e, q, m] e
</code></pre> | python|pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.