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 |
|---|---|---|---|---|---|---|
7,000 | 65,731,662 | Does Python support declaring a matrix column-wise? | <p>In <em>Python numpy</em> when declaring matrices I use <em>np.array([[row 1], [row 2], . . . [row n]])</em> form. This is declaring a matrix row-wise. Is their any facility in <em>Python</em> to declare a matrix column-wise? I would expect something like - <em>np.array([[col 1], [col 2], . . . [col n]], parameter = ... | <p>At the time of array-creation itself, you could use <code>numpy.transpose()</code> instead of <code>numpy.array()</code>, because <code>numpy.tranpose()</code> takes any "array-like" object as input:</p>
<pre><code>my_array = np.transpose ([[1,2,3],[4,5,6]])
print (my_array)
</code></pre>
<p><strong>Output... | python|arrays|numpy|matrix | 2 |
7,001 | 65,560,510 | Import RSS with FeedParser and Get Both Posts and General Information to Single Pandas DataFrame | <p>I am working on as a python novice on an exercise to practice importing data in python. Eventually I want to analyze data from different podcasts (infos on the podcasts itself <em>and</em> every episode) by putting the data into a coherent dataframe work on it with NLP.</p>
<p>So far I have managed to read a list of... | <p>Feed title can be accessed in this case with <code>feed.feed.title</code>:</p>
<pre><code># ...
for url in rss_feeds:
feed = feedparser.parse(url)
for post in feed.entries:
posts.append((feed.feed.title, post.title, post.link, post.summary))
df = pd.DataFrame(posts, columns=['feed_title', 'title', '... | python|pandas|rss|feedparser | 1 |
7,002 | 63,648,837 | Excel with pandas - once read, pandas do not take changes made to xlsx file into account | <p>I need to convert an xlsx file into csv. After googling, I found this satisfying answer :</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
read_file = pd.read_excel("./data/myxlsxfiles.xlsx" )
read_file.to_csv("./data/mycsv.csv", index=None, header=True, sep=";")... | <p>Maybe you can try to clear the read_file variable first, but I think it's a problem on Windows.</p>
<p>Otherwise, you can just duplicate the file into a temp folder, read the duplicate, proceed it and then delete the duplicate. Like this (not tested):</p>
<pre><code>path = "./data/"
temp_path = "./dat... | python|excel|pandas|csv | 0 |
7,003 | 63,420,936 | How to select rows from DataFrame based on subset inclusion? | <p>I have a DataFrame with a column of sets and a column of numbers:</p>
<pre><code>df
ant cons
0 ("Q1A_3") 2
1 ("Q1A_2", "Q2A_4") 3
2 ("Q2A_5") 6
</code></pre>
<p>Ideally, I'd like to be able to retrieve all the rows based on them b... | <p>Try two <code>contains</code></p>
<pre><code>subdf=df[df['ant'].str.contains("Q1A_3") & df['ant'].str.contains("Q2A_4")]
</code></pre> | python|pandas | 0 |
7,004 | 63,365,653 | Preserving unknown batch dimension for custom static tensors in Tensorflow | <p>Some notes: I'm using tensorflow 2.3.0, python 3.8.2, and numpy 1.18.5 (not sure if that one matters though)</p>
<p>I'm writing a custom layer that stores a non-trainable tensor N of shape (a, b) internally, where a, b are known values (this tensor is created during init). When called on an input tensor, it flattens... | <p>You have to have as many flattened <code>N</code> vectors, as you have samples in your input, because you are concatenating to every sample. Think of it like pairing up rows and concatenating them. If you have only one <code>N</code> vector, then only one pair can be concatenated.
To solve this, you should use <code... | python|tensorflow|keras | 3 |
7,005 | 63,507,023 | How to make a Keras Dense Layer deal with 3D tensor as input for this Softmax Fully Connected Layer? | <p>I am working on a custom problem, and i have to change the fully connected layer (Dense with softmax), My model code is something like this (with Keras Framework):</p>
<pre><code>.......
batch_size = 8
inputs = tf.random.uniform(shape=[batch_size,1024,256],dtype=tf.dtypes.float32)
preds = Dense(num_classes,activatio... | <p>There are three different ways in which this can be done (that I can think of). If you want to have a single dense layer, that maps a vector of 256 elements to a vector of <code>num_classes</code> elements, and apply it all across your batch of data (that is, use the same <code>256 x num_classes</code> matrix of wei... | tensorflow|keras|deep-learning|neural-network|tensor | 1 |
7,006 | 63,380,691 | How to model.predict inside loss function? (Tensorflow, Keras) | <p>I am trying to construct a custom loss for a regression problem with the following structure, following this answer:
<a href="https://stackoverflow.com/questions/46858016/keras-custom-loss-function-to-pass-arguments-other-than-y-true-and-y-pred">Keras Custom loss function to pass arguments other than y_true and y_pr... | <p>Sounds like you can use model.add_loss for this. You can use this to specify the loss function inside of the model. It also removes the need for the loss function to only take in y and y_pred.
<a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_loss" rel="nofollow noreferrer">https://www.te... | python|tensorflow|loss-function | 1 |
7,007 | 24,601,014 | Behaviour of custom NaN floats in Python and Numpy | <p>I need to pack some extra information into floating point NaN values. I am using single-precision IEEE 754 floats (32-bit floats) in Python. How do Python and NumPy treat these values?</p>
<p><strong>Theory</strong></p>
<p>The IEEE 754-2008 standard seems to think a number is really not a number, if the exponent b... | <p>After thinking of this for some time and having a look at the source code ad then rethinking a bit, I think I can answer my own question. My hypotheses are almost correct but not the whole story.</p>
<p>As NumPy and Python handle numbers quite differently, this answer has two parts.</p>
<p><strong>What really happ... | python|python-2.7|numpy | 8 |
7,008 | 29,926,772 | putting headers into an array, python | <p>I have a set of data that is below some metadata. I'm looking to put the headers into a numpy array to be used later. However the first header needs to be ignored as that is the x data header, then the other columns are the y headers. How do i read this?</p> | <p>Assuming I have understood what you mean by headers (it would be easier to tell with a few complete lines, even if you had to scale it down from your actual file)...</p>
<p>I would first read the irregular lines with normal python then, on the regular lines, use genfromtxt with skip_header and usecols (make a tuple... | python|csv|numpy | 0 |
7,009 | 30,041,286 | Sum rows where value equal in column | <p>How can I sum across rows that have equal values in the first column of a numpy array? For example: </p>
<pre><code>In: np.array([[1,2,3],
[1,4,6],
[2,3,5],
[2,6,2],
[3,4,8]])
Out: [[1,6,9], [2,9,7], [3,4,8]]
</code></pre>
<p>Any help would be greatly appreciat... | <p>Pandas has a very very powerful groupby function which makes this very simple.</p>
<pre><code>import pandas as pd
n = np.array([[1,2,3],
[1,4,6],
[2,3,5],
[2,6,2],
[3,4,8]])
df = pd.DataFrame(n, columns = ["First Col", "Second Col", "Third Col"])
df.groupby("F... | python|numpy|sum|row | 16 |
7,010 | 29,920,114 | How to gauss-filter (blur) a floating point numpy array | <p>I have got a numpy array <code>a</code> of type <code>float64</code>. How can I blur this data with a Gauss filter?</p>
<p>I have tried</p>
<pre><code>from PIL import Image, ImageFilter
image = Image.fromarray(a)
filtered = image.filter(ImageFilter.GaussianBlur(radius=7))
</code></pre>
<p>, but this yields <cod... | <p>If you have a two-dimensional numpy array <code>a</code>, you can use a Gaussian filter on it directly without using Pillow to convert it to an image first. scipy has a function <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.ndimage.filters.gaussian_filter.html"><code>gaussian_filter</code... | python|numpy|opencv|python-imaging-library|filtering | 58 |
7,011 | 53,476,876 | np.around for array with none and integer values | <p>I have an array:</p>
<pre><code>MDP= [[0.705,.655,0.614,0.388],[0.762,None,0.660,-1],[0.812,.868,0.918,+1]]
</code></pre>
<p>How can I apply np.around on above array without getting the error for None and -1, +1 values?</p>
<p>TIA</p> | <p>Make sure that you work with a numpy array, not lists of lists:</p>
<pre><code>np.around(np.array(MDP).astype(float))
#array([[ 1., 1., 1., 0.],
# [ 1., nan, 1., -1.],
# [ 1., 1., 1., 1.]])
</code></pre>
<p>You can convert the result back to a nested list with <code>.tolist()</code>, if needed.<... | python|numpy | 1 |
7,012 | 53,657,152 | Looping Range of Numbers & Appending to df.col using pandas or itertools | <p>I would like to iterate a range of numbers through a dataframe column.</p>
<pre><code>data = {'NAME': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy','Tina3', 'Jake2', 'Amy1','Jake3', 'Amy2' ],
'REPORTS': [4, 24, 31, 2, 3, 12, 13, 63, 22, 64]}
df = pd.DataFrame(data)
df['col'] = 0
range = [1,2,3]
</code></pre>
... | <p>IIUC, you can use <code>itertools.cycle</code> to cycle through your range for the length of the dataframe:</p>
<pre><code>from itertools import cycle
c = cycle(range(1,4))
df['new_column'] = [next(c) for _ in range(len(df))]
>>> df
NAME REPORTS new_column
0 Jason 4 1
1 Molly ... | python|pandas|loops|apply | 1 |
7,013 | 53,618,106 | Performing computations with values of two dataframes | <p>I have two pandas data frames.</p>
<p><strong>DataFrame 1</strong></p>
<pre><code>Index_Col Col1 Col2 Col3 Col4 Col5
Row1 0.64 0.89 0.76 0.22 1.34
Row2 0.54 0.56 0.82 0.46 0.23
and so on.
</code></pre>
<p>DataFrame 2 has Thresholds for each of the columns in dataframe... | <pre><code>import pandas as pd
import io
# SAmple Data
df1 = pd.read_table(io.StringIO("""
Index_Col Col1 Col2 Col3 Col4 Col5
Row1 0.64 0.89 0.76 0.22 1.34
Row2 0.54 0.56 0.82 0.46 0.23
"""),delim_whitespace=True)
df2 = pd.read_table(io.StringIO("""
Column_Name Group ... | python|python-3.x|pandas|dataframe | 0 |
7,014 | 53,378,909 | How to change the first value in the tuple of a list? | <p>This is my matrix:</p>
<pre><code>b = [[(1, 0.044), (2, 0.042)], [(4, 0.18), (6, 0.023)], [(4, 0.03), (5,
0.023)]]
</code></pre>
<p>And I want to let it to be a </p>
<pre><code>b = [[(6, 0.044), (7, 0.042)], [(9, 0.18), (11, 0.023)], [(9, 0.03), (10,
0.023)]]
</code></pre>
<p>To add n for the first value in th... | <p>Tuples are immutable. You can use a list comprehension instead:</p>
<pre><code>res = [[(i+5, j) for i, j in tup] for tup in b]
[[(6, 0.044), (7, 0.042)], [(9, 0.18), (11, 0.023)], [(9, 0.03), (10, 0.023)]]
</code></pre> | python|numpy|replace|tuples | 3 |
7,015 | 19,863,964 | fastest way to find the magnitude (length) squared of a vector field | <p>I have a large vector field, where the field is large (e.g. 512^3; but not necessarily square) and the vectors are either 2D or 3D (e.g. shapes are [512, 512, 512, 2] or [512, 512, 512, 3]).</p>
<p>What is the fastest way to compute a scalar field of the squared-magnitude of the vectors?</p>
<p>I could just loop o... | <p>The fastest is probably going to be <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="noreferrer"><code>np.einsum</code></a>:</p>
<pre><code>np.einsum('...j,...j->...', vf, vf)
</code></pre>
<p>The above code tells numpy to grab its to inputs and reduce the last dimension of e... | python|math|optimization|vector|numpy | 6 |
7,016 | 71,792,666 | How to replace missing value with NA using for loop in Python | <p>I have a data frame with 2 features which I have created using python code:</p>
<pre><code>data_df = {"Age" : [10, 20, 30, 40, 50, np.NaN, np.NaN, np.NaN, np.NaN],
"Name" : ["A", "B", "C", "D", "E", "F", "G", "H... | <p>For test missing values use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.isna.html" rel="nofollow noreferrer"><code>pandas.isna</code></a>:</p>
<pre><code>am_decision = []
for (x,y) in zip(data_df['Age'],data_df['Name']):
if pd.isna(x):
am_decision.append(np.NaN)
else:
... | python|python-3.x|pandas|numpy | 3 |
7,017 | 72,023,608 | python reading a csv file with panda and multiple filters | <p>I want to read a csv with python and panda with multiple filters</p>
<p>example csv file with the name passwd.csv:</p>
<pre><code>Funktion, Benutzer, Kennwort
user_p, user1, test1
user_f, user2, test2
user, bla, blup
</code></pre>
<p>python code:</p>
<pre class="lang-py prettyprint-override"><code>import pandas
d = ... | <p>I don't know if this is a typo, but you're trying to combine two dataframes (returned by <code>query</code>) with the <code>|</code> operator. It belongs in your expression:</p>
<pre><code>res = d.query('Funktion == "user_f" | Benutzer == "user2" ')
</code></pre> | python|pandas|filter | 0 |
7,018 | 71,909,917 | "ModuleNotFoundError: No module named 'keras'" after computer restart | <p>Over the weekend Windows restarted my computer for updates. Now I can no longer run large amounts of code!</p>
<p>I'm running this segment of <code>jyupter</code> code in <code>VS Code</code></p>
<pre><code>from tensorflow import keras
normalizer = keras.layers.experimental.preprocessing.Normalization(axis=-1)
norm... | <p>A <code>ModuleNotFoundError:</code> is triggered when a package can't be found, or is not installed. As you have recently updated, I assume your window's installation of Python as automatically upgraded.</p>
<blockquote>
<p>I'm using the proper interpreter and <strong><code>conda list</code> includes the entire <cod... | python|tensorflow|anaconda3 | 0 |
7,019 | 71,929,046 | Convert an image from RGB to index in palette using Tensorflow | <p>I want to convert an RGB image to one with a single channel, whose value is an integer index from a palette (which has already been extracted).</p>
<p>An example:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
# image shape (height=2, width=2, channels=3)
image = tf.constant([
[
[... | <p>I used the technique described in this other question (<a href="https://stackoverflow.com/questions/64930665/find-indices-of-rows-of-numpy-2d-array-in-another-2d-array">Find indices of rows of numpy 2d array in another 2D array</a>) and adapted it from Numpy to Tensorflow. It is fully vectorized and executes very fa... | python|tensorflow | 0 |
7,020 | 17,090,577 | eulerian-magnification tuple index out of range python | <p>I'm making an attempt to build and work with this video project in Python.</p>
<p><a href="https://github.com/brycedrennan/eulerian-magnification" rel="nofollow">https://github.com/brycedrennan/eulerian-magnification</a></p>
<p>The command that I'm trying to run is:</p>
<pre><code>eulerian_magnification('media/fa... | <p>This may indicate that the OpenCV bin directory is not in the path.</p> | python|opencv|numpy|scipy | 1 |
7,021 | 19,221,694 | How many columns in pandas, python? | <p>Have anyone known the total columns in pandas, python?
I have just created a dataframe for pandas included more than 20,000 columns but I got memory error.</p>
<p>Thanks a lot</p> | <p>You get an out of memory error because you run out of memory, not because there is a limit on the number of columns.</p> | python|pandas | 6 |
7,022 | 55,434,047 | Passing values to function using numpy | <p>Suppose, I have a function that has three inputs prob(x,mu,sig).
With sizes:</p>
<pre><code>x = 1 x 3
mu = 1 x 3
sig = 3 x 3
</code></pre>
<p>Now, I have a dataset X, mean matrix M and std. deviation matrix sigma.
Sizes are:-</p>
<pre><code>X : m x 3.
mean : k x 3.
sigma : k x 3 x 3
</code></pre>
<p>For each ... | <p>If using a single for loop is acceptable then you can probably use the following,</p>
<pre><code>import itertools
sigma.shape = k, 9
zipped_array = np.array(list(zip(mean, sigma)))
all_possible_combo = list(itertools.product(X, zipped_array))
list_len = len(all_possible_combo) # = m * k
s = np.zeros(k)
responsibil... | python|function|numpy | 0 |
7,023 | 55,191,194 | pandas version impact on tables | <p>I have a html file with tables.(wikipedia links)
I am trying to access the tables using pandas.</p>
<p>My code is :</p>
<pre><code>dfs=pd.read_html(url1)
for i in range(0,5):
print(dfs[i])
</code></pre>
<p>This works in pandas version 0.23.0</p>
<p>but the same does not work on 0.23.4 version.
I get the erro... | <p>Use beautiful soap with pandas:</p>
<pre><code>import pandas as pd
import requests
from bs4 import BeautifulSoup
res = requests.get("https://en.wikipedia.org/wiki/List_of_bicycle-sharing_systems")
soup = BeautifulSoup(res.content,'html.parser')
table = soup.find_all('table')[0]
df = pd.read_html(str(table))
</co... | python|pandas | 0 |
7,024 | 56,841,907 | How to set the columns in pandas | <p>Here is my dataframe:</p>
<pre><code> Dec-18 Jan-19 Feb-19 Mar-19 Apr-19 May-19
Saturday 2540.0 2441.0 3832.0 4093.0 1455.0 2552.0
Sunday 1313.0 1891.0 2968.0 2260.0 1454.0 1798.0
Monday 1360.0 1558.0 2967.0 2156.0 1564.0 1752.0
Tuesday 1089.0 2105.0 2476.0 1577.0 ... | <pre><code>df.reset_index().melt(id_vars='index').drop('variable',1)
</code></pre>
<p>Output:</p>
<pre><code> index value
0 Saturday 2540.0
1 Sunday 1313.0
2 Monday 1360.0
3 Tuesday 1089.0
4 Wednesday 1329.0
5 Thursday 798.0
6 Saturday 2441.0
7 Sunday 1891.0
8 Monda... | python|pandas|dataframe | 9 |
7,025 | 56,670,223 | Remove square brackets from cells using pandas | <p>I have a Pandas Dataframe with data as below</p>
<pre><code>id, name, date
[101],[test_name],[2019-06-13T13:45:00.000Z]
[103],[test_name3],[2019-06-14T13:45:00.000Z, 2019-06-14T17:45:00.000Z]
[104],[],[]
</code></pre>
<p>I am trying to convert it to a format as below with no square brackets</p>
<p>Expected output... | <p>Loop through the data frame to access each string then use:</p>
<pre><code>newstring = oldstring[1:len(oldstring)-1]
</code></pre>
<p>to replace the cell in the dataframe.</p> | regex|pandas | 0 |
7,026 | 56,496,731 | Coloring entries in an Matrix/2D-numpy array? | <p>I'm learning python3 and I'd like to print a matrix/2d-array which is color-coded (CLI). So let's say I'd like to assign each of these integers a certain background color, creating a mosaic-style look.</p>
<p>I've figured out how to fill a matrix of a given size with random integers, but I can't wrap my head around... | <p>The following will <code>print</code> a colored output on console... </p>
<pre><code>>>> map = np.random.randint(4 + 1, size=(10, 10))
>>> def get_color_coded_str(i):
... return "\033[3{}m{}\033[0m".format(i+1, i)
...
>>> map_modified = np.vectorize(get_color_coded_str)(map)
>>&... | arrays|python-3.x|numpy|matrix|colors | 4 |
7,027 | 66,917,947 | creating a range of numbers in pandas based on single column | <p>I have a pandas dataframe:</p>
<pre><code>df2 = pd.DataFrame({'ID':['A','B','C','D','E'], 'loc':['Lon','Tok','Ber','Ams','Rom'], 'start':[20,10,30,40,43]})
ID loc start
0 A Lon 20
1 B Tok 10
2 C Ber 30
3 D Ams 40
4 E Rom 43
</code></pre>
<p>I'm looking to add in a c... | <p>You might prepare range creating function and <code>.apply</code> it to start column following way:</p>
<pre><code>import pandas as pd
df2 = pd.DataFrame({'ID':['A','B','C','D','E'], 'loc':['Lon','Tok','Ber','Ams','Rom'], 'start':[20,10,30,40,43]})
def make_10(x):
return list(range(x, x-10-1, -1))
df2["rang... | python|pandas | 1 |
7,028 | 66,993,314 | Create a single categorical column based on conditions on many numerical columns (pandas) | <p>I have a pandas dataframe like this</p>
<p>df:</p>
<pre><code>sEXT | sNEU | sAGR | sCON | sOPN
2.4 | 3 | 2 | 2 | 5
3 | 1 | 4 | 2.7 | 1.5
</code></pre>
<p>I want to create a column "type" according the following rules. If sEXT > 2.5 add string "E" to status, else "I&quo... | <p>You can write a function that creates the string, and then apply the dataframe to that function:</p>
<pre><code>import pandas as pd
data = [ { "sEXT": 2.4, "sNEU": 3, "sAGR": 2, "sCON": 2, "sOPN": 5 }, { "sEXT": 3, "sNEU": 1, "sAGR": 4,... | python|python-3.x|pandas | 1 |
7,029 | 67,054,207 | Difference between different lenght timestamp-indexed DataFrames | <p>I have two dataframes, both are indexed with timestamp values like '2021-03-23 13:04:00.134000+00:00'.</p>
<p>I would like to compute the difference between them on some columns, but the problem is that they are not time-aligned and have different number of rows.</p>
<p>Is there a good way to makes the difference of... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a> first:</p>
<pre><code>df = pd.merge_asof(df1,
df2,
left_index=True,
right_index=True,
tol... | python|pandas|dataframe|timestamp | 1 |
7,030 | 66,926,140 | Why tf.keras loss becomes NaN when number of train images increases from 100 to 9000? | <p>I am following a CNN example in <a href="https://www.tensorflow.org/tutorials/images/cnn" rel="nofollow noreferrer">here</a>.
Here are my code to prepare the CNN model:</p>
<pre><code>model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
model.add(layers.MaxPo... | <p>what I would do is to use categorical cross entropy. In your generators change class_mode to 'categorical'. In model.compile make loss='categorical_crossentropy. Not sure this will fix it but it can't hurt. Could be when you use more images, perhaps there are some Na
labels. Check your datafame for Na's.</p> | python|image|tensorflow|keras|computer-vision | 0 |
7,031 | 66,923,714 | Make a pandas dataframe using one available series | <p>I have a pandas series for players as follows:</p>
<pre><code>0 1
1 1
2 3
3 4
</code></pre>
<p>My expected output is:</p>
<pre><code> players teams night morning
0 1 [] [] []
1 1 [] [] []
2 3 [] [] []
3 4 [] [] []
</code... | <p>The purpose eludes me, but this can be done by filling the <code>None</code> values with empty lists:</p>
<pre><code>df = pd.DataFrame({'players': [1, 1, 3, 4], 'teams': None, 'night': None, 'morning': None})
df = df.applymap(lambda x: [] if not x else x)
</code></pre>
<p>Result:</p>
<pre><code> players teams n... | python|pandas | 0 |
7,032 | 68,066,429 | Keep non-numerical columns with resample | <p>I have a data frame structure that looks like this:</p>
<pre><code>df =
ds col1 col2 col3 col4
2021-04-11 17:41:55 foo1 bar1 7263 1234
2021-04-11 17:46:55 foo1 bar1 8464 5726
2021-04-11 17:51:55 foo1 bar1 3321 ... | <p>You can use this columns for grouping (if possible):</p>
<pre><code>df_new = df.groupby([pd.Grouper(freq='60min', key='ds'), 'col1','col2']).mean()
print (df_new)
col3 col4
ds col1 col2
2021-04-11 17:00:00 foo1 bar1 6349.333333... | python|pandas|dataframe | 1 |
7,033 | 68,038,312 | Extract data from a column in pandas DataFrame | <p>how can we extract the car model from the dataframe below:</p>
<p>Output:</p>
<p>2015 Maruti Swift VDI ABS........................... VDI ABS</p>
<p>2012 Maruti Swift Dzire VDI BS IV..............VDI BS IV</p>
<p>2013 Maruti Swift VDI......................................VDI</p>
<p>2012 Maruti Swift VDI................ | <p>If you have this dataframe:</p>
<pre class="lang-none prettyprint-override"><code> column
0 2015 Maruti Swift VDI ABS
1 2012 Maruti Swift Dzire VDI BS IV
2 2013 Maruti Swift VDI
3 2012 Maruti ... | python|pandas|dataframe | 0 |
7,034 | 68,077,392 | How do you create a datetime/timestamp from multiple columns in a csv file | <p>I am using pandas to read in a csv file which contains the year in the first column, the month in the second, the day in the third, the hour in the fourth, and the sea level in the fifth (<a href="https://i.stack.imgur.com/Mk7Bs.png" rel="nofollow noreferrer">csv layout</a>).</p>
<p>I would like to use the columns t... | <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html#pandas-to-datetime" rel="nofollow noreferrer"><code>pd.to_datetime</code></a> is pretty handy. Assuming columns are named appropriately they can be easily passed in.</p>
<p>Given this DataFrame:</p>
<pre><code>df = pd.DataFrame([[1973, 3, ... | python|pandas|datetime|timestamp | 2 |
7,035 | 68,092,351 | Pandas: LDA Top n keywords and topics with weights | <p>I am doing a topic modelling task with LDA, and I am getting 10 components with 15 top words each:</p>
<pre><code>for index, topic in enumerate(lda.components_):
print(f'Top 10 words for Topic #{index}')
print([vectorizer.get_feature_names()[i] for i in topic.argsort()[-10:]])
print('\n')
</code></pre>
<... | <p>If I understand correctly, you have a dataframe with all values and you want to keep the top 10 in each row, and have 0s on remaining values.</p>
<p>Here we <code>transform</code> each row by:</p>
<ul>
<li>getting the 10th highest values</li>
<li>reindexing to the original index of the row (thus the columns of the d... | python|pandas|dataframe|lda|topic-modeling | 0 |
7,036 | 59,214,988 | Convert CSV file to HTML and display in browser with Pandas | <p>How can I convert a <code>CSV</code> file to <code>HTML</code> and open it in a web browser via <code>Python</code> using <code>pandas</code>.
Below is my program but I can not display them in the web page:</p>
<pre><code>import pandas
import webbrowser
data = pandas.read_csv(r'C:\Users\issao\Downloads\data.csv')
d... | <p>You need to pass a <code>url</code> to <code>webbrowser</code>.</p>
<p>Save the html content into a local file and pass it's path to webbrowser</p>
<pre><code>import os
import webbrowser
import pandas
data = pandas.read_csv(r'C:\Users\issao\Downloads\data.csv')
html = data.to_html()
path = os.path.abspath('data.h... | python|html|pandas|csv|web | 2 |
7,037 | 59,433,911 | How to convert string to datetime format if it is in a list? | <p>I am trying to plot a graph with dates format. The thing is that I have problem with the format of the dates column.</p>
<p>I have tried to use the solution like this:</p>
<pre class="lang-py prettyprint-override"><code>df['Date'] = pd.to_datetime(df['Date'])
</code></pre>
<p>It works. But the problem is that whe... | <p>hope this will work</p>
<p>solution1</p>
<pre><code>df['Date']=df['Date'].astype('datetime64[ns]')
</code></pre>
<p>Solution2</p>
<p>date is the list of date in string formate,if u want to convert into datetime then try this code</p>
<pre><code>dates_list = [dt.datetime.strptime(date, '"%Y-%m-%d"').date() for d... | python-3.x|pandas|datetime | 0 |
7,038 | 59,200,373 | Padding and reshaping pandas dataframe | <p>I have a dataframe with the following form:</p>
<pre><code>data = pd.DataFrame({'ID':[1,1,1,2,2,2,2,3,3],'Time':[0,1,2,0,1,2,3,0,1],
'sig':[2,3,1,4,2,0,2,3,5],'sig2':[9,2,8,0,4,5,1,1,0],
'group':['A','A','A','B','B','B','B','A','A']})
print(data)
ID Time sig sig2 gr... | <p>Here's one approach creating the new index with <code>pd.MultiIndex.from_product</code> and using it to <code>reindex</code> on the <code>Time</code> column:</p>
<pre><code>df = data.set_index(['ID', 'Time'])
# define a the new index
ix = pd.MultiIndex.from_product([df.index.levels[0],
... | python|pandas|padding | 1 |
7,039 | 59,445,281 | How can I read from a file with Python from a specific location to a specific location? | <p>Currently, I'm doing: </p>
<pre><code> source_noise = np.fromfile('data/noise/' + source + '_16k.dat', sep='\n')
source_noise_start = np.random.randint(
0, len(source_noise) - len(audio_array))
source_noise = source_noise[source_noise_start:
source_noise_start + le... | <p>you can use the seek method to move inside file and read specific places. </p>
<p>file data -> "hello world"</p>
<pre><code>start_read = 6
with open("filename", 'rb') as file:
file.seek(start_read)
output = file.read(5)
print(output)
# will display world
</code></pre> | python|numpy|file | 1 |
7,040 | 46,008,310 | Why does outputing numpy.dot to memmap does not work? | <p>If I do:</p>
<pre><code>a = np.ones((10,1))
b = np.ones((10,1))
c = np.memmap('zeros.mat', dtype=np.float64, mode='w+', shape=(10,10), order='C')
a.dot(b.T, out=c)
</code></pre>
<p>I am getting:</p>
<blockquote>
<p>ValueError: output array is not acceptable (must have the right type,
nr dimensions, and be a ... | <p>It doesn't just have to match the dtype; it also has to have the right <em>type</em>, as in <code>type(c)</code>. <code>c</code> is a <code>numpy.memmap</code> instance, not a <code>numpy.ndarray</code>, so that check fails.</p>
<p>As recommended in the <a href="https://docs.scipy.org/doc/numpy/reference/generated/... | python|numpy | 3 |
7,041 | 45,925,327 | Dynamically filtering a pandas dataframe | <p>I am trying to filter a pandas data frame using thresholds for three columns</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"A" : [6, 2, 10, -5, 3],
"B" : [2, 5, 3, 2, 6],
"C" : [-5, 2, 1, 8, 2]})
df = df.loc[(df.A > 0) & (df.B > 2) & (df.C > -1)].reset_... | <p>If you're trying to build a dynamic query, there are easier ways. Here's one using a list comprehension and <code>str.join</code>:</p>
<pre><code>query = ' & '.join(['{}>{}'.format(k, v) for k, v in limits_dic.items()])
</code></pre>
<p>Or, using <code>f</code>-strings with python-3.6+, </p>
<pre><code>que... | python|pandas|dataframe|filter|exec | 76 |
7,042 | 45,999,895 | Tensorboard is not populating graph on windows | <p>I have written simple python program to multiply two values and expected to populate the tensorboard graph.</p>
<p>I am using Windows - CPU machine.</p>
<p>Then after executing my program it generated required graph event file in the log directory path with the name <code>events.out.tfevents.1504266616.L7</code></... | <p>Tensorboard requires that you use linux style paths with forward slashes, e.g.</p>
<pre><code>tensorboard --logdir C:/Users/SIMBU/python_pgm/TensorFlow/graph
</code></pre> | python|tensorflow|tensorboard|tensorflow-xla | 3 |
7,043 | 35,745,992 | Apply a threshold on a Pandas DataFrame column | <p>I have a Daframe that looks like this</p>
<pre><code>In [52]: f
Out[52]:
Date
2015-02-23 12:00:00 0.172517
2015-02-23 13:00:00 0.172414
2015-02-23 14:00:00 0.172516
2015-02-23 15:00:00 0.173261
2015-02-23 16:00:00 0.172921
2015-02-23 17:00:00 0.172371
2015-02-23 18:00:00 0.176374
2015-02-23 19:... | <p>IIUC then the following should work:</p>
<pre><code>f[f> Threshold] = some_val
</code></pre>
<p>Or you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.clip_upper.html" rel="noreferrer"><code>clip_upper</code></a>:</p>
<pre><code>f = f.clip_upper(Threshold)
</code></pre>
<p... | python|pandas|boolean|time-series | 13 |
7,044 | 50,797,615 | Exact string search using lambda function | <p>How can one search for exact string using a lambda function? The data frame looks as follows:</p>
<pre><code>A B
10 Mini
20 Mini Van
15 Mini
13 Mini Bus
</code></pre>
<p>Desired results</p>
<pre><code>A B
10 Mini
15 Mini
</code></pre>
<p>I have tried the following, but all fail:</p>
<pre><code>d... | <p>Just check for equality:</p>
<pre><code>df_temp = df_temp[df_temp['B'] == 'Mini']
</code></pre>
<p>This works because <code>df_temp['B'] == 'Mini'</code> returns a Boolean series, which is then used to index <code>df_temp</code>.</p>
<p>Or you can use <a href="http://pandas.pydata.org/pandas-docs/version/0.22/gen... | python|pandas | 5 |
7,045 | 51,109,471 | cannot replace [''] with method pad on a DataFrame | <p>running python2.7</p>
<p>Question1</p>
<p>I want to replace empty string '' with None in my dataframe "test": </p>
<pre><code> from numpy.random import randn
test = pd.DataFrame(randn(3,2))
test.iloc[0,0]=''
test.replace('', None)
</code></pre>
<p>Give me error TypeError: </p>
<p>cannot replace [... | <p>None is being interpreted as a lack of an argument. Try:</p>
<pre><code>test.replace({'':None})
</code></pre>
<p>Question 2:</p>
<pre><code>test.where(test != '', None)
</code></pre> | python|pandas | 6 |
7,046 | 50,936,819 | Python - How to plot data from multiple text files in a single graph | <p>I am trying to plot a graph by importing data from multiple text files in a single graph (multiple lines). For that, I wrote the following code: </p>
<pre><code>import glob
import matplotlib.pyplot as plt
import numpy as np
filenames=glob.glob("FHGM3168-01G2-*#1.txt")
for f in filenames:
print(f)
data = np.lo... | <p>Initialize the graph outside the for loop (plt.figure() or the like). If you need plt.show(), do it after the loop.</p> | python|numpy|matplotlib|plot|spyder | 0 |
7,047 | 50,840,255 | Can I make numpy.sum return 0 when array is 0 rows? | <p>I have a sum function that, in a simplified version, looks like this: The row arrays used as indicers change dynamically within my program, but this is a heavily reduced version to demonstrate the issue:</p>
<p>This runs perfectly fine if I throw a few integers into the Row1 array, which is obviously intended, but ... | <blockquote>
<p>"This could obviously be interpreted to return 4 (0 + 4) <em>but numpy will obviously throw an error as I'm trying to indice a 0 dimension array</em>. I could solve this by doing:"</p>
</blockquote>
<p>Nope, as long as you make sure the empty array has dtype <code>int</code> it works just fine.</p>
... | python|numpy | 2 |
7,048 | 33,232,265 | How to get column value as percentage of other column value in pandas dataframe | <p>I have a question. I have a relatively huge pandas dataframe like this one:</p>
<pre><code>df:
Column1 Column2 Column3 Column4
0 100 50 25 10
1 200 100 50 10
2 10 10 5 5
3 20 15 10 5
4 10 7 7 7
</cod... | <p>Something like this?</p>
<pre><code>In [95]: (df.astype(str) +
' (' +
df.apply(lambda x: (100 * x / x['Column1']), axis=1).astype(str) +
'%)')
Out[95]:
Column1 Column2 Column3 Column4
0 100 (100.0%) 50 (50.0%) 25 (25.0%) 10 (10.0%)
1 200 (100.0%) 100 (... | python|pandas|dataframe | 3 |
7,049 | 33,481,440 | Substitute numpy array elements using dictionary | <p>I have this numpy array </p>
<pre><code>message = [ 97 98 114 97]
</code></pre>
<p>and this dictionary </p>
<pre><code>codes = {97: '1', 98: '01', 114: '000'}
</code></pre>
<p>and I am now iterating through the numpy array and converting those numbers to the ones corresponding in the dictionary like this:</p>
<... | <p>Here's a <em>NumPythonic</em> solution using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> -</p>
<pre><code>np.asarray(codes.values())[np.searchsorted(codes.keys(),message)]
</code></pre>
<p>Please note that the output would be... | python|arrays|numpy|dictionary | 1 |
7,050 | 66,531,167 | Calculate z-score for multiple columns of dataset on groupby and transform to original shape in pandas without using loop | <p>I have a data frame</p>
<pre><code>df = pd.DataFrame([["A",1,98,56,61], ["B",1,99,54,36], ["C",1,97,32,83],["B",1,96,31,90], ["C",1,45,32,12], ["A",1,67,33,55], ["C",1,54,65,73], ["A",1,34,84,98], ["B",1,76,12,99]], columns=[&q... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code... | python|python-3.x|pandas|dataframe | 2 |
7,051 | 66,603,096 | Creating a Heatmap of Cartisan X,Y,Z values using Python | <p>Here is what I am looking to do:</p>
<ol>
<li>Import .csv file containing Cartesian Coordinates of X, Y, and Z values, as well as nominal Z values.</li>
<li>Create a 2D heatmap image of those points where X, Y are locations of known points and the Z value determines the color at that location. Specifically the devia... | <p>If your data is ordered then you can use a pcolormesh.</p>
<pre class="lang-py prettyprint-override"><code>
import matplotlib.pyplot as plt
import numpy as np
theta, r = np.meshgrid(np.linspace(0, 2*np.pi, 50), np.linspace(0, 5, 50));
X_coord = r * np.cos(theta);
Y_coord = r * np.sin(theta);
Z_coord = np.sin(3*theta... | python|pandas|numpy|matplotlib|heatmap | 0 |
7,052 | 66,514,218 | Is pytorch 1.7 officially enabled for cuda 10.0? | <p>I had to stay on CUDA 10.0 for personal projects.</p>
<p>Rather than installing Pytorch with versions appropriate for CUDA 10.0, I accidentally installed Pytorch 1.7 supported with CUDA 10.1. In particular, I installed by</p>
<pre><code>pip install torch==1.7.1+cu101 torchvision==0.8.2+cu101 torchaudio==0.7.2 -f htt... | <blockquote>
<p>Surprisingly, everything works fine so far although the CUDA versions
do not match.</p>
</blockquote>
<p>Changes between minor versions should work (mismatch like this worked in my case), although there is no promise of compatibility in <code>10.x</code> release (<a href="https://docs.nvidia.com/deploy/... | installation|pytorch | 2 |
7,053 | 66,498,690 | How to take the first non null element, row-wise, from a column that consists of lists? | <p>Suppose a generic dataframe with 4 numeric columns and one final column that, row-wise, gathers all observations of the past four columns inside a list.</p>
<p>Let me provide a code example of the initial dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
x = pd.DataFrame({'col_1': [np.nan, 35, 27, 50... | <p><code>explode</code> the list then take the <code>first</code> value along the index.</p>
<pre><code>x['sixth_col'] = x['fifth_col'].explode().groupby(level=0).first()
</code></pre>
<hr />
<pre><code> col_1 col_2 col_3 col_4 fifth_col sixth_col
0 NaN 15.0 12.0 NaN [nan, 15.0, 12.0, na... | python|pandas|list|dataframe | 1 |
7,054 | 66,661,238 | Save model.summary() as pdf | <p>I'm trying to print my model.summary() to pdf.</p>
<p>I tried following the question asked here: <a href="https://stackoverflow.com/questions/45199047/how-to-save-model-summary-to-file-in-keras">How to save model.summary() to file in Keras?</a></p>
<pre><code>def myprint(s):
with open('/content/drive/My Drive/xx... | <p>Do you need to save the summary as a PDF? If so, you need to use a wrapper library like <a href="https://pyfpdf.readthedocs.io/en/latest/FAQ/index.html" rel="nofollow noreferrer">fpdf</a> or <a href="https://pypi.org/project/PyPDF2/" rel="nofollow noreferrer">PyPDF2</a> in order to generate the required PDF metadata... | python|tensorflow|pdf|keras | 0 |
7,055 | 16,452,182 | Error when importing numba in Python 3 | <p>I have just installed numba in my Ubuntu 13.04 via pip-3.3, as an alternative to numpy and cython to make calculations, but every time i try to import it in Python i get a "Segmentation fault (core dumped)" error and Python exists:</p>
<pre><code>esteban@esteban-Inspiron-1525:~$ python3
Python 3.3.1 (default, Apr 1... | <p>Numba has preliminary support for Python 3. It should work, but I don't think it's received as much testing. Which version of numba did you try? </p>
<p>Also, how did you install llvm and llvmpy and which version of numpy do you have installed? </p> | python|numpy|python-3.x|installation|cython | 4 |
7,056 | 16,563,552 | Pandas: fancy indexing a dataframe | <p>I have a Pandas dataframe, df1, that is a year-long <em>5 minute</em> timeseries with columns A-Z.</p>
<pre><code>df1.shape
(105121, 26)
df1.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2002-01-02 00:00:00, ..., 2003-01-02 00:00:00]
Length: 105121, Freq: 5T, Timezone: None
</code></pre>
<p>I have a se... | <p>Here's one way to do this:</p>
<pre><code>t_index = df1.index
d_index = df2.index
mask = t_index.map(lambda t: t.date() in d_index)
df1[mask]
</code></pre>
<p>And slightly faster (but with the same idea) would be to use:</p>
<pre><code>mask = pd.to_datetime([datetime.date(*t_tuple)
for ... | numpy|pandas | 0 |
7,057 | 57,622,868 | Elegant way to do fuzzy map based on a mix of substring and string in pandas | <p>I have two dataframes <code>mapp</code> and <code>data</code> like as shown below</p>
<pre><code>mapp = pd.DataFrame({'variable': ['d22','Studyid','noofsons','Level','d21'],'concept_id':[1,2,3,4,5]})
data = pd.DataFrame({'sourcevalue': ['d22heartabcd','Studyid','noofsons','Level','d21abcdef']})
</code></pre>
<p><... | <p>If need map by strings and first 3 letters create 2 separate Series and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.c... | python|python-3.x|pandas|dataframe | 3 |
7,058 | 57,696,446 | how to replace timestamp with 1 and 0? | <p>I would like to replace the enrolment time log with 1 and the null cells with 0 on a large dataset, below is a sample:</p>
<pre><code>data = [['tom', '10', "2014-02-05 21:24:44 UTC"], ['nick', '',''], ['juli', 14, '2014-02-15 21:55:43 UTC']]
BD = pd.DataFrame(data, columns = ['Name', 'Age', 'Enrolled_at'])
</code... | <pre><code>BD['Enrolled_at'] = pd.to_datetime(BD['Enrolled_at'])
BD['Enrolled_at'] = np.where(BD['Enrolled_at'] > '1990-01-01', 1, 0)
</code></pre>
<p>You can set the 1990 date to the lowest value of dates in your data</p> | python|pandas|numpy | 3 |
7,059 | 57,558,956 | How can I add functions to aggregations in groupby in python? | <p>I'm trying to get groupby stats with additional math operations between the aggregations</p>
<p>I tried</p>
<pre><code>...agg({
'id':"count",
'repair':"count",
('repair':"count")/('id':"count")
})
</code></pre>
<blockquote>
<pre><code>yr id repair
2016 37 27
2017 53 28
</code></pre>
</blockquote>
... | <p>Consider a custom function that returns an aggregated data set:</p>
<pre><code>def agg_func(g):
g['id'] = g['id'].count()
g['repair'] = g['repair'].count()
g['repair_per_id'] = (g['repair'] / g['id']) * 100
return g.aggregate('max') # CAN ALSO USE: min, max, mean, median, mode
agg_df = (df.grou... | python|pandas|group-by|aggregation | 3 |
7,060 | 57,705,746 | Python Pandas: Append column names in each row | <p>Is there a way to append column names in dataframe rows?</p>
<p>input:</p>
<pre><code>cv cv mg mg
5g 5g 0% zinsenzin
</code></pre>
<p>output:</p>
<pre><code>cv cv col_name mg mg col_name
5g 5g cv 0% zinsenzin mg
</code></pre>
<p>I tried by this, but it's not working</p>
<pre><cod... | <p>In pandas working with duplicated columns names is not easy, but possible:</p>
<pre><code>c = 'cv cv mg mg sa sa ta ta at at ad ad an av av ar ar ai ai ca ca ch ch ks ks ct ct ce ce cw cw dt dt fr fr fs fs fm fm it it lg lg mk mk md md mt mt ob ob ph ph pb pb rt rt sz sz tg tg tt tt vv vv yq yq fr fr ms ms lp lp ts... | pandas | 2 |
7,061 | 24,340,785 | Python plot values at nodes in meshgrid | <p>I have from</p>
<pre><code> numpy.meshgrid(xx,yy)
</code></pre>
<p>a rectangular grid.</p>
<p>To get the coordinates (nodes) I split it into two lists X and Y with values:</p>
<pre><code> X = (0.0 , 0.2 , 0.4 , 0.6 , 0.8 , 1.0)*6
Y = (0.0 , 0.2 , 0.4 , 0.6 , 0.8 , 1.0)*6
</code></pre>
<p>Which gives a... | <p>Take your output array and:</p>
<pre><code>disparray = myarray + (arange(6) * .2)[:,None]
plot(X.flatten(), disparray.flatten(), '.')
</code></pre>
<p>This should do.</p>
<p>And, of course you can plot with a for loop.</p>
<pre><code>figure()
for r in range(myarray.shape[0]):
plot(X[0], myarray[r] + 0.2*r, '... | python|numpy|matplotlib|plot|mesh | 1 |
7,062 | 24,109,603 | Vectorize over only one axis in a 2D array with numpy vectorize | <p>I have the following function to get the Euclidean distance between two vectors <code>a</code> and <code>b</code>. </p>
<pre><code>def distance_func(a,b):
distance = np.linalg.norm(b-a)
return distance
</code></pre>
<p>Here, I want <code>a</code> to be an element of an array of vectors. So I used numpy vec... | <p>You don't need to use <code>vectorize</code>, you can just do:</p>
<pre><code>a = np.array([[1,2],[2,3],[3,4],[4,5],[5,6]])
b = np.array([1,2])
np.linalg.norm(a-b, axis=1)
</code></pre>
<p>which gives:</p>
<pre><code>[ 0. 1.41421356 2.82842712 4.24264069 5.65685425]
</code></pre>
<p>(I assume this i... | python|arrays|python-2.7|numpy|vectorization | 4 |
7,063 | 24,381,090 | Performance issue with reading integers from a binary file at specific locations | <p>I have a file with integers stored as binary and I'm trying to extract values at specific locations. It's one big serialized integer array for which I need values at specific indexes. I've created the following code but its terribly slow compared to the F# version I created before.</p>
<pre><code>import os, struct
... | <p>Heavily depending on your index file size you might want to read it completely into a numpy array. If the file is not large, complete sequential read may be faster than a large number of seeks.</p>
<p>One problem with the seek operations is that python operates on buffered input. If the program was written in some ... | python|numpy|binaryfiles | 4 |
7,064 | 43,772,218 | fastest way to use numpy.interp on a 2-D array | <p>I have the following problem. I am trying to find the fastest way to use the interpolation method of numpy on a 2-D array of x-coordinates.</p>
<pre><code>import numpy as np
xp = [0.0, 0.25, 0.5, 0.75, 1.0]
np.random.seed(100)
x = np.random.rand(10)
fp = np.random.rand(10, 5)
</code></pre>
<p>So basically, <code... | <p>So basically you want output equivalent to</p>
<pre><code>np.array([np.interp(x[i], xp, fp[i]) for i in range(x.size)])
</code></pre>
<p>But that <code>for</code> loop is going to make that pretty slow for large <code>x.size</code></p>
<p>This should work:</p>
<pre><code>def multiInterp(x, xp, fp):
i, j = np... | numpy|interpolation|linear-interpolation | 10 |
7,065 | 72,869,547 | from_logits in SparseCategoricalCrossEntropy loss function not working as expected | <p>After researching, my understanding of logit is that when <code>from_logits=True</code> output is not normalized (not a probability distribution) and when <code>from_logits=False</code> it is normalized by softmax function. So if <code>from_logtis=False</code> isn't it supposed to output probability distribution of ... | <p>You need to use <code>Softmax</code> activation function if you are using <code>from_logits=False</code> (which is default <code>from_logits=False</code> if not defined) to get the output probability distribution of the class.</p>
<pre><code>tf.Tensor(
[1.2676346e-01 1.1662615e-02 1.2230438e-03 8.4634316e-01 6.98247... | python|tensorflow|keras|deep-learning | 0 |
7,066 | 73,169,558 | pd.DataFrame.to_sql() is prepending the server name and username to the table name | <p>I have a Pandas dataframe <code>df</code> which I want to push to a relational database as a table. I setup a connection object (<code><Connection></code>) using SQLAlchemy (pyodbc is the connection engine), and called the command</p>
<p><code>df.to_sql(<Table_Name>, <Connection>)</code></p>
<p>whi... | <p>By default, <code>.to_sql()</code> assumes the default schema for the current user unless <code>schema="schema_name"</code> is provided. Say, for example, the database contains a table named <code>dbo.thing</code> and the database user named <code>joan</code> has a default schema named <code>engineering</c... | python|pandas|sqlalchemy|pyodbc | 2 |
7,067 | 70,473,374 | How to scale the x-axis (in datetime format) of dataframes graphs to the same scale ? Python Pandas | <p>I have several dataframe graphics on a single figure. The X axis is a timestamp in the format: dd/mm/yy HH:MM:SS</p>
<p>The problem is that the time axis is not on the same scale and I can't put them on the same scale. I tried this but it doesn't work:</p>
<pre><code>df1:
Timestamp,Value
2018-11-13 00:26:43.267725,... | <p>You can <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axis.Axis.get_view_interval.html" rel="nofollow noreferrer">take</a> the view interval of both Axes and enlarge the smaller one to match the bigger, then <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xlim.html" rel="n... | python|pandas|datetime|matplotlib | 0 |
7,068 | 70,650,372 | why python pandas not able to generate xlsx file? | <p>I am trying to achieve below tasks:</p>
<p><strong>traverse_dir() function</strong></p>
<pre><code>- read a root directory, and get the names of the sub directories.
- read the sub directories and see if 'installed-files.json' file is present.
- if the 'installed-files.json' file is present in all the directories, t... | <p>The main issue is that <code>if file_name in i:</code> is always false, hence no xlsx file created.
You may need to make some changes to test for the file existence, for example:</p>
<pre><code>import os
def traverse_dir(rootDir, file_name):
dir_names = []
for names in os.listdir(rootDir):
entry_path... | python|python-3.x|pandas|dataframe | 1 |
7,069 | 42,832,829 | How to use Tensorflow's batch_sequences_with_states utility | <p>I am trying to build a generative RNN using Tensorflow. I have a preprocessed dataset which is a list of <code>sequence_length x 2048 x 2</code> numpy arrays. The sequences have different lengths. I have been looking through examples and documentation but I really couldn't understand, for example, what <code>key</co... | <p><strong>Toy Implementations</strong></p>
<p>I tried this and I will be glad to share my findings with you. It is a toy example. I attempted to create an example that works and observe how the output varies. In particular I used a case study of lstm. For you, you can define a conv net. Feel free to add more input an... | python|numpy|tensorflow | 5 |
7,070 | 42,816,129 | Select first few rows of pandas dataframe with a certain value in the column | <p>I am trying to set values of a column in a pandas dataframe based on the value of another column, </p>
<pre><code>df2.loc[df2['col1',len] == val, 'col2'] = df1['col2']
</code></pre>
<p>Above code works fine, however, now the problem is that I want to set values only for first few rows, something like below:</p>
<... | <p>Change it to this:</p>
<pre><code>df2.iloc[:len(df1.index),].ix[df2.col1 == val, 'col2'] = df1['col2']
</code></pre>
<p>Here it is working not sure what's wrong with it. </p>
<pre><code> name gender age occupation years_of_school married
0 Bob M 37 Dentist 20 N
1 Sally ... | python|pandas | 1 |
7,071 | 42,713,161 | pandas unstack the list | <p>I encounter a problem:</p>
<pre><code>import pandas
data=pandas.DataFrame({'data1':[[('m',2)],[('n',3),('y',4)],[('x',3),('y',5)],[('m',3)]]},
index=[['a','a','c','d'],[1,1,3,4]])
</code></pre>
<p>the data like this:</p>
<pre><code> data1
a 1 [(m, 2)]
1 [(n, 3), (y, 4)]
c 3 [(x, 3), (y... | <p>You can use list comprehension for creating <code>df</code> by tuples and then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a>:</p>
<pre><code>df = pd.DataFrame([dict(x) for x in data.data1], index=data.index)
pr... | python|pandas | 1 |
7,072 | 42,608,621 | How to create layers of arrays (arrays in arrays) with given sizes | <p>I want to create arrays in arrays in an array in a flexible way. The question is probably best illustrated by an example.</p>
<p>We want to construct an array with three layers. The size of each layer are given by the following:</p>
<pre><code>S1, S2, S3 = 3, [3,2,2], 4
</code></pre>
<p>Each constant represent a ... | <p>You could do:</p>
<pre><code>[[[0]*s3 for _ in range(size)] for size in s2]
</code></pre>
<p><code>s1</code> is really not needed as information, since <code>s1 == len(s2)</code>.</p> | python|arrays|numpy|multidimensional-array | 2 |
7,073 | 27,242,390 | Finding the sum of grouped data by column | <p>My grouped data looks like:</p>
<pre><code>deviceid time total_sent
022009f075929be71975ce70db19cd47780b112f 1980-January 36 4
52 1
94 ... | <p>Since <code>total_sent</code> column is to be summed, it shouldn't be within the groupby keys. You can try the following:</p>
<pre><code>data1.groupby(['deviceid', 'time']).agg({'total_sent': sum})
</code></pre>
<p>which will sum the <code>total_sent</code> column for each group, indexed by <code>deviceid</code> a... | python|pandas|data-analysis | 1 |
7,074 | 14,444,916 | Pandas obtain share from DataFrame | <p>I need a smart and concise way to arrive from data_1 to data_3 dataframe.
Right now I m arrived easily just to dataframe 2.</p>
<pre><code>DATA_1
key SEGM1 SEGM2 VAL
A K X 1
B K X 2
C K X 3
D K Y 4
E... | <p>Here's a one-liner:</p>
<pre><code>In [1]: df
Out[1]:
SEGM1 SEGM2 VAL
key
A K X 1
B K X 2
C K X 3
D K Y 4
E K Y 5
F J Y 6
G J Z 7
H J Z 8
I J Z 9
</code></pre>
<p>Use the <code>DataFrame.div</c... | dataframe|grouping|pandas | 1 |
7,075 | 25,169,066 | Is there a Pandas equivalent to each_slice to operate on dataframes | <p>I am wondering if there is a Python or Pandas function that approximates the Ruby #each_slice method. In this example, the Ruby #each_slice method will take the array or hash and break it into groups of 100. </p>
<pre><code>var.each_slice(100) do |batch|
# do some work on each batch
</code></pre>
<p>I am trying ... | <p>There isn't a built in method as such but you can use numpy's <code>array_slice</code>, you can pass the dataframe to this and the number of slices.</p>
<p>In order to get ~100 size slices you'll have to calculate this which is simply the number of rows/100:</p>
<pre><code>import numpy as np
# df.shape returns the... | python|pandas | 1 |
7,076 | 26,790,050 | pandas conditional aggregation | <p>I want to group the below dataframe based on 'id', then have the aggregate sums of 'flow' for all values of 'id' except 0; those should stay independent. What is the best solution?</p>
<p>Original:</p>
<pre><code>id flow
0 1
0 1
1 1
1 1
2 1
2 1
</code></pre>
<p>Aggregated:</p>
<pre><code>id flow
0 ... | <p>One way would be to use <code>transform</code> to assign the new flow values back and then drop duplicates:</p>
<pre><code>In [48]:
df.loc[df['id'] != 0, 'flow'] = df.groupby('id')['flow'].transform('sum')
df.drop(df[df['id']!=0].drop_duplicates().index)
Out[48]:
id flow
0 0 1
1 0 1
3 1 2
5 ... | python|pandas|aggregation | 2 |
7,077 | 39,198,108 | pandas standalone series and from dataframe different behavior | <p>Here is my code and warning message. If I change <code>s</code> to be a standalone <code>Series</code> by using <code>s = pd.Series(np.random.randn(5))</code>, there will no such errors. Using Python 2.7 on Windows.</p>
<p>It seems Series created from standalone and Series created from a column of a data frame are ... | <p>By doing <code>s = sample['c_d']</code>, if you make a change to the value of <code>s</code> then your original Dataframe <code>sample</code> also changes. That's why you got the warning.</p>
<p>You can do <code>s = sample[c_d].copy()</code> instead, so that changing the value of <code>s</code> doesn't change the v... | python|python-2.7|pandas|numpy|dataframe | 1 |
7,078 | 19,614,379 | How do you calculate expanding mean on time series using pandas? | <p>How would you create a column(s) in the below pandas DataFrame where the new columns are the expanding mean/median of 'val' for each 'Mod_ID_x'. Imagine this as if were time series data and 'ID' 1-2 was on Day 1 and 'ID' 3-4 was on Day 2.</p>
<p>I have tried every way I could think of but just can't seem to get it... | <p>Hard to test properly on your DataFrame, but you can use something like this:</p>
<pre><code>>>> df1["exp_mean"] = df1[["Mod_ID_x","val"]].groupby("Mod_ID_x").transform(pd.expanding_mean)
>>> df1
ID Mod_ID_x car val color wheel exp_mean
0 1 15 ford 10000 green 4wheel ... | python-2.7|pandas|dataframe|time-series | 2 |
7,079 | 29,087,284 | create a feature vector using pandas or python | <p>i have an a binary classifier which takes a 200 element input feature vector as shown below </p>
<pre><code> [ id, v1, v2, ...,v190, v200, class]
[ 7, 0, 0, ..., 0, 0, 0 ],
[ 8, 0, 1, ..., 0, 0, 1 ],
[ 9, 0, 0, ..., 0, 0, 1 ],
</code></pre>
<p>For each element X ... | <p>First initializing a pandas dataframe and then building on your example:</p>
<pre><code>df = pd.DataFrame(None, columns=['v'+str(i) for i in range(1,201)])
sql = 'SELECT x_id, x_attr FROM elements WHERE x_hash = %s'
cur.execute(sql, (x_hash,))
x1_id, features = cur.fetchone()
df.loc[x1_id] = 0 # Initializes all va... | python|numpy|pandas | 2 |
7,080 | 33,891,923 | How do you get the number of masked rows in a numpy masked array? | <p>So I have a numpy array that contains a number of numpy arrays where some of them have masked values that looks like the one below:</p>
<pre><code>[[1 2 3]
[-- -- --]
[7 8 9]]
</code></pre>
<p>What is the most efficient way to get the number of masked numpy arrays (meaning something like [-- -- --]) in the bigge... | <p><a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/maskedarray.generic.html#accessing-the-mask" rel="nofollow">Masked arrays have a <code>.mask</code> attribute</a> consisting of a boolean array that is <code>True</code> wherever a value is masked. If you want to know how many rows contained <em>at least one<... | python|arrays|numpy | 4 |
7,081 | 23,719,203 | Pandas Dataframe selecting groups with minimal cardinality | <p>I have a problem where I need to take groups of rows from a data frame where the number of items in a group exceeds a certain number (cutoff). For those groups, I need to take some head rows and the tail row.</p>
<p>I am using the code below</p>
<pre><code>train = train[train.groupby('id').id.transform(len) > h... | <p>Use <code>groupby/filter</code>:</p>
<pre><code>>>> df.groupby('id').filter(lambda x: len(x) > cutoff)
</code></pre>
<p>This will just return the rows of your dataframe where the size of the group is greater than your cutoff. Also, it should perform quite a bit better. I timed <code>filter</code> here ... | python|pandas|dataframe|data-processing | 7 |
7,082 | 62,115,259 | Pandas drop rows in time series with less than x observation | <p>I am working with timeseries data in Pandas (timestamp used as index). I am doing some filtering on my dataset and end up with a dataframe that mostly contains consecutive observations (one-minute data). However, there are also time intervals with only one or a few minutes of obervations. These I would like to exclu... | <p>Use:</p>
<pre><code>#convert index to Series
s = df.index.to_series()
#test if 1 Minute difference, then cumulative sum
a = s.diff().ne(pd.Timedelta(1, unit='Min')).cumsum()
#filter if counts of cumulative value greater like N, e.g. 3
N = 3
df = df[a.map(a.value_counts()).gt(N)]
print (df)
val... | python|pandas|time-series | 1 |
7,083 | 62,284,095 | What are the parameters to tf.GradientTape()'s __exit__ function? | <p>According to the <a href="https://www.tensorflow.org/api_docs/python/tf/GradientTape" rel="nofollow noreferrer">documentation</a> for <code>tf.GradientTape</code>, its <code>__exit__()</code> method takes three positional arguments: <code>typ, value, traceback</code>.</p>
<p><strong>What exactly are these parameter... | <p><code>sys.exc_info()</code> returns a tuple with three values <code>(type, value, traceback)</code>.</p>
<ol>
<li>Here <code>type</code> gets the exception type of the Exception being handled</li>
<li><code>value</code> is the arguments that are being passed to the constructor of an exception class.</li>
<li><code>... | python|tensorflow|oop|with-statement|automatic-differentiation | -1 |
7,084 | 51,470,186 | scipy.optimize.minimize changes values at low decimal place | <p>this is my code for the optimisation.</p>
<pre><code> initialGuess = D.Matrix[:,D.menge]
bnds = D.Matrix[:,(D.mengenMin,D.mengenMax)]
con1 = {'type': 'eq', 'fun': PercentSum}
con2 = {'type': 'eq', 'fun': MinMaxProportion}
cons = ([con1,con2])
solution = minimize(rootfunc,initialGuess,method='SLSQP',\
... | <p>Those "tiny steps" are not values selected by the solver in each iteration, they are from finite differencing. Gradient-based solvers like this one require gradients. Since you didn't provide the gradients as functions, it defaults to calculating them for you with finite difference. Your real problem, as the error s... | python|numpy|scipy|nonlinear-optimization | 0 |
7,085 | 51,548,551 | reading nested .h5 group into numpy array | <p>I received this .h5 file from a friend and I need to use the data in it for some work. All the data is numerical. This the first time I work with these kind of files. I found many questions and answers here about reading these files but I couldn't find a way to get to lower level of the groups or folders the file co... | <p>You need to traverse down your HDF5 hierarchy until you reach a dataset. Groups do not have a shape or type, datasets do.</p>
<p>Assuming you do not know your hierarchy structure in advance, you can use a recursive algorithm to yield, via an iterator, full paths to all available datasets in the form <code>group1/gr... | python|arrays|numpy|hdf5|h5py | 13 |
7,086 | 51,417,282 | ValueError: ndarray is not contiguous | <p>when I build a matrix using the last row of my dataframe:</p>
<pre><code>x = w.iloc[-1, :]
a = np.mat(x).T
</code></pre>
<p>it goes:</p>
<pre><code>ValueError: ndarray is not contiguous
</code></pre>
<p>`print the x shows(I have 61 columns in my dataframe):</p>
<pre><code>print(x)
cdl2crows 0.00000... | <p>np.mat expects array form of input.
refer to the doc
<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.mat.html" rel="nofollow noreferrer">doc</a></p>
<p>So your code should be</p>
<pre><code>x = w.iloc[-1, :].values
a = np.mat(x).T
</code></pre>
<p>.values will give numpy array format of datafr... | python|pandas|numpy | 1 |
7,087 | 51,177,262 | Where can I find documentation on NumPy's delineation of its directories? | <p>This may be a stupid question, but...</p>
<p>Where can I find a simple explanation of what goes under 'lib,' vs 'core'? How do I know whether a function goes under fromnumeric.py, or function_base.py? Some of the .py files have explanation strings at the beginning, but others do not. </p> | <p>You may double check the <a href="https://docs.scipy.org/doc/numpy/reference/" rel="nofollow noreferrer">numpy/reference</a> and <a href="https://docs.scipy.org/doc/numpy/user/" rel="nofollow noreferrer">numpy/user</a> guides.</p> | numpy | 0 |
7,088 | 48,595,802 | Tensorflow: Finding index of first occurrence of elements in a tensor | <p>Suppose I have a tensor, x = [1, 2, 6, 6, 4, 2, 3, 2]<br>
I want to find the index of the first occurrence of every unique element in x.<br>
The output should be [0, 1, 6, 4, 2].
I basically want the second output of numpy.unique(x,return_index=True). This functionality doesn't seem to be supported in tf.unique.
Is... | <pre><code>x = [1, 2, 6, 6, 4, 2, 3, 2]
x_count = tf.cumsum(tf.ones_like(x))-1
unique, unique_id = tf.unique(x)
unique_first = tf.unsorted_segment_min(x_count, unique_id, tf.shape(unique)[0])
with tf.Session() as sess:
print(sess.run(tf.stack([unique, unique_first],0)))
</code></pre>
<p>Gives:</p>
<pre><code>[[1 ... | python|tensorflow | 1 |
7,089 | 48,766,275 | Appending a column to data frame using Pandas in python | <p>I'm trying some operations on Excel file using pandas. I want to extract some columns from a excel file and add another column to those extracted columns. And want to write all the columns to new excel file. To do this I have to append new column to old columns.</p>
<p>Here is my code- </p>
<pre><code>import panda... | <p>There is no need to explicitly append columns in <code>pandas</code>. When you calculate a new column, it is included in the dataframe. When you export it to excel, the new column will be included.</p>
<p>Try this, assuming 'Num Labels' and 'Num Tracks' are in "D,I,J,AU" [otherwise add them]:</p>
<pre><code>import... | python|pandas | 3 |
7,090 | 48,871,043 | How to update row by row of dataframe using python pandas | <p>I don't know whether it can be achieved or not using python pandas. Here is the scenario I'm trying to do</p>
<p>I created a databases connection to MSSQL using python (pyodbc, sqlalchemy) </p>
<p>I read one table and saved it as dataframe like this </p>
<pre><code>data = pd.read_sql_table('ENCOUNTERP1', conn)
</... | <p>I assume that the two tables have same row size and are both in desired order you wanted. If it's correct, then you can simply use:</p>
<pre><code>df = pd.concat([data, pd], axis=1)
</code></pre>
<p>Then extract the columns you wanted:</p>
<pre><code>df = df.ix[;,['ENCOUNTERID','CODE', 'DIAGSEQNO', 'POA', 'DIAGVE... | python|pandas|dataframe | 1 |
7,091 | 70,892,948 | Transform not getting applied on CustomDataset Pytorch | <p>I images with folder structure as following :</p>
<pre><code>root_dir
│
└───folder1
│ │ file011.png
│ │ file012.png
│
└───folder2
| │ file021.png
| │ file022.png
|
└───folder2
│ file031.png
│ file032.png
...
</code></pre>
<p>Now I wanted to create a CustomeDataset without labels in PyT... | <p>You forgot to assign the <code>transform</code> object as an attribute of the instance. This, in turn, means <code>self.transform</code> evaluates to <code>None</code> in the <code>__getitem__</code> function. Simply add the following in the <code>__init__</code>:</p>
<pre><code>self.transform = transform
</code></p... | python|pytorch | 1 |
7,092 | 71,091,025 | How to Combine CSV files according to some conditions in pandas python? | <p>I have 4 CSV Files:
<a href="https://i.stack.imgur.com/BtNLa.png" rel="nofollow noreferrer">CSV Files Picture</a></p>
<p>I want to combine the 4 files into one data frame. I have to Use the Invoices.Customer_ID and Customers.ID. When combining, I also have to make sure that the result set only contains customers an... | <p>According to <a href="https://stackoverflow.com/questions/44781633/join-pandas-dataframes-based-on-column-values">this post</a>, you can merge dataframes per column-definitions like this:</p>
<pre><code>df = pd.merge(df1, df2, on=['document_id','item_id'])
</code></pre>
<p>So for your case, i think you would have to... | python|pandas|csv | 0 |
7,093 | 51,950,226 | Capped / Constrained Weights | <p>I have a dataframe of weights, in which I want to constrain the maximum weight for any one element to 30%. However in doing this, the sum of the weights becomes less than 1, so the weights of all other elements should be uniformly increased, and then repetitively capped at 30% until the sum of all weights is 1.</p>
... | <p>@jpp </p>
<p>The following is a rough approach, modified from your answer to iteratively solveand re-cap. It doenst produce a perfect answer though... and having a while loop makes it inefficient. Any ideas how this could be improved?</p>
<pre><code>import pandas as pd
import numpy as np
cap = 0.1
df = pd.DataFr... | python|pandas|weighted | 1 |
7,094 | 51,700,232 | ClipByValue error when deploying to ML Engine | <p>When trying to deploy a keras model to ML Engine I get</p>
<pre><code>$ gcloud ml-engine versions create v2 --model=plantDisease01 --origin=gs://${BUCKET_NAME}/
plantDisease01 --runtime-version=1.4
Creating version (this might take a few minutes)......failed. ... | <p><code>ClipByValue</code> was <a href="https://github.com/tensorflow/tensorflow/commits/700a6698e634391cf96a314f378a8de973b49995/tensorflow/compiler/tf2xla/kernels/clip_by_value_op.cc" rel="nofollow noreferrer">introduced in TensorFlow 1.8</a>. You can either <a href="https://www.tensorflow.org/extend/adding_an_op#op... | tensorflow|keras|google-cloud-ml | 1 |
7,095 | 51,872,431 | pandas cumulative subtraction in a column | <p>I have a dataframe where I need to do a burndown starting from the baseline and subtracting all the values along, essentially I'm looking for an <strong>opposite of DataFrame().cumsum(0)</strong>:</p>
<pre><code> In Use
Baseline 3705.0
February 2018 0.0
March 2018 2.0
April 2018 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.diff</code></a> by groups created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow noreferrer"><c... | python|python-3.x|pandas|numpy | 3 |
7,096 | 64,345,662 | Connect column of nodes based on another column | <p>I would need to build a network where nodes are websites and should be grouped based on a score assigned. If the website is new, then it will have a label 1, otherwise 0.</p>
<p>Example of data:</p>
<pre><code>url score label
web1 5 1
web2 10 1
... | <p>Probably a partition graph might be a good idea if you want to include the <code>score</code> as a node too. You can start by creating the graph with <code>nx.from_pandas_edgelist</code> as you did, and update the node attributes as:</p>
<pre><code>B = nx.from_pandas_edgelist(df, source='url', target='score')
node_... | python|pandas|networkx | 1 |
7,097 | 47,703,606 | pandas groupby: TOP 3 values for each group | <p><strong>A new and more generic question has been posted in <a href="https://stackoverflow.com/questions/47714181/pandas-groupby-top-3-values-in-each-group-and-store-in-dataframe?noredirect=1#comment82388261_47714181">pandas groupby: TOP 3 values in each group and store in DataFrame</a> and a working solution has bee... | <p><strong>NOTE: This solution works only if each group has at least 3 rows</strong></p>
<p>Try the following approach:</p>
<pre><code>In [59]: x = (df.groupby(pd.Grouper(freq='H'))['VAL']
.apply(lambda x: x.nlargest(3))
.reset_index(level=1, drop=True)
.to_frame('VAL')... | python|pandas|dataframe|pandas-groupby | 4 |
7,098 | 48,935,971 | Getting top 3 values from multi-index pandas dataframe | <p>I have a multi-level grouped pandas dataframe which looks something like this:</p>
<pre><code>date AccountNum ProgramName Duration
2017-11-12 12345 program1 200
program2 300
program4 100
... | <p>Is that what you want?</p>
<pre><code>In [143]: df.groupby(level=[0,1], as_index=False).apply(lambda x: x.nlargest(3, columns=['Duration'])).reset_index(level=0, drop=True)
Out[143]:
ProgramName Duration
date AccountNum
2017-11-12 12345.0 program2 300
12345.0 ... | python|pandas | 0 |
7,099 | 48,951,946 | Adding a row of totals to a dataframe | <p>I have a data frame and I am trying to figure out how to add a row to each client that sums up the hours for each client. Here is an example of my data frame:</p>
<pre><code> hours
client month
A January 203.50
February 227.75
... | <p>IIUC, you can using <code>concat</code></p>
<pre><code>pd.concat([df,df.sum(level=0).assign(month='Total').set_index('month',append=True)]).sort_index()
Out[1754]:
hours
client month
A April 203.25
February 227.75
January 203.50
March 159.75
... | pandas|sum|append | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.