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 |
|---|---|---|---|---|---|---|
356,800 | 69,953,354 | How to fix the error of this code: "dirac[:N / 2] = 1"? | <p>I got this python code from the internet, and it's for calculating the modulation spread function (MTF) from an input image. Here is the
<a href="https://github.com/habi/GlobalDiagnostiX/blob/master/MTF.py" rel="nofollow noreferrer">full code</a>.</p>
<p>The problem is that the code is not functioning on my PC due t... | <p>Simply make N/2 an integer again.</p>
<pre><code>dirac[:int(N/2)] = 1
</code></pre> | python|numpy|image-processing | 0 |
356,801 | 69,974,453 | Datetime format pandas | <p>I am trying to read a csv and to convert the datetime column into a datetime index, but I am struggling with the format. How do you specify the +2 in the format parameter of <code>pd.to_datetime</code>?</p>
<p>Many thanks,</p>
<pre><code>date = ['2015-02-03 21:00:00+02:00','2015-02-03 22:30:00+02:00','2016-02-03 21... | <p>Use <code>parse_dates=['date']</code> as parameter of <code>pd.read_csv</code>:</p>
<pre><code>df = pd.read_csv('data.csv', parse_dates=['date'], index_col='date')
</code></pre>
<p>Output:</p>
<pre><code>>>> df
V1
date
2015-02-03 21:00:00+02:00 3... | python|pandas|csv|datetime-format | 0 |
356,802 | 69,735,838 | how to repeat (2, 1) tensors to (50, 1) tensors in TensorFlow 1.10 | <p>For example,</p>
<pre><code># x is a tensor
print(x)
[1, 0]
# after repeating it
print(x)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code></pre>
<p>There is no <code>tf.repeat</code> in <code>TensorFlow 1.... | <p>If you can really only use Tensorflow <code>1.10</code> then try something like this:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
x = tf.constant([1, 0])
x = tf.reshape(tf.tile(tf.expand_dims(x, -1), [1, 25]), (50, 1))
print(x)
'''
tf.Tensor(
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1... | python|tensorflow|tensor | 1 |
356,803 | 69,734,461 | Pandas apply a function using index name and column name | <p>Consider the dataframe:</p>
<pre class="lang-py prettyprint-override"><code>data = pd.DataFrame(0, index=[1,2,3,4], columns=[1,2,3,4])
data
1 2 3 4
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
4 0 0 0 0
</code></pre>
<p>I want to fill the values using a function that takes two argument... | <p>If use <code>apply</code> there are loops under the hood, so not vecorized solution, If need multiple index by columns names use numpy soluton like:</p>
<pre><code>a = data.index.to_numpy() * data.columns.to_numpy()[:, None]
print (a)
[[ 1 2 3 4]
[ 2 4 6 8]
[ 3 6 9 12]
[ 4 8 12 16]]
</code></pre>
<hr />
... | python|pandas|vectorization | 2 |
356,804 | 69,878,468 | InvalidArgumentError: Received a label value of 3 which is outside the valid range of [0, 3) tensorflow sentimen analysis | <p>So i try to learn sentimen analysis with tensorflow,my data set is contain 3 y_labels that is <code>1 == 'negative,2=='neutral,3=='positive'</code>. Here is my code</p>
<pre><code>tokenizer = Tokenizer(num_words=vocab_size,oov_token=oov_tok)
tokenizer.fit_on_texts(X)
word_index =tokenizer.word_index
training_seque... | <p>I got the anser from Luke Borowy that in multiclass or multi label classification all label should start from 0</p> | python|tensorflow|keras|deep-learning|sentiment-analysis | 0 |
356,805 | 69,759,159 | Ifelse leaving other observations as is | <p>In R and tidy verse, there is a way to use ifelse() such that I can change several of the observations in a variable but then I can leave other observations that I don't want changed as they are but just setting else to that column (so in the example below, "Virginica and "Versicolor" would remain the... | <p>Use <code>replace</code>:</p>
<pre><code>iris['new_spicies'] = iris['species'].replace('setosa', 'set')
</code></pre>
<p>Output:</p>
<pre><code> sepal_length sepal_width petal_length petal_width species new_spicies
0 5.1 3.5 1.4 0.2 setosa set
1 ... | pandas | 1 |
356,806 | 69,723,012 | Parse datetime-range or duration given a partial datetime | <p>Suppose I am given a partial datetime string. I wish to obtain the datetime it represents, and what was the resolution of the given datetime.</p>
<p>For example:</p>
<ul>
<li><code>"2021-01-06 12"</code> -> <code>2021-01-06 12:00:00.000000</code> and <code>"hour"</code></li>
<li><code>"2... | <p>Addressing specifically this section of the question:</p>
<blockquote>
<p>EDIT: It seems that the internal function pandas._libs.tslibs.parsing.parse_datetime_string_with_reso returns what I want. Does anyone know how can I access it (not accessible using from pandas._libs.tslibs.parsing import parse_datetime_string... | python|pandas|datetime|datetime-format|python-datetime | 1 |
356,807 | 69,936,595 | Filter datetime by date, pandas python | <p>I don't know why my code is not working when there are many, many examples of filtering a pandas dataframe datetime column by date, but I can't get them to work.</p>
<p>My dataframe has a datetime column that does NOT have an index. I have tried to use the <code>to_datetime()</code> to make sure the Series is a date... | <p>Try adding this line before you do any sorting:</p>
<pre class="lang-py prettyprint-override"><code>less_hot_df['date_time'] = pd.to_datetime(less_hot_df['date_time'])
</code></pre> | pandas|dataframe|datetime | 1 |
356,808 | 69,987,074 | Dropping multiples rows based on list of column values | <p>I am working on a World Bank dataset of Co2 Emission and GDP. I want to remove values of non countries from the dataframe.</p>
<p>I tried using negation and <code>reset_index</code> as follow. But the rows are not getting removed. I want the rows to be removed where the country name in the column <code>Country Name<... | <p>Try this:</p>
<pre><code>df_indicator = df_indicator.loc[~df_indicator['Country Name'].isin(non_countries)]
</code></pre> | python|pandas|dataframe|analytics | 0 |
356,809 | 69,670,306 | pip uninstall does not remove package fully | <p>Long story short, numpy gave me error when I was importing matplotlib, so I wanted to <code>pip uninstall numpy</code> and reinstall it. but failed to fully uninstall numpy.</p>
<pre><code>RuntimeError Traceback (most recent call last)
RuntimeError: module compiled against API version 0x... | <p>You can delete the files with this commands</p>
<pre><code>rm -rf f2py
rm -rf 2py2
rm -rf numpy-1.16.6.dist-info/*
rm -rf numpy/*
</code></pre>
<p>or only:</p>
<pre><code> rm f2py
rm 2py2
rm numpy-1.16.6.dist-info/*
rm numpy/*
</code></pre> | python|numpy|pip | 0 |
356,810 | 69,885,569 | Merge two dataframe based on a list element matches in pandas | <p>I have a dataframe such as</p>
<p><strong>df1</strong></p>
<pre><code>Groups Value1 Value2 List_sp
G1 2 3 [Segment_1_1-300_+__Sp1, Segment_2_301-400_-__Sp2]
G1 4 5 [Segment_3_400-500_+__Sp3, Segment_2_600-700_+__Sp4]
G2 6 7 [Segment_12_800-900_-__Sp1]
G2 8 9 [S... | <p>You may need to do <code>explode</code> first then we can <code>merge</code></p>
<pre><code>df1.List_sp = df1.List_sp.str.strip('[|]').str.split(', ')
# noted above is try to convert the string to list , if your original df already have list type , you can just go start with below
df1['sp'] = df1.List_sp
out = df2.... | python|pandas | 0 |
356,811 | 69,871,808 | How can I speed up a pandas groupby that is performing a sum on more than one column? | <p><strong>Ask</strong></p>
<p>I would like to speed up a pandas groupby that is also applying a summation on two columns and have the resulting dataframe returned.</p>
<p><strong>Code</strong></p>
<pre><code>df = df.groupby(['key','code','name','period','agg_metric'], sort=False, observed=True, dropna=False)[['metricA... | <p>What type of data do you have?
It looks like the columns <code>metricA</code> /<code> metricB</code> are of type <code>object</code>, and pandas performs slow summation for Python objects rather than fast summation for numpy arrays. Try to convert metric columns to <code>float64</code> or <code>integer</code> type.<... | python|pandas|numpy|pandas-groupby | 1 |
356,812 | 69,870,907 | How to create a dataframe based on list containing column names? | <p><strong>How to create a dataframe based on list containing column names?</strong></p>
<p><strong>Situation</strong></p>
<p>I've got a list of column names stored in variable named data:</p>
<ul>
<li>values_c1_114</li>
<li>values_c1_84</li>
<li>values_c1_37</li>
<li>values_c1_126
...</li>
</ul>
<p>In total there are ... | <p>See if this is what you need. If I understand OP's question right, OP's key problem is how to get the variable name as a string, then use the set of string as the <code>dataframe</code> column.</p>
<pre class="lang-py prettyprint-override"><code>def namestr(obj, namespace):
return [name for name in namespace if ... | python|pandas|list|dataframe | 1 |
356,813 | 43,439,627 | Issues while comparing float32 objects in dataframes in pandas | <p>I have a dataframe data which is like this:</p>
<pre><code>>>> data.head(10)
stock pop ma order
Date
2016-01-04 325.316 82.0 NaN -1
2016-01-11 320.036 83.0 NaN -1
2016-01-18 299.169 79.0 82.5 -1
2016-01-25 296.579 84.0 81.0 -1
2016-02-01 295.334 82.0 81.... | <p>First, you are running into chained indexing - running this interactively you'll see a warning, see also the docs <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#why-does-assignment-fail-when-using-chained-indexing" rel="nofollow noreferrer">here</a>.</p>
<p>Second, <code>pop</code> is a DataFram... | python|pandas|dataframe|compare | 2 |
356,814 | 43,171,376 | Python pandas rolling mean while retaining index and column | <p>I have a pandas DataFrame of statistics for NBA games. Here's a sample of the data for away teams:</p>
<pre><code> away_team away_efg away_drb away_score
date
2000-10-31 19:00:00 Los Angeles Clippers 0.522 74.4 94
2000-10-31 19:00:00 Milwaukee Bucks ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift</code></a> here which <em>shifts</em> the index for a given amount to make your rolling window use the last three values excluding the current value:</p>
<pre><code># create ... | python|pandas | 4 |
356,815 | 43,302,679 | Removing data from a column in pandas | <p>I'm trying to prune some data from my data frame but only the rows where there are duplicates in the "To country" column</p>
<p>My data frame looks like this:</p>
<pre><code> Year From country To country Points
0 2016 Albania Armenia 0
1 2016 Albania Armenia 2
2 2016 Albania ... | <p>No, this behavior is correct—assuming every team played every other team, it's finding the firsts, and all of those firsts are "From" Albania.</p>
<p>From what you've said below, you want to keep row 0, but not row 1 because it repeats <strong>both</strong> the <code>To</code> and <code>From</code> countries. The w... | python|pandas | 3 |
356,816 | 43,250,683 | Faster RCNN, Why does conv's result can become the bbox_deltas? | <p><a href="https://github.com/smallcorgi/Faster-RCNN_TF/blob/master/lib/rpn_msr/proposal_layer_tf.py#L56" rel="nofollow noreferrer">Here</a> and <a href="https://github.com/smallcorgi/Faster-RCNN_TF/blob/master/lib/rpn_msr/proposal_layer_tf.py#L95" rel="nofollow noreferrer">here </a>are the code.</p>
<p>I'm confused ... | <p>Suppose we have a <code>(3,2,36)</code> conv's result.</p>
<p>Note that:</p>
<pre><code>36 = 4 * 9
</code></pre>
<p>So after reshape, each point of <code>(3,2)</code> have 9 proposal.</p>
<p>As the program shows:</p>
<pre><code>import numpy as np
a = [[[1]*36,[2]*36],[[3]*36,[4]*36],[[5]*36,[6]*36]]
a = np.arra... | image-processing|tensorflow|computer-vision|deep-learning|detection | 0 |
356,817 | 43,226,467 | How to find a position of a last ocurrence of certain value in a pandas dataframe? | <p>In a dataframe where one column is datetime and another one is only ones or zeros, how can I find the times of each of the last occurences of 1?
For example:</p>
<pre><code>times = pd.date_range(start="1/1/2015", end="2/1/2015",freq='D')
YN = np.zeros(len(times))
YN[0:8] = np.ones(len(YN[0:8]))
YN[12:20] = np.ones(... | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow noreferrer">Series.shift(-1)</a> in conjunction with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow noreferrer">Series.diff()</a> methods</p>
<pre... | python|pandas | 4 |
356,818 | 43,097,140 | Pandas Category sub-group 0 counts | <p>I'm new to Pandas, and trying to generate a table of subgroup counts maintaining the category order, and showing zero counts. It's a simple category with 4 options. </p>
<p>Without grouping it works as expected, but with grouping it isn't displaying zero counts (see last group). </p>
<p>In [21]:</p>
<pre><code>df... | <p>You can create a <code>MultiIndex</code> from all combinations of values of two grouping columns and reindex the groupby result with this multiindex. Then fill NaN values with zeros.</p>
<pre><code>import pandas as pd
# example data
df = pd.DataFrame({'a':list('xxxyyy'), 'b':[1,2,3,1,2,2]})
# a b
# 0 x 1
# 1 ... | python|pandas | 2 |
356,819 | 43,146,201 | Tensorflow Layers Api Linear Activation Function | <p>This question is similar to this question: <a href="https://stackoverflow.com/questions/36519724/how-to-use-a-linear-activation-function-in-tensorflow">How to use a linear activation function in TensorFlow?</a> however not the same. </p>
<p>On the final dense layer I want to output 28 nodes with a linear activatio... | <p>The <a href="https://www.tensorflow.org/api_docs/python/tf/layers/dense" rel="noreferrer">documentation of <code>dense</code></a> says about the <code>activation</code> parameter:</p>
<blockquote>
<p><code>activation</code>: Activation function (callable). Set it to None to maintain a linear activation.</p>
</blo... | python|tensorflow | 8 |
356,820 | 43,198,079 | Unstack and convert dates of observations to sequence number? | <p>I have a CSV with one row for every observation per individual:</p>
<pre><code>USER DATE SCORE
1 7/9/2015 37.2
1 11/18/2015 68.9
2 7/7/2015 45.1
2 11/2/2015 42.9
3 6/4/2015 56
3 10/27/2015 39
3 5/11/2016 42.9
</code></pre>
<p>I'd like to produce a dataframe where the first observ... | <ul>
<li>First sort values by <code>USER</code> and <code>DATE</code> (this seems to be done already in example data but just to be sure).</li>
<li>Then create a new column <code>ROUND</code> that will sequentially number entries for every user.</li>
<li>Set index to columns <code>USER</code> and <code>ROUND</code>.</l... | python|pandas|dataframe | 0 |
356,821 | 43,119,941 | Tensorflow segfault when using with numpy-quaternion library | <p>The following code snippet crashes on the second last line, so where <code>tf.train.latest_checkpoint)</code> is called:</p>
<pre><code>import tensorflow as tf
from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm
import quaternion
latest_checkpoint = tf.train.latest_checkpoint('checkpoints/... | <p>There are two possible ways to work around/fix the error:</p>
<p><strong>Don't import batch_norm</strong></p>
<p>Just always use <code>tf.contrib.layers.python.layers.batch_norm</code> directly in the code, thus omitting the import statement (admittedly, creates a lot of clutter).</p>
<p><strong>Set environment v... | python|numpy|tensorflow | 1 |
356,822 | 43,472,125 | Sort pandas DataFrame with MultiIndex according to column value | <p>I have a DataFrame with MultiIndex looking like this after printing in the console:</p>
<pre>
value indA indB
scenarioId group
2015-04-13 1 A -54.0 1.0 1.0
B -160.0 1.0 1.0
... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="noreferrer"><code>sort_values</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="noreferrer"><code>sort_index</code></a>:</p>
<pre><code>... | python|pandas|dataframe|multi-index | 7 |
356,823 | 43,392,838 | How can I reuse a Dense layer? | <p>I have a network in Tensorflow, and I want to define a function that passes it's input through a <code>tf.layers.dense</code> layer (obviously, the same one). I see the <code>reuse</code> argument, but in order to use it properly it seems I need to keep a global variable just to remember if my function was called al... | <p>I find <a href="https://www.tensorflow.org/api_docs/python/tf/layers/Dense" rel="noreferrer">tf.layers.Dense</a> cleaner than the above answers. All you need is a Dense object defined beforehand. Then you can reuse it any number of times.</p>
<pre><code>import tensorflow as tf
# Define Dense object which is reusab... | python|tensorflow|neural-network | 12 |
356,824 | 43,397,942 | How to filter csv data by applying conditions on certain columns in python | <p>I am new python data analysis and having some problems to get the required data in specific format.</p>
<p>My data is in following format. ( please check the attached link for data in csv format as the data is quite large)</p>
<p><a href="https://i.stack.imgur.com/EKuvh.png" rel="nofollow noreferrer"><img src="htt... | <p>You can use <code>query</code></p>
<pre><code>cols = ['Country_Area', 'Energy_Supply_per_capita', 'Avg_GDP']
data_c.query('Energy_Supply_per_capita > 280')[cols]
</code></pre>
<p>Or equivalently with a boolean series and <code>loc</code></p>
<pre><code>cols = ['Country_Area', 'Energy_Supply_per_capita', 'Avg_G... | python|pandas|jupyter | 2 |
356,825 | 43,296,001 | Train and test in TensorFlow with CSV files | <p>I have a train.csv and a test.csv. I want to use tensorflow to look at the training.csv and print out a two column CSV file for the test.csv file. The first column being the id and the second column being what the tensorflow predicts is the category for the id. I am using python.</p> | <p>Whatever Tensorflow predicts, once you do .eval() on that, it becomes a 'standard' Python datatype, which you can write to CSV using usual non-Tensorflow APIs.</p>
<p>Here's a snippet of code that does just that (pieced it together from various parts of a larger file, so excuse if not fully coherent)</p>
<pre><cod... | python|python-3.x|csv|tensorflow | 0 |
356,826 | 43,195,068 | pandas.read_sas can load SAS columns labels | <p>I'd like to load a SAS7BDAT file into a pandas dataframe, and then into a database. </p>
<p>I understand that <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sas.html" rel="nofollow noreferrer">pandas.read_sas</a> allows loading a SAS7BDAT, but I'd also like to retrieve the SAS column lab... | <p>I achieved this by using SAS7BDAT class instead of Dataframe and when I inspected the columns, I was able to see labels as well </p>
<pre><code>with SAS7BDAT('xxx.sas7bdat',encoding='latin-1') as sas:
for row in sas:
</code></pre>
<p>sas-> columns will have name as well as label</p> | python|pandas | -1 |
356,827 | 43,433,168 | Aggregate Pandas Column based on values in Column Range | <p>Dataset:</p>
<p><a href="https://i.stack.imgur.com/WKahw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WKahw.png" alt="enter image description here"></a></p>
<p>Need output like below in using dataframe pandas. I would like to group by PRCP based on the PRCP range and aggregate the count. Plea... | <pre><code>import pandas as pd
df = pd.DataFrame({'CLDATE':['1/1/16','1/10/16','1/11/16','11/12/16','11/13/16','11/14/16','11/15/16','11/16/16'],
'count':[64396,49877,41603,41124,45839,45846,52719,59626],'PRCP':[0,1.8,0,0,0,0,0,0.24]})
df['precipate_Range']=pd.cut(df['PRCP'],[0,1,2,3],right=False,... | python-3.x|pandas|numpy|dataframe | 0 |
356,828 | 43,359,479 | Pandas: parsing 24:00 instead of 00:00 | <p>I have a dataset, in which the hour is recorded as <code>[0100:2400]</code>, instead of <code>[0000:2300]</code></p>
<p>For example </p>
<pre><code>pd.to_datetime('201704102300', format='%Y%m%d%H%M')
</code></pre>
<p>returns</p>
<pre><code>Timestamp('2017-04-10 20:00:00')
</code></pre>
<p>But </p>
<pre><code>p... | <p>Pandas uses the system <code>strptime</code>, and so if you need something non-standard, you get to roll your own.</p>
<p><strong>Code:</strong></p>
<pre><code>import pandas as pd
import datetime as dt
def my_to_datetime(date_str):
if date_str[8:10] != '24':
return pd.to_datetime(date_str, format='%Y%... | python|pandas|datetime | 10 |
356,829 | 43,457,107 | Pivot a pandas DataFrame to be the correct format: `DataError: No numeric types to aggregate` | <p>Here is a pandas DataFrame I would like to manipulate: </p>
<pre><code>import pandas as pd
data = {"grouping": ["item1", "item1", "item1", "item2", "item2", "item2", "item2", ...],
"labels": ["A", "B", "C", "A", "B", "C", "D", ...],
"count": [5, 1, 8, 3, 731, 189, 9, ...]}
df = pd.DataFrame(data)
... | <p>Use <code>set_index</code> and <code>unstack</code>:</p>
<pre><code>df = df.set_index(['grouping','labels']).unstack().rename_axis(None)
df.columns = df.columns.droplevel()
print(df)
</code></pre>
<p>Output:</p>
<pre><code>labels A B C D
item1 5 1 8 None
item2 3 731 189 9
</code></pre> | python|pandas|dataframe|pivot | 6 |
356,830 | 43,355,176 | Data chopping issue in Python | <p>Problem 1 : I have different ID's for each ID I want to chop the <code>Item vs. Value</code> curve at the minimum <code>Value</code>. Basically, I want to filter out the values and keep only until it goes minimum value.</p>
<p>Problem 2. Can I extrapolate by fitting the chopped curve in Python?</p>
<p>Please help ... | <p>use <code>.loc[:df.Value.idxmin()]</code></p>
<pre><code>df.groupby('ID', group_keys=False).apply(lambda df: df.loc[:df.Value.idxmin()])
</code></pre>
<hr>
<pre><code> ID Item Value
0 30702556 40 1.000000
1 30702556 41 1.000000
2 30702556 42 1.000000
3 30702556 43 1.0000... | python|pandas|numpy|data-manipulation | 2 |
356,831 | 43,244,940 | select one column of a data frame pandas python | <p>I am trying to select a column from a pandas data frame I am reading</p>
<pre><code>tweets = pd.read_csv(r'C:\Users\PedroLuis\Documents\Manita\LASSO 20170219-20170402.csv', sep = " , ", engine='python')
tweets = pd.DataFrame(tweets)
</code></pre>
<p>When I list the columns what I see is</p>
<pre><code> list(tw... | <p>There is a space in your sep = " , " which causes all the column to combine.</p>
<p>Change it to</p>
<pre><code>tweets = pd.read_csv(r'C:\Users\PedroLuis\Documents\Manita\LASSO 20170219-20170402.csv', sep = ",", engine='python')
</code></pre>
<p>You should be able to call tweet['text'] </p> | python|pandas|dictionary|select|dataframe | 2 |
356,832 | 43,268,872 | Parquet creation Conversion from pandas dataframe to pyarrow table not working for object dtype | <p>I want to create a parquet file from a csv file. For test purposes, I've below piece of code which reads a file and converts the same to pandas dataframe first and then to pyarrow table. This table is then stored on AWS S3 and would want to run hive query on the table.</p>
<p>Inputfile contents:</p>
<pre><code>YEA... | <p>This replicated fine for me for roundtripping. Please specify your platform & versions of <code>python</code>, <code>pandas</code> and <code>pyarrow</code></p>
<p>On 3.6 / macox (also worked on 2.7)</p>
<pre><code>In [1]: import pandas as pd
In [2]: import pyarrow as pa
In [3]: pd.__version__
Out[3]: '0.19.2... | pandas|hive|parquet | 0 |
356,833 | 43,113,076 | ImportError Tensorflow | <p>I am having a serious problem trying to import Tensorflow. When I do it, I get the following error:</p>
<hr>
<pre><code>Traceback (most recent call last):
File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper
fp, p... | <p><em>(Posted on behalf of the OP)</em>.</p>
<p>The problem was that I had Python 3.6, while Tensorflow only supports Python 3.5.</p> | python|python-3.x|tensorflow | 0 |
356,834 | 43,287,700 | Need of abs () method while plotting a power spectral density for a given dataset | <p>Hello Everyone,
I am a newbie in data science and would like to know the significance of using the abs () function and squaring the values received as an output of fft () function of python's scipy. fftpack library, used while trying to plot a power spectral density for a dataset. I have found that many... | <p>The general-purpose FFT consumes complex-valued data (i.e., real and imaginary) and returns complex-valued data. Even if your input is real-only, all FFT routines I’m familiar with (FFTW, Numpy’s FFT, Scipy’s FFTPACK, Matlab, etc.) have <code>fft()</code> that returns complex-valued data.</p>
<p>So. To plot a compl... | python|numpy|machine-learning|scipy|signal-processing | 1 |
356,835 | 43,240,980 | Efficiently counting duplicate values in a numpy column and appending the counts | <p>I have a dataset representing a directed graph. The first column is the source node, the second column is the target node, and we can ignore the third column (essentially a weight). So for example:</p>
<pre><code>0 1 3
0 13 1
0 37 1
0 51 1
0 438481 1
1 0 3
1 4 354
1 10 2602
1 11 2689
1 12 1
1 18 345
1 19 311
1 23 1... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>numpy.unique</code></a>.</p>
<p>Suppose your input data is in the array <code>data</code>:</p>
<pre><code>In [245]: data
Out[245]:
array([[ 0, 1, 3],
[ 0, 13, ... | python|numpy|bigdata | 4 |
356,836 | 43,159,077 | Trouble in obtaining correct geometric transformation of cartesian coordinates | <p>I am working in python and i have previous <code>(x_prev,y_prev) = (1.5, 3)</code> coordinate and current <code>(x,y) = (2, 3.2)</code>coordinate and <code>angle</code> difference between them and i want the next coordinate to be at a certain distance <code>d</code> with the same orientation as the current <code>(x,... | <p>I partly agree with <a href="https://stackoverflow.com/questions/43159077/trouble-in-obtaining-correct-geometric-transformation-of-cartesian-coordinates#comment73399281_43159077">@ImportanceOfBeingErnest</a> that your question is a geometrical one. However, I'm adding an answer because numpy lets you avoid all that ... | python|numpy | 0 |
356,837 | 43,210,157 | C# - Start multiple threads childs of the same "never-closing" father process | <p>I need to open a CMD window and run a process that starts an environment (command <code>activate tensorflow</code>). Then, when needed, I launch another command that can be considered a thread, with a sequence of other commands, into the same window. </p>
<p>Practically, the father process is always up for allowin... | <p>If you're starting a <code>Process</code>, you may be interested in redirecting the <a href="https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput.aspx" rel="nofollow noreferrer">input</a>, <a href="https://msdn.microsoft.com/en-us/library/system.diagnostics.processstarti... | c#|multithreading|parallel-processing|tensorflow | 0 |
356,838 | 43,377,203 | assert _backend in {'theano', 'tensorflow'} AssertionError | <p>I'm trying to run <a href="https://gist.github.com/fchollet/7eb39b44eb9e16e59632d25fb3119975" rel="nofollow noreferrer">this code</a>, but getting the following error:</p>
<pre><code>Traceback (most recent call last):
File "classifier_from_little_data_script_3.py", line 39, in <module>
from keras import... | <p>your keras.json should look like this</p>
<pre><code>{
"image_data_format": "channels_last",
"epsilon": 1e-07,
"floatx": "float32",
"backend": "tensorflow"
}
</code></pre>
<p>Notice the difference <code>"backend" : "tensorflow"</code> versus what you have <code>"backend" : "tf"</code></p> | python|tensorflow|theano|keras | 1 |
356,839 | 43,068,124 | Calculate matrix column mean | <p>I've got this matrix:</p>
<pre><code> [[[ 0.49757494 0.50242506]
[ 0.50340754 0.49659246]
[ 0.50785456 0.49214544]
...,
[ 0.50817149 0.49182851]
[ 0.50658656 0.49341344]
[ 0.49419885 0.50580115]]
[[ 0.117 0.883 ]
[ 0.604 0.396 ]
... | <p>Assuming your input shape is <code>(3,n,2)</code> and you want the shape to be <code>(n,3,2)</code> you will want first to do</p>
<pre><code>in=in.reshape((-1,3,2))
</code></pre>
<p>If you have a weighting vector <code>w</code></p>
<pre><code>w = np.random.rand(3)
</code></pre>
<p>Then you can do weighted averag... | python|python-3.x|numpy|machine-learning | 2 |
356,840 | 43,036,302 | How to make sure there are an equal amount of elements in two Python lists? | <p>I have two lists each with a length of about 1.6 million items. Each item is either blank or has an embedded list within it of 1 or more strings. Unfortunately, there's missing data in one of the lists such that the two don't correspond. I want to write the contents of these lists to a flat dataframe, but can't if t... | <p>In your example, the corresponding items are either identical, or the one in <code>list_B</code> should be replaced by a list of <code>NA</code>'s of the same length as the item in <code>list_A</code>. This generator expression should be fast enough:</p>
<pre><code>(a if a==b else len(a)*['NA'] for a,b in zip(list... | python|list|python-3.x|numpy | 5 |
356,841 | 72,299,238 | How can I apply this function and assign the calculated values in a new column of the dataframe in python? | <p>I want to calculate option greeks delta value and assign the calculated values in new column in the dataframe. Here is my code below_</p>
<pre><code>#!pip install mibian
import requests
import json
import pandas as pd
import mibian
import time
session = requests.Session() # Create request session object
url1 = &q... | <p>Change the below lines of code,</p>
<pre><code>ce_df["ce_delta"] = ce_df.apply(call_delta(ce_df["ce_underlyingValue"], ce_df["strike"],
int(intrestRate), int(daysToExpiry), ce_df["ce_impliedVolatility"]))
</code></pre>
<p>to</p>
<pre><code>ce_df["ce_delta"] = ce_df.... | python|pandas | 0 |
356,842 | 72,170,227 | Create sparse matrix from three datasets | <p>I have three datasets:</p>
<pre><code>users_df = pd.read_csv('users.csv')
books_df = pd.read_csv('books.csv')
ratings_train_df = pd.read_csv('ratings_train.csv')
</code></pre>
<p>The first one describes all the users in the system. The second one describes all the books and the third one contains UserID and BookID a... | <p>LightFM is a library for boomers. You should use</p> | pandas|machine-learning|sparse-matrix | 0 |
356,843 | 72,382,518 | Combining two columns in Pandas using a set rule | <p>I have a large Pandas dataframe that looks roughly like this:</p>
<pre><code>df = pd.Dataframe({'1m1y_vol': {0: 71.0, 1: 60.1, 2: 68.95},
'1m25y_vol': {0: 75.9, 1: 81.45, 2: 89.4},
'Days_since_meeting': {0: 8, 1: 1, 2: 5},
'Days_to_meeting': {0: -50, 1: -39,... | <p>Is this what you are looking for if not I'm not entirely sure I understand the question.</p>
<pre><code>df = pd.DataFrame({'1m1y_vol': {0: 71.0, 1: 60.1, 2: 68.95},
'1m25y_vol': {0: 75.9, 1: 81.45, 2: 89.4},
'Days_since_meeting': {0: 8, 1: 1, 2: 5},
'Days_to... | python|pandas|dataframe | 0 |
356,844 | 72,416,179 | convert the datetime stamp in numpy array | <p>This might be simple but I had no luck finding the right solution.
I have a 'date' column in np array with dates in format 'Tue Feb 04 17:04:01 +0000 2020' which I would like to convert to '2020-02-04 17:04:01'</p>
<p>Are there any inherent methods in np which does that?</p>
<p>There are solutions which suggested lo... | <p>Maybe you can try <strong>dateutil</strong> to parse dates</p>
<pre><code>from dateutil import parser
date_str = 'Tue Feb 04 17:04:01 +0000 2020'
new_date = parser.parse(date_str).strftime('%Y-%m-%d %T')
</code></pre>
<p>With NumPy maybe you do as below:</p>
<pre><code>np.datetime64(new_date)
#Example
date_str = 'T... | python|numpy | 0 |
356,845 | 72,425,723 | How to properly create an ‘indicator column’ | <p>Hi so this is my example dataframe. In reality there are hundreds and thousands of players. I am trying to create a new column which indicates if the player has left or not. I’m thinking of coding if lost_on column = NaN then (new indicator col= No) and if it has a value(date) then yes? I’m not entirely sure about t... | <p>IIUC, you can use</p>
<pre class="lang-py prettyprint-override"><code>df['Player_lost'] = np.where(df['Lost_on'].isna(), 'No', 'Yes')
</code></pre> | python|pandas|multiple-columns|indicator | 1 |
356,846 | 72,243,958 | Drop duplicate IDs keeping if value = certain value , otherwise keep first duplicate | <pre><code>>>> df = pd.DataFrame({'id': ['1', '1', '2', '2', '3', '4', '4', '5', '5'],
... 'value': ['keep', 'y', 'x', 'keep', 'x', 'Keep', 'x', 'y', 'x']})
>>> print(df)
id value
0 1 keep
1 1 y
2 2 x
3 2 keep
4 3 x
5 4 Keep
6 4 x
7 5 y
8 5 x
</... | <p>In your case try with <code>idxmax</code></p>
<pre><code>out = df.loc[df['value'].eq('keep').groupby(df.id).idxmax()]
Out[24]:
id value
0 1 keep
3 2 keep
4 3 x
5 4 Keep
7 5 y
</code></pre> | python|pandas | 1 |
356,847 | 72,179,220 | User defined function two data sets on same plot python | <p>I have written a user-defined function to make a plot. I apply this plot to two different data sets. They appear in two separate figures, but I want them to be plotted on the same figure.</p>
<pre><code>dictionaries = [dic_1,dic_2,dic_3,dic_4,dic_5,dic_6] # array of dictionaries
dataframes={}
#import dataframes
fo... | <p>The following is a start, though sharing a minimal working example (i.e. actual code and data) will make it possible to provide a better answer.</p>
<h3>toy data, and imports:</h3>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 ... | python|pandas | 0 |
356,848 | 72,366,931 | plotly Choropleth Map gets stuck loading when changing colour= | <p>I am trying to create a plotly choropleth map of the uk local authorities, using predicted autism prevalence. The script is getting stuck infinitely loading when I try and assign "colour=predictedprevalence" so that the choropleth shows predicted autism rates from the dataset in each authority area. I am u... | <p>Are you sure you are not specifying the user data incorrectly, it should be in csv format, but you are reading JSON format. I datamined your CSV data image and ran the code. The graph appears to be displayed correctly.</p>
<pre><code>import pandas as pd
import json
from urllib.request import urlopen
import numpy as ... | python|pandas|plotly|plotly-python | 1 |
356,849 | 72,206,485 | Python Pandas: Create new column by matching one column value to a different row [i] and column if a separate column on row [i] equals col one value | <p>Sorry for the very wordy title. I have a df which looks like this:</p>
<pre><code>df:
username user_id subreddit_id subr_fav_by
0 'John69' 1 1 '5illycat'
1 'John69' 1 2 'adsgd'
2 'Harry12' 2 3... | <p>You could try <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>pd.DataFrame.merge</code></a>:</p>
<pre><code>df.merge(df[['username', 'user_id']].rename(
columns={'username':'subr_fav_by', 'user_id':'subr_fav_by_id'}), how='left')
</code></pre> | python|pandas|dataframe | 1 |
356,850 | 72,266,602 | The sensitivity does not improve despite making multiple changes in model and dataset | <p>I have a CNN model which I run on the dataset which is linked here for viewing : <a href="https://drive.google.com/drive/folders/1JPvRIs81XQOooRz4-VQt9vH_3Vat556a?usp=sharing" rel="nofollow noreferrer">data</a>
I have tried using sensitivity and specificity provided by Keras and also tried the one using scikit learn... | <p>The performance metrics improved when I used my custom validation set which is a stratified split of 80-20 from training.</p> | python|tensorflow|keras|scikit-learn|deep-learning | 0 |
356,851 | 72,473,324 | Python imaging producing rectangular pixels instead of square pixels | <p>New to Python Imaging Library (PIL) but have noticed that generated pixels are rectangular and not a square. See images</p>
<p><a href="https://i.stack.imgur.com/5041Lm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5041Lm.png" alt="Left red pixel is off" /></a>
<a href="https://i.stack.imgur.com... | <p>I think that is a division problem because the dimension of your image can't fit the number of pixels you want to draw.</p>
<p>If you change your dimension to:</p>
<pre><code>dim=(480, 480)
</code></pre>
<p>You'll get perfect squares</p>
<p>I'd probably use power of 2 for both "n" and dims, so you'll never... | python|image|numpy|python-imaging-library|pixel | 2 |
356,852 | 72,235,953 | Assign multiple columns different values based on conditions in Panda dataframe | <p>I have dataframe where new columns need to be added based on existing column values conditions and I am looking for an efficient way of doing.
For Ex:</p>
<pre><code>df = pd.DataFrame({'a':[1,2,3],
'b':['x','y','x'],
's':['proda','prodb','prodc'],
'r':['oz1','... | <p>The exact output is unclear, but you can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with 2D data.</p>
<p>For example:</p>
<pre><code>cols = ['c', 'd']
df[cols] = np.where(df['b'].eq('x').to_numpy()[:,None],
... | python|pandas|dataframe|numpy | 1 |
356,853 | 72,296,493 | Add the number of columns that have a value above a certain value pandas | <p>Assuming I have the following toy model, <code>df</code>:</p>
<pre><code>product customer1 customer2 customer3
apple 40 110 120
banana 200 150 180
coconut 10 5 25
daq 120 10 30
eclair ... | <p>Try this</p>
<pre><code>df = pd.DataFrame({'product': ['apple', 'banana', 'coconut', 'daq', 'eclair'],
'customer1': [40, 200, 10, 120, 45],
'customer2': [110, 150, 5, 10, 190],
'customer3': [120, 180, 25, 30, 35]})
# among the customer columns, count the num... | python|pandas | 5 |
356,854 | 72,336,232 | Create numpy array with shape of one array and values from a list | <p>I have a (128x128) array consisting of values of which cluster/super-pixel each pixel belongs to, small 9x9 example:</p>
<pre><code>array([[0, 0, 1, 1, 1, 2, 2, 2, 2],
[0, 0, 1, 1, 1, 2, 2, 2, 2],
[0, 0, 1, 1, 1, 2, 2, 2, 2],
[3, 3, 3, 3, 4, 4, 4, 4, 4],
[3, 3, 3, 3, 4, 4, 4, 4, 4],
... | <p>Use the original array as the index of the mapping array:</p>
<pre><code>>>> arr
array([[0, 0, 1, 1, 1, 2, 2, 2, 2],
[0, 0, 1, 1, 1, 2, 2, 2, 2],
[0, 0, 1, 1, 1, 2, 2, 2, 2],
[3, 3, 3, 3, 4, 4, 4, 4, 4],
[3, 3, 3, 3, 4, 4, 4, 4, 4],
[3, 3, 3, 3, 4, 4, 4, 4, 4],
[5, ... | python|numpy|superpixels | 2 |
356,855 | 72,482,319 | How to reorder pandas dataframe based off list containing column order | <p>Say I have a dataframe 'df' that contains a list of files and their contents:</p>
<pre><code>File Field Folder
Users.csv Age UserFolder
Users.csv Name UserFolder
Cars.csv Color CarFolder
Cars.csv Model CarFolder
</code></pre>
<p>How can I reorder this df i... | <p>First, put your new orders in a dictionary:</p>
<pre><code>mapping = {
'Users': ['Name', 'Age'],
'Cars': ['Model', 'Color'],
}
</code></pre>
<p>Then, create a new column with those values properly positioned according to the <code>File</code> values, and make <code>Field</code> the index and index it with th... | python|pandas|dataframe|sorting | 1 |
356,856 | 72,355,098 | Pandas: Aggregate data frame based on column values | <p>I have a data set that looks like this:</p>
<pre><code> Name Volume Period
1 oil 29000 Jun 21
2 gold 800 Mar 22
3 oil 21000 Jul 21
4 gold 1100 Sep 21
5 gold 3000 Feb 21
6 depower 3 Q1 21
7 oil 23000 Apr 22
8 czpower 26 Q1 23
9 oil 17000... | <p>Is this what you're looking for?</p>
<pre><code>newDF = df.pivot_table("Volume", ["Period"], "Name")
</code></pre> | python|pandas|dataframe|data-wrangling | 1 |
356,857 | 72,362,222 | How to count duplicates in column Pandas? | <p>I use this rule to filter all rows where column num is unique. So I remove the duplicates:</p>
<pre><code>df.drop_duplicates(subset=["num"], keep=False)
</code></pre>
<p>Also the same I do with column age:</p>
<pre><code>df.drop_duplicates(subset=["age"], keep=False)
</code></pre>
<p>How to show ... | <p>For new DataFrame call <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a> per columns in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer... | python|pandas | 2 |
356,858 | 72,463,563 | Is there a function to download a pickle file via requests.post(url) and load it into a dataframe without saving it locally | <p>I am trying to download a <strong>pickle</strong> file from a web-based API via the requests.post(url) function in python. I was able to download and load the pickle file in a dataframe however i had to save it locally before loading it. I wanted to check if there is a way to load the pickle file directly into the d... | <p>Just a guess at something that might work for you since it looks like the pickle file contains text-csv-like data.</p>
<pre><code>df=pd.read_csv(io.StringIO(pd.read_pickle(url)),header=0,engine=None)
</code></pre> | python|pandas|post|python-requests|pickle | 1 |
356,859 | 72,440,268 | logits and labels must have the same first dimension, got logits shape [2048,10] and labels shape [32] | <p>I am trying to use the following code to for a CNN to classify images.</p>
<p>essentially, this code takes in a directory with folders and images, and trains a CNN to classify them.</p>
<p>This is my code:</p>
<pre><code> self.model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', pa... | <p>Without knowing your data and data preparation it is hard to reproduce, but I think the problem could be your <strong>loss function</strong></p>
<pre><code>self.model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=["accuracy"]
)
</code></pre>
<p>Try using <code>categ... | python|tensorflow|keras|neural-network|conv-neural-network | 1 |
356,860 | 72,169,392 | convert tf.tensor to numpy | <p>I've built a custom loss function to train my model</p>
<pre><code>def JSD_Tensor_loss(P,Q):
P=tf.make_ndarray(P)
Q=tf.make_ndarray(Q)
M=np.divide((np.sum(P,Q)),2)
D1=np.multiply(P,(np.log(P,M)))
D2=np.multiply(Q,(np.log(Q,M)))
JSD=np.divide((np.sum(D1,D2)),2)
JSD=np.sum(JSD)
return JSD
model.comp... | <p>Your error stems from your conversion to numpy.array (first two lines).</p>
<p>If you have to convert a tensor (which in my opinion you shouldn't in this case), I would go with:</p>
<pre><code>P, Q = P.numpy(), Q.numpy()
</code></pre>
<p>However, this is really not necessary here. Just replace the numpy function wit... | python|numpy|tensorflow|tensor | 0 |
356,861 | 72,282,662 | Concatenate row values in Pandas DataFrame | <p>I have a problem with Pandas' DataFrame Object.
I have read first excel file and I have DataFrame like this:
<a href="https://i.stack.imgur.com/zoUvD.png" rel="nofollow noreferrer">First DataFrame</a></p>
<p>And read second excel file like this:
<a href="https://i.stack.imgur.com/GX6EB.png" rel="nofollow noreferrer"... | <p><code>merge</code> does not concatenate the dfs as you want, use <code>append</code> instead.</p>
<pre><code>ndf = df1.append(df2).sort_values('name')
</code></pre>
<p>You can also use concat:</p>
<pre><code>ndf = pd.concat([df1, df2]).sort_values('name')
</code></pre> | pandas|dataframe|merge|concatenation | 0 |
356,862 | 72,292,399 | How to search a data frame and remove items that match another data frame | <p>I have two dataframes:</p>
<p>df1 = names: Tom, Nick, Pat, Frank
df2 = names: Tom, Nick</p>
<p>I would like to make a df3 by having df2 search through df1 and remove matches so I am left with a new dataframe:
df3 = names: Pat, Frank</p> | <p>You can do:</p>
<pre class="lang-py prettyprint-override"><code>df3 = df1[~df1['names'].isin(df2['names'])]
</code></pre>
<p>This checks each name in df1 to see if it is in df2, then takes the opposite of the boolean result, and filters df1 based on those resulting bools.</p> | pandas|dataframe | 0 |
356,863 | 72,392,017 | Link values in table to (first) column - pandas | <p><strong>I got a table with no header in which the first column is followed by around 50 other columns with some nan-values and some values that appear more than 5 times.</strong></p>
<p>I would like to let the values from the 2nd to the last column point to the values in the first column.</p>
<p>For example, my data... | <p>I wrote some quick and dirty code to help myself.</p>
<pre><code>df_list = frame1.values.tolist()
z=[]
for x in df_list:
z.append(set(x))
q=[]
for b in z:
q.append({x for x in b if x==x})
r=[]
for w in q:
r.append(list(w))
dict_values = { i+1 : r[i] for i in range(0, len(r) ) }
dict2= {}
for keys,val... | python|pandas | 0 |
356,864 | 72,423,191 | Dataframe update code runs perfectly on a test dataframe but not on a larger dataframe | <p>I am trying to update a dataframe and while the update code works perfectly fine in a test dataframe, it does not work on a bigger dataframe. I cannot seem to understand why.</p>
<pre><code>selection_weights:
country league Win DNB O 1.5 U 4.5
0 Africa Africa Cup of Nations ... | <h3>Possible cause of the problem</h3>
<p><code>DataFrame.update</code> internally relies on matching indices(both columns and rows) to update the corresponding values.</p>
<p>Now in your small dataframe the merge <code>ids</code> doesn't seem to have duplicates hence the resulting merged dataframe has indices similar ... | python|pandas|dataframe | 1 |
356,865 | 72,263,534 | Get average intervals in a list of dates in dataframe | <p>I have a dataframe like this</p>
<pre><code>Event dates Duration
Event1 [1796-12-02, 1796-12-10, 1796-12-11] 9 days
Event2 [1848-03-31, 1848-02-26] 34 days
Event3 [1826-05-20] 0 days
</code></pre>
<p>And I would like to add an "Average ... | <p>You can use this line:</p>
<pre><code>df["Average"] = df.apply(lambda x: float(x["Duration"].replace(" days", ""))/(len(x["dates"])-1), axis=1)
</code></pre> | python|pandas|dataframe|datetime | 0 |
356,866 | 72,373,595 | Keras Tuner get_best_hyperparameters() | <p>Is there any way to have the best hyperparameters get returned as a list that I can access in other parts of my code?
I don't want the entire model, I just want to be able to extract the values of the optimal hyperparameters it finds and use it in a different python file.</p>
<pre><code>tuner = keras_tuner.RandomSea... | <p>I think I found a way to do it. Turns out there is a dictionary that stores the best hyperparameters values and names, to acces it you have to type the following (try it in the console first):</p>
<pre><code>best_hp.values
</code></pre>
<p>This is of course, assuming that you have already done the tuning and hyperpa... | python-3.x|tensorflow|keras-tuner | 2 |
356,867 | 72,151,375 | Separate values in a DataFrame column into a new columns depending on value | <p>I have a DataFrame like below but much larger:</p>
<pre><code>df = pd.DataFrame({'team': ['Mavs', 'Lakers', 'Spurs', 'Cavs', 'Mavs', 'Lakers', 'Spurs', 'Cavs'],
'name': ['Dirk', 'Kobe', 'Tim', 'Lebron', 'Kobe', 'Lebron', 'Tim', 'Lebron'],
'rebounds': [11, 7, 14, 7, 9, 5,7,12],
... | <p>You can try <code>pivot</code></p>
<pre class="lang-py prettyprint-override"><code>df_ = df.pivot(index=['name', 'rebounds', 'points'], columns='team', values='team').reset_index().fillna('')
</code></pre>
<pre><code>print(df_)
team name rebounds points Cavs Lakers Mavs Spurs
0 Dirk 11 26... | python|pandas|dataframe | 2 |
356,868 | 72,252,830 | How to solve a system of ODEs with Scipy when the variables in the equations are autogenerated | <p>I'm generating a system of ODEs in the form of a list of equations where the variables are <code>sympy.Symbol()</code>, for example <code>[3*sympy.Symbol('x')**3+sympy.Symbol('y') , sympy.Symbol('x')-sympy.Symbol('y')**4]</code>.</p>
<p>So using this example, I can solve this system through the code</p>
<pre><code>i... | <p>The reason you are getting that results is because you are overwriting <code>eqs</code> inside <code>kin</code> at each iteration. Also, as mentioned by Lutz, you should use <code>lambdify</code> which is going to convert symbolic expressions to numerical functions so that they can be evaluated by Numpy (much faster... | python|numpy|scipy|sympy|ode | 1 |
356,869 | 72,335,578 | How to apply multiple functions to all sheets and then save as one excel workbook | <p>So I imported all sheets from an excel file using <code>pd.read_excel('df.xlsx',sheet_name=None)</code>.
I have a dict with key value pairs.
In all these sheets there is a table present. I want to make the first column as index and then insert a column from a separate dataframe that I already have.</p>
<p>What is th... | <p>As you have a dict of key, values, where each value is a df, you can iterate over them and first set the index, next create a column based on the other df. Use:</p>
<pre><code>for name, df in data.items():
df = df.set_index('info')
df['new col'] = another_df['specified col']
</code></pre> | pandas|dataframe|dictionary | 0 |
356,870 | 72,166,499 | Bin rows by time with pandas | <p>So this may seem like a simple question, but every question I've checked isn't exactly approaching the problem in the same way I am.</p>
<p>I'm trying to bin the timestamps of a dataframe into specific buckets. I want to be able to count every minute of a dataframe starting from the first row until the last. I then ... | <p>I am not sure I quite get what you are going for here but wouldn't this be equivalent to getting the rank of seconds?</p>
<p>As far as I understand it, binning has to do with putting together an interval (fixed or not) and counting the number of items in it. If you could please elaborate on this I'll do my best to h... | python|pandas|dataframe | 0 |
356,871 | 72,261,260 | pandas dataframe: How to replace a value in a row, based on whether the ID of that row is in a certain list | <p>So I’ve got this dataset(df) that includes Unique IDs representing a person, then certain IDs for jobs each person has applied for that go across a row like so</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">ID</th>
<th style="text-align: left;">JobA</th>
<th st... | <p>One option using a boolean mask:</p>
<pre><code>lst = [2, 4]
mask = df['ID'].isin(lst)
df[mask] = df[mask].replace(31, float('nan'))
</code></pre>
<p>output:</p>
<pre><code> ID JobA JobB JobC JobD
0 1.0 23.0 31.0 56.0 67.0
1 2.0 4.0 13.0 NaN 43.0
2 3.0 7.0 18.0 31.0 33.0
3 4.0 NaN 34.0 ... | python|pandas|dataframe | 0 |
356,872 | 72,179,285 | TypeError: Unable to convert function return value to a Python type! The signature was () -> handle anaconda spyder | <p>This is the code:</p>
<pre><code> import os
import random
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, Input
from tensorflow.keras.models import... | <p>Check if your numpy is the latest version.</p>
<pre><code>import numpy
print(numpy.__version__)
</code></pre>
<p>If your numpy is not the latest version, try to upgrade to the latest version.</p>
<pre><code>pip install numpy --upgrade
</code></pre> | python|python-3.x|tensorflow|machine-learning|keras | 0 |
356,873 | 72,178,647 | assign row of pandas dataframe to another row in another dataframe | <p>I have two dataframes df1 and df2. df1 has 10 columns, where column 0 includes the original image names and the remaining columns including their features and the target variable. df2 has one column that include the augmented image names. I want to pick the values in each row of df1 and assign them to each row in df... | <p>If the image names are all like that, you could use regex to extract the original from the augmented, then merge.</p>
<pre><code>>>> df2['original'] = df2['augmented'].str.extract(r'/(.*?)\.')
>>> df2.merge(df1, how='left', on='original')
augmented original features target
0 ... | python|pandas|dataframe | 0 |
356,874 | 72,435,916 | Why do you need to put index, row in data frame.iterrows() in pandas when using a for loop? | <p>I tried to run this code:</p>
<pre><code>import pandas
data = pandas.read_csv("data.csv")
for row in data.iterrows():
print(row["column_title"])
</code></pre>
<p>I kept getting a TypeError:</p>
<pre><code> File "main.py", line 4, in <module>
print(row["column_title_1&q... | <p>Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iterrows.html" rel="nofollow noreferrer">iterrows</a> returns a <code>tuple</code> containing the <code>index</code> and the <code>Series</code> of the row, as stated by the documentation.</p>
<blockquote>
<p>Iterate over DataFrame rows as... | python|pandas | 1 |
356,875 | 72,232,157 | Dataframe Operation Splicing | <p>I have a single column dataframe without headers and I want to split it into multiple columns as follows
The current dataframe -</p>
<pre><code>1
2
3
4
5
.
.
100
</code></pre>
<p>I want to represent it as -</p>
<pre><code>1 6 .. .. 96
2 7 .. .. 97
3 8 .. .. 98
4 9 .. .. 99
5 10 .. .. 100
</code></pre> | <p>Assuming such a DataFrame:</p>
<pre><code>df = pd.DataFrame({'col': range(1, 101)})
</code></pre>
<p>you can use the underlying numpy array to reshape:</p>
<pre><code>df2 = pd.DataFrame(df['col'].to_numpy().reshape(5, -1, order='F'))
</code></pre>
<p>output:</p>
<pre><code> 0 1 2 3 4 5 6 7 8 9 ... | pandas|dataframe | 0 |
356,876 | 72,291,454 | Frequencies for Hermitian Fourier Transform (`numpy.fft.hfft()`)? (hypothetical function `numpy.fft.hfftfreq()`) | <p>For a normal FFT, Numpy implements the method <code>fftfreq(n,d)</code>, which provides the frequencies of the FFT right away. However, for the Hermitian transformation <code>hfft</code>, the companion function <code>hfftfreq</code> is missing. What would be the returned values of the function <code>hfftfreq(n,d)</c... | <p>The <code>hfft()</code> / <code>ihfft()</code> pairs are equivalent to <code>irfft()</code> / <code>rfft()</code> pairs, respectively and except for the normalization.</p>
<p>In particular, <code>np.fft.hfft(arr, n, norm='forward')</code> is identical to <code>np.fft.irfft(arr, n, norm='backward')</code> (the <code>... | python|numpy|fft | 2 |
356,877 | 72,407,092 | Boolean value of Tensor with more than one value is ambiguous | <p>I have this class of NN:</p>
<pre><code>class Block(nn.Module):
def __init__(self, in_planes, out_planes, stride=1):
super(Block, self).__init__()
self.conv1 = nn.Conv2d(in_planes, in_planes, kernel_size=3, stride=stride,
padding=1, groups=in_planes, bias=False)
self.bn1 = nn... | <p>The issue is with the <code>nn.ReLU()</code> in the <code>feedforward()</code>. I was printing it which is not possible in <strong>ipynb</strong> file.</p>
<pre class="lang-py prettyprint-override"><code>class Block(nn.Module):
def __init__(self, in_planes, out_planes, stride=1):
super(Block, self).__in... | neural-network|pytorch|conv-neural-network|mobilenet | 1 |
356,878 | 72,155,602 | ValueError: x and y must be equal-length 1D arrays | <p>I run the following code to animate a moving sphere, in which the coordinates are in a text file:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import cm
from matplotlib import animation
import pandas as pd
df = pd.read_csv('/path/to/text/file', s... | <p>If the surface you are about to plot has a parametric equation (such as a sphere), use the meshgrid approach (<code>x, y, z</code> must be 2D arrays) and call <code>ax.plot_surface</code>. Instead, you used 1D arrays and later called <code>ax.plot_trisurf</code>: this function is better suited when it's not easy to ... | python|arrays|pandas|matplotlib|animation | 1 |
356,879 | 72,222,845 | Convert JSON format column to new columns | <p>I have a sub-Yelp Dataset in csv, and attributes column is in json format. I'm trying to convert that column to new columns, but none of the relevant code on different question works for me.</p>
<p>Texts in the attributes column are in this format, in every row:</p>
<pre class="lang-py prettyprint-override"><code>bu... | <p>This gets you a step closer to what you want:</p>
<pre><code>d = {"WiFi": "u'no'", "HasTV": "False", "Caters": "False", "Alcohol": "u'full_bar'", "Ambience": "{'touristy': False, 'hipster': False, 'romantic': True, 'divey'... | python|json|pandas|csv | 0 |
356,880 | 72,390,776 | Creating a new column based on conditions for other columns | <p>I have a DataFrame with columns consisting of some values and NaN where there were no values assigned for the specific column.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'id': [10, 46, 75, 12, 99, 84],
'col1': ['Nan',
15,
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isna.html" rel="nofollow noreferrer"><code>DataFrame.isna</code></a> for test all columns if missing and then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html" rel="nofollow noreferrer"... | python|pandas | 2 |
356,881 | 72,399,848 | Backfilling and Forwardfilling NaNs and Zeros | <p>I am trying to back/forward fill the work experience (years) of employees. What I am trying to achieve is:</p>
<p>Employee 200</p>
<p>2019 - 3 yrs, 2018 - 2 yrs, 2017 - 1 yr</p>
<p>Employee 300</p>
<p>Keep as Nan</p>
<p>Employee 400</p>
<p>2018 - 3 yrs, 2017 - 2 yrs</p>
<p>Employee 500</p>
<p>2018 - 6 yrs, 2017 - 5 ... | <p>Assuming there's a single nonzero and non-nan experience for each employee, try this</p>
<pre class="lang-py prettyprint-override"><code>df_test = pd.DataFrame({'DeptID':[0,0,0,1,1,1,2,2,2],
'Employee':[200, 200, 200, 300, 400, 400, 500, 500, 500],
'Year':[2017, 2018, ... | python|pandas|missing-data | 3 |
356,882 | 72,217,385 | Python & Pandas: apply scoring function to df new column not working | <p>I want to create a score based on the value of several columns in the dataframe. I created the following snippet but the function does not apply as it return only 0 values...</p>
<pre><code>def momentum_score (row):
if ((row['rsi_1'] < 30) & (row['rsi_2'] > 30) & (row['rsi_3'] > 30)):
... | <p>You can try with apply but it's slower than a vectorized solution.
The problem is the use of the if-elif-els statement.</p>
<pre class="lang-py prettyprint-override"><code>def momentum_score (row):
if ((row['rsi_1'] < 30) & (row['rsi_2'] > 30) & (row['rsi_3'] > 30)):
val = 1
elif ... | python|pandas|apply|scoring | 1 |
356,883 | 72,170,164 | Divide a large dataframe into smaller sub dataframes in order | <p>Is there any way to divide the very large data frame into smaller 5 sub-data frames with equal parts? I cannot use the train test split because it does not keep the data in order.
The solution that already exists <a href="https://stackoverflow.com/questions/17315737/split-a-large-pandas-dataframe">Split a large pand... | <p>Following my comment. Here is an example, note it's probably not the best approach..:</p>
<pre><code>import numpy as np
dfs = np.array_split(df2, 5)
for index, df in enumerate(dfs):
globals()['df%s' % index] = pd.DataFrame(df)
df3
</code></pre> | python|pandas|dictionary | 0 |
356,884 | 72,202,525 | TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' when using cv2 | <pre><code>import cv2
import numpy as np
from os import listdir
from os.path import isfile, join
# Get the training data we previously made
data_path = 'C:\\Users\\hp\\Unlock-Application\\frames'
onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path, f))]
# Create arrays for training data and labels
Tra... | <p>I suspect the error originates from this line:</p>
<p><code>onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path, f))] </code></p>
<p>You are checking if <code>isfile</code> but instead you should be checking if it's an image i.e if its <code>.png</code>, <code>.jpg</code>, because anything can be a f... | python|numpy|opencv | 0 |
356,885 | 72,274,023 | Pandas: get first occurrence and ignore if in any other column on same day | <p>Newbee here.</p>
<p>Given the below files, I am trying to count how many times a distinct value occurs. The data is for multiple facilities for each day so stuck how to get the correct totals.</p>
<p>Tried using nunique in combination with groupby but not able to get the logic.</p>
<pre><code>df1 = df.groupby(['Date... | <p><strong>UPDATED ANSWER:</strong></p>
<p>Based on clarifications by OP in comments, here is a new strategy to get what is required:</p>
<pre class="lang-py prettyprint-override"><code>df = df.set_index(['Date', 'Facility', 'Begin Time']).stack()
df.index=df.index.droplevel(3)
df = df.to_frame().rename(columns={0:'Nam... | python|pandas|dataframe | 1 |
356,886 | 72,409,779 | ModuleNotFoundError: No module named 'tensorflow.keras' , I tried almost everything | <p><a href="https://i.stack.imgur.com/vVZL2.png" rel="nofollow noreferrer">packages1</a></p>
<p><a href="https://i.stack.imgur.com/U41rY.png" rel="nofollow noreferrer">packages2</a></p>
<p>These are my packages on anaconda . I get this error on last photo . I tried almost everything on stackoverflow and on github .I tr... | <p>You should import Keras from Tensorflow, like so:</p>
<pre><code>import tensorflow as tf
import tensorflow.keras as keras
</code></pre>
<p>And to import the modules you want from Keras, you can use</p>
<pre><code>from keras.models import Sequential
from keras.layers import Input, Dense, TimeDistributed, Dropout
from... | python|tensorflow|machine-learning|keras | 1 |
356,887 | 50,322,001 | How to save/load a tensorflow hub module to/from a custom path? | <p>The <code>tensorflow_hub</code> library maintainers has made it every easy for users to download and use the pre-trained tensorflow modules, e.g.:</p>
<pre><code>import tensorflow_hub as hub
embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/1")
</code></pre>
<p>But from the <code>sys.stderr<... | <p>You can download your model need from url + '?tf-hub-format=compressed'</p>
<p>i tried downloading elmo and it worked </p>
<p>url = <a href="https://tfhub.dev/google/elmo/2" rel="noreferrer">https://tfhub.dev/google/elmo/2</a> + '?tf-hub-format=compressed'</p>
<p>eg: <a href="https://tfhub.dev/google/elmo/2?tf-hu... | python|tensorflow|deep-learning|pre-trained-model|tensorflow-hub | 19 |
356,888 | 50,658,852 | How to add leading 0's to different values in same column in pandas? | <p>I have a column that has values of length 5,6,8, or 9. The column should just have values of length 6 or 9. I need to add leading 0's if the value is of length 5 or 8. </p>
<p>There is another column which can identfy if the value should be 6 or 9 digits (indicator). An indicator value of 'Red' means 6 digits, and ... | <p>The error message tells you the type of your <code>digits</code> column is <code>float</code>, you need to change it to <code>int</code>. </p>
<p>Also, <code>lambda x: "{:006d}".format(x)</code> is just <code>"{:006d}".format</code>:</p>
<pre><code>df['digits'] = df[df['indicator'] == 'red']['digits'].astype(int).... | python|pandas|pandas-apply | 1 |
356,889 | 50,557,378 | What is the purpose of creating a reverse dictionary from a regular dictionary in Python | <p>I'm looking at the official Tensorflow example for Word2Vec. They created a dictionary for all the words, and then created a reverse dictionary, and the reverse dictionary was mainly used in the rest of the code. </p>
<p>The line in question:</p>
<pre><code>reverse_dictionary = dict(zip(dictionary.values(), dictio... | <p>To build the list <code>data</code>, the <code>build_dataset()</code> function requires a word to index mapping.</p>
<p>For use in subsequent functionality, an index to word mapping is required.</p>
<p>In Python, as in most languages, there is no structure for a memory-efficient <a href="https://stackoverflow.com/... | python|dictionary|tensorflow | 1 |
356,890 | 50,650,826 | Pandas to_excel as variable (without destination file) | <p>I recently had to take a dataframe and prepare it to output to an Excel file. However, I didn't want to save it to the local system, but rather pass the prepared data to a separate function that saves to the cloud based on a URI. After searching through a number of ExcelWriter examples, I couldn't find what I was lo... | <p>Works like the common examples, but instead of specifying the file in ExcelWriter, it uses the standard library's BytesIO to store in a variable (<code>processed_data</code>):</p>
<pre><code>from io import BytesIO
import pandas as pd
df = pd.DataFrame({
"a": [1, 2, 3],
"b": [4, 5, 6]
... | python|excel|pandas|pandas.excelwriter | 3 |
356,891 | 50,415,115 | Pandas: Select rows containing only strings? | <p>I have a data-frame that looks like this:</p>
<pre><code> [Column1] [Column2]
0 16155.22300 1.246982
1 16193.009 BMS1P17,BMS1P18,BMS1P22,DUXAP8
2 16231.289 LINC01297
5 16265.05300 2.156268
6 16287.937 POTEH,POTEH-AS1
7 16288.53800 2.156268
10 17645.92500 44.765792
11 17646.335 HDHD5,HDHD5... | <p>You can use:</p>
<pre><code>df['Column2'].loc[pd.to_numeric(df['Column2'], errors='coerce').isnull()]
</code></pre>
<p>Or if you want it in a list.</p>
<pre><code>list(df['Column2'].loc[pd.to_numeric(df['Column2'], errors='coerce').isnull()])
</code></pre> | python|pandas | 6 |
356,892 | 50,642,057 | Human body detection using opencv, tensorflow and python | <p>I am working on a robotic project that involves the detection of a human body for which I am using tensor flow and predefined data sets to create a training model. As I am new to machine learning, I am unable to properly get the output from my classifier. I require only the Person detection and want to avoid the det... | <p>As I can see from the docs <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/data/mscoco_label_map.pbtxt" rel="noreferrer">here</a>, you have to check only for the person class. Right now <code>vis_util</code> checks for all classes. You have to add an <code>if</code> condition for ... | python|opencv|image-processing|tensorflow | 6 |
356,893 | 50,350,539 | How to use an index to recall a label of a dataframe pandas | <p>maybe it's a trivial question but I cant find an answer to this problem:
I have a dataframe with these columns:</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df.columns
Index(['label', 'num.feature 1', 'num.feature 2', 'num.feature 3',
'num.feature 4', 'num.feature 5',...... | <p>You are pretty much there. just need to add format.</p>
<pre><code>for i in range(30):
df['num.feature {}'.format(i)].hist(bins=90,range=(0,0.4))
</code></pre>
<p>Should be good now.</p> | python|pandas|dataframe|indexing | 1 |
356,894 | 50,361,356 | Pandas/matplotlib isn't plotting all column data | <p>I have a dataframe called 'blah' that was created like this:</p>
<pre><code>blah = pandas.read_csv(address, index_col='Date', parse_dates=True)
blah.head()
TransactionName Withdrawal Deposit Total
Date
2016-12-01 PTS TO: ####### ... | <h2>NaN will always interrupt the line plot:</h2>
<p>Because the NaN still exist in the data the line will be interrupted. Pandas doesn't know how to carry the line through an NaN so only sequential numeric values can be plotted. You must remove the NaN to have the line continue all the way through the valid data. If ... | python|pandas|matplotlib|plot | 4 |
356,895 | 50,642,204 | write panda data to csv | <p>I have a csv sheet and it looks like below , each column has some data.
Want to filter data by Name . I know the names, from which I have to filter. </p>
<pre><code>Name gender address age post city
A M abc 20 dd ASD
C F xyz 21 ll KLM
B M lmn 22 mm ... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer">Series.str.contains</a> is the function you need. It returns a boolean Series which can be used to filter the DataFrame when used as its index. For multiple names, separate the names with <code>... | python|python-3.x|python-2.7|pandas|csv | 1 |
356,896 | 50,657,545 | Pandas dataframe groupby sum while ignoring non-numerical values | <p>I have a dataframe like below. The 'LATENCY' column has both numerical and 'NA' characters, that makes groupby() complex.</p>
<pre><code> DEVICE START_PRICE LATENCY
0 ab.fxx.in 500 NA
1 ab.fxx.in 500 1
2 ab.fxx.in 500 5
3 kddo.fxx.in 500 NA
4 ... | <p>You can convert <code>LATENCY</code> series to numeric before you use <code>groupby</code>.</p>
<p>Using <code>errors='coerce'</code> ensures you have <code>NaN</code> values where conversion is not successful. When you use <code>groupby.sum</code>, <code>pandas</code> handles these gracefully by ignoring them.</p>... | python|python-3.x|pandas|dataframe|pandas-groupby | 4 |
356,897 | 50,508,473 | ValueError: Wrong number of items passed 47, placement implies 1 and KeyError: 'size' | <p>Here's my dataframe shape</p>
<pre><code>a.shape
(4899, 48)
</code></pre>
<p>Then I did</p>
<pre><code>a['size'] = a.groupby(['customer_id']).transform(np.size)
</code></pre>
<p>And an error result is</p>
<pre><code>---------------------------------------------------------------------------
KeyError ... | <p>You need define one column after <code>groupby</code>, if use <code>size</code> each column working, else here get <code>DataFrame</code> - counts for each column:</p>
<pre><code>a = pd.DataFrame({'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':... | python|pandas|dataframe | 1 |
356,898 | 50,360,114 | Add columns to dataframe K-Mean - Python | <p>I am using this code to do K-Mean analysis on a dataframe. I am able to plot the resulting dataframe but I want to add the original dataframe columns to it. My python is not brilliant so it might be simple but I keep getting invalid syntax for whatever I try.</p>
<pre><code>import pandas as pd
import matplotlib.pyp... | <p>Simply do</p>
<pre><code>sh_df['x'] = df2['x']
sh_df['y'] = df2['y']
</code></pre>
<p>assuming the <code>sh_df</code> and <code>my_df</code> are ordered the same. That is, that the nth row of one dataframe corresponds to the nth row of the other. </p> | python|pandas|k-means|knn | 1 |
356,899 | 50,330,835 | Custom Lambda layer for Kronecker product in Keras - troubles with the dimension reserved for batch_size | <p>I am using Keras 2.1.5 with Tensorflow backend to create a model for image classification.
In my model, I would like to combine the input and the output of a convolution layer by counting the <a href="https://en.wikipedia.org/wiki/Kronecker_product" rel="nofollow noreferrer">Kronecker product</a>. I've written the f... | <p><strong>Easy solution:</strong></p>
<p>Simply add the batch dimension to your calcs and reshapes </p>
<pre><code>def kronecker_product(mat1, mat2):
#Computes the Kronecker product of two matrices.
batch, m1, n1 = mat1.get_shape().as_list()
mat1_rsh = K.reshape(mat1, [-1, m1, 1, n1, 1])
batch, m2, ... | python|tensorflow|lambda|keras|keras-layer | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.