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 |
|---|---|---|---|---|---|---|
16,300 | 56,127,227 | How to append a list to pandas column, series? | <p>Asume that I have the following dataframe:</p>
<pre><code>d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
</code></pre>
<p>I would like to extend <code>col1</code> with array <code>xtra</code>. However this errors out.</p>
<pre><code>xtra = [3,4]
df['col1'].append(xtra)
</code></pre>
<p>How can I ... | <p>just copy the same format you used (<code>dict</code>) to make a dataframe like so:</p>
<pre><code>import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
xtra = {'col1': [3,4]}
df = df.append(pd.DataFrame(xtra))
</code></pre> | python|pandas|append | 13 |
16,301 | 55,802,131 | Problem with reading in a pandas DataFrame to Stocker | <p>I recently began working on a project that uses Stocker (an API that runs off of fbprophet to do machine learning stuff with stock data). I love the simplicity of the API but it has a fatal flaw. It uses quandl to receive its stock data. Quandl stopped updating their data sometime in 2018 and it is impossible to run... | <p>The problem depends on columns and columns names returned by Quandl and IEX. </p>
<p>Quandl returns: </p>
<pre><code>Date Open High Low Close Volume Ex-Dividend Split Ratio Adj. Open Adj. High Adj. Low Adj. Close Adj. Volume
</code></pre>
<p>while IEX returns:</p>
<pre><code>date open high low close volu... | python|pandas|quandl | 0 |
16,302 | 55,848,836 | pandas read_excel sharing violation | <p>I have a couple of time series in a excel file. My goal is to check if the excel file exists. If it does, then load it using <code>pd.read_excel</code>, if it doesn't then call a remote server to download the data and then store it into a excel file.</p>
<p>Trying to follow the "ask forgiveness not permission" anti... | <p>refer to <a href="https://stackoverflow.com/questions/29416968/python-pandas-does-read-csv-keep-file-open">This Question</a> its same question. Better to use <code>with</code> since its going to close the file as well in your try block.</p>
<pre><code>def foo():
with open("myfile.csv", "w") as f:
</code></pre> | python|excel|python-3.x|pandas|xlsxwriter | 2 |
16,303 | 55,618,876 | Select rows from with same values in one column but different value in the other column | <p>I have some duplicates in my data that I need to correct.</p>
<p>This is a sample of a dataframe:</p>
<pre><code> test = pd.DataFrame({'event_id':['1','1','2','3','5','6','9','3','9','10'],
'user_id':[0,0,0,1,1,3,3,4,4,4],
'index':[10,20,30,40,50,60,70,80,90,100]})
</code></pre... | <p>Ummm, I try to fix your code </p>
<pre><code>test.groupby('event_id').
filter(lambda x : (len(x['event_id'])==x['user_id'].nunique())&(len(x['event_id'])>1))
Out[85]:
event_id user_id index
3 3 1 40
6 9 3 70
7 3 4 80
8 9 4 90
... | python-3.x|pandas|duplicates | 2 |
16,304 | 55,781,501 | Concise way to sum selected rows of a numpy array | <p>I have a <code>2D</code> <code>numpy</code> array <code>L</code>, which I want to convert into another <code>numpy</code> array of the same shape such that each row is replaced by the sum of all the other rows. I have demonstrated this below.</p>
<p>My question is if there is a more concise/elegant way of doing thi... | <p>Simply subtract <code>L</code> from the column-summations and hence leverage <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> too in the process for a vectorized solution -</p>
<pre><code>In [12]: L.sum(0) - L
Out[12]:
array([[18, 21, ... | python|numpy | 2 |
16,305 | 55,812,146 | How to count frequency of a element in numpy array? | <p>I have a 3 D numpy array which contains elements with repetition.
<code>
counterTraj.shape
(13530, 1, 1
</code>
For example counterTraj contains such elements: I have shown few elements only:</p>
<pre><code> array([[[136.]],
[[129.]],
[[130.]],
...,
[[103... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>numpy.unique</code></a> with <code>return_counts=True</code> parameter, which will return the count of each of the elements in the array.</p>
<pre><code># sample array
In [89]: np.random.seed(23)
In [90]:... | python|numpy|counter|counting|numpy-ndarray | 3 |
16,306 | 64,875,108 | Prevent pandas interpolate from extrapolating | <p>I am trying to interpolate a some data containing NaN's. I would like to fill 1-3 consecutive NaN's, but I cannot figure out to do so with pd.interpolate()</p>
<pre><code>data_chunk = np.array([np.nan, np.nan, np.nan, 4, 5, np.nan, np.nan, np.nan, np.nan, 10, np.nan, np.nan, np.nan, 14])
data_chunk = pd.DataFrame(da... | <p>Create a boolean mask to see which <code>NA-groups</code> have less than 4 consecutive <code>NA's</code>.</p>
<pre><code>mask = (data_chunk.notnull() != data_chunk.shift().notnull()).cumsum().reset_index().groupby(0).transform('count') < 4
</code></pre>
<p>Select interpolated values if <code>mask == True</code> a... | pandas|interpolation | 2 |
16,307 | 64,966,458 | Can I define multiple metrics_set in pipeline.config for TF2 Obejct Detection API | <p>I have been trying to know if I can define multiple metrics_set for one model. I read the source code, I have read lots of writing, even learned proto2 syntax to see if it's possible to agument the code as I want. But couldn't get any results. (Also .config files doesn't look like written in proto2).</p>
<p>Any sugg... | <blockquote>
<p>The TensorFlow Object Detection API currently supports three evaluation protocols, that can be configured in EvalConfig by setting metrics_set to the corresponding value.</p>
</blockquote>
<ol>
<li>coco_detection_metrics</li>
<li>pascal_voc_detection_metrics</li>
<li>oid_V2_detection_metrics</li>
</ol>
... | tensorflow|tensorflow2.0|object-detection|object-detection-api | 0 |
16,308 | 65,048,962 | Pandas: Forward fill with overlap on Series containing List Objects | <p>I have a Series/DataFrame such as this one. The elements contained in them are lists with one or more values:</p>
<pre><code>0 NaN
1 [40]
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 [35]
10 NaN
11 NaN
12 [28]
13 NaN
14 NaN
15 NaN
16 NaN
17 ... | <p>You could try:</p>
<pre><code># fill na by empty list
df['tags'] = [[] if na else s for s, na in zip(df['tags'], df['tags'].isna())]
# compute rolling windows
df['res'] = [[l for ls in window for l in ls] for window in df['tags'].rolling(5)]
print(df)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> tag... | python|pandas|list|dataframe|fillna | 1 |
16,309 | 64,763,352 | Pandas dataframe to dictionary with row index as value? | <p>How can I convert a pandas df to a dictionary that uses its row index as the value? For example, say I have df with a single column:</p>
<pre><code>df = pd.DataFrame({
'ID': [3823, 4724,6233,2438],
})
</code></pre>
<p>which gives me:</p>
<pre><code> ID
0 3823
1 4724
2 6233
3... | <p>Use to_dict() and dictionary comprehension as follows.</p>
<pre><code>{v:k for k, v in df['ID'].to_dict().items()}
</code></pre> | python|pandas|dataframe|dictionary | 3 |
16,310 | 69,352,675 | Trouble with Beautiful Soup Scraping | <p>I am working on scraping multiple pages of search results from this website into a neatly formated pandas dataframe.</p>
<p>I've outlined the steps for how I am to finish this task.</p>
<p>1.) Identify information from each result I want to pull (3 things)</p>
<p>2.) Pull all the information from the 3 things into s... | <p>I think you don't need to parse all pages, just download the csv.</p>
<pre><code>import pandas as pd
import requests
import io
url = 'https://www.federalregister.gov/documents/search?conditions%5Bpublication_date%5D%5Bgte%5D=08%2F28%2F2021&conditions%5Bterm%5D=economy'
url += '&format=csv' # <- Download... | python|pandas|dataframe|web-scraping|beautifulsoup | 3 |
16,311 | 69,336,820 | How to find the maximum overlap between columns of the same rows of two dataframes? | <p>Given two dataframes, how would you find the maximum overlap of start and end values, between rows, and pair them based on the overlap in a new dataframe, and also rank the other overlaps by decreasing overlap?</p>
<pre><code>df_1
start end
a 1 10
b 20 50
c 70 100
df_2
start ... | <p>Try with range index and <code>overlap</code></p>
<pre><code>idx1 = pd.arrays.IntervalArray.from_arrays(
df1['start'],
df1['end'],
closed='both')
df2['new'] = df2.apply(lambda x : df1.index[idx1.overlaps(pd.Interval(x['start'... | python|pandas | 1 |
16,312 | 53,970,677 | How to ease and efficient store simulation data for numpy ufuncs in OO | <p>In a jupyter notebook I OO-modeled a resource but in the control loop need to aggregate data over multiple objects being inefficient compared to ufuncs and similar operations. <br>To package functionality i chose OO but for efficient and concise code i probably have to pull out the data into a storage class (maybe) ... | <p>Here is my take on it:</p>
<pre><code>import numpy as np
K = 3
class Res:
logs = 2
def __init__(self):
self.log = None
def set_log(self, view):
self.log = view
batteries = [Res(), Res()]
d = {'Res': np.random.random( (Res.logs * len(batteries), K) )}
for i in range(len(batte... | python|numpy|oop|jupyter | 0 |
16,313 | 54,107,378 | ImportError: cannot import name model_fn: Tensorflow | <p>I have successfully generated retrained_graph.pb and retrained_labels.txt model. </p>
<p>But not able to convert the Model into TFLite format.</p>
<p>Using following versions</p>
<p>tensorflow 1.12.0<br>
tensorflow-gpu 1.1.0</p>
<p>Help will be appreciated.</p> | <p><strong>(1)</strong> You may use <code>tflite_convert</code> a <strong>command line tool</strong> to achieve this.<br>
Starting from TensorFlow 1.9, the command-line tool <code>tflite_convert</code> is installed as part of the Python package.<br>
See <a href="https://www.tensorflow.org/lite/convert/cmdline_examples#... | python|ios|tensorflow | 0 |
16,314 | 54,055,357 | Converting Mutiple Fields to SIngle Fields | <p>I am having this Pandas DataFrame </p>
<pre><code>a b c d e f g
1 2022 11 12 13 14 15
2 2023 17 22 23 24 25
</code></pre>
<p>I want to convert this to </p>
<pre><code>a ... | <p>I think this should be <code>melt</code> problem </p>
<pre><code>newdf=df.melt(['a','b']).sort_values('b')
newdf
a b variable value
0 1 2022 c 11
2 1 2022 d 12
4 1 2022 e 13
6 1 2022 f 14
8 1 2022 g 15
1 2 2023 c 17
3 2 2023 ... | python|pandas | 4 |
16,315 | 53,969,443 | Fail installation of tensorflow over conda | <p>I have just installed anaconda latest version X64 for windows with python 3.7.</p>
<p>trying to install tensorflow ends up with the next error message:</p>
<pre><code>conda install -c conda-forge tensorflow
Solving environment: failed
UnsatisfiableError: The following specifications were found to be in conflict:
... | <p>Try switching to python 3.6 instead</p> | python|tensorflow|anaconda | 1 |
16,316 | 54,243,064 | Pyro change AutodiagonalNormal settings | <p>I use pyro-ppl 3.0 for probabilistic programming. When I go through the tutorial on Bayesian regression. I used AutoGuide and pyro.random_module to transfer a normal feed-forward network to bayesian network.</p>
<pre><code># linear regression
class RegressionModel(nn.Module):
def __init__(self, p):
# p ... | <p>I think you'll just need to <code>pyro.clear_param_store()</code> between training settings. I believe what was happening is that you were training with <code>latent_dim=5</code>, and then when you set <code>latent_dim=10</code> the old parameters were still in Pyro's global param store. Note that the <code>torch.ra... | pytorch|pyro.ai | 0 |
16,317 | 53,937,795 | Matplotlib opening 2 windows with plt.show() | <p>On my project, I'm using 2 figures with plt.show(), the first one, runs correctly, but the second one, creates 2 windows, 1 correctly named 'Figure 2', and 1 with nothing on the screen, just the 'function bar', named 'Figure 1' (like the first figure). How can I create just the right window?</p>
<pre><code>x = pd.... | <p>close the plot window before generating new plot.</p>
<pre><code>plt.close()
plt.figure(figsize=(20,12), dpi=200)
.... etc
</code></pre> | python|pandas|matplotlib | 0 |
16,318 | 54,227,240 | What's the best way to create a Pandas MultiIndex from a list of dictionaries? | <p>I have an iterative process that runs with different parameter values each iteration and I want to collect the parameter values and results and put them in a Pandas dataframe with a multi-index built from the sets of parameter values (which are unique).</p>
<p>Each iteration, the parameter values are in a dictionar... | <p>I ran into this recently and it seems there's a slightly cleaner way than the accepted answer:</p>
<pre><code>results_index = [
{'p': 2, 'q': 7},
{'p': 2, 'q': 5},
{'p': 1, 'q': 4},
{'p': 2, 'q': 4}
]
results_data = [
{'A': 0.18, 'B': 0.18},
{'A': 0.67, 'B': 0.21},
{'A': 0.96, 'B': 0.45... | python|pandas|dictionary|dataframe|multi-index | 3 |
16,319 | 66,250,446 | Program works correcly only with certain initial conditions | <p>A square matrix is called stochastic if its entries are non-negative and the sum of each row is 1. For example, the following matrix is stochastic:</p>
<pre><code>[0.3, 0.7]
[0.9, 0.1]
</code></pre>
<p>It is well known that any power of a stochastic matrix is still stochastic. I wrote a program to verify this fact,... | <p>I believe it's floating point precision. Lesson learned: avoid comparing two floats with <code>==</code>.</p>
<p>Numpy has <code>allclose</code> method for this:</p>
<pre><code> if np.allclose(B.sum(axis=1),1):
print("Good")
else:
print("Bad")
</code></pre> | python|numpy|linear-algebra | 2 |
16,320 | 66,286,556 | pandas selecting original format of to_datetime | <p>I have the following df:</p>
<pre><code>df
index Original Date
19.02.2021 19.02.2021
19.02.2021 19.02.2021
...
04.12.2020 04.12.2020
03.12.2020 03.12.2020
</code></pre>
<p>I would like to set index column as an index, however it is at the mome... | <p>Try the following:</p>
<pre><code>df.index = pd.to_datetime(df.index, format = '%Y-%m-%d').strftime('%d.%m.%Y')
</code></pre> | python|pandas|datetime|type-conversion | 0 |
16,321 | 66,267,995 | Converting schemas via pandas vs pyarrow | <p>I have a dataframe in pandas that I want to use pyarrow to write it out as a parquet.</p>
<p>I also need to be able to specify column types. If I change the type via pandas, I get no error; but when I change the it via pyarrow, I get an error. See examples:</p>
<h1>Given</h1>
<pre><code>import pandas as pd
import py... | <p>When converting from one type to another, arrow is much stricter than pandas.</p>
<p>In your case you are converting from int64 to float32. Because they are limits to the exact representation of whole number in floating point, arrow limits the range you can convert to 16777216. Past that limit, the float precision g... | python|pandas|dataframe|pyarrow | 1 |
16,322 | 52,884,563 | Loading numpy array from http response without saving a file | <p>I have a bunch of files containing numpy arrays at some url (e.g., <code>https://my_url/my_np_file.npy</code>) and I am trying to load them in my computer.</p>
<p>If I download the file manually, I can properly load the numpy array using <code>np.load('file_path')</code>. If I take the url reponse (using the code b... | <p>You are missing <code>io.BytesIO</code> to make the string appear like a file object to <code>np.load</code>!</p>
<p>The following is what you're looking for:</p>
<pre><code>import requests
import io
response = requests.get('https://my_url/my_np_file.npy')
response.raise_for_status()
data = np.load(io.BytesIO(res... | python|numpy | 11 |
16,323 | 52,569,876 | python pandas.read_json() doesn't work for IG Labs REST | <p>I am trying to read some json string into a pandas dataframe. I seem to be able to retrieve the json itself. But when I try to use a pandas dataframe to read it, it seems to fail.</p>
<p>Any experts have any thoughts?</p>
<pre><code>import requests
import json
import pandas
url = 'https://demo-api.ig.com/gateway/... | <p><strong>Imports:</strong></p>
<pre><code>import pandas as pd
</code></pre>
<p><strong>Create a main DataFrame:</strong></p>
<pre><code>df_main = pd.DataFrame()
</code></pre>
<p><strong>Data: it's not in json format</strong></p>
<pre><code>data = {'accountType': 'CFD',
'accountInfo': {'balance': 0,
... | json|python-3.x|pandas | 2 |
16,324 | 52,458,409 | How to remove nan and inf values from a numpy matrix? | <p>Here is my code</p>
<pre><code>import numpy as np
cv = [[1,3,4,56,0,345],[2,3,2,56,87,255],[234,45,35,76,12,87]]
cv2 = [[1,6,4,56,0,345],[2,3,4,56,187,255],[234,45,35,0,12,87]]
output = np.true_divide(cv,cv2,where=(cv!=0) | (cv2!=0))
print(output)`
</code></pre>
<p>I am getting Nan and inf values.i tried to remov... | <p>You can just replace <code>NaN</code> and infinite values with the following mask:</p>
<pre><code>output[~np.isfinite(output)] = 0
>>> output
array([[1. , 0.5 , 1. , 1. , 0. ,
1. ],
[1. , 1. , 0.5 , 1. , 0.46524064,
... | python|numpy|matrix | 10 |
16,325 | 58,278,691 | How to use IF statements to categorize with multiple conditions with Pandas | <p>I have a categorization problem. The categorizing rule is:</p>
<p>If</p>
<ol>
<li><code>Storage Condition == 'refrigerate'</code> and</li>
<li><code>100 < profit Per Unit < 150</code> and</li>
<li><code>Inventory Qty <20</code></li>
</ol>
<p>is given, <code>restock Action = 'Hold Current stock level'... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where</a>:</p>
<pre><code>c1=df['Stroage Condition'].eq('refrigerate')
c2=df['Profit Per Unit'].between(100,150)
c3=df['Inventory Qty']<20
df['Restock Action']=np.where(c1&c2&c3,'Hold Current ... | python|pandas | 2 |
16,326 | 68,961,084 | Update the csv display_names to column_names based on Query | <p>I have a csv file which consists of following.</p>
<pre><code>x1,x2,x3
66,1000,Copper
</code></pre>
<p>Here, the x1,x2,x3 are the display names.</p>
<p>My major goal is to update the table based on csv columns and values using</p>
<pre><code>pd.read_csv()
df.to_sql("table", engine)
</code></pre>
<p>In my c... | <p>perhaps select the column display name mappings first into a dictionary and then replace in the <code>df</code> before <code>df.to_sql</code> <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rename.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ren... | python|pandas | 0 |
16,327 | 69,094,925 | how to properly accomodate a matrix in order to convert it to a positive semi-definite matrix? | <p>I am trying to convert a matrix to a semi-definite matrix by using <code>nearPSD()</code> function:</p>
<pre><code>import numpy as np
phi_zero, phi_one= 0.7, -0.2
A=[[phi_zero, phi_one],
[1, 0]]
def nearPSD(A,epsilon=0):
n = A.shape[0]
eigval, eigvec = np.linalg.eig(A)
val = np.matrix(np.maximum(eigv... | <p>You're passing a <code>list</code> to a function that expects a <code>np.array</code>. Simple fix:</p>
<pre class="lang-py prettyprint-override"><code>nearPSD(A=np.array(A))
</code></pre> | python|numpy|matrix | 1 |
16,328 | 61,067,586 | Deeplearning4j - java - You can register a SameDiff Lambda layer using KerasLayer.registerLambdaLayer(lambdaLayerName, sameDiffLambdaLayer); | <p>I am trying to load my model.h5 in my java code using deeplearning4j. I am following this tutorial <a href="https://deeplearning4j.konduit.ai/keras-import/model-functional" rel="nofollow noreferrer">https://deeplearning4j.konduit.ai/keras-import/model-functional</a></p>
<p>Java code</p>
<pre><code>public static vo... | <p>The error message does tell you what is wrong: You have a lambda layer, i.e. a layer that is defined with a lambda:</p>
<blockquote>
<pre><code>split = Lambda(lambda whole: tf.split(whole, num_or_size_splits=hyper['max_len'], axis=1))(x)
</code></pre>
</blockquote>
<p>As we can't guess what the lambda layer is doi... | tensorflow|keras|deep-learning|deeplearning4j | 1 |
16,329 | 71,587,489 | Alternative way to select subsets of columns in pandas? | <p>Let's say I have the following dataframe:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(4,8), columns = list('abcdefgh'))
</code></pre>
<p>I would like to choose column c and columns e to h.</p>
<p>I know I could do something like:</p>
<pre><code>df.iloc[:,[2,4,5,6,7]]
</code... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.r_.html" rel="nofollow noreferrer"><code>numpy.r_</code></a>:</p>
<pre><code>print (df.iloc[:,np.r_[2,4:len(df.columns)]])
c e f g h
0 0.111579 0.745122 0.149010 0.571919 0.342449
1 0.264858 0.310361 ... | python|pandas | 0 |
16,330 | 71,699,957 | Copy all .csv files in directory to .xlsx files in another directory, Traceback error | <p>I'm working on this script that first takes all .csv's and converts them .xlsx's in a separate folder. I'm getting the first file to output exactly how I want in the 'Script files' folder, but then it throws a Traceback error before it does the second one.</p>
<p>Script code below, Traceback error below that. Some p... | <p>Have you tried to convert to xlsx the second file in the folder? I'm not sure but it seems like there's a problem when Pandas reads the csv.</p> | pandas|csv | 0 |
16,331 | 71,626,052 | How to map list of string to existing list of integer? | <p>I have this string vocab file: <a href="https://drive.google.com/file/d/1mL461QGC5KcA3M1r8AESaPjZ3D_ufgPA/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1mL461QGC5KcA3M1r8AESaPjZ3D_ufgPA/view?usp=sharing</a>.</p>
<p>I have this sentences file, made from all vocab file above: <a href="htt... | <p>IIUC:</p>
<pre><code>df = pd.DataFrame(output)
vocab = pd.Series(encoded_string, index=data_into_list)
df['encoded'] = df.explode(df.columns.tolist())['token'] \
.map(vocab).groupby(level=0).agg(list)
</code></pre>
<p>Output:</p>
<pre><code>>>> df
... | python|pandas|dataframe | 1 |
16,332 | 71,578,939 | Calculate stdev for a row and previous row in pandas without series error | <p>Here is my dataset</p>
<pre><code>Date,p1Close,p2Close,spread,movingAverage
2022-02-28,5,10,2,NaN
2022-03-01,2,6,3,2.5
2022-03-02,4,8,2,2.5
2022-03-03,2,8,4,3
</code></pre>
<p>I am trying to create a new column in pandas data frame that is equal to the standard deviation between <code>spread</code> from previous row... | <p>You can actually just use <code><column>.rolling(2).std()</code>:</p>
<pre><code>df['standardDeviation'] = df['spread'].rolling(2).std()
</code></pre>
<p>Output:</p>
<pre><code>>>> df
Date p1Close p2Close spread movingAverage standardDeviation
0 2022-02-28 5 10 2 ... | python|python-3.x|pandas|dataframe|rolling-computation | 1 |
16,333 | 71,579,502 | Merging Pandas-File with OSMNX | <p>I want to find out which is the most dangerous road in Switzerland based on accidents that are happening there.
I have a csv-file with geolocations where each row is an accident and contains information on type of accident, people involved, date, geolocation (which I managed to transform into EPSG:4326) and more. I ... | <ul>
<li>used Swiss accident data</li>
<li>have used two <em>merge</em> techniques between accident data and <strong>OSMNX</strong> data
<ol>
<li>scoped data using a polygon of a city. Used <code>sjoin()</code> for this</li>
<li>located <em>bad</em> roads by using <code>sjoin_nearest()</code> to find indexes of <em>Li... | python|openstreetmap|geopandas|osmnx | 1 |
16,334 | 42,139,225 | Iterating through a nested table/spreadhseet | <p>Not sure how to go about getting started. I have many tab delimited files that I want to be able to put into a database. However the hard part is that the table is not laid out in the best way. For example the parent row will have will be designated a letter (D) then the rows under that parent corresponds to the ... | <p>I think this works. It simply adds a list of "child" lines at the end of each "parent" line in a list of "parent" lines.</p>
<pre><code>customer_file = open('index_of_customers.txt', 'r') # you should of course do more try-except stuff in your script
database = [] # all data en... | python|python-2.7|csv|pandas | 0 |
16,335 | 70,012,967 | Group by 4 quarters and aggregate in python | <p>I have a dataset, df, where I would like to group by 4 quarters and aggregate in python</p>
<p><strong>Data</strong></p>
<pre><code>id type date count
aa hi Q1 2022 4
aa hi Q2 2022 6
aa hi Q3 2022 7
aa hi Q4 2022 5
aa ok Q1 2022 1
aa ok Q2 2022 1
aa ok Q3 2022 1
aa o... | <p>few ways - note using <code>str</code> methods means your <code>series</code> will be a string, cast it to an int if you need to do so.</p>
<p>using <code>str.split</code></p>
<pre><code>df.assign(
date=df['date'].str.split(' ',expand=True)[1]
).groupby(['id','type','date']).sum()
... | python|pandas|numpy | 1 |
16,336 | 69,990,773 | Incorporating a TensorHub model into my Keras model | <p>TensorFlow 2.7, Keras 2.7</p>
<p>I am trying to use an existing TFHub model as a layer in my model. Wrapped it by a custom keras layer but probably missed something around the batch size. Wrote a simple version of it below.
The model below receives [ BATCH_SIZE, 224, 224, 3 ], uses a TFHub model to generate one repr... | <p>@Dani This is because the <a href="https://tfhub.dev/intel/midas/v2/2" rel="nofollow noreferrer"><code>tfhub.KerasLayer</code></a> you are using in your code is built for a single image.</p>
<p>It is clearly mentioned in that tfhub page <a href="https://tfhub.dev/intel/midas/v2/2" rel="nofollow noreferrer">https://t... | python|tensorflow|keras | 0 |
16,337 | 69,824,372 | Find missing dates in multiple date ranges for multi groups | <p>Im trying to extract missing date list for a date range in columns <code>DATE FROM</code> and <code>DATE TO</code> for multiple groups in column <code>CURRENCY</code>, the ranges is splited in multiple rows for each group column <code>CURRENCY</code> :</p>
<p>For example : Currency EUR have three date ranges in row ... | <p>Both pd.date_range and pd.period_range can do. I have used date range which only has close either right or left, so you may have to do some filter. Code below</p>
<pre><code>df= df.assign(end=df['DATE FROM'].shift(-1),start=df['DATE TO']).iloc[:-1 , :]#Define the start and end for date range
df=df.assign(Missing=df... | python|pandas | 2 |
16,338 | 69,713,186 | Applying np.where in a sliding window | <p>I have an array of <code>True</code>/<code>False</code> values which I want to use as a repeating mask over another array of a different shape.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
mask = np.array([[ True, True],
[False, True]])
array = np.random.randint(10, size=... | <p>Use broadcasting with reshape so you wouldn't need extra memory for the repeated <code>mask</code>:</p>
<pre><code>x, y = array.shape[0]// mask.shape[0], array.shape[1] // mask.shape[1]
result1 = np.where(mask[None, :, None],
array.reshape(x, mask.shape[0], y, mask.shape[1]),
2... | python|numpy|sliding-window | 2 |
16,339 | 69,690,777 | RuntimeError: Expected 4-dimensional input for 4-dimensional weight [64, 512, 3, 3], but got 2-dimensional input of size [32, 2048] instead | <p>I want to train a classifier based on a pretrained network with PyTorch. What I need to do is to take a pretrained model (I tried with ResNet50), add some layers at the end (I need to do this as it is required by the project specifications) and train only those layers I add. I tried this:</p>
<pre><code>import torch... | <p>You can't replace resnet50's <code>fc</code> with a convolutional network. The output of resnet's feature extractor is a CNN which outputs a flat <em>2048</em>-long tensor, as such the layers following it should be fully connected layers.</p> | python|deep-learning|neural-network|pytorch|resnet | 1 |
16,340 | 69,789,380 | Slicing NumPy ndarray giving indices at specific axis | <p>Suppose there is a <code>ndarray A = np.random.random([3, 5, 4])</code>, and I have another index <code>ndarray</code> of size 3 x 4, whose entry is the index I want to select from the 1st axis (the axis of dimension being 5). How can I achieve it using pythonic code?</p>
<p>Example:</p>
<pre><code>A = [[[0.95220166... | <pre><code>In [148]: A = np.arange(3*5*4).reshape([3, 5, 4])
In [151]: B = np.array([[3, 1, 2, 1],
...: [3, 2, 0, 4],
...: [3, 3, 1, 2]])
In [152]: B.shape
Out[152]: (3, 4)
In [153]: A.shape
Out[153]: (3, 5, 4)
</code></pre>
<p>Apply <code>B</code> to the middle dimension, and use arrays with shape ... | python|numpy|slice|numpy-ndarray | 2 |
16,341 | 43,334,338 | Printing tensorflow tensor in Python hangs forever | <p>I am trying to print a python tensor in a simple program. The program reads the iris data set from a file using a tensorflow reader. If I uncomment the last line of the program, it hangs forever. The goal is to print sepal_length, sepal_width, etc. What do I have to do to print the sepal_length tensor????</p>
<... | <p>I figured it out, here is the working program:</p>
<pre><code>import tensorflow as tf
def read_csv(batch_size, file_name, record_defaults):
filename_queue = tf.train.string_input_producer(["iris.data"])
reader = tf.TextLineReader(skip_header_lines=1)
key, value = reader.read(filename_queue)
# dec... | python|tensorflow | 5 |
16,342 | 50,231,495 | pandas groupby ID then look for occurrence of 'H' character in the risk column of all rows | <p>I have an example Pandas dataframe df:</p>
<pre><code>ID risk
1111 H
1111 H
1111 L
1111 L
1112 L
1112 L
1113 H
1113 L
1113 H
1113 H
1113 H
1114 L
1114 L
1114 L
1114 L
</code></pre>
<p>I want to group data based on ID and then look for occurrence of 'H' character in the risk column. If there exist... | <p>First find all unique <code>ID</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and then replace values by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer... | python|pandas|pandas-groupby | 3 |
16,343 | 62,888,787 | how to match partial string from a text in pandas dataframe | <p>My data frame looks like -</p>
<pre><code>id text
1 good,i am interested..please mail me.
2 call me...good to go with you
3 not interested...bye
4 i am not interested don't call me
5 price is too high so not interested
6 i have some requir... | <pre><code>In [20]: df = pd.read_csv("a.csv")
In [21]: a
Out[21]: ['not interested', 'nt interested']
In [22]: df
Out[22]:
id text
0 1 good i am interested..please mail me.
1 2 call me...good to go with you
2 3 not interested...b... | python|python-3.x|pandas | 1 |
16,344 | 62,887,468 | How to create new list column values from groupby | <p>My goal is to create a new column <code>c_list</code> that contains a list after an groupby (without <code>merge</code> function): <code>df['c_list'] = df.groupby('a').agg({'c':lambda x: list(x)})</code></p>
<pre><code>df = pd.DataFrame(
{'a': ['x', 'y', 'y', 'x'],
'b': [2, 0, 0,... | <p>Try with <code>transform</code></p>
<pre><code>df['d']=df.groupby('a').c.transform(lambda x : [x.values.tolist()]*len(x))
0 [8, 6]
1 [2, 5]
2 [2, 5]
3 [8, 6]
Name: c, dtype: object
</code></pre>
<p>Or</p>
<pre><code>df['d']=df.groupby('a').c.agg(list).reindex(df.a).values
</code></pre> | pandas|pandas-groupby | 2 |
16,345 | 62,514,008 | For dataframe: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() | <p>In a dataframe, I want to append a column through an if statement as follows:</p>
<pre><code>death_flag = []
For entry in
range(len(demographics)):
if pd.isnull(df['DOD'] [entry]) == False:
if [(df['DOD']-df['DOA'] > pd.Timedelta(days=365) == True)]:
death_flag.append(1)
</code></pre>
<p>Df is a datafra... | <p>Dont use loops in pandas, if exist super fast vectorized solution like here - create boolean mask for conditions and then create new column by chained masks by <code>&</code> for <code>bitwise AND</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollo... | pandas | 0 |
16,346 | 62,520,756 | Random 3d image slicing tensorflow data, depth of NoneType shape | <p>What I need to do is to cut some slices (fix size) of a 3D-binary masks randomly.
The data is stored in a tensorflow dataset (tf.data). It does have to be this kind of data type to be able to use caching for speed up.</p>
<p>My source code so far:</p>
<pre><code>import tensorflow as tf #version 2.2.0
mask.sha... | <p>Assuming that you want to randomly slice a fixed <code>slice_size</code> from a Tensor dimension with unknown depth, the following demonstrates how it can be done:</p>
<pre><code>import tensorflow as tf
@tf.function
def random_slice(slice_size):
# For demonstration purposes, generate your mask with random depth
... | tensorflow|3d|conditional-statements|tensorflow2.0|shapes | 1 |
16,347 | 62,877,118 | Delete a row when a cell is empty | <p>I'm trying to delete a row when a cell is empty from the 'calories.xlsx' spreadsheet and send all data, except empty rows, to the 'destination.xlsx' spreadsheet. The code below is how far I got. But still, it does not delete rows that have an empty value based on the calories column.</p>
<p>This is the data set:</p>... | <p>Create dummy data</p>
<pre><code>df=pd.DataFrame({
'calories':[2306,3256,1235,np.nan,3654,3256],
'Person':['person1','person2','person3','person4','person5','person6',]
})
</code></pre>
<p>Print data frame</p>
<pre><code> calories Person
0 2306.0 person1
1 3256.0 person2
2 1235.0 person3
3... | python|excel|pandas | 2 |
16,348 | 54,687,497 | How to unpack an integer bit-pattern into a tf.Tensor? | <p>I have a biggish dataset stored relatively efficiently on disk, with one-hot vectors packed into the bits of a bunch of ints. The data format is fixed-width, so I can read it in fine with <code>tf.data.FixedLengthRecordDataset</code>, and with <code>tf.decode_raw()</code> and <code>tf.bitwise.*</code> I have conver... | <p>You can do that like this:</p>
<pre><code>import tensorflow as tf
def bits_to_one_hot(bits, depth, dtype=None):
bits = tf.convert_to_tensor(bits)
masks = tf.bitwise.left_shift(tf.ones([], dtype=bits.dtype),
tf.range(depth, dtype=bits.dtype))
masked = tf.bitwise.bitwise... | python|tensorflow|tensorflow-datasets | 1 |
16,349 | 73,558,722 | Insert a value into a column by a condition Python | <p>I can't figure out how to insert a value according to the condition in another column. It is necessary to insert the value from the second file according to the condition, the beginning is the value "01", and the end is the value "01"-1. The beginning always begins with "01".
Examples o... | <pre class="lang-py prettyprint-override"><code>df1['N2'] = df2.loc[(df1['N1'] == '01').cumsum() - 1].set_axis(df1.index, axis=0)
</code></pre>
<p><strong>Result:</strong></p>
<pre class="lang-py prettyprint-override"><code> N1 N2
0 01 PALA A
1 02 PALA A
2 03 PALA A
3 01 PALA B
4 02 PALA B
5 01 PALA ... | python|python-3.x|pandas|dataframe | 0 |
16,350 | 71,303,700 | Combining np.where with conditional duplicate to assign column value | <p>I have put together a conditional statement using the duplicate function to extract a row from the following data. That is extracted from a larger dataset</p>
<pre><code>{'NID': {104565: '213003580',
104566: '213003580',
104567: '213003580',
104568: '213003580',
104569: '213003580',
104570: '213003580',
... | <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">numpy.where()</a> accepts an array_like boolean condition. Result of <code>(df.duplicated(['NID','Fdat','BCode'], keep='last') & (df['BCode'].eq(1)) & (df['Result'].ge(0)))</code> is already a list, you don'... | python|pandas | 1 |
16,351 | 71,388,163 | pandas groupby create new columns based on col1 containing value of col2 | <p>I have a pandas dataframe that I want to group by and create columns for each value of col1 and they should contain the value of col2. And example dataframe:</p>
<pre class="lang-py prettyprint-override"><code>data = {'item_id': {0: 2, 1: 2, 2: 2, 3: 3, 4: 3},
'feature_category_id': {0: 56, 1: 62, 2: 68, 3: 56, 4: ... | <p>What you are searching for is pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot()</code></a> function. It does exactly what you want:</p>
<pre><code># Change df shape
result = df.pivot(index="item_id", columns="feature_categ... | python|pandas|dataframe | 0 |
16,352 | 52,335,065 | Is tensorflow session running in parallel to the rest of my code? | <p>I'm running my session on a GPU and I'm wondering if the 'session.run()' piece of code is running in parallel to my other code in my script.
I use batch processing on the CPU prior to running 'session.run()' in a loop and would like to pipeline this processing with the execution on the GPU. Is this already satisfie... | <p>After some research I found out that 'session.run' is not running concurrently to your other code. Indeed, as Ujjwal suggested, the 'tf.data.Dataset' API is the best choice for pipelining batch preprocessing and GPU execution.</p> | python|multithreading|tensorflow|parallel-processing|batch-processing | 0 |
16,353 | 52,070,036 | Processing an Image using Tensorflow | <p>I've a 15 images which are stored locally. How do I transform these images to a array using tensorflow for a CNN type of Classification?</p> | <p>Convert the image to numpy array format</p>
<pre><code>import cv2
im = cv2.imread("some_image.tiff")
</code></pre>
<p>Reshape them to an arbitrary, but identical, size</p>
<pre><code>def reshape(image_array):
return np.reshape(image_array, [128, 128, 3])
</code></pre>
<p>Put them all in a list and then stand... | python|tensorflow | 0 |
16,354 | 52,336,355 | Summing up rows in a DataFrame while maintaining a similar DataFrame structure | <p>I have the following DataFrame:</p>
<pre><code>Stint Year ID Data1 Data2 Team
1 2010 A 10 1 SFN
1 2011 A 10 1 SFN
1 2013 A 10 1 SFN
2 2013 A 10 1 ATL
1 1922 B 10 1 ARI
1 1923 B 10... | <h3><code>groupby</code> with <code>as_index=False</code></h3>
<p>Will not include grouped columns in a new index</p>
<pre><code>df.groupby(['Year', 'ID'], as_index=False)[['Data1', 'Data2']].sum()
Year ID Data1 Data2
0 1922 B 10 1
1 1923 B 10 1
2 1924 B 10 1
3 2010 A 10 ... | python|pandas | 2 |
16,355 | 60,390,868 | Add array to a dataframe in python | <p>I have a datframe df, with the <code>df.shape</code>: (971,1)</p>
<p>And I have an array with the <code>anarray.shape</code>: (971,80).</p>
<p>How can I add the array to my dataframe, so that I have the shape: (971,81).</p>
<p>I only find solutions where the array goes into one column, but in my case it should go... | <p>I believe you need helper <code>DataFrame</code> with same index like <code>df</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join</code></a>:</p>
<pre><code>df = df.join(pd.DataFrame(anarray, index=df.index))
... | python|pandas | 2 |
16,356 | 60,739,797 | How to flip a column of ratios, convert into a fraction and convert to a float | <p>I have the following data frame:</p>
<pre><code> Date Ratio
0 2000-06-21 4:1
1 2000-06-22 3:2
2 2000-06-23 5:7
3 2000-06-24 7:1
</code></pre>
<p>For each item in the <code>Ratio</code> column, I want to reverse the ratio, convert it into a fraction and convert it to a float.</p>
<p>Meaning 4:1... | <p>Create new <code>DataFrame</code> with <code>expand=True</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a>, convert to integers and last divide columns:</p>
<pre><code>df1 = df['Ratio'].str.split(":"... | python|pandas|dataframe | 4 |
16,357 | 60,341,662 | why before embedding, have to make the item be sequential starting at zero | <p>I learn collaborative filtering from this bolg, <a href="https://www.johnwittenauer.net/deep-learning-with-keras-recommender-systems/" rel="nofollow noreferrer">Deep Learning With Keras: Recommender Systems</a>.</p>
<p>The tutorial is good, and the code working well. <a href="https://github.com/kk412027247/nn_colla... | <p>Embeddings are assumed to be sequential.</p>
<p>The first input of <code>Embedding</code> is the input dimension.
So, if the input exceeds the input dimension the value is ignored.
<code>Embedding</code> assumes that max value in the input is input dimension -1 (it starts from 0).</p>
<p><a href="https://www.tenso... | python-3.x|tensorflow|neural-network|embedding|collaborative-filtering | 0 |
16,358 | 72,749,111 | creating training.csv and test.csv file after splitting a dataset using sklearn | <p>I am working on iris dataset. I was able to split the dataset with training and test set.</p>
<pre><code>X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size = .3, random_state = 50)
</code></pre>
<p>Now I want to extract two individual csv files one for training dataset and another one for test dataset... | <p>From my answer <a href="https://stackoverflow.com/a/69822068/15239951">here</a>, load the dataset and convert it to a dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
df = pd.DataFrame(dat... | pandas|scikit-learn|split | 1 |
16,359 | 72,516,057 | change tf.contrib.layers.xavier_initializer_conv2d to 2.0.0 | <p>How can I change <code>tf.contrib.layers.xavier_initializer_conv2d</code> to 2.0.0 so that I can use it in the context of tensorflow-2.0.0.</p>
<p>Thank you!</p> | <p>You can use <strong><a href="https://www.tensorflow.org/api_docs/python/tf/keras/initializers/GlorotNormal" rel="nofollow noreferrer">Glorot normal initializer</a></strong>, also called <strong>Xavier normal initializer</strong> in <code>TF 2.x</code> in place of <code>xavier_initializer_conv2d()</code>.</p>
<pre><c... | python|tensorflow|keras|tensorflow2.0|tf.keras | 0 |
16,360 | 72,633,568 | drop values in a pandas dataframe in a for loop | <p>I'm working with a dataframe which carries daily data from february 2013 to may 2022 and has the following format:</p>
<pre><code> Unnamed: 0 prod und proc tipo min mcom max merc date year month day
0 0 Bacalhau Cx.25Kg NOR Saith NaN 437.50 NaN Est 2013/02/01 2013 2 1
1 1... | <p>you don't need to loop over it, all can be done in a single statement</p>
<pre><code>df.drop(df[( (df['year'].isin(anos)) & (df['month'] == 2) & (df['day'] == 29) )].index)
</code></pre>
<p>PS: can you post the dataframe example as a csv?</p> | python|pandas|dataframe|for-loop | 2 |
16,361 | 72,832,711 | Insert values to a pandas column containing list alternatively from other column containing list | <p>Posting minimal reproducible example</p>
<p>Lets say I have a dataframe</p>
<pre><code> combined values
0 [0, 0, 0, 0, 0, 0, 0, 0] [1, 2, 3, 4]
1 [0, 0, 0, 0, 0, 0, 0, 0] [5, 6, 7, 8]
2 [0, 0, 0, 0, 0] [9, 10, 11]
</code></pre>
<p>Now I need to populate column <... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>for a, b in zip(df["combined"], df["values"]):
a[::2] = b
print(df)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code> combined values
0 [1, 0, 2, 0, 3, 0, 4, 0] [1, 2, 3, 4]
1 [... | python|pandas|list|slice | 1 |
16,362 | 72,775,766 | Use cv2.imshow() to display an np.array | <p>so at the moment im accesing the BGR Channels of images and do a bit of calculation around them.</p>
<p>Like the mean or standard deviation.. stuff like that.</p>
<p>As far as i know i dont have to convert numPy Arrays to display them with cv2.imshow().</p>
<p>But when I display my array with this command:</p>
<pre>... | <p>opencv has BGR channel ordering, PIL and matplotlib use RGB order</p>
<p>try not to mix different libraries with different paradigms</p> | python|numpy|opencv|python-imaging-library | 1 |
16,363 | 72,563,781 | Pandas dataframe aggregation with different operations | <p>I have created a pandas dataframe called <code>df</code> with this code:</p>
<pre><code>d = {'col1' : [5,3,2,1,34,54,6,7],
'col2' : [23,65,7,8,9,12,11,10],
'col3' : [65,67,7,11,7,7,9,10],
'col4' : [32,32,12,12,1,2,1,3],
'ops' : [1,1,1,1,2,2,2,2]}
df = pd.DataFrame(data=d)
print(df... | <p>Let's try</p>
<pre class="lang-py prettyprint-override"><code>out = df.groupby('ops', as_index=False).agg({'col1': 'first',
'col2': 'min',
'col3': 'max',
'col4': 'last'})
</code></pr... | python|pandas|dataframe|group-by|aggregate | 1 |
16,364 | 59,550,793 | combine multiple dataframes in a csv file separating each with an empty row | <p>how can I separate each dataframe with an empty row
ive combined them using this snippet</p>
<pre><code>frames1 = [df4, df5, df6]
Summary = pd.concat(frames1)
</code></pre>
<p>so how can i split them with an empty row</p> | <p>You can use the below example which works:</p>
<p>Create test dfs</p>
<pre><code>df1 = pd.DataFrame(np.random.randint(0,20,20).reshape(5,4),columns=list('ABCD'))
df2 = pd.DataFrame(np.random.randint(0,20,20).reshape(5,4),columns=list('ABCD'))
df3 = pd.DataFrame(np.random.randint(0,20,20).reshape(5,4),columns=list(... | python|pandas | 4 |
16,365 | 61,939,401 | How to compare two rows in pandas/ python if they overlap | <p>I have data frame like below</p>
<pre><code> product model ci_low ci_upp
A X 0.041667 48.0
A Y 0.000000 21.0
</code></pre>
<p>I want to check if ci_low and ci_upp overlap by product and return something like</p>
<pre><code> product ... | <p>First we need <code>pivot</code> and create the range index then use the <code>overlap</code> to find the intersection </p>
<pre><code>df['Ci band']=pd.IntervalIndex.from_arrays(df.ci_low,df.ci_upp,closed='both')
s=df.pivot('product','model','Ci band').add_prefix('CI Band')
s['Overlap']=s.apply(lambda x : x['CI Ban... | python|pandas|compare | 3 |
16,366 | 61,719,478 | Accessing different columns in "apply" in pandas dataframes | <p>I'm looking for the proper way to "iterate" over the rows or - let's say - do the same thing without iteration, as I know that iteration is not the recommended way of handling the data in a dataframe for computations, as explained for instance in <a href="https://stackoverflow.com/questions/16476924/how-to-iterate-o... | <p>Use the apply method of the dataframe and index the columns you want with <code>[]</code> syntax.</p>
<pre><code>import numpy as npd
import pandas as pd
df_test = pd.DataFrame({"start": [-2.0, -1.0, -5.0 ],
"end": [3.0, 1.0, -1.0],
"n": [6, 3, 9]
... | python|pandas|numpy | 1 |
16,367 | 54,806,450 | Tensorflow LSTM Error (ValueError: Shapes must be equal rank, but are 2 and 1 ) | <p>I know this questions have been asked many times but i am kind of new to tensorflow and none of the previous threads could solve my issue. I am trying to implement a LSTM for series of sensor data to classify data. I want my data be classified as 0 or 1 so its a binary classifier. I have over all 2539 samples which ... | <p>Just an update the problem was with the shape of Labels. After adding onehot encoding for labels and make the 2dimensional problem was solved.</p> | python|tensorflow|deep-learning|lstm|recurrent-neural-network | 0 |
16,368 | 55,001,289 | Pandas: Groupby based on matching substring in pandas column | <p>I have a list that has elements like:</p>
<pre><code>emails= ['xyz.com', 'abc.com','def.com']
</code></pre>
<p>Now, I have a dataframe that looks like:</p>
<p>df:</p>
<pre><code>UserID Email_Address
U001 u001@abc.com
U002 u002@xyz.com
U003 u003@xyz.com
U004 u004@abc.com
U004 u005@def.... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>Series.str.extract</code></a> for get values by lists and aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="... | python|pandas|dataframe|group-by | 3 |
16,369 | 54,945,933 | Performance of numpy.insert dependant from array size - workaround? | <p>Using the following code, I get the impression that the insert into a numpy array is dependant from the array size.</p>
<p>Are there any numpy based workarounds for this performance limit (or also non numpy based)?</p>
<pre><code>if True:
import numpy as np
import datetime
import timeit
myArray = np.em... | <p>This has to do with the way <code>numpy</code> works. For each insert operation, it takes the whole array and stores it in a new place. I would recommend using <code>list</code> append and convert it then to a <code>numpy</code> array. Maybe duplicate of <a href="https://stackoverflow.com/questions/38470264/numpy-co... | python|performance|numpy | 3 |
16,370 | 49,477,393 | How to impute column values on Dask Dataframe? | <p>I would like to impute negative values of Dask Dataframe, with pandas i use this code:</p>
<pre><code>df.loc[(df.column_name < 0),'column_name'] = 0
</code></pre> | <p>I think need <a href="http://dask.pydata.org/en/latest/dataframe-api.html#dask.dataframe.Series.clip_lower" rel="nofollow noreferrer"><code>dask.dataframe.Series.clip_lower</code></a>:</p>
<pre><code>ddf['B'] = ddf['B'].clip_lower(0)
</code></pre>
<p><strong>Sample</strong>:</p>
<pre><code>import pandas as pd
df... | pandas|dataframe|dask | 4 |
16,371 | 49,649,236 | Difference between final cell state and RNN output in LSTM Tensorflow? | <p>I am trying to understand LSTM in Tensorflow , I am doing simple classification using <code>tf.nn.bidirectional_dynamic_rnn</code> , which return two things , One is final_result of each cell and second is hidden state of only last cell , Now my confusion is if i am taking final output for next fully_connected layer... | <p>This is not a complete answer but here I can point out some points that may help you,</p>
<blockquote>
<p>I am doing simple classification using tf.nn.bidirectional_dynamic_rnn
, which return two things , One is final_result of each cell and
second is hidden state of only last cell</p>
</blockquote>
<p>This ... | python|tensorflow|deep-learning|lstm|rnn | 0 |
16,372 | 49,754,734 | Padding a matrix with numpy | <p>I have a 2D numpy array called <code>adj=dim(16,16)</code>. l would like to pad it with zeros to get <code>new_adj=dim(31,31)</code>.</p>
<p>I tried...</p>
<pre><code>new_adj=np.pad(adj,((15,31),(31,15)),mode='constant')
</code></pre>
<p>However </p>
<pre><code>new_adj.shape=(62, 62)
</code></pre>
<p>I'm suppos... | <p>If you look at the documentation of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="nofollow noreferrer"><code>np.pad</code></a>, it explains that each tuple in the second argument specifies how many positions of pad to add at the beginning and end of each dimension. You are adding... | python-3.x|numpy | 3 |
16,373 | 73,422,867 | How to convert a pandas series of objects into a dataframe where each item becomes a column and the values in the rows | <p>I am stuck at this:
I have a Series with the following structure
Name: sn
dtype: object</p>
<pre><code>0 { key1: value1, key2: value2, key3: value3}
1 { key1: value4, key2: value5, key3: value6}
2 { key1: value7, key2: value8, key3: value9}
3 { key1: value10, key2: value11, key3: value12}
</code></pre>
<p>I want... | <p>IIUC, this should work:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame.from_records(sn)
</code></pre> | python|pandas|dataframe|series | 2 |
16,374 | 67,189,529 | how to use loc in dataframe to get all values of columns except last one in python? | <p>I am using pandas dataframe in python. I am trying to get values from a particular row by using slicing. It works well when I try with all (:) or by using start index to end(start_index:). But it does not work when I use it with negative indexing to select upto last value(:-1).</p>
<p>Consider the following:</p>
<pr... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a> for select by positions, but need also position of column <code>mid</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.ge... | python|pandas|dataframe | 2 |
16,375 | 67,533,759 | How to expand list which contains multiple dictionaries into a dataframe? | <p>I need to expand list with multiple dictionaries but really cant find the way...</p>
<p>This is how df looks:</p>
<pre><code>ColumnA actions
A [{'link_click': '1'}, {'post_engagement': '1'}]
B [{'link_click': '13'}, {'post_engagement': '5'}, {'page_engagement': '7'}]
</code></pre>
<p>Th... | <p>Start by merging the list of dicts in each row to create a single record corresponding to each row, then create a new dataframe from these generated records now add prefix and <code>join</code> the new dataframe with the original frame</p>
<pre><code>records = [{k:v for d in l for k, v in d.items()} for l in df['act... | python|pandas|list|dictionary | 3 |
16,376 | 67,508,505 | Pandas calculate net based on previous row value | <p>I have a pandas dataframe from which I am trying to get net value based on previous row values</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">id</th>
<th style="text-align: center;">date</th>
<th style="text-align: center;">current_value</th>
<th style="text-... | <p>It looks like:</p>
<pre><code>df['net_value'] = (df.groupby(['id','date'])
['current_value'].cumsum()
.add(df['previous_date_value'])
</code></pre>
<p>)</p> | pandas|dataframe | 1 |
16,377 | 67,601,764 | Equally distribute a pandas Dataframe based on column | <p>I have a Pandas DataFrame with unevenly distributed labels:</p>
<pre><code>a label
0 0
1 0
2 0
3 0
4 0
..
65693 7
65694 7
65695 7
65696 7
65697 7
</code></pre>
<p>"Rows" per label:</p>
<pre><code>1: 7673
2: 28930
3: 615
4: 7619
5: 3888
6: 2853
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.head.html" rel="nofollow noreferrer"><code>GroupBy.head</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_c... | python|pandas | 3 |
16,378 | 60,069,156 | Pandas cummulative sum based on True/False condition | <p>I'm using python and need to solve the dataframe as cumsum() the value until the boolean column change its value from True to False. How to solve this task?</p>
<pre><code> Bool Value Expected_cumsum
0 False 1 1
1 False 2 3
2 False 4 ... | <p>You can try this</p>
<pre><code>a = df.Bool.eq(True).cumsum().shift().fillna(0)
df['Expected_cumsum']= df.groupby(a)['Value'].cumsum()
df
</code></pre>
<p><strong>Output</strong></p>
<pre><code> Bool Value Expected_cumsum
0 False 1 1
1 False 2 3
2 False 4 7
3 True 1 ... | python|pandas | 3 |
16,379 | 60,021,777 | Pytorch Module: Why do we pass the class and object to the parent class initializer, in the __init__ method? | <p>Why do we pass the class and the object (self) to the parent's init method for pytorch Module? For e.g.</p>
<pre><code>class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
</code></pre>
<p>Why is the class RNN, as well as the object (self) passed to the pa... | <p>Every method receives the instance of the class invoking the method as its first argument; <code>__init__</code> is no exception. <code>foo = RNN(...)</code> causes <code>foo.__init__(...)</code> to be called, which is equivalent to <code>RNN.__init__(foo, ...)</code>.</p>
<p><code>super</code> returns a "proxy" fo... | pytorch | 1 |
16,380 | 65,314,638 | Custom metric for Keras model, using Tensorflow 2.1 | <p>I would like to add a custom metric to model with Keras, I'm debugging my working code and I don't find a method to do the operations I need.</p>
<p>The problem could be described as a multi classification trough logistic multinomial regression.
The custom metric I would like to implement is this:</p>
<pre><code>(1/... | <p>So you want calculate <strong>average recall wrt multiclass in the batch</strong>, here is my example code using <code>numpy</code> and <code>tensorflow</code>:</p>
<pre><code>import tensorflow as tf
import numpy as np
y_t = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1]], dtype=np.f... | python|keras|tensorflow2.x|keras-metrics | 2 |
16,381 | 65,455,136 | Pandas: Selecting row-range and column on a filtered dataframe | <p>Lets say I have data like this:</p>
<pre><code>df = pd.DataFrame({'category': ["blue","blue","blue", "blue","green"], 'val1': [5, 3, 2, 2, 5], 'val2':[1, 3, 2, 2, 5]})
print(df)
category val1 val2
0 blue 5 1
1 blue 3 3
2 blue 2 ... | <p>This makes sense because you are chaining two loc calls. My suggestion is to squash the two loc calls together. You can do this by filtering, then grabbing the index and to use in another <code>loc</code>:</p>
<pre><code>df.loc[df[df['category'].eq('blue')].index[1:3], 'val1'] = 123
</code></pre>
<p>Notice I have to... | python|pandas|dataframe | 2 |
16,382 | 65,428,746 | Pandas Remove Duplicate Rows Based on Condition | <p>I have a pandas data frame as follows</p>
<pre><code>+---------+------------+------------+-------+--------+
| Product | Date | Adj_Date | Price | Factor |
+---------+------------+------------+-------+--------+
| A | 01-06-2020 | 01-07-2020 | 100 | 10 |
| A | 01-06-2020 | 01-08-2020 | 200 ... | <p>First, convert <code>Date</code> and <code>Adj_Date</code> to Timestamp. This will make your life a lot easier:</p>
<pre><code>for col in ['Date', 'Adj_Date']:
df[col] = pd.to_datetime(df[col], dayfirst=True)
</code></pre>
<p>Then:</p>
<pre><code># Pick one row for each product
def pick_one(group):
if len(gr... | pandas|dataframe|group-by|duplicates | 2 |
16,383 | 64,121,155 | How to index a dataframe by a column's values between two limits | <p>I want to be able to make a smaller subset of a dataframe by indexing a dataframe by the required values in one column of the dataframe.</p>
<p><em><strong>Code</strong></em></p>
<pre><code>import pandas as pd
import numpy as np
data = [['Alex',15,4],['Bob',5,1],['Clarke',13,2],['dan',6,2],['eve',19,1],['fin',12,1... | <p>Another way to do it is to use apply with lambda:</p>
<pre><code>mid_range = df[df['Age'].apply(lambda x: x in range(lo,hi+1))]
</code></pre>
<p>When measuring the execution time of using apply with lambda and the <code>&</code> operator,
I noticed that apply lambda is a bit faster!</p>
<pre><code>start_time = t... | python|pandas|dataframe|indexing | 1 |
16,384 | 64,155,232 | Check uniqueness for a specific value in each column | <p>Suppose I have a pandas.DataFrame <code>df</code> similar to this:</p>
<pre class="lang-py prettyprint-override"><code> A0 A1 A2
0 a a b
1 b b g
2 c b h
3 d c NaN
</code></pre>
<p>Now there are specific values that I want to check against that DataFrame. Let's call them</p>
<pre clas... | <p>Let's use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a> to create a boolean mask corresponding to each of the candidates then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFram... | python|pandas|dataframe | 2 |
16,385 | 46,756,233 | Import file with multiple column file as variables with pandas in python | <p>I have a .txt file with several columns from a measurement.
These values came from sensors and the number of columns is <strong>not always the same</strong>.</p>
<p>The file structure looks something like this (it has about 40 lines of "trash" from the descriptions of the sensors, dates and so on):</p>
<p>1,096666... | <p>Use parameter <code>header</code> for default columns names - <code>0,1,2..</code> and then <code>rename</code> them by <code>dictionary</code>:</p>
<pre><code>import string
#dict for map columns
d = dict(zip(range(26), list(string.ascii_lowercase)))
print (d)
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g'... | python|python-3.x|pandas | 0 |
16,386 | 46,941,149 | How to implement this activation function in numpy? | <p>How can I implement with numpy:</p>
<p><a href="https://i.stack.imgur.com/AILyc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AILyc.png" alt="enter image description here"></a></p>
<p>and its derivative <code>f'(x)</code>? I tried to:</p>
<pre><code> def func (x,y):
if x.all() <... | <p>How about:</p>
<pre><code>def func (x, beta):
y = np.empty_like(x)
mask = x <= 0
y[mask] = beta * (np.exp(x[mask])-1)
y[~mask] = x[~mask]
return y
</code></pre>
<p>mask contains the indizes for elements that are <= 0, so that you can seperate the two cases.</p> | python|python-3.x|numpy|scipy | 2 |
16,387 | 62,906,251 | How to convert integer type array (with some NaN) to string type array | <p>I have an array <code>x</code> and one of the values is <code>NaN</code>.</p>
<p><code>x = [1, 2, NaN, 3, 5]</code></p>
<p>All the elements are integer excepting <code>NaN</code>.
This array type is regarded as float64 not int.</p>
<p>I would like to convert type from floating to string.</p>
<p>I tried <code>astype(... | <pre><code>import numpy as np
df1 = df.replace(np.nan, '', regex=True)
</code></pre>
<p>This might help. It will replace all NaNs with an empty string.</p> | python|python-3.x|pandas|numpy | 4 |
16,388 | 62,965,808 | How to effeciently remove character if available at the beginning and end of a string in Pandas? | <p>The idea is to remove full stop, commas, quotation if it is available at the beginning and last string in Pandas.</p>
<p>Given a <code>df</code> as below</p>
<pre><code>data = {'Name': ['"Tom hola.', '"nick"', 'krish here .','oh my *']}
</code></pre>
<p>The expected output is</p>
<pre><code>Tom hola
n... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>pd.Series.str.replace</code></a> if you want replace only colum else use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" r... | python|pandas|replace | 2 |
16,389 | 63,245,493 | NumPy - Excluding all zero 2D arrays from a 3D array | <p>I have multiple 3D arrays with different shapes but I'm going to assume I have an array named <code>A</code> with shape <code>(53, 768, 768)</code> for an example. It consists of 53 2D arrays and some of them may be empty images. Those empty images have only 0 pixel values.</p>
<p>If there are <code>N</code> slices ... | <p>Let's assume your data is something like this:</p>
<pre class="lang-py prettyprint-override"><code>z = np.array([
[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]],
[[0, 0, 0], [0, 0, 0]],
[[1, 1, 1], [1, 1, 1]]
])
</code></pre>
<p>The shape of <code>z</code> is <code>(4, 2, 3)</code>. We therefore n... | python|arrays|numpy | 1 |
16,390 | 67,904,490 | Efficient pythonic way for this operation | <p>I am looking for an efficient way to perform the following operation; here is a minimal working code:</p>
<pre><code>import numpy as np
from scipy.signal import fftconvolve
n = 7
m = 100
N = 3000
a = np.random.rand( n,m,N ) + np.random.rand( n,m,N )*1j
b = np.random.rand( n,m,N ) + np.random.rand( n,m,N )*1j
# we... | <h4>Reference implementation</h4>
<p>I will start wrapping the operation in a function so that I can easily compare implementations</p>
<pre class="lang-py prettyprint-override"><code>def ref_impl(a,b):
n,m,N = a.shape
a = a.reshape( m*n, N )
ans = []
for i in range( n ):
b_tiled = np.tile( b[... | python-3.x|numpy|scipy | 1 |
16,391 | 67,963,014 | common Value for each row in a single column in pandas | <p>I'm trying to find a duplicate value for each row in a specific column in the pandas dataframe.</p>
<pre><code>df = pd.DataFrame(data=[[1,['A','B','C']],[1,['C','D','F']],[1,['C','E','F']],[2,['E','G','F']],[2,['E','D','H']] ],columns=['id','tag'])
df
Out[1]:
id tag
0 1 [A, B, C]
1 1 [C, D, F... | <p>To get the common value among all lists per group use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html#pandas-core-groupby-dataframegroupby-aggregate" rel="nofollow noreferrer"><code>groupby aggregate</code></a> with a bit of <code>set</code> log... | python|pandas|duplicates | 0 |
16,392 | 61,343,564 | How to fill in missing values in pandas dataframe with zeros? | <p>I have a pandas DataFrame with the following values:</p>
<pre><code>df =
1970-01-01 00:00:18 1 1 0 1 0
1970-01-01 00:00:19 0 0 0 1 0
1970-01-01 00:00:20 0 0 0 1 0
1970-01-01 00:00:25 0 1 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html" rel="nofollow noreferrer"><code>DataFrame.asfreq</code></a> working with <code>DatetimeIndex</code>, last convert <code>index</code> to column if necessary:</p>
<pre><code>print (df)
date a b c ... | python|pandas|dataframe|missing-data | 2 |
16,393 | 61,203,989 | Pandas Dataframe: I want to merge two cells with same value into one | <p>My excel sheet looks like this:-
<a href="https://i.stack.imgur.com/T8NlO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T8NlO.png" alt="enter image description here"></a></p>
<p>I need output in this format:</p>
<p><a href="https://i.stack.imgur.com/9DYfC.png" rel="nofollow noreferrer"><img sr... | <p>Here is a working example with empty strings in the duplicated <code>Data</code> column cells:</p>
<pre><code>df = pd.DataFrame({'Data': [10, 10, 20, 30, 20, 15, 30, 45], 'Value': [1,2,3,4,5,6,7,8]})
duplicated_data = df.Data.duplicated(keep='last')
df.Data = df.Data.where(~duplicated_data, '')
df
</code></pre>
<p... | python|pandas|dataframe | 2 |
16,394 | 61,546,036 | Why do we average the losses of all elements of the batch if we typically should average the gradients (rather than the losses)? | <p>My <code>loss</code> output is </p>
<pre><code>tensor([0.0430, 0.0443, 0.0430, 0.0430, 0.0443, 0.0466, 0.0466, 0.0466],
grad_fn=<AddBackward0>)
</code></pre>
<p>When I execute <code>loss.backward()</code>, I obtained <code>*** RuntimeError: grad can be implicitly created only for scalar outputs</code>... | <p>Because by default when called upon a scalar it passes <code>[1]</code> as input to the backward function. If it's a tensor with more than one element then you should pass <code>[1,1,....1]</code> as the input to the backward. </p>
<pre><code>loss.backward(torch.Tensor([1, 1, 1, 1, 1, 1, ... ,1]))
</code></pre>
<... | python|pytorch|gradient | 0 |
16,395 | 68,679,009 | pytorch tensor conversion - tensor of tensors | <p>I have two tensors in one dataset as below
<a href="https://i.stack.imgur.com/LdyYF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LdyYF.png" alt="enter image description here" /></a></p>
<p>how i can convert into tensor of tensors? to get final output as below:
<a href="https://i.stack.imgur.com... | <p>resolved by:</p>
<pre><code>samplelist = []
for i in transformed_dataset:
sample = i['image'], i['label'].view(1)
samplelist.append(sample)
</code></pre> | python|pytorch|tensor | 0 |
16,396 | 68,736,653 | TensorFlow GPU version instead of CPU version in Pycharm | <p>How do I use TensorFlow GPU version instead of CPU version in PyCharm (or other environment)?</p> | <p>By default, as of TensorFlow 2.1 (regardless of PyCharm or whatever env you're coding in), TensorFlow installs the CPU+GPU package together. For older versions (which I do not recommend), you can explicitly use <code>pip install tensorflow</code> (old CPU versions) or <code>pip install tensorflow-gpu</code></p>
<p>I... | tensorflow|gpu | 0 |
16,397 | 68,655,634 | Pandas groupby to expanding to list (numpy array) | <p>I have a DataFrame that can be produced using this Python code:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'visit': [1] * 6 + [2] * 6,
'time': [t for t in range(6)] * 2,
'observations': [o for o in range(12)]})
</code></pre>
<p>The following code enables me to reform... | <p>Looks like a good solution has been provided but dropping this here as a viable alternative.</p>
<pre><code>(df.
set_index('visit')['observations'].
apply(lambda x: [x]).
reset_index().groupby('visit')['observations'].
apply(lambda x: x.cumsum())
)
</code></pre> | python|pandas|pandas-groupby | 1 |
16,398 | 65,526,864 | Could you please help me pivot this pandas data frame in python? | <p>I am trying to figure out how to pivot this table in Python.</p>
<pre><code>example = {"ABC":{'2020-09':1.33,'2020-10':0.75,'2020-11':1.55},
"DEF":{'2020-09':1.22,'2020-10':1.75,'2020-11':2.73}}
df = pd.DataFrame(example)
df
</code></pre>
<p><a href="https://i.stack.imgur.com/WEMYX.png" rel="nof... | <p>The simplest version is probably</p>
<pre><code>df.unstack()
</code></pre>
<p>which gives you an outcome with multiindex:</p>
<pre><code>ABC 2020-09 1.33
2020-10 0.75
2020-11 1.55
DEF 2020-09 1.22
2020-10 1.75
2020-11 2.73
dtype: float64
</code></pre>
<p>If you don't want the ... | python|pandas|dataframe | 2 |
16,399 | 65,509,802 | Transposing group of data in pandas dataframe | <p>I have a large dataframe like this:</p>
<pre><code>|type| qt | vol|
|----|---- | -- |
| A | 1 | 10 |
| A | 2 | 12 |
| A | 1 | 12 |
| B | 3 | 11 |
| B | 4 | 20 |
| B | 4 | 20 |
| C | 4 | 20 |
| C | 4 | 20 |
| C | 4 | 20 |
| C | 4 | 20 |
</code></pre>
<p>How can I transpose to the datafr... | <p>You can <code>group</code> the dataframe on <code>type</code> then create key-value pairs of groups inside a dict comprehension, finally use <code>concat</code> along <code>axis=1</code> and pass the optional <code>keys</code> parameter to get the final result:</p>
<pre><code>d = {k:g.reset_index(drop=True) for k, g... | python|pandas|dataframe | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.