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 |
|---|---|---|---|---|---|---|
6,100 | 65,205,582 | How can i add a Bi-LSTM layer on top of bert model? | <p>I'm using <strong>pytorch</strong> and I'm using the base <strong>pretrained bert</strong> to classify sentences for hate speech.
I want to implement a <strong>Bi-LSTM</strong> layer that takes as an input all outputs of the latest
transformer encoder from the bert model as a new model (class that implements <strong... | <p>You can do it as follows:</p>
<pre><code>from transformers import BertModel
class CustomBERTModel(nn.Module):
def __init__(self):
super(CustomBERTModel, self).__init__()
self.bert = BertModel.from_pretrained("bert-base-uncased")
### New layers:
self.lstm = nn.LST... | python|deep-learning|neural-network|pytorch|lstm | 9 |
6,101 | 50,179,949 | Create a function to extract specific columns and rename pandas | <p>I have a target table structure (3 columns). I have multiple sources, each with its own nuances but ultimately I want to use each table to populate the target table (append entries)</p>
<p>I want to use a function (I know I can do it without a function but it will help me out in the long run to be able to use a fun... | <p>Here's a flexible way to write this function:</p>
<pre><code>def func(dframe, **kwargs):
return dframe.filter(items=kwargs.keys()).rename(columns=kwargs)
func(df, id="id", col1="num", col2="group")
# group id num
# 0 b 1 a
# 1 b 1 a
# 2 d 1 c
</code></pre>
<p>To ensure that your ne... | python|pandas|numpy | 2 |
6,102 | 63,831,229 | How to split a DataFrame into multiple DataFrames by row value? | <p>I have a dataframe like below one. I want to split the Dataframe based on Rows</p>
<pre><code> Rows col1 value1 value2
0 row_1 var1 12 3434
1 row_1 var2 212 546
2 row_1 var3 340 8686
3 row_2 ... | <ul>
<li>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby</code></a> on the <code>'Rows'</code> and create a <code>dict</code> of <code>DataFrames</code> with unique <code>'Row'</code> values as keys, with a <a href="... | python|pandas|dataframe | 1 |
6,103 | 46,893,745 | Set new column values in pandas DataFrame1 where DF2 column values match DF1 index | <p>I'd like to set a new column in a pandas dataframe with values calculated using a groupby on dataframe2.</p>
<p>DF1:</p>
<pre><code> col1 col2
id
1 'a'
2 'b'
3 'c'
</code></pre>
<p>DF2:</p>
<pre><code> id col2
index
1 1 11
1 1 22
1 1 ... | <p>Use <code>map</code> on <code>df1.index</code> series.</p>
<pre><code>In [5327]: df1['col2'] = df1.index.to_series().map(df2.groupby('id')
.apply(lambda x: my_func(x['col2'])))
In [5328]: df1
Out[5328]:
col1 col2
id
1 a 360.0
2 b NaN
3 c 5... | python|pandas|pandas-groupby | 2 |
6,104 | 63,139,530 | Most efficient way to detect non-transparent pixels in ImageMagick / RMagick | <p>I've got a series of drawings created via HTML Canvas. I need to create a heatmap using these drawings to show where the most common areas are.</p>
<p>Each drawing is a PNG image with a transparent background. The only non-transparent pixels are those which the users has drawn on. Here are a couple sample images: <a... | <p>In command line ImageMagick, you can list all the non-transparent pixels using sparse-color: or parsing txt:. Here is a 100x100 transparent image with a 2x2 red square in the top left corner.</p>
<p><a href="https://i.stack.imgur.com/qi79H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qi79H.png"... | ruby|numpy|imagemagick|heatmap|rmagick | 2 |
6,105 | 63,181,994 | Python pandas: if column A value appears more than once, assign first value of column B | <p>I am trying to dynamically replace the value <em>i</em> of <strong>column B</strong> with a consistent value conditional on the value count of <em>j</em> in <strong>column A</strong>.</p>
<p>I'm trying to use a dictionary to map the values, but it isn't working.</p>
<pre><code>color = ['black','mauve','teal','green'... | <p>It is <code>transform</code> and <code>first</code></p>
<pre><code>df['new_code'] = df.groupby('color').code.transform('first')
Out[21]:
color code new_code
0 black E45 E45
1 mauve M46 M46
2 teal Y76 Y76
3 green G44 G44
4 teal T76 Y76
5 black B43 E45
</code></pre> | python|pandas|dictionary|conditional-statements|mapping | 2 |
6,106 | 63,290,575 | text response from get request into a python pandas data frame excluding begin and end lines | <p>I am new to python, I am working on code that performs a get request from an api and returns the response in a text format and when I use</p>
<pre><code>print(response.text)
</code></pre>
<p>I get the response in the below format -</p>
<pre><code>ResponseBegin
Name|Age|Gender|Country
"ABC"|23|M|USA
"A... | <p>It's more helpful if you do not show what <code>print(response.text)</code> contains, but just what <code>response.text</code> contains, since the print function is doing some formatting for human readability.</p>
<p>But I will assume that <code>response.text</code> is just a single string that looks like this:</p>
... | python|pandas|dataframe | 2 |
6,107 | 67,824,746 | How to print rows of data where the difference in columns is >1 | <p>the data table i'm using is:</p>
<pre><code>enter code here
|State| Sno Center| Mar-21| Apr-21|
|AP 1 | Guntur | 121 | 121.1 |
| 2 | Nellore | 118.8 | 118.3|
| 3 | Visakhapatnam| 131.6 | 131.5|
|ASM | 4 Biswanath-| 123.7 | 124.5|
| 5 | Doom-Dooma | 127.8 |128.2|
| 6 | Guwahati ... | <p>You can try as follows</p>
<pre><code>df_new = df[(df["Apr-21"]-df["Mar-21"]) > 1].copy()
</code></pre>
<p>For example</p>
<pre><code>df = pd.DataFrame(data={'State':[1,2,3,4,5,6, 7, 8, 9, 10],
'Sno Center': ["Guntur", "Nellore", "Visakhapatna... | pandas|dataframe | 0 |
6,108 | 67,688,117 | How to re-add deleted columns from a dataframe in pandas python? | <p>How to re-add columns from original dataframe, which were once in the data frame but got removed using a list?</p>
<pre><code>df_original =['a','b','c','d','f']
df_new=df_original[['b','c','d']]
user_re_add col=['a']
if user_re_add not in df_new.columns:
add= df_new.append(user_re_add)
print("Re-add th... | <p>Using your example:</p>
<pre><code>df_original = pd.DataFrame(columns=['a','b','c','d','f'])
df_new=df_original[['b','c','d']]
user_re_add = df_original[['a']]
if [column for column in user_re_add.columns] not in [column for column in df_new.columns]:
add = df_new.append(user_re_add)
add = add[[column for ... | python|pandas|dataframe|data-science|data-manipulation | 1 |
6,109 | 68,012,066 | To plot graph non linear function | <p>I want to plot graph of this function:</p>
<pre><code>y = 2[1-e^(-x+1)]^2-2
</code></pre>
<p>When I plot a linear function, I used this code :</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.array(...)
y = np.array(...)
z = np.polyfit(x, y, 2)
p = np.poly1d(z)
xp = np.linspace(...)
_ = plt... | <p>I hate to be the one to break this news to you, but polynomials of order greater than one are technically nonlinear too.</p>
<p>When you plot in matplotlib, you're really supplying discreet x and y values at a resolution sufficient to be visually pleasing. In this case, you've chosen <code>xp</code> to determine the... | python|numpy|matplotlib|plot | 1 |
6,110 | 67,683,777 | tflite: Make multiple invocations at once | <p>Assume a webpage where multiple users send an image at once for inference. One option is to load the tflite model for each inference call by loading it inside the function</p>
<pre><code>def detect_from_image(image_path):
# load model
interpreter = tf.lite.Interpreter(model_path="detect.tflite")
... | <p>Please consider having a pool for storing TFLite interpreter instances and picking up one instance per request. TFLite interpreter API does not guarantee the multi-thread support.</p> | python|tensorflow|tensorflow-lite | 0 |
6,111 | 61,441,165 | Pandas: Slicing up a df based on repeated flags | <p>I have a <code>df</code> that looks something like this: </p>
<pre><code> HEADER1 HEADER2 HEADER3
0 Group1 Value2 Value3
1 Group2 Value4 Value5
4 Group1 Value6 Value7
5 Group2 Value8 Value9
6 TAIL1 TAIL2 TAIL3
</code></pre>
<p>Header and Tail will always... | <p>Use list comprehension with <code>groupby</code> and add last row by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>DataFrame.append</code></a>:</p>
<pre><code>#get last row
last = df.iloc[[-1]]
print (last)
HEADER1 HEADER2 HEADER3
... | python|python-3.x|pandas|dataframe | 2 |
6,112 | 61,280,184 | Model with multiple outputs and custom loss function | <p>I'm trying to train a model that has multiple outputs and a custom loss function using keras, but I'm getting some error <code>tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: iterating over ``tf.Tensor`` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf... | <p>With quick tests, I think I solved the problem by replacing:</p>
<pre><code> mean, variance = y_pred
variance = variance + 0.0001
</code></pre>
<p>With</p>
<pre><code> mean = y_pred[0]
variance = y_pred[1] + 0.0001
</code></pre>
<p>Unpacking <code>y_pred</code> (which is a Tensor) c... | python|tensorflow|keras | 4 |
6,113 | 68,860,208 | Put specific rows at the end of data frame depending on column value | <p>If I have a data frame that looks something like:</p>
<pre><code>df =
col1 col2 col3
--------------------
10 56.4 78.2
20 45.6 23.3
30 12.1 26.0
40 55.4 22.9
50 10.1 98.3
</code></pre>
<p>Then I have a regular list that contains:</p>
<pre><code>list1 = [10, 30]
</code><... | <p>Use <code>key</code> parameter in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a>:</p>
<pre><code>list1 = [10, 30]
df = df.sort_values('col1', key=lambda x: x.isin(list1))
print (df)
col1 col2 ... | python|pandas | 5 |
6,114 | 53,126,795 | Sum time difference and pivot it - pandas dataframe | <p>I have a dataframe has two columns: unix_time and user. It has thousands of rows, this is part of it:</p>
<pre><code>unix_time user
2000000000000 A
2000000000001 A
2000000000002 B
2000000000003 B
2000000000004 B
</code></pre>
<p>I want to calculate how much unix_time each user spent in total by:<br... | <p>You can use <code>groupby()</code> and <code>diff()</code> and then <code>agg()</code> your results:</p>
<pre><code>df['time_difference_sum'] = df.sort_values(['user','unix_time']).groupby('user')['unix_time'].diff()
df.groupby('user').agg({'time_difference_sum': 'sum'})
</code></pre>
<p>Yields:</p>
<pre><code> ... | python|pandas|datetime|dataframe | 1 |
6,115 | 53,101,293 | Scalar-valued isnull()/isnan()/isinf() | <p>In Pandas and Numpy, there are vectorized functions like <code>np.isnan</code>, <code>np.isinf</code>, and <code>pd.isnull</code> to check if the elements of an array, series, or dataframe are various kinds of missing/null/invalid.</p>
<p>They do work on scalars. <code>pd.isnull(None)</code> simply returns <code>Tr... | <p>All you have to do is wrap <code>pd.isnull</code> in a way that in case it gets an iterable it will be forced to check it element-wise. This way you will always get a scalar boolean as output.</p>
<pre><code>from collections import Iterable
def is_scalar_null(value):
if isinstance(value, Iterable):
ret... | python|pandas|numpy|missing-data | 2 |
6,116 | 53,275,955 | how to join two dataframe with a key and duplicate the matching value to fill in | <p>how can I join two data frames by column "ID" and fill the blanks with the matching value. Since it is complicated to explain, here is my code to show what I want for the result.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'id': [1, 1, 1, 2, 2, 3, 4, 4, 4], 'col1': [3, 0, -1, 3.4, 4, 5, 6, 7, 8]})
df2... | <p>Are you looking for <code>merge</code>?</p>
<pre><code>df.merge(df2, on='id')
id col1 col2
0 1 3.0 A
1 1 0.0 A
2 1 -1.0 A
3 2 3.4 B
4 2 4.0 B
5 3 5.0 C
6 4 6.0 D
7 4 7.0 D
8 4 8.0 D
</code></pre> | python|pandas|dataframe|join | 1 |
6,117 | 53,231,699 | Converting png to Tensor tensorflow.js | <p>I'm currently attempting to figure out how to convert a input png into a tensor with tensorflow.js so I can feed it into my model for training. Currently I'm capturing the image, saving it locally, reading it with fs.readFileSync, and then creating a buffer. Where i'm a bit lost is normalizing the buffer values from... | <p>tensorflowjs already has a method for this: <a href="https://js.tensorflow.org/api/0.13.3/#fromPixels" rel="nofollow noreferrer"><code>tf.fromPixels(), tf.browser.fromPixels()</code></a>.</p>
<p>You just need to load the image into on of the accepted types(<code>ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideo... | javascript|node.js|png|buffer|tensorflow.js | 13 |
6,118 | 65,754,740 | Modifying entire row of an array based on a condition using Numpy | <p>I have an array:</p>
<p><code>xNew = np.array([[0.50,0.25],[-0.4,-0.2],[0.60,0.80],[1.20,1.90],[-0.10,0.60],[0.10,1.2]])</code></p>
<p>and another array:</p>
<p><code>x = np.array([[0.55,0.34],[0.45,0.26],[0.14,0.29],[0.85,0.89],[0.27,0.78],[0.45,0.05]])</code></p>
<p>If an element in a row is smaller than 0 or larg... | <p>You can use advanced indexing:</p>
<pre><code>idx = ((xNew<0)|(xNew>1)).any(-1)
xNew[idx]=x[idx]
</code></pre>
<p>output:</p>
<pre><code>[[0.5 0.25]
[0.45 0.26]
[0.6 0.8 ]
[0.85 0.89]
[0.27 0.78]
[0.45 0.05]]
</code></pre> | python|arrays|numpy | 1 |
6,119 | 65,754,329 | Create a empty dataframe and append a new row | <p>Im trying to create a empty dataframe with 3 columns: <code>movieId</code>, <code>title</code> and <code>predicted_rating</code>.</p>
<p>This is what I have so far:</p>
<pre><code>column_names = ["movieId", "title", "predicted_rating"]
return_df = pd.DataFrame(columns=column_names)
re... | <p>I think its because <code>append</code> returns a new DataFrame, it probably doesn't modify inplace.</p>
<p>So try this:</p>
<pre><code>return_df = return_df.append({"movieId":1,"title":2,"predicted_rating":3}, ignore_index=True)
</code></pre> | python|pandas|dataframe | 0 |
6,120 | 65,704,040 | How to sort a date column in Pandas with value_counts? | <p>I have a column in my dataframe like this:</p>
<pre><code> submit_date
1 2020-12-14
3 2020-12-14
4 2020-12-14
5 2020-12-14
29 2020-12-15
...
746 2021-01-12
771 2021-01-12
744 2021-01-12
757 2021-01-12
772 2021-01-12
</code></pre>
<p>I want to obtain how many submissions are... | <p>You can sorting index <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.sort_index.html" rel="nofollow noreferrer"><code>Series.sort_index</code></a> :</p>
<pre><code>df['submit_date'].value_counts().sort_index()
</code></pre>
<p>Or if original column is sorted add <code>sort=False</co... | python|pandas|datetime | 2 |
6,121 | 65,804,813 | Pandas - How to fill column with range time conditions | <p>I have a dataset with different columns: the activity description and when it's started and ended</p>
<pre><code> Activity Start End In time
Activity 1 10:44:26 15:02:24
Activity 2 15:22:42 13:52:54
Activity 3 14:41:57 16:03:48
Activity 4 11:16:08 13:37:16... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<pre><code>#if necessary convert to times
#df['Start'] = pd.to_datetime(df['Start']).dt.time
#df['End'] = pd.to_datetime(df['End']).dt.time
from datetime import time
mask = (d... | python|pandas|dataframe|if-statement | 1 |
6,122 | 63,359,261 | Finding newest columns in pandas dataframe | <p>I am trying to read/parse some Excel-file through pandas dataframe into SQL Server.</p>
<p>The excel-file that I need to read is not completely static and column-names changes from time to time, but mostly in a fairly predictable manner - I am just not sure how to actually capture it. Also the order of the columns c... | <p>Might require a hack-y solution, given the inconsistencies. Import your Excel file and grab the column names, and then use string methods to pull out and track the relevant info. Luckily months are unique, and you can just use the abbreviation.</p>
<pre><code>df = pd.DataFrame({'ID': np.random.randn(5),
... | python|pandas | 1 |
6,123 | 63,497,505 | Automating the creation of dataframes from subsets of an existing dataframe | <p>I'm working with the kaggle New York City Airbnb Open Data which is available here:
<a href="https://www.kaggle.com/dgomonov/new-york-city-airbnb-open-data" rel="nofollow noreferrer">https://www.kaggle.com/dgomonov/new-york-city-airbnb-open-data</a></p>
<p>The data contains a column of the 'neighbourhood_groups', co... | <p>You should not copy into new dfs unless strictly necessary. Try to do your analysis with the full df as much as possible. Use <code>.groupby</code> as in</p>
<pre><code>by_neigh = airbnb.groupby('neighbourhood_group')
</code></pre>
<p>Then use <code>.agg</code>, <code>.apply</code>, or <code>.transform</code> as nee... | python|pandas|dataframe|for-loop|automation | 0 |
6,124 | 53,662,172 | How to save timestamps in parquet files in C++ and load it in Python Pandas? | <p>I am using <code>Apache Arrow</code> in C++ to save a collection of time-series as a parquet file and use python to load the parquet file as a <code>Pandas</code> <code>Dataframe</code>. The process works for all types except the <code>Date64Type</code>. I am saving the epoch time in C++ and when loading it in panda... | <p>You need to use <code>arrow::TimestampType</code> instead. <code>Date32Type</code> and <code>Date64Type</code> only support day resolution; their internal representation is a bit different through (<code>int32_t</code> days since the UNIX epoch vs. <code>int64_t</code> milliseconds since the UNIX epoch)</p> | c++|pandas|parquet|pyarrow | 1 |
6,125 | 72,046,944 | Python (pandas) - How to group values in one column and then delete or keep that group based on values in another column | <p>Let's say I have the following pandas dataset:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>dog</td>
<td>RE</td>
</tr>
<tr>
<td>dog</td>
<td>RE FX</td>
</tr>
<tr>
<td>cat</td>
<td>RE BA</td>
</tr>
<tr>
<td>mouse</td>
<td>... | <p>You can try <code>groupby</code> then <code>filter</code></p>
<pre class="lang-py prettyprint-override"><code>out = df.groupby("Column 1").filter(lambda df: ~df['Column 2'].isin(["RE", "RE BA"]).any())
</code></pre>
<pre><code>print(out)
Column 1 Column 2
3 mouse AQ
4 mou... | python|pandas | 1 |
6,126 | 71,832,948 | How to convert Excel file to json using pandas? | <p>I would like to parse Excel file which has a couple of sheets and save a data in JSON file.</p>
<p>I don't want to parse first and second sheet, and also the last one. I want to parse those in between and that number of sheets is not always equal and names of those sheets are not always the same.</p>
<pre><code>impo... | <p>I would just create a sheet level dict and loop through each of the sheets. Something like this:</p>
<pre><code>import pandas
import json
sheets = ['sheet1','sheet2','sheet3']
output = dict()
# Read excel document
for sheet in sheets:
excel_data_df = pandas.read_excel('data.xlsx', sheet_name=sheet)
# Convert e... | python|json|excel|pandas|dataframe | 1 |
6,127 | 55,511,186 | Could not identify NUMA node of platform GPU | <p>I try to get Tensorflow to start on my machine, but I always get stuck with a "Could not identify NUMA node" error message.</p>
<p>I use a Conda environment:</p>
<ul>
<li>tensorflow-gpu 1.12.0</li>
<li>cudatoolkit 9.0</li>
<li>cudnn 7.1.2</li>
<li>nvidia-smi says: Driver Version 418.43, CUDA Version 10.1</li>
</ul... | <p>I could fix it with a new conda enviroment:</p>
<pre><code>conda create --name tf python=3
conda activate tf
conda install cudatoolkit=9.0 tensorflow-gpu=1.11.0
</code></pre>
<p>A table of compatible CUDA/TF combinations is available <a href="https://www.tensorflow.org/install/source#linux" rel="nofollow noreferre... | python|tensorflow|keras | 1 |
6,128 | 56,452,689 | How do I import rows of a Google Sheet into Pandas, but with column names? | <p>There are great instructions in a number of places to import a Google Sheet into a Pandas DataFrame using gspread, eg:</p>
<pre><code># Open our new sheet and read some data.
worksheet = gc.open_by_key('...').sheet1
# get_all_values gives a list of rows.
rows = worksheet.get_all_values()
# Convert to a DataFrame ... | <p>You can do </p>
<pre><code>row=[[1,2,3,4]]*3
pd.DataFrame.from_records(row[1:],columns=row[0])
1 2 3 4
0 1 2 3 4
1 1 2 3 4
</code></pre> | pandas|gspread | 4 |
6,129 | 67,028,048 | Making common units within a column of a Pandas DataFrame | <p>I have a dataframe that has measurements with different units in the same column. A separate column exists for the unit names.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'color': ['red','green','blue','blue','green'],
'length': [3,6,9,120,15],
'le... | <p>Create a <code>dict</code> of <code>dicts</code> where the keys are your desired units and the value is a dict with all conversions to that unit (that are required in your data). Then given your consistent naming conventions of the columns, use a simple loop to map the unit to its conversion and multiply by the valu... | python|pandas | 3 |
6,130 | 66,895,438 | Unable to find out how to specify datetime dtype to Numba @guvectorize | <p>I would like to handle array of datetime values in Numba.
I tried so on a small example, but I am unable to have it working.</p>
<pre class="lang-py prettyprint-override"><code>import numba as nb
from numba import guvectorize
@guvectorize('void(nb.types.NPDatetime("ns")[:],nb.types.NPDatetime("ns&quo... | <p><code>guvectorize</code> does not work with datetime types. Convert to float timestamp.</p>
<pre><code>import numba as nb
from numba import guvectorize
import numpy as np
import pandas as pd
import arrow
@guvectorize([(nb.types.float64[:],nb.types.float64[:])],'(m)->(m)')
def ts_copy(ts, ts_c):
for idx, t i... | python|numpy|numba | 1 |
6,131 | 47,254,587 | Is pandas / numpy's axis the opposite of R's MARGIN? | <p>Is it correct to think about these two things as being opposite? This has been a major source of confusion for me.</p>
<p>Below is an example where I find the column sums of a data frame in R and Python. Notice the opposite values for <code>MARGIN</code> and <code>axis</code>.</p>
<p>In R (using <code>MARGIN=2</co... | <p>Confusion arises because <code>apply()</code> talks both about which dimension the apply is "over", as well as which dimension is <em>retained</em>. In other words, when you <code>apply()</code> over rows, the result is a vector whose length is the number of columns in the input. This particular confusion is highl... | python|r|pandas|numpy | 3 |
6,132 | 59,241,216 | Padding NumPy arrays to a specific size | <p>I would like to pad all my arrays to a certain constant shape. </p>
<p>All arrays have size (X, 13) but I want them to be (99, 13). X is smaller than or equals to 99. There are arrays that are smaller than 99. I'm looking for a way to pad them to the size of the default <code>var</code>. </p>
<p>I have seen and tr... | <p>Here:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
arr = np.random.randint(0, 10, (7, 4))
def padding(array, xx, yy):
"""
:param array: numpy array
:param xx: desired height
:param yy: desirex width
:return: padded array
"""
h = array.shape[0]
w = array.s... | python|numpy | 5 |
6,133 | 45,986,897 | Multiplying elementwise over final axis of two arrays | <p>Given a 3d array and a 2d array,</p>
<pre><code>a = np.arange(10*4*3).reshape((10,4,3))
b = np.arange(30).reshape((10,3))
</code></pre>
<p>How can I run elementwise-multiplication across the final axis of each, resulting in <code>c</code> where <code>c</code> has the shape <code>.shape</code> as <code>a</code>? I... | <p>Without any sum-reduction involved, a simple <code>broadcasting</code> would be really efficient after extending <code>b</code> to <code>3D</code> with <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#numpy.newaxis" rel="nofollow noreferrer"><code>np.newaxis/None</code></a> -</p>
<pre... | python|python-3.x|numpy|numpy-einsum | 2 |
6,134 | 46,140,609 | One to many, left, outer join with pandas (Python) | <p>I'm trying to join three tables together using Python 2.7 and pandas. My tables look like the ones below:</p>
<pre><code>Table 1
ID | test
1 | ss
2 | sb
3 | sc
Table 2
ID | tested | value1 | Value2 | ID2
1 | a | e | o | 1
1 | axe | ee | e | 1
1 | b... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> for count <code>ID2</code> in both <code>df2</code> and <code>df3</code> for merge by unique <code>pairs</code>. Then <a href="http://pandas.pydata... | python|pandas|join|outer-join | 1 |
6,135 | 51,011,970 | For loop for an array | <p>I have the array <code>vAgarch</code> and I am trying to extract each element from that, so I have the following code now:</p>
<pre><code>vAgarch = [0.05, 0.03, 0.04, 0.05, 0.03, 0.04]
vAgarch = np.array(vAgarch)
# Extract each element from array vAgarch
dA1garch = np.fabs(vAgarch[0])
dA2garch = np.fabs(vAgarch[1]... | <p>There is no need to use a for loop,<code>numpy fabs</code> parameters can be <code>array_like</code>, so you can just pass list to it. As below code(I have change some elements in <code>vAgarch</code> to minus):</p>
<pre><code>def test_s():
vAgarch = [-0.05, 0.03, -0.04, 0.05, 0.03, 0.04]
print vAgarch
... | python|arrays|loops|numpy | 0 |
6,136 | 66,661,492 | Identifying overlapping events (datetime records) in a pandas dataframe | <p>I am having difficulty in trying to detect overlapping <code>start_datetime</code> and <code>end_datetime</code> in my dataset.</p>
<p>Currently my dataset looks like the following</p>
<p><a href="https://i.stack.imgur.com/UOE27.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UOE27.png" alt="enter... | <h3><code>Numpy broadcasting</code></h3>
<pre><code>s, e = df[['start_datetime', 'end_datetime']].to_numpy().T
m1 = (s[:, None] > s) & (s[:, None] < e) # Check if start time overlap
m2 = (e[:, None] < e) & (e[:, None] > s) # Check if ending time overlap
df['overlap'] = (m1 | m2).any(1)
</code></pre... | python|pandas|dataframe|datetime|python-datetime | 4 |
6,137 | 70,946,613 | pandas timeseries offset BusinessMonthBegin doesn't roll over on the new month | <p>I have a couple of pandas functions that I use to collect relative start dates for previous time periods. I noticed today on the start of the new month, my business month start (<code>BMS</code>) function returned an unexpected timestamp:</p>
<pre><code># so.py
import pandas
import time
def now(format='ms', normali... | <p>If the date falls on the offset, the offset addition already gives the previous bmonth start date (e.g. 2022-02-01 is a business month start date):</p>
<pre><code>import pandas as pd
t_on_offset = pd.Timestamp('2022-02-01')
t_after_offset = pd.Timestamp('2022-02-02')
## on the offset, the offset addition will go b... | python|pandas|datetime|time|timestamp | 1 |
6,138 | 51,887,356 | How to make repeated column values columns? | <p>Here is the dataset that I have. The items below are recorded on a daily basis. </p>
<p>Cigarettes, Tobacco, Snack/Grocery, Beverages, Milk, Coffee, Solaray, Prepared Foods, International Foods, Automotive/NewsPaper, Lottery - Scratch, Lottery - Machine, Whl-Sales/Gift-Card are repeated per date.</p>
<p>I want to ... | <p>One way to do this would be to set the index to <code>['Date', 'Dept']</code> and <code>unstack()</code> but you have multiple values for each <code>Dept</code> for the date <code>2018-12-03</code>.</p>
<p>Note sure if that is expected but one way to resolve that issues is to <code>groupby().first()</code> to take ... | python|pandas|dataframe|pivot | 1 |
6,139 | 51,585,272 | ValueError: Index DATE invalid with pandas.read_csv on header row | <p>Trying to create a dictionary with the key's being the first row of the csv file and the value's being a dictionary of {first column: corresponding column to row}:</p>
<pre><code>import pandas as pd
df = pd.read_csv('~/StockMachine/data_stocks.csv', index_col=['DATE'], sep=',\s+')
data = df.to_dict()
print(data)... | <p>Similiar thing happened to me and in my case some readings of <code>['DATE']</code> were strings with empty spaces inside. Maybe if you would do something like:</p>
<pre><code>import pandas as pd
df = pd.read_csv('~/StockMachine/data_stocks.csv', sep=',\s+')
df['DATE'] = df['DATE'].apply(lambda x: str(x.strip()))... | python|pandas|csv|valueerror|header-row | 2 |
6,140 | 37,350,525 | Train SyntaxNet model | <p>I am trying to train the Google Syntaxnet model in a different language using the datasets available at <a href="http://universaldependencies.org/" rel="nofollow">http://universaldependencies.org/</a> and following this <a href="https://github.com/tensorflow/models/tree/master/syntaxnet#detailed-tutorial-building-an... | <p>I recall having a similar error at the beginning. Did you use the exact code under 'training a parser step 1: local pretraining'? Because you will notice there's an uninitialized $PARAMS variable in there that is supposed to represent the parameters of your trained POS tagger. When you train a tagger (see earlier in... | nlp|tensorflow|bazel|syntaxnet | 0 |
6,141 | 37,350,052 | pandas groupby when one record belongs to more than one group | <p>I would like to be able to produce summary statistics and pivot tables from a dataset that can be grouped in multiple ways. The complication arises because each entry can belong to more than one group within one categorisation axis (see example below).</p>
<p>So far, I have found a solution based on multi-indexing ... | <p>I created a function that takes a <code>DataFrame</code> and a column name. It's expected that the column specified by the column name has a string that can be split by <code>','</code>. It will append this split to the index with the appropriate name.</p>
<pre><code>def expand_and_add(df, col):
expand = lamb... | python|database|pandas | 0 |
6,142 | 31,632,050 | Where should I put try/except? | <p>In an effort to improve my coding, I was wondering if I should put try/except inside a function or keep it outside. The following examples display what I mean.</p>
<pre><code> import pandas as pd
df = pd.read_csv("data.csv")
# Example 1
def do_something(df):
# Add some columns
# Spl... | <h2>Possibility of internal handling</h2>
<p>If the function can provide a <em>sensible</em> recovery from the exception and handle it within its scope of responsibilities and without any additional information, then you can catch the exception right there</p>
<h2>Raise or translate to caller</h2>
<p>Otherwise, it m... | python|exception|pandas | 5 |
6,143 | 31,396,226 | Numpy multiply multiple columns by scalar | <p>This seems like a really simple question but I can't find a good answer anywhere. How might I multiply (in place) select columns (perhaps selected by a list) by a scalar using numpy?</p>
<p>E.g. Multiply columns 0 and 2 by 4</p>
<pre><code>In: arr=([(1,2,3,5,6,7), (4,5,6,2,5,3), (7,8,9,2,5,9)])
Out: arr=([(4,2,12... | <p>You can use array slicing as follows for this -</p>
<pre><code>In [10]: arr=([(1,2,3,5,6,7), (4,5,6,2,5,3), (7,8,9,2,5,9)])
In [11]: narr = np.array(arr)
In [13]: narr[:,(0,2)] = narr[:,(0,2)]*4
In [14]: narr
Out[14]:
array([[ 4, 2, 12, 5, 6, 7],
[16, 5, 24, 2, 5, 3],
[28, 8, 36, 2, 5, ... | python|numpy | 3 |
6,144 | 31,295,084 | Matplotlib data plot contains too many labels | <p>I tried to visualize csv data with a 3D graph.</p>
<p>My code is included below:</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
MY_FILE = 'total_watt.csv'
df = pd.read_csv(MY_FILE, parse_dates=[0], header=None, names=['datetime', 'co... | <p>I'm not sure to get the purpose of your question and wasn't able to test it but I think you should change the length of the zticks list:</p>
<pre><code># resizing the yticks list and changing the values
ax.set_yticks(yy[0,::10])
# changing the yticks labels
ax.set_yticklabels(dates[::10], color='lightseagreen')
# c... | python|pandas|matplotlib | 0 |
6,145 | 64,250,531 | Is it possible to have both numpy array values and object atribute pointing to the same position in memory? | <p>In a project I am developing I was wondering if it is possible to do something like:</p>
<pre><code>class P:
def __init__(self, x):
self.x = x
def __str__(self):
return str(self.x)
def __repr__(self):
return self.__str__()
obj_lst = [P(x=2), P(x=3), P(x=4), P(x=5)]
np_x = arra... | <p>You can do it if you think a bit outside the box (and possibly tweak your requirements just slightly). Let's reverse the way things are set up and create a buffer that holds the data first:</p>
<pre><code>np_x = np.array([2, 3, 4, 5])
</code></pre>
<p>Now define your class a bit differently. Instead of recording the... | python|numpy|oop|pointers | 2 |
6,146 | 47,646,130 | Create a nnModule that's just the identity | <p>
I'm trying to debug a pretty complex interaction between different nnModules. It would be very helpful for me to be able to replace one of them with just an identity network for debugging purposes. For example:</p>
<pre class="lang-py prettyprint-override"><code>net_a = NetworkA()
net_b = NetworkB()
net_c = Networ... | <p>You can also <a href="https://github.com/pytorch/pytorch/issues/9160#issuecomment-402381789" rel="nofollow noreferrer">just do</a>:</p>
<pre><code>net_b = torch.nn.Sequential()
</code></pre>
<p>EDIT: in PyTorch 1.7, <code>[nn.Identity](https://pytorch.org/docs/stable/generated/torch.nn.Identity.html#torch.nn.Identit... | pytorch | 4 |
6,147 | 47,750,388 | TensorBoard Callback in Keras does not respect initial_epoch of fit? | <p>
I'm trying to train multiple models in parallel on a single graphics card. To achieve that I need to resume training of models from saved weights which is not a problem. The <code>model.fit()</code> method has even a parameter initial_epoch that lets me tell the model which epoch the loaded model is on. However whe... | <p>Turns out that when i pass the number of episodes to model.fit() to tell it how long to train, it has to be the number FROM the initial_epoch specified. So if initial_epoch=self.step_num then , epochs=self.step_num+10 if i want to train for 10 episodes.</p> | tensorflow|keras|tensorboard | 4 |
6,148 | 47,540,944 | Python / Pandas - Merging on index with multiple repeated keys | <p>I have this dataframe:</p>
<pre><code>df1:
year revenues
index
03374312000153 2010 25432
03374312000153 2009 25433
48300560000198 2014 13894
48300560000198 2013 18533
48300560000198 2012 ... | <p>I actually see nothing wrong with what you're doing, using Pandas 0.19.2. If your version isn't up to date that could be your issue. Check it with:</p>
<pre><code>import pandas as pd
pd.__version__
</code></pre>
<p>How I built your dataframes:</p>
<pre><code>df1 = pd.DataFrame({'year' : pd.Series([2010,2009,2014,... | python|pandas | 1 |
6,149 | 49,004,037 | TypeError: 'DataFrame' object is not callable in concatenating different dataframes of certain types | <p>I keep getting the following error.</p>
<p><a href="https://i.stack.imgur.com/q21nP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q21nP.png" alt="enter image description here"></a></p>
<p>I read a file that contains time series data of 3 columns: [meter ID] [daycode(explain later)] [meter read... | <p>You need same size of both <code>DataFrames</code>, so is necessary <code>day</code> and <code>hm</code> are <code>unique</code>.</p>
<p>Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a> with <code>drop=True<... | pandas|dataframe|merge|typeerror | 1 |
6,150 | 59,015,036 | Retuning columns in a numpy array given a boolean index | <p>I have the given dataset:</p>
<pre><code>data = np.array([
[1, 2, 1, 3, 1, 2, 1],
[3, 4, 1, 5, 2, 7, 2],
[2, 1, 2, 1, 1, 4, 5],
[6, 1, 2 ,3, 1, 3, 1]])
cols_idx = np.array([0, 0, 1, 0, 1, 0, 0])
</code></pre>
<p>I want to return columns from <code>data</code> where <code>cols_idx == 1</code>. For ... | <p><code>print(np.nonzero(cols_idx))</code> gives <code>(array([2, 4]),)</code> (a tuple rather than just an array)</p>
<p>So you should use <code>np.nonzero(cols_idx)[0] # gives [2 4]</code> to get what you want:</p>
<p><strong>Full code:</strong></p>
<pre><code>import numpy as np
data = np.array([
[1, 2, 1, 3... | python|numpy | 1 |
6,151 | 58,678,005 | Numeric file name, upload multiple txt files, Python Pandas | <p>I have around 70 .txt files all saved as </p>
<pre><code>1.txt, 2.txt
</code></pre>
<p>and so on. I would like to create a dataframe with just one columne like <code>fileContent</code> and in each row have text from each txt file. Each time I try to upload file with the name from array of numbers I get error.
Is ... | <pre><code>import pandas as pd
import os
txt_files = [f for f in os.listdir('path_of_txt_files') if '.txt' in f]
pd.DataFrame(pd.Series(dict(zip(txt_files,[open(f,'r').read() for f in txt_files]))))
</code></pre>
<p>This will create a table containing filenames in one column, and their respective contents in the oth... | python|pandas|dataframe | 3 |
6,152 | 70,029,304 | Create pandas dataframe from datetime range | <p>I currently have a data that ranges from 2020-11-03 to 2021-10-01.</p>
<p>I want to make a new dataframe where the row value is equal to the date.</p>
<p>To clarify the first row of the datafame would be 2020-11-03 and the second row would be 2020-11-04 and so on.</p>
<p>Would there be a way to create a new datafram... | <p>You can use the pandas function <code>date_range</code> (documentation <a href="https://pandas.pydata.org/docs/reference/api/pandas.date_range.html" rel="noreferrer">here</a>) and pass your desired date strings to the <code>start</code> and <code>end</code> arguments (and the default frequency is 1 day):</p>
<pre><c... | python|pandas|datetime | 5 |
6,153 | 70,239,393 | mypy error when evaluating return of np.argmin function | <p>I have a function that looks as follows:</p>
<pre><code>import numpy as np
def test() -> np.ndarray:
return np.argmin(np.array([1, 2, 3]))
</code></pre>
<p>According to the <a href="https://numpy.org/doc/stable/reference/generated/numpy.argmin.html" rel="nofollow noreferrer">documentation</a> the return type... | <p>If the array you pass is 1D (shape is <code>(X,)</code>), <code>np.argmin</code> returns the index of the smallest value in that array.. For <code>[1,2,3]</code>, obviously, the lowest value is <code>1</code> at index <code>0</code>; thus <code>np.argmin</code> will return zero:</p>
<pre><code>>>> import nu... | python|numpy|mypy | 0 |
6,154 | 70,132,252 | Using NumPy argmax to count vs for loop | <p>I currently use something like the similar bit of code to determine comparison</p>
<pre><code>list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
high = 29980.0
lookback = 10
counter = 1
for number in list_of_numbers:
if (high >= number) \
and (counter < lookback):
counter... | <p>You can get a boolean array for where <code>high >= number</code> using NumPy:</p>
<pre><code>list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
high = 29980.0
lookback = 10
boolean_arr = np.less_equal(np.array(list_of_numbers), high)
</code></pre>
<p>Then finding where is the first <strong... | python|numpy | 1 |
6,155 | 56,248,645 | How do I get the precursor nodes of each layer in Pytorch? | <p>I can get the summary of the model from pytorch, just like keras:</p>
<pre><code>device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
resnet = models.resnet18().to(device)
summary(resnet , (3, 224, 224))
</code></pre>
<p>result like this:</p>
<pre><code>------------------------------------------... | <p>You're right - PyTorch uses dynamic computation graphs and as such has no concept of children/ancestors by itself. For instance, the <code>Inception3</code> model <a href="https://github.com/pytorch/vision/blob/master/torchvision/models/inception.py#L57" rel="nofollow noreferrer">is created</a> by declaring a bunch ... | python|python-3.x|pytorch | 0 |
6,156 | 55,604,575 | Tensorflow compute update_op for metric using values from previous iteration | <p>I am working on a custom metric and my <code>update_op</code> is a function of current values and the values from the previous run. How do I use them? I have smth like this</p>
<pre><code>x, y = f(data)
var1 = metric_variable([], dtypes.float32)
var1_op = state_ops.assign_add(var1, x + y_previous_iteration)
var2 ... | <p>I solved the problem. The idea is inspired by <a href="https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/contrib/metrics/python/ops/metric_ops.py#L3561" rel="nofollow noreferrer"><code>streaming_concat</code></a> to create a variable of size <code>2*size</code> ( where <code>size</code> is the length of... | python|tensorflow | 0 |
6,157 | 39,772,896 | Add prefix to specific columns of Dataframe | <p>I've a DataFrame like that :</p>
<pre><code>col1 col2 col3 col4 col5 col6 col7 col8
0 5345 rrf rrf rrf rrf rrf rrf
1 2527 erfr erfr erfr erfr erfr erfr
2 2727 f f f f f f
</code></pre>
<p>I would like to rename all columns but not... | <p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="noreferrer">DataFrame.rename()</a> method</p>
<pre><code>new_names = [(i,i+'_x') for i in df.iloc[:, 2:].columns.values]
df.rename(columns = dict(new_names), inplace=True)
</code></pre> | python|pandas | 23 |
6,158 | 39,649,902 | python pandas 'AttributeError: Can only use .dt accessor with datetimelike values' decimal to hours | <p>I have a column in a df that looks like </p>
<pre><code>hour
1.0
2.0
3.0
6.0
Nan
</code></pre>
<p>I want to convert this into a time format so like below</p>
<pre><code>hour
1:00
2:00
3:00
6:00
</code></pre>
<p>However I cannot get the formatting correct. I have tried to coerce the format like below. I would al... | <p>Here:</p>
<pre><code>pd.to_datetime(df['hour'], unit='h')
</code></pre>
<p>Change the <code>format</code> to <code>unit</code>. If you are using numeric data (like you are), then you <strong>cannot</strong> use <code>format</code>. <code>format</code> works only on strings.</p>
<p><code>%H</code>, for example is ... | python|pandas | 0 |
6,159 | 44,028,741 | Matplotlib + Pandas = how to see labels ? | <p>I am trying to display a dataframe with long labels.
The plot is mainly occupied by the graphs, when I would like it to show the labels.
I have : </p>
<pre><code>new_labels = []
for i, index in enumerate(df.index):
new_label = "%s (%.2f)"%(index,df.performance[i])
new_labels.append(new_label)
fig , axes = ... | <p>Try this:</p>
<pre><code>df.sort_values(col_name).plot(x=new_labels, kind='barh', ax=axes)
# NOTE: ^^^^^^^^^^^^
</code></pre> | python|pandas|matplotlib | 0 |
6,160 | 44,141,253 | Tensorflow: simple linear regression | <p>I just started to use Tensorflow in python for optimisation problems. And I just gave it a try with really simple regression model. But the results (both slope and constant) I obtain seemed to be quite far off from what I expect, can anyone point out what I have done wrong (the code runs, but I am not sure if I use ... | <p>You have to call the optimizer multiple times for multiple iterations of gradient descent. As, @dv3 noted, try</p>
<pre><code>init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(50):
opt, result_alpha, result_beta = sess.run([optimizer, alpha, beta], fee... | tensorflow | 1 |
6,161 | 69,475,434 | Reason for getting different array each time when 2nd code block is executed | <pre><code>dataset=tf.keras.preprocessing.image_dataset_from_directory(
"PlantVillage",
shuffle=True,
image_size=(IMAGE_SIZE,IMAGE_SIZE),
batch_size=BATCH_SIZE
)
for image_batch,label_batch in dataset.take(1):
print(image_batch[1])
</code></pre>
<p>When i am executing 2nd code block each time sys... | <p>Setting shuffle=True will randomize the data order. Looking at the documentation, you could set shuffle=False to sort the data alphanumerically, or use a seed to ensure your shuffles stay constant, i.e.</p>
<pre><code>dataset=tf.keras.preprocessing.image_dataset_from_directory(
"PlantVillage",
shuffle=... | python|tensorflow|keras|deep-learning | 0 |
6,162 | 69,343,228 | Grouping a column based on values on other columns to create new columns in pandas | <p>I have a dataframe which looks something like this:</p>
<pre><code>dfA
name group country registration
X engg Thailand True
A engg Peru True
B engg Nan False
H IT Nan False
J IT India F... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.any.html" rel="nofollow norefer... | python|pandas|pandas-groupby | 1 |
6,163 | 40,879,967 | How to use Batch Normalization correctly in tensorflow? | <p>I had tried several versions of batch_normalization in tensorflow, but none of them worked! The results were all incorrect when I set batch_size = 1 at inference time.</p>
<p>Version 1: directly use the official version in tensorflow.contrib</p>
<pre><code>from tensorflow.contrib.layers.python.layers.layers import... | <p>I have tested that the following simplified implementation of batch normalization gives the same result as <code>tf.contrib.layers.batch_norm</code> as long as the setting is the same.</p>
<pre><code>def initialize_batch_norm(scope, depth):
with tf.variable_scope(scope) as bnscope:
gamma = tf.get_varia... | tensorflow|deep-learning | 8 |
6,164 | 54,044,781 | openpyxl changes number format of columns in un-altered worksheet of the same file | <p>I've noticed that when I use openpyxl to add an extra sheet to a .xlsx file, it automatically alters the number format of column(s) in a pre-existent sheet in this file.</p>
<p>Chronologically, the problem is as follows:</p>
<p>1) I use a "timestamp" format to record by hand the date and time of some events of int... | <p>possible partial solution: </p>
<p>Use read only when opening the workbook. Save the output to a new excel file.
workbook = openpyxl.load_workbook(filename='name.xlsx', read_only=True)</p>
<p>My problem: 2 font cells change to 1 font cells.</p> | python|excel|pandas|openpyxl|datetime-format | 1 |
6,165 | 38,292,340 | How to count rows not values in python pandas? | <p>I would like to group DataFrame by some field like</p>
<pre><code>student_data.groupby(['passed'])
</code></pre>
<p>and then count number of rows inside each group. </p>
<p>I know how to count values like</p>
<pre><code>student_data.groupby(['passed'])['passed'].count()
</code></pre>
<p>or</p>
<pre><code>stude... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> with parameter <code>dropna=False</code>:</p>
<pre><code>import pandas as pd
import numpy as np
student_data = pd.DataFrame({'passed':[1,1,2,2,2,np.nan,np.nan]})
pri... | python|pandas | 3 |
6,166 | 38,177,549 | How does one implement a subsampled RBF (Radial Basis Function) in Numpy? | <p>I was trying to implement a Radial Basis Function in Python and Numpy as describe by <a href="http://work.caltech.edu/slides/slides16.pdf" rel="nofollow noreferrer">CalTech lecture here</a>. The mathematics seems clear to me so I find it strange that its not working (or it seems to not work). The idea is simple, one... | <h3>Scaling of interpolating functions</h3>
<p>The main problem is unfortunate choice of standard deviation of the functions used for interpolation:</p>
<pre><code>stddev = 100
</code></pre>
<p>The features of your functions (its humps) are of size about 1. So, use</p>
<pre><code>stddev = 1
</code></pre>
<h3>Order... | python|numpy|machine-learning|neural-network | 4 |
6,167 | 38,382,497 | Numpy recarray indexing by column truncates floats | <p>In a simple recarray in python, the output value is getting truncated when indexed by column name:</p>
<pre><code>import numpy #1.10.0
arr = numpy.zeros(1, dtype=[('a', np.float)])
arr[0]['a'] = 0.1234567891234
print arr
print arr['a']
[(0.1234567891234,)]
[ 0.12345679]
</code></pre>
<p>Why does this happen? Can ... | <p>The print precision for a numeric array is 8 digits:</p>
<pre><code>In [250]: np.get_printoptions()
Out[250]:
{'edgeitems': 3,
'formatter': None,
'infstr': 'inf',
'linewidth': 75,
'nanstr': 'nan',
'precision': 8,
'suppress': False,
'threshold': 1000}
</code></pre>
<p>But it doesn't use that value when disp... | python|numpy | 1 |
6,168 | 38,387,765 | Loop over columns to cleanse the values | <p>I have many columns in my pandas data frame which I want to cleanse with a specific method. I want to see if there is a way to do this in one go.</p>
<p>This is what I tried and this does not work.</p>
<pre><code>list = list(bigtable) # this list has all the columns i want to cleanse
for index in list:
bigtab... | <p>try this should work:</p>
<pre><code>bigtable1=pd.Dataframe()
for index in list:
bigtable1[index] = bigtable[index].str.split(',', expand=True).apply(lambda x: pd.Series(np.sort(x)).str.cat(sep=','), axis=1)
</code></pre> | python|pandas | 1 |
6,169 | 66,304,853 | Calculate weight using normal distribution in Python | <p>I have to add a weight column in the titanic dataset to calculate adult passengers' weight using a normal distribution with std = 20 and mean = 70 kg. I have tried this code:</p>
<pre><code>df['Weight'] = np.random.normal(20, 70, size=891)
df['Weight'].fillna(df['Weight'].iloc[0], inplace=True)
</code></pre>
<p>but ... | <ol>
<li><p>Range of a Normal distribution is not restricted. It spans all across real numbers. If you want to restrict it, you should do it manually or use other distributions.</p>
<pre><code>df['Weight'] = np.random.normal(20, 70, size=891)
df.loc[df['Weight'] < min_value, 'Weight'] = min_value
df.loc[df['Weight']... | python|dataframe|numpy|scipy|normal-distribution | 0 |
6,170 | 65,941,521 | automatic detection of matrix size, numpy | <p>I created a code that adds a value of 10 in each column. But it's only created for an array that has 3 rows.
I have more matrix in a cycle with different dimensions
Is it possible to do this so that I don't have to constantly forward the number of columns or rows, but to do so it automatically finds out the number o... | <p>If you want the multiple of tens to be added to be proportional to the column number (as in your answer), you can make a <code>range</code> based on the number of columns and multiply by 10:</p>
<pre><code>>>> np.arange(1, c1.shape[1]+1)*10
array([10, 20, 30])
>>> c1 + np.arange(1, c1.shape[1]+1)... | python|arrays|numpy | 2 |
6,171 | 66,117,362 | Python Pandas Delete empty cells | <p>I'm trying to delete empty cells with pandas. I wanna delete only empty cells but I have no idea how to do that.</p>
<p>ex</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
<th>F</th>
<th>G</th>
<th>H</th>
<th>I</th>
<th>J</th>
</tr>
</the... | <p>I made it with this</p>
<p><a href="https://stackoverflow.com/questions/61569994/removing-nan-from-pandas-dataframe-and-reshaping-dataframe">Removing nan from pandas dataframe and reshaping dataframe</a></p>
<p>Keypoint : Change Invalid_val with len of value strings</p> | python|excel|pandas|dataframe | 0 |
6,172 | 66,169,726 | How to ignore empty columns in a dataframe?(Pandas) | <p>I want to ignore empty columns in a dataframe.</p>
<p>For Example:</p>
<p>sample.csv</p>
<pre><code>Id Name Address Contact Item Rate Qty Price
1 Mark California 98429102 Shirt 57 2 8
2 Andre Michigan 92010211
</code></pre>
<p>I have tried:</p>
<pre><code>import pandas as pd
df = pd.read_csv... | <p>Just use a memory buffer and <code>strip()</code></p>
<pre><code>import io
df = pd.read_csv(io.StringIO("""1*Mark*California*98429102*Shirt*57*2*8
2*Andre*Michigan*92010211****"""), sep="*", header=None)
with open("sample.csv", "w") as f:
f.write(&quo... | python|python-3.x|pandas|dataframe|numpy | 2 |
6,173 | 46,217,242 | Creating arrays quickly from a dataframe with lots of values? | <ol>
<li>I have a large dataframe (imported from a csv file via pandas) with lots of values (259 rows × 27 columns). The index are months starting from January 1996 through to July 2017.</li>
</ol>
<p><a href="https://i.stack.imgur.com/Fx1Cl.png" rel="nofollow noreferrer">Image of my dataframe</a></p>
<ol start="2">
<l... | <p>You can use:</p>
<pre><code>np.random.seed(458)
cols = ['K37L', 'K37M', 'K37N', 'K37P', 'K37Q', 'K37R', 'K37S', 'K37T', 'K37U','K37V', 'K37W', 'K37X', 'K37Y', 'K37Z', 'K382', 'K383', 'K384', 'K385', 'K386', 'K387', 'K388', 'K389', 'K38A', 'K38B', 'K38C', 'K38D', 'K38E']
idx = pd.date_range('1996-01-01', periods=259... | python|python-3.x|pandas|numpy|dataframe | 1 |
6,174 | 58,530,882 | Group by in Pandas to find Median | <p>I have a properties dataset. I would like to know the median price according to several attributes as follows:
<code>suburb</code>,<code>rooms</code>,<code>bathrooms</code>,<code>type</code>,<code>car</code>,<code>age</code>. Then I want to add a new boolean column to state if the property is overpriced or not. </p>... | <p>Like this</p>
<pre class="lang-py prettyprint-override"><code>def over_price(elements):
median = np.median(elements)
return elements > median
house["OverPrice"] = house.groupby(["subrub","rooms","bathroom","type","car","age"])["price"].transform(over_price)
</code></pre> | python|pandas | 0 |
6,175 | 58,402,887 | How to vectorize custom algorithms in numpy or pytorch? | <p>Suppose I have two matrices:</p>
<pre><code>A: size k x m
B: size m x n
</code></pre>
<p>Using a custom operation, my output will be <code>k x n.</code></p>
<p>This custom operation is not a dot product between the rows of <code>A</code> and columns of <code>B</code>. <strong>Suppose</strong> this custom operati... | <p>Apart from the method @hpaulj outlines in the comments, you can also use the fact that what you are calculating is essentially a pair-wise Minkowski distance:</p>
<pre><code>import numpy as np
from scipy.spatial.distance import cdist
k,m,n = 10,20,30
A = np.random.random((k,m))
B = np.random.random((m,n))
method1... | python|numpy|vectorization|pytorch | 1 |
6,176 | 69,126,255 | Python, Numpy: copying single rows to multiple indexes in irregular order | <p>I have a problem where I need to copy single rows of one matrix to multiple specific rows in a bigger matrix. For example:</p>
<pre><code> Matrix A:
[row1]
[row2]
[row3]
</code></pre>
<p>Copied to</p>
<pre><code> Matrix B:
[row3]
... | <p>I am not sure if this is what you are looking for but it looks decently fast</p>
<pre><code>%%timeit
A = np.matrix([[1,2],[3,4],[5,6]])
Alist = A.tolist()
B = np.matrix([Alist[2],Alist[2],Alist[1],Alist[1],Alist[2],Alist[0]])
13.4 µs ± 82.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre... | python|arrays|numpy|matrix|copy | 0 |
6,177 | 44,816,922 | Pandas multi indexing not working | <p>I have below code, </p>
<pre><code>purchase_1 = pd.Series({'Name': 'Chris', 'Item Purchased': 'Dog Food',
'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter',
'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod', 'Item Purchased': 'Bird See... | <p>You forget assign <code>df</code>:</p>
<pre><code>df['location'] = df.index
#assign back to df
df = df.set_index(['location', 'Name'])
df = df.append(pd.Series(data={'Cost': 3.00, 'Item Purchased': 'Kitty Food'},
name=('Store 2', 'Kevyn')))
print (df)
Cost Item Purchased
loc... | pandas | 0 |
6,178 | 60,858,780 | Dict of cluster and partition with kmeans python | <p>I search a solution to my problem.</p>
<p>I use Kmeans by sklearn and i want a dictionary with <code>{ cluster : list of partition}</code></p>
<pre><code>kmeans = KMeans(n_clusters=n)
kmeans.fit(data)
result = zip(data,kmeans.labels_)
sortedR = sorted(result,key=lambda x: x[1])
cluster_nb = {}
for k,v in sortedR... | <p>Try this:</p>
<pre><code>from sklearn.cluster import KMeans
import numpy as np
data = np.random.randint(100, size=(100, 2))
kmeans = KMeans(n_clusters=5)
kmeans.fit(data)
centroids_partitions = {}
for centr in kmeans.cluster_centers_:
centroid_label = kmeans.predict([centr])
partition = []
for k, v in... | python|arrays|numpy|dictionary|k-means | 0 |
6,179 | 61,138,390 | Get dummy variables from a string column full of mess | <p>I'm a less-than-a-week beginner in Python and Data sciences, so please forgive me if these questions seem obvious.</p>
<p>I've scraped data on a website, but the result is unfortunately not very well formatted and I can't use it without transformation.</p>
<p><strong>My Data</strong></p>
<p>I have a string column... | <p>I think one way to do this would be:</p>
<pre><code>df.loc[df['My messy strings colum'].str.contains("bluetooth", na=False),'Bluetooth'] = 1
df.loc[~(df['My messy strings colum'].str.contains("bluetooth", na=False)),'Bluetooth'] = 0
df.loc[df['My messy strings colum'].str.contains("climatisation", na=False),'Clima... | python|regex|pandas|dummy-variable | 0 |
6,180 | 61,065,720 | Substraction of pandas dataframe | <p>I am trying to subtract 2 dataframes but I am not getting what I want and afterward, I would like to divide the difference by the values of a third dataframe.</p>
<p>For the first part, I have tried to do: </p>
<pre class="lang-py prettyprint-override"><code>r.sub(rf, fill_value=0)
</code></pre>
<p>And to be sure... | <p>Note that according to your image:</p>
<ul>
<li>you have <strong>only one</strong> DataFrame (say <em>df</em>) with <strong>two columns</strong>,</li>
<li>you write about <strong>subtraction</strong> of them, but the second value is
<strong>negative</strong>.</li>
</ul>
<p>So run:</p>
<pre><code>df['Brent Oil'] +... | python|pandas|dataframe|subtraction | 0 |
6,181 | 71,749,056 | How can I divide each array by the first value in that array in an array of arrays | <p>I have 4 labels listed and a corresponding 4 arrays listed for four different conditions containing relevant data.</p>
<p>I'm trying to write a loop that will go through 4 arrays(the conditions) of 4 arrays(for the 4 labels)and divide each array by the first value of that array, subtract 1, and *100 (each item in th... | <p>This should do I guess:</p>
<pre><code>def per_herg_block(i,base,negative,x):
return negative - (i/base) *x
for i in range(len(drug_name)):
o9 = per_herg_block(ord_90, ord_90[i][0], 1, 100)
print(o9)
</code></pre> | python|arrays|numpy|for-loop|calculation | 0 |
6,182 | 71,743,275 | Python index error: too many indices for array | <p>I am trying to code a plot with this code:</p>
<pre><code> for k in range(5):
plt.scatter(np.arange(0,200),cprofit[:,k],label = marketshare)
a = pd.Series([np.mean(cprofit[:,k]), np.std(cprofit[:,k]), np.max(cprofit[:,k]), np.min(cprofit[:,k])], index=df.columns)
df = df.appe... | <p>The two inputs of <code>plt.scatter()</code> should be of the same dimension, and size. You have <code>numpy.arange(0, 200)</code> creating a 1-dimensional array of size 200, and it's unclear what <code>cprofit[:,k]</code> is doing, but it seems to be slicing a large 2-D array, which may or may not produce a 1-D arr... | python|arrays|python-3.x|pandas|numpy | 0 |
6,183 | 71,712,054 | How do I change PyCharm output so it shows all yahoo finance data when using company.history()? | <p>I am using yahoo finance in python and when I run the following code:</p>
<pre><code>print(apple.history('max'))
</code></pre>
<p>It gives me this output:</p>
<pre class="lang-none prettyprint-override"><code> Open High ... Dividends Stock Splits
Date ... ... | <p><code>ticker.history()</code> returns a Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer">DataFrame</a>. You can access any column using the column name e. g. <code>'Low'</code>. A primer on indexing and selecting data can be found in the <a href="https://p... | python|pandas|yahoo-finance|yfinance | 0 |
6,184 | 42,247,358 | How do I check if a pandas Series is merely initialised (i.e. empty) or defined? | <p>I'd like to distinguish between a pandas Series that has merely been initialised, and one that has actually been defined and has values. I tried the following code, but it doesn't work.</p>
<pre><code>import pandas as pd
labels = pd.Series
print len(labels)
print labels.empty
</code></pre>
<p>I get:</p>
<ul>
<li>... | <p>In the first instance you took a reference to the method <code>Series</code>:</p>
<pre><code>In [31]:
labels = pd.Series
print(type(labels))
labels = pd.Series
print(type(labels))
<class 'type'>
</code></pre>
<p>hence all the errors, you want empty parentheses to make an empty series:</p>
<pre><code>In [33... | python|pandas | 1 |
6,185 | 69,702,449 | Get rid of NaT and duplicates from a pandas dataFrame to obtain a series of datetime values | <p>I have a dataframe that looks like shown picture <a href="https://i.stack.imgur.com/wk0aS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wk0aS.png" alt="enter image description here" /></a></p>
<p>Dataframe shape is (1944,900).
Each row of the dataframe has one value (it might be repeated multipl... | <p>it looks like you could just get the values from the diagonal of this array right? If so, then assuming your dataframe is called <code>df</code></p>
<pre><code>df.values[range(len(df)), range(len(df))]
</code></pre>
<p>will give you a numpy array of these values you want</p> | python|pandas|dataframe|datetime | 0 |
6,186 | 69,765,548 | Get original values from rolling sum in Pandas DataFrame | <p>I got data describing the number of newly hospitalized persons for specific days and regions.
The number of hospitalized persons is the rolling sum of new hospitalized persons for the last 7 days.
The DataFrame looks like this:</p>
<pre><code>Date Region sum_of_last_7_days
01.01.2020 1 1
02.... | <p>To get the original, perform a <code>diff</code> and fill with the first value:</p>
<pre><code>s = df.groupby('Region')['sum_of_last_7_days'].diff()
df['original'] = s.mask(s.isna(), df['sum_of_last_7_days'])
</code></pre>
<p>output:</p>
<pre><code> Date Region sum_of_last_7_days original
0 01.01.2020 ... | python|pandas|dataframe|rolling-computation | 2 |
6,187 | 69,977,726 | Why am i getting the error: list' object has no attribute 'replace'. I need to put my answer in a list without the character \xa0 | <p>Here is my code:</p>
<pre><code>df_olympics = pandas.read_csv("Olympics_data.csv", sep = ";")
df_olympics.drop(df_olympics.tail(1).index,inplace=True)
df_olympics= df_olympics[(df_olympics[' summer_games_played'] >0) & (df_olympics['winter_games_played'] >0)]
df_olympics['total_medals_... | <p>Try this:</p>
<pre><code>team_list_name_clean = [x.replace('\xa0', '') for x in team_name]
</code></pre> | python|pandas|dataframe | 1 |
6,188 | 43,393,164 | Extract sub-DataFrames | <p>I have this kind of dataframe in Pandas :</p>
<pre><code>NaN
1
NaN
452
1175
12
NaN
NaN
NaN
145
125
NaN
1259
2178
2514
1
</code></pre>
<p>On the other hand I have this other dataframe :</p>
<pre><code>1
2
3
4
5
6
</code></pre>
<p>I would like to separate the first one into differents sub-dataframes like this:</p>... | <p><strong>UPDATE:</strong> thanks to <a href="https://stackoverflow.com/questions/43393164/extract-sub-dataframes/43393492?noredirect=1#comment73848980_43393492">@piRSquared</a> for pointing out that the solution above will not work for DFs/Series with non-numeric indexes. Here is more generic solution:</p>
<pre><cod... | python|pandas | 2 |
6,189 | 72,230,482 | Signal correlation shift and lag correct only if arrays subtracted by mean | <p>If I have two arrays that are identical except for a shift:</p>
<pre><code>import numpy as np
from scipy import signal
x = [4,4,4,4,6,8,10,8,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4]
y = [4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,6,8,10,8,6,4,4]
</code></pre>
<p>And I want to quantify this shift through a cross-correlation:</p>
<pre><co... | <p>the issue is as you are doing 'full' correlation, the algorithm add zeros to complete the vectors. which mean that you will have the highest value when both signal are align in the convolution
here both example with and without the mean suppression</p>
<pre><code>import numpy as np
from scipy import signal
import ma... | python|numpy|scipy|correlation|cross-correlation | 2 |
6,190 | 72,184,641 | Python/Pandas - Combine two columns with NaN values | <p>Lets say i have a dataframe with two columns: OldValue and NewValue</p>
<p>i want to do some plotting and i want to combine values. If OldValue is empty, NewValue is filled, and the other way around. There is not a single instance both or neither are filled.
Lets say my dataframe looks like this:</p>
<pre><code> Ol... | <p>Your solution should be change with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.add.html" rel="nofollow noreferrer"><code>Series.add</code></a> and <code>fill_value=0</code>:</p>
<pre><code>df["AllValues"] = df["Newvalues"].add(df["OldValues"], fill_... | python|pandas|dataframe | 4 |
6,191 | 72,164,620 | Data Extraction in Python | <p>I've been given a data set consisting of three columns. One column has transaction information, one has a store number, and one has sections. My goal is to extract the store number from the transaction information column for 300 different stores using entity extraction. My thought process behind this was to make som... | <p>try this :</p>
<pre><code>df['c'] = df['transaction_descriptor'].apply(lambda x: (df[df['transaction_descriptor'].str.contains(x)]['store_number']))[0]
for index,row in df.loc[df['c'].isna(),:].iterrows():
test_=df.loc[index,'store_number']
test=df.loc[index,'transaction_descriptor']
result=[s for s in t... | python|pandas|nlp|named-entity-extraction | 1 |
6,192 | 50,459,267 | In eager mode, how to convert a tensor to a ndarray | <p>How can I convert a tensor to a numpy array in eager mode?
In eager mode, I do not need to create a session, so I cannot use <code>.eval()</code>.</p>
<p>And I tried <code>tf.constant()</code>, it gives the following error:</p>
<p><code>TypeError: Failed to convert object of type <class 'tensorflow.python.ops.v... | <p>Simpy call the <code>numpy</code> method:</p>
<pre><code>filters_C.numpy()
</code></pre>
<p>It is a <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/ops.py#L723" rel="nofollow noreferrer">property of the <code>EagerTensor</code> class</a>, which is the subclass of <code>Ten... | python|tensorflow | 2 |
6,193 | 50,373,813 | Aggregate columns with same date (sum) | <p>So, i need to aggregate rows where the date is the same.</p>
<p>My code, as of now, returns the following:</p>
<pre><code> date value source
0 2018-04-08 15:52:26.110 1 ANAPRO
1 2018-04-22 12:14:38.807 1 ANAPRO
2 2018-04-22 12:34:18.403 1 ANAPRO
3 2018-04-22 12:40:35.87... | <p>IIUC, you might want <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>pandas.Series.dt.date</code></a>:</p>
<pre><code>df['date'] = pandas.to_datetime(df['date']).dt.date
>>> df
date value source
0 2018-04-08 1 AN... | python|excel|pandas|xlsx|xlsxwriter | 3 |
6,194 | 50,400,038 | Warning in NumPy when setting array element to NaN using Spyder | <p>I am running Python 3.6.4 with Anaconda and Spyder.</p>
<p>When I am trying to set a value of a NumPy array to NaN I am getting the following RuntimeWarning.</p>
<pre><code>a = numpy.array([5.0,2.0,1.0])
a[0] = numpy.nan
</code></pre>
<blockquote>
<p>C:\Users..\Anaconda3\lib\site-packages\numpy\core_methods.py:29:
... | <p>I have updated the NumPy version and everything works fine now.</p> | python|numpy|nan|spyder | 2 |
6,195 | 50,283,088 | Cut a bounding box using numpy meshgrid python | <p>I want to create a bounding box out of the following dimensions using meshgrid but just not able to get the right box. </p>
<p>My parent dimensions are <code>x = 0 to 19541</code> and <code>y = 0 to 14394</code>. Out of that, I want to cut a box from x' = 4692 to 12720 and <code>y' = 4273 to 10117</code>.</p>
<p>H... | <p>I think you got it almost right in the first attempt, in the second one you're building a <code>meshgrid</code> for the full image while you just want the shape mask, don't you?</p>
<pre><code>import numpy as np
import matplotlib as mpl
from matplotlib.path import Path
from matplotlib import patches
import matplotl... | python-2.7|numpy|matplotlib|polygon|bounding-box | 2 |
6,196 | 45,720,331 | Getting NaN's in mutiple columns after pivoting | <p>I need to pivot a dataframe (dfM) which looks something like</p>
<pre><code>Task Question Answer analystID
x a 1 u
y b 2 i
z c 3 o
</code></pre>
<p>I want to pivot it so that the analyst IDs are the headers and the Answers are what is filled under the headers, with the ... | <p>One way you can see what is wrong with your 'Answer' column,<br>
is to find the letters in the strings that are not numerics</p>
<pre><code>dfm= pd.DataFrame({'Answer': ['1', '2 ', '3o', '1,000']})
def find_non_num(x):
uniq= set(str(x))
nums= set(['1','2','3','4','5','6','7','8','9','0'])
return uniq -... | python|pandas | 0 |
6,197 | 45,612,077 | Creating vector of tensorflow nodes efficiently | <p>Lets say I have the following function in python, that gets tensorflow variable x and some constant y and as output it returns node, that depends in some way on those two. </p>
<pre><code>import tensorflow as tf
x = tf.Variable(3.0)
y = {"a" : 3, "b" : 1.0}
def make_graph(x, y):
return y["a"] * x**2 + y["b"]... | <p>The answer depends on the function that you are applying. In your example, you could do something like this:</p>
<pre><code>import tensorflow as tf
x = tf.Variable(3.0)
y = {"a" : [3, 4, 5], "b" : [1.0, 2.0, 3.0]}
def make_graph(x, y):
return tf.reduce_sum(y["a"] * x**2 + y["b"], axis=0)
f = make_graph(x, y... | python|tensorflow | 1 |
6,198 | 45,671,466 | Distributed Tensorflow reload model failed | <p>I use tensorflow distributed, <strong>store model with codes</strong>:</p>
<pre><code>hooks=[tf.train.StopAtStepHook(last_step=1000000)]
with tf.train.MonitoredTrainingSession(master=server.target,
is_chief=is_chief,
check... | <p>You need to clear device assignments when you load the graph, ie</p>
<pre><code>tf.train.import_meta_graph('...', clear_devices=True)
</code></pre> | python|tensorflow|distributed | 1 |
6,199 | 45,670,487 | numpy.cov() exception: 'float' object has no attribute 'shape' | <p>I have a dataset for different plant species, and I separated each species into a different <code>np.array</code>.</p>
<p>When trying to generate gaussian models out of these species, I had to calculate the means and covariance matrices for each different label. </p>
<p>The problem is: when using <code>np.cov()</c... | <p>The error is reproducible if the array is of <code>dtype=object</code>:</p>
<pre><code>import numpy as np
label0 = np.random.random((50, 3)).astype(object)
np.cov(label0, rowvar=False)
</code></pre>
<blockquote>
<p>AttributeError: 'float' object has no attribute 'shape'</p>
</blockquote>
<p>If possible you sh... | python|arrays|numpy|attributeerror | 30 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.