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 |
|---|---|---|---|---|---|---|
351,000 | 67,142,257 | Split DataFrame as per series values | <p>I am working on a Netflix dataset where some columns having comma-separated values.
I would like a have count of shows released per country but data is like</p>
<p><a href="https://i.stack.imgur.com/wbsso.png" rel="nofollow noreferrer">Image of dataset</a></p>
<p>How do I split the data and make it countrywide like ... | <p>You can split the comma-separated string to the list and then apply 'explode' to that column.</p>
<pre><code>df['country'] = df['country'].str.split(',')
df = df.explode('country')
print(df)
</code></pre> | python|pandas|data-analysis | 1 |
351,001 | 66,944,098 | Pandas convert multilabeled column into separate encoded columns | <p>I have a Pandas series that looks like this:</p>
<pre><code>0 NaN
1 NaN
2 red almond
3 blue walnut
4 RED ALMOND,B... | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>In [55]: from collections import Counter
In [56]: s = pd.Series([None, None, "red almond", "blue walnut", "RED ALMOND,BLUE WALN... | python|pandas | 0 |
351,002 | 67,010,760 | Doubts about pandas axis working my code may be off | <p>My issue is the following, I'm creating a pandas data frame from a dictionary that ends up looking like [70k, 300]. I'm trying to normalise each cell be it either by columns and after rows, and other way around rows then columns.</p>
<p>I ha asked a similar question before but this was with a [70k, 70k] data frame s... | <p>I think your new code is doing what you want.</p>
<p>If we look at a 3x3 toy example:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame([
[1, 2, 3],
[2, 4, 6],
[3, 6, 9],
])
</code></pre>
<p>The <code>axis=1</code> mean is:</p>
<pre class="lang-py prettyprint-override"><code>df.mean(a... | python|pandas|row|normalization | 1 |
351,003 | 67,037,458 | Python issue adding a column to a dataframe using a function I have defined | <p>I'm really new to Python (knew nothing before Christmas), am self taught and am having a bit of an issue with dataframes.</p>
<p>I'm importing data from a CSV into a dataframe in Python using Pandas.
This data has a DateTime field called "ItemTime".
What I need to do is split ItemTime into "Date"... | <p>It's been a while since I worked with pandas, that being said it doesn't look like you turned details into a data frame so you won't have all the functionality of a data frame.</p>
<p>Have you tried</p>
<p><code>detail = pd.read_csv(<the filename>, usecols=['SiteID', 'TransactionID', 'ItemTime', 'TotalGross', ... | python|python-3.x|pandas|dataframe | 0 |
351,004 | 67,038,279 | Pandas: pd.DateOffset error while adding weeks to date | <p>I am trying create a column 'planned_off_hire_date' that is basically 'complete_date' plus number of weeks in 'hire_duration' column.</p>
<p><strong>My df:</strong></p>
<pre><code> complete_date hire_duration_wks planned_off_hire_date
2020-12-27 13.0 NaT
2020-12-3... | <p>Instead of using this:</p>
<pre><code>df['planned_off_hire_date'] = df['complete_date'] + pd.DateOffset(weeks=(df['hire_duration_wks']))
</code></pre>
<p>Make use of <code>apply()</code> method:</p>
<pre><code>df['planned_off_hire_date']=df['complete_date'] + df['hire_duration_wks'].apply(lambda x:pd.DateOffset(week... | python|python-3.x|pandas | 0 |
351,005 | 67,116,877 | Image copy does not show the same image on OpenCV | <p>I would like to display a copy of an image but it does not work.</p>
<pre><code>def display_and_close(img):
cv2.imshow("test",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('assets/tests.jpeg',0)
width, height = img.shape
new_img = np.zeros((width, height))
new_img[:width, :heigh... | <p>You need to specify the dtype as uint8 for your black image in Python/OpenCV or it will default to float.</p>
<p>So replace</p>
<pre><code>new_img = np.zeros((width, height))
</code></pre>
<p>with</p>
<pre><code>new_img = np.zeros((width, height), dtype=np.uint8)
</code></pre>
<p>Also note that Numpy and shape use y... | python|numpy|opencv | 1 |
351,006 | 66,985,786 | How to subtract a dataframe from a dataframe based on columns? | <p>I have below dataframes</p>
<pre><code>df1 = pd.DataFrame({
'contact_id': [1,3,4,5,-1],
'subscription_id': ['AAA', 'ccc', 'ddd', 'eee', 'fff']
});
print(df1)
contact_id subscription_id
0 1 AAA
1 3 ccc
2 4 ddd
3 5 eee... | <p>What you want is basically result of <code>Left join</code> minus result of <code>Inner Join</code>. This looks like a typical case of <code>merge</code> not <code>pd.concat</code>.</p>
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>df.merge<... | python|pandas|dataframe | 3 |
351,007 | 66,978,528 | Pandas groupby aggregation multiple sums | <p>Newbie question. I would like to calculate a dataframe column using two summed up columns like so:</p>
<pre><code>grouped_columns = df1.groupby(['Parent1', 'Parent2']).agg(Attr_fac = ('Exposure1', 'sum') / ('Exposure2', 'sum'))
</code></pre>
<p>keep getting TypeError: Unsupported operand type(s) for /: 'tuple' and ... | <p>You can't really do <code>('Exposure1', 'sum') / ('Exposure2', 'sum')</code> hence the error. You can try:</p>
<pre><code>grouped_columns = (df1.groupby(['Parent1', 'Parent2'])
[['Exposure1','Exposure2']].sum()
.assign(Attr_fac=lambda x: x['Exposure1']/x['Exposure2'])
... | python|pandas | 1 |
351,008 | 66,939,091 | Input 0 of layer sequential is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: [None, 67500] | <p><strong>I am having an issue in predicting from cnn model</strong></p>
<p><a href="https://i.stack.imgur.com/xnAU2.png" rel="nofollow noreferrer">model structure</a></p>
<pre><code>from tensorflow.keras.preprocessing import image
import numpy as np
img = image.load_img("test/apple/apple.jpg", target_size... | <p>You are flattening image, but your model <code>takes batch-wise image data</code>.
<strong>Add a dimension</strong> using <a href="https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html" rel="nofollow noreferrer">np.expand_dims</a> to the resized image and pass to model for prediction.</p>
<p>Try in... | tensorflow|machine-learning|deep-learning|computer-vision|conv-neural-network | 0 |
351,009 | 66,891,160 | How can I solve the shpe and reconstract CNN for this project? | <p>when I train this network on medical images data
-train
-benign
-normal
-cancer
-test
-benign
-normal
-cancer
-valid
-benign
-normal
-cancer
I get an error when I do training</p>
<p>this is data loading.
import os
import torch
from torchvision import datasets, transforms</p>
<pre><code>### TODO: Write data loaders f... | <p>its because you have a model definition which have <code>1 channel</code>...and your <code>datasets</code> class have images of <code>3 channels</code><br />
So in your model should be written as</p>
<pre><code>import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
... | python|deep-learning|pytorch|conv-neural-network|medical-imaging | 0 |
351,010 | 66,929,799 | pandas How to insert the column name of datafram into the mysql table as value instead of inserting it as field name | <p>i have a datafram simplely like this:</p>
<pre><code>import numpy as np
import pandas as pd
dataA = [["2005-1-20", "9:35", 5, 15, 5], ["2005-1-20", "9:40", 8, 6, 1], ["2005-1-20", "9:45", 7, 5, 6],
["2005-1-20","9:50", 4, 8, 3]]
df =... | <p>Try</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(np.vstack([df.columns, df]))
</code></pre>
<p>before you do <code>df.to_sql(...)</code></p>
<p>taken from here <a href="https://stackoverflow.com/questions/43975986/conversion-column-names-into-first-row">conversion column names into first row... | python|mysql|pandas|dataframe | 1 |
351,011 | 67,019,360 | How to add metadata to a tensorflow lite file converted from a tensorflow file | <p>I am trying to add a tensorflow lite file to Android studio but when I add it, I get an error saying metadata not found. I have the tensorflow model working remotely on my laptop to a 70% accuracy. I used the following code to convert from tensorflow to tensorflow lite.</p>
<pre><code>import tensorflow as tf
model ... | <p>Metadata is required when there is a need to use tflite support library. Since you already have the converted tflite model, you can use tflite interpreter API directly to run the converted model. Please refer to the tflite android page. <a href="https://www.tensorflow.org/lite/guide/android" rel="nofollow noreferre... | android-studio|tensorflow|tensorflow-lite | 0 |
351,012 | 67,140,090 | ODE with time-varying coefficients in scipy | <p>I am evaluating a set of ODEs with time varying coefficients</p>
<pre><code>def deriv(y, t, N, coefficients):
S, I, R = y
dSdt = coefficients['beta'](t) * S * I / N * -1
dIdt = coefficients['beta'](t) * S * I / N - coefficients['gamma']* I
dRdt = coefficients['gamma'] * I
return dSdt, dIdt, dRdt
... | <p>Since <code>len(mybetas) == int(max(t))</code>, you can get an out-of-bounds error even for values of t which are not beyond max(t).
For example, <code>mybetas.iloc[int(max(t))]</code> will give you the out-of-bounds error, even though <code>int(max(t)) <= max(t)</code> for positive values of <code>t</code>.</p>
... | python|numpy|scipy|ode | 1 |
351,013 | 67,182,782 | Integrating pandas-profiling report in dash app | <p>How to integrate pandas-profiling report into a dash app?</p>
<p><a href="https://pandas-profiling.github.io/pandas-profiling/docs/master/rtd/" rel="nofollow noreferrer">Pandas Profiling</a></p>
<p>Streamlit allows these integrations (but I'm having a hard time managing cache/sessions in it)
<a href="https://discuss... | <p>You have 2 options:</p>
<h4>Generate de html page and loadt it as an asset in Dash:</h4>
<pre><code>1 - Create the Report
profile = ProfileReport(df, title="Pandas Profiling Report")
profile.to_file("your_report.html")
2 - Load the html report
https://github.com/plotly/dash-core-components/iss... | python|pandas|plotly-dash|streamlit|pandas-profiling | 1 |
351,014 | 66,914,097 | Pandas dataframe - add suffix to column value only if it is repeated | <p>I have a column in a data frame which looks like -</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Key</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
</tr>
<tr>
<td>B</td>
</tr>
<tr>
<td>C</td>
</tr>
<tr>
<td>A</td>
</tr>
<tr>
<td>A</td>
</tr>
</tbody>
</table>
</div>
<p>I want to transform... | <p>Let us try with <code>cumcount</code> then <code>mask</code> with total <code>count</code> for each group</p>
<pre><code>g = df.groupby('Key')
df['Key'] += g.cumcount().add(1).astype(str).radd('_').mask(g['Key'].transform('count')==1,'')
df
Key
0 A_1
1 B
2 C
3 A_2
4 A_3
</code></pre> | python|pandas|dataframe|pandas-groupby | 3 |
351,015 | 66,790,985 | Selecting a column from a conditional loop on a pandas dataframe | <p>I have a pandas dataframe with five rows 3 three columns. I want to create a function where my code returns columns where the last row is greater than the first row. In my code example I want it to generate a list with the column name 'Temp01'. I fumbled when creating the if / else to check the columns whose last ro... | <pre><code>import pandas as pd
#Create Dataframe
df0 = pd.DataFrame({'Temp01':[10,20,30,40,15],'Temp02':[50,60,70,70,45],'Temp03':[80,90,100,100,75]})
lst=[]
for col_name in df0.columns:
if df0[col_name].iloc[-1]>df0[col_name].iloc[0]:
lst.append(col_name)
print(lst)
</code></pre> | python|pandas|dataframe | 1 |
351,016 | 66,803,148 | Pass row numbers while using apply() function in a column in Pandas | <p>So basically what I am trying to do is to format date column. Dates are given as : 24th Mar, 5th Jul and so on. I wrote a function to split these and make it like 24/03 and 05/07. But the problem is that for rows 0 to 8 in my pandas data frame it is for 2021 and rest of the rows is for 2020. So basically with the cu... | <p>Instead of row-wise parsing the dates (which can be slow) we can <code>replace</code> the abbreviations, and add the years to the first few rows. This then allows us to easily convert to a <code>datetime</code> dtype which has the ability easily format the dates into your strings with <code>strftime</code>.</p>
<p>I... | python|pandas|apply|data-cleaning | 1 |
351,017 | 66,819,584 | How to extract time series of pairwise correlation from correlation matrix calculated using pandas.ewm? | <p>I have time-series data of asset return. Return data frame index are dates and columns are asset names.</p>
<pre><code> L/S HF US World
1995-02-28 0.030366 0.029288 0.014742
1995-03-31 0.008086 0.017165 0.027338
1995-04-28 0.013615 0.013851 0.018561
1995-05-31 0.020304 0.029865 ... | <p>This should work for the 'US'/'World' correlation (same idea for other pairs):</p>
<pre><code>corHist.xs('US',level=1)['World']
</code></pre>
<p>produces (for your basic example) a Series:</p>
<pre><code>1995-02-28 NaN
1995-03-31 -1.000000
1995-04-28 -0.484825
1995-05-31 -0.592066
1995-06-30 0.43344... | python|pandas|correlation | 1 |
351,018 | 67,177,900 | How to name and color different traces plotly graph objects? | <p>I have following problem using plotly graph objects:
I am currently working with airline-data.
My aim is to create a bubble / scatter plot where I can show which airline, traveled how far and how many flights they needed.</p>
<p>The problem is, that I can't get the points to match the legend correctly.</p>
<pre><cod... | <p>The data to create the graph was created appropriately, so please replace it. Specify the airline name in the loop process of the scatter plot.</p>
<pre><code>import plotly.graph_objects as go
import pandas as pd
import numpy as np
import random
airline_names = ['AA - American Airlines', 'AS - Alaska Airlines', 'B6... | python|pandas|dataframe|plotly-python | 0 |
351,019 | 66,998,010 | How to pivot from columns to rows in Pandas | <pre><code>data = [[1, 'tom', 10, 53, 2, 3, 9, 6 ], [2, 'nick', 1, 53, 2, 23, 4, 7], [3, 'juli', 9, 23, 2, 31, 9, 3]]
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Apple.Food.0', 'Apple.Food.1', 'Apple.Food.2', 'Pear.Food.0', 'Pear.Food.1', 'Pear.Food.2'])
df
</code></pre>
<div class="s-table-container">
<tab... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> for <code>MultiIndex</code> with columns without <code>.</code> first, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.... | python|pandas | 2 |
351,020 | 67,134,902 | loss defined on repeated evaluation of the same model | <p>I have a model denoted by <code>f()</code>,</p>
<p>Suppose the target is <code>t</code>, <code>f(x1) = y1</code> and <code>f(x2) = y2</code> and my loss is defined as<br />
<code>loss = mse(y1,y2) + mse(y2,t)</code></p>
<p>Since both <code>y1</code> and <code>y2</code> reguires grad, I have received error such as</p... | <blockquote>
<p>Suppose the target is <code>t</code>, <code>f(x1) = y1</code> and <code>f(x2) = y2</code> and my loss is defined as
<code>loss = mse(y1,y2) + mse(y2,t)</code></p>
<p>Since both <code>y1</code> and <code>y2</code> reguires grad, I have received error such as</p>
</blockquote>
<p>This statement is incorre... | neural-network|pytorch | 1 |
351,021 | 66,773,024 | Mapping values in one DataFrame based on the data from external data table | <p>I have DF as below of actual features' values (more than 6000 rows):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>A</td>
<td>acc</td>
<td>?</td>
</tr>
<tr>
<td>2</td>
<td>B</td>
<td>bcc</td>
<td>?</td>
... | <p>Try with <code>merge</code> then filter with range</p>
<pre><code>out = df1.merge(df2,on=['B','C'],how='left')
out = out[(out['A']>=out['A min']) & (out['A']<=out['A max'])]
out
Out[421]:
A B C Amin Amax D
0 1 A acc 1.0 5.0 120.0
</code></pre> | python|pandas|apply | 1 |
351,022 | 66,916,566 | How to use df.apply to switch between columns? | <p>Consider the following code.</p>
<pre><code>import pandas as pd
np.random.seed(0)
df_H = pd.DataFrame( {'L0': np.random.randn(100),
'OneAndZero': np.random.randn(100),
'OneAndTwo': np.random.randn(100),
'GTwo': np.random.randn(100),
... | <p>Just because it is Good Friday, we can try the following. Else it is a commonly asked question.</p>
<pre><code>c1=df_H['Decide'].le(0)
c2=df_H['Decide'].between(0,1)
c3=df_H['Decide'].between(1,2)
c4=df_H['Decide'].gt(2)
cond=[c1,c2,c3,c4]
choices=[df_H['L0'],df_H['OneAndZero'],df_H['OneAndTwo'],df_H['GTwo']]
... | python|pandas | 2 |
351,023 | 67,165,078 | python apply function with df as input | <p>I have a function that uses 2 dataframes and a number as inputs. I want to apply that function to every row in a dataframe while using an input from that dataframe in the aforementioned function.</p>
<pre><code>def function(df1, df2, number):
df3['result'] = df3['number'].apply(function, args=(df1, df2, df3['number... | <p>@Quang solutions is good, you can also explicitly use a lambda which might increase readability:</p>
<pre><code>df3['result'] = df3['number'].apply(
lambda s: function(df1, df2, s)
)
</code></pre> | python|pandas|apply | 0 |
351,024 | 66,894,190 | How to compare two dataframes with multiple data types | <p>I am trying to compare two dataframes and print the difference. When I try to compare I get a "ValueError: Can only compare identically-labeled Series objects"</p>
<p>Here are samples of the dataframes I am comparing.</p>
<pre><code> Name NetAmount
0 AARON, ANN 440.40
1 AARON... | <p>To be generic that the 2 dataframes can be of different sizes, you can compare values in dataframe <code>a</code> column <code>Name</code> with the list of all <code>Name</code> fields in dataframe <code>b</code>. Repeat for the other side.</p>
<p>Build mask of a.Name not in b.Name.to_list() then use <code>.loc[]... | python|pandas|dataframe|compare | 0 |
351,025 | 66,770,911 | np.where in a loop overwriting all the values | <p>I want to recode the values in my label array so that the labels 0,1,2 correspond to the center values
1.00162877,0.74014188,1.16120161</p>
<pre><code>import numpy as np
label=np.array([0, 2, 1, 1, 2, 1, 0, 0, 1, 2])
center=np.array([[1.00162877],
[0.74014188],
[1.16120161]])
</code></pre>
<p>Using the np.wher... | <p>This is not a loop but I think it works:</p>
<pre><code>center[label].ravel()
</code></pre>
<p>Output:</p>
<pre><code>array([1.00162877, 1.16120161, 0.74014188, 0.74014188, 1.16120161,
0.74014188, 1.00162877, 1.00162877, 0.74014188, 1.16120161])
</code></pre> | python-3.x|numpy | 2 |
351,026 | 66,995,543 | Rounding up values using np.ceil | <p>Why does np.ceil give me different answers for what should equivalent expressions?</p>
<pre><code>np.ceil(336)
Out[34]: 336.0
np.ceil(100*(2.85+0.43+.08))
Out[35]: 337.0
</code></pre> | <h1>Ceil</h1>
<p>The ceil of the scalar number x is the smallest number i, that is larger or equal to x (i.e., i>=x).</p>
<p>The first expression 336 is having data type int.</p>
<p>Whereas on evaluating the next expression it is found that the <strong>result is not 336</strong> but <strong>336.00000000000006</stron... | numpy|rounding|ceil | 1 |
351,027 | 67,176,572 | Parsing CSV data with unmatched column - Python Pandas | <p>I have a CSV file which contain unmatched columns, (i.e) first row will have 8 columns and second row will have 10 columns like below,</p>
<p>input.csv,</p>
<pre><code>B|prem|29|get|get1|get2|get3|
T|prem1|30|get|get1|get2|get3|get4|get5|get6
B|prem2|31|get|get1|get2|get3|
T|prem1|30|get|get1|get2|get3|get4|get5|get... | <p>You can try <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer"><code>itertools.groupby()</code></a></p>
<pre class="lang-py prettyprint-override"><code>import itertools
import pandas as pd
from io import StringIO
with open('test.csv') as f:
lines = f.read().sp... | python|pandas|csv | 3 |
351,028 | 66,811,500 | How do I group a dataframe by a column Id and then label 2 days intervals within the groups? | <p>I have a dataset that contains 5 columns where the first column is a visitorId, second column is a datetime, and the last column is a searchId. It looks something like that</p>
<pre><code>|visitorId | datetime |searchId |
|:---------|:---------:|--------:|
| 123 | 2020-06-06| abd |
| 123 | 2020-0... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.diff.html" rel="nofollow noreferrer"><code>Series.diff()</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumsum.html" rel="nofollow noreferrer"><code>GroupBy.cumsum()</co... | python|pandas|dataframe|pandas-groupby | 2 |
351,029 | 67,064,790 | Filtering multiple csv files by creation date and concatenate into one pandas DataFrame | <p>I would like to read just csv last 7 days createds csv files from a directory into pandas and concatenate them into one big DataFrame. I have not been able to figure it out though. Here is what I have so far:</p>
<p>Edit: I'm trying to filter by the creation date of csv file, not by any column in csv.</p>
<pre><code... | <p>You could do something like this.</p>
<pre><code>df = pd.DataFrame()
for filename in all_files:
df = df.append(pd.read_csv(filename))
</code></pre> | python|pandas|dataframe|csv|filtering | 0 |
351,030 | 66,807,890 | h5py: How to abstract indices | <p>I have an HDF5 file with subgroups that I currently index like:</p>
<pre><code>file = h5py.File(filename, 'r')
data = np.array(file[index1][index2][index3])
</code></pre>
<p>I would rather abstract those indices and pass a list instead (<code>indices = [index1, index2, index3]</code>) but I can't think of a more eff... | <p>I don't entirely understand what you are trying to do.</p>
<ul>
<li>Are <code>index1, index2, and index3</code> all datasets at the root level (aka
the file group, so you have <code>/index1</code>, <code>/index2</code>, and <code>/index3</code>).</li>
<li>Or is <code>index1</code> a group, <code>index2</code> a subg... | python|numpy|indexing|h5py | 1 |
351,031 | 66,888,011 | create representation of questions using LSTM via a pre-trained word embedding such as GloVe | <p>I am new in LSTM and python. My goal is to represent the sentence using LSTM.
Could u tell me I am doing the right? how to fix the error when running the following code ?</p>
<p>"TypeError: embedding(): argument 'indices' (position 2) must be Tensor, not str"</p>
<pre><code>import torch
import torch.nn as ... | <p>Please see <a href="https://pytorch.org/tutorials/beginner/nlp/word_embeddings_tutorial.html" rel="nofollow noreferrer">torch embedding tutorial</a> and <a href="https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/" rel="nofollow noreferrer">use embedding with keras</a> for knowledge abo... | python|nlp|pytorch|lstm|embedding | 0 |
351,032 | 67,160,592 | RuntimeError: Expected 4-dimensional input for 4-dimensional weight [256, 1, 3, 3], but got 3-dimensional input of size [64, 1, 786] instead | <p>I'm trying to combine the CausalConv1d with Conv2d as the encoder of my VAE. But I got this error which is produced on Encoder part. The CausalConv1d is implemented by a nn.Conv1d network, So it should only have 3-dimensional weight, but why the error says expected 4-dimensional? And I have another question, why I ... | <p>I know this may not be intuitive, but when you use a <code>kernel_size</code> with 2-dim (e.g., <code>(3,3)</code>), then your <code>Conv1d</code> has 4-dim weights. Therefore, to solve your issue, you must change from:</p>
<pre class="lang-py prettyprint-override"><code>CausalConv1d(in_channels,out_channels,kernel_... | pytorch | 0 |
351,033 | 67,014,613 | PyTorch - Change weights of Conv2d | <p>For some reason, I cannot seem to assign all the weights of a Conv2d layer in PyTorch - I have to do it in two steps. Can anyone help me with what I am doing wrong?</p>
<pre><code>layer = torch.nn.Conv2d(in_channels=1, out_channels=2, kernel_size=(2,2), stride=(2,2))
layer.state_dict()['weight']
</code></pre>
<p>giv... | <p>I'm not sure about why you can't directly assign them but the more proper way to achieve what you're trying to do would be</p>
<pre><code>layer.load_state_dict({'weight': torch.tensor([[[[0.4738, -0.2197],
[-0.3436, -0.0754]]],
[[[0.1662, 0.4098],
[-0.4... | pytorch|tensor | 1 |
351,034 | 66,873,206 | loc method to update the values in an existing column consistency? | <p>I have the following toy example of a dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a':[1, 2, 3, 4, 5], 'b':['aa', 'bb', 'cc', 'dd', 'ee']})
</code></pre>
<p>And here is what I am doing:</p>
<pre><code>df.loc[df.a < 3, 'a'] = df.a * 0.95
</code></pre>
<p>Please advise how pandas "knows&qu... | <p>When you use the condition <code>df.a < 3</code>, Pandas will effectively take note of the indices in the dataframe for which the condition holds true. Therefore, when it applies the transformation: <code>df.a * 0.95</code>, it knows to only apply it to the relevant indices.</p> | python-3.x|pandas|dataframe | 1 |
351,035 | 66,933,093 | Cumulative count at group level with boolean indexing in Pandas | <p>I'm developing an answer to <a href="https://stackoverflow.com/questions/66932614/cumulative-count-at-a-group-level-python">this</a> question that just uses boolean indexing rather than <code>cumcount</code>. The intended output is a column <code>total_paid_invoices</code> that — for each company — counts the number... | <p>Thanks to @rafaelc for pointing out the overwriting issue. You need to index for <code>company</code> on both sides of <code>=</code> to apply the lambda function to subsets of the dataframe at a time:</p>
<pre><code>for company in df.company.unique():
df.loc[df.company==company, 'total_paid_invoices'] = df.date... | python|pandas | 1 |
351,036 | 67,104,630 | Use filename as an indicator to process datetime columns using pandas | <p>I am reading 15 csv files into pandas dataframe. The columns that I want in final dataframe are spread across multiple csv files</p>
<p>Filename pattern for file 1 to file 8 - Med* (ex: Med1, Med2, Medtest, Medkill)</p>
<p>Sample data from file 1 to file 8 looks like below</p>
<pre><code>df = pd.DataFrame({'person_i... | <p>Use <code>if</code> statemenet for test by filenames:</p>
<pre><code>import os
#custom function for add values by duration
def func(x):
if pd.isna(x['dur']):
return x['start_date']
elif x[1] == 'w':
return x['start_date'] + pd.offsets.DateOffset(weeks=x[0])
elif x[1] == 'm':
re... | python|pandas|dataframe|numpy|series | 1 |
351,037 | 66,893,949 | Why does tensorflow show inaccurate loss? | <p>I'm using Tensorflow to train a network to predict the third item in a list of numbers.</p>
<p>When I train, the network appears to train quite well and do well on both the training and test set. However, when I evaluate its performance myself, it seems to be doing quite poorly.</p>
<p>For example, at the end of tra... | <p>What you miss is that the shape of <code>y_test</code>.</p>
<pre><code>y_test.numpy().shape
(500,) <-- causing the behaviour
</code></pre>
<p>Simply reshape it like:</p>
<pre><code>val_loss = tf.math.reduce_mean(tf.keras.losses.MSE(y_test.numpy().reshape(-1,1), model.predict(x_test))).numpy()
print(val_loss) # 1.... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
351,038 | 67,166,498 | Converting an API response into Python Pandas Data Frame | <p>Dear community experts</p>
<p>I have an API returning the following structure that I need to convert into a pandas data frame.
How could I do to create such Data Frame?.</p>
<p>Thanks, Hernan</p>
<pre><code>[{'quoteSymbol': 'USDT',
'baseSymbol': 'ETH',
'orderBooks': [{'exchange': 'Bittrex',
'orderBook': {'as... | <p>My suggestion is to first transform the JSON you have into a list of dictionaries. Each dictionary should have keys that correspond to the columns you want in the final dataframe.</p> | python|pandas|api | 0 |
351,039 | 66,891,003 | One Dataset causes ```IndexError: list index out of range``` while other runs perfectly | <p><strong>My Dataset</strong></p>
<ul>
<li>In numpy array</li>
<li><code>np.shape(data)</code> -> (6989, 4)</li>
<li><code>stats.describe(data)</code> -> DescribeResult(nobs=6989, minmax=(array([0., 0., 0., 0.]), array([ 299.99, 86785. , 10997. , 13222. ])), mean=array([ 12.47994992, 3407.00243239, 27.232... | <p>The issue was solved by adding more colors. Ex.:</p>
<p><code>color_palette = sns.color_palette('Paired', 1000)</code></p> | python|arrays|numpy | 0 |
351,040 | 66,988,303 | Kaggle: Dealing with extra unlabelled test data in CNN | <p>I'm doing a kaggle competition and I've got extra test data that I don't have labels for.</p>
<p>I have a train.txt file which has the format</p>
<pre><code>train/0.jpg 5
train/1.jpg 1
train/2.jpg 10
train/3.jpg 2
train/4.jpg 22
train/5.jpg 3
etc...
</code></pre>
<p>So image 0.jpg is of class 5 for example.</p>
<p>T... | <p>Unless you label the data yourself (by hand) or have another (superior) model at hand, there is not much you can do with the unlabeled "test" data.</p>
<p>The idea of test data is to compare the predicted results with the true labels - if you don't have them, you should discard the data from the test set.<... | python|tensorflow|keras|conv-neural-network|kaggle | 1 |
351,041 | 66,802,938 | Merging several string columns with possible duplicates in a pandas dataframe | <p>I'm trying to migrate data between two of our systems and one system has descriptions split across multiple columns while the destination system only has one column. So I need to merge these 5 columns into a single column while removing possible duplicates.</p>
<p>Here is what I have so far, which works, but is ther... | <p>You can use <code>pandas.unique()</code>: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.unique.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.unique.html</a></p>
<p>Here is my implementation, I replaced your <code>\n</code> character wit... | python|pandas|dataframe|duplicates|string-concatenation | 1 |
351,042 | 66,854,172 | Keeping only the Last occurrences of a data in column on a given date in pandas | <p>I'm pretty new to pandas so bear with me. I have 1 min interval wise data time frame for few years. Each row have a <code>Long Stop Loss Signal</code> column . My index for data frame is date time column.</p>
<p>Ignore the other columns ,</p>
<p><a href="https://i.stack.imgur.com/E4AC4.png" rel="nofollow noreferrer"... | <p>You can <code>groupby</code> using <code>dt.day</code> to get daily results, and use <code>nlargest(1,keep='last')</code>on our column of interest. It's important that you use <code>last</code> because the default is <code>first</code> and will return back the index of first occurrence of 1. You can store your resu... | python|pandas | 1 |
351,043 | 67,013,152 | extract start and end of time interval based on a given date | <p>For a <code>df</code> column with dates (all in the past), I need to replace two columns with start and end dates surrounding given date. For each <code>df</code> row, there are two columns with current (relative to today<code>2021-4-9</code>) start and end dates that could be either of the two exact six month inte... | <p>This can be vectorized into 3 lines with <a href="https://numpy.org/doc/stable/reference/generated/numpy.sort.html" rel="nofollow noreferrer"><strong><code>np.sort()</code></strong></a> and <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><strong><code>np.where()<... | python-3.x|pandas | 1 |
351,044 | 67,139,587 | Pandas: How to sum columns on data frame based on value of another data frame | <p>I am new to Pandas and I am trying to do the following thing::</p>
<ul>
<li>I have a dataframe called <em>comms</em> with columns articleID and commentScore (among others)</li>
<li>I have another dataframe called <em>arts</em> with column articleID</li>
</ul>
<p>I need to create in <em>arts</em> a new column called ... | <pre><code>#article count and sum
df = df.groupby('artID').agg(['sum', 'count'])
#create new column and utilize your formula
df['artScore'] = df['commScore']['sum'] / math.sqrt(df['commScore']['count']+1)
commScore artScore
sum count
artID
1x5w 5 2 5.0
3612 5 1 5.0
77k3 0... | python-3.x|pandas | 1 |
351,045 | 66,839,602 | ANSI SQL equivalent of pandas `factorize()`? | <p>So I have to create user IDs from user's emails and all data is present on BigQuery. In python, pandas, its an easy one-liner as:</p>
<pre><code>all_data['user_id'] = all_data['email'].factorize()[0]
</code></pre>
<p>But I cannot figure out a way to do this in BigQuery SQL. I tried using <code>RANK()</code> function... | <p>Consider below two options</p>
<p>Note, I am using slightly modified data example - you will see why (I hope)</p>
<pre><code>with `project.dataset.table` as (
select '2021-01-01 00:01:00' sent , 'email4@example.com' recipient union all
select '2021-01-01 00:02:00', 'email2@example.com' union all
select '20... | python|pandas|google-bigquery | 1 |
351,046 | 66,775,118 | Web scraping - scraping data for multiple URL's gives None | <p><strong>1)</strong> I am trying to scrape data for multiple URL's stored in CSV, but in result it gives None.</p>
<p><strong>2)</strong> I want to store the fetched data simultaneously in rows one by one in a dataframe named <code>df</code> but it only stores one row.</p>
<p>here's my code(i have pasted below from w... | <p>I don't think the end of your code is appending new lines to the dataframe.</p>
<p>Try replacing df["name""] = [name] and the other lines with the following:</p>
<pre class="lang-py prettyprint-override"><code>new_line = {
"name": [name],
"location": [loc],
"connec... | python|pandas|web-scraping|beautifulsoup|jupyter-notebook | 0 |
351,047 | 47,305,633 | language modeling in tensorflow - how to tie embedding and softmax weights | <p>As suggested by recent language modeling papers, I want to use weight tying in my RNN language model. That is, I want to share the weights between the embedding and softmax layer. However, I am not sure how this can be done in TensorFlow.</p>
<p>My network receives inputs of shape <code>(batch_size, sequence_length... | <p>I have figures out how to implement weight sharing correctly:</p>
<pre><code> with tf.variable_scope('embedding'):
self.embedding_matrix = tf.get_variable( "embedding", shape=[self.vocab_size, self.n_hidden], dtype=tf.float32, initializer=self.initializer)
[...]
# tie in... | tensorflow|nlp|language-model | 1 |
351,048 | 47,128,715 | Splitting tensors in tensorflow | <p>I want to split tensor into two parts: </p>
<pre><code>ipdb> mean_log_std
<tf.Tensor 'pi/add_5:0' shape=(?, 2) dtype=float32>
</code></pre>
<p>Context: ? is for number of samples and the other dimension is 2. I want to split along the second dimension into two tensorflow of shape 1 along that dimension.... | <p>You can <em>slice</em> the tensor at the second dimension with:</p>
<pre><code>x[:,0:1], x[:,1:2]
</code></pre>
<p>Or split on the second axis:</p>
<pre><code>y, z = tf.split(x, 2, axis=1)
</code></pre>
<hr>
<p><em>Example</em>:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
x = t... | tensorflow | 10 |
351,049 | 47,340,745 | Why automatically omits repeated values when making the conversion? | <p>I have the following dictionary :</p>
<pre><code>dict_1={'AB':50,'ACC':20,'CEKK':75,'AB':25,'CEKK':75,'BBA':58,'BBA':58 }
</code></pre>
<p>When I turn it into a df:</p>
<pre><code>pd.DataFrame(data=list(dict_1.values()),index=list(dict_1.keys()),columns=['number'])
</code></pre>
<p>It only provides each key from... | <p>Python dictionary eliminates all duplicates in keys <strong>before</strong> it gets to Pandas.</p>
<pre><code>In [466]: dict_1={'AB':50,'ACC':20,'CEKK':75,'AB':25,'CEKK':75,'BBA':58,'BBA':58 }
In [467]: dict_1
Out[467]: {'AB': 25, 'ACC': 20, 'BBA': 58, 'CEKK': 75}
</code></pre>
<p>Workaround:</p>
<pre><code>In [... | python|pandas | 2 |
351,050 | 47,333,990 | Dataframes: Replace Value in Column If 2 Separate Conditions are Met | <p>Logic I'm trying to implement:</p>
<ol>
<li>If 'phasename' column contains C1, C2, C4, or C18 AND 'reqmnt' column contains C</li>
<li>Replace C in requirement column with value in 'phasename' column</li>
<li><em>Otherwise</em> leave 'reqmnt' column as is</li>
</ol>
<p>Below is a sample screen shot of what I'm tryi... | <p>I <em>think</em> you're looking for <code>np.where</code>:</p>
<pre><code>v = ['C1', 'C2', 'C4', 'C18']
df.reqmnt = np.where(df.phasename.isin(v) & df.reqmnt.eq('C'), df.phasename, df.reqmnt)
</code></pre> | python|pandas|dictionary|dataframe | 0 |
351,051 | 47,465,542 | How to concatenate all (string) values in a given pandas dataframe row to one string? | <p>I have a pandas dataframe that looks like this:</p>
<pre><code> 0 1 2 3 4
0 I want to join strings
1 But only in row 1
</code></pre>
<p>The desired output should look like this:</p>
<pre><code> 0 1 2 3... | <p>IIUC, by using <code>apply</code> , <code>join</code></p>
<pre><code>df.apply(lambda x :' '.join(x.astype(str)),1)
Out[348]:
0 I want to join strings
1 But only in row 1
dtype: object
</code></pre>
<p>Then you can assign them</p>
<pre><code>df1=df.iloc[1:]
df1['5']=df.apply(lambda x :' '.join(x.astype... | python|string|pandas | 4 |
351,052 | 47,122,697 | Tensorflow: searching for an op supporting vector- tensor broadcasting | <p>I am trying to achieve something like:</p>
<p>inputs: </p>
<ol>
<li>x: a vector with length n, [x1,x2,...,xn], elements (xi, i=1,2,...n) are scalars.</li>
<li>T: a tensor with length n in its first dimension, [t1,t2,...tn], elements (ti, i=1,2,..,n) are tensors with rank 3.</li>
</ol>
<p>return: a tensor, <code>[... | <p>Just bring the two vectors to the same dimensions:</p>
<pre><code>T = tf.constant([[[[1,1]]],[[[2,2]]]])
x = tf.constant([3,4])
xr = tf.reshape(x, [-1,1,1,1])
res = T*xr
</code></pre>
<p>Running <code>res</code> will print:</p>
<pre><code> [[[[3, 3]]],[[[8, 8]]]]
</code></pre>
<p>which is exactly what you're as... | python|tensorflow | 1 |
351,053 | 47,245,655 | Pandas new way to convert daily data to weekly data? | <p>I pretty much copied the code <a href="https://gist.github.com/prithwi/339f87bf9c3c37bb3188" rel="nofollow noreferrer">here</a> to convert my daily stock data to weekly data. It's saying that the how args in .resample() is now deprecated. I assume it wants me to do something like <code>.max()</code> and <code>.min()... | <p>Use <code>agg</code> instead of <code>how</code> inside resample (edit in the code link suggested) i.e </p>
<pre><code>output = df.resample('W').agg({'Open': take_first,
'High': 'max',
'Low': 'min',
'Close': take_last,
... | python-2.7|pandas | 3 |
351,054 | 47,364,539 | Get unique pairs of columns of a pandas dataframe | <p>I have a Pandas dataframe that looks as follows:</p>
<pre><code>name1 country1 name2 country2
A GER B USA
C GER E GER
D GER Y AUS
E GER A USA
</code></pre>
<p>I want to get a new dataframe with two columns <code>name</code> and ... | <p>First filter columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</code></a>, transpose, flatten values and create new <code>DataFrame</code> by constructor:</p>
<pre><code>a = df.filter(like='name').values.T.ravel()
b = df.fi... | pandas|dataframe|unique|multiple-columns | 4 |
351,055 | 47,424,128 | How to concatenate all values of a pandas dataframe into an integer in python? | <p>I have the following dataframe:</p>
<pre><code> 1 2 3 4 5 6 7 8 9 10
dog cat 1 1 0 1 1 1 0 0 1 0
dog 1 1 1 1 1 1 0 0 1 1
fox 1 1 1 1 1 1 0 0 1 1
jumps 1 1 1 1 1 1 0 1 1 1
over 1 1 1 1 1 1 0 0 1 1
the 1 1 1 1 ... | <p><strong>Option 1</strong><br>
<code>apply(str.join)</code> + <code>str.cat</code>:</p>
<pre><code>df.astype(str).apply(''.join, 1).str.cat(sep='')
'110111001011111100111111110011111111011111111100111111111011'
</code></pre>
<hr>
<p><strong>Option 2</strong><br>
<code>apply</code> + <code>np.add</code>, proposed b... | python|pandas|dataframe | 2 |
351,056 | 47,337,528 | TensorFlow DecodePng throws Value Error | <p>For decoding a png image, normally we use the following segment of code.</p>
<pre><code>image_placeholder = tf.placeholder(tf.string)
image_tensor = tf.read_file(image_placeholder)
image_tensor = tf.image.decode_png(image_tensor, channels=1)
</code></pre>
<p>For deploying a model using Tensorflow serving, I follow... | <p><code>tf.parse_example</code> operates on a batch ("rank 1"), and <code>decode_png</code> expects a single image (a scalar string, "rank 0"). I'd either use <a href="https://www.tensorflow.org/api_docs/python/tf/parse_single_example" rel="nofollow noreferrer">tf.parse_single_example</a> or add a <code>reshape</code>... | tensorflow|tensorflow-serving | 1 |
351,057 | 47,494,658 | Saving and running wide_deep.py model | <p>I've been playing around with the <a href="https://www.tensorflow.org/tutorials/wide_and_deep" rel="nofollow noreferrer">Tensorflow Wide and Deep tutorial</a> using the census dataset.</p>
<p>The linear/wide tutorial states:</p>
<pre><code>We will train a logistic regression model, and given an individual's inform... | <p>The function is <a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/estimator/Estimator#predict" rel="nofollow noreferrer">predict</a>, but I didn't figure out how to input one example data directly (I tried <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/inputs/numpy_input_fn" re... | tensorflow | 2 |
351,058 | 47,267,826 | Python: average of dictionary key values over panda values | <p>I have a rather complex data structure, namely dictionaries in a panda dataframe. Lets say I have this dataframe.</p>
<pre><code>trials_ = [1,2,1,2]
stimul_ = [1,1,2,2]
data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spike... | <p>For what you are asking I would advise restructuring your dataframe. Instead of constructing <code>featve</code> with:</p>
<pre><code>data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spikecount': [1]}], 'NaN']
data_ = {'pe... | python|python-3.x|pandas|dictionary|median | 1 |
351,059 | 47,267,636 | TensorFlow : How do i find my output node in my Tensorflow trained model? | <p>I am quite new in using Tensorflow, this is a sample of code that i found while googling. I tried to freeze the graph but it said that i need to input the correct output node. Since i am new to this, i am having a hard time to understand it. How do i find my output node in this code or do i need to freeze the whole ... | <p>You first need to read/load your already frozen graph.</p>
<pre><code>def load_graph(frozen_graph_filename):
# We load the protobuf file from the disk and parse it to retrieve the
# unserialized graph_def
with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
graph_def = tf.GraphDef()
g... | python|numpy|tensorflow | 12 |
351,060 | 47,275,577 | How to fill in an incrementing integer in Pandas | <p>Given a <code>pd.DataFrame</code> such as:</p>
<pre><code>print(pd.DataFrame([['a', 0, 'b'], ['c', 1, 'd'], ['f', 4, 'e']]))
0 1 2
0 a 0 b
1 c 1 d
2 f 4 e
</code></pre>
<p>I would like to "fill in" rows by incrementing on the integer column. That is, I would like to obtain:</p>
<pre><code> 0 1 ... | <p>You could turn your 1 column into an index and reindex using it:</p>
<pre><code>In [33]: df.set_index(1).reindex(range(df[1].iloc[0], df[1].iloc[-1]+1)).reset_index()
Out[33]:
1 0 2
0 0 a b
1 1 c d
2 2 NaN NaN
3 3 NaN NaN
4 4 f e
</code></pre>
<p>and then you could reorder the ... | python-3.x|pandas|dataframe|nan|fillna | 2 |
351,061 | 47,277,436 | How to use python structure array similar to matlab | <p>Good morning
I have thoroughly looked around to try figuring out a way to create a
matlab like struct array in python. My input .csv file is header less </p>
<p>My matlab code </p>
<pre><code> dumpdata = csvread('dumpdata.csv');
N_dumpdata_samples = length(dumpdata);
rec_sample_1second = struct('U... | <p>In Octave:</p>
<pre><code>>> data = struct('A',{}, 'B', {});
>> for s=1:1;5
data(s).A = s
for t=1:1:3
data(s).B(t) = s+t
end;
end;
</code></pre>
<p>producing</p>
<pre><code>>> data.A
ans = 1
ans = 2
ans = 3
ans = 4
ans = 5
>> data.B
ans =
2 3 ... | arrays|python-2.7|list|pandas|numpy | 1 |
351,062 | 47,105,442 | Custom display format for a pandas DatetimeIndex? | <p>I'd like to <em>display</em> a <code>DataFrame</code> using a custom format for the index.</p>
<p>I know how to convert a <code>DatetimeIndex</code> into string using some format, and I am also aware of the nice <a href="https://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow noreferrer" title="styli... | <p>I can only using string make up the format...</p>
<pre><code>df.index=df.index.astype(str)+' '+df.index.weekday_name.str[:3]
df
Out[1108]:
v
2017-01-01 Sun 0
2017-01-02 Mon 1
2017-01-03 Tue 2
</code></pre> | python|pandas | 0 |
351,063 | 47,254,705 | Unable to save and restore a trained TensorFlow Model | <p>I just read the <strong><a href="https://www.tensorflow.org/get_started/mnist/pros" rel="nofollow noreferrer">Deep MNIST for Experts</a></strong> tutorial and modified the <strong>mnist_deep.py</strong> code to save the trained model using
<code>saver = tf.train.Saver()</code> before creating the session and
<code... | <p>You didn't give explicit names to your placeholders:</p>
<pre class="lang-py prettyprint-override"><code># Create the model
x = tf.placeholder(tf.float32, [None, 784])
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
</code></pre>
<p>... as a result, they are named <code>Placeholder</code... | python|tensorflow|conv-neural-network|restore|machine-learning-model | 3 |
351,064 | 47,192,133 | Python Pandas: Cumulative Sum based on multiple conditions | <p>I am calculating the value for the <em>Total ‘1st’ Position</em> column (table below) and would like to do this using multiple conditions.</p>
<p>I want <em>Total ‘1st’ Position</em> to reflect the number of times a given athlete has won a race (as of a given day). </p>
<p>For example... see below that Steve's <em... | <p>You can do it this way:</p>
<pre><code>df = your_file
df.loc[(df['Position'] == 1), 'firsts'] = 1
df=df.fillna(0)
df['Total 1st Position'] = (df['firsts']*df['Position']).groupby(df['Athlete']).cumsum()
</code></pre>
<p>If we run your data frame through this we get the following:</p>
<pre><code> Race Day Athl... | python|pandas | 3 |
351,065 | 47,147,749 | Data calculation in pandas python | <p>I have:</p>
<pre><code> A1 A2 Random data Random data2 Average Stddev
0 0.1 2.0 300 3000 1.05 1.343503
1 0.5 4.5 4500 450 2.50 2.828427
2 3.0 1.2 800 80 2.10 1.272792
3 9.0 9.0 900 90 9.00 0.000000
</c... | <p>Your error has to do with pandas preferring bitwise operators and using the built in min function isn't going to work row wise.</p>
<p>A potential solution would be to make two new calculated columns then using the pandas dataframe .min method.</p>
<pre><code>df['calc_col_1'] = df['Random data']-df['Average']
df['... | python|pandas|jupyter-notebook | 1 |
351,066 | 47,442,778 | Accuracy of learning algorithm drops after averaging features | <p>I have a huge dataset that I am trying to clean up. Within this dataset I have 6 columns that represent a rating system from 1-10. So the first column rates a person based on attractiveness, the second column based on intelligence, etc.</p>
<pre><code>attr1 attr2 attr3 attr4 attr5 attr6
2 5 6 8 ... | <p>Its natural that accuracy will decrease. You are taking <code>mean</code> but not correlation. In learning algorithm, internally <code>dependency</code> of value in one attribute is affecting the other. If you just average all attributes, how it can learn <code>dependency</code> of one on the other.</p>
<p>Another ... | pandas|machine-learning|neural-network|bigdata|prediction | 3 |
351,067 | 47,298,447 | How to fix low volatile GPU-Util with Tensorflow-GPU and Keras? | <p>I have a 4 GPU machine on which I run Tensorflow (GPU) with Keras. Some of my classification problems take several hours to complete. </p>
<p>nvidia-smi returns Volatile GPU-Util which never exceeds 25% on any of my 4 GPUs.
How can I increase GPU Util% and speed up my training?
<a href="https://i.stack.imgur.com/z... | <p>If your GPU util is below 80%, this is generally the sign of an input pipeline bottleneck. What this means is that the GPU sits idle much of the time, waiting for the CPU to prepare the data:<a href="https://i.stack.imgur.com/UNNuq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UNNuq.png" alt="enter image... | tensorflow|keras|nvidia|multi-gpu | 24 |
351,068 | 47,459,299 | Network outputs from tf.session.run greatly differ from the ones obtained with keras.Model.predict | <p>I'm trying to use Keras model through Tensorflow session. But results form <code>model.predict</code> and <code>sess.run</code> different. Is there any way to work with Kers model through Tensorflow session?</p>
<blockquote>
<p>Tensorflow version: 1.4.0<br>
Keras version: 2.1.1</p>
</blockquote>
<pre class="la... | <p>Okay, it's <code>K.set_session(s)</code> and not <code>K.tensorflow_backend.set_session(s)</code>.</p>
<p>Second: <code>sess.run(tf.global_variables_initializer())</code> resets all variables using their respective initializer, including the network weights (they use <code>xavier</code> initializer by default).</p>... | python|tensorflow|keras | 6 |
351,069 | 47,517,506 | variable size of input for CNN model in text classification? | <p>I implemented the CNN model for text classification based on this <a href="http://www.aclweb.org/anthology/D14-1181" rel="nofollow noreferrer">paper</a>. Since the CNN can only deal with the sentences that have fixed size, so I set the size of input as max length of sentence in my dataset and zero padding the short ... | <p>Quick answer:</p>
<p>No you can't</p>
<p>Longer answer:</p>
<p>Pooling is like a reduce function. Applying it on a layer reduces the dimensions. But different input shapes don't produce the same output shapes. However with zero padding you can probably simulate this, with max_len we are doing this. So, in the sec... | tensorflow|nlp|convolution|text-classification | 0 |
351,070 | 47,132,557 | Tensorflow: How to use the "new" Dataset API with QueueRunner | <p>Basically I have a list of images to be processed.
And I need to do some pre-processing (data augmentation) after loading, then feed to the main graph of TF.
Currently I am working with a customized generator which takes a list of paths yield a pair of tensors(images) and feed to the network via placeholder. And the... | <p>You don't have to use the QueueRunner to have queues/buffers if you are using the Dataset API. It is possible to create queues/buffers using the Dataset API and to pre-process data and train a network concurrently. If you have a dataset, you can create a queue/buffer by either using the <a href="https://www.tensorfl... | python|tensorflow|dataset | 1 |
351,071 | 47,385,028 | Implemented the groupby and want to insert by output of groupby in my .csv file | <p>I have around 8781 rows in my dataset. I have grouped the different items according to month and calculated the mean of a particular item of every month. Now, I want to store the result of every month after inserting the new row after every month.
Below is the code that I have worked upon for grouping the item and c... | <p>If your indices are named <code>1mean</code>, <code>2mean</code>, <code>3mean</code>, etc., <code>sort_indexes</code> should place them where you want.</p>
<pre><code>e.index = [str(n)+'mean' for n in range(1,13)]
df = df.append(e)
df = df.sort_index()
</code></pre> | python|pandas|pandas-groupby | 0 |
351,072 | 47,401,961 | Derive name based on a substring | <p>I have to get the label from <code>df B</code> based on a sub-string in a column of <code>df A</code>.</p>
<p><strong>Question</strong></p>
<p>Is there a way to do this without using Loop?</p>
<p><strong>dataframe A:</strong></p>
<pre><code>original string:
1. test1(arizona)
2. NJtest2
</code><... | <p>Use <code>str.extract</code> + <code>merge</code>:</p>
<pre><code>df1
Col
0 test1(arizona)
1 NJtest2
df2
keyword Label
0 test1 First Cycle Test
1 test2 Second Cycle Test
</code></pre>
<pre><code>p = '(?P<Key>.*(?P<keyword>{}).*)'.format('|'.join(df2.keywo... | python|pandas|dataframe | 1 |
351,073 | 47,112,615 | How to create a new column in python under multiple conditions? | <p>I would like to create a new column under the following condition:</p>
<p>So basically I have two column <code>Majoy car</code> and <code>Major housetype</code>. I would let all the <code>'nocar'</code> within <code>Majoy car</code> AND <code>'Rented'</code> within <code>Major housetype</code> to merge to a new col... | <p>As the comments suggest it is unclear if you are using pandas but if you are, and your columns are 'Majoy car' and 'Major housetype' then the following should work if you want all the rows in your dataframe conforming to your requirements.</p>
<pre><code>imd_car_house[(imd_car_house['Majoy car']=='nocar')&(imd_... | python|pandas|conditional-statements|pandas-loc | 0 |
351,074 | 47,165,911 | How to write a Pandas Dataframe into a HDF5 dataset | <p>I'm trying to write data from a Pandas dataframe into a nested hdf5 file, with multiple groups and datasets within each group. I'd like to keep it as a single file which will grow in the future on a daily basis. I've had a go with the following code, which shows the structure of what I'd like to achieve</p>
<pre cla... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_hdf.html" rel="nofollow noreferrer">df.to_hdf()</a> expects a string as a <code>key</code> parameter (second parameter):</p>
<blockquote>
<p><strong>key</strong> : string</p>
<p>identifier for the group in the store</p>
</blockquote>... | python-3.x|pandas|hdf5|h5py | 4 |
351,075 | 47,399,883 | split dict intro sub dicts when values are numpy arrays | <p>I have a dict whose values are numpy arrays as follows: </p>
<pre><code>mydict = {
"key0": array0,
"key1": array1,
"key2": array2
}
</code></pre>
<p><code>array0</code> and other two have the same length.
I want split <code>mydict</code> into two sub dicts, each has the same key as <cod... | <p>You can use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.array_split.html#numpy.array_split" rel="nofollow noreferrer"><code>np.array_split</code></a>:</p>
<pre><code>import numpy as np
array0 = np.arange(4)
array1 = np.arange(4, 8)
array2 = np.arange(5) # Odd number of elements
d =... | python|python-3.x|numpy | 2 |
351,076 | 47,223,531 | What's keeping this simple CNN from classifying whether an image contains a cat or not? | <p>Instead of "cats vs dogs", I'm trying "cats vs. everything else" on a brand new network (no transfer learning) using a large number of random internet images I've sorted into "cat" or "no cat" categories. </p>
<p>Unfortunately, my network won't seem to train itself past random for this task.</p>
<p>My networks hav... | <p>The "cats vs dogs" example often uses VGG16 as in the <a href="http://course.fast.ai/" rel="nofollow noreferrer">fast.ai</a> course.</p>
<p>Its 16-layer network was used by the VGG team in the <a href="http://www.image-net.org/challenges/LSVRC/2014/" rel="nofollow noreferrer">ILSVRC-2014 ImageNet</a> competition.
S... | machine-learning|tensorflow|neural-network|keras|conv-neural-network | 1 |
351,077 | 47,492,033 | `THIndexTensor_(size)(target, 0) == batch_size' failed. at d:\projects\pytorch\torch\lib\thnn\generic/ClassNLLCriterion.c:54 | <p>I am trying to train my neural networks on dog breeds data set. After feed-forward, during the loss computation it throws this error : </p>
<pre><code>RuntimeError: Assertion `THIndexTensor_(size)(target, 0) == batch_size' failed. at d:\projects\pytorch\torch\lib\thnn\generic/ClassNLLCriterion.c:54
</code></pre... | <p>I think problem is that you are missing the batch dimension on the tensor <code>labels</code>. The error says that the size of the <code>0th</code> dimension is not equal to the batch size.</p>
<p>Try changing this: </p>
<pre><code>loss = criterion(outputs, labels.unsqueeze(0))
</code></pre>
<p>Please note, the <... | machine-learning|neural-network|deep-learning|conv-neural-network|pytorch | 1 |
351,078 | 47,240,349 | import error keras.models Dense, LSTM, Embedding | <p>I have trouble running the code from this <a href="https://machinelearningmastery.com/how-to-develop-a-word-level-neural-language-model-in-keras/" rel="nofollow noreferrer">this</a> neural language model tutorial.
It seems that I cannot import the relevant packages from keras.models although I have installed keras a... | <p><code>Dense</code> is not a model. Dense is a layer, and it's in <code>keras.layers</code>:</p>
<pre><code>from keras.layers import Dense,LSTM,Embedding
from keras.models import Sequential,Model
</code></pre>
<p>Often I work importing everything at once and forget about it:</p>
<pre><code>from keras.layers import... | python|tensorflow|keras|cpu | 1 |
351,079 | 47,319,704 | Is it possible to check if elements of a tensor are out of boundaries? | <p>Is it possible to check if elements of a tensor are out of boundaries using <code>torch.cuda.FloatTensor</code> on <strong>PyTorch</strong>, <strong>GPU</strong> approach? </p>
<p>Example (<code>check limits</code>):</p>
<pre><code>for i in range(pop):
if (x[i]>xmax):
x[i]=xmax
elif (x[i]<xmi... | <p>You can get a CPU copy of tensor <code>x</code>, do your operations and then push the tensor to GPU memory again.</p>
<pre><code>x = x.cpu() # get the CPU copy
# do your operations
x = x.cuda() # move the object back to cuda memory
</code></pre> | python|gpu|pytorch | 0 |
351,080 | 47,455,323 | Weird behavior with datetime: error: time data '0' does not match format '%d%b%Y:%H:%M:%S' | <p>I know this has been asked 1000 times before but what i am experiencing is really weird and I cant troubleshoot it.</p>
<p>I have a date column structured like this:</p>
<blockquote>
<p>24JUN2017:14:46:57</p>
</blockquote>
<p>I use:</p>
<blockquote>
<p>pd.to_datetime('24JUN2017:14:46:57', format="%d%b%Y:%H:%... | <p>As pointed by jezrael and EdChum, i have bd data in my column. errors='coerce' option solved this problem.</p> | python|pandas|python-datetime | 0 |
351,081 | 47,396,954 | creating an array of tuples with matched elements - mnist data | <p>I have a csv data, the first column of the data is 'label' and columns after the first one to the end 784 column contains a representation of an image (28*28) format. </p>
<p>I am trying to create an array of these two. I get it created but the format I like is not appearing. </p>
<p>This is the code I used:</p>
... | <p>With a sample 'csv' text:</p>
<pre><code>In [41]: txt = b'''label1 1 2 3 4
...: label2 8 9 10 11
...: label3 10 11 12 13
...: '''
</code></pre>
<p>and a compound dtype:</p>
<pre><code>In [46]: dt = np.dtype([('label','U10'),('image',float,(2,2))])
</code></pre>
<p><code>genfromtxt</code> can load the... | python|numpy | 0 |
351,082 | 47,408,427 | Tensorflow - timeseries data import with datetime | <p>I am a noob for the Tensorflow and I am starting with some timeseries prediction example.</p>
<p>I would like to import the exact datetime instead of the sequence number for the below code. How to do that? Thanks.</p>
<p>Code:</p>
<pre><code>csv_file_name = './data/sales.csv'
reader = tf.contrib.timeseries.CSVRea... | <p>According to the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py" rel="nofollow noreferrer" title="source">source code</a>, a <code>RandomWindowInputFn</code> accepts either a <code>CSVReader</code> or a <code>NumpyReader</code>. So you ... | tensorflow | 1 |
351,083 | 47,516,326 | Pandas DataFrame Issue. Don't know how to clean and manage a sort of block matrix | <p>here is my first question: I have a pandas DataFrame that looks like the following:</p>
<p><a href="https://i.stack.imgur.com/MFfOE.png" rel="nofollow noreferrer">Pandas Dataframe</a></p>
<p>The DataFrame shown in the picture is simplified (its original shape is <code>[1195674 x 11])</code> but it doesn't matter.<... | <p>Let's try <code>ffill</code>, which will fill forward values for NaN:</p>
<pre><code>df[['A','B','C','D']] = df[['A','B','C','D']].ffill()
</code></pre> | python|python-3.x|pandas|dataframe|data-cleaning | 1 |
351,084 | 47,225,863 | Import list of folder names in a folder with Python | <p>So I've started down the path again of trying to automate something. My end game is to combine the data within Excel files containing the Clean Up in the file name and combine the data from a tab within these files named LOV. So basically it had to go into a folder with folders which have folders again that have 2 f... | <p>If you only want the list of folders in your current directory, you can use <code>os.path</code>. Here is how it works:</p>
<pre><code>import os
directory = "V:/PCC Clean Up Project 2017/_DCS Data SWAT Project/PCC Files
Complete Ready to Submit/Brake System Parts"
childDirectories = next(os.walk(directory))[1]
</c... | python|excel|pandas | 0 |
351,085 | 47,177,825 | numpy upgrade is not happening | <p>when i import pandas , i get following error </p>
<pre><code>ImportError: this version of pandas is incompatible with numpy < 1.9.0.
your numpy version is 1.8.0rc1.
</code></pre>
<p>so I upgraded numpy using</p>
<pre><code>sudo pip install numpy --upgrade --ignore-installed
Installing collected packages: nump... | <p>maybe you can check the original numpy lib location.</p>
<pre><code>>>> import numpy
>>> print numpy.__version__
1.6.0
>>> print(numpy)
<module 'numpy' from '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/__init__.pyc'>
</code></pre>
<p>you can del... | pandas|numpy | 0 |
351,086 | 47,513,724 | Scale Data to log-normal. Is my approach right? | <p>I have a one dimensional Array where the datas are between 1 and 500.
The distribution of the data looks like log-normal.</p>
<p>What i want is to resample the array to log(data)</p>
<p>i am not sure about which function to use:</p>
<p><a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.log... | <ul>
<li>if you want to fit your data to a log normal distribution : you should use scipy.stats.lognorm.fit(listofdata) and check the quality of the fitting with a Kalmogorov Smirnov test : scipy.stats.kstest</li>
<li>if you want to transform your data np.log(dataset) should be enough.</li>
</ul>
<p>Best</p> | python|numpy|normalization | 1 |
351,087 | 47,493,135 | binarize input for pytorch | <p>may I ask how to make data loaded in pytorch become binarized once it is loaded?
Like Tensorflow can done this through:</p>
<pre><code>train_data = mnist.input_data.read_data_sets(data_directory, one_hot=True)
</code></pre>
<p>How can pytorch achieve the <code>one_hot=True</code> effect. </p>
<p>The data_loader... | <p>The one-hot encoding idea is used for classification. It sounds like you are trying to create an autoencoder perhaps.</p>
<p>If you are creating an autoencoder then there is no need to round as BCELoss can handle values between 0 and 1. Note when training it is better not to apply the sigmoid and instead to use <a ... | input|binary|loader|pytorch | 0 |
351,088 | 47,482,208 | include variables into pd.read_excel skiprows option | <p>This works perfectly. </p>
<pre><code>for fname in glob.iglob(path):
df2 = pd.read_excel(fname, skiprows=5, header=0).dropna(subset=['TreeNodeCode'],how='any')
</code></pre>
<p>However, each excel sheet has different numbers of rows to skip, so I am trying to make a variable to loop around skiprows:</p>
<p>I... | <p>Thanks for all the answers! The answers in the comment don't seem to work, but I use a kinda ugly way which it works:</p>
<pre><code> if CLIENT_ID in ('6'):
df2 = pd.read_excel(fname, skiprows=5, header=0).dropna(subset=['TreeNodeCode'],how='any')
elif CLIENT_ID in ('7'... | python-3.x|pandas | 0 |
351,089 | 11,225,488 | Numpy/Python: Meshgrid division operation: MemoryError | <p>I'm programming a neural field with numpy and for a map of 100*100 neurons, I need to manage a 10000*10000 connections map.</p>
<p>So I create my connection map with meshgrid and I try to applicate an adaptation of Mexican Hat fonction. Here, you have the code you can try: if you put <code>taille = 60</code> or <co... | <p>Basic arithmetic operations on numpy arrays make copies. </p>
<pre><code>>>> a = numpy.arange(10)
>>> b = a + 1
>>> c = b + 1
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> c
array([ 2, 3, 4, 5, 6, 7, ... | python|numpy|division | 6 |
351,090 | 10,867,437 | finding the area of a closed 2d uniform cubic B-spline | <p>I have a list of 2d points which are the control vertices (Dx) for a closed uniform cubic B-spline. I am assuming a simple curve (non-self-intersecting, all control points are distinct).</p>
<p>I am trying to find the area enclosed by the curve:</p>
<p><img src="https://i.stack.imgur.com/3Vlf1.png" alt="enter imag... | <p>Personally, I would use the splines to their best advantage and rewrite the area integral as a contour integral using <a href="http://mathworld.wolfram.com/GreensTheorem.html" rel="nofollow">Green's theorem</a>.</p>
<p>Since you already know the curve, it'll be an easy matter to do the integration using Gaussian qu... | python|math|numpy|spline | 4 |
351,091 | 10,923,212 | Assigning to columns in NumPy | <p>How could the following MATLAB code be written using NumPy?</p>
<pre class="lang-matlab prettyprint-override"><code>A = zeros(5, 100);
x = ones(5,1);
A(:,1) = x;
</code></pre>
<p>Assigning to rows seems to work easily, but I couldn't find an example of assigning an array to a column of another array.</p> | <p>Use <code>a[:,1] = x[:,0]</code>. You need <code>x[:,0]</code> to select the column of <code>x</code> as a single numpy array. If you have the choice of how to format <code>x</code>, it's better to not make it a 2-dimensional array in the first place, but just a regular (row) array:</p>
<pre><code>>>> a
... | python|numpy | 67 |
351,092 | 68,293,253 | How to compare training and test performance in a Faster RCNN object detection model | <p>I'm following a tutorial <a href="https://github.com/microsoft/computervision-recipes/blob/master/scenarios/detection/01_training_introduction.ipynb" rel="nofollow noreferrer">here</a> for implementing a Faster RCNN against a custom dataset using PyTorch.</p>
<p>This is my training loop:</p>
<pre><code>for images, t... | <p>The <code>evaluate()</code> function <a href="https://github.com/pytorch/vision/blob/master/references/detection/engine.py#L71" rel="nofollow noreferrer">here</a> doesn't calculate any loss. And look at how the loss is calculate in <code>train_one_epoch()</code> <a href="https://github.com/pytorch/vision/blob/master... | python|pytorch|object-detection|faster-rcnn | 2 |
351,093 | 68,416,813 | Printing values with Pandas | <p>First of all, I am totally new on Python, so, maybe is something super simple I am not doing correctly.</p>
<p>I am reading a multiple worksheet xlsx file and sending each of them to separated dataframe. (at least, I think I am doing it).</p>
<pre><code>xl = pd.ExcelFile("results/report.xlsx")
d = {} # you... | <p><code>d['Seg10_results'][lista_colunas]</code> is basically <code>d['Seg10_results][7, 10, 101, 102, 103, 104]</code> and none of the items in <code>lista_colunas</code> is an actual column in <code>d['Seg10_results']</code> .</p>
<p>You might want to either:</p>
<ul>
<li><p>use <code>pandas.DataFrame.iloc</code> (<... | python|excel|pandas|openpyxl | 1 |
351,094 | 68,177,107 | reading data from txt file with varying number of columns and saving it as a dataframe | <p>I have a data.txt file that looks like this:</p>
<pre><code>1000
1 2 3
4 5 6
2000
11 12 13
14 15 16
</code></pre>
<p>and I wanted it to be converted to a dataframe like this:</p>
<pre><code>1000 1 2 3
1000 4 5 6
2000 11 12 13
2000 14 15 16
</code></pre>
<p>I'm new to Python and tried different methods, but it is s... | <pre><code># read the file, as sep='\n', then use `str.split` to get the columns
obj = pd.read_csv('data.txt', sep='\n', header=None)[0]
df = obj.str.split(expand=True)
# handle the lable line `1000 or 2000`, as column 1 is null
cond = df[1].isnull()
# column 4 store the lable `1000` and `2000`
# use `ffill()` to fill... | pandas|dataframe|multiple-columns | 0 |
351,095 | 68,297,309 | Perform calculation based on consecutive time | <p>I have a dataframe, df, where I would like to add a calculated field column and subtract from this number for every consecutive date period.</p>
<p><strong>Data</strong></p>
<pre><code>base id date con retro finalc sp
100 aa q122 5 1 4 159
100 aa q222 10 1 9 50
50... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumsum.html" rel="nofollow noreferrer"><code>GroupBy.cumsum</code></a> with subtract:</p>
<pre><code>df['start'] = df['base'].sub(df.groupby('id')['finalc'].cumsum())
print (df)
base id date con retro finalc ... | python|pandas|numpy | 1 |
351,096 | 68,240,733 | How to visualize multivariate time series dataset | <p>I have time series data containing 100 features. (these are all meaningful features, so I cannot reduce the size anymore)</p>
<p>What is the best way to visualize these features distributions to find out the patterns ?</p>
<p>If I plot all dataframe columns separately, there are too many graphs.
And If I I plot all ... | <p>I would start by making a pairplot. Seaborn is a good library for this. You can see some starter code and sample outputs in the documentation:</p>
<p><a href="https://seaborn.pydata.org/generated/seaborn.pairplot.html" rel="nofollow noreferrer">https://seaborn.pydata.org/generated/seaborn.pairplot.html</a></p>
<p>Yo... | python|pandas|plot|time-series|data-visualization | 0 |
351,097 | 68,253,222 | Logits and Labels must have the same shape : Tensorflow | <p>I m trying to classify Cats vs Dogs Using a CNN Network, However despite checking twice I am not able to find the error where it is coming . According to me the loss functions and shapes are in order , still I am not able to find the source of the error</p>
<pre><code>!unzip cats_and_dogs.zip
PATH = 'cats_and_dogs'
... | <p>I forgot to Flatten my Tensor before flowing it to Dense layers</p> | tensorflow|keras|computer-vision|shapes|valueerror | 0 |
351,098 | 68,338,687 | Joining using column names in pandas | <p>I'm having two dataframes in pandas, the one is initial one:</p>
<p><a href="https://i.stack.imgur.com/DAF5W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DAF5W.png" alt="enter image description here" /></a></p>
<p>and the other is the result of <code>TF-IDF</code> operation. So basically, <code... | <p>Melt the 2nd data frame and then merge with the 1st one:</p>
<pre><code>df2.melt('Group', var_name='Name', value_name='Res').merge(df1, how='right')
Group Name Res
0 1 A 0.0
1 1 A 0.0
2 2 A 0.0
3 2 B 0.1
4 3 B 0.0
5 3 C 0.1
</code></pre> | python|pandas|for-loop|join | 2 |
351,099 | 68,064,903 | Change from array of specified size to dynamic array? | <p>I have a program that's looking for certain values in a log file and listing them out. Essentially, one line of a 50000 line file would look like this:</p>
<pre><code>Step Elapsed Temp Press Volume TotEng KinEng PotEng E_mol E_pair Pxx Pyy Pzz Pxz Pxy Pyz
0 0 298 -93.542117 448382.78 -6739... | <p>make a list of lists and append items to those lists. when you get to the end of the file cast the list of lists to a np.ndarray.
change</p>
<pre><code>data = numpy.zeros((numcol,100000))
</code></pre>
<p>to</p>
<pre><code>data = [[] for i in range(numcol)]
</code></pre>
<p>and change</p>
<pre><code>data[i][ln]=(flo... | python|arrays|numpy|append | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.