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 |
|---|---|---|---|---|---|---|
17,900 | 72,722,553 | How to create a nested dictionary from a given dataframe? | <p>I got a df like this one:</p>
<pre><code>level profile chest_gold chest_silver chest_bronze
1 a TRUE FALSE TRUE
2 a FALSE FALSE TRUE
3 a FALSE TRUE TRUE
</code><... | <p>Check a nested dictionary comprehension. The inner comprehension builds dictionary where keys are levels and outer comprehension builds a dictionary where the keys are profiles.</p>
<pre><code>output = {k: {i: v for i, *v in d.set_index('level').filter(like='chest').astype(int).to_records()} for k, d in df.groupby('... | python|pandas|dataframe|dictionary|pandas-groupby | 0 |
17,901 | 72,514,941 | Train local model with SVM instead of NN in federated learning | <p>I have a dataset with numeric features and labels. I am building a federated learning model using TensorFlow (TFF).
Basically, the model that I have is the (neural network) which is always explained in the TFF tutorials.
I want to ask if there is a chance to build another model for the local clients, such as SVM? si... | <p>TFF supports a wide variety of models, including just about any model you can write in <code>tf.keras</code>.</p>
<p>You can also create a TFF model directly by subclassing <a href="https://www.tensorflow.org/federated/api_docs/python/tff/learning/Model" rel="nofollow noreferrer">https://www.tensorflow.org/federated... | python|tensorflow|keras|tensorflow-federated | 1 |
17,902 | 72,768,971 | Find max local value in a range | <p>I've been struggling with a problem for some days and I can't find the way.</p>
<p>I just need to find the MAX value in a range, but this is a dynamic range looking 2 rows forward and the 2 previous rows if possible. So for the first row I look only forward rows [0, 1, 2] but in row 5 I want to compare maxs of [3,4... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>rolling</code></a>:</p>
<pre><code>df['Max5'] = df['Close'].rolling(5, center=True).max()
print(df)
# Output:
Close Max5
0 10 NaN
1 12 NaN
2 13 13.0
3 ... | python|pandas|range|max | 0 |
17,903 | 72,549,986 | How to parse colon delimiter data in python when list style is different? | <p>Cell 1, Cell 2, and Cell 3 are 3 rows within excel which contains the data I would like to parse - see below(initial data). I am trying to parse the information in each cell by respecting their value possible using python libraries or excel formulas. I am trying to create column for each line like the outcome data b... | <p>Given a cell of data:</p>
<pre><code>d = """Employee:
Info: John Doe3, John.Doe3@abc.com
Response: Yes
Request Date: Wednesday, June 1, 2022 7:00:00 PM
Response Date: Thursday, June 2, 2022 8:00:00 AM
Manager:
Info: John Doe4, John.Doe4@abc.com
Response: Yes
Request Date: Wednesday, June 1, 2022 7:... | python|excel|pandas | 0 |
17,904 | 62,025,397 | Transform and append string values in a list inside dataframe | <p>I have this dataframe:<br /></p>
<pre><code>dict_values = {'name':['John','Peter'], 'attach':['0001-test.jpg,0002-test.jpg','0003-test.jpg']}
</code></pre>
<pre><code>name | attach
John | 0001-test.jpg,0002-test.jpg
Peter | 0003-test.jpg
</code></pre>
<p>I need to get the value before "-" and append into a list.<... | <p>u can also use findall</p>
<pre><code>dict_values = {'name':['John','Peter'],
'attach':['0001-test.jpg,0002-test.jpg','0003-test.jpg']}
df = pd.DataFrame(dict_values)
df['attach'] = df['attach'].str.findall("(\d+)-")
</code></pre>
<p>output,</p>
<pre><code> name attach
0 John [0001, ... | python|pandas | 4 |
17,905 | 61,858,079 | "IndexError: child index out of range "- converting xml to csv | <p>As a beginner with the Python, I am trying to convert my XML files to CSV using this tutorial instructions (<a href="https://www.youtube.com/watch?v=kq2Gjv_pPe8&list=PLiIy2ThQvgewp67FDKV2H1h-154bJK9RS&index=2&t=477s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=kq2Gjv_pPe8&list=PLiIy2ThQ... | <p>Please try:</p>
<pre><code>for member in root.findall('object'):
value = (root.find('filename').text,
int(root.find('size').find('width').text),
int(root.find('size').find('height').text),
member[0].text,
int(member.find("bndbox").find('xmin').... | python|xml|csv|tensorflow|elementtree | 7 |
17,906 | 61,930,843 | Python Bokeh plot static secondary y axis | <p>I'm just trying to use the candlestick example and adding a volume bar chart. So far so good. I want to have a static range on my secondary y axis, so that all zooming only happens on the primary axis.</p>
<pre><code># Candlestick price chart
inc = df.close >= df.open
dec = df.open > df.close
p = figure(x_axi... | <blockquote>
<p>Now I want, that this range never changes. </p>
</blockquote>
<p>Currently (as of version 2.0.2), extra axes are always linked together to maintain their original relative scale. It's not possible to have a second axis that does not rescale while the other axis changes range. AFAIK there is not any i... | python|python-3.x|bokeh|pandas-bokeh | 1 |
17,907 | 61,951,517 | Parsing array from txt file to Pandas dataframe in Python | <p><strong>Hi, I have such array in my .txt file:</strong></p>
<p>n|vechicle.car.characteristics[0].speed|180<br>
n|vechicle.car.characteristics[0].weight|3<br>
c|vechicle.car.characteristics[0].color|black<br>
c|vechicle.car.characteristics[0].fuel|95<br>
n|vechicle.car.characteristics[1].speed|160<br>
n|vechicle.car... | <p>Read as <code>csv</code> file with <code>sep='|'</code> then get last column which contain values and then <code>reshape</code> in appropriate shape.</p>
<pre class="lang-py prettyprint-override"><code>>>> columns=['speed','weight','color','fuel']
>>> s = pd.read_csv('filename.txt', sep='|', heade... | python|pandas|dataframe|parsing|text-parsing | 1 |
17,908 | 61,659,414 | AttributeError: module 'tensorflow' has no attribute 'CuDNNLSTM' | <p>My code is as follows:</p>
<pre><code>import tensorflow as tf
from tensorflow.keras import layers
# initial layer
model = tf.keras.Sequential()
# emmbed word vectors
model.add(tf.keras.layers.Embedding(len(fasttext_model.wv.vocab)+1,300,input_length=X.shape[1],weights=[embed_matrix],trainable=False))
model.add(t... | <p>If you're using versions before 2.0, the statement is:</p>
<pre><code>model.add(tf.keras.layers.CuDNNLSTM(300, return_sequences = True))
</code></pre>
<p>If the version of tensorflow is >= 2.0, this layer has been removed. Instead, simply using LSTM layer with default activations automatically uses CuDNN. You can ... | tensorflow | 2 |
17,909 | 57,739,774 | Unable to replace empty values with 0 in a list of tuples with pandas | <p>I have a data which looks like below</p>
<pre><code>data = [[('A', 204.593564568), ('B', 217.421341061), ('C', 237.296250326), ('D', 217.464281998), ('E', 206.329901299)], [('F', 210.297625953), ('G', 228.117692718), ('H', 4), ('I', 265.319671257), ('K',)]]
</code></pre>
<p>This is just a small part of the data th... | <p>use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer">pd.applymap</a></p>
<pre><code>df.applymap(lambda x: (x[0],0) if len(x) == 1 else x)
</code></pre>
<hr>
<pre><code> 0 1 2 \
0 (... | python|pandas | 4 |
17,910 | 54,877,448 | Using Or Statement in pandas for assigning values? | <p>I have two dataframes</p>
<p>df1</p>
<pre><code> a b c
0 Sussex NaN NaN
</code></pre>
<p>df2</p>
<pre><code> d e f g
0 NaN NaN NaN NaN
</code></pre>
<p>I'm trying to use a Or statement to assign the df3['i'] from either df1['a'] or df2['d']</p>
... | <p>The question is not fully clear. What is i here? If df1['a'] or df2['d'] is the first iteration, is the second iteration df1['b'] or df2['e'] ? Where does the iteration end? Long winded solution and not sure if this is what you are looking for</p>
<pre><code>def applymapfunction(df1,df2):
df3 = pd.DataFrame()
... | python|pandas|dataframe | 0 |
17,911 | 54,805,316 | How access objects (tables) of Other Users in Oracle DB using Python tools (SQLAlchemy, cx_Oracle, etc.)? | <p>I have read access to other users' tables. How can I read them into pandas dataframe or just download as <code>*.csv</code> using Python tools?</p> | <p>You need to install cx_oracle and SQLAlchemy.</p>
<pre><code>import cx_Oracle
import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine ('oracle+cx_oracle://user:pwd@host:port/dbname')
connection = engine.connect()
df = pd.read_sql("select * from otheruser.table", connection)
df.head()
df.to_csv("file.... | python|sql|oracle|pandas|sqlalchemy | -1 |
17,912 | 54,852,316 | Appending Numpy Arrays | <p>I have a for loop where I create numpy array a. I want to have a results numpy array that I append array a to every loop. So the final structure of the results array should be [a,a,a,etc...], such that I can get into a new array [len(a),Len(a),etc..]</p>
<p>I can't figure out how to do this. I've tried np.append, a... | <p>The simplest (and quickest) way is to collect the arrays in a list, then use <code>np.concatenate</code> to join them all together.</p>
<p>Example test data </p>
<pre><code>import numpy as np
a = np.random.rand(4,5)
b = np.random.rand(4,5)
c = np.random.rand(4,5)
d = np.random.rand(4,5)
lst = [a,b,c,d]
</code></... | python|numpy | 1 |
17,913 | 49,767,631 | get day wise average task time in python | <p>Friends in the dataframe I have</p>
<pre><code>ID creationdateTime Totaltime
283318 2018-03-30 18:54:18 64.7000
283316 2018-03-30 18:50:35 87.4000
283249 2018-03-30 17:55:51 114.9333
283213 2018-03-30 17:34:54 107.8500
283197 2018-03-30 16:25:15 71.8000
283178 2018-03-30 15:13:10 140.5500
28317... | <p>If I've understand correctly, you have a data of second or minute wise and you want to compute the average for day.
First of all you have to combine the <code>creationdateTime</code> time column day wise which can be done with Grouper functionality and then you can use the mean function so that it will get you the ... | python|pandas | 0 |
17,914 | 49,661,371 | pyspark groupBy with multiple aggregates (like pandas) | <p>I'm very new to pyspark and I'm attempting to transition my pandas code to pyspark. One thing I'm having issues with is aggregating my groupby.</p>
<p>Here is the pandas code:</p>
<pre class="lang-python prettyprint-override"><code>df_trx_m = train1.groupby('CUSTOMER_NUMBER')['trx'].agg(['mean', 'var'])
</code></p... | <p>You can import <a href="http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#module-pyspark.sql.functions" rel="noreferrer"><code>pyspark functions</code></a> to perform aggregation.</p>
<pre class="lang-python prettyprint-override"><code># load function
from pyspark.sql import functions as F
# aggregate... | python|pandas|pyspark|pyspark-sql | 8 |
17,915 | 73,361,251 | Outlier detection not working in pandas, negative number on the lower limit | <p>I have the following dataset:</p>
<p><a href="https://raw.githubusercontent.com/Joffreybvn/real-estate-data-analysis/master/data/clean/belgium_real_estate.csv" rel="nofollow noreferrer">https://raw.githubusercontent.com/Joffreybvn/real-estate-data-analysis/master/data/clean/belgium_real_estate.csv</a></p>
<p>with de... | <p>Your method is correct, however a small change need to be done to make it complete.</p>
<p>When the lower limit (<code>Q1 - 1.5 * IQR</code>) is smaller than the minimum, you don't have any outliers that are very low.</p>
<p>On the other hand, the upper limit (<code>Q3 + 1.5 * IQR</code>) is smaller than the maximum... | python|pandas | 0 |
17,916 | 60,154,854 | Pandas - split column after the last instance of a delimiter only where there is 2 numeric following the delimiter | <p>I'm attempting to split a column in a pandas DataFrame following the last instance of a delimiter in this case: <code>-</code>, and only where the value after the delimiter is two numeric values.</p>
<p>An snippet of the DataFrame <code>df</code> is seen below.</p>
<pre><code>full_code
101-453-11 ... | <pre><code>df = df.assign(after_delimiter=
df['full_code'].str.split('-')
.apply(lambda x: x[-1] if len(x[-1]) == 2 and x[-1].isnumeric() else 'nan'))
mask = df['after_delimiter'].ne('nan')
df.loc[mask, 'full_code'] = df.loc[mask, 'full_code'].str[:-3]
>>> df
full_code after_... | python|pandas | 1 |
17,917 | 60,050,503 | How to select from a 2D numpy.array where column == condition | <p>As an example, I have a set of records in a 2D numpy.array and I would like to select all records where value in the 3rd column equal 10. Is there a way to do that apart from looping through the array and build a list of the selected records?</p> | <p>Once I knew of the 'filter' concept, I searched some more and found the answer I was looking for in this <a href="https://stackoverflow.com/questions/47885848/filter-a-2d-numpy-array">stackoverflow question</a>.</p>
<p>So in the car example, the filter would be written as
df[df[:,1] == 'car']</p> | arrays|python-3.x|numpy|select | 0 |
17,918 | 60,104,842 | Is in Tensorflow 2.x we aren't need to specify the input shape? | <p>I just read the official tutorial <a href="https://www.tensorflow.org/tutorials/quickstart/advanced" rel="nofollow noreferrer">in this page</a>. And the code example to create a model is below:</p>
<pre><code>class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32,... | <p>Everything is working as intended.</p>
<p>Convolution as an operation works regardless of the input shape. Just the channels of the input needs to match.
You can see this behavior work as expected in tf.nn.conv2d. (Which is what your code snippet is using)</p>
<p>Now, you are linking a reference to keras.conv2d wh... | python|conv-neural-network|tensorflow2.0 | 1 |
17,919 | 65,074,325 | TypeError: tuple - tuple on keras custom error | <p>I want to make a custom loss function that compares gradient between two images, using Keras. So I made a code like:</p>
<pre><code>def mean_gradient_error(y_true,y_pred):
alpha = 0.6
if not B.is_tensor(y_pred):
y_pred = B.constant(y_pred)
y_true = B.cast(y_true, y_pred.dtype)
yt_grad = B_.tf... | <p>The documentation of <a href="https://www.tensorflow.org/api_docs/python/tf/image/image_gradients" rel="nofollow noreferrer"><code>tf.image.image_gradients</code></a> states :</p>
<blockquote>
<p><strong>Returns</strong>
Pair of tensors (dy, dx) holding the vertical and horizontal image gradients (1-step finite diff... | python|tensorflow|keras|deep-learning | 1 |
17,920 | 65,309,385 | Vectorized matrix calculation comparing a relational matrix and taking the minimum in Python | <p><strong>Matrices</strong></p>
<p>I want to create a vectorized approach (numpy) to populate/calculate the matrix called "qtyP" using input from the matrices "qtyC" and "rel". It is easy to solve in for loops but I would like to do it in a smarter way. First I will describe my matrices.<... | <p><strong>EDIT -</strong> Changing my answer based on the comments.</p>
<p>IIUC, here is what you can do -</p>
<ol>
<li>Since, before you can calculate the minimum, you need the different quantities for each product for each week, what you need to construct is a <code>(6,5,5)</code> tensor with <code>broadcasting</cod... | python|numpy | 0 |
17,921 | 65,378,688 | unable to initialize Keras model through subclassing | <p>im trying to create a keras model through subclassing using:</p>
<pre><code>class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.dense1 = Dense(64, activation='relu')
self.dense2 = Dense(10)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
... | <p>You passed the input data as arguments to the model constructor. You need to instantiate it</p>
<pre><code>model = MyModel()
</code></pre>
<p>Then you can pass input tensors</p>
<pre><code>model(tf.random.uniform([1, 10]))
</code></pre>
<p>And this will work</p>
<pre><code><tf.Tensor: shape=(1, 10), dtype=float32... | python|tensorflow|keras|tensorflow2.0|tf.keras | 0 |
17,922 | 49,936,674 | Plot line chart by grouping columns in dataframe | <p>I have a csv file with data that I grouped the information on months and then used cumsum to calculate the running total for the month into a dataframe.</p>
<p>Using this code:</p>
<pre><code>df = df.sort_index(sort_remaining=True).sort_values('months')
df['value'] = df.groupby('months')['value'].cumsum()
</code><... | <p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> with <code>rename</code> for months names instead numeric and for new index values use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.G... | pandas|matplotlib|plot|linechart|cumulative-line-chart | 0 |
17,923 | 50,002,289 | Pandas update values in a multi-index dataframe | <p>How can I edit a values of a multi-index dataframe? If it was a non-multi-index dataframe, I know I could do this: <code>df.at[0,'foo'] = 12.3</code>.
Also, this does not work: <code>df.loc[0]['foo']['a'] = 12.3</code>.</p>
<p>Consider a multi-index column dataframe.</p>
<pre><code>colnames = [
['foo', 'foo', 'f... | <p>Use <code>tuple</code>s for select <code>MultiIndex</code> in columns:</p>
<pre><code>df.loc[0, ('foo','a')] = 12.3
print (df)
foo po di
a b c a b c a b c
0 12.3 NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN N... | python|pandas|dataframe|multi-index | 15 |
17,924 | 49,849,390 | How to create a new column of dates by adding a corresponding column of days to today's date using PANDAS | <p>The final column of my dataframe <code>df</code> looks like:</p>
<pre><code> ... Days till Service
0 ... 0
1 ... 28
2 ... 7
3 ... 54
4 ... 0
5 ... 6
6 ... 28
7 ... ... | <p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>pd.to_timedelta</code></a>, you can convert <code>df['Days till Service']</code> to timedeltas, then add them to today's date:</p>
<pre><code>df['Predicted Service Date'] = \
pd.to_dat... | pandas|datetime | 2 |
17,925 | 50,082,440 | python stacked bar chart using categorical data | <p>I have a Pandas dataframe (1800 obs) that looks something like this:</p>
<pre><code> A B C D
1 CL0 CL1 CL2 CL0
2 CL2 CL1 CL1 CL3
3 CL3 CL2 CL0 CL1
. ... ... ... ...
. ... ... ... ...
n CL2 CL1 CL0 CL3
</code></pre>
<p>I want ... | <pre><code>print(df)
</code></pre>
<p>Output:</p>
<pre><code> A B C D
1 CL0 CL1 CL2 CL0
2 CL2 CL1 CL1 CL3
3 CL3 CL2 CL0 CL1
</code></pre>
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer">.apply()</a></p>
<pre><code>counts... | python|pandas|matplotlib | 5 |
17,926 | 64,135,460 | How to get rows where column value starts with 2 or 3 digits and inch symbol (") | <p>I have a df with rows like:</p>
<pre><code>index | text
0 | '28,3" LEDTV K98765 AB12345 EU'
1 | '65" LEDTV K98765 AB12345 EU'
2 | '55,3" LEDTV K98765 AB12345 EU'
3 | 'MON 22,8" LED U754 PL333 DE'
4 | 'DAB Radio Work 34RT55 Blue'
</code></pre>
<p>Every TV starts with the size i... | <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 numbers before <code>"</code>, replace <code>,</code> and convert to floats, so possible compare by <a href="http://pandas.pydata.org/panda... | pandas|string|conditional-statements|series | 1 |
17,927 | 64,065,963 | How I solve the runtim error coming while running the MNIST datasets in pycharm | <p>RuntimeWarning: Invalid cache, redownloading file warn("Invalid cache, redownloading file", RuntimeWarning)</p> | <p>This is a warning message, you can retry to fix it</p> | dataset|sklearn-pandas | 0 |
17,928 | 46,789,098 | Create new column in dataframe with match values from other dataframe | <p>Have two dataframes, one has few information (df1) and other has all data (df2). What I am trying to create in a new column in df1 that finds the Total2 values and populates the new column accordingly based on the Names. Note that the Names visible in df1 will always find a match in Names of df2. I am wondering if ... | <p>Need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="noreferrer"><code>map</code></a> by <code>Series</code> first for new column:</p>
<pre><code>df1['Total2'] = df1['Name'].map(df2.set_index('Name')['Total2'])
print (df1)
Name Total Total2
0 Accounting 3... | python|pandas|dataframe | 13 |
17,929 | 62,923,547 | Extract data from certain columns and generate new rows | <p>I have a pandas dataframe</p>
<pre><code>COL1 COL2 COL3 COL4
A B C [{COL5: D1, COL6: E1, COL7: F1},
{COL5: D2, COL6: E2, COL7: F2},
{COL5: D3, COL6: E3, COL7: F3},
...
{COL5: D10, COL6: E10, COL7: F10}]
</code></pre>
<p>The outpu... | <p><em><strong>Setup</strong></em></p>
<pre><code>data = [{"COL5": f"D{i}", "COL6": f"E{i}", "COL7": f"F{i}"} for i in range(1, 4)]
df = pd.DataFrame({"COL1": ["A"], "COL2": ["B"], "COL3": ["C"], &quo... | python|pandas|dataframe|data-science | 1 |
17,930 | 62,921,956 | How to plot bar plot for dataframe? | <p>I am trying to plot a bar plot, but it looks really bad.</p>
<pre><code>plt.style.use('ggplot')
x = ['High School or Below', 'College', 'Bachelor', 'Master or Above']
y = [maleDataFrame["Education"].str.contains("High School or Below").sum(),
maleDataFrame["Education"].str.contains... | <p>You can add back the line that defines <code>y</code> to reproduce it using the data you have. Protip: Use <code>bar(x, y, width=30)</code> to modify the width of the bar as per your requirement.</p>
<p>Modified your code to:</p>
<pre><code>plt.style.use('ggplot')
x = ['High School \nor Below', 'College', 'Bachelor'... | pandas|matplotlib | 1 |
17,931 | 63,096,468 | Writing to CSV with python pandas module: Extra column is being added | <p>I'm trying to get a dataset of numbers to train an AI to predict that the output should be the input + 1.
I'm using the pandas module to write to a .csv file. The dictionary: numbers is generated fine I think. However, when exporting to the csv, an extra column is added. Does anyone know how to get around this?</p>
... | <p>I guess you are getting one more index, if that's the case</p>
<p>Use <code>index=False</code></p>
<pre><code>df.to_csv('numbers.csv', index=False)
</code></pre> | python|pandas|csv | 1 |
17,932 | 63,171,917 | Pandas Dataframe Reshape with Multiple Index | <p>Working to understand reshape functions in Pandas. So far I can work with a reshape on a dataframe with a simple structure such as</p>
<pre><code>d = {'id1': [1,1,1,2,2,2], 'id2': [1,1,1,1,1,1], 'value': [1,2,3,4,5,6], 'type':['A','B','C','A','B','C']}
tab = pd.DataFrame(data=d)
tab.pivot(index = 'id1', column... | <p>It appears as though a simpler option is to use <code>pivot_table</code> function in pandas:</p>
<pre><code>d = {'id1': [1,1,1,1,1,1,2,2,2], 'id2': [1,1,1,2,2,2,1,1,1], 'value': [1,2,3,4,5,6,7,8,9], 'type':['A','B','C','A','B','C','A','B','C']}
tab4 = pd.DataFrame(data=d)
tab4.pivot_table(
values='value',
... | python|pandas | 2 |
17,933 | 63,221,798 | TensorFlow: Number of elements was larger than representable by 32-bit output type | <p>For a large tensor shape such as (72, 7007313, 5) and using a large network such as this:</p>
<pre><code>import keras
import numpy as np
from keras.optimizers import Adam
from keras.models import Sequential
from keras.layers import Dense, Flatten
Y = np.random.randint(low=0, high=1, dtype=np.int16, size=(72, 2))
X ... | <pre class="lang-cc prettyprint-override"><code>OP_REQUIRES(
ctx, FastBoundsCheck(size, std::numeric_limits<int32>::max()),
errors::InvalidArgument("Number of elements was larger than "
"representable by 32-bit output type"));
</code></pre>... | python|tensorflow|deep-learning|neural-network|tensorflow2.0 | 2 |
17,934 | 67,781,920 | Create a ranking of data based on the dates and categories of another column | <p>I have the following dataframe:</p>
<pre><code> account_id contract_id type date activated
0 1 AAA Downgrade 2021-01-05
1 1 ADS Original 2020-12-12
2 1 ADGD Upgrade 2021-02-03
3 1 BB Winback 2021-05-08
4 1 CC Upgrade 2021-06-01
5 2 HHA Original 2021-03-05
6 2 HAKD Downg... | <p>Let us just change the <code>cumcount</code> result</p>
<pre><code>s = df.groupby('account_id').cumcount()
s[df.type=='Winback'] = 0
df['Renewal Order'] = s.apply(format_order)
</code></pre> | python|pandas|dataframe | 2 |
17,935 | 61,216,066 | Compare spans in a list and return a label if similar | <p>I want to build a list of labels to match the words in a sentence</p>
<pre><code>sentence="I am a healthy boy who lives in Florida"
subject= "I am a healthy boy"
</code></pre>
<p>first I split:</p>
<pre><code>sen = sentence.split(" ")
subj = subject.split(" ")
</code></pre>
<p>then I try to iterate.</p>
<pre><c... | <p>It can be done quite easily using regular expressions. </p>
<pre><code>sentence="I am a healthy boy who lives in Florida"
subject= "I am a healthy boy"
</code></pre>
<h1>Build the expression</h1>
<pre><code>abc = '({})'.format('|'.join(re.escape(y) for y in sorted(subject, key=len, reverse=True)))
</code></pre>
... | python|pandas|data-structures|nlp|itertools | 0 |
17,936 | 61,341,213 | Adding rows to a column for every element in the list for every unique value in another column in python pandas | <p>I have two lists of unequal length:</p>
<pre><code>Name = ['Tom', 'Jack', 'Nick', 'Juli', 'Harry']
bId= list(range(0,3))
</code></pre>
<p>I want to build a data frame that would look like below:</p>
<pre><code>'Name' 'bId'
Tom 0
Tom 1
Tom 2
Jack 0
Jack 1
Jack 2
Nick 0
Nick 1
Nick 2
Juli 0
Juli 1
JU... | <p>Use <a href="https://docs.python.org/3.8/library/itertools.html#itertools.product" rel="nofollow noreferrer"><code>itertools.product</code></a> with DataFrame constructor:</p>
<pre><code>from itertools import product
df = pd.DataFrame(product(Name, bId), columns=['Name','bId'])
print (df)
Name bId
0 Tom... | python|pandas|dataframe | 1 |
17,937 | 61,393,417 | python change 3d array from MxNxN into NxNxM | <p>Hello, I want to ask a question about how to change the dimension order(?). </p>
<p>I have 75x120x120 (AxBxC) ( I am trying to save the array to .mat file), and I want to make it as 120x120x75 (BxCxA). </p>
<p>Please kindly give me a suggestion on this problem. </p>
<p>Thank you. </p> | <p>Use can use reshape function for the same...
For simplicity,I took the dimensions to be smaller but surely it will serve the purpose </p>
<pre><code>arr = np.array([[[1,2,3],[4,5,6],[7,8,9]],[[9,8,7],[6,5,4],[3,2,1]]])
arr.shape
>> (2,3,3)
arr = np.reshape(arr,(3,3,2))
arr.shape
>> (3,3,2)
</code></pre... | python|multidimensional-array|3d|numpy-ndarray | 1 |
17,938 | 68,718,086 | How do you create a pivot table with a limited number of new columns using pandas? | <p>I have this dataframe for example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>emp_id</th>
<th>label</th>
</tr>
</thead>
<tbody>
<tr>
<td>a1</td>
<td>101</td>
</tr>
<tr>
<td>a1</td>
<td>102</td>
</tr>
<tr>
<td>a1</td>
<td>103</td>
</tr>
<tr>
<td>a1</td>
<td>104</td>
</tr>
<tr>
<td>a2... | <p>Similar approach, we can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby cumcount</code></a> to enumerate <code>emp_id</code>, and use a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/panda... | python|pandas|dataframe|pivot-table | 0 |
17,939 | 53,182,464 | Pandas delete a row in a dataframe based on a value | <p>I want do delete rows in a pandas dataframe where a the second column = 0</p>
<p>So this ...</p>
<pre><code> Code Int
0 A 0
1 A 1
2 B 1
</code></pre>
<p>Would turn into this ...</p>
<pre><code> Code Int
0 A 1
1 B 1
</code></pre>
<p>Any help greatly appreciated!</p> | <p>Find the row you want to delete, and use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="noreferrer">drop</a>.</p>
<pre><code>delete_row = df[df["Int"]==0].index
df = df.drop(delete_row)
print(df)
Code Int
1 A 1
2 B 1
</code></pre>
<p>Further more. you ca... | python|pandas | 11 |
17,940 | 63,674,466 | how to add multiple rows in a specified position with modification in python? | <p>I have a data frame where I want to replicate and rows in the following manner</p>
<pre><code> d=pd.DataFrame({"col1":["a","b","c","d"],
"col2":[12,13,14,16]})
</code></pre>
<p>required output:
want to copy rows a1, a2, b1, b2</p>
<pre><code... | <p>IIUC, You can try <code>index.repeat</code> with <code>groupby+cumcount</code></p>
<pre><code>n = 3
out = d.loc[d.index.repeat(n)]
out = out.assign(col1=out['col1']+out.groupby("col1").cumcount()
.replace(0,'').astype(str)).reset_index(drop=True)
</code></pre>
<hr />
<pre><code>print(out)... | python|python-3.x|pandas | 3 |
17,941 | 72,041,369 | How can I use pandas to reformat the table flexibly like using dplyr group_by and do | <p>How can I reshape a data frame by group and add the next step in a group to a new column.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'id': ['A', 'A', 'A', 'B', 'B', 'B', 'C'],
'step': [1,2,3,1,3,4,1]
})
print(df)
id step
0 A 1
1 A 2
2 A 3
3 B 1
4 B 3
5 B 4
6 C ... | <p>With <a href="https://github.com/pwwang/datar" rel="nofollow noreferrer"><code>datar</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>>>> import pandas as pd
>>> from datar.all import f, group_by, summarise, lead
>>>
>>> df = pd.DataFrame({
... 'id': ['A', 'A',... | pandas | 1 |
17,942 | 71,910,745 | Using pandas, how do i loc a value where my column contains lists? | <p>I have a df, with a column that contains a list.
for example -</p>
<pre><code>df = pd.DataFrame({'name': ['name1', 'name2', 'name3', 'name4'],
'age': [21, 23, 24, 28],
'occupation': ['data scientist', 'doctor', 'data analyst', 'engineer'],
'knowledge':[['pyt... | <p>You need to use a loop:</p>
<pre><code>df[['python' in l for l in df['knowledge']]]
</code></pre>
<p>output:</p>
<pre><code> name age occupation knowledge
0 name1 21 data scientist [python, c++]
1 name2 23 doctor [python, c#]
</code></pre>
<h4>alternatives</h4>
<h5>finding any elemen... | python|pandas|list|dataframe|filter | 4 |
17,943 | 72,011,114 | ValueError: Shapes (None, None) and (None, 28, 28, 10) are incompatible | <p>I am working on a neural network to recognize handwritten digits using the MNIST digits dataset. I wanted to use ImageDataGenerator from Keras to see if I could use that to increase the score of the predictions. But when I actually try to run the model I get this error: ValueError: Shapes (None, None) and (None, 28,... | <p>You should convert your labels to one-hot encoded labels if you want to use <code>categorical_crossentropy</code>. Also, use a <code>Flatten</code> layer in the beginning of your model. Here is a working example:</p>
<pre><code>import tensorflow as tf
import numpy as np
datagen = tf.keras.preprocessing.image.ImageD... | python|tensorflow|keras | 1 |
17,944 | 55,449,747 | Convert column of epoch timestamps to datetime with timezone | <p>I have a dataframe in my Jupyter notebook with a column of epoch timestamps, it looks like this: </p>
<pre><code> Name stop ts remark
A 01 1546470653 -
B 032 1546470969 Not listed
C 022 1546471069 Not listed
D 045 1546471238 Not lis... | <p>Use <code>pd.to_datetime</code> with <code>unit='s'</code>. You can then set the timezone using the <code>tz_*</code> methods.</p>
<pre><code>df['timestamp'] = (pd.to_datetime(df['ts'], unit='s')
.dt.tz_localize('utc')
.dt.tz_convert('Asia/Hong_Kong'))
df
Name stop ... | python|pandas|datetime|timestamp|epoch | 10 |
17,945 | 55,304,386 | Getting a column from dataframe to write it in csv file | <p>I'm working on a pandas dataframe that contains 3 columns named : drugName, review and rating.
I'm trying to get the review according to its rate, if it is higher or equal to 6, so it is a positive review that I must write it in a csv file. Here is my code :</p>
<pre><code>import csv
import pandas as pd
filename ="... | <p>Change the end of your code to the following:</p>
<pre><code>df.loc[df['rating'][i] >= 6, 'review'].to_csv("C:\\Users\\rev_pos.csv",encoding='utf8')
</code></pre>
<p>This code filters the 'review' column by the 'rating' and then saves the result to a CSV all at once.</p> | python|pandas|csv|dataframe | 1 |
17,946 | 56,668,301 | python, qtreewidgetitem, numpy matrix and image widget | <p>I would like to create a json file viewer in order to iterate through the key/values of the file. For that I decided to go with a qtreewidgetitem where in the first column I would have the key, in the second column the value and in a third column I would like actually to display the values of an numpy array as an im... | <p>I managed to solve my problem by using the pyqtgraph external library and creating the following widget structure: </p>
<pre><code># Tree
self.tree_widget = QtWidgets.QTreeWidget()
self.tree_widget.setHeaderLabels(["Key", "Value", "Image"])
root_item = QtWidgets.QTreeWidgetItem(["Test Item"])
self.tree_widget.add... | python|arrays|image|numpy | 0 |
17,947 | 67,051,359 | Problem with pandas pivot_table Margin=True not giving me the correct answers | <p><code>pd.pivot_table(subset_one,index=["Institution_Types"],values=["Current_Balance"],aggfunc=([len, np.mean, max, min]),\ margins=True, margins_name='Total').reset_index()\ .rename(columns={'len': 'Loan Count', 'mean':'Average', 'max':'Max','min':'Min'})</code></p>
<p>The total column is not gi... | <p>Alternatively, you could try to do you pivot table with <code>Margin=False</code> and add afterwards a line <em>Total</em> like this:</p>
<pre class="lang-py prettyprint-override"><code>pd.pivot_table(
subset_one,
index=["Institution_Types"],
values=["Current_Balance"],
aggfunc=([... | python|pandas | 0 |
17,948 | 68,276,636 | Python/Numpy: Reduce two boolean arrays based on conditionals relating to both arrays | <p>I have two boolean Numpy arrays of boolean indicators:</p>
<pre><code> v v v
A = np.array([0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1], dtype=bool)
B = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1], dtype=bool)
... | <p>This can barely be done efficiently with Numpy (probably not possible efficiently without loops), but easily and efficiently with the <strong>Numba's JIT</strong>. This is mainly due to the rather sequential nature of the applied operation.</p>
<p>Here is an example in Numba:</p>
<pre class="lang-py prettyprint-over... | python|arrays|numpy|masking | 1 |
17,949 | 57,008,147 | Average every four two dimensional numpy arrays python | <p>If I have a numpy array like this (8 two dimensional sub arrays): </p>
<pre><code> array([[[1, 1, 1],
[1, 1, 1]],
[[2, 2, 2],
[2, 2, 2]],
[[1, 1, 1],
[1, 1, 1]],
[[2, 2, 2],
[2, 2, 2]],
[[3, 3, 3],
[3, 3, 3]],
[[4, 4,... | <p>Split the first axis into two with the length of the second one being <code>4</code> resulting in <code>n+1-dim</code> array and then get average along that one -</p>
<pre><code># a is the input array
In [42]: a.reshape((-1,4)+a.shape[1:]).mean(1)
Out[42]:
array([[[1.5, 1.5, 1.5],
[1.5, 1.5, 1.5]],
... | python|python-2.7|numpy | 1 |
17,950 | 57,046,646 | How to create a date difference value based on conditional logic in a dataframe? | <p>I'm trying to create a numeric field in a dataframe based on boolean logic. How do I check and format the values of date columns to result in a numeric value?</p>
<p>There is a sold date and a cancel date, both loaded as string/objects. There is also a "Churn" column that has a 1 if the user has canceled, 0 if they... | <p>you should use the inbulit <code>to_datetime</code> function from pandas. It will directly parse a Pandas Series object to datetime, you don't really need your <code>days_between</code> function, you can just <code>df.loc</code> to get the rows and simply subtract.</p> | python|pandas|dataframe | 0 |
17,951 | 57,052,950 | Why sess.run(tf.assign) take longer time to execute after each epoch? | <p>I wrote a function to update trainable variables after each epoch by tf.assign() function with new value is numpy array and shape of trainable variables do not change after each epoch. But when epoch increase, time to run this code increase too although number and shape of trainable variables is the same. Is there a... | <p>If you run that code multiple times, then you will be creating more and more replicated ops in the graph, which will slow things down. Instead, create the assignment ops only once:</p>
<pre><code>assignment_ops = []
for i, v in enumerate(tf.trainable_variables()):
v_tensor = graph.get_tensor_by_name(v.name)
... | python|numpy|tensorflow | 0 |
17,952 | 45,725,642 | tf.nn.conv2d_transpose output_shape for FCN | <p>I want to implement deconvolution layer in tensorflow for FCN model, I used tf.nn.conv2d_transpose for each of 5 conv outputs, what I need is that the output shape of each of the 5 deconv to be the same as the input image shape. So I set </p>
<pre><code>deconv_shape = tf.shape(input)
tf.nn.conv2d_transpose(value=de... | <p>I think your implementation isn't correct, here's the few step to get it right.</p>
<pre><code>in_channels = input.shape[-1]
# here set the output_height, width as [stride*input_height, stride*input_width]]
output_shape = [batch_size, output_height, output_width, out_channels]
filter_size =2 # for example
stride =... | tensorflow | -1 |
17,953 | 46,080,421 | Tensorflow, printing loss function causes error without feed_dictionary | <p>I am just reading Tensorflow documentation. In following code, I just changed last line. I pushed last line in iteration, to see what exactly is going on...</p>
<pre><code>import tensorflow as tf
# linear_model = W*x+B
W = tf.Variable(.3, dtype=tf.float32)
B = tf.Variable(-3., dtype=tf.float32)
x = tf.placeholder... | <p>If you print out <code>loss</code>, you'll see that it's a Tensor, not a variable. This is because TensorFlow defines a computation graph, then executes it when you call <code>sess.run</code>, it doesn't perform sequential execution like python. </p>
<p>You can think of <code>loss</code> as a function of x and y to... | python|tensorflow | 2 |
17,954 | 66,467,386 | Unusual reshape of numpy array | <p>I am trying to render geophysics section with <strong>contourf</strong> map in <strong>matplotlib</strong>.
I almost get desired result with only one exception, it renders from the bottom left corner.
<a href="https://i.stack.imgur.com/bwWpg.png" rel="nofollow noreferrer">Rendered geophysics section</a></p>
<p>As it... | <p>If the data D is a numpy 2D array,</p>
<pre><code>D = D.T
</code></pre>
<p>a simple transpose will achieve that.</p> | python|numpy|matplotlib|contourf | 1 |
17,955 | 66,407,539 | low VGG16 validation accuracy on biased dataset | <p>i am new to machine learning i have a retinal image dataset of about 35K images from different 5 labels.<a href="https://i.stack.imgur.com/I5TeL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I5TeL.png" alt="its biased dataset the no. of images for train,test and validations are:
Total number of... | <p>Imbalanced data sets are a common problem. For example in your case if your model just predicts level 0 it will be right 20000/35000 percent of the time. There are a number of ways to deal with the problem. Most obvious of course is to find more samples for the under represented classes. Unfortunately that is often ... | python|tensorflow|machine-learning | 0 |
17,956 | 66,562,744 | Is there a way to use Openpyxl and Seaborn together? (Python) | <p>I have several small datasets within an excel worksheet. I would like to create small graphs beside each dataset.</p>
<p>Here is my worksheet:</p>
<p><a href="https://i.stack.imgur.com/Z6rYr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z6rYr.png" alt="enter image description here" /></a></p>
<p... | <p>While this should be possible to do this with Seaborn plots – you need to save them as images and then add them, but as long as you can live with the charts that Excel produces, it would probably be easiert to do this.</p> | python|pandas|plotly|seaborn|openpyxl | 1 |
17,957 | 57,633,850 | fail to submit job to f1-micro with gcloud ml-engine (or ai-platform) command in jupyter notebook | <p>I am trying to submit a google cloud job that trains cnn model for mnist digit. since I am new to gcp, I want to train this job on f1-micro machines first for practice. but not successful. I have two issues along the way.</p>
<p>here's my systems. windows 10, anaconda, jupyter notebook 6, python 3.6, tf 1.13.0.
a... | <p>f1-micro is not supported by AI Platform Training.
<a href="https://cloud.google.com/ml-engine/docs/machine-types#compute-engine-machine-types" rel="nofollow noreferrer">Here</a> is the list of supported machines. Also you don't need to specify zone. just the machine type. I.e., --master-machine-type=n1-standard-4</... | python|tensorflow|google-cloud-platform|jupyter-notebook|google-cloud-ml | 0 |
17,958 | 57,396,709 | how to create a google calc file with pandas dataframe on each sheet | <p>I am trying to use the google sheet api to create a file containing on each sheet a dataframe. </p>
<p>The code is failing and I do not know how to fix it. </p>
<pre><code>import pandas as pd
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from gspread_dataframe... | <ul>
<li>You want to create new Spreadsheet and put the values of dataframe.</li>
<li>You want to achieve this using google-api-python-client with Python.</li>
<li>You have already been able to put and get values for Spreadsheet.</li>
</ul>
<p>If my understanding is correct, how about this modification? I think that t... | python|pandas|google-sheets | 0 |
17,959 | 73,000,553 | Reading a json object as a single row pandas df | <p>I have a json object of the following format</p>
<pre><code>{
"ABC": 123,
"DATE": "2020-01-01",
"AMOUNT": 100,
"IDENTIFIER": 12345
}
</code></pre>
<p>I want to read this into pandas as a single row df. So the output should look like</p>
<pre><code>ABC DATE... | <p>I am not sure if I understand you well
as I understood you need to convert JSON object like this</p>
<pre><code>{
"ABC": 123,
"DATE": "2020-01-01",
"AMOUNT": 100,
"IDENTIFIER": 12345
}
</code></pre>
<p>to dataframe, you can read the file and then pass the re... | json|pandas | 1 |
17,960 | 73,172,512 | categorize data into N categories where each category has the same number of data but different interval | <p>I have a series of stock returns, could be approximate 5000 data. I want to categorize them into 5 categories. Each categories should have almost the same number of data.</p>
<p>for example, categorize following data into 3 categories:</p>
<pre><code>test = pd.DataFrame({'Returns': [0.003,0.005,0.02,0.01,0.1,0.9,-0.... | <p>Try with <code>qcut</code></p>
<pre><code>test['cate'] = pd.qcut(test.Returns,3).cat.codes
test['cate'].value_counts()
Out[577]:
0 4
1 4
2 4
Name: cate, dtype: int64
</code></pre> | python|pandas | 1 |
17,961 | 51,460,868 | Numpy: Can you use broadcasting to replace values by row? | <p>I have a M x N matrix X and a 1 x N matrix Y. What I would like to do is replace any 0-entry in X with the appropriate value from Y based on its column.</p>
<p>So if </p>
<pre><code>X = np.array([[0, 1, 2], [3, 0, 5]])
</code></pre>
<p>and </p>
<pre><code>Y = np.array([10, 20, 30])
</code></pre>
<p>The desired ... | <p>Sure. Instead of physically repeating <code>Y</code>, create a broadcasted view of <code>Y</code> with the shape of <code>X</code>, using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html" rel="nofollow noreferrer"><code>numpy.broadcast_to</code></a>:</p>
<pre><code>expanded = nu... | python|numpy|array-broadcasting | 1 |
17,962 | 51,238,926 | Deploying model | <p>I just finished training a categorizer model exactly the way described in <a href="https://github.com/GoogleCloudPlatform/MiniCat" rel="nofollow noreferrer">https://github.com/GoogleCloudPlatform/MiniCat</a> but I am not sure how to use the model to make predictions.</p>
<p><a href="https://i.stack.imgur.com/UTxuA.... | <p>So in the folder where you got the trained model, you just need to load that model in your session. First create a saver (you can also use it for laoding)</p>
<pre><code>train_saver = tf.train.Saver()
</code></pre>
<p>Now inside your session:</p>
<pre><code>train_saver.restore(sess, 'path/to/model/doc_classifier_... | tensorflow|google-cloud-platform | 1 |
17,963 | 51,325,444 | Pandas groupby find common strings | <p>My Dataframe:</p>
<pre><code> Name fav_fruit
0 justin apple
1 bieber justin apple
2 Kris Justin bieber apple
3 Kim Lee orange
4 lee kim orange
5 mary barnet orange
6 tom hawkins pears
7 Sr Tom Hawkins pears
8 Jose Haw... | <p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> with custom function - first create one big string of joined values, convert to lowercase and split, last use <a href="https://docs.python.org/3... | python|pandas|pandas-groupby | 1 |
17,964 | 51,231,576 | TensorFlow/Keras - expected global_average_pooling2d_1_input to have shape (1, 1, 2048) but got array with shape (7, 7, 2048) | <p>I'm fairly new to TensorFlow and Image Classification, so I may be missing key knowledge and is probably why I'm facing this issue.</p>
<p>I've built a <code>ResNet50</code> model in TensorFlow for the purpose of image classification of Dog Breeds using the <code>ImageNet</code> library and I have successfully trai... | <p>Thanks to <a href="https://stackoverflow.com/users/2891324/nessuno" title="nessuno">nessuno</a>'s assistance, I figured out the issue. The problem was indeed with the <code>pooling</code> layer of <code>ResNet50</code>.</p>
<p>The following code in my script above:</p>
<pre><code>return ResNet50(weights='imagenet'... | python|tensorflow|keras|resnet|imagenet | 4 |
17,965 | 70,846,083 | pandas.Dataframe.loc() and pandas.Dataframe.drop() not working | <p>I am using pandas to create a ranklist. I created a csv file and used pandas to create a Dataframe. When I am slicing the dataframe using iloc method, its working fine, but its showing error with loc method. Similar error is also shown with drop method. When I am dropping the first column "Name", it works ... | <p>Get column names by <code>file1.columns</code>. Copy and use these column names. Your column names probably have whitespaces in the beginning or in the end.</p> | python|pandas|dataframe | 0 |
17,966 | 70,880,874 | matplotlib custom path markers not displaying correctly | <p>just wondering if anybody has experience with matplotlib custom markers</p>
<p>I want each marker in my plot to be a pie chart. To achieve this, my strategy was to create custom markers using the path class, method wedge.</p>
<p><a href="https://matplotlib.org/stable/api/path_api.html" rel="nofollow noreferrer">http... | <p>I managed to get the pie charts to display correctly.</p>
<p>Scaling by doing affine transforms does not help because the path markaers are all resized, as in
<a href="https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/markers.py#L495" rel="nofollow noreferrer">line 495 of markers.py</a> .</p>
<pre><c... | python|numpy|matplotlib|math | 0 |
17,967 | 51,565,978 | Converting a column of minutes to hours and minutes in Python | <p>I have a DataFrame in Pandas with a column called "duration" given in minutes.</p>
<p>I want to get a new column that gives the duration in Hours:Minutes ( <code>HH:MM</code> ).</p> | <p>Assuming your DataFrame looks like this:</p>
<pre><code>df = pd.DataFrame({'duration': [20, 10, 80, 120, 30, 190]})
</code></pre>
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><strong><code>pd.to_datetime</code></strong></a> with <strong><code>st... | python|pandas|time-series | 8 |
17,968 | 35,852,050 | merging multiple columns in a dataframe | <p>I have data frame like this one:</p>
<pre><code>dataf = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'], 'C': ['c', 'c',np.nan]})
get_dummies(df):
A_a A_b B_a B_b B_c C_c
0 1 0 0 1 0 1
1 0 1 1 0 0 1
2 1 0 0 ... | <p>You can add parameters <code>prefix</code> and <code>prefix_sep</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow noreferrer"><code>get_dummies</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.htm... | python-3.x|pandas | 0 |
17,969 | 36,151,040 | Create array from dict | <p>I have some words in a dictionary and according to these and some sentences I want to create a specific array.</p>
<pre><code>words = {'a': array([ 1.78505888, -0.40040435, -0.2555062 ]), 'c': array([ 0.58101204, -0.23254054, -0.5700197 ]), 'b': array([ 1.17213122, 0.38232652, -0.78477569]), 'd': array([-0.0754501... | <p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> to establish correspondence between the string keys of <code>words</code> and the strings in each element of <code>sentences</code>. Repeat this process for all ele... | python|numpy|list-comprehension | 2 |
17,970 | 37,284,395 | Bitfusion Ubuntu 14 TensorFlow AMI fails with OOM Errors | <p>Using the <a href="https://aws.amazon.com/marketplace/pp/B01EYKBEQ0?ref=cns_srchrow" rel="nofollow">"Bitfusion Ubuntu 14 TensorFlow" AMI</a>, any attempt to preform operations with large Tensors, such as</p>
<pre><code>sess.run(tf.argmax(y, 1), feed_dict={x: use_x})
</code></pre>
<p>when <code>use_x</code> is a 28... | <p>The problem is the memory limit on the AWS GPUs ~ 4GB, it is not a problem with the AMI:</p>
<pre><code>Limit: 3928915968
InUse: 3903864320
MaxInUse: 3903864320
NumAllocs: 418794
MaxAllocSize: 3703905024
</code></pre>
<p>The memory limi... | amazon-web-services|machine-learning|gpu|tensorflow|amazon-ami | 1 |
17,971 | 38,002,357 | What is the suggested practice for storing multiple runs of a summary writer in TensorFlow? | <p>I am learning to use TensorBoard and every time I launch tensorboard I get in my terminal the message:</p>
<pre><code>WARNING:tensorflow:Found more than one graph event per run. Overwriting the graph with the newest event.
</code></pre>
<p>I assume is because I've run the same model multiple times with the same na... | <p>When you export the model in your graph tensorflow creates a new file with the log information. So every time you run it the new information is added in the same folder. </p>
<p>As tensorboard cannot differenciate one model from other it shows the warning. So yes, you should use a different log folder per iteration... | machine-learning|neural-network|tensorflow|conv-neural-network|tensorboard | 5 |
17,972 | 38,020,396 | Convert column of timestamp with a different UTC base to current UTC using Python | <p>I have a dataframe with timestamps that are number of seconds since Jan 1,2010 midnight UTC time zone. I need to convert them to the present UTC time. I am able to do that for a given row using timedelta but not able to implement that for the entire timestamp column.</p>
<pre><code> # The base of my timestamp is... | <p>try this:</p>
<pre><code>dif = (datetime.datetime(2010,1,1) - datetime.datetime(1970,1,1)).total_seconds()
sec_shift = 4*60*60
pd.to_datetime(df.timestamp + diff + sec_shift, unit='s')
</code></pre>
<p>demo:</p>
<pre><code>In [29]: pd.to_datetime(df.timestamp + dif + sec_shift, unit='s')
Out[29]:
0 2016-05-25 1... | python|pandas|dataframe | 4 |
17,973 | 37,974,068 | find next row in DataFrame based on column values | <p>I have a DataFrame with a non-unique sorted datetime index where I need to find the next row after a specific match on some columns of data.</p>
<p>I can find the correct row with DataFrame.query() which gives me a new DataFrame, but I don't know how I can locate where this row is in the original DataFrame. Here is... | <p>Does this work? Just reset the index, and identified the index of the row you're after </p>
<pre><code>df = pd.DataFrame(index=ts_index, data={'BID_PRICE': bid_price,
'BID_QTY': bid_qty, 'ASK_PRICE': ask_price, 'ASK_QTY': ask_qty})
df.reset_index(inplace = True)
most_recent_match = df.query('(BID_PRICE == 77... | python|numpy|pandas | 2 |
17,974 | 37,897,737 | Set of matrices | <p>I have lots of matrices (as result of rotations, etc.), but I would be sure to store them only once. I thought about <em>using a set</em> :</p>
<pre><code>print set([np.matrix([[0, 0],[0, 1],[1, 1],[2, 1]]),
np.matrix([[0, 0],[1, 0],[1, -1],[1, -2]])])
</code></pre>
<p>Unfortunately, I get :</p>
<blockquote>
... | <pre><code>In [299]: m1
Out[299]:
matrix([[0, 0],
[0, 1],
[1, 1],
[2, 1]])
In [300]: m2
Out[300]:
matrix([[ 0, 0],
[ 1, 0],
[ 1, -1],
[ 1, -2]])
In [297]: set([tuple(m1.A1),tuple(m2.A1)])
Out[297]: {(0, 0, 0, 1, 1, 1, 2, 1), (0, 0, 1, 0, 1, -1, 1, -2)}
</code></pre>... | python|numpy|matrix | 0 |
17,975 | 31,490,600 | Python: standard deviation of gaussian weighted pixel region | <p>I would like to calculate a Gaussian weighted standard deviation of a 2D array with Python, does anyone know how to do this? So basically apply a 2D Gaussian filter but instead of returning the convolution of each array element with the filter, I would like it to return the standard deviation of the Gaussian weighte... | <p>There is a numpy function called std. Example</p>
<pre><code> x = np.random.uniform(0,5,(20,20))
np.std(x)
</code></pre>
<p>And this will return the standard deviation of the 20x20 array. If you want a specific portion of the image you can use array splicing to accomplish this.</p> | python|numpy | 1 |
17,976 | 64,287,044 | Pandas Get Sequence of 1s and 0s Given Strings | <p>Given the following:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a':['K','1','1,2,3']})
df
a
0 K
1 1
2 1,2,3
</code></pre>
<p>I would like to convert the values in column a to a corresponding sequence of 1s and 0s given this map:</p>
<pre><code>K 1 2 3 4 5
1 1 1 1 1 1
</code></pre>
<p>If... | <p>Let us try <code>get_dummies</code> then <code>reindex</code></p>
<pre><code>s = df.a.str.get_dummies(',').reindex(columns=['K','1','2','3','4','5'],fill_value=0).astype(str).agg(''.join,1)
0 100000
1 010000
2 011100
dtype: object
df['b'] = s
</code></pre> | python|pandas | 1 |
17,977 | 64,491,443 | Dataframe row of JSON list for training ML with scikit | <p>I'm trying to do multivariate classification with <a href="https://github.com/alan-turing-institute/sktime" rel="nofollow noreferrer">Sktime</a> over a set of JSON files organized as experiments.</p>
<p>The input is the following structure:</p>
<pre class="lang-json prettyprint-override"><code>[
{ v: 431, t: 2, d1... | <p>It turned out I was looking for nesting ndarray in a DataFrame as the following:</p>
<pre class="lang-py prettyprint-override"><code> experiments = pd.DataFrame(['exp'])
for file in files:
tmp = pd.read_json(file).to_numpy()
experiments = experiments.append({'exp': tmp}, ignore_index=True)
</c... | python|pandas|numpy|scikit-learn|sktime | 0 |
17,978 | 64,255,533 | Is it possible to mask NaN values in keras LSTM's Label-set? | <p>I have an LSTM Dataset. Some labels contain NaNs at the end, which cant be backward filled (because theres no values after them) and foreward-filling them would make no sense (since the labels timestamp will be deprecated in a 'nearer future'-timestamp (=missing value locatoin) compared to its acutal timeindex)</p>
... | <p>You can accomplish data masking via a Keras Masking layer:<a href="https://keras.io/api/layers/core_layers/masking/" rel="nofollow noreferrer">https://keras.io/api/layers/core_layers/masking/</a>.</p>
<p>Layers that following the masking layer <em>and support masking</em> (the LSTM layer does) will skip samples / st... | python|tensorflow|machine-learning|keras|lstm | 0 |
17,979 | 47,613,582 | convert epoch to datetime format python - typeerror | <p>I have a dataframe with 2 columns - some values and Time. Timestamp is in epoch time format and I am trying to transform using the strftime function from time library in python. </p>
<p>Here's some sample data </p>
<pre><code>df = [{'A': 762, 'Time': 1512255906},
{'A': 810, 'Time': 1480719906}]
</code></pre>... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>pandas.DataFrame.apply</code></a>:</p>
<pre><code>>>> import pandas as pd
>>> import time
>>> df = pd.DataFrame([{'A': 762, 'Time': 1512255906},
... | python|python-3.x|pandas|typeerror|python-datetime | 2 |
17,980 | 58,763,194 | compare the two lists in python and check they equality on some conditions | <p>I am new to the python and pandas . Here I have the following dataframe which has two lists .</p>
<pre><code>Test Test1
[1,1,1] [1,2,2]
[1,2,2] [1,0,1]
[1,0,0] [1,1,1]
[2,2,2] [0,0,2]
</code></pre>
<p>In this datframe I am trying while compairing the two lists .There... | <p>What about the following</p>
<pre class="lang-py prettyprint-override"><code>def compare(a, b):
# Ensure there are two zeros on either side
if a.count(0) == 2 or b.count(0) == 2:
# Compute the intersection and ensure it's not zero
return len(set(a).intersection(b)) is not 0
return False
... | python|python-3.x|pandas|numpy | 0 |
17,981 | 70,140,778 | How to rewrite this code to use a "for" loop | <p>I guess this code can write in for loop, but I have no idea how to do it?
Thanks a lot!</p>
<pre><code>worksheet1=pd.read_excel(xls,"sheet2",usecols=feature1)
worksheet2=pd.read_excel(xls,"sheet2",usecols=feature2)
worksheet3=pd.read_excel(xls,"sheet2",usecols=feature3)
worksheet4=pd.re... | <p>Try</p>
<pre><code>featuresList = [feature1,feature2,feature3,feature4,feature5,feature6]
worksheets = [pd.read_excel(xls,"sheet2",usecols=feat) for feat in featureList]
</code></pre>
<p>then you can call to <code>worksheets[1]</code> wich is worksheet2 and so (one index displacement)</p>
<hr />
<p><stro... | python|excel|pandas | 3 |
17,982 | 70,225,514 | Pandas - check for string matches in different columns with column values being comma separated | <p>Hi I have a df like the following:</p>
<pre><code>Col1 Col2
SM_ SM_
SM_ N_
EX_,SM_ EX_,CO_
SL_,N_ PD_,SL_
</code></pre>
<p>I want to compare both columns, and see if a value in Col1 is present in Col2 or not. Multiple values in both columns are comma separated. So, ideally the r... | <p>You could use a function that for each cell constructs a set of the comma-separated values and returns whether the intersection of those sets in a row is not empty:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
def columns_overlap(row):
sets = [set(s.split(',')) for s in row]
inter... | pandas|dataframe | 3 |
17,983 | 56,244,446 | geopandas assign to geometry | <p>I have a geopandas GeoDataframe representing the continental US states. I want to transform all the coordinates to a different coordinate system with non-trivial mapping.</p>
<p>My plan was to do something like (this is just a simple test, not the real transform):</p>
<pre><code>from shapely.ops import transform
... | <p>This code works:</p>
<pre><code>from shapely.ops import transform
def touv (x, y):
if type(x) is not float:
raise TypeError
return ll2UV (satlat, satlon, BSlat, BSlon, y, x)
for row in conus.index:
conus.at[row,'geometry'] = transform (touv, conus.loc[row,'geometry'])
</code></pre>
<p>The key,... | python|pandas|geopandas|shapely | 1 |
17,984 | 56,190,112 | installing geopandas with conda, can't find dependencies libgcc-ng | <p>I am trying to install geopandas with conda.</p>
<p>I have created a fresh environment</p>
<pre><code>conda create --name gp python=2
</code></pre>
<p>Then tried to install geopandas</p>
<pre><code>conda install geopandas
</code></pre>
<p>Which returns </p>
<blockquote>
<p>Error: Could not find some depende... | <p>If the point of the new env is to have <code>geopandas</code> in it, then let Conda know that right from the start and it can solve the dependencies upfront:</p>
<pre><code>conda create -n gp python=2 geopandas
</code></pre>
<p>However, as @martinfleis points out, you may still have channel priority issues. Testin... | python|conda|geopandas | 1 |
17,985 | 55,967,321 | Get MS Excel Properties, Python 3.6 | <p>I want to find "Last Modified" Date from Excel File.</p>
<p>Script </p>
<pre><code>os.stat(Excel_File_Path).st_ctime
</code></pre>
<p>gives locally created time, but I want to fetch Excel File "Last Modified", which is available in Excel Properties, I use Excel 2013, here if I select "File" it will show Excel Pro... | <p>You can get the modified time by using
<code>import os</code>
<code>os.path.getmtime(path_to_file)</code></p>
<p>More details <a href="https://docs.python.org/3/library/os.path.html#os.path.getmtime" rel="nofollow noreferrer">here.</a></p> | python|excel|python-3.x|pandas | 1 |
17,986 | 55,657,082 | Multithread prange loop throws "double free or corruption (fasttop)" error | <p>I made a few changes to the original question. Turns out the <strong>malloc</strong> part is actually probably the issue, as suggested in the comments.</p>
<p>I want to run a function in a Cython prange loop as in the code below. This code throws a "<strong>double free or corruption (fasttop)</strong>" error.</p>
... | <p>I originally identified one issue that wasn't causing your problem but did need fixing (this is now fixed in the edited code): Cython has no way of knowing that the exception has been raised - in the C API an exception is indicated by returning <code>NULL</code>, but your function is <code>void</code>. See <a href="... | python|c|numpy|openmp|cython | 1 |
17,987 | 55,926,719 | create boxes on graph in python | <p><a href="https://i.stack.imgur.com/fR2Rn.jpg" rel="nofollow noreferrer">I want this kind of result</a>. I want my code to read elements of a text file and if <code>element=='healthy'</code>
it should create a box in a graph and its color should be green ('healthy written in box').
else if <code>element=='unhealthy'... | <p>There are a few different ways you can do this and your code is probably not the best but we can use it as a starting point. Your issue is that you are looping through the plots and then looping through your data again for each plot. Your current code also adds text above the plot. If you want the text above I would... | python|python-3.x|pandas|numpy|matplotlib | 1 |
17,988 | 64,914,598 | PyTorch: RuntimeError: Input, output and indices must be on the current device | <p>I am running a BERT model on torch. It's a multi-class sentiment classification task with about 30,000 rows. I have already put everything on cuda, but not sure why I'm getting the following run time error. Here is my code:</p>
<pre><code>for epoch in tqdm(range(1, epochs+1)):
model.train()
loss_tr... | <p>You should put your model on the device, which is probably cuda:</p>
<pre><code>device = "cuda:0"
model = model.to(device)
</code></pre>
<p>Then make sure the inputs of the model(input) are on the same device as well:</p>
<pre><code>input = input.to(device)
</code></pre>
<p>It should work!</p> | python|nlp|pytorch|bert-language-model | 12 |
17,989 | 64,963,553 | Can pandas truncate my data and cause irreparable data loss without any kind of warning whatsoever? | <pre><code>import pandas as pd
import io
indata = io.StringIO("c\n10000000000")
df = pd.read_csv(indata, header=0)
print(df)
indata.seek(0)
df = pd.read_csv(indata, header=0, dtype={"c":int})
print(df)
</code></pre>
<p>Expected Output:</p>
<pre><code> c
0 10000000000
c
0... | <p>I see what's happening here. From the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">pandas documentation</a>:</p>
<blockquote>
<p>dtypeType name or dict of column -> type, optional
Data type for data or columns. E.g. <code>{‘a’: np.float64, ‘b’... | python|pandas|floating-point|truncate | 2 |
17,990 | 43,977,109 | Loading NORB Dataset for use with Keras Tensorflow in Python | <p>I am trying to do some work with the NORB dataset (<a href="http://www.cs.nyu.edu/~ylclab/data/norb-v1.0-small/" rel="nofollow noreferrer">http://www.cs.nyu.edu/~ylclab/data/norb-v1.0-small/</a>) but I can't get it read from the binary files where the dataset is contained. Any body can help?</p>
<p>I tried <code>nu... | <p>I recently had the same problem, since I had to work with that dataset and I discovered that it is distributed in a strange binary format.</p>
<p>For this purpose I made a <strong>python wrapper</strong> that you may find useful. You can find it <a href="https://github.com/ndrplz/small_norb" rel="nofollow noreferre... | numpy|tensorflow|keras|tensor | 3 |
17,991 | 43,996,951 | Read very long array from mat with scipy | <p>I have a result file from Dymola (.mat v4) which stores all variables in a huge 1D array (More or less 2GB of data in one array...). I can't do anything about the file format as we are bound to use Dymola. When trying to read the file using scipy (with Python 2.7.13 64bit), I get the following error:</p>
<pre><code... | <p>I suggest you turn on conversion to SDF file format which is based on HDF5. This format can better handle large files. See Simulation/Setup. </p>
<p>Alternatively you can reduce the number of variables stored in the file using Variable Selections in Dymola. </p> | python|numpy|scipy|mat | 0 |
17,992 | 69,493,617 | Appending 2 data sets whilst keeping the header | <p>I am trying to extract a few items from an Excel file and subsequently save them into a separate Excel file.</p>
<p>For example, I am trying to:</p>
<ol>
<li>Select only transactions that is 500 and above from Column G</li>
<li>Randomly select 3 transactions from the remaining items in the original Excel file</li>
<... | <p>You want to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer">concat</a>.</p>
<pre><code>combined_df = pd.concat([df1, df2], ignore_index=True)
combined_df.to_excel('filename.xlsx',index=False)
</code></pre> | python|excel|pandas|numpy | 0 |
17,993 | 69,577,306 | X-axis labels not showing on bar plot | <p>I'm having an issue with my plot only displaying every other label on the x-axis.</p>
<p>Code:</p>
<pre><code>m_count= [12, 12, 13, 16, 12, 12, 13, 16, 9, 10]
f_count =[13, 13, 12, 9, 13, 13, 11, 9, 15, 15]
labels = ["Capomulin", "Ceftamin", "Infubinol", "Ketapril", &quo... | <p>My quickest fix is to use</p>
<pre><code>plt.xticks(ind, labels)
</code></pre>
<p>But thanks to Trenton's comments, I have come up with an updated solution:</p>
<pre><code>ax.set_xticks(ind)
ax.set_xticklabels(labels)
</code></pre> | python|pandas|matplotlib|bar-chart | 2 |
17,994 | 69,616,623 | Pandas DataFrame - Filter rows according to substring | <p>Let's assume I've created a data frame, and I want to filter all rows in which the value in column C is not a substring of the value in column B.</p>
<p>For example -</p>
<pre><code>Column A Column B
string str
another arr
nope eee
</code></pre>
<p>As you can see, none of the v... | <p>Try:</p>
<pre><code>mask = df[["Column A", "Column B"]].apply(lambda x: x["Column B"] in x["Column A"], axis=1)
res = df[mask]
print(res)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>0 True
1 False
2 False
dtype: bool
</code></pre> | python|pandas|dataframe | 0 |
17,995 | 69,352,733 | Remove duplicates from row applying exceptions | <p>I try to remove duplicates on rows but I need to have strings with length <= 2 and integer.</p>
<p>I have a sentence like this:</p>
<pre><code>AIR OPTIX Air Optix plus HydraGlyde Lenti a Contatto Mensili, 6 Lenti, BC a 6 mm, DIA 14.2 mm, -0.75 Diopt
</code></pre>
<p>What I need to obtain is:</p>
<pre><code>AIR OP... | <p>Here. Not the best code, but it get's the job done - it passes the test.</p>
<pre class="lang-py prettyprint-override"><code>def uniqueList(row):
words = str(row).split(" ")
unique = words[0]
for w in words:
try:
int(w)
unique = unique + " " + ... | python|pandas|string|duplicates | 0 |
17,996 | 41,168,635 | How to find all possible daughters in a sequence of numbers stored in dataframe | <p>I have a python dataframe which one of its column such as <code>column1</code> contains series of numbers. I have to mention that each these numbers are the result of cell mutation so cell with number <code>n</code> deviates to two cells with following numbers: <code>2*n</code> and <code>2*n+1</code>. I want to sear... | <p>The two sequences look like the numbers who's <a href="http://oeis.org/A004754" rel="nofollow noreferrer">binary expansion starts with <code>10</code></a> and the numbers for which the <a href="http://oeis.org/A004755" rel="nofollow noreferrer">binary expansion starts with <code>11</code></a>.</p>
<p>Both sequences... | python|numpy|search|dataframe | 1 |
17,997 | 54,020,610 | Sending two Pandas dataframes side-by-side using HTML in email | <p>I'm trying to send some summary on my shares portfolio creation via email. I'm using Python + Pandas for the calculations and email.mime module to send html via email.</p>
<p>I am using Pandas to_html method and email.mime module to include the html in the email:</p>
<pre><code>import smtplib
from email.mime.text ... | <p>If you want to create two columns, replace the two divs with the below table. Div's dont have the same support as tables on all email clients.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prett... | python|html|css|pandas|html-email | 1 |
17,998 | 66,087,874 | Summing dictionary of lists values by key | <p>I have a dictionary of lists as below:</p>
<p>defaultdict(<class 'list'>, {0: [[1.0, 2.0, 3.0], [7.0, 8.0, 9.0]], 1: [[4.0, 5.0, 6.0], [10.0, 11.0, 12.0]]})</p>
<p>I need a dictionary that reduces the dimension by summing the list's value from it such as below</p>
<p>{0: [6.0, 24.0], 1: [15.0, 33.0]}</p>
<p>Hi... | <p>Iterate over the keys and sum each of the sublists in a list comprehension:</p>
<pre><code>d = {0: [[1.0, 2.0, 3.0], [7.0, 8.0, 9.0]], 1: [[4.0, 5.0, 6.0], [10.0, 11.0, 12.0]]}
for k in d:
d[k] = [sum(l) for l in d[k]]
>>> d
{0: [6.0, 24.0], 1: [15.0, 33.0]}
</code></pre>
<p>Also works on a <code>defa... | python-3.x|pandas|dictionary | 1 |
17,999 | 66,177,768 | A boundary of p pixels going in a 2d numpy array using quick function | <p>I have a (n_rows,m_cols) numpy array (The values of n_rows and m_cols are usually in a few hundred) of floats. I would like to make a strip (boundary if you like) around this but not change the size of the array.</p>
<p>How I want to do that is to make the first p rows, last p rows, first p cols and last p cols all ... | <pre class="lang-py prettyprint-override"><code>import numpy as np
# simulating your data
array = np.random.random(size=(100, 200))
# change to what you need
n_rows_head = 1
n_rows_tail = 2
n_cols_head = 2
n_cols_tail = 2
# new array
new_array = np.zeros_like(array)
new_array[n_rows_head:-n_rows_tail + 1, n_cols_hea... | python|arrays|numpy | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.