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 |
|---|---|---|---|---|---|---|
14,400 | 13,589,390 | How to use numpy.where with logical operators | <p>I'm trying to find the indices of all elements in an array that are greater than a but less than b. It's probably just a problem with my syntax but this doesn't work:</p>
<pre><code>numpy.where((my_array > a) and (my_array < b))
</code></pre>
<p>How should I fix this? Or is there a better way to do it?</p>
... | <p>Here are two ways:</p>
<pre><code>In [1]: my_array = arange(10)
In [2]: where((my_array > 3) & (my_array < 7))
Out[2]: (array([4, 5, 6]),)
In [3]: where(logical_and(my_array > 3, my_array < 7))
Out[3]: (array([4, 5, 6]),)
</code></pre>
<p>For the first (replacing <code>and</code> with <code>&... | python|numpy|where|logical-operators | 79 |
14,401 | 62,200,493 | Iloc and rename in pandas | <p>I am new to data Science and recently i have been working with pandas and cannot figure out what the following line means in it!</p>
<pre><code>df1=df1.rename(columns=df1.iloc[0,:]).iloc[1:,:]
</code></pre>
<p>The problem states that this is used to make the columns with index 11 as the header but i can't understa... | <p>Just disect the line by each method applied:</p>
<pre><code>df1 = # reassign df1 to ...
df1.rename( # the renamed frame of df1 ...
columns = # where column names will use mapper of ...
df1.iloc[0,:] # slice of df1 on row 0, include all columns ...
)
... | python|pandas|rename | 1 |
14,402 | 62,127,213 | AttributeError: 'GeoDataFrame' object has no attribute 'str' | <p>So I have tried this:</p>
<pre><code>import GeoDataFrame
</code></pre>
<p>But it shows the following error:</p>
<pre><code>ModuleNotFoundError
Traceback (most recent call last)
<ipython-input-93-3125c1efb589> in <module>
----> 1 import GeoDataFrame
ModuleNotFoundError: No module named 'GeoDataFram... | <p>I think you need to install it via <code>pip install geopandas</code>. Go go through their <a href="https://geopandas.org/reference/geopandas.GeoDataFrame.html" rel="nofollow noreferrer">documentation</a> for using geodataframe.</p> | python|python-2.7|geopandas | 1 |
14,403 | 62,255,704 | Python numpy vectorization for heat dispersion | <p>I'm supposed to write a code to represent heat dispersion using the finite difference formula given below.</p>
<p><code>()=((−1)[+1,] + (−1) [−1,] +(−1)[,+1] + (−1)[,−1])/4</code>
The formula is supposed to produce the result only for a time step of 1. So, if an array like this was given: </p>
<pre><code>100 10... | <p>Try:</p>
<pre><code>h[1:-1,1:-1] = (h[2:,1:-1] + h[:-2,1:-1] + h[1:-1,2:] + h[1:-1,:-2]) / 4
</code></pre>
<p>This solution uses slicing where:</p>
<ul>
<li><code>1:-1</code> stays for indices 1,2, ..., LAST - 1</li>
<li><code>2:</code> stays for 2, 3, ..., LAST</li>
<li><code>:-2</code> stays for 0, 1, ..., LAST... | python|numpy|vectorization|heat | 3 |
14,404 | 62,302,878 | Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same | <p>****I set my model and data to the same device, but always raise the error like this:
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same**
The following is training code**</p>
<pre><code>total_epoch = 1
best_epoch = 0
training_losses = []
val_losses = []
for... | <p>The model's weights are on the GPU, while the <code>image</code> is on the CPU. You need to put it onto the GPU as well.</p>
<pre class="lang-py prettyprint-override"><code>image = pil_image.unsqueeze(0)
image = image.cuda()
result = loaded_model(image)
</code></pre>
<p>It looks like you didn't manually put the m... | python|machine-learning|deep-learning|pytorch|gpu | 1 |
14,405 | 62,443,689 | Numpy - How to vectorize on Sub-Arrays | <p>How do you apply vectorized functions on sub-arrays? Suppose I have the following:</p>
<pre><code>array = np.array([
[0, 1, 2],
[2],
[],
])
</code></pre>
<p>And I wanted to obtain the first element in each subarray, else <code>None</code>.</p>
<p><code>[0, 2, None]</code></p>
<p>While simple, is ther... | <p>You've created an object dtype array - containing lists (not subarrays):</p>
<pre><code>In [2]: array = np.array([
...: [0, 1, 2],
...: [2],
...: [],
...: ])
/usr/local/bin/ipython3:4: VisibleDeprecationWarning: Creati... | python|python-3.x|numpy|vectorization|numpy-ndarray | 1 |
14,406 | 51,438,920 | Multiindex dataframe rows replacement | <p>I have two Multi-indexed DataFrames.
One is my reference (about 37000 rows) and the other has fewer rows (e.g., 10).</p>
<p>I want to replace the rows of the big one with the values from the second one.</p>
<p>Sample <code>df1</code>:</p>
<pre><code>lvl1 lvl2 lvl3 Value Value2
A 1 I 0,862877333 ... | <p>You can try to replace values on index matching like this:</p>
<pre><code>for ind in df2.index:
df1.loc[ind, 'Value'] = df2.loc[ind, 'Value']
</code></pre>
<p>If you like to replace rows:</p>
<pre><code>for ind in df2.index:
df1.loc[ind,] = df2.loc[ind,]
</code></pre> | python|pandas|dataframe | 3 |
14,407 | 51,501,541 | Pandas Pivot_Table defined function aggfunc | <p>I am trying to apply a custom aggregation function to a pivot table, but keep receiving KeyError: 'PayoffUPB'. Is this a syntax problem with aggfunc, or do I need to use a lambda function here? Thank you for the help.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([201801,201801,201801,201802,201802,201802,2... | <p>We can using <code>groupby</code> with <code>unstack</code></p>
<pre><code>df.groupby(['Month','Program']).apply(CPR).unstack()
Out[310]:
Program a b c
Month
201801 45.963991 45.963991 21.528328
201802 27.928082 29.379551 35.364845
201803 55.3... | python|pandas|pivot-table | 2 |
14,408 | 51,338,508 | pandas: extend dataframe and increase indices automatically | <p>Given a <code>DataFrame</code> with a monotonically increasing index, e.g.</p>
<pre><code> values
100 10
200 9
300 15
400 7
</code></pre>
<p>I'd like to extend it by copying the last value, and automatically continue the indices (or perhaps by supplying the step, that's still fine):</p>
<pre><code... | <p>You could build a new index via</p>
<pre><code>index = 100 * pd.RangeIndex(start=1, stop=7)
</code></pre>
<p>and use it to reindex your DataFrame and fill the created NaN values with forwardfill.</p>
<pre><code>df = df.reindex(index).fillna(method='ffill')
</code></pre> | python|pandas|dataframe | 2 |
14,409 | 48,250,054 | Matplotlib: How to skip a range of hours when plotting with a datetime axis? | <p>I have tick-by-tick data of a financial instrument, which I am trying to plot using <code>matplotlib</code>. I am working with <code>pandas</code> and the data is indexed with <code>DatetimeIndex</code>.</p>
<p>The problem is, when I try to plot multiple trading days I can't skip the range of time between the marke... | <p><strong>TL;DR</strong></p>
<p>Replace the matplotlib plotting functions:</p>
<pre><code>top.plot(instrument.index, instrument['Price'])
bottom.bar(instrument.index, instrument['Volume'], 0.005)
</code></pre>
<p>With these ones:</p>
<pre><code>top.plot(range(instrument.index.size), instrument['Price'])
bottom.bar(ran... | python|pandas|datetime|matplotlib | 4 |
14,410 | 48,723,470 | numpy randint generation as a string | <p>I am trying to learn TensorFLow and NumPY, however, I appear to be having an issue with NumPY creating strings instead of an int.</p>
<p>here are the lines of code where the error occurs:</p>
<pre><code> data = int(np.random.randint(1000, size="10000"))
x = tf.constant(data, name="x")
</code></pre>
<p>and... | <p>Okay after a bit of messing around i figured it out as NumPY works like so:</p>
<pre><code>np.random.randint(low,high.size,dataType)
</code></pre>
<p>so the line of code to solve my problem is:</p>
<pre><code>data = np.random.randint(0,1000,10000,int)
</code></pre> | python|numpy|tensorflow | 1 |
14,411 | 48,719,863 | tflearn is not ported to tensorflow 0.12 on windows yet! Even with tensorflow 1.5 | <p>I currently have tensorflow-gpu 1.5, Python 3.5, and tflearn 0.3.2 installed however when I try running the sample code given <a href="https://github.com/pannous/tensorflow-speech-recognition/blob/master/speaker_classifier_tflearn.py" rel="nofollow noreferrer">here</a>, I get this error.</p>
<p><a href="https://i.s... | <p>Nevermind, there was an if statement in the actual code that was printing this error. </p>
<p>after running other tflearn sample code, I realized my tflearn is working fine.</p> | tensorflow|windows-10|tflearn | 0 |
14,412 | 48,728,847 | How to combine 2 level column index of DataFrame into a single column index? | <p>I have a DataFrame like below having 2 level column index, now I have to combine it into single level column index in a pattern like "Level1_Level2"</p>
<pre><code> CNT_LOAN CNT_RCHG
month 201605 201606 201607 201608 201609 201610 201605
id ... | <p>Use <code>list comprehension</code>:</p>
<pre><code>df.columns = ['{}_{}'.format(x, y) for x, y in df.columns]
print (df)
CNT_LOAN_201605 CNT_LOAN_201606 CNT_LOAN_201607 CNT_LOAN_201608 \
id
800008184 6.0 ... | python|pandas|data-analysis | 2 |
14,413 | 48,608,546 | Tensorflow Serving Git Repository Stale? Tensorflow folder does not exist | <p>I am attempting to create a Tensorflow server in accordance with the instructions. The <code>docker build</code> command works, as does the <code>docker run</code> command after it. However, when I attempt to cd into serving/tensorflow it tells me file does not exist. Indeed 'ls' command reveals that the serving dir... | <p>Thanks for the responses. The above suggestion did not work for me.</p>
<p>Fortunately, the following answer by zf109 from GitHub worked: </p>
<blockquote>
<p>you can try manually clone it:</p>
<p>cd /serving && git clone --recursive <a href="https://github.com/tensorflow/tensorflow.git" rel="nofoll... | linux|git|docker|tensorflow|tensorflow-serving | 1 |
14,414 | 48,448,647 | Splitting a DataFrame based on duplicate values in columns | <p>Here's my starting dataframe:</p>
<pre><code>StartDF = pd.DataFrame({'A': {0: 1, 1: 1, 2: 2, 3: 4, 4: 5, 5: 5, 6: 5, 7: 5}, 'B': {0: 2, 1: 2, 2: 4, 3: 2, 4: 2, 5: 4, 6: 4, 7: 5}, 'C': {0: 10, 1: 1000, 2: 250, 3: 100, 4: 550, 5: 100, 6: 3000, 7: 250}})
</code></pre>
<p>I need to create a list of individual datafram... | <p>You can use a <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a>, iterate over each group and build a list using a list comprehension.</p>
<pre><code>df_list = [g for _, g in df.groupby(['A', 'B'])]
</code></pre>
<p></p>... | python|pandas|dataframe | 2 |
14,415 | 48,764,485 | dlib face detection error : Unsupported image type, must be 8bit gray or RGB image | <p>i am trying to crop out the faces from instagram avatars by first detecting the faces and then resizing the image. i am reading all the images which have been stored in a dataframe and then creating a numpy array. Then i am running a frontal face detector which returns me an object but when i call the object it retu... | <p>Opencv reads image as BGR per default.</p>
<p>You can read images with cv2:</p>
<pre><code>import cv2
cv2.imread(image_filepath)
</code></pre> | python|image|numpy|face-detection|dlib | 2 |
14,416 | 70,966,642 | what is equivalent to torch.nn.fold in tensorflow? | <p>i want to convert torch.nn.fold function to tensorflow.</p>
<p>Is there any function just like nn.fold in tensorflow?
'''</p>
<pre><code>import torch
import torch.nn as nn
import torch.nn.functional as F
z = F.fold(z, kernel_size=s, output_size=(H1, W1), stride=s)
</code></pre>
<p>'''</p> | <p>It is not equivalent but if you want only the sliding window feature, there are some functions related to it.</p>
<ul>
<li><a href="https://www.tensorflow.org/text/api_docs/python/text/sliding_window" rel="nofollow noreferrer">https://www.tensorflow.org/text/api_docs/python/text/sliding_window</a></li>
<li><a href="... | tensorflow|pytorch|torch | 0 |
14,417 | 51,591,589 | concatenate rows on dataframe one by one | <p>I have 2 dataframes </p>
<pre><code>df1:
data type
0 a 1
1 b 1
2 c 1
3 d 1
4 e 1
df2:
data type
0 v 2
1 w 2
2 x 2
3 y 2
4 z 2
arr = [['a', 1], ['b', 1], ['c', 1], ['d', 1], ['e', 1]]
arr2 = [['v', 2], ['w', 2], ['x', 2], ['y', 2], ['z', ... | <p>One way is to change the indices of your input dataframes. Then concatenate and sort by index. This will also handle situations where your dataframes have mismatched lengths.</p>
<pre><code>df1.index = df1.index*2
df2.index = df2.index*2 + 1
res = pd.concat([df1, df2]).sort_index()
print(res)
data type
0 a... | python|python-3.x|pandas|dataframe|concat | 1 |
14,418 | 64,191,365 | Using List Comprehension to Make an Array to Plot | <p>I was asked to write some code to make a triangle wave and plot it. I originally wrote it using if/elif logic inside of a for loop. This works well and gives me the correct results, but it's so slow. I rewrote the code using list comprehension, but the plot ends up being misshapen and incorrect at times. I think the... | <p>I would suggest that your first method is preferable. You may like to consider using np.abs() in preference of np.sqrt(x**2) as this will slightly speed things up. Alternatively, you can just reduce the 8000 to a more reasonable number like 100. On my computer your code runs in 200ms, how much faster do you need it?... | python|numpy|matplotlib | 1 |
14,419 | 48,990,527 | How to efficiently sum each element of vector with matrix getting enlarged matrix | <p>I would like to achieve the following in an efficient way in numpy. Suppose I have a matrix</p>
<pre><code>A = np.asarray([[1, 2], [3, 4]])
</code></pre>
<p>and a vector of the following form</p>
<pre><code>B = np.asarray([7, 8, 9])
</code></pre>
<p>What I would like to achieve is the following: Take the first e... | <p>Add two new axes to <code>B</code> to its end and then perform addition, thus leveraging <code>broadcasting</code> and finally a reshape for <code>2D</code> output such that the number of columns is same as in <code>A</code> -</p>
<pre><code>In [396]: (A + B[:,None,None]).reshape(-1,A.shape[-1])
Out[396]:
array([[... | python-2.7|numpy | 2 |
14,420 | 58,775,094 | 2D bin (x,y) and calculate mean of values (c) of 10 deepest data points (z) | <p>For a data set consisting of:</p>
<ul>
<li>coordinates x, y</li>
<li>depth z</li>
<li>a certain value c</li>
</ul>
<p>I would like to do the following more efficient:</p>
<ol>
<li>bin the data set in 2D bins based on the coordinates (x, y)</li>
<li>take the 10 deepest data points (z) per bin</li>
<li>calculate th... | <p>you can use <code>np.searchsorted</code> to bin the rows by x and y and then use groupby to take 10 deep values and calculate means. As groupby will maintains the order in each group you can sort values before applying bins. groupby will perform better without apply</p>
<pre class="lang-py prettyprint-override"><co... | python|pandas|numpy | 0 |
14,421 | 58,843,269 | Display graph using Tensorflow v2.0 in Tensorboard | <p>Following code using TensorFlow v2.0</p>
<pre><code>import tensorflow as tf
a = tf.constant(6.0, name = "constant_a")
b = tf.constant(3.0, name = "constant_b")
c = tf.constant(10.0, name = "constant_c")
d = tf.constant(5.0, name = "constant_d")
mul = tf.multiply(a, b , name = "mul")
div = tf.divide(c,d, nam... | <p>It is possible to do this, in a couple of ways, but there are two problems. The main thing is that TensorFlow 2.0 generally works in eager mode, so there is no graph to log at all. The other issue that I have found, at least in my installation, is that with 2.0 Tensorboard crashes when I try to load a log directory ... | python-3.x|tensorflow|machine-learning|tensorboard | 6 |
14,422 | 58,647,988 | assign indices in order of appearance | <p>I have a dataframe</p>
<pre><code>> df = pd.DataFrame({"user_hash": ["b","a","c", "a"]})
> df
user_hash
0 b
1 a
2 c
3 a
</code></pre>
<p>where <code>user_hash</code> represents long hash values, so for clarity I'd like to add a column that just enumerates the elements in ord... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.factorize.html" rel="nofollow noreferrer">pd.factorize</a>:</p>
<pre><code>labels, _ = pd.factorize(df['user_hash'])
result = df.assign(user_id=labels)
print(result)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> user_ha... | python|pandas | 3 |
14,423 | 70,226,532 | How to search for faulty chats in python? | <p>This is the example of a chat in a dataframe: Suppose my list of faulty words contains : name , number etc. Example: list=["Name","number","crap"] How to return all sessions where words from the list exist and return that message with two lines above and below it where faulty words fro... | <p>You can use <code>str.contains('your_word')</code></p>
<p>For example, If you have a simple dataframe like this:</p>
<pre><code>df
row Text Msg
0 1 Hi, I m Python
1 2 Hey
2 3 Whats You name
3 4 What is you product number
</code></pre>
<p... | python|pandas | 0 |
14,424 | 70,247,729 | Replacing column values in pandas dataframe using "replace' | <p>I have a dataset where the part numbers are categorized into subinventories.</p>
<p>I want to replace some values, e.g. "COIL 8" with just "COIL", so I can group similar parts together. The data is an object in the dataframe. I've stripped out leading and trailing spaces. I've also copied the v... | <p>Basically you're replacing, but not saving the change.</p>
<p>Try :</p>
<pre><code>elemental_inv_df.replace({'Subinventory': 'COIL 8'}, {'Subinventory': 'COIL'}, regex=True, inplace = True)
</code></pre>
<p>or</p>
<pre><code> elemental_inv_df = elemental_inv_df.replace({'Subinventory': 'COIL 8'}, {'Subinventory': ... | python|pandas|dataframe|replace | 1 |
14,425 | 70,278,263 | Scipy, Pandas find maximum peak within subset of peaks | <p>Have a bit of a complicated scenario, hopefully the solution is easy!</p>
<p>I want to find the highest peak within a set time-frame of an acceleration.</p>
<p>An acceleration is defined as over 140. The acceleration starts when it crosses 140 and stops when it falls below 140.</p>
<p>Then what I want to do is find ... | <p>You could specify the minimum peak height directly in <code>find_peaks</code> (see <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html" rel="nofollow noreferrer">find_peaks</a>)</p>
<pre class="lang-py prettyprint-override"><code>peaks, _ = find_peaks(df['value'], height=140)
<... | python|pandas|scipy | 1 |
14,426 | 56,334,210 | How to extract sklearn decision tree rules to pandas boolean conditions? | <p>There are so many posts <a href="https://stackoverflow.com/questions/20224526/how-to-extract-the-decision-rules-from-scikit-learn-decision-tree">like this</a> about how to extract sklearn decision tree rules but I could not find any about using pandas.</p>
<p>Take <a href="https://www.datacamp.com/community/tutoria... | <p>First of all let's use the scikit <a href="https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html" rel="noreferrer">documentation</a> on decision tree structure to get information about the tree that was constructed :</p>
<pre><code>n_nodes = clf.tree_.node_count
children_left = clf.tree... | python|pandas|machine-learning|scikit-learn|decision-tree | 26 |
14,427 | 56,065,727 | Pandas - Replace values in column with other values from the same column | <p><strong>Dataframe</strong> with 3 columns:</p>
<pre><code>FLAG CLASS CATEGORY
yes 'Sci' 'Alpha'
yes 'Sci' 'undefined'
yes 'math' 'Beta'
yes 'math' 'undefined'
yes 'eng' 'Gamma'
yes 'math' 'Beta'
yes 'eng' 'Gamma'
yes 'eng' 'Omega'
yes 'eng' 'Omega'
yes 'eng' 'undefined'
yes 'Geog' 'Lambda'
yes '... | <p>I will using <code>ffill</code> and <code>bffil</code> within <code>groupby</code> </p>
<pre><code>s=df.CATEGORY.mask(df.CATEGORY.eq('undefined'))
s2=s.groupby(df['CLASS']).transform('nunique')
df.loc[s2.eq(1)&s.isnull(),'CATEGORY']=s.groupby(df.CLASS).apply(lambda x : x.ffill().bfill())
df
Out[388]:
FLAG C... | python|pandas | 2 |
14,428 | 56,369,565 | Large (6 million rows) pandas df causes memory error with `to_sql ` when chunksize =100, but can easily save file of 100,000 with no chunksize | <p>I created a large database in Pandas, about 6 million rows of text data. I wanted to save this as a SQL database file, but when I try to save it, I get an out of memory RAM error. I even reduced the chuck size to 100 and it still crashes. </p>
<p>However, if I just have smaller version of that dataframe with 100,00... | <p>I've used <strong>df.to_sql</strong> for 1 year and now I'm struggling with the fact I running big resources and it wasn't working. I realized that chucksize overload your memory, pandas loaded in memory and after that sent it by chuncks. I had to control directly using sql. (here is where I found the solution ->... | python|sql|pandas | 4 |
14,429 | 55,981,529 | Adding a new column for a certain condition for a combination of two column values in dataframe | <p>I have 3 columns in the table with last column as "Status" . I want the table to be grouped and to add a new column "Final Status" . Final Status should be "fail" if for any dept_id and session_id combination , the status is fail in original table. </p>
<p>My data and expected results looks like below : </p>
<pre>... | <p>You can also try this answer:</p>
<p><code>df.replace({'Pass':True,'Fail':False}).groupby(['Dept_id', 'Session_id']).all().reset_index().replace({'True':'Pass','False':'Fail'})</code></p> | python|python-3.x|pandas|python-2.7|pandas-groupby | 0 |
14,430 | 55,899,684 | Speed up turn probabilities into binary features | <p>I have a dataframe with 3 columns, in each row I have the probability that this row, the feature T has the value 1, 2 and 3</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(42)
df = pd.DataFrame({"T1" : [0.8,0.5,0.01],"T2":[0.1,0.2,0.89],"T3":[0.1,0.3,0.1]})
</code></pre>
<p>For row 0, T is 1 w... | <p>Here's one based on <a href="https://stackoverflow.com/a/40475357/">vectorized <code>random.choice</code> with a given matrix of probabilities</a> -</p>
<pre><code>def matrixprob_to_onehot(ar):
# Get one-hot encoded boolean array based on matrix of probabilities
c = ar.cumsum(axis=1)
idx = (np.random.ra... | python|pandas|performance|numpy|vectorization | 4 |
14,431 | 64,647,581 | create dataframe from list of list python | <p>I have list of list(t):</p>
<pre><code>[[{'CreationDate': b"D:20191125142104+05'00'",
'Creator': b'PDF-XChange Editor 7.0.325.1',
'ModDate': b"D:20191125142754+05'00'",
'Producer': b'PDF-XChange Core API SDK (7.0.325.1)'}],
[{'CreationDate': b"D:20200215153643+05'00'",
'Cre... | <p>Use concat and from_dict:</p>
<pre><code>df=pd.concat([pd.DataFrame().from_dict(x) for x in ls])
</code></pre> | python|pandas|list | 1 |
14,432 | 64,790,437 | How to convert the pandas row to custom json format and make a POST request | <p>My DataFrame contains the following columns and rows</p>
<pre><code>hosp doc dep p_t ins tpa p_n i_c t_date cat c_amt
ALZ Dr.M Onc SAICO SAISA AZBRONZE AZS 11 2020-08-11 Cons 341.25
ALZ Dr.K Card Mitra Mit ASGOLD ASG 8265 2020-08-15 Cons 1123.45
</code></pre>
<p>... | <p>Here is solution</p>
Since you would want to run this for all the rows present in the DataFrame, do the following
<pre><code># Number of rows
all_rows = len(df)
for i in range(all_rows):
# choose the first half of cols before "activities"
x = dict(df.iloc[i, 0:7])
# add the "activ... | python|pandas|dataframe|request | 0 |
14,433 | 40,061,889 | Problems mapping a series to a min(list, key=lambda x: abs(series)) function | <p>I want to find a number in <code>series</code>, and find which number it's closest to in <code>[1,2,3]</code>. Then use the <code>key</code> to replace the series value with the appropriate letter.</p>
<pre><code>key = {1: 'A', 2:'B', 3:'C')
series = pd.Series([x*1.2 for x in range(10)])
pd.DataFrame = key[min([1... | <p>use the <code>apply</code> method and then <code>map</code> your <code>Series</code> such has:</p>
<pre><code>key = {1: 'A', 2:'B', 3:'C'}
series = pd.Series([x*1.2 for x in range(10)])
def find(myNumber):
return min([1,2,3], key=lambda x:abs(x-myNumber))
series.apply(find).map(key)
Out[50]:
0 A
1 A
2 ... | python|pandas|numpy|dataframe|series | 1 |
14,434 | 44,170,132 | Add lists inside dictionary to DataFrame as new columns | <p>Let's say I have the following pandas DataFrame:</p>
<pre><code>df = pd.DataFrame({'x': [0, 1, 2], 'y': [3, 4, 5], 'z': [6, 7, 8]})
x y z
0 0 3 6
1 1 4 7
2 2 5 8
</code></pre>
<p>And the following dictionary:</p>
<pre><code>d = {'a': [10, 10, 10], 'b': [100, 100, 100]}
</code></pre>
... | <p>Use <code>assign</code> with dictionary unpacking </p>
<pre><code>df.assign(**d)
x y z a b
0 0 3 6 10 100
1 1 4 7 10 100
2 2 5 8 10 100
</code></pre>
<p>Note that with <code>assign</code> as long as the length of the lists is consistent with the dataframe, then the indices a... | python|pandas|dictionary | 4 |
14,435 | 69,554,112 | Create new columns by comparing the current row's values and previous in Pandas | <p>Given a dummy dataset <code>df</code> as follow:</p>
<pre><code> year v1 v2
0 2017 0.3 0.1
1 2018 0.1 0.1
2 2019 -0.2 0.5
3 2020 NaN -0.3
4 2021 0.8 0.0
</code></pre>
<p>or:</p>
<pre><code>[{'year': 2017, 'v1': 0.3, 'v2': 0.1},
{'year': 2018, 'v1': 0.1, 'v2': 0.1},
{'year': 2019, 'v1': -0.2, 'v2... | <p>You can specify columns for test trend by compare shifted values with filtered missing values:</p>
<pre><code>cols = ['v1','v2']
arr = np.where(df[cols] < df[cols].shift(),'decrease',
np.where(df[cols] > df[cols].shift(),'increase',
np.where(df[cols].isna() | df[cols].shift().isna(), None, 'equal')... | python-3.x|pandas|dataframe | 1 |
14,436 | 69,375,264 | Different aggregation for dataframe with several columns | <p>I am looking for some short-cut to reduce the manual grouping required:</p>
<p>I have a dataframe with many columns. When grouping the dataframe by 'Level', I want to group two columns using nunique(),but all other columns (ca. 60 columns representing years from 2021 onward) using mean().</p>
<p>Does anyone have an ... | <p>I would do it following way</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'X':[1,1,1,2,2,2],'A':[1,2,3,4,5,6],'B':[1,2,3,4,5,6],'C':[7,8,9,10,11,12],'D':[13,14,15,16,17,18],'E':[19,20,21,22,23,24]})
aggdct = dict.fromkeys(df.columns, pd.Series.mean)
del aggdct['X']
aggdct['A'] = pd.Series.nunique
print(df.gr... | python|pandas|group-by|pandas-groupby|aggregate-functions | 0 |
14,437 | 40,791,433 | Flatten a one-to-one mapping in a multiindex pandas dataframe | <p>I have the following data structure:</p>
<pre><code>from collections import OrderedDict
import pandas as pd
d = OrderedDict([
((5, 3, 1), {'y1': 1}),
((5, 3, 2), {'y2': 2}),
((5, 4, 1), {'y1': 10}),
((5, 4, 2), {'y2': 20}),
((6, 3, 1), {'y1': 100}),
((6, 3, 2), {'y2': 200}),
((6, 4, 1)... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> for remove <code>NaN</code>, because create <code>Series</code>, remove <code>third</code> level by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/p... | python|pandas | 2 |
14,438 | 40,951,782 | mpi4py does not speed up embarrisingly parallelizable code | <p>I am trying to diagonalize a large number of totally independent matrix computations using numpy.linalg, and openmpi/mpi4py on a 6-core intel xeon machine. </p>
<p>When running with N processes, each matrix computation seems to take N times longer so that the total time for the computation is the same (actually a b... | <p>I resolved the issue: the linear algebra was using MKL, with a default setting to use all available threads for one process, at which point there were no other resources for the other processes, and the parallel code was basically executing in serial with each process taking turns using the whole cpu.</p>
<p>To fix... | python|numpy|mpi|openmpi | 0 |
14,439 | 54,246,799 | The histograms' color and its labels are inconsistent | <p>I'm trying to analyze the <code>wine-quality</code> dataset. There are two datasets: the <code>red wine</code> dataset and the <code>white wine</code>. I combine them together to form the <code>wine_df</code>. I want to plot it. And I want to give the red histogram red color, the white histogram white color. But fo... | <p>The colors are a level of your index, so use that to specify colors. Change your line of code to:</p>
<pre><code>counts.plot(kind='bar', title='Counts by Wine Color and quality',
color=counts.index.get_level_values(1), alpha=.7)
</code></pre>
<p><a href="https://i.stack.imgur.com/0AfSw.png" rel="nofol... | python|pandas|matplotlib|seaborn | 1 |
14,440 | 53,919,836 | Conv 1x1 configuration for feature reduction | <p>I am using 1x1 convolution in the deep network to reduce a feature <strong>x</strong>: <code>Bx2CxHxW</code> to <code>BxCxHxW</code>. I have three options:</p>
<ol>
<li>x -> Conv (1x1) -> Batchnorm-->ReLU. Code will be <code>output = ReLU(BN(Conv(x)))</code>. Reference <a href="https://github.com/KaimingHe/deep-re... | <p>Since you are going to train your net end-to-end, whatever configuration you are using - the weights will be trained to accommodate them.</p>
<p><strong>BatchNorm?</strong><br>
I guess the first question you need to ask yourself is do you want to use <code>BatchNorm</code>? If your net is deep and you are concerned... | tensorflow|machine-learning|deep-learning|pytorch|conv-neural-network | 3 |
14,441 | 54,231,821 | TensorFlow 2 and Keras: | <p>When I want to use Keras with TensorFlow 2 I got this error: </p>
<blockquote>
<p>AttributeError: module 'tensorflow' has no attribute
'get_default_graph'</p>
</blockquote> | <p>The Keras API (<a href="https://keras.io/" rel="nofollow noreferrer">https://keras.io/</a>) has multiple implementations, including the original and reference implementation (<a href="https://github.com/keras-team/keras" rel="nofollow noreferrer">https://github.com/keras-team/keras</a>), but also various other imple... | tensorflow|tensorflow2.0 | 2 |
14,442 | 66,141,235 | Jupyter with docker: __init__() got an unexpected keyword argument 'column' | <p>I recently installed TensorFlow with GPU support using docker:</p>
<pre><code>docker pull tensorflow/tensorflow:latest-gpu-jupyter
</code></pre>
<p>But sometimes when I start a jupyter notebook server using the command:</p>
<pre><code>docker run --gpus all -it -p 8888:8888 tensorflow/tensorflow:latest-gpu-jupyter ju... | <p>This seems to be an incompatibility between jedi and ipython, see <a href="https://github.com/ipython/ipython/issues/12740" rel="nofollow noreferrer">this issue</a>.</p>
<p>The fix would be to pin jedi to 0.17.2, so either run:</p>
<pre><code>pip install jedi==0.17.2
</code></pre>
<p>Or if you are using poetry add t... | python|docker|jupyter-notebook|tensorflow2.0 | 4 |
14,443 | 66,272,814 | Date column's format changing in pandas -python | <p>I have a dataframe <code>df</code> with <code>Date</code> column:</p>
<pre><code>Date
--------
Wed 23 Dec
Sat 28 Nov
Thu 26 Nov
Sun 22 Nov
Tue 1 Dec
Wed 2 Dec
</code></pre>
<p>The <code>Date</code> column is <code>object-type</code>, I want to change the format using <code>format="%m-%d-%Y"</code> into <co... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with format specified original data with added year, get column filled by datetimes:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date']+'2020', format="%a %d ... | python|python-3.x|pandas|dataframe|datetime | 1 |
14,444 | 66,024,675 | Python Pandas - how to merge the disjoint content of two dataframes (of same dimensions) into a single dataframe | <p>I have two dataframes which are the same shape (identical index and column names) and both sparsely populated. The populated cells in the two dataframes are guarenteed to be disjoint e.g. is cell A1 in df1 is populated, the corresponsing cell in df2 is guaranteed not to be. I want to merge the contents of these two ... | <p>You can do <code>concat</code> and <code>dropna</code> with <code>all</code> condition:</p>
<pre><code>df=pd.concat([df1,df2],axis=0).replace('',np.NaN).dropna(how='all').sort_index().fillna('')
df
Out[21]:
Fruit Veg
0 Apple Onion
1 Banana Parsnip
2 Orange
3 Carrot
</code></pre> | python|pandas|dataframe|merge | 1 |
14,445 | 52,547,223 | x-axis dates not showing up on matplotlib when importing data from pandas DataReader | <p>I'm using pandas DataReader to graph stock charts in matplotlib, but the dates don't show up on the x-axis when I use the following code: </p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import datetime as dt
from datetime import datetime
import pandas_datareader.data as web
s... | <p>I think you should change your index to <code>datetime</code> format </p>
<pre><code>spy.index=pd.to_datetime(spy.index)
</code></pre>
<p>Then , pass the xlim by using <code>Timestamp</code></p>
<pre><code>spy['open'].plot(xlim=[pd.Timestamp('2018-01-01'),pd.Timestamp('2018-02-28')])
</code></pre>
<p><a href="ht... | python|pandas|matplotlib|pandas-datareader | 0 |
14,446 | 52,847,125 | How to change numeric numpy array to char array? | <p>I want to change a numeric numpy array to char array using python,for example,</p>
<pre><code>a = np.arange(25).reshape([5,5])
</code></pre>
<p>How to change array a to char array ?</p> | <p>You can change the datatype of the numpy array by using <code>astype</code> method. Try below example:</p>
<pre><code>import numpy as np
a = np.arange(25).reshape([5,5])
a.dtype #check data type of array it should show int
new = a.astype(str) #change data type of array to string
new.dtype #Check the data type... | python|numpy | 8 |
14,447 | 58,460,698 | Combine several rows into one row by column value, and split into several dataframes based on number of concatenated rows, for several columns | <p>This is a followup to this SO question: <a href="https://stackoverflow.com/questions/58459681/concatenate-several-rows-into-one-row-by-column-value-and-split-resulting-dataf">Concatenate several rows into one row by column value, and split resulting dataframe into several dataframes based on number of concatinated r... | <p>Develop from @Wen solution. Instead of <code>pivot</code>, use <code>pivot_table</code></p>
<pre><code>df['New']=df.groupby('Age').cumcount()
s= df.pivot_table(index='Age',columns='New',
values=['Name', 'Location'],
aggfunc='first').reindex(['Name', 'Location'], axis=1, level=0)... | python|pandas | 1 |
14,448 | 69,292,517 | How to decompose cohort data? | <p>I'm trying to decompose cohort data into time series for further analysis. I'm imagining the algorithm pretty well, but my code doesn't work at all.</p>
<p>The input data in <code>df</code> is like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Cohort Day</th>
<th>0</th>
<th>1</th>
<th... | <p>Avoid using looping codes which are slow. Use fast vectorized Pandas built-in functions whenever possible.</p>
<p>You can transform the dataframe from wide to long by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>.stack()</code></a>.... | python|pandas|loops|for-loop | 2 |
14,449 | 68,916,331 | PYTHON: Identify Non-English words in a Pandas dataframe using enchant library | <p>I like working with <code>pandas</code> due to my affinity to <code>tidyverse</code> in <code>R</code> when dealing with tables. I have a table of about 200,000 rows and need to replace punctuations and extract non-English words, and put it another column named <code>non_english</code> in the same table. I prefer us... | <p>remove str from word.str.split(' '), it will work fine.
Try this:
words = word.split(' ')</p> | python|pandas|text|nlp | 0 |
14,450 | 44,746,507 | Keras + TensorFlow Realtime training chart | <p>I have the following code running inside a Jupyter notebook:</p>
<pre><code># Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
... | <p>There is <a href="https://github.com/stared/livelossplot" rel="noreferrer">livelossplot</a> Python package for live training loss plots in Jupyter Notebook for Keras (disclaimer: I am the author).</p>
<pre><code>from livelossplot import PlotLossesKeras
model.fit(X_train, Y_train,
epochs=10,
vali... | python|machine-learning|tensorflow|keras|jupyter-notebook | 24 |
14,451 | 60,920,672 | Time distributed layer keras | <p>Iam trying to understand the time distributed layer in keras/tensorflow.
As far as I have understood it is a kind of wrapper, making it possible to in example process a sequence of images.</p>
<p>Now Iam wondering how would design a time distributed network without using the time distributed layer.</p>
<p>In exam... | <p>I created a prototype for you. I used the least number of layers and arbitrary units/kernels/filters, change them as you like. It creates a cnn model first that takes inputs of size (256,256,1). It uses the same cnn model 3 times (for your three images in the sequence) to extract features. It stacks all the features... | tensorflow|keras | 1 |
14,452 | 60,810,331 | How to manually add labels to plot or map the dictionary efficiently to display on your plot | <p>I am working with two <code>Pandas dataframes</code>. In the first <code>dataframe</code>. I am interested in matching the <code>ProductID</code> with the <code>CompanyName</code> that purchased a product. </p>
<p>In order to solve this problem matching. I first create an <code>empty dictionary</code> and then <cod... | <p>I figured the best way to solve this problem was to indeed convert the two columns of interest to a dictionary and then map that dictionary to the column. </p>
<pre><code>map_obj = dict(df[['ProductID', 'CompanyName']].values)
df['Product_Company'] = df['ProductID'].map(map_obj)
</code></pre> | python|pandas|dataframe|dictionary|matplotlib | 0 |
14,453 | 61,038,455 | How to count at multiple levels in pandas dataframe? | <p>Sorry for not being able to provide with the code. I solved this problem in SAS, now I want to do the same in Python.</p>
<p>In the following dataframe, there are several instances of consecutive zeros:</p>
<pre><code>Date Time Ask Bid Day Price Return
xxx xxx xxx ... | <p>Use:</p>
<pre><code>#filter 0 values - if strings use '0'
mask = df['Return'].eq(0)
#consecutive groups for 0
g1 = df['Return'].ne(df['Return'].shift()).cumsum()
#consecutive groups for Days
g2 = df['Day'].ne(df['Day'].shift()).cumsum()
#filter by 0 rows and aggregate counts
df1 = (g2[mask].groupby([g1, df['Day']])... | python|pandas|dataframe | 1 |
14,454 | 71,503,386 | Query data frame in python pandas, can't save query | <p>I have a list of data frames that I'm opening in a for loop. For each data frame I want to query a portion of it and find the average.</p>
<p>This is what I have so far:</p>
<pre><code>k = 0
for i in open('list.txt', 'r'):
k = k+1
i_name = i.strip()
df = pd.read_csv(i_name, sep='\t')
#Create querie... | <p>This does not do what you expect:</p>
<pre><code> A = df.query('location == 1' and '1000 >= start <= 120000000')
B = df.query('location == 10' and '2000000 >= start <= 60000000')
</code></pre>
<p>You are doing the Python "and" of two strings. Since the first string has a True value, the... | python|pandas | 4 |
14,455 | 71,607,949 | Fetch only the column content which has Latin or special characters in DT25 column | <p>I am trying to reduce a csv file content based on first_name column, when I say reduce, I am trying to filter out only those rows which contain latin characters in it.</p>
<p>my data looks like this,</p>
<pre><code>A_ID ID_NUMBER DT25 DT45
abcd 0001 Condé and Geoff S... | <p>You can use the regular expression <code>[^\t-\r -~]</code>:</p>
<pre><code>filtered = df[df['DT25'].str.contains('[^\t-\r -~]')]
</code></pre>
<p>Output:</p>
<pre><code>>>> filtered
A_ID ID_NUMBER DT25
0 abcd 1 Condé and Geoff Shallard
1 abcd... | python|pandas|dataframe|numpy | 1 |
14,456 | 71,648,157 | How can I join/merge 2 DataFrames, keeping values from the second? | <p>I have two DataFrames with user details and scores. Some users have a second score and will be present in the second DataFrame. What I want to do is to join or merge them together (don't really mind which) to get their final score i.e. if they exist in the second DataFrame then take it from there, otherwise from the... | <p>Use <code>pd.concat</code> and <code>drop_duplicates</code>:</p>
<pre><code>out = pd.concat([df2, df1]).drop_duplicates(['first_name', 'last_name', 'email'])
print(out)
# Output
first_name last_name email score feedback
0 Bill First user1@example.com 100.0 Much be... | python|pandas|dataframe | 2 |
14,457 | 71,664,840 | Installing GeoPandas on Spyder 5.1.5 | <p>Since updating Spyder to version 5.1.5, I'm unable to install GeoPandas. I've tried the following:</p>
<p><code>conda install geopandas</code></p>
<p><code>conda install --channel conda-forge geopandas</code></p>
<p><code>conda install -c conda-forge geopandas</code></p>
<p>and</p>
<pre><code>conda create -n geo_env... | <p>After some research and a <a href="https://stackoverflow.com/questions/69704561/cannot-update-spyder-5-1-5-on-new-anaconda-install">helpful post</a>, I figured out a solution. There must have been an error when I previously updated Spyder to 5.1.5, and even though I had uninstalled and reinstalled Anaconda a number ... | python|anaconda|spyder|geopandas | 0 |
14,458 | 71,722,093 | Pandas sort and limit groups after group by | <p>I want to create dataframe showing sales for a given year. The end goal is to show three products with the highest sales in the entire year, but with figures broken down by quarter.</p>
<p>I created dataframe <code>result</code> based on another dataframe <code>df</code> containing relevant data</p>
<p><code>result ... | <p>IIUC, you need a second groupby after sorting the values:</p>
<pre><code>(df
# group (as columns) and sum
.groupby(['Product', 'Order Date'], as_index=False).sum()
# now sort the values
.sort_values(by='Quantity Ordered')
# keep the top 3 per date
.groupby('Order Date').head(3)
)
</code></pre>
<p><em>NB. untested as... | python|pandas|dataframe | 0 |
14,459 | 71,709,364 | GridSearchCV & BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable | <p>I'm running a GridSearchCV for NLP data, this is the code I'm using:</p>
<pre><code>%%time
# Next we can specify the hyperparameters for each model
param_grid = [
{
'transformer': list_of_vecs,
'scaler': [StandardScaler()],
'model': [LogisticRegression()],
'model__penalty': ['l1', 'l2'],
... | <p>You can fix it by removing the <code>n_jobs=-1</code>. However, I am not sure how to fix and also allow parallel processing. Another thing you could try is to set the <code>pre_dispatch</code>. It controls the number of jobs that get dispatched during parallel execution. The default value is 2 times the <code>n_jobs... | python|pandas|dataframe|pickle|gridsearchcv | 0 |
14,460 | 69,862,217 | How to calculate Euclidian distance when arrays have different dimensions? | <p>I am trying to compute Euclidian distance step by step. Since Euclidian distance is: Dsqr = S+R-2*G, I am calculating each element separately.</p>
<p>Here is what I have so far:</p>
<pre><code>import numpy as np
# Create X matrix
X = np.array([[1,2],[3,4]])
Z = np.array([[1,4],[2,5],[3,6]])
# Calculate G from X us... | <p>Think about distances:</p>
<ul>
<li>the distance from your base camp to peak of Mount Everest on a 2-dimensional map X is one thing</li>
<li>in the real world situation Z it is 3-dimensional and so it is an other thing</li>
</ul>
<p>I think it is more appropriate to use the content of your data to find the adaption ... | python-3.x|numpy | 0 |
14,461 | 69,812,267 | Is it possible to use image_dataset_from_directory() with convolutional autoencoders in Keras? | <p>There is a similar question <a href="https://stackoverflow.com/questions/68261201/how-can-i-use-image-dataset-from-directory-with-autoencoder">here</a> which asks how to use <code>image_dataset_from_directory()</code> with autoencoder. Question is actually unanswered, because answer suggests using something else.</p... | <p>It is definitely possible, you just have to adjust your inputs to your model beforehand:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.ut... | python|tensorflow|keras|deep-learning|tensorflow-datasets | 7 |
14,462 | 69,873,161 | How to create a 3 X 3 Matrix will all ones in it using NumPy | <p>I am learner , bit stuck with it
Not getting how do I create below 3 X 3 matrix will all 1 ones in it</p>
<pre><code> 1 , 1 , 1
1 , 1 , 1
1 , 1 , 1
</code></pre>
<p><strong>My code :</strong></p>
<pre><code>import numpy as np
arr=np.ones(np.full(1)).reshape(3,3)
arr
</code></pre> | <p>What about this:</p>
<pre><code>>>> np.ones((3,3))
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>> np.ones((3,3)).dtype
dtype('float64')
</code></pre>
<p>if You want <code>int</code></p>
<pre><code>>>> np.ones((3,3), dtype='int')
array([[1, 1, 1],
[1, 1, 1],
... | python|arrays|numpy | 3 |
14,463 | 43,432,765 | How to create a "subtraction matrix"? -python | <p>I am a novice programmer.</p>
<p>I would like to create a "subtraction matrix." (I lack the vocabulary to describe it). I would like to create a matrix from all the combination of subtractions.</p>
<pre><code>v = [1, 5, 10]
0 4 9
4 0 5
9 5 0
</code></pre>
<p>I think I am missing something very basic ... | <p>You can use the <code>outer</code> method of the <code>subtract</code> ufunc. <code>outer</code> applies the operation (in this case subtraction) to every possible pair and arranges the result in a matrix:</p>
<pre><code>v = [1, 5, 10]
np.absolute(np.subtract.outer(v, v))
# array([[0, 4, 9],
# [4, 0, 5],
# ... | python|numpy|scipy | 2 |
14,464 | 72,204,374 | Pandas group by and fraction where two columns equal | <p>I want to get the fraction of rows where two columns are equal, where I group by another column.</p>
<p>In the example below, I want to group by col1, and compare col2 == col3.</p>
<p>Input:</p>
<pre><code>col1 | col2 | col3
A | c | c
A | d | g
B | c | c
B | d | d
</code></pre>
<p>Desired... | <h2><code>groupby</code> + <code>mean</code>:</h2>
<pre><code>df['col2'].eq(df['col3']).groupby(df['col1']).mean()
</code></pre>
<hr />
<pre><code>col1
A 0.5
B 1.0
dtype: float64
</code></pre> | python|pandas | 1 |
14,465 | 62,639,216 | Compute different dataframes using a foor loop based on df.columns | <p>I have a pandas dataframe with a date column and 10 other columns with values. Now I want to have 10 dataframes where each dataframe has the date column and one of the other columns.</p>
<p>What I tried is this:</p>
<pre><code>for i in df.columns:
i = df[["Datum", i]]
print(i)
</code></pre>
<p>df.c... | <p>You can do something like this.</p>
<pre><code>dfs = {col : df[['Datum', col]] for col in df.columns[1:]}
dfs['Alle'].info()
</code></pre> | python|pandas|loops|dataframe | 0 |
14,466 | 62,588,549 | Combining rows where values in df1 correspond to values in df2 | <p>I have two large data sets that look like similar to the following</p>
<p>DataFrame <code>df1</code>:</p>
<pre><code>P Y p_start p_stop
p1 y1 7 9
p2 y2 6 7
p3 y3 12 14
</code></pre>
<p>DataFrame <code>df2</code>:</p>
<pre><code>T t_start t_stop
t1 5 ... | <p>Use:</p>
<pre><code># STEP 1
df3 = df2.assign(key=1).merge(df1.assign(key=1), on='key').drop('key', 1)
# STEP 2
df3 = df3[df3['t_start'].lt(df3['p_start']) & df3['t_stop'].gt(df3['p_stop'])]
# STEP 3
df3 = df3.melt(['T', 't_start', 't_stop'])
# STEP 4
df3['variable'] += '_' + df3.groupby(['T', 't_start', 't_s... | python|pandas|dataframe|append | 0 |
14,467 | 73,787,169 | How to turn a numpy array (mic/loopback input) into a torchaudio waveform for a PyTorch classifier | <p>I am currently working on training a classifier with PyTorch and torchaudio. For this purpose I followed the following tutorial: <a href="https://towardsdatascience.com/audio-deep-learning-made-simple-sound-classification-step-by-step-cebc936bbe5" rel="nofollow noreferrer">https://towardsdatascience.com/audio-deep-l... | <p>According to the doc, you will get a <code>numpy</code>array of shape frames × channels. For a stereo microphone, this will be <code>(N,2)</code>, for mono microphone <code>(N,1)</code>.</p>
<p>This is pretty much what the <code>torch</code> <code>load</code> function outputs: <code>sig</code> is a raw signal, and ... | python|pytorch|wav|waveform|audio-processing | 1 |
14,468 | 73,803,147 | How to find row number in a dataframe(data imported from a csv file) if one or few columns in a row has null value | <p>I have to find the row number from the dataframe where there is null values in specific columns. Which pandas function shall I use?</p> | <p>Considering the dataframe below :</p>
<pre><code>import pandas as pd
import numpy as np
data_dict = {'col1': [np.nan, 'bar', 'baz','missing'],
'col2': ['', 'foo', np.nan, 'bar'],
'col3': [249,np.nan,924,np.nan]
}
df = pd.DataFrame (data_dict)
print(df)
col1 col2 col3
... | python-3.x|pandas | 1 |
14,469 | 73,809,615 | Pandas equivalent of R merge all=TRUE | <p>apologies if this sounds like a dumb question, I haven't worked on Pandas for a long time.</p>
<p>I've two data frames, Nodes:</p>
<p><a href="https://i.stack.imgur.com/6hBdI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6hBdI.png" alt="Nodes" /></a></p>
<p>Rate Card:</p>
<p><a href="https://i.s... | <p>IIUC I believe you are looking for pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with option <code>how=cross</code>:</p>
<pre><code>select_cols = ['service', 'duration', 'rate']
nodes.merge(rate_card[select_cols], how='cross... | python|pandas | 1 |
14,470 | 71,224,709 | Count the number of clients that have bought in different stores in my dataframe | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>client</th>
<th>product</th>
<th>store</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>toy1</td>
<td>10</td>
</tr>
<tr>
<td>001</td>
<td>toy2</td>
<td>20</td>
</tr>
<tr>
<td>003</td>
<td>toy3</td>
<td>10</td>
</tr>
<tr>
<td>004</td>
<td>toy4</td... | <p>Try this:</p>
<pre><code>new_df = df.groupby('client')['store'].count().value_counts().to_frame().sort_index().T.add_suffix(' store').reset_index(drop=True)
</code></pre>
<p>Output:</p>
<pre><code>>>> new_df
1 store 2 store 3 store
0 1 1 1
</code></pre> | python|pandas|dataframe | 1 |
14,471 | 52,371,705 | Apply timezone offset to datetime in Python | <p>For a given date string such as <code>2009-01-01T12:00:00+0100</code> I want the UTC datetime object. </p>
<pre><code>from datetime import datetime
datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z")
</code></pre>
<p>returns</p>
<pre><code>datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=dateti... | <p>This feels a bit dirty but it does work</p>
<pre><code>from datetime import datetime
orig_dt = datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z") # datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
utc_time_value = orig_dt - orig_dt.utcoffset()
utc_... | python|pandas|datetime|timezone|timezone-offset | 7 |
14,472 | 52,267,157 | How to find values that occur specific number of times in Pandas Series? | <p>Given the following Series:</p>
<pre><code>sr = pd.Series([5, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8])
</code></pre>
<p>I want to find the values that occur 3 times. This is my solution which seems to work but looks very strange:</p>
<pre><code>(sr.value_counts() == 3)[sr.value_counts() == 3].index.values
</code></pre>
<p... | <p>Your logic is fine, you just shouldn't repeat the most expensive part, which is the counting. Store this in a variable and reuse. You may also not need to retrieve the underlying NumPy array, <code>pd.Index</code> objects are often sufficient:</p>
<pre><code>sr = pd.Series([5, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8])
counts... | python|pandas|counter|series | 3 |
14,473 | 52,036,505 | Key error adding two Pandas data-frames together | <p>Frames <code>df1</code> and <code>df2</code> that I'd like to add together to make <code>df3</code>. Partial data-frames (as they are quite large) are as follows</p>
<p><code>df1</code>:</p>
<pre><code> total_pnl_per_pos invested
date
2015-03-17 0.330533 145790.529585
201... | <p>It looks like <code>date</code> is already index. In other words, you cannot assign <code>date</code> as index <strong>twice</strong>. Thus below would work:</p>
<pre><code>df3 = df1.add(df2, axis='index', fill_value=0)
</code></pre>
<p>Output:</p>
<pre><code> total_pnl_per_pos invested
date ... | python|pandas | 1 |
14,474 | 72,700,400 | How to print the three rows with the highest values in a single column in a pandas dataframe | <p>I have a pd.dataframe that look like this:</p>
<pre><code> 0 1
0 10 0.9679487179487178
1 38 0.9692307692307693
2 24 0.9833333333333332
3 62 0.9525641025641025
4 17 0.9679487179487178
5 23 0.9679487179487178
6 72 0.9679487179487178
7 22 0.9538461538461538
8 90 0.9525641025641025
9 32... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.nlargest.html" rel="nofollow noreferrer"><code>pandas.DataFrame.nlargest</code></a></p>
<pre class="lang-py prettyprint-override"><code>out = df.nlargest(3, '1')
</code></pre>
<pre><code>print(out)
0 1
2 24 0.983333
1 ... | python|pandas | 2 |
14,475 | 72,731,022 | How to run scipy.stats.gmean for rows contanining values less than 1 and zeros? | <p>We have the following dataframe (df)</p>
<p><code>print(df)</code></p>
<pre><code> #Gene GSM772 GSM773 GSM774 GSM775 GSM776
0610007P14Rik 0.003485 0.003415 0.005431 0.003667 0.007146
0610009B22Rik 0.001220 0.001351 0.001762 0.001404 0.002177
0610009L18Rik 0.000055 0.000009 ... | <p>Problem solved. Actually, the above script works without any issue.
Sorry, this question was posted without hindsight. We cannot delete any question, so this will stay here.
Hope the script is useful for someone.</p>
<p>Note, that this script will not work if the dataframe contains any column with strings. After rem... | python-3.x|numpy|scipy|statistics|geometric-mean | 0 |
14,476 | 72,542,309 | Calculation of the sales in the last 6 months | <p>I have a problem. I would like to calculate the turnover customer-specifically for the last 6 months. I have already calculated when the "end date" is (i.e. until where the 6 months go). I would now like to calculate per row and customer-specifically what he has purchased from the purchasing department in ... | <p>You can basically use <code>sum()</code> in combination with a location that fits your criterion:</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
from dateutil.relativedelta import relativedelta
import pandas as pd
def find_last_date(date_: datetime) -> datetime:
six_month... | python|pandas|dataframe|date | 1 |
14,477 | 72,737,553 | How do i create separate columns from one column for this Pandas Dataset | <p>data set:</p>
<p><img src="https://i.stack.imgur.com/wFwQF.png" alt="data set" /></p>
<p>In this data set genres column have multiple strings which i want to separate in a column for every movie! can that be possible in pandas or how can we do that?</p> | <pre class="lang-py prettyprint-override"><code>df['genres'].str.split(',',expand=True)
</code></pre> | pandas|dataframe | 1 |
14,478 | 61,779,593 | pandas: modify a string value based on its rank in column | <p>I am trying to modify the value of a string based on the rank of that string in the column. I am stuck and I can't find resources to troubleshoot. </p>
<p>Here is what the problem looks like:</p>
<pre><code> Id Supplier Quantity
0 001 XXX 10
1 001 XYZ 12
2 002 XWA 9
3 0... | <p>You don't need <code>groupby</code> for the easy part:</p>
<pre><code>dataset = datatest.sort_values(['Id','Quantity'], ascending=[True, False])
dataset.loc[dataset.duplicated('Id'),'Id'] += '-S'
</code></pre>
<p>Output:</p>
<pre><code> Id Supplier Quantity
0 001 XXX 10
1 001-S XYZ ... | python|pandas | 2 |
14,479 | 61,816,696 | function with date parameter to run on dataframe | <p>I have a dataframe:</p>
<p>df = </p>
<pre><code> |date months_left amount
0|06/09/2019 34 150000
1|25/12/2019 23 70000
2|13/01/2020 7 85000
...
</code></pre>
<p>I want to define a function that takes a date parameter and runs through each row in the dataframe. It ... | <p>First make sure your <code>date</code> column is a datetime</p>
<pre><code>df["date"] = pd.to_datetime(df["date"]) # note it is better to do this when you read the data
</code></pre>
<p>Then you can use <a href="https://stackoverflow.com/a/59719009/1011724">this approach</a> to figure out if you are before the en... | python|pandas|dataframe|datetime | 0 |
14,480 | 61,718,447 | Merging values from columns in Pandas Dataframe | <p>Before I start, my disclaimer is that I'm very new to Python and I've been building a flask app in an effort to learn more, so my question might be silly but please oblige me.</p>
<p>I have a Pandas Dataframe created from reading in a csv or excel doc on a flask app. The user uploads the document, so the dataframe ... | <p>Sounds like what you want to do is more like an element-wise concatenation, not a merge. </p>
<p>If I understand you correctly, you can get your desired result with a list comprehension creating a nested list that is turned into a pandas Series by assigning it as a new DataFrame column:</p>
<pre class="lang-py pre... | python|pandas|dataframe | 1 |
14,481 | 61,729,503 | How to get the first date with the first value, by country in a Dataframe - Python | <p>I would like to get the first date with value > 0 in a dataframe.</p>
<p>It seems like really simple, but I can't thing anything really clear. The thing is I need to get is grouped by country.</p>
<p>I have tried to use like that:</p>
<pre><code>result.head(1000)
Out[5]:
Confirmed Deaths Rec... | <p>IIUC you need:</p>
<pre><code>result.query('Confirmed > 0').groupby('Country/Region').head(1)
</code></pre> | python|pandas|dataframe | 1 |
14,482 | 61,648,443 | Keras NLP validation loss increases while training accuracy increases | <p>I have looked at other posts with similar problems and it seems that my model is overfitting. However, I've tried regularization, dropout, reducing parameters, decreasing the learning rate and changing the loss function, but nothing seems to help.</p>
<p>Here is my model:</p>
<pre><code>model = Sequential([
Embedd... | <p>You're doing a binary classification and your validation accuracy is near 50%. It just means your model learnt nothing useful, it's equivalent to random prediction.</p>
<p>Your training accuracy is really high, which suggests your model is badly overfitted.</p>
<ol>
<li><p>Don't apply dropout after embedding layer... | tensorflow|keras|nlp|word-embedding|hyperparameters | 2 |
14,483 | 54,834,637 | Why won't apply reduce my single-column DataFrame to a Series? | <p>I'm getting the error </p>
<pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>I'm not sure why. The <code>samples</code> is a (3681, 58) DataFrame. <code>predictions</code> ends up being a (3681, 1) DataFrame as well, instead of a ... | <p>Since prediction is a DataFrame:</p>
<pre><code>predictions.iloc[i] == targets.iloc[i]
</code></pre>
<p>is a Series rather than a boolean.</p>
<p>Perhaps you want to use equals?</p>
<pre><code>predictions.iloc[i].equals(targets.iloc[i])
</code></pre> | python-3.x|pandas | 0 |
14,484 | 49,522,484 | Create column by comparing two data frames with groupby | <p>I've got one large data frame with columns like so:</p>
<pre><code>TimeHrs A B SeqNum
</code></pre>
<p>I want to figure out if the max of A for each group grouped by the SeqNum happens within +/-2 seconds of the max of B. For now, I've got a groupby going for each to obtain the rows of the max values of ... | <p>Is there any reason why you can't perform this in 2 steps?</p>
<p>In the below example, you find the max of each column groupwise, then perform your comparison using <code>pd.Series.between</code>.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[8, 10, 1], [1, 4, 1], [5, 8, 1],
[5, 15, ... | python|pandas | 1 |
14,485 | 49,438,163 | trying to understand .loc in pandas - python | <pre><code>df=pd.DataFrame({'a':[1,2,3,4,5,6,7,8],'b':['g1','g1','g1','g1','g2','g2','g2','g2'],'c':['v1','v2','v1','v2','v1','v2','v1','v2']})
df.set_index(['b','c'], inplace=True)
>> df
a
b c
g1 v1 1
v2 2
v1 3
v2 4
g2 v1 5
v2 6
v1 7
v2 8
</code></pre>
<p>why does <code>df... | <p>In this example the dataframe has multiindex (i.e. indexed over several columns). So, row keys are iterables instead of a single value. So, in the <code>df.loc['g1','v1']</code> example pandas interprets <code>('g1','v1')</code> as a row index instead of firsrt column of multiindex and a column.</p>
<p>If you want ... | python|pandas|indexing | 1 |
14,486 | 49,452,941 | Creating appropriate input_fn in DNNClassifier TensorFlow | <p>I'm building a neural network with DNNClassifier and I've read the examples on the site, and done by others, about this estimator, but I'm still confused on the construction of the input_fn. I post my code below</p>
<pre><code>import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.model_selecti... | <p>The <code>indicator_column</code> function requires a <code>_CategoricalColumn</code>, but you're calling it with the <code>_NumericColumn</code> returned by <code>numeric_column</code>. I think you can obtain a <code>_CategoricalColumn</code> by calling <code>bucketized_column</code>.</p> | python|tensorflow|tensorflow-datasets|tensorflow-estimator | 0 |
14,487 | 73,317,612 | Bringing together transformations in pandas and TDD practices | <p>So I have read <a href="https://www.aidancooper.co.uk/pandas-anti-patterns/" rel="nofollow noreferrer">this article on pandas anti-patterns</a> and in the article it mentions the following: when you want to apply a set of transformation to a dataframe, you should chain them:</p>
<pre><code># Mutation - DON'T DO THIS... | <p>In my own personal experience, I would say that in your particular scenario it depends on what you are aiming to test:</p>
<ol>
<li>Test individual transformation steps that are subsequently applied to a pandas DataFrame</li>
<li>Test the final output of your transformation pipeline steps</li>
</ol>
<p>For scenario ... | python|pandas|tdd | 0 |
14,488 | 73,300,957 | Pandas remove NaN and move all value on the same line | <p>I have a simple list that want to convert it to excel using pandas.
I googled about how to remove NaN, but they all talk about remove either whole row or column.
Is there a way to put all the value on the same line?</p>
<pre><code>list = [{'cisco': 15}, {'developer': 15}, {'root': 15}]
df = pd.DataFrame(list)
</code... | <p>You should consider the values as a list, Below format works</p>
<p>df_list = {'cisco': [15], 'developer': [15], 'root': [15]}</p>
<p>df = pd.DataFrame(df_list)</p> | python|pandas | 0 |
14,489 | 73,286,708 | Python Limit time to run pandas read_html | <p>I am trying to limit the time for running <em>dfs = pd.read_html(str(response.text))</em>. Once it runs for more than 5 seconds, it will stop running for this url and move to running the next url. I did not find out timeout attribute in <em>pd.readhtml</em>. So how can I do that?</p>
<pre><code>
from bs4 import Beau... | <p>I'm not certain what the issue is, but pandas seems to get overwhelmed by this file. If we utilize <code>BeautifulSoup</code> to instead search for tables, prettify them, and pass those to <code>pd.read_html()</code>, then it seems to be able to handle things just fine.</p>
<pre><code>from bs4 import BeautifulSoup
i... | python|python-3.x|pandas | 1 |
14,490 | 67,485,731 | Transforming yearwise data using pandas | <p>I have a dataframe that looks like this:</p>
<pre><code> Temp
Date
1981-01-01 20.7
1981-01-02 17.9
1981-01-03 18.8
1981-01-04 14.6
1981-01-05 15.8
... ...
1981-12-27 15.5
1981-12-28 13.3
1981-12-29 15.6
1981-12-30 15.2
1981-12-31 17.4
365 rows × 1 columns
</code></pre>
<p>And I want to ... | <p>Try grabbing the year and dayofyear from the index then pivoting:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
# Create Random Data
dr = pd.date_range(pd.to_datetime("1981-01-01"), pd.to_datetime("1982-12-31"))
df = pd.DataFrame(np.random.randint(1, ... | python|pandas | 2 |
14,491 | 60,285,568 | Learning parameters of each simulated device | <p>Does tensorflow-federated support assigning different hyper-parameters(like batch-size or learning rate) for different simulated devices?</p> | <p>Currently, you may find this a bit unnatural, but yes, such a thing is possible.</p>
<p>One approach to doing this that is supported today is to have each client take its local learning rate as a top-level parameter, and use this in the training. A dummy example here would be (sliding the model parameter in the com... | tensorflow|tensorflow2.0|tensorflow-federated | 0 |
14,492 | 59,925,735 | Apply qcut to columns of dataframe with user defined percentile values | <p>I have two dataframes, that looks like below.</p>
<pre><code>dataframe1 =
Index features constant
0 AA 0.25
1 AB 0.45
2 AC 0.78
3 AD 0.91
4 AE 0.12
dataframe2 =
Index AA AB AC AD AE
0 10 45 15 14 98
1 14 55 ... | <p>Just pass the percentiles to <code>qcut</code></p>
<pre><code>percentiles = [0, constant + ((1-constant)*0.2), constant + ((1-constant)*0.4), constant + ((1-constant)*0.6), constant + ((1-constant)*0.8), 1]
qcut(dataframe2['AA'], percentiles)
</code></pre>
<p>Assuming all your values are vaild percentiles, ie bet... | python|pandas|dataframe | 0 |
14,493 | 60,064,748 | Performing pair-wise comparisons of some pandas dataframe rows as efficiently as possible | <p>For a given pandas dataframe <code>df</code>, I would like to compare every sample (row) with each other. </p>
<p>For bigger datasets this would lead to too many comparisons (<code>n**2</code>). Therefore, it is necessary to perform these comparisons only for smaller groups (i.e. for all of those which share the sa... | <p>An inner <code>merge</code> will destroy the index in favor of a new Int64Index. If the index is important bring it along as a column by <code>reset_index</code>, then set those columns back to the Index.</p>
<pre><code>df_pairs4 = (pd.merge(left=df.reset_index(), right=df.reset_index(),
how=... | python-3.x|pandas|performance|numpy|pairwise | 1 |
14,494 | 60,128,565 | 'serving_default' : Classification input must be a single string Tensor | <p>I'm building a very simple Classifier. The input data has the following features</p>
<pre><code>job object
marital object
education object
default int64
housing int64
loan int64
contact object
dayofmonth object
month object
duration int64
campaign ... | <p>Oh, I just found that the problem is not really solved. I did not read the information clearly. The following error still appears at the end:</p>
<pre><code>INFO:tensorflow:Signatures INCLUDED in export for Eval: None
INFO:tensorflow:Signatures INCLUDED in export for Classify: None
INFO:tensorflow:Signatures INCLUD... | tensorflow|serialization|tensorflow-serving | 0 |
14,495 | 60,194,646 | Is it possible to TRAIN a neural network model with Tensoflow Lite/Or any other frameworks on smartphones? | <p>Is it possible to TRAIN a neural network model with Tensoflow Lite/Or any other frameworks on smartphones?</p>
<p>Specifically in the context for federative learning?</p> | <p>You could check out <a href="https://deeplearning4j.konduit.ai/android/setup" rel="nofollow noreferrer">Deeplearning4j</a> which supports Android integration and also on-device training. For a Federated Learning setup, you may think of implementing the Federated Averaging algorithm by yourself on a Java based server... | deep-learning|tensorflow-federated | 3 |
14,496 | 65,467,621 | What are the numbers in torch.transforms.normalize and how to select them? | <p>I am <a href="https://discuss.pytorch.org/t/normalization-in-the-mnist-example/457/4" rel="noreferrer">following</a> <a href="https://github.com/pytorch/examples/blob/master/mnist/main.py" rel="noreferrer">some</a> <a href="https://towardsdatascience.com/handwritten-digit-mnist-pytorch-977b5338e627" rel="noreferrer"... | <p>Normalize in pytorch context subtracts from each instance (MNIST image in your case) the mean (the first number) and divides by the standard deviation (second number). This takes place for each channel separately, meaning in mnist you only need 2 numbers because images are grayscale, but on let's say cifar10 which h... | python|machine-learning|deep-learning|pytorch|mnist | 12 |
14,497 | 65,433,666 | Rename columns with regex and Pandas to extract contents between specific punctuations | <p>Given a test dataset as follows:</p>
<pre><code> city district ... Q3:*your age[open question] Q4:*skill[open question]
0 bj cy ... 45 R
1 bj cy ... 34 Python
</code></pre>
<p>I need to rename ... | <p>Try:</p>
<pre><code>cols = []
for i in df.columns:
if re.search(r'Q\d:',i) != None:
cols.append(re.match(r'^Q\d:\*(your\s)?([\w]*)',i).group(2))
else:
cols.append(i)
</code></pre>
<p>Oneliner substitute for above:</p>
<pre><code>[(re.match(r'^Q\d:\*(your\s)?([\w]*)',i).group(2)) if re.search(... | python-3.x|regex|pandas|dataframe | 1 |
14,498 | 65,290,419 | Merged Columns in Python Data Frame | <p>How can I make this table: <img src="https://i.stack.imgur.com/nSNhV.png" alt="this" /></p>
<p>into a Pandas data frame? Can't make that Machine Column.</p> | <p>You can't really do that in a dataframe, as you can't have a one-level index combined with a multi-level index on the same axis.</p>
<p>One way to get as close as possible to what you want is to concatenate individual pandas series for the first one-level columns with a two-level dataframe for the 'machine' columns ... | python|pandas|list|dataframe|dictionary | 1 |
14,499 | 50,130,212 | Is there any way to make a timeseries scatterplot with array sizing in Matplotlib? | <p>I'm trying to make a scatterplot with time series data in a Pandas DataFrame. I would like to make the size of the markers proportional to values in an array. </p>
<p><code>matplotlib.pyplot.plot_date(x, y)</code> won't work because it won't accept a marker size argument.</p>
<p>When I try to use <code>plt.scatter... | <p>Given this df:</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
df = {'col1': ['2017-12-01','2017-12-02','2017-12-03', '2017-12-04'],
'col2': [5,10,20,30]}
df = pd.DataFrame(data=df)
df['col1'] = pd.to_datetime(df['col1'], format='%Y-%m-%d')
x = df['col1']
y = df['col2']
print df
co... | python|pandas|matplotlib|data-visualization|scatter-plot | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.