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 |
|---|---|---|---|---|---|---|
2,200 | 62,464,882 | Is there a way to divide multi index dataframe with a singled indexed dataframe? | <p>I have a multi-index series that looks like:</p>
<pre><code> Value1 Value2
Month Group Type
02 A Blue 2 3
Red 5 4
B Blue 4 7
Red 8 12
03 A Blue 9 22
... | <p>You need select column <code>Value</code> for divide by <code>Series</code> and add <code>axis=0</code> for compare by index:</p>
<pre><code>df = df.div(df2['Value'], level=0, axis=0)
print (df)
Value1 Value2
Month Group Type
2 A Blue 1.0 1.5
Red 2... | python|pandas|dataframe|division|multi-index | 2 |
2,201 | 62,356,994 | How to split an array into unequal parts according to a condition in python? | <p>I am trying to divide an array of numbers into smaller chunks if the next element in the array is larger than the ith element. Basically, I have the following array:</p>
<p><code>a = [97, 122, 98, 111, 98, 111, 98, 101, 101, 103, 103, 104, 97, 107, 107, 108]</code></p>
<p>and I want to get sub arrays of:</p>
<pre... | <p>You can iterate on the pairs <code>current, next</code> and on condition stop the current values or add into it </p>
<pre><code>a = [97, 122, 98, 111, 98, 111, 98, 101, 101, 103, 103, 104, 97, 107, 107, 108]
result = []
values = [a[0]]
for current_v, next_v in zip(a, a[1:]):
if next_v < current_v:
re... | python|arrays|numpy|split|conditional-statements | 1 |
2,202 | 62,352,617 | Parallelizing a Dask aggregation | <p>Building off of <a href="https://stackoverflow.com/questions/46080171/constructing-mode-and-corresponding-count-functions-using-custom-aggregation-fun">this post</a>, I implemented the custom mode formula, but have found issues with performance on this function. Essentially, when I enter into this aggregation, my cl... | <p>In the end, I used futures to essentially parallelize the aggregation for each column. Since I had so many columns, passing each aggregation to its own worker thread saved me a bunch of time. Thanks to David for his comments as well as <a href="https://examples.dask.org/applications/embarrassingly-parallel.html" rel... | python|pandas|dask|dask-distributed|dask-dataframe | 1 |
2,203 | 62,341,905 | Convert a matrix of zeroes and ones into a colored graph | <p>I'm trying to convert an array like this one int a double-colored graph- where there are zeroes: blue ,where there are ones: white:</p>
<p><img src="https://i.stack.imgur.com/UB0iR.png" alt="Array numbers"></p>
<p><img src="https://i.stack.imgur.com/fvzcs.png" alt="Array as image"></p>
<p>I have tried to do this ... | <p>Although this might not be ideal but it'll do the job:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
def plot_islands(matrix):
cmap = LinearSegmentedColormap.from_list('my_cmap', ['darkblue', 'white'])
plt.imshow(X=matrix, cmap=cmap... | python|numpy|matplotlib | 0 |
2,204 | 62,375,626 | Pandas finding transitive relation from tuples A and B (two columns) | <p>Now hello, what I would like is showing hirarchy of likes. People from column 1 can like someone from column 2. Basically it'd be ideal having 4 columns A, B, C, D which show for every person who they like and for that person the next one etc. Basically from (a, b) tuples to (a, b), (b, c), (c, d).
I only know it mu... | <p>What you need is a couple of left-join (merge) operations. </p>
<p>Here's the code, broken to a couple of steps for clarity: </p>
<pre><code>step1 = pd.merge(df, df, left_on="col2", right_on="col1", how = "left")
step1 = step1[["col1_x", "col2_x", "col2_y"]]
step1.columns = ["first", "second", "third"]
step2 = p... | python|pandas|algorithm|recursion|relation | 0 |
2,205 | 51,164,460 | TypeError: 'float' object is not iterable; occurs when calling class from another file | <p>This is my first time posting on stackoverflow so thanks for the help. I am relatively new to python and this is my first time working on a personal project involving coding. The ultimate point of the file is to create a class to plot motor curves based on inputs. My main file currently is:</p>
<pre><code>import mo... | <p>Don't call your class "map". That's a function name in the standard library, so things are going to get confused. Your call <code>a = map(1047,0.343,x.kt,0.275,6)</code> is getting the standard library one, which is why the error message is weird and confusing. If you rename the class, things will make more sense... | python|numpy | 5 |
2,206 | 48,284,884 | Improve accuracy with Tensorflow Object detection pretrained model | <p>I am working on building an object detection model which I would like to create with 22 new classes (most of them are not in COCO or PETS datasets)
What I've already done is:</p>
<ul>
<li><p>Prepared images with multiple labels using LabelIMG. </p></li>
<li><p>Decrease image size in 2 for images that are bigger tha... | <p>1) What is the difference between train.py from Object detection, which I used in the above, to retrain.py from image_retraining to train_image_classifier.py from Slim</p>
<p>Ans : To what i know, none. Because train.py imports trainer.py which imports slim.learning.train(the same class which is used in train_image... | python|object|tensorflow|detection|object-detection | 0 |
2,207 | 48,373,687 | Concat column values based on condition | <p>This code : </p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(['a1', 'a2', 'stop', 'a4', 'a4', 'a5', 'stop', 'a3'],
columns=['c'])
</code></pre>
<p>renders: </p>
<pre><code> c
0 a1
1 a2
2 stop
3 a4
4 a4
5 a5
6 stop
7 a3
</code></pre>
<p>I'm attem... | <p>First, create a boolean mask by testing the equality of <code>c</code> to "stop":</p>
<pre><code>>>> df = pd.DataFrame(['a1', 'a2', 'stop', 'a3', 'a4', 'a5', 'stop', 'a6'],
columns=['c'])
>>> mask = df['c'].eq('stop')
</code></pre>
<p>You also specified you want to ignore va... | python|pandas | 5 |
2,208 | 48,132,807 | Why does tensor flow return NaN when running variables after training? | <p>I can't really understand why this is not working, basically I'm trying to retrieve values for m and q just to print them but I always get [nan, nan]</p>
<pre><code>import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
m = tf.Variable(tf.random_uniform(shape=()), dtype=tf.float32)
q = tf.Vari... | <p>Solved, the error was that train.csv was missing the y value at line 215</p> | python|tensorflow|machine-learning|deep-learning | 0 |
2,209 | 48,820,939 | How to append all the arrays inside a list into a single array combined by the depth in numpy | <p>I have a list which contains a variable amount of [n,1,2] numpy arrays. I need a way of combining all those arrays into one [n+however many,1,2] arrays. </p>
<p>I have tried to create a loop with an empty array and then using dstack to sort of combine them. But I have to 1) predefine the size of the array in advanc... | <p>Use <code>np.concatenate</code>.</p>
<pre><code>>>> arrays = [np.zeros((3, 1, 2)) for _ in range(3)]
>>> np.concatenate(arrays, axis=0).shape
(9, 1, 2)
</code></pre> | python|numpy | 1 |
2,210 | 70,840,604 | DataFrame (pandas) plot opens window but there is no plot | <p>I am unable to produce any charts in Python (matplotlib 3.5.1) with the pandas DataFrame plot() method. A window opens and the axes return value is <AxesSubplot:> as opposed to returning an object like that prints as somethig like <matplotlib.axes._subplots.AxesSubplot at 0x7f3958bcf9d0>, which is what I... | <p>I have resolved the (mis)behaviour without really being sure that I have resolved the issue responsible for this misbehaviour.</p>
<p>As looked around for a way out, I found this discussion (<a href="https://stackoverflow.com/questions/3285193/how-to-change-backends-in-matplotlib-python">How to change backends in ma... | pandas|dataframe|matplotlib|plot | 0 |
2,211 | 70,871,978 | Pandas concat multiple sheets appending new column for each sheet | <p>I have an excel Workbook with 36 sheets within. Each sheet has the same columns - there are only 5 columns that I actually need (below) but there are a bunch more. Each sheet is follows this naming convention YYYY-MM-DD MRR</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Subscription I... | <p>If I understand your question correctly, you don't need the for loop at all. Excel sheet data can be combined easily using concat function. Additional columns can be added by just initialising them. Then you can use logic to populate values for those additional columns.</p>
<p>Consider this code:</p>
<pre><code>impo... | python|excel|pandas | 1 |
2,212 | 71,082,546 | How to select rows with at least one categorical value in pandas DataFrame | <p>How I can retrieve indexes of the rows, in a pandas DataFrame (df), with "object" type (dtype=='O') in at least one column of the DataFrame?</p>
<p>What I would like to do in practice is to create a new dataframe (numeric_df) with only the numeric values of a source dataframe (df).</p> | <p>Use:</p>
<pre><code>df = pd.DataFrame({'object col':[1,'a',25]})
df[df['object col'].apply(lambda x: type(x))==int]
</code></pre>
<p>result:</p>
<p><a href="https://i.stack.imgur.com/JrV8A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JrV8A.png" alt="enter image description here" /></a></p>
<p>B... | python|pandas|dataframe|google-colaboratory | 0 |
2,213 | 70,771,650 | df Objects to float | <p>I have a problem I have this df :</p>
<pre><code>
**<class 'pandas.core.frame.DataFrame'>
RangeIndex: 44640 entries, 0 to 44639
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 NOx_Min_[ppm] 44640 non-null objec... | <p>You can try:</p>
<pre><code>gd['NOX'].apply(pd.to_numeric, args=('coerce',))
</code></pre> | python|pandas|dataframe|type-conversion | 0 |
2,214 | 51,714,124 | Feeding example to tf predictor.from_saved_model() for estimator trained with tf hub module | <p>I try to export the model for text classification with <a href="https://www.tensorflow.org/hub/tutorials/text_classification_with_tf_hub" rel="nofollow noreferrer">tf hub modules</a>, and then infer a prediction from it for a single string example using <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/... | <p>So, all I need was <code>serialized_example = example.SerializeToString()</code>
Writing the example on a file requires to start a session before reading it back. Simply serialising is enough:</p>
<pre><code> # Example message for inference
message = "Was ist denn los"
saved_model_predictor = predictor.f... | tensorflow|tensorflow-hub | 1 |
2,215 | 41,797,136 | How to Concatenate "Jagged" Tensors | <p>I am trying to write an implementation of <a href="http://www.aclweb.org/anthology/P14-1062" rel="nofollow noreferrer">this</a> paper in TensorFlow and I have come across a bit of a snag. In my pooling layer, I have to concatenate everything together. This is the code I use:</p>
<pre><code> pooled_outputs = []
... | <p>You can pass <code>-1</code> as one of the component of the shape to the <code>tf.reshape</code> method; it will be automatically inferred from the the shape of you tensor so the total size will be the same.</p>
<p>So, try to change the problem line to</p>
<pre><code>pooled_outputs = [tf.reshape(out, [-1, 94, 1, s... | python|python-3.x|machine-learning|tensorflow|conv-neural-network | 1 |
2,216 | 64,241,940 | How can I get the percentage of missing in a column using agg function? | <p>I'm working with the dataset database_versao_LatLongDecimal_fonteANM_23_01_2019.csv - you can find it here <a href="https://www.kaggle.com/edumagalhaes/brazilian-dams-and-brumadinho-households" rel="nofollow noreferrer">https://www.kaggle.com/edumagalhaes/brazilian-dams-and-brumadinho-households</a> - and I was hopi... | <p>Remove column name and instead divide <code>sum</code> by length use <code>mean</code>:</p>
<pre><code>summary = (
base_1.groupby(["UF"], sort=False)
.agg(
media=("Dano_Potencial__Alta", "count"),
minimo=("Dano_Potencial__Alta", "mean"),
... | python|pandas|dataframe|aggregate-functions | 2 |
2,217 | 64,294,336 | How do i save bs4 values in xls or csv? | <p>So I have extracted data from a website and I need to save it in excel. I'm new to python and can't figure out how to go about it.</p>
<p>here is the data that I've extracted and it's type is bs4.beautifulsoup</p>
<pre><code>{"lookbook":{"img":[],"count":0},"sizeInfoDes":{&quo... | <p>Convert the data that you have into a <code>dictionary</code> (it mostly looks like a json file, so u can easily convert it into a dictionary using the <code>json</code> module). Then, just use this code to output the data to an excel file:</p>
<pre><code>from bs4 import BeautifulSoup
import pandas as pd
dictionary... | python|python-3.x|pandas|beautifulsoup|python-beautifultable | 0 |
2,218 | 64,520,774 | How to upload a .txt file in python dataframe | <p>I am trying to upload a txt file which contains data as below . I have around 1M records in the file .
Data consist of different fields (which is to be columns ) in which I have manually added a comma as a delimiter.
The challenge is all the records does not have the same set of fields.
The columns should be "T... | <p>try using <code>engine='python'</code> and <code>error_bad_lines=False</code> in your pd.read_csv()</p> | python|pandas|dataframe|text|python-import | 0 |
2,219 | 47,908,091 | Model seems to be overfitting with Optimizer.minimize() but not tf.contrib.layers.optimize_loss() | <p>When I create <code>train_op</code> like this:</p>
<pre><code>train_op = tf.contrib.layers.optimize_loss(
loss=loss,
global_step=tf.contrib.framework.get_global_step(),
learning_rate=params['learning_rate'],
optimizer='Adam'
)
</code></pre>
<p>I get a working network that performs well on validatio... | <p>The issue is with batchnorm update operations, and it's actually <a href="https://www.tensorflow.org/api_docs/python/tf/layers/batch_normalization" rel="nofollow noreferrer">documented</a>:</p>
<blockquote>
<p>Note: when training, the moving_mean and moving_variance need to be updated. By default the update ops a... | tensorflow|machine-learning|neural-network|conv-neural-network | 2 |
2,220 | 47,682,621 | Returning a pandas DataFrame with the indexes of first next cases of >= value | <p><strong>Initial DataFrame</strong> </p>
<pre><code>index is_case value_a value_b
03/01/2005 True 0.598081665 0.189099313
04/01/2005 False 0.480809369 0.142255603
05/01/2005 False 0.963128886 0.422756089
06/01/2005 False 0.687675456 0.739599384
07/01... | <p>IIUC, and if your dataframes aren't too big, you can use a cartesian join and filters, then drop duplicates to get the first value matches like this:</p>
<pre><code>df_is_case = df[df['is_case'] == True]
df_joined = df_is_case.assign(key=1)\
.merge(df.assign(key=1),
... | python|pandas|dataframe | 3 |
2,221 | 49,013,228 | Using cleanco on dataframe column | <p>I am trying to create a script to clean company names using cleanco module in Python. </p>
<p>cleanco has an example which is as follows:</p>
<pre><code>business_name = "Some Big Pharma, LLC"
x = cleanco(business_name)
x.clean_name()
</code></pre>
<p>which results in "Some Big Pharma".</p>
<p>I am trying to do t... | <p>I used a lambda function to pull the "clean" name from the newly created column.</p>
<p>Try this:</p>
<pre><code>df2['emp3'] = df2['emp2'].apply(lambda x: x.clean_name())
</code></pre> | python|pandas | 2 |
2,222 | 48,906,313 | Is the numpy.linalg.lstsq rcond parameter not working according to the description? | <p>I am trying to use the least squares solution from numpy (<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html" rel="nofollow noreferrer">Description</a>). According to the website to use the new default for the 'rcond' parameter: ''To silence the warning and use the new default, use... | <p>You need NumPy >= 1.14. What version are you using?</p> | python|python-3.x|numpy | 2 |
2,223 | 49,140,570 | Match string with pandas series that contain a list of strings | <p>I have a pandas dataframe like this:</p>
<p><a href="https://i.stack.imgur.com/bbQm8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bbQm8.jpg" alt="enter image description here"></a></p>
<p>The values are string type. I would like to find out if each of these row contains the string <code>'63'<... | <p>You can use a list comprehension.</p>
<p>Here is a minimal example.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A': [[196], [504], [63, 100], [35, 1], [63]]})
df2 = df[[63 in x for x in df['A']]]
# A
# 2 [63, 100]
# 4 [63]
</code></pre>
<p>This works because the list comprehension ... | python|pandas|split|string-matching|series | 1 |
2,224 | 58,622,807 | python 3.8.0 - print self-documenting expression with value of variable on a new line | <p>Python 3.8.0 allows for self-documenting expressions and debugging using <code>=</code>, e.g.: <code>print(f'{myvar=}')</code>.</p>
<p>Is it possible to print the output on a new line? this would be useful for variables with multi-line outputs like dataframes.</p>
<p>e.g. </p>
<pre><code>>>> df = pd.Data... | <p>If you make your f string triple-quoted, you can include a newline after the <code>=</code>:</p>
<pre><code>df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion',
'monkey', 'parrot', 'shark', 'whale', 'zebra']})
print(f'''{df=
}''')
</code></pre> | python|python-3.x|pandas|f-string|python-3.8 | 2 |
2,225 | 58,623,653 | Pandas groupby get filtered sum over total sum | <p>I have the following dataframe:</p>
<pre><code>df = pd.DataFrame([[1, 2, True], [1, 4, False], [2, 6, False], [2, 8, True]], columns=["Group", "Value", "C"])
Group Value C
0 1 2 True
1 1 4 False
2 2 6 False
3 2 8 True
</code></pre>
<p>And I would like for eac... | <p>I believe you can use a division on <code>groupby.transform()</code> with sum and assign using <code>.assign()</code> after filtering so as to align on ythe index:</p>
<pre><code>df[df['C']].assign(Ratio=df['Value']/df.groupby('Group')['Value'].transform('sum'))
</code></pre>
<p>If more than 1 True per group, use:... | python|pandas|pandas-groupby | 2 |
2,226 | 58,664,141 | How to write data frame to Postgres table without using SQLAlchemy engine? | <p>I have a data frame that I want to write to a <strong>Postgres</strong> database. This functionality needs to be part of a <strong>Flask</strong> app.</p>
<p>For now, I'm running this insertion part as a separate script by creating an <strong>SQLAlchemy engine</strong> and passing it to the <code>df.to_sql()</code>... | <p>You can use those connections and avoid SQLAlchemy. This is going to sound rather unintuitive, but it will be much faster than regular inserts (even if you were to drop the ORM and make a general query e.g. with <code>executemany</code>). Inserts are slow, even with raw queries, but you'll see that <code>COPY</code>... | python|pandas|postgresql|sqlalchemy | 3 |
2,227 | 58,989,975 | Move for loop into numpy single expression when calling polyfit | <p><em>Fairly new to numpy/python here, trying to figure out some less c-like, more numpy-like coding styles.</em></p>
<h2>Background</h2>
<p>I've got some code done that takes a fixed set of x values and multiple sets of corresponding y value sets and tries to find which set of the y values are the "most linear".</p... | <p>From the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.polyfit.html#numpy.polynomial.polynomial.polyfit" rel="nofollow noreferrer"><code>numpy.polynomial.polynomial.polyfit</code> docs</a> (not to be confused with <code>numpy.polyfit</code> which is not interchangable)
:</... | numpy | 0 |
2,228 | 58,732,274 | Pandas Merge Vlookup, KeyError: "['Value'] not in index" | <p>I am trying to perform a vlookup/merge betwen two dataframes. I get the error
<code>KeyError: "['Player'] not in index"</code></p>
<p>i've tried to reindex the columns but doesnt seem to work.
<code>df1= df1.reindex(columns = ['Player','Category'])</code></p>
<p>My current code is like so <code>missingnames = pd.... | <p>You can do it like this:</p>
<pre><code>df1['Exists'] = df1['Player'].str.lower().isin(df2['Player Name'].str.lower())
</code></pre> | python|pandas | 1 |
2,229 | 58,977,672 | How can I pass a pandas data frame into a request parameter | <p>I am trying to do something like this:</p>
<pre><code>df = pd.read_csv(r'Desktop/test.csv')
url = 'http://localhost:5000/run_model'
response = requests.post(url, data=df)
</code></pre>
<p>But I am having this error:</p>
<pre><code>ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a... | <p>Depending on your endpoint you can convert your DataFrame to CSV or json like</p>
<pre><code>df.to_json()
</code></pre>
<p>or</p>
<pre><code>df.to_csv()
</code></pre> | python|pandas|python-requests | 2 |
2,230 | 70,167,070 | How to run tf.lite model on raspery-pi instead of saved keras model | <p>I am tring to classify traffic sings by using raspery-pi, for this i trained and saved a keras model that is .h5 file, but it consume too much cpu so i convert it to .tflite model and tried to run. However it gives that error <code>OSError: SavedModel file does not exist at: yourmodel.tflite/{saved_model.pbtxt|saved... | <p>Try to save your keras model using this code</p>
<pre><code># model is your keras model
tflite_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
</code></pre>
<p>To load and use it you will need tf.lite.Interpreter</p>
<pre><code># inst... | python|tensorflow|keras|raspberry-pi | 0 |
2,231 | 70,309,742 | How to resample to a coarser resolution but to samples within the original index? | <p>I have the following use case:</p>
<pre><code>import pandas as pd
import numpy as np
# create dataframe
df = pd.DataFrame(data=np.random.rand(10, 3),
columns=['a', 'b'],
index=pd.date_range('2021-01-01', periods=10, freq='W-FRI'))
# data is random, I'm just saving time with copy ... | <p>One way is to transform the index to period, then drop the duplicates:</p>
<pre><code>months = df.index.to_series().dt.to_period('M')
df[~month.duplicated()]
</code></pre>
<p>Another, might actually be better, is <code>groupby().head()</code></p>
<pre><code>df.groupby(pd.Grouper(freq='M')).head(1)
</code></pre>
<p>O... | python|pandas|numpy|pandas-resample | 1 |
2,232 | 70,368,274 | How to get the filenames of the samples from tensorflow dataset? | <p>For example, I have the following code, which get me the image arrays and their labels:</p>
<pre><code>import tensorflow_datasets as tfds
builder = tfds.ImageFolder('/home/ubuntu/X-dataset/')
ds_val = builder.as_dataset(split=['val'], shuffle_files=False, as_supervised=True)
ds_val = ds_val.batch(batch_size=32, dro... | <pre><code>import tensorflow as tf
image_ds = tf.data.Dataset.list_files('image/*', shuffle=False)
for file in image_ds.take(3):
print(file.numpy())
</code></pre>
<p><strong>Output</strong></p>
<pre><code>b'image/flower.jpg'
b'image/flower2.jpg'
b'image/flower1.jpg'
</code></pre> | tensorflow|tensorflow2.0|tensorflow-datasets | 0 |
2,233 | 55,957,051 | How to make any changes in a column when there is a change in the corresponding row in other column while looping through in python | <ol>
<li>I want to add a new column 'rate' where the first entry of the day should be 0.</li>
<li>If the time difference is 05 mins then it should be 2 else it should be 2.</li>
</ol>
<p>input: </p>
<pre><code>date time
20190101 750
20190101 755
20190101 800
20190101 810
20190101 815
20190102 820
20190102 82... | <p>If I understand correctly: to fix your problem for the change of day you can use <code>groupby</code> on the date, that way it will not compare just the time but the dates too (if your column date is your index, this will work, if not change <code>df.index</code> to <code>df.date</code> in the groupby)</p>
<pre><cod... | python-3.x|pandas|loops | 0 |
2,234 | 55,892,254 | Trying to get CSV ready for keras model with tensorflow dataset | <p>I do have a keras CNN model ready which expects [None,20,20,3] arrays as input. (20 is image size here...) On the other side I do have a CSV with 1200 (20*20*3) columns ready in my cloud storage.</p>
<p>I want to write an ETL pipeline with tensorflow to obtain a [20,20,3] shape tensor for each row in the csv.</p>
... | <p><code>tf.data.experimental.make_csv_dataset</code> creates a OrderedDict of column arrays. For your task I'd use <code>tf.data.TextLineDataset</code>. </p>
<pre class="lang-py prettyprint-override"><code>def parse(filename):
string = tf.strings.split([filename], sep=',').values
return string
dataset = tf.... | csv|tensorflow|dataset|shapes|tensor | 0 |
2,235 | 55,962,827 | Code to find top 95 percent of column values in dataframe | <p>I am looking for help gathering the top 95 percent of sales in a Pandas Data frame where I need to group by a category column. I found the following (top section of code) which is close. <code>TotalDollars</code> in my df gets properly sorted in descending fashion, but the resulting number of rows includes more th... | <pre><code>import pandas as pd
import numpy as np
np.random.seed(100)
test_df = pd.DataFrame({
'group': ['A'] * 5 + ['B'] * 5,
'value': np.random.randint(1,100,10)
})
def retain_quantile(df, percentile=0.95):
percentile_val = df['value'].quantile(percentile)
return df[df['value'] <= percentile_... | python-3.x|pandas | 1 |
2,236 | 64,693,529 | ipywidgets and pandas dataframe | <p>How I can get dataframe out of @interact function for next cell?
My interact function looks something like this:</p>
<pre><code>@interact(eutPlace=eutPlaces)
def selectByEut (eutPlace):
rdsTable = tabelSisse.drop(['Id', 'Serial_number', 'User_modified'], axis='columns')
rdsTable = rdsTable.loc[rdsTable['EUT_... | <p>Found one solution. Use interactive instead of @interact.</p>
<pre><code>def selectByEut (eutPlace):
rdsTable = tabelSisse.drop(['Id', 'Serial_number', 'User_modified'], axis='columns')
rdsTable = rdsTable.loc[rdsTable['EUT_place'] == eutPlace]
display(rdsTable)
return rdsTable
intrFilt = interactiv... | python|pandas|jupyter-notebook|ipywidgets | 1 |
2,237 | 65,002,526 | Tensorflow 2: Sort a 3D tensor accoding to a 2D tensor | <p>I have a 3D tensor with batch, sequence, feature dimension (N,s,e). It is a sequence of probability distributions. Then I want to order them according to the integer corresponding to the highest predictions. So say</p>
<pre><code>x_probabs = 3D tensor (ex: [[[0.5, 0.1, 0.4], [0.3, 0.3, 0.4], [0.1,
0.8, 0.1]]]; # sh... | <p>You can add <code>batch_dims</code> argument to start gathering from the lower dimension:</p>
<pre><code>x = tf.gather(x_probabs, x, batch_dims=1)
</code></pre> | python|sorting|tensorflow | 0 |
2,238 | 44,066,571 | Accumalate column through pandas | <p>I have multiple tab delimited files, all having same entries. I intend to read each file choose first column as index. My final table will have first column as index mapped against last column from all the files. For this, I wrote a pandas code but not a great ones. Is there an alternate way to do this ?</p>
<pre><... | <p>To clean the code and use a looping mechanism, you can put both your file names and the columns you are dropping in two separate lists, and then use list comprehension on the file names to import each dataset. Subsequently, you concatenate the output of the list comprehension into one dataframe:</p>
<pre><code>impo... | python-3.x|pandas | 1 |
2,239 | 44,323,136 | How to debug a Python program that freezes on one line? | <p>When I run my code ,it just stay in the line <code>image_batch, label_batch = sess.run([test_images, test_labels])</code> without any error prompt. It just stays here and can't move.</p>
<p>Here is my code:</p>
<pre><code># coding=utf-8
from color_1 import read_and_decode, get_batch, get_test_batch
import color_i... | <p>Seems like you are not starting the queue-runners / initializing the variables properly. I have seen similar behavior with my models when i forgot to to that.
When this is the case you most likely get stuck at the line</p>
<pre><code>image_batch, label_batch = sess.run([test_images, test_labels])
</code></pre>
<p>... | python|tensorflow | 0 |
2,240 | 69,448,084 | Efficient way to populate missing indexes from pandas group by | <p>I grouped a column in a pandas dataframe by the number of occurrences of an event per hour of the day like so:</p>
<pre><code>df_sep.hour.groupby(df_sep.time.dt.hour).size()
</code></pre>
<p>Which gives the following result:</p>
<pre><code>time
2 31
3 6
4 7
5 4
6 38
7 9
8 5
9 31
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>Series.reindex</code></a> with <code>range(24)</code>:</p>
<pre><code>df_sep.hour.groupby(df_sep.time.dt.hour).size().reindex(range(24), fill_value=0)
</code></pre> | python-3.x|pandas|pandas-groupby | 2 |
2,241 | 69,521,760 | Filtering grouped dataset by index column | <p>I'm trying to get a Pandas exercise done and it's driving me bonkers.</p>
<p>I have a dataset containing the number of cyclists that went by a certain zone of the city every hour of each day, so something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Year</th>
<th>Month</th>... | <p>Use <a href="https://pandas.pydata.org/docs/user_guide/timeseries.html#partial-string-indexing" rel="nofollow noreferrer"><code>partial string indexing</code></a>, with <code>DatetimeIndex</code>:</p>
<pre><code>df['datetime'] = pd.to_datetime(df[["Year", "Month", "Day"]])
df = df.drop(... | python|pandas|dataframe | 1 |
2,242 | 41,181,499 | Get Pandas Duplicate Row Count with Original Index | <p>I need to find duplicate rows in a Pandas Dataframe, and then add an extra column with the count. Lets say we have a dataframe:</p>
<pre><code>>>print(df)
+----+-----+-----+-----+-----+-----+-----+-----+-----+
| | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|----+-----+-----+-----+-----+-----+-----+--... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a> first for convert <code>index</code> to columns and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggr... | python|pandas|group-by|aggregate|multiple-columns | 4 |
2,243 | 54,070,780 | How to Covert multiple list columns in data frame into given one? | <p>I have Dataframe like this</p>
<pre><code> Number String Aut
0 [12, 13] [hi are, ho to] ppppp
1 34 How qqqqq
2 35 are wwwwwww
</code></pre>
<p>i want to convert this into this</p>
<pre><code> Number String Aut
... | <p>There is mix list with scalars, so first need some pre processing and then create DataFrame by <code>chain</code> with <code>repeat</code>:</p>
<pre><code>n = [x if isinstance(x, list) else [x] for x in df['Number']]
s = [x if isinstance(x, list) else [x] for x in df['String']]
lens = [len(x) for x in n]
from iter... | python|pandas|dataframe | 0 |
2,244 | 66,148,933 | Update specific column values based upon group by from different column in Pandas | <p>I have below pandas data frame in python.</p>
<p><a href="https://i.stack.imgur.com/6wkJr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6wkJr.png" alt="enter image description here" /></a></p>
<p>Looking for below output:</p>
<p><a href="https://i.stack.imgur.com/GOw6x.png" rel="nofollow norefer... | <p>Try:</p>
<pre><code>df['col1'] = df['col1'].mask(df['col2'].duplicated()).ffill()
</code></pre>
<p>Or:</p>
<pre><code>df['col1'] = df.groupby('col2')['col1'].transform('first')
</code></pre> | python|pandas|dataframe | 2 |
2,245 | 66,099,929 | Unexpected result sklearn StandardScaler | <p>I try to test some Scaler with following code.
I expect a result like the blue distributions but scaled.
What I get is the orange one.
Can anybody help me?</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
x1=np.random.normal(loc=... | <p>With <code>df_trans[0]</code> you don't select the entire column. You should change them as:</p>
<pre><code>axs[0].hist(df_trans[:,0],color='orange') # all rows, first column
axs[1].hist(df_trans[:,1],color='orange') # all rows, second column
</code></pre>
<p>That will produce as follows:</p>
<p><a href="https://i.s... | python|pandas|matplotlib|scikit-learn | 1 |
2,246 | 66,201,579 | Row-wise comparison against a list-type column | <p>let's assume I have the following code</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'List type':[[1, 2, 3], [4, 5, 6], [7, 8, 9]], 'Integer type':[5, 4, 1]})
</code></pre>
<p>and resulting Pandas dataframe:</p>
<pre><code>| List-type | Integer-type |
| -------- | -------------|
| [1, 2, 3] | 5 ... | <p>One way using <code>pandas.DataFrame.apply</code>:</p>
<pre><code>df["mask"] = df.apply(lambda x: x["Int-type"] in x["List-type"], axis=1)
print(df)
</code></pre>
<p>Output:</p>
<pre><code> List-type Int-type mask
0 [1, 2, 3] 5 False
1 [4, 5, 6] 4 True
2 [7, 8... | python|pandas | 2 |
2,247 | 65,941,834 | Pytorch: How to unflatten/get back the network from flattened network? | <p>I am using the following function to flatten the network:</p>
<pre><code>#############################################################################
# Flattening the NET
#############################################################################
def flattenNetwork(net):
flatNet = []
shapes = []
for p... | <p>There is a difference between model definition (its <code>forward</code> function), and the parameter configuration (what's called model state, and is easily accessible as a dictionary using <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.state_dict" rel="nofollow noreferrer">... | python|pytorch|flatten | 0 |
2,248 | 66,124,374 | Pandas: add elements to index at even intervals | <p>I have a dataframe that looks like this:</p>
<pre><code> B
A
0.00 5.7096
7.33 8.0280
25.82 15.7212
43.63 19.5156
55.24 20.1888
</code></pre>
<p>and I want to add rows with the index at regular intervals (say by 10), so that I can then interpolate the column B with method = 'index'. ... | <p>Effectively do a union by doing an outer join.</p>
<pre><code>df = pd.read_csv(io.StringIO("""A B
0.00 5.7096
7.33 8.0280
25.82 15.7212
43.63 19.5156
55.24 20.1888"""), sep="\s+").set_index("A")
df = df.join(pd.DataFrame(index=pd.RangeIndex(0,60... | python|pandas|reindex | 2 |
2,249 | 58,227,451 | Need to convert time to h:m:s | <p>I have time formats with missing hours like 36:21 or incompleted hour format like 1:23:30, would like to convert it to standard time format like 00:00:00,
but I don't know why my code did not work. </p>
<p>Need to convert time format H: M:S like this --> 00:00:00
len(x) == 6 i.e. 36:21 ; len(x) == 7 i.e. 1:23:30<... | <p>you should use apply method, it is much faster than iteration</p>
<p>also i recommend you to read <a href="https://thispointer.com/python-how-to-pad-strings-with-zero-space-or-some-other-character/" rel="nofollow noreferrer">https://thispointer.com/python-how-to-pad-strings-with-zero-space-or-some-other-character/<... | python|pandas | 0 |
2,250 | 69,010,072 | Plotting matplotlib subplots | <p>I begin with matplotlib and subplots. Could you tell me how to assign the 2 plots generated from this code in 2 columns:</p>
<pre><code># Bar Plot for Firm Performance
fig = plt.figure(figsize = (6, 4))
title = fig.suptitle("Firm performance", fontsize=14)
fig.subplots_adjust(top=0.85, wspace=0.3)
fig, ax... | <p>You just need to pass <code>ax</code> parameter to <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html" rel="nofollow noreferrer"><strong><code>pandas.DataFrame.plot</code></strong></a>:</p>
<pre><code>fig, axs = plt.subplots(1, 2, figsize = (6, 4))
title = fig.suptitle("Firm perfor... | python|pandas|dataframe|matplotlib|seaborn | 0 |
2,251 | 69,278,507 | Unfreeze model Layer by Layer in PyTorch | <p>I'm working with a PyTorch model from <a href="https://github.com/yitu-opensource/T2T-ViT" rel="nofollow noreferrer">here</a> (T2T_ViT_7).</p>
<p>I'm trying to freeze all layers except the last (head) layer and train it on my dataset. I want to evaluate its performance, and then unfreeze layers one by one and train ... | <p>If by <em>layers</em> you mean each block inside of <code>model.blocks</code>, then you can use <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=children#torch.nn.Module.children" rel="nofollow noreferrer"><code>nn.Module.children</code></a> (// <a href="https://pytorch.org/docs/stab... | machine-learning|pytorch|layer | 2 |
2,252 | 44,563,707 | How to create pandas DataFrame with index from the list of tuples | <p>What would be the best way to create pandas DataFrame with index from records.
Here is my sample:</p>
<pre><code>sales = [('Jones LLC', 150, 200, 50),
('Alpha Co', 200, 210, 90),
('Blue Inc', 140, 215, 95)]
labels = ['account', 'Jan', 'Feb', 'Mar']
df = pd.DataFrame.from_records(sales, columns=labels)
</c... | <p>Simpliest is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="noreferrer"><code>set_index</code></a>:</p>
<pre><code>df = pd.DataFrame.from_records(sales, columns=labels).set_index('account')
print (df)
Jan Feb Mar
account
Jones LLC ... | python-2.7|pandas|dataframe | 6 |
2,253 | 44,653,239 | Tensorflow 1.2 assigning variables | <p>As the title says I'm using tensorflow version 1.2 built from source for my machine. I don't believe that affects my question though.</p>
<p>What is the difference between these two chunks of code?
The top one causes me to never get values assigned while training but the bottom does. I am copying all my epoch data... | <p>Remember that pretty much everything is an operation in TensorFlow. I believe the issue in your code is that you never run the assignment operation (you just evaluate the <code>input_data</code> tensor as it has been initialised).</p>
<p>You then need to assign the return of the assignment method to a variable:</p>... | python|tensor|tensorflow | 0 |
2,254 | 60,830,646 | Indexing Dataframe | <p>I am getting SettingWithCopyWarning:</p>
<pre><code>A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
</code></pre>
<p>Here is my dataframe(Capacity):</p>
<pre><code> ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> for set values of <code>DataFrame</code>, not <code>Series</code>:</p>
<pre><code>Capacity.loc[(Capacity.index.month >= 3), 'A'] = 20.40
</code></pre>
<p>Mor... | pandas|indexing | 0 |
2,255 | 60,802,823 | Multi-column input to ML.PREDICT for a TensorFlow model in BigQueryML | <p>We have trained a model in Google Cloud AutoML (a tool that we like a lot) and successfully exported it to GCS, and then created the model in BigQuery using the below command:</p>
<pre><code>create or replace model my_dataset.my_bq_ml_model
options(model_type='tensorflow',
model_path='my gcs path to exported tenso... | <p>After you load the model into BigQuery ML, click on the model in the BigQuery UI and switch over to the "Schema" tab. This should tell you what columns the model wants.</p>
<p>Alternately, run the program saved_model_cli on the model (it's a python program that comes with tensorflow) to see what the supported signa... | tensorflow|machine-learning|google-cloud-platform|google-bigquery|google-cloud-automl | 0 |
2,256 | 60,939,280 | Convert Multi-Index Pandas Dataframe to JSON | <p>Consider a Pandas <code>DataFrame</code> with <code>MultiIndex</code>: </p>
<pre><code> virtual_device_135 virtual_device_136
tag_5764 tag_5764
timestamp
31/03/2020 02:10:30 -0.97 N... | <p>I found it can be done as following:</p>
<p>If the <code>DataFrame</code> is df:</p>
<pre class="lang-py prettyprint-override"><code>df.columns = ['_'.join(col) for col in df.columns]
df.reset_index(inplace=True)
df_list = json.loads(df.to_json(orient='records'))
for each in df_list:
body_content_list.append... | python|pandas|pandas-groupby|multi-index | 1 |
2,257 | 60,927,247 | Tensorflow LSTM: How to use different weights for each batch? | <p>I'm talking about the <code>tf.keras.layers.LSTM</code> implementation, as I want to use <code>cuDNN</code> for my batched LSTM.</p>
<p>Right now, I use a "hand made" LSTM implementation, because I want to have different weights/biases for each batch. Do you know a way how to use TensorFlows LSTM implementation of ... | <p>Maybe you can use something like this. It is an example for a fully-connected layer for a CNN </p>
<pre><code>def dense_fc4(n_objects):
initializer = lambda: tf.contrib.layers.xavier_initializer()(shape=(1024,512))
return tf.Variable(initial_value=initializer, name='fc4/kernel',
... | python|tensorflow|lstm|tensorflow2.0 | 0 |
2,258 | 71,639,870 | How to transpose and merge two dataframes with pandas - obtaining a key error | <p>I have a data frame (file1.txt) like this:</p>
<pre><code>identifer 1 2 3
Fact1 494 43 3
Fact2 383 32 5
Fact3 384 23 5
Fact4 382 21 7
</code></pre>
<p>And another data frame (file2.txt) like this:</p>
<pre><code>Sample Char1 Char2 Char3
1 4 5 ... | <p>You can to set the index</p>
<pre><code>df1 = df1.set_index('identifer')
df1.columns = df1.columns.astype(float)
out = df1.T.join(df2.set_index('Sample'))#.reset_index()
Out[82]:
Fact1 Fact2 Fact3 Fact4 Char1 Char2 Char3
1.0 494 383 384 382 4 5 5
2.0 43 32 23 21... | python|pandas | 3 |
2,259 | 69,898,397 | adding a zero at first element in a numpy array or a way to create an array keeping the first position as zero | <p>I got this function to looking for some specific characters in a string and if it is found it add a value at that position in the array, ex:</p>
<pre><code>def skew_array(text):
import numpy as np
skew = np.zeros(len(text))
for i in range(0, len(text)):
if text[i] == 'G':
skew[i] += ... | <p>i think that functions that change the flat size of arrays are pretty slow, so i'd create skew larger from the start. and you can use a dict to avoid an elif soup</p>
<pre><code>import numpy as np
def skew_array(text, dict_):
skew = np.zeros(len(text)+1)
for i, char in enumerate(text, start=1):
skew[... | arrays|numpy | 1 |
2,260 | 43,331,335 | Subsetting DataFrame based on column names of another DataFrame | <p>I have two DataFrames and I want to subset <code>df2</code> based on the column names that intersect with the column names of <code>df1</code>. In <code>R</code> this is easy.</p>
<p><code>R</code> code:</p>
<pre><code>df1 <- data.frame(a=rnorm(5), b=rnorm(5))
df2 <- data.frame(a=rnorm(5), b=rnorm(5), c=rnor... | <p>If you need a true intersection, since <code>.columns</code> yields an Index object which supports basic set operations, you can use <code>&</code>, e.g.</p>
<pre><code>df2[df1.columns & df2.columns]
</code></pre>
<p>or equivalently with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas... | python|pandas|dataframe | 2 |
2,261 | 43,444,291 | Strange thing happens when i restore my model in Tensorflow | <p>I just want to load my previously saved model and train it further, my code works just fine until the restoring step,things become strange when i use ‘sess.run’. The program end immediately without executing ‘sess.run’.</p>
<p>But, when i removed my AdamOptimizer op, ‘sess,run’ came back to work</p>
<p>Why?</p>
<... | <p>You may need to join all the threads you used for your asynchronous execution. Here's an example snippet from (<a href="https://www.tensorflow.org/programmers_guide/reading_data" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/reading_data</a>)</p>
<pre><code>with tf.Session() as sess:
# St... | python|tensorflow|deep-learning | 0 |
2,262 | 72,208,712 | Drop all rows id pandas df except ones mentioned in another df | <p>I have two dataframes, one containing lot of columns</p>
<pre><code>df1:
id age topic date text
1 23 Student 1.1. Lorem
2 19 Student 1.2. Cupcake
20 19 Student 1.2. Lorem Ipsum
190 21 Student 11.1. Cupcake Ipsum
</code></pre>
<p>And one with two columns</p>
<pre><co... | <pre><code>result_df = df1.merge(df2['id'])
</code></pre>
<p>Given:</p>
<pre><code>df1:
id age topic
0 1 23 Student
1 2 19 Student
2 20 19 Student
3 190 21 Student
df2:
id count
0 1 105
1 20 4843
2 31 361
</code></pre>
<p>Doing:</p>
<pre><code>result_df = df1.merge(df2['id'... | python|pandas|dataframe|drop | 1 |
2,263 | 72,318,923 | Pandas/Openpyxl - Save Current Date into xlsx Filename | <p>Trying to save an xlsx file and include the current date in the file name during the process. Currently, I'm using the below code but I receive the error <code>invalid format string</code> - uncertain what format I can use to accomplish this.</p>
<p>I saw this method recommended in another thread but it doesn't work... | <p>The error is in the <code>save</code> command where you have an extra <code>%</code> in the end. Also, just <code>now</code> is not sufficient, it needs the <code>()</code>. For the code above, think it also needs the <code>datetime.</code> to be added. So, change the last line from....</p>
<pre><code>wb1.save('file... | pandas|openpyxl|python-3.10 | 0 |
2,264 | 50,602,820 | How to make a new pandas DF column conditionally based on two other columns | <p>I have a dataframe which looks like this:</p>
<pre><code>col 1 | col2 | col3 | col4 | col5
'abc' | 1 | 20 | 10 | 15
'abc' | 2 | 25 | 5 | 30
'def' | 1 | 340 | 12 | 22
'def' | 2 | 185 | 16 | 120
...
</code></pre>
<p>I'd like to create another column <code>col6</code> which is based on ... | <p>Try this,</p>
<pre><code>df.loc[df['col2'] ==1,'col6']=df['col3']*df['col5']
df.loc[df['col2'] ==2,'col6']=df['col4']*df['col5']
df['col6']=df['col6'].fillna(0)
</code></pre> | python|pandas | 2 |
2,265 | 50,518,309 | Tensorflow gradient through while_loop | <p>I've got a tensorflow model where the output of a layer is a 2d tensor, say <code>t = [[1,2], [3,4]]</code>.</p>
<p>The next layer expects an input which consists of every row combination of this tensor. That is, I need to turn it into <code>t_new = [[1,2,1,2], [1,2,3,4], [3,4,1,2], [3,4,3,4]]</code>.</p>
<p>So fa... | <p>In this case you are fine to have <code>back_prop</code> as false. It doesn't need to back propagate through the computation of the indices because that computation doesn't depend on any learned variables.</p> | python|tensorflow|machine-learning | 0 |
2,266 | 62,631,051 | Insert rows into a dataframe by group and entry is from another dataframe_complex match | <p>I wish to insert some entries into a dataframe called 'df_recorded' for each group, and the entry is searched from another dataframe called "df_missed".</p>
<pre><code>import pandas as pd
df_recorded = pd.DataFrame({
'id': ['2008 11', '2008 11', '2008 11', '2008 07', '2008 07', '2008 12', '2008 12', '... | <p>IIUC you can simply rename the columns in the missing df and <code>concat</code>:</p>
<pre><code>df_missed.columns = ["id", "score", "date"]
df = pd.concat([df_recorded,df_missed], ignore_index=True, sort=False).sort_values("id", ascending=False)
df.loc[df["info"].i... | python|pandas|dataframe|insert|match | 4 |
2,267 | 62,637,195 | Is There Anyway to Fetch a Batch of Image to TFLite model on Edge TPU? | <p>I am having trouble on some small detections on Coral Board and I have decided to use sliding window to cut the image in small sample images. But how can I fetch it to the edge_tpu model which only allow 1 image passing through?</p>
<p>Is there anyway to change the batch input when convert to TFlite model?</p>
<p>I ... | <p>After looking for the code file <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/export_tflite_ssd_graph.py" rel="nofollow noreferrer">export_tflite</a>
I switch to change the number of the batch from 1 to my desire number and everything is fine now.
Edit the batch from 2 files:
<s... | tensorflow-lite|google-coral | 2 |
2,268 | 62,705,066 | Euclidian distance between two python matrixes without double for-loop? | <p>I am working with two numpy matrixes, <strong>U</strong> (<em>dimensions Nu x 3</em>) and <strong>M</strong> (<em>dimensions 3 x Nm</em>)</p>
<p>A contains Nu users and 3 features</p>
<p>M contains Nm movies (and the same 3 features)</p>
<p>For each user of <strong>U</strong>, I would like to calculate its euclidian... | <p>Check out <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy-spatial-distance-cdist" rel="nofollow noreferrer">scipy.spatial.distance.cdist</a>. Something like this will do:</p>
<pre><code>from scipy.spatial.distance import cdist
dist = cdist(U, M.T)
</code></pre> | python|arrays|numpy|scipy|distance | 1 |
2,269 | 62,860,380 | How to convert tflite model from unquanted to quant/ realtime image classifier react-native | <p>I have copied a react native code from <a href="https://medium.com/@namar/high-performance-image-classification-with-react-native-336db0a96cd" rel="nofollow noreferrer">here</a></p>
<p>then i have created a deeplearning model using keras and converted it to tflite (they had used mobilenet quant model ) and replaced ... | <p>when i created tflite model with same dataset using teachablemachine of google the saved my model name as mask_unquant.tflite . i think there is something with quant and unquant.</p> | reactjs|react-native|keras|deep-learning|tensorflow-lite | 0 |
2,270 | 54,620,614 | Average of each consecutive segment in a list | <p>I have a list:</p>
<pre><code>sample_list = array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
</code></pre>
<p>I want to calculate the average of every, say 4 elements. But not 4 elements separately, rather the first 4:</p>
<pre><code>1,2,3,4
</code></pre>
<p>followed by:</p>
<pre><code>2,3,4,5
</code></pre>
<p>... | <p>If <code>numpy</code> is an option a simple way to achieve this is to use <a href="https://docs.scipy.org/doc/numpy-1.14.1/reference/generated/numpy.convolve.html" rel="nofollow noreferrer"><code>np.convolve</code></a>, which can be used to compute a <i>rolling mean</i> when convolving with an array of <a href="http... | python|list|numpy|average | 8 |
2,271 | 73,595,548 | Struggling to displaying the right (formatted) value for a matplotlib labels | <p><strong>Guide</strong>:
<a href="https://theoehrly.github.io/Fast-F1/examples_gallery/plot_qualifying_results.html#sphx-glr-examples-gallery-plot-qualifying-results-py" rel="nofollow noreferrer">https://theoehrly.github.io/Fast-F1/examples_gallery/plot_qualifying_results.html#sphx-glr-examples-gallery-plot-qualifyin... | <p>I overlooked something in the docs. I was not specifying the label only the container.</p>
<p><strong>Reference:</strong>
<a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar_label.html#matplotlib.axes.Axes.bar_label" rel="nofollow noreferrer">https://matplotlib.org/stable/api/_as_gen/matplotl... | python-3.x|pandas|matplotlib|data-science | 0 |
2,272 | 73,545,526 | Ploting dataframe with NAs with linearly joined points | <p>I have a dataframe where each column has many missing values. How can I make a plot where the datapoints in each column are joined with lines, i.e. NAs are ignored, instead of having a choppy plot?</p>
<pre><code>import numpy as np
import pandas as pd
pd.options.plotting.backend = "plotly"
d = pd.DataFra... | <p>You can use <strong>pandas</strong> <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.interpolate.html" rel="nofollow noreferrer">interpolate</a>. Have demonstrated using <strong>plotly express</strong> and chained use so underlying data is not changed.</p>
<p>Post comments have amended answer ... | pandas|dataframe|plotly | 0 |
2,273 | 73,730,231 | Convert JSON load to readable Pandas Dataframe | <p>I am trying to load some data from ArcGis. I am used to working in Pandas Dataframes, not entirely sure how I can read from API's and get it in a nice table. I tried data['results'] and get feature dataset. But not sure how to organize the data by unique Object ID.
Anyone have an idea how to read this into a pandas ... | <p>If I understood right you want to create a dataframe for all the features and the geometry.
The following code creates the dataframe bellow:</p>
<pre><code>import urllib.request as urlopen
import urllib.parse as urlencode
import urllib.request as request
import json
import pandas as pd
import numpy as np
inPts = {&... | python|pandas|api|rest|arcgis | 1 |
2,274 | 71,273,332 | tff.simulation.datasets.ClientData to build federated learning model from CSV files | <p>I am building a federated learning model using my own dataset.
I aim to build a multi classification model.
The data are presented in separate 8 CSV files.</p>
<p>I followed the instructions in this <a href="https://stackoverflow.com/questions/60265798/tff-how-define-tff-simulation-clientdata-from-clients-and-fn-fun... | <p>In this setup it maybe useful to consider <a href="https://www.tensorflow.org/federated/api_docs/python/tff/simulation/datasets/FilePerUserClientData" rel="nofollow noreferrer"><code>tff.simulation.datasets.FilePerUserClientData</code></a> and <a href="https://www.tensorflow.org/api_docs/python/tf/data/experimental/... | python|tensorflow|tensorflow-federated | 1 |
2,275 | 71,167,751 | How to quickly add a large list of value to the corresponding python pandas dataframe | <p>I have a large csv file with the following format (example), the report_date is currently empty:</p>
<pre><code>| ids | disease_code | report_date |
| --- | ------------ | ----------- |
| 10 | I202 | |
| 11 | I232 | |
| 11 | I242 | |
</code></pre>
<p>I g... | <p>First, you can create a dataframe with your data. You'll see that the column <code>"disease_code"</code> contains a list of values, just as you mentioned:</p>
<pre><code>>> df = pd.DataFrame(
[(10, ['I202'], "2021-10-22"), (11, ['I232', 'I242'], "2021-11-22"), (11, ['I232', 'I... | python|pandas|csv | 1 |
2,276 | 71,299,148 | Filtering dataframe based on other dataframe column on Python | <p>I have two DataFrames. One contains multiple columns with sample name and rows containing values. The second DataFrame contains one column called "Sample Name" which contains a list of the names of samples that pass a quality control.
df1</p>
<pre><code>| mz | Sample 001| Sample 002...
|:---- |:--------... | <p>Se if this works:</p>
<pre><code>for col in df1.columns:
if col not in df2['Sample Name'].unique():
df1.drop(columns=[col], inplace=True)
</code></pre> | python|pandas|dataframe | 0 |
2,277 | 52,310,755 | Changing the categories in a column pandas? | <p>I was experimenting with iter function on pandas.</p>
<p>1- I made a list from a pandas column.</p>
<blockquote>
<p>in1:</p>
</blockquote>
<pre><code>df_area_code_iter = iter(df["Area Code"])
df_area_code_iter_list = list(df_area_code_iter)
df_area_code_iter_list
</code></pre>
<blockquote>
<p>out_1:</p>
</bl... | <p>The main problem is assignment requires <code>=</code>, not the equality operator <code>==</code>.</p>
<p>You are forced to append to a new list since the variable <code>i</code> inside your loop is a scalar, not a reference pointing to an element in your original list. Instead, you can use <code>enumerate</code> a... | python|pandas|for-loop|iterator|iteration | 1 |
2,278 | 60,652,215 | How to subtract a column value with every value in another column (pandas) | <p>I have two columns A and B. I want to subtract column B value with every value in column A and create a new column without using for-loop.</p>
<p>Below is my Dataframe</p>
<pre><code> A B
0 5 3
1 3 2
2 8 1
</code></pre>
<p>Desired output </p>
<pre><code> A B C D E
0 5 3 2 3 ... | <p>Using numpy's array <a href="https://docs.scipy.org/doc/numpy/user/theory.broadcasting.html#array-broadcasting-in-numpy" rel="nofollow noreferrer">broadcasting</a>:</p>
<pre><code>df = pd.DataFrame({'A':[5, 3, 8],
'B':[3, 2, 1]})
df2 = pd.DataFrame(df['A'].values[:, None] - df['B'].values, colum... | python|pandas|numpy | 4 |
2,279 | 60,452,450 | Get only those string where specific ratio condition meets using diff tool SequenceMatcher | <p>Any example where I can get two strings in a column of a dataframe when ratio condition met?</p>
<p>Example - While comparing one string with column of a dataframe, it should return only those when SequenceMatcher.ratio() > 0.8.</p> | <p>IIUC use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with filter by lambda function in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"... | python|pandas | 1 |
2,280 | 60,403,628 | pandas compute difference using to column filters | <p>I have a pandas dataframe like: </p>
<pre><code>| country | year | people
| US | 1990 | 20
| US | 1991 | 34
| .. | .. | ..
| US | 2020 | 456
| UK | 1990 | 5
| UK | 1991 | 7
| .. | .. | ..
| UK | 2020 | 300
</code></pre>
<p>I would like to compute the difference be... | <p>Since the years of interest are 2020 and 1990, we filter for just those years, sort the people column in descending order, groupby country, and use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.subtract.html" rel="nofollow noreferrer">numpy subtract</a> and <a href="https://docs.scipy.org/doc/n... | python|pandas|dataframe | 1 |
2,281 | 72,794,356 | pytorch.info summary for Generator of AN equivalent to discriminator or summary for whole GAN | <p>Is it possible to generate a summary for the generator network of a GAN equivalent to the summary for the discriminator network using pytorch.info (containing inputs and outputs) or is there even a standard summary for the whole GAN including both networks?</p>
<p>For the Discriminator I used the following:</p>
<pre... | <p>This package is not recommended for debugging your code, you should therefore always make sure your code runs on random data before testing the summary.</p>
<p>In the second group of commands, you are using <code>output_size</code> instead of <code>input_size</code> (cf. <a href="https://github.com/TylerYep/torchinf... | pytorch|summary|generative-adversarial-network | 0 |
2,282 | 72,559,630 | Preserving the Custom Number Format when using read_excel() then converting to CSV with to_csv() with Pandas | <p>I've created a simple script that converts Excel files to CSV using Pandas. Here's the gist of my code:</p>
<pre><code>read_file = pd.read_excel(excel_file)
read_file.to_csv(csv_file, index=None, header=True, float_format='%.0f')
</code></pre>
<p>However, my issue is that the Excel file has several columns with date... | <p>Rendering cell value using number format is a function of Excel. I think pandas and openpyxl only know the information of the table, such as the value and number format, but do not know how to render cell value according to the number format.</p>
<p>If we wanted to, we can render the value as a string based on the n... | python|pandas | 0 |
2,283 | 72,763,875 | Google Colab TensorFlow model.fit() error | <p>Hi Im new to Stack overflow. Im having trouble with my code, I was at model.fit() and when I entered a value at the epochs and ran the code I got an error. Here is the code for the model.fit:</p>
<p>model.fit(
train_ds,
validation_data = valid_ds,
epochs = 10
)</p>
<p>and below here is the error I got:</p>
<p>ValueE... | <p>Probably you need to upscale the size of your image which you are feeding into the CNN. 360x360x3 is a standard one. Your image size is too small, hence it is not able to build the model fully.</p> | python|tensorflow | 0 |
2,284 | 61,860,819 | How to convert string entries in pandas dataframe to integers? | <p>The pandas data frame that I was working with has a column with string entries and I wish to convert it to integers.</p>
<p>The column is called <code>diagnosis</code> and each row has a value of either <code>M</code> or <code>B</code>. I wanted to convert all <code>M</code> to 1 and all <code>B</code> to 0 with th... | <p>You can use <code>map</code> to do this</p>
<pre><code>data['diagnosis'] = data['diagnosis'].map({'M':1,'B':0})
</code></pre> | python|pandas|dataframe | 2 |
2,285 | 61,823,299 | Extract instances of a patterned text sequence from a very long string using Python | <p>I am working with this <a href="https://www.senate.gov/artandhistory/history/resources/pdf/chronlist.pdf" rel="nofollow noreferrer">PDF document</a> of about 80 pages. It lists all 1,984 US senators from US history in chronological order. I have extracted the text of the document using PyPDF2. The text is now assign... | <p>You can try the following approach::</p>
<pre><code>d = re.split(r"([a-zA-Z]+\,\s+[a-zA-Z]+)", d)[1:]
d = [", ".join(d[i:i+2]) for i in range(0, len(d), 2)]
d = [re.findall(r'^(.*?)\s+\((.*?)\)\s+(.*?\d{4})(.*?)$', _)[0] for _ in d]
df = pd.DataFrame(d, columns=["name", "party/state", "date_to_convert", "rank_to_c... | python|regex|pandas|pdf | 2 |
2,286 | 61,795,444 | Slice multi-index pandas dataframe by date | <p>Say I have the following multi-index dataframe:</p>
<pre><code>arrays = [np.array(['bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'foo', 'foo']),
pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04'])]
df = pd.DataFrame(np.zeros((8, 4)),... | <p>Here is possible compare each level and then set <code>1</code>, there is <code>:</code> for all columns in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p>
<pre><code>m1 = df.index.get_level_values(0) =='bar'... | python|pandas|dataframe|slice|multi-index | 2 |
2,287 | 61,690,819 | Accessing classes/models with Flask Sqlalchemy which I created through pandas.to_sql | <p>I am trying to develop a web app with Flask. What I am trying to do is:</p>
<ol>
<li>Get data from client in the form of a table</li>
<li>Use pandas to perform calculations on each row of the table and create multiple dfs and then append them to a single df</li>
<li>Then use to_sql to upload the consolidated df to ... | <p>Ended up defining classes (db.Model) within the app and then appending data to the models with pd.to_sql but would still like to know a shorter way if possible. </p> | python|pandas|flask-sqlalchemy | 1 |
2,288 | 61,764,107 | Detect sign changes in Pandas Dataframe | <p>I have a pandas dataframe that is datetime indexed and it looks like this:</p>
<pre>
Datetime
2020-05-11 14:00:00-03:00 0.097538
2020-05-11 14:30:00-03:00 -0.083788
2020-05-11 15:00:00-03:00 -0.074128
2020-05-11 15:30:00-03:00 0.059725
2020-05-11 16:00:00-03:00 0.041369
2020-05-11 16:30:00-03:00 0.0... | <p>Let us try </p>
<pre><code>import numpy as np
np.sign(data).diff().ne(0)
</code></pre> | python|pandas | 14 |
2,289 | 57,920,584 | Gather a slice given an idex array | <p>I have an input tensor <code>params</code> of size <code>(BxHxWx200)</code> and an index array <code>idx</code> of size <code>(Bx1000x2)</code>. <code>idx</code> holds 1000 different locations of <code>param</code> tensor, i.e. the last axis (the one of size 2) is <code>HxW</code> location which corresponds to the <... | <p>You need another index in the last dimension of <code>idx</code> to index the first axis of <code>params</code>:</p>
<pre><code>import tensorflow as tf
# Input data (can be dynamic shapes)
B, H, W = 10, 20, 30
params = tf.placeholder(tf.float32, [B, H, W, 200])
idx = tf.placeholder(tf.int32, [B, 1000, 2])
# Dimens... | python|tensorflow | 1 |
2,290 | 57,741,059 | Write value (datetime) in pandas dataframe under diff condition | <p>I want to write into "Start_time" column the value of datetime that was for first non-zero occurrence of grouped_measurement and write the last time that occurred for grouped_measurement to "End_time" column. If grouped_measurement is 0, the "Start_time" and "End_time" should ... | <p>You are pretty close! Use groupby on 'grouped_measurement' column you created.</p>
<pre><code>df['grouped_measurement'] = df['value'].diff().fillna(1).eq(1).cumsum().where(df['value'].ne(0))
result = (df.join(df.groupby('grouped_measurement')['time']
.agg([('Start_time','min'),('End_time','max')... | python|pandas|datetime | 2 |
2,291 | 54,839,768 | Pandas Dataframe. Add multiple columns based on nonnull values of other columns | <p>My dataframe example.</p>
<pre><code>np.random.seed(66)
df = pd.DataFrame(
np.random.rand(5, 3),
columns=list('ABC'),
index=['R{}'.format(i) for i in range(5)]
)
df[df < .5] = None
df.head()
A B C
R0 NaN NaN NaN
R1 0.67 NaN NaN
R2 0.75 0.55 0.51
R3 NaN NaN 0.82
R4 NaN NaN 0.6... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.floor.html" rel="nofollow noreferrer"><code>numpy.floor</code></a>, then boolean mask should be removed:</p>
<pre><code>df[['A_percent', 'B_percent']] = np.floor(df[['A', 'B']] * 100)
print (df)
A B C A_perce... | python|pandas|dataframe | 2 |
2,292 | 55,060,553 | how to replace all column value | <p><a href="https://i.stack.imgur.com/bp1wj.jpg" rel="nofollow noreferrer">![I want to replace File_attribute and region
_attribute column value with '{}']<a href="https://i.stack.imgur.com/bp1wj.jpg" rel="nofollow noreferrer">1</a></a></p> | <p>Assuming the data is in a Pandas DataFrame object <code>df</code>,</p>
<pre><code>df['File_attribute'] = '{}'
df['Region_attribute'] = '{}'
</code></pre> | python-3.x|pandas | 1 |
2,293 | 49,371,486 | create training validation split using sklearn | <p>I have a training set consisting of X and Y, The X is of shape (4000,32,1) and Y is of shape (4000,1).</p>
<p>I would like to create a training/validation set based on split. Here is what I have been trying to do</p>
<pre><code>from sklearn.model_selection import StratifiedShuffleSplit
sss = StratifiedShuffleSplit... | <p>It's a little bit weird because I copy/pasted your code with sklearn's breast cancer dataset as follow </p>
<pre><code>from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
X, Y = cancer.data, cancer.target
from sklearn.model_selection import StratifiedShuffleSplit
sss = StratifiedShuffleSp... | python|numpy|machine-learning|scikit-learn|sklearn-pandas | 0 |
2,294 | 73,400,270 | Got an Input to reshape is a tensor with 3368 values, but the requested shape has 2048 error while fine-tuning Roberta | <p>I have a csv file that has two input columns and one class with multiple labels which means I'm trying to do a multi-class classification using fine-tuned RoBERTa model. This is the structure of my csv file (<code>df</code>):</p>
<pre><code>text text2 ... | <p>I'm not really an expert, maybe I'm wrong. However, shouldn't you use a model appropriate for your task (something like a <code>TFRobertaForTokenClassification</code> or <code>TFRobertaForSequenceClassification</code>, etc.). See the <a href="https://huggingface.co/transformers/v3.0.2/model_doc/roberta.html#tfrobert... | python|tensorflow|keras|huggingface-transformers|roberta | 1 |
2,295 | 73,336,937 | What is the difference between list and 1-D array ? and what is the difference between series and dictionary? | <p>What is the difference between list and 1-D array ? and what is the difference between series and dictionary ?</p> | <p>Welcome to Stackoverflow :)
list and dictionary are data types in python to hold data. The 1-D array is a data structure similar to a list that can contain any kind of data.
Both list or NumPy arrays can be one or multidimensional.
1-D means that every element in a list or in an array can be accessed by one index.
e... | python-3.x|pandas|series | 0 |
2,296 | 67,339,906 | Convert a list to dictionary | <p>Hello is there a way to split this dataset to dictionary where the word will be the key and the value will be a list of numbers separated with comma ?</p>
<pre><code>content =
['the 0.125 0.8542 1.253 \n',
'of 0.678 0.568 0.184 \n',
'that 0.565 0.897 0.267 \n']
</code></pre> | <pre><code>content = [
"the 0.125 0.8542 1.253 \n",
"of 0.678 0.568 0.184 \n",
"that 0.565 0.897 0.267 \n",
]
out = {c.split()[0]: [float(x) for x in c.split()[1:]] for c in content}
print(out)
</code></pre>
<p>Prints:</p>
<pre><code>{'the': [0.125, 0.8542, 1.253], 'of': [0.67... | pandas|dataframe|txt | 0 |
2,297 | 67,276,943 | Editing a column to equal its first value | <p>I have some inconsistencies with some data that I would like to fix</p>
<pre><code>import pandas as pd
import numpy
import io
datastring = """
ride_id,start_time,end_time,driver_id,region,is_completed
4,5,2021-01-15 21:02:58,NaN,2,Cape Town,1
26,27,2021-03-31 21:51:00,NaN,2,San Francisco,1
0,1,20... | <p>Use of <code>groupby</code> will group observations by <code>driver_id</code>. Use of <code>transform</code> will let you set every row in a group to the first row value.</p>
<pre><code>dddd['region'] = dddd.groupby('driver_id')['region'].transform('first')
</code></pre> | python|pandas | 1 |
2,298 | 67,205,527 | Append dataframe columns in a loop to yield a single dataframe | <p>I wrote code to extract data from a csv and put them into a dataframe and sort them after. The code looks as such:</p>
<pre><code>def highest_value_sorter(value):
sorted_df = df_result[value].astype('float64').sort_values(ascending=False)
sorted_df = sorted_df.head(10).to_frame().reset_index()
return sor... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pandas.concat()</code></a> to concat list of dataframes on columns with <code>axis</code> set to 1.</p>
<pre class="lang-py prettyprint-override"><code>dfs = []
for value in values:
sorted_tmp_d... | python|pandas | 2 |
2,299 | 60,045,913 | Installing numpy before using numpy.distutils.core.setup | <p>I am using <code>numpy.distutils</code> to setup a package (mypackage) that has a frotran module. The problem is that if I do <code>pip install mypackage</code> on an environment that does not have numpy, I get the following error:</p>
<blockquote>
<p>ModuleNotFoundError: No module named 'numpy'</p>
</blockquote>... | <p>It is a common issue. How to install a <em>build-time</em> dependency? You might want to use a <code>pyproject.toml</code> file and take advantage of the <code>build-system</code> feature. See <a href="https://www.python.org/dev/peps/pep-0517/" rel="nofollow noreferrer">PEP517</a>. And an example here:</p>
<pre><co... | python|numpy|installation|setuptools|f2py | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.