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 |
|---|---|---|---|---|---|---|
358,700 | 68,142,926 | Match list of strings with column and return corresponding column value | <p>This is my dataframe df3:<br />
<a href="https://i.stack.imgur.com/yY3ss.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yY3ss.png" alt="enter image description here" /></a></p>
<p>My Template files are named like:<br />
<code>AdDape CBS Index Template 6.3.xlsx</code></p>
<p><code>AdDape Midlife I... | <p>I think what you generally want here is to use <code>merge()</code>, which will merge together two dataframes to give all the columns of both.</p>
<p>Your df2 will need columns for filename and sheetname. It looks like you might have to do a little work to get them into the same format as what you have in df3. Once ... | python|pandas|dataframe|data-analysis | 0 |
358,701 | 68,171,812 | Pandas creating new column based on consecutive duplicates | <p>I have a Pandas dataframe like the one below, where column A is a series of strings, and values in column B are true/false depending on whether the value of column A is the same as the value of column A in the previous row.</p>
<pre><code>A B
1 False
1 True
1b False ... | <p>Try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.ngroup.html#pandas-core-groupby-groupby-ngroup" rel="nofollow noreferrer"><code>groupby ngroup</code></a> + 1 be sure to <code>sort=False</code> to make sure groups are created in the order they appear in the DataFrame:</p>
<p... | python|pandas|numpy|boolean|shift | 2 |
358,702 | 68,263,505 | Python how to filter a csv based on a column value and get the row count | <p>I want to do data insepction and print count of rows that matches a certain value in one of the columns. So below is my code</p>
<pre><code>import numpy as np
import pandas as pd
data = pd.read_csv("census.csv")
</code></pre>
<p>The census.csv has a column "income" which has 3 values '<=50K'... | <p>The key is to learn how to filter pandas rows.</p>
<h3>Quick answer:</h3>
<pre><code>import pandas as pd
data = pd.read_csv("census.csv")
df2 = data[data['income']=='<=50K']
print(df2)
print(len(df2))
</code></pre>
<h3>Slightly longer answer:</h3>
<pre><code>import pandas as pd
data = pd.read_csv(&qu... | python|python-3.x|pandas | 1 |
358,703 | 68,245,212 | What is the issue with my date sorting in pandas dataframe? | <p>I'm trying to sort the dates in pandas using the standard method, the dates are converted to timestamps</p>
<pre><code> # open the merged data csv as df veriable
df = pd.read_csv(raw_data)
# turns the dates from an object into a pandas recognizes date format
df['Start Date'] = pd.to_datetime(df['Start Date'], forma... | <p>You have two options.
Edit last line, either</p>
<pre><code>df = df.sort_values(['Start Date'], ascending= True, kind= 'quicksort')
</code></pre>
<p>or</p>
<pre><code>df.sort_values(['Start Date'], ascending= True, kind= 'quicksort', inplace=True)
</code></pre> | python|pandas|sorting|datetime | 1 |
358,704 | 68,279,690 | Join without Cartesian output | <p>I have two dataframes, df1, df2, where I would like to join on two different table names. The goal is to concatenate the tables based on values that match in the site and id column without a Cartesian output. I am getting a final output with an exponentially increased records number.</p>
<p><strong>Data</strong></p... | <pre><code>df1.reset_index().join(df2.reset_index())# if it has no index
</code></pre>
<p>Or</p>
<pre><code>df1.join(df2 ,lsuffix='lft', rsuffix='rght')# if it has index
site planq tr unit alias energy serial sku type reason id
0 ny q1 22 du1 du_cc 10 34444.0 d1 d ok ny
1 ny q... | python|pandas|numpy | 1 |
358,705 | 68,315,656 | Element-wise apply array of functions to array of values in numpy, efficiently | <p>I have a numpy array with functions and another one with values:</p>
<pre><code>f = np.array([np.sin,np.cos,lambda x: x**2])
x = np.array([0,0,3])
</code></pre>
<p>I want to apply each function to each element in <code>x</code>. This can be easily done as</p>
<pre><code>np.array([F(X) for F,X in zip(f,x)])
</code></... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer"><code>np.vectorize</code></a>:</p>
<pre><code>>>> def apply(func, arg):
return func(arg)
>>> vectorized_apply = np.vectorize(apply)
>>> vectorized_apply(f, x)
arra... | python|numpy | 1 |
358,706 | 68,362,799 | Check if values are inside a specific area around a predefined linear function | <p>My research on solving my issue was unfortunately unsuccessful and I hope you can help me. I have defined the following linear function for a straight line</p>
<pre><code>x = [298358.3258395831, 298401.1779180078]
y = [5625243.628060675, 5625347.074197255]
m, b = np.polyfit(x, y, 1)
</code></pre>
<p>and I want to ch... | <p>For a line given by the equation <code>ax + by + c = 0</code>, the distance from a point <code>A = (x_a,y_a)</code> to this line is given by the following formula :</p>
<pre><code>dist = np.abs(a * x_a + b * y_a + c) / np.sqrt(a**2 + b**2)
</code></pre>
<p>Source <a href="https://en.wikipedia.org/wiki/Distance_from_... | python|pandas|numpy | 2 |
358,707 | 68,131,940 | ResourceExhaustedError: OOM when allocating tensor with shape[32,512,64,64] GPU Tesla P4 | <p>I'm trying to run a Resnet50 model of the Keras API and use transfer learning for classification in the google cloud platform servers but it gives me the following error:</p>
<pre><code>ResourceExhaustedError: OOM when allocating tensor with shape [32,512,64,64] and type float on / job: localhost / replica: 0 / task... | <p>Posting this <code>Community Wiki</code> for better visibility.</p>
<p><code>OOM</code> as <code>Out of Memory</code> means that your GPU (<a href="https://images.nvidia.com/content/pdf/tesla/184457-Tesla-P4-Datasheet-NV-Final-Letter-Web.pdf" rel="nofollow noreferrer">Tesla P4</a> in your case) runs out of memory an... | python|tensorflow|keras|google-cloud-platform|gpu | 1 |
358,708 | 68,147,226 | Operand type error while computing returns | <pre><code>TypeError: unsupported operand type(s) for /: 'str' and 'str'
</code></pre>
<p>So this code has been written in my Finance class and is basically importing financial stock data given macroeconomic conditions. The problem lies with the variable "macro_etf_df_mom" for some reason the computation of... | <p>You can inspect the dataframe data types using</p>
<pre><code>print(macro_etf_df.dtypes)
</code></pre>
<p>and make sure that you are using math on numbers, not strings. If you see that your dataframe has the type 'objects' then try converting the column to integer. See the toy code below that starts with all value... | python|pandas|string|typeerror|operands | 0 |
358,709 | 68,300,268 | Parallel Select's to Postgresql in Python | <p>Hi we were trying to parallelize a huge select by chopping it to smaller selects. The dataset had a "segment" column and for this reason we used it as a way to partition the select. Our target was a PosgreSQL database. Unfortunately we did not observe a performance benefit, in other words performance incre... | <p>After some tests with <code>psycopg3</code> and <code>asyncpg</code> I settled on the <a href="https://github.com/sfu-db/connector-x" rel="nofollow noreferrer">connector-x</a> library.
Having a PostgreSQL table with three columns (time:timestamp, variable:text and value:double) and 3 million rows, the following code... | python|pandas|postgresql|performance|psycopg2 | 1 |
358,710 | 68,149,097 | Truth value of a Series is ambiguous. Use a.empty(), a.bool(), a.item(), a.any() or a,all() | <p>I'm trying to write a code that takes certain (optional) inputs from a .csv file and outputs based on which criteria (inputs) have been given and which have not. I managed to get the code to take optional inputs but I want the program to take certain outputs from certain rows of the file (for example, variable w is ... | <pre><code>df.iloc[[1,4],[1,11]]
</code></pre>
<p>and other such statements return a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html" rel="nofollow noreferrer"><code>pd.series</code></a>, not a Boolean.</p>
<p>In order to evaluate those in an If statement, you have to reduce these... | python|pandas|numpy|csv | 0 |
358,711 | 68,108,245 | How to sample a dataframe using a dataframe as weights with pandas | <p>I want to sample rows from each columns of a dataframe according to a dataframe of weights.
All columns of the dataframe of weights sum to 1.</p>
<pre><code>A=pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]]).transpose()
w=pd.DataFrame([[0.2,0.5,0.3],[0.1,0.3,0.6],[0.4,0.5,0.1]])
sampled_data = A.sample(n=10, replace=True, we... | <p>It sounds like you want independent samples from each column. If so, I think this does what you want:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
A=pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]]).transpose()
w=pd.DataFrame([[0.2,0.5,0.3],[0.1,0.3,0.6],[0.4,0.5,0.1]]).transpose()
L=[]
for i in [0,... | python|pandas|numpy|random|sample-data | 0 |
358,712 | 68,381,733 | Error module 'keras.optimizers' has no attribute 'RMSprop' | <p>I am running this code below and it returned an error AttributeError: module 'keras.optimizers' has no attribute 'RMSprop'. I download tensorflow using <code>pip install tensorflow</code>.</p>
<pre><code>from keras import layers
from keras import models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3)... | <p>As you said, you installed tensorflow (which includes keras) via <code>pip install tensorflow</code>, and not keras directly. Installing keras via <code>pip install keras</code> is not recommended anymore (see also the instructions <a href="https://github.com/keras-team/keras#installation" rel="noreferrer">here</a>)... | python|tensorflow|keras | 17 |
358,713 | 68,330,318 | Bar chart plotting issue: TypeError: 'AxesSubplot' object is not iterable | <p>Below shown is the categorical data detail for the bar chart, which is from a specific <code>DataFrame</code> column i.e. <code>coast</code></p>
<pre><code>import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
IN: data['coast'].dtypes
OUT:
CategoricalDtype(categories=[0, 1], ordered=False... | <p>As @Henry Ecker commented, you should be iterating over ax.patches. The pandas plot function is returning the axis not the patches/rectangles.</p>
<p><a href="https://i.stack.imgur.com/wmT10.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wmT10.png" alt="enter image description here" /></a></p>
<p... | python|pandas|numpy|matplotlib|seaborn | 1 |
358,714 | 318,390 | Running numpy from cygwin | <p>I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. </p>
<p>This all works great when I run the Python (command line) tool that comes with Python.</p>
<p>However, if I run cygwin and then run Python from within, it cannot find the numpy package.</p>
<p>Wh... | <p>Cygwin comes with its own version of Python, so it's likely that you have two Python installs on your system; one that installed under Windows and one which came with Cygwin.</p>
<p>To test this, try opening a bash prompt in Cygwin and typing <code>which python</code> to see where the Python executable is located. ... | python|numpy | 4 |
358,715 | 59,425,502 | get the index along the axes where the maximum value happens | <p>I am using python and numpy for some data analysis. So, say I have the following segment:</p>
<pre><code>import numpy as np
x = np.random.rand(2, 2, 2)
</code></pre>
<p>resulting in:</p>
<pre><code>array([[[0.7213753 , 0.89782739],
[0.10375189, 0.02501165]],
[[0.732744 , 0.17957702],
[0.85... | <pre class="lang-py prettyprint-override"><code>>>> x.argmax(axis=0)
array([[1, 0],
[1, 1]])
</code></pre> | python|numpy | 1 |
358,716 | 59,403,157 | Python/Pandas - Adding a hourly column with floats (ex 3.30) to time column (ex 7:00am) | <p>I have a dataset with two columns that I want to combine, one has floats which represent hours/mins, and the other has a start time such as 7:00am. I also pulled the data from regular expressions, so the hours column has a tab space indicator such as \t:</p>
<pre><code>Hours - Start Time
\t3.30 7:00am
\t1.0 ... | <p>Try this:</p>
<pre><code>import dateutil
import pandas as pd
df['Hours'] = df.Hours.replace(r'.*(\d+)\.(\d+)', r'\1:\2', regex=True)
df['New Time'] = df.apply(lambda x: dateutil.parser.parse(x['Start Time']) + datetime.timedelta(hours=int(x.Hours.split(':')[0]), minutes=int(x.Hours.split(':')[1])), axis=1)
df['New ... | python|pandas|numpy|time | 1 |
358,717 | 59,155,904 | Fill all occurrences of a value in a pandas dataframe with a different random number | <p>I have a pandas dataframe that is like this:</p>
<pre><code>Col1 Col2 Col3
0 -1 0
-1 1 1
0 0 1
</code></pre>
<p>and I would like to replace all the occurrences of the value -1 with a random number, generated according to a uniform distribution.
I have tried to use the replace... | <p>First add parameter <code>size</code> to <a href="https://docs.scipy.org/doc/numpy-1.14.1/reference/generated/numpy.random.uniform.html" rel="nofollow noreferrer"><code>numpy.random.uniform</code></a> and then replace values with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mas... | pandas|random|replace | 1 |
358,718 | 59,433,147 | Mapping a function to a dataframe | <p>I was trying to apply a function to a dataframe in pandas. I am trying to take two columns as positional arguments and map a function to it. Below is the code I tried.
Code:</p>
<pre><code>df_a=pd.read_csv('5_a.csv')
def y_pred(x):
if x<.5:
return 0
else:
return 1
df_a['y_pred']=df_a['pro... | <p>The apply function take each column one by one, run it through the function and return an transformed column. Here are more documentation on it <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">pandas documentation</a>.
Your setup would be bett... | python|pandas | 1 |
358,719 | 59,377,797 | np.where with datetimes producing Unix timestamp | <p>I have a dataframe with a column that has time stamp data with some nulls. I am trying to replace the nulls with the earliest date in the column using np.where.</p>
<p>The dataframe looks like this:</p>
<pre><code>index date
1 2019-06-30 22:40:25.799000+00:00
2 2019-06-30 22:40:25.799000+00:00
3 ... | <p>numpy has a bias toward treating array's elements as floats. It saw NaN and Timestamp are both representable as floats so it converts <code>df['date']</code> to float.</p>
<p>You can use <code>fillna</code> instead:</p>
<pre><code>df['date'].fillna(mini, inplace=True)
</code></pre> | python|pandas | 2 |
358,720 | 59,153,015 | Dynamic substitution of column headers in a pandas dataframe | <p>I have a dataframe like this:</p>
<pre><code>example_df =
country id metric_name metric_value account_id
US 1 clicks 111 000
UK 2 clicks 222 000
DE 3 clicks 333 000
RU 4 clicks 444 000
</code></pre>
<p>And a variable w... | <p>I suggest create dictionary with dict comprehension with <code>split</code> and <code>enumerate</code> and then <code>rename</code> columns by it:</p>
<pre><code>breakdowns = 'country'
d = {c: 'metric_key_{}'.format(i) for i, c in enumerate(breakdowns.split(','), 1)}
print (d)
{'country': 'metric_key_1'}
df = df.r... | python|pandas|list | 2 |
358,721 | 59,356,372 | Pandas compare multiple columns to a specific column in a dataframe | <p>I have a data frame like this:</p>
<pre><code>Product_ID Store_1_qty Store_2_qty Store_3_qty
A 10 20 10
B 10 10 10
C 10 10 20
</code></pre>
<p>I want to add one more column which says 'true' or 'false' if column Store_2_qty, Store_3_q... | <p>If <code>Product_ID</code> is column use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a>, also you can compare all columns with first <code>Store</code> column:</p>
<pre><code>result['match'] = (result.iloc[:, 1:].e... | python|pandas | 2 |
358,722 | 59,198,314 | How do I pass multiple column names as val_vars using melt? | <p>I have a large data frame (367 rows × 342 columns) where multiple columns have the same prefix in their name. I am trying to make our code easier to use. </p>
<p>Current code:</p>
<pre><code> value_vars = "'Intensity 01_1',
'Intensity 01_2',
'Intensity 01_3',
'Intensity 03_1',
'Intensity 03_2... | <p>Create list of columns names with <code>or</code> for chain conditions:</p>
<pre><code>alvarlist = [col for col in protstack if
('Intensity' in col) or ('iBAQ' in col) or ('intensity' in col)]
</code></pre>
<p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.S... | python|pandas|melt | 2 |
358,723 | 59,217,874 | PyTorch - to NumPy yields unsized object? | <p>Converting a PyTorch tensor to NumPy I get </p>
<pre><code>print(nn_result.shape)
# (2433, 2)
np_result = torch.argmax(nn_result).numpy()
type(np_result)
# <type 'numpy.ndarray'>
print(len(np_result))
TypeError: len() of unsized object
</code></pre>
<p>Why? I thought per documentation the <code>numpy()</code... | <p>Perhaps you'd want to use <code>torch.argmax(nn_result, dim=1)</code> ? Since <code>dim</code> defaults to 0, it returns just a single number constructed as a tensor. Let me illustrate with the below example:</p>
<pre class="lang-py prettyprint-override"><code>>>> x = np.array(1)
>>> x.shape
()
&g... | numpy|pytorch|numpy-ndarray | 1 |
358,724 | 59,262,869 | Kernel Constraint usage in Tensorflow v1.14 | <p>I am implementing a custom dense layer with weights of dimension <code>12x12</code> in which not all the neurons from one layer are connected to another layer. So I have defined a projection matrix like below:</p>
<pre class="lang-py prettyprint-override"><code>projection_matrix = np.zeros((12, 12))
connections = [... | <p>The answer to your question is: no. </p>
<p>This parameter applies a projection to your kernel (or bias) after the update performed by an Optimizer. It is used when you want, for example, your variable to belong to a given sub-domain. In this case, after the update performed by the optimizer, the variable is reproj... | python|python-3.x|tensorflow|machine-learning|deep-learning | 0 |
358,725 | 59,190,225 | Checking if value exists in any of two columns with pandas | <p>I am new to pandas.</p>
<p>I am building a dataframe with <code>True</code> and <code>False</code> values using <code>.isin()</code> method.</p>
<p>There are 7 columns in my dataframe and I check if value exists in each column compared to the column on the left. It works out fine using <code>.isin()</code> method.... | <p>If want boolean DataFrame in output simplier is compare by value without <code>isin</code>:</p>
<pre><code>#if 1 is string use '1'
#df1 = df[['A','B']].eq('1')
df1 = df[['A','B']].eq(1)
df1 = (df[['A','B']] == 1)
</code></pre>
<p>With <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataF... | python|pandas | 7 |
358,726 | 59,300,405 | pandas: How to merge multiple dataframes with same column names on one column? | <p>I have N dataframes:</p>
<pre><code>df1:
time data
1.0 a1
2.0 b1
3.0 c1
df2:
time data
1.0 a2
2.0 b2
3.0 c2
df3:
time data
1.0 a3
2.0 b3
3.0 c3
</code></pre>
<p>I want to merge all of them on id, thus getting</p>
<pre><code>time data1 data2 data3
1.0 a1 a2 a3
2.0 b... | <p>One idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> for list of <code>DataFrame</code>s - only necessary create index by <code>id</code> for each <code>DaatFrame</code>. Also for avoid duplicated columns names is add... | python|pandas | 3 |
358,727 | 59,045,826 | Replacing Outliers with median in pandas | <p>I trying to do something with pandas.....</p>
<p>I finished separating outlier from my dataframe, but I don't know how to set my outliers age to median...
Can I get some help?</p>
<p>Here's my code</p>
<pre><code>users = pd.read_table('user.txt', sep='|', index_col='user_id')
print(users)
</code></pre>
<pre><cod... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="nofollow noreferrer"><code>Series.between</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<... | python|pandas|dataframe|outliers | 1 |
358,728 | 59,290,016 | Python “for” problem - Can only tuple-index with a MultiIndex | <p>I wanna take array C2, size N,1, and make a array B, size N-1,1.</p>
<p>B[0] = C2[1]</p>
<p>B[1] = C2[2]</p>
<p>and so on. My code is:</p>
<pre><code>import numpy as np
import pandas as pd
fields = "B:D"
data = pd.read_excel(r'C:\Users\file.xlsx', "Sheet2", usecols=fields)
N = 2
# Covariance calculation
C1 = ... | <p>First, are you sure you need to be using numpy arrays? This seems like a job for python lists. </p>
<p>Next, what do you mean to be doing with <code>for i in B:</code>? what type is i?</p>
<p>In this case, iterating over B is going to set <code>i</code> to <code>[0.]</code>, and you can now see that the next line ... | python|arrays|pandas | 1 |
358,729 | 59,191,113 | ,Numpy how to extend strip numbers from certain position? | <p>I want use python numpy to extend multiple number from certain point say the number "1" at [3,2].
suppose I key in "Right3" then, the right 3 element (couting from [3,2]) self plus 10. and if I key in "Left1" then, the rightest element become 20. hope you can understand me.
thank you</p>
<pre class="lang-py prettyp... | <p>I don't know what exactly you mean by key. You can check this out:</p>
<pre><code>zero = np.zeros((8,12))
current_pos = (6, 2)
def right(steps, incr = 10):
global zero, current_pos
new_pos = (current_pos[0], current_pos[1] + steps)
zero[current_pos[0],current_pos[1]+1 : new_pos[1]+1] += incr
curren... | python|numpy | 1 |
358,730 | 59,150,004 | Python Dataframe: Dropping duplicates base on certain conditions | <p>Dataframe with duplicate Shop IDs where some Shop IDs occurred twice and some occurred thrice:<br>
I only want to keep unique Shop IDs base on the shortest Shop Distance assigned to its Area.<br></p>
<pre><code> Area Shop Name Shop Distance Shop ID
0 AAA Ly 86 5d87790c46a77300
1 ... | <p>Try to first sort the dataframe based on distance, then drop the duplicate shops.</p>
<pre><code>df = shops_df.sort_values('Distance')
df = df[~df['Shop ID'].duplicated()] # The tilda (~) inverts the boolean mask.
</code></pre>
<p>Or just as one chained expression (per comment from @chmielcode).</p>
<pre><code>d... | python|pandas|dataframe|drop-duplicates | 4 |
358,731 | 59,332,030 | Populate df row value based on column header | <p>Appreciate any help. Basically, I have a poor data set and am trying to make it more useful. </p>
<p>Below is a representation </p>
<pre><code>df = pd.DataFrame({'State': ("Texas","California","Florida"),
'Q1 Computer Sales': (100,200,300),
'Q1 Phone Sales': (400,500,600),
... | <p>IIUC, you can use:</p>
<pre><code>df_a = df.set_index('State')
df_a.columns = pd.MultiIndex.from_arrays(zip(*df_a.columns.str.split(' ', n=1)))
df_a.stack(0).reset_index()
</code></pre>
<p>Output:</p>
<pre><code> State level_1 Backpack Sales Computer Sales Phone Sales
0 Texas Q1 ... | regex|pandas|dataframe | 0 |
358,732 | 59,160,047 | How do you break a dataframe into uneven segments based on the difference between index values exceeding a certain magnitude? | <p>I have done a terrible job of the title, but I don't know how else to phrase it in one sentence. Please bear with me. I'm not even sure this is possible.</p>
<p>I have a pandas dataframe that lists daily percentage changes in the value of an object. The objects are in columns, the percentage changes are in each row... | <p>Updated: </p>
<pre><code>df.reset_index(inplace=True)
# Just in case cast time.
df['DATE'] = pd.to_datetime(df['DATE'])
df['lag'] = df['DATE'] - df['DATE'].shift(1)
idx_gaps = list(df[df['lag'] > pd.Timedelta('5days')].index)
idx_gaps.insert(0, 0)
idx_gaps.append(len(df))
df['chunk_id'] = np.NaN
for i, id... | python|pandas|time-series | 2 |
358,733 | 59,367,692 | ValueError: could not broadcast input array from shape (15,15) into shape (15) | <pre><code>import numpy
HL1_neurons = 15
input_HL1_weights = numpy.random.uniform(low=-0.1, high=0.1,size=(15, HL1_neurons))
output_neurons = 1
HL2_output_weights = numpy.random.uniform(low=-0.1, high=0.1,size=(HL1_neurons, 1))
weights = numpy.array([input_HL1_weights,HL2_output_weights])
</code></pre>
<p>while exect... | <p><code>input_HL1_weights</code> is (15,15) shape. <code>HL2_output_weights</code> is (15,1).</p>
<p>Trying to make an object dtype array from these two, results in this kind of error. If their shapes differed in the first dimensions (e.g. their transposes), the result would be a (2,) object dtype array. If the sh... | python|numpy|neural-network | 0 |
358,734 | 59,057,640 | Python: Count the First Instance of each Unique Value in a Column with Repeating Values | <p>First post here so apologies if this is unclear. I have a pandas dataframe and am trying to return a 1 for the first instance of each unique value in a column, and return a 0 for each repeating value after the first unique instance.</p>
<p>In Excel I've used the below formula but on a larger dataframe it becomes u... | <p>Use the negation of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer">duplicated</a>:</p>
<pre><code>df['unique'] = (~df.ID.duplicated()).astype(int)
print(df)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> ID unique
0 A... | python|pandas|numpy | 0 |
358,735 | 59,359,042 | count specific string in column on a dataframe python | <p>I have a (101×1766) dataframe and I put a sample down. </p>
<pre><code>Index Id Brand1 Brand2 Brand3
0 1 NaN Good Bad
1 2 Bad NaN NaN
2 3 NaN NaN VeryBad
3 4 Good NaN NaN
4 5 NaN Good VeryGood
5 6 VeryBad Good NaN
<... | <p>Let us do two steps : <code>melt</code> + <code>crosstab</code></p>
<pre><code>s=df.melt(['Id','Index'])
yourdf=pd.crosstab(s.variable,s.value)
yourdf
value Bad Good VeryBad VeryGood
variable
Brand1 1 1 1 0
Brand2 0 3 0 0
Brand3 ... | python|string|pandas|dataframe|count | 5 |
358,736 | 59,115,262 | delete pandas dataframe row if every value is equal | <p>If I have a pandas dataframe which has a row containing float values and all the values are equal in the row, how do I delete that row from the dataframe?</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nunique.html" rel="nofollow noreferrer"><code>DataFrame.nunique</code></a> for test number of unique values per rows with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ne.html" rel="nofollow nor... | python|pandas | 1 |
358,737 | 59,439,128 | what does class_mode parameter in Keras image_gen.flow_from_directory() signify? | <pre><code>train_image_gen = image_gen.flow_from_directory('/Users/harshpanwar/Desktop/Folder/train',
target_size=image_shape[:2],
batch_size=batch_size,
class_mode='binary')
</co... | <p><code>class_mode</code>: One of "categorical", "binary", "sparse", "input", or None. Default: "categorical". Determines the type of label arrays that are returned: - "categorical" will be 2D one-hot encoded labels, - "binary" will be 1D binary lab... | tensorflow|image-processing|keras|neural-network|training-data | 17 |
358,738 | 59,136,777 | RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn | <p>When I run the program I get this error:</p>
<blockquote>
<p>RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn</p>
</blockquote>
<p>However I had set <code>gen_y = torch.tensor(gen_y,requires_grad=True)</code>, but this has not helped, gen_y.grad_fn is None. And I also try <cod... | <p>I had the same error, <code>requires_grad = True</code>, did not work. If you want to be able to backward through your first call to .grad (to get gradients for your gradient penalty), you need to give it <code>create_graph=True</code>. I believe the error you mentioned is not the complete error, if your error is:</... | pytorch|gradient|torch|backpropagation|loss-function | 0 |
358,739 | 59,374,748 | Tensorflow js: Error: Error when checking : expected conv2d_13_input to have 4 dimension(s), but got array with shape [100,120,3] | <p>Can anyone explain to me what happened here ?</p>
<p>This is my code:</p>
<pre><code>var model;
async function deploy() {
console.log('Deploying model...');
model = await tf.loadLayersModel('keras model/js_model/model.json');
console.log('model loaded!');
var sample_image = document.getElementB... | <blockquote>
<p>sample_image.reshape([-1, sample_image_height, sample_image_width, 3]);</p>
</blockquote>
<p><code>reshape</code> is not an in-place operator. You need to assign back the result to the variable <code>sample_image</code> or use another variable</p>
<pre><code>const sample_image_reshaped = sample_imag... | python|tensorflow|keras|deep-learning|tensorflow.js | 1 |
358,740 | 59,262,159 | How to change these for loops to numpy operation | <p>The following is my code:</p>
<pre><code>avg = 0
for i in range((masks.shape[0])):
nz = np.count_nonzero(masks[i])
avg += nz
avg /= masks.shape[0]
index = []
for i in range((masks.shape[0])):
if np.count_nonzero(masks[i]) >= 2*avg/3:
index.append(i)
masks = masks[index]
</code></pre>
<p>The ... | <p>The first loop is not necessary <code>np.count_nonzero(masks)</code> on the whole array is the same as summing up the calls on the first dimension. Then, you can pass a tuple as the axis argument to <code>np.count_nonzero</code> (see also <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonz... | python|numpy | 0 |
358,741 | 59,359,123 | Series regex extract producing a dataframe | <p>I am working through a regex task on Dataquest. The following code snippet runs correctly
inside of the Dataquest IDE:</p>
<pre><code>titles = hn["title"]
pattern = r'\[(\w+)\]'
tag_matches = titles.str.extract(pattern)
tag_freq = tag_matches.value_counts()
print(tag_freq, '\n')
</code></pre>
<p>However, on my PC... | <p>From the docs:
<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer">Pandas.Series.str.Extract</a></p>
<p>A pattern with one group will return a Series if expand=False.</p>
<pre><code> >>> s.str.extract(r'[ab](\d)', expand=False)
0... | regex|python-3.x|pandas | 0 |
358,742 | 59,475,127 | Counting the occurence of numpy.array object in a list of numpy.array objects | <p>If I have a list:</p>
<pre><code>a = [np.array([1,1,1]), np.array([1,1,1]), np.array([1,1,1])]
</code></pre>
<p>How to do something like, <code>a.count(np.array([1,1,1])</code>? This throws:</p>
<pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</co... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_equal.html" rel="nofollow noreferrer"><code>np.array_equal</code></a> with <code>sum</code> on generator:</p>
<pre><code>>>> sum(np.array_equal(x, [1,1,1]) for x in a)
3
</code></pre> | python|arrays|list|numpy | 1 |
358,743 | 59,286,779 | Create smaller dataframes from a large dataframe using the index values from a list | <p>I have a list </p>
<pre><code>a = [15, 50 , 75]
</code></pre>
<p>Using the above list I have to create smaller dataframes filtering out rows (the number of rows is defined by the list) on the index from the main dataframe.</p>
<p>let's say my main dataframe is <strong>df</strong>
the dataframes I'd like to have i... | <p>you could modify your code by building dataframes from the main dataframe iteratively cutting out slices from the end of the dataframe.</p>
<pre><code>dfs = [] # this list contains your partitioned dataframes
a = [15, 50 , 75]
for idx in a[::-1]:
dfs.insert(0, df.iloc[idx:])
df = df.iloc[:idx]
dfs.insert(0,... | python|pandas|dataframe | 2 |
358,744 | 59,378,235 | Need a function for pandas dataframe that identifies equal strings and then assigns to new columns | <p>I made a pandas df from parts of 2 others:
Here is the pseudocode for what I want to do.
4-column pandas dataframe, values in all columns are single words.
cols A B C D and I want this: cols A B C D E F
in pseudcode:
(for every s in A;
if s equals any string (not substring) in D;
write Yes to E (new column) els... | <p>For what I understood you can apply a lamda to your DataFrame</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html</a></p>
<p>Anyway I built a small ex... | python-3.x|string|pandas|function | 0 |
358,745 | 59,088,218 | Reading inputs from CSV and using them for different functions | <p>I have a csv file with inputs, which come from users. The first column is the STATISTIC which are functions in my Python code, and the columns afterwards are different input variables for each of those statistics.</p>
<p>I.e. the WEIGHTED_MEAN statistic needs VARIABLE_COLUMN and WEIGHT_VARIABLE.</p>
<p><a href="ht... | <p>I did it with a class like this:</p>
<pre class="lang-py prettyprint-override"><code>Class ExampleClass:
def __init__(self, var1, var2, var3, all variables listed like that...):
self.var1 = var1
etc.
def func1(self):
func1 needs var1 and var3 so I use them by doing self.var1 and se... | python|python-3.x|pandas|pyspark|pyspark-sql | 0 |
358,746 | 59,229,291 | Updating dash datatable using callback function | <p>I have a dash dashboard I built. I would like to add more interactivity. I want to allow users to select an option on a drop down menu and the data shown in my datatable is filtered according to said selection</p>
<p>This is how I have defined my datatable</p>
<pre><code>html.Div([
dash_table.DataTable(
... | <p>I got it working. Here's what I did.</p>
<p>First, I changed these lines:</p>
<pre class="lang-py prettyprint-override"><code>punchstats = [(punch_stats['division'].isin(weight_class))]
punchstats = [(punchstats['sex'].isin(gender))]
</code></pre>
<p>to this:</p>
<pre class="lang-py prettyprint-override"><code>p... | python|pandas|plotly|plotly-dash | 1 |
358,747 | 59,411,185 | Import tensorflow module is slow in tensorflow 2 | <p>Related: <a href="https://stackoverflow.com/questions/45093653/import-tensorflow-contrib-module-is-slow-in-tensorflow-1-2-1">Import TensorFlow contrib module is slow in TensorFlow 1.2.1</a> also: <a href="https://stackoverflow.com/questions/49053434/what-can-cause-the-tensorflow-import-to-be-so-slow">What can cause... | <p>I want to start off by saying that I'm using a 3 Ghz quad core and it does not take me any where near ten seconds to import TensorFlow in Python. Could you elaborate on what environment you're having issues importing it with (i.e. Windows/Mac/Linux in terminal/console/command prompt/Anaconda etc.)?
You didn't speci... | python-3.x|python-import|tensorflow2.0 | 0 |
358,748 | 59,302,365 | What's wrong on my conditions ? Using the np.where statement to flag my pandas dataframes | <p>The function i am using is keep giving the red filter condition where not applied.</p>
<p>Here the function i am using:</p>
<pre><code>tolerance = 5
def rag(data):
red_filter = ((data.SHIPMENT_MOT_x == 'VESSEL') & \
((data.latedeliverydate + pd.to_timedelta(tolerance,unit='D')) &l... | <p>Here is the solution if you guys are interested.
<code>np.where</code> is useful but would not recommend when there are multiple conditions</p>
<pre><code>def pmm_rag(data):
if ((data.MOT== 'VESSEL') & ((data.m0p + pd.to_timedelta(tolerance,unit='D')) < data.m6p)) | ((data.SHIPMENT_MOT_x == 'AIR') &... | python|python-3.x|pandas | 0 |
358,749 | 59,136,579 | Subtracting Date-time objects in Pandas | <p>I have two columns in my dataframe with datetime64[ns] values. I would like to subtract the end-date from my start-date and place that value of a new column? How do I do that?</p>
<p>Here is an example of my data:</p>
<p><strong>StartedDate(Column1)</strong></p>
<p>2018-09-02 02:54:39</p>
<p>2018-09-02 15:14:31<... | <p>Like @Dan mentioned in comments is not necessary add starting datetimes, because subtracting.</p>
<p>So convert timedeltas with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.days.html" rel="nofollow noreferrer"><code>Series.dt.days</code></a> and add <a href="http://pandas.pyda... | pandas|dataframe|datetime|type-conversion | 2 |
358,750 | 14,075,855 | groupby functions to get subsequent value | <p>In my data I have stock volumes for order sequence and times, I need to go through each part of the order and find when it ends, by grabbing the next part of the chains time.</p>
<p>I am just starting in python and I would do this by subsetting each stock into its own pool, then adding then do another loop to find ... | <pre><code>In [24]: df
Out[24]:
sequence time
0 a 1
1 b 1
2 a 3
3 a 5
4 b 2
In [25]: df['nexttime'] = df.groupby('sequence').time.shift(-1).fillna(999)
In [26]: df
Out[26]:
sequence time nexttime
0 a 1 3
1 b 1 2
2 ... | group-by|pandas | 4 |
358,751 | 14,104,844 | Broadcasting across an indexed array Numpy | <p>I'm looking for a Numpy (i.e. hopefully faster) way to perform the following:</p>
<pre><code>import numpy as np
x = np.array([1,2,3,4,5],dtype=np.double)
arr = [[1,2],[0,4,3],[1,4,0],[0,3,4],[1,4]] ... | <p>I've come up with a solution that is adequate enough for my application using Numpy masked arrays. In my application, the <code>arr</code> list is not "too ragged" (i.e. the max length of any interior list is not extremely different from the min length of any interior list). Therefore, I start by padding <code>arr... | python|numpy|array-broadcasting | 0 |
358,752 | 13,978,789 | How to multiply a given row `i` or column `j` with a scalar? | <pre><code>import numpy as np
M = np.matrix([
[-1,-2,-3],
[-4,-5,-6]
])
print(M)
</code></pre>
<ol>
<li>How to multiply a given row <code>i</code> or column <code>j</code> with a scalar?</li>
<li>How to acces a given column or row as a list?</li>
<li>How to set a given column or row, given a list... | <p>To multiply a particular column:</p>
<pre><code>M[:,colnumber] *= scalar
</code></pre>
<p>Or a row:</p>
<pre><code>M[rownumber,:] *= scalar
</code></pre>
<p>And of course, accessing them as an iterable is the same thing:</p>
<pre><code>col_1 = M[:,1]
</code></pre>
<p>Although, that gives you a new matrix, not ... | python|numpy | 7 |
358,753 | 14,154,456 | numpy.concatenate multidimensional arrays | <p>I'm searching for an algorithm to merge a given number of multidimensional arrays (each of the same shape) to a given proportion (x,y,z).</p>
<p>For example 4 arrays with the shape (128,128,128) and the proportion (1,1,4) to an array of the shape (128,128,512).
Or 2 arrays with the shape (64,64,64) and the proporti... | <p>If your proportion is always one-dimensional (i.e. concatenate in one dimension only), you can use this:</p>
<pre><code>arrays = [...]
proportion = (1,1,4)
np.concatenate(arrays, axis=next(i for i,p in enumerate(proportion) if p>1))
</code></pre>
<p>Otherwise you have to explain what to do with <code>proportio... | python|arrays|multidimensional-array|numpy | 1 |
358,754 | 13,930,367 | Interpolating time series in Pandas using Cubic spline | <p>I would like to fill gaps in a column in my DataFrame using a cubic spline. If I were to export to a list then I could use the numpy's <code>interp1d</code> function and apply this to the missing values.</p>
<p>Is there a way to use this function inside pandas?</p> | <p>Most numpy/scipy function require the arguments only to be "array_like", <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="noreferrer"><code>iterp1d</code></a> is no exception. Fortunately both Series and DataFrame are "array_like" so we don't need to leave pandas:</p... | python|pandas | 8 |
358,755 | 44,960,896 | Python: Matplotlib imshow shift xlabel numbers | <p>Is it possible to shift the x and y axis label numbers for example +2 ? For example i have this image created, but i want that the label numbers begin with 2:</p>
<p><a href="https://i.stack.imgur.com/LeHjF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LeHjF.png" alt="enter image description he... | <p>You can use the <code>extent</code> argument of <code>imshow</code> to set the scale of the plot. To have it scale from 2 to 5 use</p>
<pre><code>plt.imshow(jacaardMatrix, extent=[2,5,2,5])
</code></pre>
<p>where the first two numbers denote the x range and the second two numbers the y range.</p> | python|numpy|matplotlib|scipy | 6 |
358,756 | 44,857,373 | Find number of non-zero elements in a tensor along an aixs | <p>I want to find the number of non-zero elements in a tensor along a particular axis. Is there any PyTorch function which can do this?</p>
<p>I tried to use the <a href="http://pytorch.org/docs/master/torch.html?highlight=nonzero#torch.nonzero" rel="nofollow noreferrer">nonzero()</a> method in PyTorch.</p>
<pre><cod... | <p>Meaning of the error message - <code>TypeError: Type Variable doesn't implement stateless method nonzero</code> is, we cannot use <code>torch.nonzero()</code> on <code>autograd.Variable</code> but only on simple tensors. Also it should be noted that, tensors are stateless while the Variables are stateful.</p> | python|deep-learning|pytorch | 3 |
358,757 | 44,827,002 | looking for value in a panda dataframe python | <p>I have a data frame with three columns, </p>
<pre><code> A B C
One 2 1
Two 3 0.5
Three 6 7
</code></pre>
<p>I have a list which represents the second and third columns:
[(3,0.5),(6,7),(2,1)]</p>
<p>based on that list I want to retrieve the value in the first columns ... | <p>You can set columns <code>B</code> and <code>C</code> as multi index and then query it with the list:</p>
<pre><code>idx = [(3,0.5),(6,7),(2,1)]
df.set_index(['B', 'C']).A.loc[idx].values
# array(['Two', 'Three', 'One'], dtype=object)
</code></pre>
<p>If you need a list as result, use <code>tolist</code> as @Jezra... | python|pandas|dataframe | 3 |
358,758 | 45,202,841 | Aggregate column values in pandas GroupBy as a dict | <p>This is the question I had during the interview in the past. </p>
<p>We have the input data having the following columns: </p>
<p>language, product id, shelf id, rank</p>
<p>For instance, the input would have the following format</p>
<pre><code>English, 742005, 4560, 10.2
English, 6000075389352, 4560, 49
French... | <p><strong>Setup</strong></p>
<pre><code>df = pd.read_csv('file.csv', header=None)
df.columns = ['Lang', 'product_id', 'shelf_id', 'rank_id']
df
Lang product_id shelf_id rank_id
0 English 742005 4560 10.2
1 English 6000075389352 4560 49.0
2 French 899883993 4... | python|pandas|dataframe|dictionary|pandas-groupby | 5 |
358,759 | 45,051,627 | How to get weights format from TensorFlow .pb model? | <p>I want to reorganize the nodes of tensorflow .pb model,so I first get NodeDef from GraphDef, and get attr use NodeDef.attr().for the node of "Conv2D".
I can get parameters such as strides,padding,data_format,use_cudnn_on_gpu from attr, but cann't get the weights format parameters.
The language I use is c++.
... | <p><code>Conv2D</code> has two inputs: the first one is data and the second one is <code>filter</code> (or weights), so you can simply check the format of the second input of <code>Conv2D</code>. If you are using C++, you can try this:</p>
<pre><code># Assuming inputs: conv2d_node, node_map.
filter_node_name = conv2d_... | c++|tensorflow|model | 4 |
358,760 | 45,089,650 | filter dataframe rows based on length of column values | <p>I have a pandas dataframe as follows:</p>
<pre><code>df = pd.DataFrame([ [1,2], [np.NaN,1], ['test string1', 5]], columns=['A','B'] )
df
A B
0 1 2
1 NaN 1
2 test string1 5
</code></pre>
<p>I am using pandas 0.20. What is the most efficient way to remove any rows where 'any... | <p>If based on column <code>A</code></p>
<pre><code>In [865]: df[~(df.A.str.len() > 10)]
Out[865]:
A B
0 1 2
1 NaN 1
</code></pre>
<p>If based on all columns</p>
<pre><code>In [866]: df[~df.applymap(lambda x: len(str(x)) > 10).any(axis=1)]
Out[866]:
A B
0 1 2
1 NaN 1
</code></pre> | pandas | 30 |
358,761 | 45,106,195 | Pandas rolling mean don't change numbers to NaN in DataFrame | <p>I'm working with a pandas DataFrame which looks like this: </p>
<p>(**N.B - the offset is set as the index of the DataFrame)</p>
<pre><code>offset X Y Z
0 -0.140137 -1.924316 -0.426758
10 -2.789123 -1.111212 -0.416016
20 -0.133789 -1.923828 -4.408691
30 -0.101112 ... | <p>You can fill with the original df:</p>
<pre><code>df.rolling(center=False, window=5).mean().fillna(df)
Out:
X Y Z
offset
0 -0.140137 -1.924316 -0.426758
10 -2.789123 -1.111212 -0.416016
20 -0.133789 -1.923828 -4.408691
30 -0.101112 -1.45... | python-3.x|pandas|dataframe|moving-average | 6 |
358,762 | 45,212,562 | pandas: how to pivot a table with defined levels | <p>My case is slightly different to what I have found so far online. I would like to pivot a pandas dataframe with a specific levels in the header. The pivot_table function requires values to be numeric, and the pandas.pivot function does not seem to do exactly what I want.</p>
<p>This is the starting code.</p>
<pre>... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> for resha... | python|pandas|pivot | 1 |
358,763 | 45,129,775 | Repeat array and stops at specific position w/ numpy | <p>I have to write a cyclic functie <code>cyclisch(N)</code> that constructs a Numpy-row with length N with content<code>[1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...]</code>.</p>
<p>This is de code I'm having now.</p>
<pre><code>import numpy as np
import math
def cyclisch(N):
r = np.linspace(float(1.0), float(3.0), ... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html" rel="nofollow noreferrer">np.resize</a>.</p>
<pre><code>>>> np.resize([1., 2., 3.], 5)
array([ 1., 2., 3., 1., 2.])
</code></pre>
<p>This works since:</p>
<blockquote>
<p>If the new array is larger than the ori... | python|python-3.x|numpy | 3 |
358,764 | 45,022,315 | Tensorflow ValueError: Too many vaues to unpack (expected 2) | <p>I have looked this up on Reddit, Stack Overflow, tech forums, documentation, GitHub issues etc etc and still can't solve this issue.</p>
<p>For reference, I am using <code>Python 3 TensorFlow</code> on Windows 10, 64 Bit.</p>
<p>I am trying to use my own dataset (300 pics of cats, 512x512, .png format) in <code>Te... | <p>You are yielding your results in an incorrect way:</p>
<pre><code>yield(images[i:i+batch_size]) #,labels_list[i:i+batch_size])
</code></pre>
<p>which gives you one value that is yielded, but when you call you method you are expecting two values yielded:</p>
<pre><code>images,labal = create_batches(10)
</code></pr... | python|tensorflow|runtime-error|generator|mnist | 2 |
358,765 | 45,093,113 | What does it mean by the shape (3,) of a Tensor Placeholder? | <p>I'm new to Tensorflow, and sorry if I'm asking a silly question.
Here is my code. And it always give an error: </p>
<pre class="lang-none prettyprint-override"><code>ValueError: Cannot feed value of shape (3,) for Tensor
'Placeholder:0', which has shape '(3, ?)'
</code></pre>
<p>My problem is what does it mean b... | <p>Before starting any framework, it is very beneficial to read the basics. TF already has them. It will take less than an hour to read and will save you days. Enough of the rant.</p>
<p><a href="https://www.tensorflow.org/programmers_guide/dims_types" rel="nofollow noreferrer">Reading about the terminology</a> you ca... | python|tensorflow | 1 |
358,766 | 44,825,263 | Tensorflow and Numpy mismatch data format | <p>Whit this code:</p>
<pre><code>import tensorflow as tf
w = tf.Variable(tf.random_normal( [ 3 , 3 , 1 , 1 ], stddev = 0.01 ))
if __name__ == '__main__':
initVar = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(initVar)
print w.eval()
</code></pre>
<p>Because... | <p>You need</p>
<pre><code>w = tf.Variable(tf.random_normal([1, 1, 3, 3], stddev=0.01))
</code></pre>
<p>and finally, you can use</p>
<pre><code>import tensorflow as tf
import numpy as np
mask = np.ones((1, 1, 3, 3), dtype=np.float32)
mask[:, :, 1, 2] = 0.
mask[:, :, 2, :] = 0.
print(mask)
weight = tf.get_vari... | python|tensorflow|deep-learning|tensor | 2 |
358,767 | 45,050,531 | Python Tflearn machine learning Optimiser, loss and parameters | <p>After fixing my code and prepare my data for training I've found myself in front of 2 question.</p>
<p><strong>Background</strong>:
I have data made of date (one entry per minute) for the first column and congestion (value, between 0 and 200) for the 2nd. My goal is to feed it to my neural network and so be able t... | <p>What you are trying to do is called time series prediction (given data at time <em>t-n, t-(n+1) ... t-1</em>: predict the state at time <em>t</em>) and is generally a task for a recurrent neural network. <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/" rel="nofollow noreferrer">Here</a> is the great... | python|machine-learning|tensorflow|tflearn | 1 |
358,768 | 45,109,305 | Can't learn parameters of tf.contrib.distributions.MultivariateNormalDiag via optimization | <p>Working example:</p>
<pre><code>import numpy as np
import tensorflow as tf
## construct data
np.random.seed(723888)
N,P = 50,3 # number and dimensionality of observations
Xbase = np.random.multivariate_normal(mean=np.zeros((P,)), cov=np.eye(P), size=N)
## construct model
X = tf.placeholder(dtype=tf.float32, ... | <p>I'm still looking into why this is failing, but for a short-term fix, does making the following change work?</p>
<pre><code>xLogProbs = xDist.log_prob(X, name='xLogProbs')
loss = -tf.reduce_mean(xLogProbs, name='loss')
</code></pre>
<p>Note: this is actually preferable to <code>tf.log(xProbs)</code> because i... | tensorflow | 0 |
358,769 | 45,228,872 | Dynamically reshape the dataframe in pandas | <p>I am having a dataframe which has 4 columns and 4 rows. I need to reshape it into 2 columns and 4 rows. The 2 new columns are result of addition of values of col1 + col3 and col2 +col4. I do not wish to create any other memory object for it.</p>
<p>I am trying</p>
<pre><code>df['A','B'] = df['A']+df['C'],df['B']+d... | <p>The dynamic way of summing two columns at a time is to use groupby:</p>
<pre><code>df.groupby(np.arange(len(df.columns)) % 2, axis=1).sum()
Out[11]:
0 1
0 2 4
1 10 12
2 18 20
3 26 28
</code></pre>
<p>You can use rename afterwards if you want to change column names but that would require a logic.</... | python|python-3.x|pandas|dataframe | 3 |
358,770 | 44,904,608 | Navigate to a cell in a DataFrame using a set of criteria | <p>I have a csv table like so:</p>
<pre><code>a, b, c, d
value, value, value, value
value, value, value, value
</code></pre>
<p>which I'm loading into a <code>DataFrame</code>. I also have a dictionary that looks like this:</p>
<pre><code>data = {'a': some_value, 'b' = some_value, 'c' = some_value}
</code></pre>
<p... | <p>You could convert the data into a dataframe, then use a merge:</p>
<pre><code>data = pd.DataFrame({'a':[1,2,3,4], 'b':[1,2,3,4],'c':[1,2,3,4],'d':[1,2,3,4]})
lookup = {'a':2,'b':2, 'c':2}
lookupdf = pd.DataFrame(lookup, index = [1]) #need the index, as they are all scalar
pd.merge(lookupdf, data)
a b c... | python|pandas | 1 |
358,771 | 45,263,156 | Building Convolutional Neural Network using large images? | <p>I understand reating convolutional nerural network for 32 x 32 x 3 image, but i am planning to use larger image with different pixels. How can I reduce the image size to the required size ? does the pixel reduction impact accuracy in tensor flow ?</p> | <p>Theoretically there is no limit on the size of images being fed into a CNN. The most significant problem with larger image sizes is the increased memory footprint, especially with large batches. Moreover, you would need to use more convolutional layers to down sample the input image. Downsizing an image is a possibi... | python|machine-learning|tensorflow|neural-network|conv-neural-network | 2 |
358,772 | 45,086,435 | Pip error:should upgrade pip, pandas and matplotlib but returns error | <p>I had to uninstall Python 3.6.1 and install 3.5.0 because this is the only version suitable for TensorFlow. I changed my path correctly and after I installed first package (numpy) successfuly this error came up (first two lines). I tried to do as it said and error occurred(below) and also tried to install pandas and... | <p>try: <code>pip3 install pandas matplotlib</code> without the comma. I believe that the error is that if you have something other than a space, pip is looking for a specific version.</p>
<p>see:
<a href="https://stackoverflow.com/questions/9956741/how-to-install-multiple-python-packages-at-once-using-pip">How to in... | python|python-3.x|pandas|pip | 3 |
358,773 | 44,919,437 | create dtype array column in dataframe | <p>How to create 'col new' in dataframe ?</p>
<pre><code> 'col 1' 'col 2' 'col new'
0 a b [a, b]
1 c d [c, d]
2 e f [e, f]
</code></pre>
<p>Thank in advance</p> | <p>You can use <code>list comprehension</code> with convert values to <code>list</code> from <code>tuple</code>s:</p>
<pre><code>df['col new'] = [list(x) for x in zip(df['col 1'],df['col 2'])]
print (df)
col 1 col 2 col new
0 a b [a, b]
1 c d [c, d]
2 e f [e, f]
print (type(df.loc[0, 'co... | pandas | 0 |
358,774 | 44,839,813 | How to put a comma separated value to a numpy cell | <p>I have the georeferenced image with coordinates values like (475224.0, 4186282.0).The dimension of my image is (647, 2180). ie there are 647 columns and 2180 rows. I would like to take the coordinate values into a numpy array with size (647, 2180), so that I will get the coordinates of each pixel as an array. I code... | <p>Assuming your <code>rr.transform*()</code> output is a valid Python <code>tuple</code> I think you are doing this a bit more complicated than it has to be. By default, <code>numpy</code> will handle tuples and lists equal when creating and/or assigning to <code>np.array</code>:s. Thus, a much simpler solution for yo... | python|arrays|numpy|multidimensional-array|rasterio | 1 |
358,775 | 45,166,400 | Initialize transposed numpy array | <p>I want to use the Singular-Value-Decomposition of matrix <code>A</code>.</p>
<p>If possible I would write:</p>
<pre><code>V, S, W.T = np.linalg.svd(A)
</code></pre>
<p>But I can't initialise an array with its transposed.
Now I have two questions:</p>
<ol>
<li><p>As far as I understand the python internals there... | <p>Option 2 takes over 50% more time in my experiment. It's also harder to read. </p>
<p>Option 1 is good, but observe that <code>W</code> will be a view of the array <code>tmp</code>. This should not be a problem unless you do something that makes it one, like <code>tmp[0,0] = 0</code> (which modifies <code>W</code> ... | python|arrays|numpy|initialization | 3 |
358,776 | 45,005,477 | Eliminating redundant numpy rows | <p>If I have an array</p>
<pre><code>arr = [[0,1]
[1,2]
[2,3]
[4,3]
[5,6]
[3,4]
[2,1]
[6,7]]
</code></pre>
<p>how could I eliminate redundant rows where columns values may be swapped? In the example above, the code would reduce the array to</p>
<pre><code>arr = [[0,1]... | <p>Basically you want to <a href="https://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array">Find Unique Rows</a>, and these answers borrow heavily from the top two answers there - but you need to sort the rows first to eliminate different orders.</p>
<p>If you don't care about order of rows at the ... | python|numpy | 2 |
358,777 | 45,271,275 | How to convert daytime to day in python? | <p>I have the following table :</p>
<pre><code>DayTime
1 days 19:55:00
134 days 15:34:00
</code></pre>
<p>How to convert the Daytime to fully day? Which mean the hours will change to day(devide by 24)</p> | <p>You can convert <code>Timedeltas</code> to numerical units of time by dividing by units of <code>Timedelta</code>. For instance,</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'DayTime':['1 days 19:55:00', '134 days 15:34:00']})
df['DayTime'] = pd.to_timedelta(df['DayTime'])
days = df['DayTime'] / pd.Timedel... | python|pandas|datetime|date-formatting|date-conversion | 1 |
358,778 | 44,899,848 | Create a bar plot in pandas with dates on x-axis, one bar for each value in other column | <p>I have the following pandas dataframe:</p>
<pre><code>>>> df
>>> StartDate Port Count
2011-08-10 11:07:10 3128 10
2011-08-10 11:07:40 80 1
2011-08-10 11:07:40 443 1
2011-08-10 11:07:40 3128 10
2011-08-10 11:08:00 443 1
2011-08-10 11:08:00 3128 9
2011-08-10 11:08:2... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> for r... | python|pandas | 1 |
358,779 | 45,178,457 | TypeError when feeding tensorflow placeholder | <p>I am trying to feed a placeholder with following statements:</p>
<pre><code>image = tf.placeholder(tf.int32,shape = (256,256))
image.eval(feed_dict={image, (image_)})
</code></pre>
<p>where image_ is:</p>
<pre><code>array([[ 5, 12, 8, ..., 21, 2, 11],
[ 5, 11, 13, ..., 9, 12, 4],
[ 7, 2, 13, ..... | <p>feed_dict should be a dictionary, so you need to change the line</p>
<pre><code>image.eval(feed_dict={image, (image_)})
</code></pre>
<p>into</p>
<pre><code>image.eval(feed_dict={image:image_})
</code></pre> | python|tensorflow | 1 |
358,780 | 45,225,170 | Image resampling, Memory Error | <p><strong>What I am trying:</strong> I have a 23 by 23 numpy array which I have converted to image. After that I am trying to resample it 5000 times (The new image will have a size of 23*5000 by 23*5000) with nearest neighbor sampling. But I am getting Memory Error. </p>
<p><strong>My code is-</strong></p>
<pre><cod... | <p>Resampling will change the array-size needed to store the newly sampled image.</p>
<p>Assuming you are using a grayscale-image (np.uint8), an image of size (23*5000, 23*5000) will approximately need > 12GB of memory!</p>
<p>There is not much you can do (besides buying more memory), as most image-resizers are assum... | numpy|out-of-memory | 0 |
358,781 | 45,170,920 | Numpy 2d array, select indices satisfying conditions from 2 arrays | <p>I have two 3x3 arrays. One of them indicates if an element is black (let's say 0's - white, 1's black) and another what is the cost of an element. Is there a nice way to get indices of for example all elements that are black and their price is higher than certain value? I know I can use np.where() to select from one... | <p>Following up on the advice of Psidom and rayryeng, I'll add that the output of <code>np.where</code> can be stacked to present a list of indices in the readable "coordinate" notation, as shown below </p>
<pre><code>import numpy as np
a = np.random.randint(0, 2, size=(3,3))
b = np.random.uniform(0, 10, size=(3,3))
p... | python|arrays|numpy | 2 |
358,782 | 44,887,865 | How Can I Change X Labels In Pandas Plot? | <p>I've got an Excel Worksheet that has columns of specific statuses, I need a count of each status and then I need it to be graphed in a bar plot. Example:</p>
<pre><code>Status_1 Status_2 Status_3
Active Abandoned Active
Inactive Abandoned Active
</code></pre>
<p>Currently I've been using the foll... | <p>You can use <a href="http://seaborn.pydata.org/" rel="nofollow noreferrer">seaborn</a>, along with reshaping you dataframe into a <a href="http://vita.had.co.nz/papers/tidy-data.pdf" rel="nofollow noreferrer">tidy form</a> </p>
<pre><code>import seaborn as sns
import pandas as pd
In [26]: df
Out[26]:
Status_1... | python|pandas|matplotlib | 2 |
358,783 | 44,909,134 | How to avoid overfitting on a simple feed forward network | <p>Using the <a href="https://archive.ics.uci.edu/ml/datasets/pima+indians+diabetes" rel="noreferrer">pima indians diabetes dataset</a> I'm trying to build an accurate model using Keras. I've written the following code:</p>
<pre><code># Visualize training history
from keras import callbacks
from keras.layers import Dr... | <p><a href="https://i.stack.imgur.com/aQWHZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aQWHZ.png" alt="enter image description here"></a></p>
<p>The first example gave a validation accuracy > 75% and the second one gave an accuracy of < 65% and if you compare the losses for epochs below 100, its les... | machine-learning|tensorflow|keras|prediction | 16 |
358,784 | 57,268,900 | tf.keras manual device placement | <p>Migrating to the TF2.0 I'm trying to use the <code>tf.keras</code> approach for solving things.
In standard TF, I can use <code>with tf.device(...)</code> to control where ops are.</p>
<p>For example, I might have a model something like</p>
<pre class="lang-py prettyprint-override"><code>
model = tf.keras.Sequenti... | <p>You can use the Keras functional API:</p>
<pre class="lang-py prettyprint-override"><code>inputs = tf.keras.layers.Input(..)
with tf.device("/GPU:0"):
model = tf.keras.layers.Embedding(...)(inputs)
outputs = tf.keras.layers.LSTM(...)(model)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
</code></pre> | python|tensorflow|keras|tensorflow2.0 | 2 |
358,785 | 56,882,796 | Need to convert column values of data frame into separate columns and populate count values for each cell using panda | <p>I have a dataframe </p>
<pre><code>data_frame = pd.DataFrame({'id':[1,2,3,4,5,6],'name':["A","B","C","A","B","A"], 'date':["15/03/2019","16/03/2019","15/03/2019","16/03/2019","16/03/2019","16/03/2019"], "conducted":[1,1,1,1,1,1],"present":[1,1,1,1,1,0]})`
</code></pre>
<hr>
<p>Result</p>
<p><a href="https://i.st... | <p>I guess the values inside the table are a <code>sum()</code> of <code>conducted</code>.</p>
<p>You can use <code>pandas</code> <code>pivot_table()</code>, and fill missing values with zeros <code>fillna(0.0)</code> e.g.:</p>
<pre><code>import numpy as np
table = pd.pivot_table(data_frame, values=['conducted'], ind... | python|pandas|dataframe|machine-learning | 3 |
358,786 | 57,185,573 | create dataframe based on other column's string | <p>I want to create few columns based on one column condition (key word). </p>
<p>Here is the snippet of my DataFrame</p>
<pre><code>Index wave_path
0 wav48/p225/p225_001.wav
. wav48/p227/p227_005.wav.
5
. ......................
. ......................
44040 wav48/p376/p376_265.wav
</code></p... | <p>first split the wave_path and fetch the ID from which is at last
<code>wav48/p225/p225_001.wav</code> --> 225</p>
<p>convert it into int</p>
<p>the use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>pd.merge()</code></a></p>
<pre><c... | python|regex|pandas | 0 |
358,787 | 56,915,230 | How to create Numpy matrix of row index where a certain condition is met? | <p>How do I convert a numpy matrix of values to numpy matrix of row indexes where a certain condition is met?</p>
<p>Let's say </p>
<pre><code>A = array([[ 0., 5., 0.],[ 0., 0., 3.],[ 0., 0., 0.]])
</code></pre>
<p>If there is a condition that I want to use here -- if an element is greater than 0 then replace ... | <p>Using <code>numpy.where</code></p>
<pre><code>np.where(A>0, np.arange(1, A.shape[0]+1)[:, None], A)
</code></pre>
<p></p>
<pre><code>array([[0., 1., 0.],
[0., 0., 2.],
[0., 0., 0.]])
</code></pre>
<hr>
<p>Or you can use arithmetic (won't work if you have values <em>less</em> than <code>0</code>... | numpy|matrix|where-clause | 0 |
358,788 | 56,990,259 | Filter rows which contain a list with continous values in a pandas dataframe | <p>Hi I have a dataframe as shown below:</p>
<pre><code> starttime endtime positions
0 2019-05-16 05:34:26.870 2019-05-16 05:34:41.721 [7, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24...
1 2019-05-16 05:33:56.143 2019-05-16 05:34:10.995 [9, 11, 12, 15, 16... | <p>One way is to use <code>.apply</code> on the column of lists:</p>
<pre><code>df['position'].apply(lambda x: x == list(range(min(x), max(x) + 1)))
</code></pre>
<h3>Minimal Example</h3>
<pre><code># Example input
df = pd.DataFrame({'starttime': list(range(3)),
'endtime': list(range(1, 4)),
... | python|pandas|dataframe|filter | 2 |
358,789 | 57,091,979 | Add one column after groupby function | <p>I want to add a column according to the following condition.</p>
<pre><code> df = pd.DataFrame({'X' : ['M1', 'M1', 'M1', 'M2', 'M2', 'M3', 'M4', 'M4', 'M4', 'M4'], 'Total': [1,2,3,21,15,42,1,2,25,4]})
</code></pre>
<p>Expected Output:</p>
<pre><code>X Total P
M1 1 P1
M1 2 P2
M1 3 P3
M2 21 P1
M2 15 P2
M3 42... | <p>You could <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>GroupBy</code></a> the <code>X</code> column, aggregate with the <code>cumcount</code> and add <code>P</code> as a prefix:</p>
<pre><code>df['P'] = 'P'+df.groupby('X').cumcoun... | python|pandas | 4 |
358,790 | 56,977,605 | How to assign values from 1 column to another with warning in Pandas | <p>I have a pandas DF with 56 columns. 2 of those columns(X and Y) are empty and I would like to duplicate values stored in 2 different columns in the same DF. Right now, I managed to do it, but I get a warning : </p>
<p><em>A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,... | <h3><code>fillna</code></h3>
<p>This is how you should be doing it. Pass a dictionary to <code>fillna</code> specifying what to fill each column with. The keys of the dictionary are mapped to column names. So below, fill the missing values of the <code>'Longitude'</code> column with corresponding values from <code>... | python|pandas | 3 |
358,791 | 57,118,567 | Treat two different sets of columns as a single index and column when pivoting | <p>This is my dataframe:</p>
<pre><code>df = pd.DataFrame({'a': list('xyz'), 'freq_a': [1, 2, 3], 'b': list('axy'), 'freq_b': [3, 4, 5], 'c': list('bzy'), 'freq_c': [5, 6, 7]})
df
a freq_a b freq_b c freq_c
0 x 1 a 3 b 5
1 y 2 x 4 z 6
2 z 3 y 5 y 7... | <p>You can reshape and pivot. From there, just choose which variable you want.</p>
<pre><code>res = (
df.filter(like='freq')
.melt()
.assign(label=df[['a', 'b', 'c']].values.ravel())
.pivot_table(index='label', columns='variable', values='value', aggfunc='first'))
res
variable freq_a freq_b freq_c
label... | python|pandas | 4 |
358,792 | 57,186,376 | Pandas Datetime format conversion error yyyy-mm-dd to yyyy-mm or yyyy/mm as a string | <p>I have a bunch of data in the form of yyyy-mm-dd and I need it in the form of yyyy-mm (string format) so I can plot monthly bar charts</p>
<p>I don't receive any errors but it outputs incorrect data for some values and correct values for other</p>
<pre><code>df = dx
print(df["Collection_End_Date"])
df['Date_Mod... | <p>try using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer">pd.to_datetime()</a> and <code>to_period</code> and <code>strftime</code> to change the format of date</p>
<pre><code>df = pd.DataFrame(
{
"Collection_End_Date": [&qu... | pandas|datetime | 1 |
358,793 | 56,915,246 | convert StyleFrame obj to a pandas dataframe after reading a excel file | <p>Is it possible to extract pandas dataframe from a styleframe object?</p>
<pre><code>sf = StyleFrame.read_excel("my.xlsx", read_style=True)
df = sf.to_dataframe()??
</code></pre>
<p>Panda's read_excel() does not seem to read style from excel so I am thinking of using StyleFrame (which I just found out about), but I... | <p>The underlying dataframe is accessable through the <code>data_df</code> attribute. Keep in mind that each "cell" will contain a <code>StyleFrame.Container</code> object (which wraps the value and the style) but it should behave as expected.</p>
<pre><code>sf = StyleFrame({'a': [1, 2]})
print(type(sf.data_df))
print... | python|pandas|styleframe | 1 |
358,794 | 57,066,180 | How to export 3D vector field from numpy array to *.vtk-file using pyvtk? | <p>I'm struggling to export some 3D vector-arrays (numpy arrays) from python to a *.vtk-file for later use in ParaView.</p>
<p>I have three 3D MR-Velocimetry Images, each of 100x100x200 voxels containing the velocity components in x, y and z. What I want is to export this vector field to a *.vtk-file using the pyvtk-m... | <p>I found a proper solution for my problem, using TVTK instead of PyVTK. So everyone who is interested, a possible workaround could be as follows:</p>
<pre><code>from tvtk.api import tvtk, write_data
# Unpack velocity information
vx=flow['vx']
vy=flow['vy']
vz=flow['vz']
dim=vx.shape
# Generate the grid
xx,yy,zz=n... | python|numpy|vtk | 3 |
358,795 | 56,967,190 | Pandas rolling and ignore rows that have NaN in the count | <h2>Sample data</h2>
<pre><code> id val date
id date
SE0000191827 2018-02-28 SE0000191827 8 2018-02-16
2018-03-31 NaN NaN NaT
2018-04-30 SE0000191827 7 2018-04-20
2018... | <p>You could use a variant of your attempt to build a Series per group (using apply) and just use <code>bfill</code> on that Series to fill the relevant NaN values:</p>
<pre><code>def process(sub):
calc = pd.Series(index=sub.index)
calc.loc[~sub.val.isna()] = sub['val'].dropna().rolling(4).sum().shift(-3)
... | python|pandas | 1 |
358,796 | 57,108,493 | get position of duplicate values from pandas dataframe | <p>I have pandas dataframe 20,000 X 48 as below(not all data given). </p>
<pre><code> 0 1 2 3 4
0 1 0.4784 0.4764 0.4251 0.4915
1 2 0.6180 0.4503 0.3737 0.5377
2 3 0.6735 0.4317 0.6295 0.5470
3 4 0.5294 0.5871 0.5278 0.5544
4 5 0.5555 0.4784 0.5443 0.5259
... | <p>Using <code>df.index.groupby</code>:</p>
<pre><code>df.index.groupby(df['1'])
#or
{k:list(v) for k,v in df.index.groupby(df['1']).items()}
</code></pre>
<p>Output:</p>
<pre><code>{0.4217: [13],
0.4784: [0, 5, 16],
0.5173: [18],
0.5294: [3],
0.5397: [6],
0.541: [15],
0.5555: [4],
0.5763: [8],
0.5841: [19],... | python|python-3.x|pandas|numpy | 5 |
358,797 | 56,960,547 | Pandas copy values from another dataframe into my dataframe | <p>I have 2 dataframes: <code>df_mentions</code> where I have urls, and <code>media</code> where I have info about some journals.
I need to constantly update <code>df_mentions</code> with the info contained in media.</p>
<pre><code>Mentions=['https://www.lemonde.fr/football/article/2019/07/08/coupe-du-monde-feminine-2... | <p>One thing you can do is extract the URL in <code>df_mentions</code> and use it as a key for a merge</p>
<p>Starting data (removed the empty columns in <code>df_mentions</code>):</p>
<pre><code>print(df_mentions)
Mentions Date
0 https://www.lemonde.fr/football/art... | python|pandas|dataframe | 1 |
358,798 | 57,117,039 | Tensorflow Hub: Fine-tune and evaluate | <p>Let's say that I want to fine tune one of the Tensorflow Hub image feature vector modules. The problem arises because in order to fine-tune a module, the following needs to be done:</p>
<pre><code>module = hub.Module("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/3", trainable=True, tags={"train"})
... | <p>With <code>hub.Module</code> for TF1, the situation is as you say: either the training or the inference graph is instantiated, and there is no good way to import both and share variables between them in a single tf.Session. That's informed by the approach used by Estimators and many other training scripts in TF1 (es... | python|tensorflow|tensorflow-hub | 3 |
358,799 | 57,100,827 | NumPY 1.17.0rc1 is available to Python 2.7 | <p>See <a href="https://github.com/numpy/numpy/issues/13911" rel="nofollow noreferrer">this</a> for more details. It looks like there's a bug with pip, or wheel, or something, but my issue is that I just want a work-around while they fix the real problem.</p>
<p>Is there a way around the problem? My work is straggling... | <p>Works for me as designed:</p>
<pre><code>$ mktmpenv -p python2.7
$ pip --version
pip 19.1.1 from /home/phd/.virtualenvs/tmp-f57314fa7b85dd31/local/lib/python2.7/site-packages/pip (python 2.7)
$ pip install scipy
Collecting scipy
Downloading https://files.pythonhosted.org/packages/8e/bd/f0789728ce4a399a5e7bb4af5... | python|numpy|scipy|pip | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.