Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
7,300 | 60,353,610 | Lookup child rows in a single DataFrame without using loops | <p>Currently I'm trying to extract meaninful data from a ticket system (Redmine). One of my tasks hereof is to find <strong>all</strong> the child tickets from a list of tickets which interest me. Since the children are of the same shape as their parents, live in the same DataFrame - so I cannot use <code>pd.merge</cod... | <p>The biggest performance bottleneck in your code is array-matching. Searching an array is an <code>O(n)</code> operation. Repeat it for each element in another array makes the operation <code>O(n*m)</code>. For faster result, lookup a dictionary instead, whose look up time is always <code>O(1)</code>.</p>
<p>And the... | python|pandas|data-analysis | 1 |
7,301 | 72,609,186 | Find overlap start date and end date in Pandas Groupby | <p>I am trying to find when the overlap start and when it ended in following DF.</p>
<p>I am able to determine the overlap cluster using below code, and now I want to find out when the overlap begins and when it ends</p>
<pre><code> d = [
{'G1': 'A', 'G2': 'A1','Start_Date': '6/1/2020', 'End_Date': '5/31/2022'},... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>def fn(x):
z = (
x.apply(
lambda y: pd.date_range(y["Start_Date"], y["End_Date"]),
axis=1,
)
.explode()
.sort_values()
)
y = z[z.duplicated()]
y = y[(y.diff() != pd.Ti... | python|pandas|dataframe|group-by|overlap | 2 |
7,302 | 59,859,154 | ZeroDivisionError: float division by zero (Solving colebrook (nonlinear) equation with Newton Raphson method in python) | <p>I have tried solving the colebrook (nonlinear) equation for frictional factor in python but I keep getting this error:</p>
<p>ZeroDivisionError: float division by zero</p>
<p>here is the full traceback:</p>
<pre><code>Traceback (most recent call last):
File "c:/Users/BDG/Desktop/kkk/www/Plots/jjj/Code.py", line... | <p>Your problem is in this line:</p>
<pre><code>return -0.86*np.log((e_D/3.7)+((2.51/Re))*f**(-0.5))-f**(-0.5)
</code></pre>
<p>When <code>Re</code> is 0 this fails. This happens because of:</p>
<pre><code>for re in range(len(Re)):
f = Newton(f0,re)
</code></pre>
<p>I think what you wish to do instead is:</p>
... | python|numpy|matplotlib|physics|newtons-method | 2 |
7,303 | 40,332,284 | How to divide 1 column into 5 segments with pandas and python? | <p>I have a list of 1 column and 50 rows.
I want to divide it into 5 segments. And each segment has to become a column of a dataframe. I do not want the NAN to appear (figure2). How can I solve that?
Like this:
<a href="https://i.stack.imgur.com/IxSbn.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/IxSbn.jpg" a... | <p>You can use numpy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow">reshape</a> function:</p>
<pre><code>result_list = [i for i in range(50)]
pd.DataFrame(np.reshape(result_list, (10, 5), order='F'))
Out:
0 1 2 3 4
0 0 10 20 30 40
1 1 11 21 31 4... | python-3.x|pandas|numpy | 1 |
7,304 | 40,643,819 | Pandas N-Grams to Columns | <p>Given the following data frame:</p>
<pre><code>import pandas as pd
d=['Hello', 'Helloworld']
f=pd.DataFrame({'strings':d})
f
strings
0 Hello
1 Helloworld
</code></pre>
<p>I'd like to split each string into chunks of 3 characters and use those as headers to create a matrix of 1s or 0s, depending on if a giv... | <pre><code>def str_chunk(s, k):
i, j = 0, k
while j <= len(s):
yield s[i:j]
i, j = j, j + k
def chunkit(s, k):
return [_ for _ in str_chunk(s, k)]
def count_chunks(s, k):
return pd.value_counts(chunkit(s, k))
</code></pre>
<hr>
<p><strong><em>demonstration</em></strong> </p>
<pr... | python|pandas | 2 |
7,305 | 61,760,231 | Add data to cell based on other cell values | <p>I have a large group of data with various names and sources, in a large dataframe.</p>
<p>Reproducible data by <a href="https://stackoverflow.com/users/12696163/anshul-jain">Anshul Jain</a></p>
<pre class="lang-py prettyprint-override"><code>First_Name Last_Name Source
Matt Jones XX
James ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> to group the dataframe by the columns <code>First Name</code> and <code>Last Name</code> and then apply the <code>agg</code> function <code>join<... | python|python-3.x|pandas | 3 |
7,306 | 61,844,846 | Numpy push non-zero values down along the column | <p>I have a 2D numpy matrix and I want to push all non-zero values down along the columns.
I prefer a way that doesn't contain loops.
for example making this <a href="https://i.stack.imgur.com/tDMag.jpg" rel="nofollow noreferrer">before_matrix</a>
into this <a href="https://i.stack.imgur.com/AezUU.jpg" rel="nofollow no... | <p>Use stable argsort on the binarized array</p>
<pre><code># make example
>>> from scipy import sparse
>>>
>>> exmpl = sparse.random(5,4,0.5).A
>>>
>>> exmpl
array([[0. , 0. , 0.61062949, 0. ],
[0.85030071, 0.81443545, 0. , 0.82208658],... | python|numpy|scipy | 1 |
7,307 | 61,752,679 | Convert a datetime to time with miliseconds in Python | <p>I got a DataFrame:</p>
<pre><code>client datetime
1 01/02/2020 13:47
2 02/02/2020 23:45
3 03/02/2020 16:22
4 04/02/2020 18:49
5 05/02/2020 11:02
</code></pre>
<p>and I need two new columns ["time_new"] to display the time in this format ('%H:%M:%S.%f')[:-3] and ["time_ms"] to displ... | <p>For extract custom format with times and miliseconds use:</p>
<pre><code>df['datetime'] = pd.to_datetime(df['datetime'])
df['time_new'] = df['datetime'].dt.strftime('%H:%M:%S.%f').str[:-3]
df['time_ms'] = df['datetime'].dt.microsecond // 1000
#in source df are 0 second and milisecond, so output like this
print (df... | python|python-3.x|pandas|datetime | 0 |
7,308 | 61,762,748 | Is there a way to use operator.itemgetter with slice notation? | <p>I have a bunch of numpy arrays in a python list <code>lst</code>. I can slice one of these arrays to get a specific view by indexing it with <code>[:, 1]</code>, for example. </p>
<p>I need to apply this slicing operation to all the numpy arrays in <code>lst</code>. Using generator comprehension, I could do: </p>
... | <p>The slice syntax generates <code>slice</code> objects for you. You'll have to create them explicitly to pass to <code>itemgetter</code>. Since <code>itemgetter(x,y)(a)</code> is equivalent to <code>(a[x], a[y])</code>, you also need to use parentheses to ensure that you pass a single <code>tuple</code> consisting of... | python|numpy|slice | 3 |
7,309 | 58,021,925 | tensorflow: how to use flags.DEFINE_multi_float() | <p>I use bash code to run a python file with lots of parameters. like:</p>
<pre><code>python "${WORK_DIR}"/eval.py \
--logtostderr \
--eval_split="val" \
--model_variant="xception_65" \
--atrous_rates=6 \
--atrous_rates=12 \
--atrous_rates=18 \
--output_stride=16 \
--decoder_output_stride=4 \
--eval_... | <p>for multi float you should define your parameters length(your-list) times.</p>
<p>if you have a list like this [0.5,0.25], you should define --eval_scales 2 times for each value present into your list:</p>
<p>--eval_scales=0.5</p>
<p>--eval_scales=0.25</p> | python|tensorflow | 0 |
7,310 | 57,992,962 | Sum column which has both numbers and text using Pandas | <p>I have a column which contains both numbers and text, and I'm trying to find the sum of the values.</p>
<p>I tried this sum function below, but it didn't work. Please can you advise what else I could try?</p>
<pre><code>df["Price"].sum()
</code></pre>
<p><a href="https://i.stack.imgur.com/4Vvxh.png" rel="nofollo... | <p>Use <code>pd.to_numeric</code></p>
<p><strong>Ex:</strong></p>
<pre><code>df = pd.DataFrame({"Price": ["Nil", "Na", 1,2,3,4,5, "Null"]})
print(df[pd.to_numeric(df['Price'], errors='coerce').notnull()].sum())
#or
print(pd.to_numeric(df['Price'], errors='coerce').dropna().sum())
</code></pre>
<p><strong>Output:</s... | python|excel|pandas|sum | 4 |
7,311 | 58,016,236 | how to groupby and aggregate dynamic columns in pandas | <p>I have following dataframe in pandas</p>
<pre><code>code tank nozzle_1 nozzle_2 nozzle_var nozzle_sale
123 1 1 1 10 10
123 1 2 2 12 10
123 2 1 1 10 10
123 2 2 ... | <p>How about:</p>
<pre><code>df.filter(regex='_cumsum').groupby(df['tank']).last()
</code></pre>
<p>Output:</p>
<pre><code> nozzle_1_cumsum nozzle_2_cumsum nozzle_sale_cumsum
tank
1 4 4 30
2 ... | python|pandas | 2 |
7,312 | 57,893,230 | How to aggregate data by counts of a level, setting each level's counts as its own column? | <p>I have data which has a row granularity in terms of events, and I want to aggregate them by a customer ID. The data is in the form of a pandas df and looks like so:</p>
<pre><code>| Event ID | Cust ID | P1 | P2 | P3 | P4 |
------------------------------------------
| 1 | 1 | 12 | 0 | 0 | 0 |
----------------... | <p>You can use the following method:</p>
<pre><code>df = pd.DataFrame({'Event ID':[1,2,3,4,5],
'Cust ID':[1]*3+[2]*2,
'P1':[12,12,10,206,25],
'P2':[0,0,12,0,0],
'P3':[0]*5,
'P4':[0]*5})
df.melt(['Event ID','Cust ID'])\
.groupb... | python|pandas|aggregate | 0 |
7,313 | 58,089,000 | eroding several layers of an array | <p>I'm having trouble understanding scipy's <code>binary_erosion</code> function.</p>
<pre><code>from scipy.ndimage import binary_erosion
a = np.zeros([12,12])
a[1:11,1:11]=1
binary_erosion(a).astype(int)
</code></pre>
<p>this removes the outermost edges, but what if I want to remove the second layer as well? I know ... | <p>Use the <code>iterations</code> option to have it repeat <code>n</code> times (remove additional layers): [<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.binary_erosion.html" rel="nofollow noreferrer">source</a>]</p>
<blockquote>
<p>iterations : <em>int</em>, optional<br>
The erosio... | python|arrays|numpy|scipy | 1 |
7,314 | 58,002,476 | Pandas apply : function prototype for automatic column unpacking | <p>Is there a way I can use to make a function unpack the columns automatically with df.apply method?</p>
<p>Ideally, I am looking for a way to define the function such that it automatically unpacks regardless of the number of columns in the data frame and allows me to use the column names as variables directly
Someth... | <p>If you use <code>apply</code> with a function and <code>axis=1</code> then the columns are already accessible by their names.</p>
<pre><code>def print_columns(row):
print('Column 1:', row['col1'])
print('Column 2:', row['col2'])
df.apply(print_columns, axis=1)
</code></pre>
<p>From the <code>row</code> ... | python|pandas|apply | 0 |
7,315 | 58,094,088 | Conditional merge on in pandas | <p>My question in simple I am using pd.merge to merge two df .
Here's the line of code:</p>
<p><code>pivoted = pd.merge(pivoted, concerned_data, on='A')</code></p>
<p>and I want the on='B' whenever a row has column A value as null. Is there a possible way to do this?</p>
<p>Edit:</p>
<p>As an example if</p>
<pre><... | <p>You could create a third column in your <code>pandas.DataFrame</code> which incorporates this logic and merge on this one.</p>
<p>For example, create dummy data</p>
<pre><code>df1 = pd.DataFrame({"A" : [1, None], "B" : [1, 2], "Val1" : ["a", "b"]})
df2 = pd.DataFrame({"A" : [1, 2], "B" : [None, 2], "Val2" : ["c", ... | pandas | 1 |
7,316 | 36,768,889 | LinearDiscriminantAnalysis - Single column output from .transform(X) | <p>I have been successfully playing around with replicating one of the <a href="http://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_vs_lda.html#example-decomposition-plot-pca-vs-lda-py" rel="nofollow">sklearn tutorials</a> using the iris dataset in PyCharm using Python 2.7. However, when trying to repe... | <p>The array <code>y</code> in the example you posted has values of 0, 1 and 2 while yours only has values of 0 and 1. This change achieves what you want:</p>
<pre><code>import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
y = np.random.randint(3, size=500)
X = np.random.randint(1, ... | python|python-2.7|numpy|scikit-learn|pycharm | 2 |
7,317 | 54,911,646 | tensorflow : loop value in placeholder shape [None] | <p>My question is as follows: if I have a placeholder with shape of <code>'None'</code>, how can I write the code in tensorflow to loop the value of shape of <code>'None'</code>? For example, given a a placeholder, if I predefined the shape, I can write: </p>
<pre><code>[i for i in range(placeholder.shape[0].value)]
... | <p>Maybe you can use tf.scan:</p>
<pre><code>import numpy as np
import tensorflow as tf
tf.InteractiveSession()
placeholder = tf.placeholder(dtype=tf.int32) # The shape of the placeholder is unknown for now
def fn(_, x):
y = 2 * x # Do something with this value
return y
shape = tf.scan(fn, tf.shape(placeholder)... | python|tensorflow | 0 |
7,318 | 27,993,058 | Pandas apply to dateframe produces '<built-in method values of ...' | <p>I'm trying to build a <a href="http://geojson.org/geojson-spec.html#examples" rel="noreferrer">GeoJSON object</a>. My input is a csv with an address column, a lat column, and a lon column. I then created Shapely points out of the coordinates , buffer them out by a given radius, and get the dictionary of coordinates ... | <p>Thanks, DSM, for pointing that out. Lesson learned: pandas is not good for arbitrary Python objects</p>
<p>So this is what I wound up doing:</p>
<pre><code>temp = zip(list(data.geom), list(data.address))
output = map(lambda x: {'geometry': x[0], 'properties':{'address':x[1]}}, temp)
</code></pre> | python|pandas|apply|geojson|shapely | 3 |
7,319 | 73,504,379 | Key error for Level Values Raise Key Error(key) | <p>Anyone know why I am getting a Level_Values raise KeyError, my guess is there are too many of the same date value? or something. I can see the values when I do a .get('new date') it just won't sort the column:</p>
<p>df = pd.read_csv("Status 9 Data.csv", header=0, sep=",")</p>
<p>##df.columns = [... | <p>The Error you should pass in <code>by</code> the name of the column <code>new date</code> not the data like <code>df["new date"]</code></p>
<pre><code>df.sort_values(by='new date', inplace=True, ascending=False)
</code></pre> | pandas | 0 |
7,320 | 73,274,016 | unable to concat the output for multiple rows | <p>I have a dataframe which is like below</p>
<p><a href="https://i.stack.imgur.com/Dq2uW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dq2uW.png" alt="enter image description here" /></a></p>
<p>If i write a code like below</p>
<pre><code>df.iloc[0]
</code></pre>
<p><a href="https://i.stack.imgur.... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with comprehension:</p>
<pre><code>df1 = pd.concat((df.loc[i] for i in df.index))
</code></pre>
<p>Or:</p>
<pre><code>df1 = pd.concat((df.iloc[i] for i in range(len(df.index)))... | python|python-3.x|pandas|list|dataframe | 1 |
7,321 | 73,322,872 | How can I save result from groupby in a new column? | <p>I have a dataframe</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>key1</th>
<th>key2</th>
<th>key3</th>
<th>value1</th>
<th>value2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>a</td>
<td>s2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>a</td>
<td>s2</td>
<td>2</td>
<td>3</td>
... | <p>use groupby and transform to return the sum of individual columns</p>
<pre><code>df[['sum_value1','sum_value2']]=df.groupby(['key1','key2','key3'])[['value1','value2']].transform(sum)
df
</code></pre>
<pre><code> key1 key2 key3 value1 value2 sum_value1 sum_value2
0 1 a s2 3 ... | python|pandas|dataframe|group-by|sum | 0 |
7,322 | 30,972,588 | Columns name dropped on append in pandas | <p>WinPython: pandas 0.16.1, py3.4</p>
<pre><code>df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']},
index=[0, 1, 2, 3])
df1.columns.names=["hello... | <p>The <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.append.html" rel="nofollow"><code>DataFrame.append</code> method</a> is not as good as the <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow"><code>pandas.concat</code> function</a> for this purpose.</p>
... | python|pandas | 1 |
7,323 | 67,509,823 | Concat Read Excel Pandas | <p>I'm needing to read in an excel file and read all sheets inside that excel file.</p>
<p>I've tried:</p>
<pre><code>sample_df = pd.concat(pd.read_excel("sample_master.xlsx", sheet_name=None), ignore_index=True)
</code></pre>
<p>This code worked, but it's suddenly giving me this error:</p>
<pre><code>TypeErr... | <p>First, you will want to know all of the sheets that need to be read in. Second, you will want to iterate over each sheet.</p>
<ol>
<li><em>Getting Sheet names</em>.- You can get a list of the sheet names in a workbook with <code>sheets = pd.ExcelFile(path).sheet_names</code>, where <code>path</code> is the full path... | python|pandas | 0 |
7,324 | 60,329,555 | fastest way to replace values in an array with the value in the same position in another array if they match a condition | <p>I'm trying this syntaxis to replace values in an array with the value in the same position in another array if they match a condition:</p>
<pre><code>array[array>limit]=other_array[array>limit]
</code></pre>
<p>It works but I think I might be doing it the hard way. Any thoughts?</p> | <p>Use <a href="https://numpy.org/doc/1.18/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a>:</p>
<blockquote>
<p>Parameters</p>
<p>condition: array_like, bool</p>
<pre><code> Where True, yield x, otherwise yield y.
</code></pre>
<p>x, y: array_like</p>
<pre><cod... | python|arrays|numpy|indexing|replace | 2 |
7,325 | 60,260,753 | Join two dataframes to get cartesian product | <p>How to join two dataframes and get the cartesian product of all rows in both dataframes.</p>
<p>df1:</p>
<pre><code> values
0 4
1 5
2 6
</code></pre>
<p>df2:</p>
<pre><code> values
0 7
1 8
2 9
</code></pre>
<p>Expected Output:</p>
<pre><code> values_x values_y
0 ... | <p>You can use a dummy column to merge on:</p>
<pre><code>df1.assign(dummy=1).merge(df2.assign(dummy=1), on='dummy', how='outer').drop('dummy', axis=1)
</code></pre>
<p>Output:</p>
<pre><code> values_x values_y
0 4 7
1 4 8
2 4 9
3 5 7
4 5 ... | python|pandas|dataframe|merge|cartesian-product | 2 |
7,326 | 60,056,340 | How to get the unique pairs from the given data frame column with file handling? | <p>sample data from dataframe:
<a href="https://i.stack.imgur.com/7csTt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7csTt.png" alt="sample data from dataframe" /></a></p>
<h1>Pairs</h1>
<pre><code>(8, 8), (8, 8), (8, 8), (8, 8), (8, 8)
(6, 7), (7, 7), (7, 7), (7, 6), (6, 7)
(2, 12), (12, 3), (3, ... | <p>You could use the <strong>set</strong> method:</p>
<pre><code>data = (((8, 8), (8, 8), (8, 8), (8, 8), (8, 8)),
((6, 7), (7, 7), (7, 7), (7, 6), (6, 7)),
((2, 12), (12, 3), (3, 4), (4, 12), (12, 12)))
uniques = []
for col in data:
for unique in list(set(col)):
uniques.append(unique)
for x in uniques:
... | python|pandas|data-science | 1 |
7,327 | 65,345,723 | start date is first day of month, end date is subsequent month first day Pandas | <p>I'm looking to iterate through a date range where start_date and end_date increment on a monthly basis with each iteration starting at the beginning of the month.</p>
<p>First iteration example:</p>
<pre><code>start_date = '2020-01-01'
end_date = '2020-02-01'
</code></pre>
<p>The second iteration of the loop should ... | <pre><code>start_date = pd.to_datetime('2020-02-01')
end_date = pd.to_datetime('2020-03-01')
for x in range(20):
print(start_date.strftime('%Y-%m-%d'))
print(end_date.strftime('%Y-%m-%d'))
# do the work here...
# then increment the dates for the next iteration
start_date = start_date + pd.of... | python-3.x|pandas|date | 0 |
7,328 | 65,185,165 | Filling column with values (pandas) | <p>I have a problem filling in values in a column with pandas. I want to add strings which should describe the annual income class of a customer. I want 20% of the length of the data frame to get the value "Lowest", 9% of the data frame should get "Lower Middle" etc... I thought of creating a list a... | <p>You can use <code>numpy</code> to do a weighted choice. The method has a list of choices, the number of choices to make, and the probabilities. You could generate this and just do <code>df['Annual Income'] = incomes</code></p>
<p>I've printed out the value counts so you can see what the totals were. It will be sl... | python|pandas|dataframe|dataset|data-science | 1 |
7,329 | 65,243,260 | PYTHON pandas Is there a way to dynamically delete rows from pandas dataframe WHILE writing it to CSV to free memory? | <p>I have several huge dataframes, and I'm writing multithreaded functions to write them to disk as .csv but it takes a really long time and I want that memory back so I can go get more huge dataframes while these slowly write.</p>
<p>Is it possible to use pandas to:</p>
<ol>
<li>write a chunk</li>
<li>delete those row... | <p>I am not quite sure how this works under the hood - but assume that chunksize parameter might be what you are looking for.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">Pandas docs</a></p> | python|pandas|dataframe | 0 |
7,330 | 65,481,370 | Size mismatch in tensorflow_federated eager executor | <p>I am following this code <a href="https://github.com/BUAA-BDA/FedShapley/tree/master/TensorflowFL" rel="nofollow noreferrer">https://github.com/BUAA-BDA/FedShapley/tree/master/TensorflowFL</a> and trying to run the file same_OR.py</p>
<p>there is a problem in <code>import tensorflow.compat.v1</code> as tf its show t... | <p>It looks like this is a case of mismatched tensor shapes, specifcially its expecting a shape of <code>float32[784,10]</code> but the argument is shape<code>float32[10]</code>.</p>
<p>Near the end of the stack trace the key line appears to be:</p>
<pre class="lang-py prettyprint-override"><code>File "C:\Users\Aw... | python|tensorflow|machine-learning|tensorflow-federated|federated-learning | 0 |
7,331 | 65,320,693 | iterate rows of a column and remove all text after specific words in python | <p>Is there a way in python to remove all text if a specific combination of words is found in a row?
I have six different combinations of words after which the text should be deleted ('from the manufacturer' is an example). I want to iterate over rows of a column and remove all the text found after these words.</p>
<pr... | <p>Try the following, using a lambda function:</p>
<pre><code>list_of_words = ['Descrizione Prodotto', 'Produktbeschreibung des Herstellers', 'Description du fabricant', 'From the manufacturer', 'Descripción Prodotto']
def clear(x):
for i in list_of_words:
if i in x:
x=x[:x.find(i)+len(i)]
... | python|pandas | 1 |
7,332 | 65,338,973 | Pandas Move text in column | <p>I have a data frame that contains search results. Is it possible to move the text around in the column so that the the name is always first?</p>
<pre><code>Results
'Phil Spencer', 'Microsoft'
'Larry Hryb', 'Microsoft'
'Microsoft', 'Bill Gates'
'Sony', 'Kenichiro, Yoshida'
'Sony', 'PS5', 'Howard Stringer'
</code></pr... | <p>Quite a tough one, but we could assume that anything with a <code>space</code> is a name and try to order it that way.</p>
<p>First let's split by <code>,</code> that only proceeds after <code>'</code> and is followed by a space <code>\s</code></p>
<hr />
<pre><code>s = df['Results'].str.split("',\s",expan... | python|pandas|dataframe | 3 |
7,333 | 50,137,837 | Pandas DataFrame mean with object | <p>I have a dataframe with 2 column nbr and tag. Nbr contain integer and tag contain Tag object. </p>
<p>And I want to get the mean of all the tag object (using value attribute, and the result is a new Tag with that value).</p>
<p>For <code>dataframe.add</code> I had the add a the <code>__add__</code> method to the T... | <p>Looking at the source code, it seems like Pandas's mean coerces the results to a numeric type. </p>
<p>You can get close by adding the <a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow noreferrer">special <code>__float__</code> method</a> to <code>Tag</code>:</p>
<pre><code>import pandas a... | python|pandas|object|mean | 2 |
7,334 | 50,175,706 | Binary Arrays: Determine if all 1s in one array come before first 1 in the other | <p>I've been working on an interesting problem and figured I should post about it on here. The problem is the following:</p>
<p>You are given two arrays, A and B, such that the elements of each array are 0 or 1. The goal is to figure out if all the 1s in A come before the first 1 in B. <em>You can assume that all 1s a... | <p>If you check out <a href="https://stackoverflow.com/questions/8768540/how-to-find-last-occurrence-of-maximum-value-in-a-numpy-ndarray">this question</a> you can find how to get the index of the last "max" value in a numpy array. then check to see if that is less than the first 1 in B and you are good. </p>
<pre><co... | python|algorithm|numpy|bit-manipulation|time-complexity | 0 |
7,335 | 49,831,784 | Filter groups after GroupBy in pandas while keeping the groups | <p>in pandas I want to do:
<code>df.groupby('A').filter(lambda x: x.name > 0)</code> - group by column <code>A</code> and then filter groups that have the value of the name non positive. However this canceles the grouping as <code>GroupBy.filter</code> returns <code>DataFrame</code> and thus losing the groupings. I ... | <p>I think the previous answers propose workarounds, which are maybe useful in your case but doesn't answer the question. </p>
<p>You created groups, and you want to throw out or keep some groups based on group statistics THEN perform some group statistics you actually care for on the groups. This should be possible, ... | python|pandas|pandas-groupby | 6 |
7,336 | 64,136,603 | How to deal with categorical data that has 35 unique values? | <p>I am working on IPL cricket dataset which has data about batting stats for all the teams over by over.</p>
<p>I want to visualise how different cricket grounds affect the total score of the batting team. I try to plot a simple scatter plot but the stadium names are too long and it does not show the names clearly.</p... | <p>You can change the size of the font and/or rotate it: <a href="https://matplotlib.org/api/matplotlib_configuration_api.html#matplotlib.rc" rel="nofollow noreferrer">https://matplotlib.org/api/matplotlib_configuration_api.html#matplotlib.rc</a></p> | python|pandas|matplotlib|data-science|categorical-data | 1 |
7,337 | 63,937,996 | Python sliding MinMaxScaler on last 100 values | <p>I now have a normalization across the entire column:</p>
<pre><code>MinMaxScaler().fit_transform(Glfeatures[['Temp']])
</code></pre>
<p>How to get a column without for, where for each value is normalized to 100 values to it?</p>
<p>For example:</p>
<pre><code>Glfeatures['Temp'][200] minmaxnormalizing on Glfeatures['... | <p>This is an old question but I stumbled across it trying to accomplish the same thing.</p>
<p>Here is my solution as suggested in the comments above:</p>
<pre><code>def min_max(df, window):
def func(data):
x = data.values
return (x[-1] - min(x)) / (max(x) - min(x))
return d... | python|pandas | 1 |
7,338 | 46,862,662 | Getting error 'str' object has no attribute 'dtype' when exporting textsum model for TensorFlow Serving | <p>I am currently trying to get a TF textsum model exported using the PREDICT SIGNATURE. I have _Decode returning a result from a passed in test article string and then I pass that to buildTensorInfo. This is in-fact a string being returned. </p>
<p>Now when I run the textsum_export.py logic to export the model, it g... | <p>PREDICT signature work with tensors, if res is 'str' type python variable, then res_tensor will be of dtype tf.string</p>
<pre><code>res_tensor = tf.convert_to_tensor(res)
</code></pre> | tensorflow|tensorflow-serving | 4 |
7,339 | 46,964,319 | How do select 2nd column or a matrix from a pandas dataframe? | <p>How do you select column other than the first column?</p>
<pre><code>import pandas as pd
df = pd.read_csv('bio.csv')
df
</code></pre>
<p><a href="https://i.stack.imgur.com/qDf6G.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qDf6G.jpg" alt="Output 1"></a></p>
<p>I could select the first column... | <p>Below is the complete answer</p>
<pre><code>import pandas as pd
df = pd.read_csv('bio.csv', sep='[ \t]*,[ \t]*', engine='python')
df['Height']
</code></pre>
<p>Theis is the output:</p>
<pre><code>Out[22]: 0 65.78
1 71.52
2 69.40
3 68.22
4 67.79
... | pandas | 0 |
7,340 | 47,082,071 | Trying to add results to an array in Python | <p>I have 2 matrixes and I want to safe the euclidean distance of each row in an array so afterwards I can work with the data (knn Kneighbours, I use a temporal named K so I can create later a matrix of that array (2 columns x n rows, each row will contain the distance from position n of the array, in this case, k is t... | <p>You are trying to assign data to a function call, which is not possible. If you want to add the data computed by <code>linalg.norm()</code> to the array <code>distancias</code> you can do like shown below.</p>
<pre><code>import numpy as np
v1=np.matrix('1,2;3,4')
v2=np.matrix('5,6;7,8')
k=0
distancias = []
for ... | python|numpy | 2 |
7,341 | 46,855,114 | Poor quality classifier in Tflearn? | <p>I am new to machine learning and trying out <em>TFlearn</em> because it is simple.</p>
<p>I am trying to make a basic classifier which I find interesting.
My objective is to train the system to predict in which direction a point lies.</p>
<p>For example If I feed two 2D co-ordinates <code>(50,50)</code> and <code>... | <p>As discussed in my comment above, here is code that trains a multi-layer perceptron classifier model using <a href="https://github.com/nicholastoddsmith/pythonml/blob/master/TFANN.py" rel="nofollow noreferrer">a MLP helper class I created</a>. The class is implemented using TensorFlow and follows the scikit-learn fi... | machine-learning|tensorflow|classification|tflearn | 1 |
7,342 | 46,880,050 | Attempting to find the 5 largest values per month using groupby | <p>I am attempting to show the top three values of <code>nc_type</code> for each month. I tried using <code>n_largest</code> but that doesn't do it by date.</p>
<p>Original Data:</p>
<pre><code> area nc_type occurred_date
0 Filling x ... | <p><strong>Scenario 1</strong><br>
<em>MultiIndex series</em></p>
<pre><code>occurred_date nc_type
1.0 x 3
y 4
z 13
w 24
f 34
12.0 d 18
g 10
w... | python|pandas|group-by | 1 |
7,343 | 46,698,020 | Reorganize pandas data frame to display data horizontal | <p>I have a data frame that displays which segments a particular organization belongs to. I want to prep the data frame for a left join merge on Org ID with other organization data. </p>
<p>Current, this df displays info top to bottom with each segment (with org id) in a separate row. Below is a sample of the df and a... | <p>You can use <code>pd.crosstab</code>:</p>
<pre><code>df = df.drop_duplicates()
pd.crosstab([df['Org ID'], df['Org Name']], df['Segment']).reset_index()
</code></pre>
<hr>
<p><em>Example</em>:</p>
<pre><code>df = pd.DataFrame({
'A': ['a', 'a', 'b', 'b', 'c'],
'B': [1, 2, 2, 3, 4],
'C': ['seg1', 'seg1'... | python|python-3.x|pandas | 2 |
7,344 | 32,869,110 | Can Pandas Groupby Aggregate into a List of Objects | <p>While panda's <code>groupby</code> is able to aggregate data with functions like <code>sum</code> and <code>mean</code>, is there a way to aggregate into a list of objects, where the keys of these objects corresponds to the column names these values were aggregated from?</p>
<p><strong>Question:</strong></p>
<p>If... | <p>I actually wasn't sure this would work, but seems to.</p>
<pre><code>In [35]: df.groupby('A').apply(lambda x: x.to_dict(orient='records'))
Out[35]:
A
1 [{u'A': 1, u'C': 22, u'B': 10}, {u'A': 1, u'C'...
2 [{u'A': 2, u'C': 13, u'B': 11}, {u'A': 2, u'C'...
3 [{u'A': 3, u'C': 0, u'B': 14}]
... | python|python-2.7|pandas | 1 |
7,345 | 38,635,580 | Matrix of polynomial elements | <p>I am using NumPy for operations on matrices, to calculate matrixA * matrixB, the trace of the matrix, etc... And elements of my matrices are integers. But what I want to know is if there is possibility to work with matrices of polynomials. So for instance I can work with matrices such as <code>[x,y;a,b]</code>, not ... | <p>One option is to use the <a href="http://docs.sympy.org/dev/modules/matrices/matrices.html" rel="nofollow">SymPy Matrices module</a>. SymPy is a symbolic mathematics library for Python which is quite interoperable with NumPy, especially for simple matrix manipulation tasks such as this. </p>
<pre><code>>>>... | python|numpy|matrix|sympy | 2 |
7,346 | 38,572,914 | 3D tensor input to embedding layer in keras or tensorflow? | <p>I want to build a network which takes in sentences as input to predict the sentiment. So my input looks something like (num of samples x num of sentences x num of words). I then want to feed this in an embedding layer to learn the word vectors which can be then summed to get sentence vector. Is this type of architec... | <p>I guess this class resolves for Keras:</p>
<pre><code>class AnyShapeEmbedding(Embedding):
'''
This Embedding works with inputs of any number of dimensions.
This can be accomplished by simply changing the output shape computation.
'''
#@overrides
def compute_output_shape(self, input_shape):
... | python|tensorflow|keras | 2 |
7,347 | 38,644,441 | Splitting line and adding numbers to a numpy array | <p>I have several text files in a folder, all with data in the form of numbers, each separated by 3 spaces. There are no line breaks. I want to take the numbers, put them in order in a numpy array, and then reshape it to be a 240 by 240 array. (I have the correct number of data points in each file to do so.) Afterwards... | <p>It sounds like a number with reading one of the files. I'd suggest first doing a </p>
<pre><code> lines = file.readlines()
</code></pre>
<p>and making sure that the lines look right. You may also want to add a <code>strip</code></p>
<pre><code>In [244]: [int(x) for x in '121 342 123\n'.strip().split(' ')]
Ou... | python|arrays|python-3.x|numpy | 2 |
7,348 | 63,292,433 | Alternative to pandas iterrows? | <p>I'm building a trading bot that looks through a df of prices and sells, buys, or passes depending on the price relative to the bounds. Every transaction uses all funds available, so the other constraint is that you must have the stock in the bank to execute a sale and vice versa. Finally I want to add the relevant t... | <p>I would suggest using the <code>[numpy.where()][1]</code> function which is usually pretty fast especially if the conditions and manipulations aren't very complex. For your example it would look something like this:</p>
<pre><code>import numpy as np
prices['usd_bank'] = np.where((prices['sell_price'] > row['uppe... | python|pandas | 0 |
7,349 | 62,908,391 | 7 days hourly mean with pandas | <p>I need some help calculating a 7 days mean for every hour.</p>
<p>The timeseries has a hourly resolution and I need the 7 days mean for each hour e.g. for 13 o'clock</p>
<pre><code>date, x
2020-07-01 13:00 , 4
2020-07-01 14:00 , 3
.
.
.
2020-07-02 13:00 , 3
2020-07-02 14:00 , 7
.
.
.
</code></pre>
<p>I tried it with... | <p>Add a new <code>hour</code> column, grouping by <code>hour</code> column, and then add
The average was calculated over 7 days. This is consistent with the intent of the question.</p>
<pre><code>df['hour'] = df.index.hour
df = df.groupby(df.hour)['x'].rolling(7).mean().reset_index()
df.head(35)
hour level_1 x
0 ... | pandas|mean|rolling-computation | 1 |
7,350 | 67,910,484 | Multiple conditions in for-loop | <p>I want to loop through a data frame to check if one statement is stratified (before checking elif, I want the code goes through all the K values and if it is not satisfied check the elif):
I have the following data frame:</p>
<pre><code>z={'speed':[2.2,12.74,5.1,.91,8.9]}
data=pd.DataFrame(data=z)
</code></pre>
<p>I... | <p>Your <code>break</code> statement indentation is not correct. The code is always breaking the loop at the first <code>break</code>.
The code should be like this:</p>
<pre><code>import pandas as pd
z={'speed':[2.2, 2.74, 5.1, 9.1, 0.5]}
data=pd.DataFrame(data=z)
found = 0
for k in range(len(data['speed']) - 1, 0, -... | python|pandas|dataframe|for-loop|if-statement | 1 |
7,351 | 67,958,246 | How do you flatten the last two dimensions of an numpy array? | <p>For example, given a numpy array of dimensions (132, 82, 100), the resultant dimensions would be (132, 8200)</p> | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.reshape.html" rel="nofollow noreferrer">reshape()</a> function to change shape of the array. Using -1 as a parameter to reshape tells numpy to infer the dimension there.</p>
<pre><code>arr = np.zeros((132, 82, 100))
arr = arr.reshape(*arr.sh... | python|numpy | 0 |
7,352 | 32,000,987 | Converting Indices of Series to Columns | <p>I need to convert the Indices of a Series <code>amounts</code> into its Columns. For example, I need to convert:</p>
<pre><code> 1983-05-15 1
1983-11-15 1
1984-05-15 1
1984-11-15 101
</code></pre>
<p>into:</p>
<pre><code> 1983-05-15 1983-11-15 1984-05-15 19... | <p>Build a <code>DataFrame</code> out of your <code>Series</code>, then the <code>.T</code> property returns a transposed version.</p>
<pre><code>In [87]: pd.DataFrame(s).T
Out[87]:
1983-05-15 1983-11-15 1984-05-15 1984-11-15
0 1 1 1 101
</code></pre> | python|pandas | 3 |
7,353 | 32,073,927 | Test which Numpy function argument has more than one element | <p>Consider the following function:</p>
<pre><code>def foo(a, b, c):
""" Toy function
"""
return a, b, c
</code></pre>
<p>Each of these arguments will be of type <code>numpy.array</code>. I need to efficiently determine which of these arguments has more than one element for use further in the function. I... | <p>You can use <code>locals()</code> to get a <code>dict</code> of all the arguments, then use <code>size</code> and <code>argmax</code> to find which is largest, like so:</p>
<pre><code>import numpy as np
a=np.array([1,])
b=np.array([1,])
c=np.array([1,2,3])
def foo(a,b,c):
args=locals()
return args.items()... | python|numpy|arguments | 0 |
7,354 | 41,321,082 | Pandas - split large excel file | <p>I have an excel file with about 500,000 rows and I want to split it to several excel file, each with 50,000 rows.</p>
<p>I want to do it with pandas so it will be the quickest and easiest.</p>
<p>any ideas how to make it?</p>
<p>thank you for your help</p> | <p>Assuming that your Excel file has only one (first) sheet containing data, I'd make use of <code>chunksize</code> parameter:</p>
<pre><code>import pandas as pd
import numpy as np
i=0
for df in pd.read_excel(file_name, chunksize=50000):
df.to_excel('/path/to/file_{:02d}.xlsx'.format(i), index=False)
i += 1
</... | python|excel|pandas | 9 |
7,355 | 41,267,573 | Changing values of a function within a DataFrame | <p>I'm trying to create a function that removes the ' #1' from a column within a dataframe:</p>
<pre><code>def formatSignalColumn(df):
for i,signal in enumerate(df['Signal list']):
df = df.set_value(i, 'Signal list', signal.replace(" #1", ""))
df = df.set_value(i, 'Signal list', signal.replace(" #2... | <p>You can just use vectorised <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>str.replace</code></a> and pass a regex pattern to do this in a single line:</p>
<pre><code>In [231]:
df = pd.DataFrame({'something':[' #1blah', ' #2blah', '... | python|pandas|dataframe | 2 |
7,356 | 27,483,731 | Reorder pandas DataFrame with specific rules | <pre><code>XList=[2,3,4,5,5,6]
YList=['A','A','A','B','A','A']
df = pd.DataFrame({'X':XList,
'Y':YList})
df
X Y
0 10 A
1 3 A
2 4 A
3 5 B
4 5 A
5 6 A
</code></pre>
<p>How can I reorder only Line 3 and 4 (case: same X-Value) so they are in ascedent order in Y (A,B) like this:</... | <p>If you want to sort only those values of <code>YList</code> where <code>XList</code> values are equal, here is the code:</p>
<pre><code>>>> XList=[2,3,4,5,5,6]
>>> YList=['A','A','A','B','A','A']
>>> idx = []
>>> for i in range(len(XList)-1):
... if XList[i]==XList[i+1]: idx.a... | python|pandas|group-by | 1 |
7,357 | 61,588,717 | Fastest way to average sign-normalized segments of data with NumPy? | <p>What would be the fastest way to collect segments of data from a NumPy array at every point in a dataset, normalize them based on the sign (+ve/-ve) at the start of the segment, and average all segments together?</p>
<p>At present I have:</p>
<pre><code>import numpy as np
x0 = np.random.normal(0,1,5000) # Dataset... | <p>We can leverage <code>1D convolution</code> -</p>
<pre><code>np.convolve(x,np.sign(x[:-l+1][::-1]),'valid')/(len(x)-l+1)
</code></pre>
<p>The idea is to do the windowed summations with convolution and with a flipped kernel as per the <a href="https://en.wikipedia.org/wiki/Convolution" rel="nofollow noreferrer"><co... | python|performance|numpy|average | 2 |
7,358 | 68,639,336 | when padding I receive this error Dimension -343776 must be >= 0 [Op:Fill] | <p>When trying to pad the audio data by this code, I receive the error in the title</p>
<pre><code>zero_padding = tf.zeros([48000] - tf.shape(waveform), dtype=tf.float32)
</code></pre> | <p>Welcome! Have you checked the value of <code>tf.shape(waveform)</code>? It is probably 43776 + 48000 = 391776.</p>
<p>Here is the code to reproduce the error:</p>
<pre class="lang-py prettyprint-override"><code>tf.zeros([48000] - tf.shape(tf.zeros(391776)), dtype=tf.float32)
</code></pre> | python|tensorflow | 0 |
7,359 | 68,544,119 | 'For' loop: creating a new column which takes into account new data from several csv files | <p>I would like to automate a process which assigns labels of several files.
Accidentally, someone created many files (csv) that look like as follows:</p>
<p>filename 1: <code>test_1.csv</code></p>
<pre><code>Node Target Char1 Var2 Start
1 2 23.1 No 1
1 3 12.4 No 1
1 4 52.1 Yes 1
1... | <p>You can achieve that with <code>pd.concat</code> and the <code>keys</code>-argument (<a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#concatenating-objects" rel="nofollow noreferrer">docs</a>).</p>
<pre class="lang-py prettyprint-override"><code>frames = [df1, df2, ...] # your dataframes... | python|pandas|for-loop | 1 |
7,360 | 53,200,748 | Calculate the rotation angle of a vector python | <p>I am trying to find the rotation <code>angle</code> of a 2D <code>vector</code>. I have found a few questions that use 3D <code>vectors</code>. The following <code>df</code> represents a single <code>vector</code> with the first <code>row</code> as the origin.</p>
<pre><code>d = ({
'X' : [10,12.5,17,20,16... | <p>First you should move the origin to <code>(0, 0)</code>, then you can use <code>np.arctan2()</code> which calculates the angle and defines the quadrant correctly. The result is already in radians (theta) so you don't need it in degrees (alpha).</p>
<pre><code>d = {'X' : [10,12.5,17,20,16,14,13,8,7], ... | python|pandas|matrix|rotation | 1 |
7,361 | 53,335,939 | Count times a value of a column appears and add a column to the dataframe with it | <p>I have a dataframe with 4 columns, one of them being people's names and another one activity they practiced. I want that in front of each row appears the number of times that combination appears. All the ways i found of counting change the dataframe or reduce the size of the data frame, apearing each combination onl... | <h3><code>groupby</code> + <code>size</code></h3>
<p>Assuming your grouper columns are <code>0</code> and <code>2</code>:</p>
<pre><code>df['combination_count'] = df.groupby([0, 2])[1].transform('size')
</code></pre>
<p>To move the new column to the front:</p>
<pre><code>cols = df.columns.tolist()
cols.insert(0, co... | python|pandas|count|pandas-groupby | 1 |
7,362 | 65,632,248 | Same sentences produces a different vector in XLNet | <p>I have computed the vectors for two same sentences using <a href="https://github.com/amansrivastava17/embedding-as-service" rel="nofollow noreferrer">XLNet embedding-as-service</a>. But the model produces different vector embeddings for both the two same sentences hence the cosine similarity is not 1 and the Euclide... | <p>This is because of to the dropout layers in the model. During inference, the dropout layers should be turned off but there is a bug in the library. It is discussed here and apparently still not fixed.</p>
<p>See the discussion here: <a href="https://github.com/amansrivastava17/embedding-as-service/issues/45" rel="no... | python|nlp|huggingface-transformers|bert-language-model|sentence-transformers | 1 |
7,363 | 65,583,992 | Data augmentation on GPU | <p>As tf.data augmentations are executed only on CPUs. I need a way to run certain augmentations on the TPU for an audio project.<br />
For example,</p>
<blockquote>
<p>CPU: tf.recs read -> audio crop -> noise addition.<br />
TPU: spectogram -> Mixup Augmentation.</p>
</blockquote>
<p>Most augmentations can be... | <p>See the Tensorflow guide that discusses <a href="https://www.tensorflow.org/guide/keras/preprocessing_layers#preprocessing_data_before_the_model_or_inside_the_model" rel="nofollow noreferrer">preprocessing data before the model or inside the model</a>. By including preprocessing inside the model, the GPU is leverage... | tensorflow|keras|tensorflow2.0|keras-layer | 2 |
7,364 | 21,029,128 | updating pandas dataframe via for loops | <p>I have a bunch of URLs stored into a data frame and I am cleaning them up via a url parsing module. The issue that I am having is that the 'siteClean' field that is supposed to update with the cleaned url is updating the entire column and not the individual cell...</p>
<p>Here is the code:</p>
<pre><code>results ... | <p>In general, it's better to avoid looping over your frame's rows, if you can avoid it. If I understand your problem correctly, you want to look at a single column from your frame, and apply a function on each element of that column. Then you want to put the result of all those function calls into a column of the or... | python|for-loop|pandas|dataframe | 2 |
7,365 | 63,704,145 | How to remove a vector which is specific value from tensor in tensorflow? | <p>I want to implement the following operation.
Given a tensor,</p>
<pre><code>m = ([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
</code></pre>
<p>How to implement to remove the vector with value [2, 2, 2] from m?</p> | <p>You can do that like this:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
def remove_row(m, q):
# Assumes m is 2D
mask = tf.math.reduce_any(tf.not_equal(m, q), axis=-1)
return tf.boolean_mask(m, mask)
# Test
m = tf.constant([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
q = tf.constant... | python|tensorflow|tensorflow2.0 | 1 |
7,366 | 63,572,811 | deleting tuple elements based on condition | <p>Data frame with DST values:</p>
<pre><code>data0 = pd.DataFrame({'DST':[33,11,-52,7,80,34,41,68,-87],'Date':['1975-01-03','1975-01-04','1975-01-07','1975-01-08','1975-01-13','1975-01-14','1975-01-15','1975-02-01','1975-02-03']})
data0
DST Date
0 33 1975-01-03
1 11 1975-01-04
2 -52 1975-01-07
3 7... | <p>First filter rows by condition in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>data0['Date'] = pd.to_datetime(data0['Date'])
df = data0[data0['DST']<-50]
print (df)
DST Date
3 -... | python|pandas|numpy|date|math | 1 |
7,367 | 63,615,305 | I'm having a problem trying to load a Pytoch model: "Can't find Identity in module" | <p>When trying to load a pytorch model it gives the following attribute error</p>
<pre><code>model = torch.load('../input/melanoma-model/melanoma_model_0.pth')
model = model.to(device)
model.eval()
</code></pre>
<blockquote>
<p>AttributeError Traceback (most recent call
last) in
1 arch = Ef... | <p>First you need a model class to load the parameters from the .pth into. And you are missing one step:</p>
<pre class="lang-py prettyprint-override"><code>model = Model() # the model class (yours has probably another name)
model.load_state_dict(torch.load('../input/melanoma-model/melanoma_model_0.pth'))
model = mod... | python|model|pytorch | 2 |
7,368 | 21,512,042 | Fast selection of a time interval in a pandas DataFrame/Series | <p>my problem is that I want to filter a DataFrame to only include times within the interval <em>[start, end)</em> . If do not care about the day, I would like to filter only for start and end time for each day. I have a solution for this but it is slow. So my question is if there is a faster way to do the time based f... | <p>You need <code>between_time</code> method.</p>
<pre><code>In [14]: %timeit df.between_time(start_time='01:00', end_time='02:00')
100 loops, best of 3: 10.2 ms per loop
In [15]: %timeit selector=(df.index.hour>=1) & (df.index.hour<2); df[selector]
100 loops, best of 3: 18.2 ms per loop
</code></pre>
<p>I h... | python|indexing|pandas | 6 |
7,369 | 21,857,153 | Error with matplotlib when used with Unicode strings | <p>I have text file containing Unicode strings and their frequencies.</p>
<pre><code>അംഗങ്ങള്ക്ക് 10813
കുടുംബശ്രീ 10805
പരിരക്ഷാപദ്ധതിക്ക് 10778
ചെയ്തു 10718
ഇന്ന് 10716
അന്തര് 659
രാജിന്റെ 586
</code></pre>
<p>When I try to plot it using <code>matplotlib</code> </p>
<p>I am getting this erro... | <p>In order to read strings from a file using <code>loadtxt</code> you have to specify the <code>dtype</code> argument (see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow">docs</a> here).</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
data = np.loadtx... | python|numpy|unicode|matplotlib | 3 |
7,370 | 24,507,550 | Swapping Columns with NumPy arrays | <p>When I have <code>a=1</code> and <code>b=2</code>, I can write <code>a,b=b,a</code> so that <code>a</code> and <code>b</code> are interchanged with each other.</p>
<p>I use this matrix as an array:</p>
<pre><code> [ 1, 2, 0, -2]
[ 0, 0, 1, 2]
[ 0, 0, 0, 0]
</code></pre>
<p>Swapping the columns of ... | <p>If you're trying to swap columns you can do it by</p>
<pre><code>print x
x[:,[2,1]] = x[:,[1,2]]
print x
</code></pre>
<p><strong>output</strong></p>
<pre><code>[[ 1 2 0 -2]
[ 0 0 1 2]
[ 0 0 0 0]]
[[ 1 0 2 -2]
[ 0 1 0 2]
[ 0 0 0 0]]
</code></pre>
<p>The swapping method you mentioned in the qu... | python|arrays|numpy|iterable-unpacking | 25 |
7,371 | 30,109,522 | multi-monthly mean with pandas' Series | <p>I have a sequence of <code>datetime</code> objects and a series of data which spans through several years. A can create a <code>Series</code> object and resample it to group it by months:</p>
<pre><code>df=pd.Series(varv,index=dates)
multiMmean=df.resample("M", how='mean')
print multiMmean
</code></pre>
<p>This, h... | <p>the following worked for me:</p>
<pre><code># create some random data with datetime index spanning 17 months
s = pd.Series(index=pd.date_range(start=dt.datetime(2014,1,1), end = dt.datetime(2015,6,1)), data = np.random.randn(517))
In [25]:
# now calc the mean for each month
s.groupby(s.index.month).mean()
Out[25]:... | python|pandas|time-series | 12 |
7,372 | 29,929,646 | Reorder Stacked DataFrame | <p>I'm trying to reorder a stacked dataframe. For example, I have:</p>
<pre><code>import numpy as np
testdf = pd.DataFrame(np.random.randn(5,4), index=range(1,6), columns = ['Eric','Jane','Mary','Don'])
testdf.stack()
</code></pre>
<p>And my output is this:</p>
<pre><code>1 Eric -0.301206
Jane 1.327379
M... | <p>use <code>set_levels</code> on the index to reorder the values:</p>
<pre><code>In [67]:
t.index.set_levels([[1,2,3,4,5],['Eric', 'Don', 'Mary', 'Jane']], inplace=True)
t
Out[67]:
1 Eric 1.139358
Don -0.368389
Mary -1.907364
Jane 0.444930
2 Eric -0.113019
Don -0.823055
Mary -1.397... | python|pandas | 2 |
7,373 | 30,238,666 | Calculate difference from a reference row in pandas (python) | <p>In Pandas I have a data frame of this type:</p>
<pre><code> value
SampleGroup sample
Group1 ref 18.1
smp1 NaN
smp2 20.3
smp3 30.0
smp4 23.8
smp5 23.2
</code></pre>
<p>What I w... | <p>OK I knocked up the following which worked for me:</p>
<pre><code>In [327]:
t="""sample value
ref 18.1
smp1 NaN
smp2 20.3
smp3 30.0
smp4 23.8
smp5 23.2"""
df = pd.read_csv(io.StringIO(t), sep='\s+')
df
Out[327]:
sample... | python|pandas|row|dataframe | 2 |
7,374 | 53,776,756 | Create merged column and index column from 2 similar columns | <p>I have a DataFrame that looks like this: <code>{"Val1": [...], "Val2": [...]}</code>
What I now want to achieve is a DataFrame that looks like this: </p>
<pre><code>{
"Vals": [<should contain all vals from Val1 and Val2>],
"type": [<1 or 2 depending on the column from which
the corr... | <p>Say you have:</p>
<pre><code>df = pd.DataFrame({'val1':[1,2,3,4],'val2':[5,6,7,8]})
</code></pre>
<p>Using <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.melt.html" rel="nofollow noreferrer"><code>pd.melt()</code></a> you'll get what you want:</p>
<pre><code>df.melt(var_name='Type'... | python|pandas | 2 |
7,375 | 53,404,010 | element-wise merge np.array in multiple pandas column | <p>I got a pandas dataframe, in which there are several columns’ value are np.array, I would like to merge these np.arrays into one array elementwise based row. </p>
<p>e.g</p>
<pre><code> col1 col2 col3
[2.1, 3] [4, 4] [2, 3]
[4, 5] [6, 7] [9, 9]
[7, 8] [8, 9] [5,... | <p>You can use <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer">numpy.concatenate</a> with apply along axis=1:</p>
<pre><code>import numpy as np
df['col_f'] = df[['col1', 'col2', 'col3']].apply(np.concatenate, axis=1)
</code></pre>
<p>If those were... | python|pandas|numpy | 0 |
7,376 | 53,494,616 | Python - How to create a matrix with negative index position? | <p>I can create a normal matrix with numpy using </p>
<p><code>np.zeros([800, 200])</code></p>
<p>How can I create a matrix with a negative index - as in a 1600x200 matrix with row index from -800 to 800? </p> | <p>Not sure what you need it for but maybe you could use a dictionary instead.</p>
<pre><code>a={i:0 for i in range(-800,801)}
</code></pre>
<p>With this you can call <code>a[-800] to a[800]</code>.</p>
<p>For 2-D,</p>
<pre><code>a={(i,j):0 for i in range(-800,801) for j in range(-100,101)}
</code></pre>
<p>This c... | python|arrays|numpy|matrix | 1 |
7,377 | 53,724,668 | CNN Using Images With Significant Size Differences | <p>I developing a convolutional neural network (CNN) for image image classification. </p>
<p>The dataset available to me is relatively small (~35k images for both train and test sets). Each image in the dataset varies in size. The smallest image is 30 x 77 and the largest image is 1575 x 5959. </p>
<p>I saw this <a h... | <p>The first important thing is: will resizing deteriorate the images?</p>
<p>Are your desired elements in the image all reasonably in the same scale despite the image size? </p>
<ul>
<li>If yes, you should not resize, use models with variable input sizes (there is a minimum, though). </li>
<li>If no, Will resize... | python|tensorflow|keras|neural-network|computer-vision | 6 |
7,378 | 17,386,835 | Extending an existing matrix in scipy | <p>I have a N*N matrix:</p>
<pre><code>N=3
x = scipy.sparse.lil_matrix( (N,N) )
for _ in xrange(N):
x[random.randint(0,N-1),random.randint(0,N-1)]=random.randint(1,100)
</code></pre>
<p>Assume the matrix looks as below:</p>
<pre><code> X Y Z
X 0 [2,3] [1,4]
Y [2,3] 0 ... | <p>Looks like you are not assigning the output of the <code>todense()</code>. </p>
<p>Try:</p>
<pre><code>c_dense = c.todense()
sp.vstack([c_dense,sp.coo_matrix(1,3)])
</code></pre> | python|arrays|numpy|matrix|scipy | 0 |
7,379 | 20,317,157 | Arrays, plotting, fitting gaussian distribution for multiples on graph which represents a power spectrum | <p>This is the code I have done which reads in a data text file which has some metadata at the start. And then 2 columns of data which represent Angle 2 theta on the left column and Radiation count in the right column. My code looks for the value of wavelenght in metadata and stores it in a variable for later use, it t... | <p>Yes that is a suitable approach.</p>
<p>First some code to get you going (I tweaked your code):</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import math
figure = plt.figure()
def Gaussian(x, Geoms):
# Geoms is a n X 3 array:
# Position, Amplitude, FWHM
#Geoms = [[2,.00001,3][1,1... | python|arrays|numpy|plot|gaussian | 0 |
7,380 | 12,461,413 | Why does comparison of a numpy array with a list consume so much memory? | <p>This bit stung me recently. I solved it by removing all comparisons of numpy arrays with lists from the code. But why does the garbage collector miss to collect it?</p>
<p>Run this and watch it eat your memory:</p>
<pre><code>import numpy as np
r = np.random.rand(2)
l = []
while True:
r == l
</code></pre>
... | <p>Just in case someone stumbles on this and wonders...</p>
<p>@Dugal yes, I believe this is a memory leak in current numpy versions (Sept. 2012) that occurs when some Exceptions are raised (see <a href="http://projects.scipy.org/numpy/ticket/2216" rel="nofollow">this</a> and <a href="https://github.com/numpy/numpy/pu... | python|arrays|list|memory-management|numpy | 5 |
7,381 | 72,016,038 | Sum up values based condition, if does not match keep current values | <p>I am looking for a way to sum up the values > or < a certain threshold in a given column (here > 6 in days_install_to_event column).</p>
<p>I tried many different ways, such a loc, query or groupby, but it return only the values > 6 not the ones < 6.</p>
<p>Here some of the things I have tried:</p>
<p... | <p>As far as I know there is no out-of-the-box solution for this but you can get this result by creating a helper grouper column:</p>
<pre><code># Set days_install_to_event = 7+ if the value is larger than 6
grouper = df['days_install_to_event'].mask(df['days_install_to_event'] > 6, '7+')
</code></pre>
<p>Then, with... | python-3.x|pandas | 4 |
7,382 | 72,031,056 | is there a way that i can convert this dataframe into a datatype | <p>already clean a lot of information into this, and i'm feel stuck now, if anyone can give some ideas and how to proceed i will apreacite so much.</p>
<p><a href="https://i.stack.imgur.com/JetLJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JetLJ.png" alt="dates column" /></a></p>
<p>later i need ... | <p>As mentioned in the comment, you should make sure your dates are strings in order to concatenate them. You can do this like that:</p>
<pre><code>df.column_name = df.column_name.astype(str)
</code></pre>
<p>After that you can use <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow noreferrer">pyth... | python|pandas|datetime-format | 0 |
7,383 | 18,852,884 | Estimate Number Of Decimal Places of Time Series | <p>How do I estimate the number of decimal places for the numbers used inside a pandas time series?</p>
<p>e.g. for</p>
<pre><code>x=[1.01,1.01,1.03]
</code></pre>
<p>i would want</p>
<pre><code>in[0]: estimate_decimal_places(x)
out[0] : 2
</code></pre>
<p>e.g. for</p>
<pre><code>x=[1.1,1.5,2.0]
</code></pre>
... | <pre><code>def estimate_decimal_places(num):
return len(str(num).split(".")[1])
x=[1.1,1.01,1.001]
for num in x:
print estimate_decimal_places(num)
</code></pre>
<p>gives</p>
<pre><code>1
2
3
</code></pre> | python|numpy | 2 |
7,384 | 21,995,036 | How to shuffle together a matrix and a response vector | <p>I have a dataset <code>X</code>, <code>y</code> where <code>X</code> is a matrix of observation <code>n*p</code> and <code>y</code> a response vector <code>n*1</code>. </p>
<p>I would like to shuffle <code>y</code> and the rows of <code>X</code> without losing the "line by line" relation.</p>
<p>How can I do that ... | <p>You mean you want to keep the correspondence between rows in <code>X</code> and <code>y</code>? Generate random indices and index both arrays with them:</p>
<pre><code>>>> perm = np.random.permutation(X.shape[0])
>>> X = X[perm]
>>> y = y[perm]
</code></pre> | python|numpy|matrix|scipy|shuffle | 2 |
7,385 | 22,149,584 | What does axis in pandas mean? | <p>Here is my code to generate a dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
dff = pd.DataFrame(np.random.randn(1,2),columns=list('AB'))
</code></pre>
<p>then I got the dataframe:</p>
<pre><code>+------------+---------+--------+
| | A | B |
+------------+---------+--------... | <p>It specifies the axis <strong>along which</strong> the means are computed. By default <code>axis=0</code>. This is consistent with the <code>numpy.mean</code> usage when <code>axis</code> is specified <em>explicitly</em> (in <code>numpy.mean</code>, axis==None by default, which computes the mean value over the flatt... | python|pandas|numpy|dataframe | 488 |
7,386 | 18,204,134 | Install python-numpy in the Virtualenv environment | <p>I would like to install the python-numpy in the Virtualenv environment. My system is Ubuntu 12.04, and my python is 2.7.5. First I installed the Virtualenv by </p>
<pre><code>$ sudo apt-get install python-virtualenv
</code></pre>
<p>And then set up an environment by</p>
<pre><code>$ mkdir myproject
$ cd myproject... | <p><code>apt-get</code> will still install modules globally, even when you're in your new <code>virtualenv</code>.</p>
<p>You should either use <code>pip install numpy</code> from within your virtual environment (easiest way), or else compile and install <code>numpy</code> from source using the <code>setup.py</code> f... | python|numpy|ubuntu-12.04|virtualenv | 7 |
7,387 | 17,998,285 | Unexpected read_csv result with \W+ separator | <p>I have an input file I am trying to read into a pandas dataframe.
The file is space delimited, including white space before the first value.
I have tried both read_csv and read_table with a "\W+" regex as the separator. </p>
<p><code>data = pd.io.parsers.read_csv('file.txt',names=header,sep="\W+")</code></p>
<p>Th... | <p>The regex <code>'\W'</code> means "not a word character" (a "word character" being letters, digits, and underscores), see the <a href="http://docs.python.org/2/library/re.html" rel="nofollow">re docs</a>, hence the strange results. I think you meant to use whitespace <code>'\s+'</code>.</p>
<p>Note: <a href="http:/... | python|pandas | 2 |
7,388 | 55,564,896 | Pandas Python - Grouping counts to others | <p>I am conducting data analysis for a project using python and pandas where I have the following data:</p>
<p>The numbers are the count.</p>
<pre><code>USA: 5000
Canada: 7000
UK: 6000
France: 6500
Spain: 4000
Japan: 5
China: 7
Hong Kong: 10
Taiwan: 6
New Zealand: 8
South Africa: 11
</code></pre>
<p>My task is to ma... | <p>IIUC using <code>np.where</code> setting the boundary , then <code>groupby</code> + <code>sum</code> , notice here I am using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.groupby.htmlis" rel="nofollow noreferrer"><code>pandas.Series.groupby</code></a></p>
<pre><code>s=df['Countr... | python|pandas | 3 |
7,389 | 55,214,715 | Couldn't parse file content | <p>When I ran my Python code, I got the error message below. Can anyone help?</p>
<pre><code>Traceback (most recent call last):
File "/home/yangjy/PycharmProjects/mmi_anti_pytorch-master/language_model/lm.py", line 8, in <module>
import tensor
File "/home/yangjy/anaconda3/lib/python3.6/site-packages/ten... | <p>Same issue, finally I found that's my source proto file importing wrong proto files.</p>
<p>After referring to the right files, it is fixed.</p>
<pre><code>syntax = "proto3";
import "tensorflow/path_to_correct_files/file1.proto";
import "tensorflow/path_to_correct_files/file1.proto";
</... | python|tensorflow | 0 |
7,390 | 56,512,330 | Pytorch: how to repeat a parameter matrix into a bigger one along both dimensions? | <p>What is the simplest syntax to transform 2D parameter tensor</p>
<pre><code>A B
C D
</code></pre>
<p>into</p>
<pre><code>A A B B
A A B B
C C D D
C C D D
</code></pre>
<p>Note they are parameter tensors, so I need autograd to back propagate gradient from latter into former.
Thanks!</p> | <p>using einops (same code works with numpy and pytorch):</p>
<pre><code>z = einops.repeat(x, 'i j -> (i 2) (j 2)')
</code></pre> | pytorch | 0 |
7,391 | 56,447,078 | How to read bulk excel file data and load into spark dataframe in Databricks | <p>i want to read the bulk excel data which contains 800k records and 230 columns in it. I have read data using spark and pandas dataframe , but while reading the data using spark data frame i'm getting the following message.</p>
<blockquote>
<p>Message: The spark driver has stopped unexpectedly and is restarting. Y... | <p>Two things you can do is increase your memory on the cluster or use the max rows in memory option on the excel library to help stream a set amount of data:</p>
<p><code>.option("maxRowsInMemory", 20)</code></p> | python-3.x|pandas|pyspark|azure-databricks | 0 |
7,392 | 56,771,162 | Concatenating two columns in pandas dataframe without adding extra spaces at the end when the second column contains NaN/empty strings | <p>I have the following pandas data frame:</p>
<pre><code>> print(tpl_subset)
>
Fullname Infrasp Authorship
Lilium abchasicum NaN Baker
Lilium affine NaN Schult. & Schult.f.
Lilium akkusianu... | <p>Or use <code>np.where</code>:</p>
<pre><code>df['Tmp'] = np.where(df['Infrasp'].isnull(), df['Fullname'], df['Fullname'] + ' ' + df['Infrasp'])
</code></pre> | python|pandas | 3 |
7,393 | 56,485,097 | How to change the format of a number in a pandas column? | <p>I have a large DataFrame of numbers but each individual number follows a different format. I want to use a regular expression to replace a large amount of them with a 111-111-1111 format</p>
<pre><code>numbers["numbers"].replace('^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$, "/*/*/*-/*/*/*-/*/*/*/*", regex=... | <p>You may use</p>
<pre><code>df["numbers"] = df["numbers"].str.replace('^(?:\+\d{1,2}\s)?\(?(\d{3})\)?[\s.-]?(\d{3})[\s.-]?(\d{4})$', r'\1-\2-\3')
</code></pre>
<p><strong>Details</strong></p>
<ul>
<li><code>^</code> - start of string</li>
<li><code>(?:\+\d{1,2}\s)?</code> - an optional sequence of</li>
<li><code>\... | python|regex|python-3.x|pandas | 0 |
7,394 | 56,650,308 | Get min values between hours for each day | <p>I have a pandas time series dataframe with a value for each hour of the day over an extended period, like this:</p>
<pre><code> value
datetime
2018-01-01 00:00:00 38
2018-01-01 01:00:00 31
2018-01-01 02:00:00 78
2018-01-01 03:00:00 82
2018-01-01 04:00:00 83
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.between_time.html" rel="nofollow noreferrer"><code>DataFrame.between_time</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>DataFram... | python|pandas | 2 |
7,395 | 25,574,976 | Taking a tensor product in python numpy without performing a sum | <p>I have two tensors, each 2D, with a common long axis (eg 20.000) and diffenrent short axes eg one 9 the other 10). I want to end up with a 9X10X20000 tensor, such that for each location on the long axis, the other two axes are the tensor product.
Explicitly, with the "long" axis here 4, I want to do:</p>
<pre><code... | <p>I tend to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> for these problems, which makes it easy to specify what should happen in terms of the indices:</p>
<pre><code>>>> A = np.arange(8).reshape(2,4)
>>> B = np.arange(... | python|numpy | 3 |
7,396 | 25,471,180 | Disable silent conversions in numpy | <p>Is there a way to disable silent conversions in numpy?</p>
<pre><code>import numpy as np
a = np.empty(10, int)
a[2] = 4 # OK
a[3] = 4.9 # Will silently convert to 4, but I would prefer a TypeError
a[4] = 4j # TypeError: can't convert complex to long
</code></pre>
<p>Can <code>numpy.ndarray</code> objects ... | <p>Unfortunately <code>numpy</code> doesn't offer this feature in array creation, you can set if casting is allowed only when you are converting an array (check the documentation for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="nofollow"><code>numpy.ndarray.astype</code><... | python|numpy | 2 |
7,397 | 66,815,863 | What is the use of tensorflow backend utilities? | <p>In order to create custom loss functions, I have seen many people use backend functionality from tensorflow.<br />
For example if we want to create custom loss function that takes <code>y_true</code> and <code>y_pred</code> as input and compute square of difference between them. ie <code>MSE</code></p>
<p><strong>Co... | <p><code>tf.keras.backend</code> comes from the time where <code>keras</code> was a standalone library that was able to use different libraries such as TensorFlow, Theano or CNTK as a "backend", i.e as the librbary that would perform the computations. The goal was to able to write the same <code>keras</code> ... | python|tensorflow | 0 |
7,398 | 67,106,137 | cannot convert string to numbers in pandas.read_excel | <p><strong>Issue</strong></p>
<p>I have an excel file in German format. It looks like this
<a href="https://i.stack.imgur.com/I8Ady.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I8Ady.png" alt="enter image description here" /></a></p>
<p>I want to read the first column as numbers into pandas using ... | <p>Unfortunately, there is no way to tell pandas what decimal separator is being used.</p>
<p>What you could do though is create a function to do the conversion and pass it to read_excel as part of the converters argument.</p>
<pre><code>def fix_decimal(num):
### convert numeric value with comma as decimal separator to... | python|pandas | 2 |
7,399 | 47,340,607 | Tensorflow GradientBoostedDecisionTreeClassifier error : "Dense float feature must be a matrix" | <p>I am getting the error:</p>
<p><strong>“tensorflow.python.framework.errors_impl.InvalidArgumentError: Dense float feature must be a matrix.”</strong> when training with estimator <strong>tensorflow.contrib.boosted_trees.estimator_batch.estimator.GradientBoostedDecisionTreeClassifier</strong>. I am using Tensorflow ... | <p>I am guessing that the parsing spec created by tf.transform is different from what we normally get.
Can you share the output of transformed_metadata.schema.as_feature_spec()?</p>
<p>As a work-around try adding this line to your input_fn after features = tf.train.shuffle_batch(...):</p>
<p><code>
features = {featu... | python|machine-learning|tensorflow|google-cloud-platform|tensorflow-transform | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.