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 |
|---|---|---|---|---|---|---|
371,900 | 45,454,922 | Python numpy random numbers probability | <pre><code>Python 3.6.1 :: Anaconda custom (64-bit)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mtptlb
print (np.__version__)
1.12.1
print (mtptlb.__version__)
2.0.2
%matplotlib inline
a=np.random.uniform(1,100,1000000)
b=range(1,101)
plt.hist(a)
</code></pre>
<p><a href="https://i.stack... | <p>By default <a href="https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist" rel="noreferrer"><code>matplotlib.pyplot.hist</code></a> uses 10 bins. So all your 1 million values are distributed into 10 bins. For a perfect uniform distribution you would expect that you have 100k occurrences (1 million divide... | python|python-3.x|numpy|matplotlib|random | 7 |
371,901 | 45,677,374 | pandas + pyodbc ODBC SQL type -150 is not yet supported | <p>I know there is many topics on this but i think this is much specific.
I get the current code for audit purpose:</p>
<pre><code>import pandas as pd
import pyodbc
query = """
--Top 50 high total CPU Queries
SELECT TOP 50
'High CPU Queries' as Type,
serverproperty('machinename') as 'Server Name',
isnull(serverproper... | <p>If you can't change the driver, you'll need to change the query to return data types it supports. </p>
<p>SQL type -150 is <code>SQL_VARIANT</code>, which is returned by <code>SERVERPROPERTY</code>. The workaround is to explicitly <code>CAST</code> the column to a supported type like <code>nvarchar</code>:</p>
<p... | sql-server|pandas|odbc|pyodbc | 8 |
371,902 | 45,315,985 | Parameterized pandas data frame names | <p>How do I create a data frame with a name that resolves from a variable? From the example below I would like to created dataframe pd0,pd2..pd10</p>
<pre><code>for i in range(0,10):
pd + "i" = pd.DataFrame()
</code></pre> | <p><strong>Option 1</strong><br>
In my opinion, its better to track them in a dictionary.</p>
<pre><code>dfs = {'pd{}'.format(i): pd.DataFrame() for i in range(10)}
</code></pre>
<p>Access them</p>
<pre><code>dfs['pd0']
</code></pre>
<hr>
<p><strong>Option 2</strong><br>
But if you insist on placing the names into... | python|pandas | 3 |
371,903 | 45,298,705 | How do I pass an expression as a function keyword in Python | <p>I am trying to be pythonic with my code but can't figure out how to do:</p>
<pre><code>dfSort.assign(i+5=pd.Series(dfWork))
</code></pre>
<p>where dfSort is a Dataframe and pd is pandas import. Of course the <code>i+5</code> is an expression and therefore cannot be passed as a column name. But I want to assign a c... | <p>If <code>dfWork</code> is a <code>pd.Series</code> type, then you can use dictionary unpacking, as Ashwini mentions, like this:</p>
<pre><code>Colname = {5: 'a',6 : 'b', 7 : 'c', 8 : 'd'}
i = ... # an integer
dfSort = dfSort.assign(**{ Colname[i + 5] : pd.Series(dfWork, index=dfSort.index.values) })
</code></pr... | python|pandas|expression|keyword | 1 |
371,904 | 45,399,581 | Linear regression, Tensorflow, non-linear equation, tf.contrib.learn | <p>As an exercise, I am trying to use tf.contrib.learn.LinearRegressor to model the equation y = 3 * x1^2 + 4 * x2^2. The code runs, but I am a little disappointed with the accuracy of the results. The results are good for linear equations like y = 3 * x1 + 4 * x2. I thought that tf.contrib.learn would cope well with s... | <p><a href="https://www.tensorflow.org/api_docs/python/tf/contrib/learn/LinearRegressor" rel="nofollow noreferrer">tf.contrib.learn.LinearRegressor</a> is used to model linear regression. The equation <code>y = 3 * x1^2 + 4 * x2^2</code> is not a linear regression in <code>x1</code> and <code>x2</code>, so <code>tf.con... | tensorflow|linear-regression | 0 |
371,905 | 45,308,225 | tensorflow.python.framework.errors_impl.NotFoundError while generating TFRecord files Object Detection API | <p>I am trying to generate <strong>TFRecord files</strong> from <strong>Pascal VOC</strong> format dataset. I am following <a href="https://stackoverflow.com/questions/44973184/train-tensorflow-object-detection-on-own-dataset">this guide</a> and used <a href="https://github.com/tensorflow/models/blob/master/object_dete... | <p>Ok, so the reason was because of wrong parameters.
As <a href="https://stackoverflow.com/questions/44973184/train-tensorflow-object-detection-on-own-dataset">this guide</a> says:</p>
<blockquote>
<p>Make sure VOCdevkit is inside models/object_detection then you can go
ahead and generate the TFRecords.</p>
</blo... | python|python-3.x|tensorflow|object-detection | 1 |
371,906 | 45,386,955 | Python: replacing outliers values with median values | <p>I have a python data-frame in which there are some outlier values. I would like to replace them with the median values of the data, had those values not been there.</p>
<pre><code>id Age
10236 766105
11993 288
9337 205
38189 88
35555 82
39443 75
10762 74
33847 ... | <p>I think this is what you are looking for, you can use loc to assign value . Then you can fill the nan </p>
<pre><code>median = df.loc[df['Age']<75, 'Age'].median()
df.loc[df.Age > 75, 'Age'] = np.nan
df.fillna(median,inplace=True)
</code></pre>
<p>You can also use np.where in one line </p>
<pre><code>df["Ag... | python|pandas|numpy | 29 |
371,907 | 45,338,235 | Iterating over a DataFrame, evaluating column values, and setting value to a third column | <p>I have been trying to iterate through a DataFrame or Apply a function, in order to change the content in a specific column of the DataFrame based on 2 other columns also in the DataFrame.</p>
<p>I have a df like:</p>
<pre><code>df = pd.DataFrame({'Age_type' : pd.Series(['Adult','Adult','Child','Child']),
'Gen... | <p>How about this?</p>
<pre><code>In [96]: df
Out[96]:
Age_type Gender
0 Adult Female
1 Adult Male
2 Child Female
3 Child Female
In [97]: m = {'FemaleAdult': 'Group A',
...: 'FemaleChild': 'Group B',
...: 'MaleAdult': 'Group C',
...: 'MaleChild': 'Group D'}
In [98]: df['group'] = ... | python|pandas|dataframe|iterable | 4 |
371,908 | 45,322,194 | Most efficient way to reshape tensor into sequences | <p>I am working with audio in TensorFlow, and would like to obtain a series of sequences which could be obtained from <em>sliding a window</em> over my data, so to speak. Examples to illustrate my situation:</p>
<p><strong>Current Data Format:</strong></p>
<p>Shape = [batch_size, num_features]</p>
<pre><code>example... | <p>You can do that using <code>tf.map_fn</code> as follows:</p>
<pre><code>example = tf.constant([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15]
]
)
res = tf.map_fn(lambda i: example[i:i+3], tf.range(example.shape[0]-2), dtype=tf.int32)
sess=tf.InteractiveSession()
res.eval()
</code></pre>
<p>... | tensorflow | 2 |
371,909 | 45,389,499 | Python Pandas: How to replace values in a Dataframe based on another array in conditional base | <p>I have a DataFrame as follows. Both columns have Member_ID which indicates which Member_ID connected with other Member_ID<br>
<pre>
col1 col2
1 3
1 4
1 5
2 3
2 4
3 1
3 2
3 5
4 1
4 2
5 1
5 3
</pre>
and I have ... | <p>we can <code>stack</code>, <code>map</code> and <code>unstack</code>:</p>
<pre><code>In [9]: d1.stack().map(d2.set_index('member_ID')['Label']).unstack()
Out[9]:
col1 col2
0 a1 a3
1 a1 b4
2 a1 b5
3 b2 a3
4 b2 b4
5 a3 a1
6 a3 b2
7 a3 b5
8 b4 a1
9 b4 b2
10 b5 a... | python|pandas|dataframe|machine-learning | 5 |
371,910 | 45,523,738 | What type of data is returned from pandas_datareader.get_data_yahoo function? | <p>What type of data is returned from pandas_datareader.get_data_yahoo function? Is it Array, List, Dictionary or Object? How can i figure it out?</p>
<p>This is sample code for downloading data:</p>
<pre><code>import pandas_datareader as pdr
df = pdr.get_data_yahoo('EURUSD=X')
</code></pre> | <p>It's a pandas' dataframe and has many attributes.</p>
<p>You can see that it is a dataframe with the following code:</p>
<pre><code>isinstance(pdr.get_data_yahoo('EURUSD=X'), pd.DataFrame)
</code></pre>
<p>And you can see the attributes with the following code:</p>
<pre><code>dir(pdr.get_data_yahoo('EURUSD=X'))
</co... | python|data-structures|pandas-datareader | 1 |
371,911 | 45,439,797 | Numpy Upgrade fails | <pre><code> sudo pip install numpy --upgrade ξ² PsYcH0
The directory '/Users/karanj/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permis... | <p>Try with <code>python -m pip install SomePackage</code>. <code>-m</code> means that it will install the latest version of the package. Also have a look over <a href="https://stackoverflow.com/questions/33004708/osx-el-capitan-sudo-pip-install-oserror-errno-1-operation-not-permitted">here</a> for a nice explanation.<... | python|numpy | 0 |
371,912 | 45,613,340 | how to add values in empty column in pandas? | <p>I have problem while adding value to <code>df['data2']</code> column.</p>
<p><a href="https://i.stack.imgur.com/PhgRn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PhgRn.png" alt="enter image description here"></a></p>
<p>But I want this output in <code>df['data2']</code> column:</p>
<p><a hr... | <p>You ovewrite the whole <code>df['date2']</code> every loop. Try instead:</p>
<pre><code>df['date2']=pd.to_datetime(df['date'])+pd.to_timedelta(df['num'].astype(np.int),'D')
</code></pre> | python|pandas|datetime | 3 |
371,913 | 45,582,795 | tensorflow multiple regression error | <pre><code>import tensorflow as tf
X = tf.placeholder(tf.float32, [None,5])
w = tf.Variable(tf.zeros([5,1]), name = 'weight')
b = tf.Variable(tf.zeros([1]), name = 'bias')
y = tf.matmul(X, w) + b
Y = tf.placeholder(tf.float32, [None,1])
cost = tf.reduce_mean(tf.square(Y-y))
train_step = tf.train.GradientDescentOptimiz... | <pre><code>import tensorflow as tf
import numpy as np
X = tf.placeholder(tf.float32, [None,5])
w = tf.Variable(tf.zeros([5,1]), name = 'weight')
b = tf.Variable(tf.zeros([1]), name = 'bias')
y = tf.matmul(X, w) + b
Y = tf.placeholder(tf.float32, [None,1])
cost = tf.reduce_mean(tf.square(Y-y))
train_step = tf.train.G... | python|tensorflow|linear-regression | 1 |
371,914 | 45,568,532 | Rearrange 2D numpy array into a column vector maintaining line indexing | <p>I have a numpy array of this form: </p>
<p><a href="https://i.stack.imgur.com/BnM9p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BnM9p.png" alt="enter image description here"></a></p>
<p>I would like to rearrange it so that columns will be stacked together maintaining their initial indexes (w... | <p>You could stack an indices array and the flattened and transposed values from your (probably) <code>DataFrame</code>.</p>
<p>For example:</p>
<p>import pandas as pd</p>
<pre><code>df = pd.DataFrame({0: [0,1,1,0,0,1,0],
1: [0,0,0,0,0,1,0],
2: [1,0,1,0,1,0,0]},
... | python|arrays|numpy|reshape | 1 |
371,915 | 45,307,763 | Pandas: substitute commas for points in a column | <p>I have a column of values from a csv-file who contain commas instead of points. With the code below I want to turn these into points, however this does not work. </p>
<p>There is no error message, the code just runs and if I call the column <code>Betrag()</code> (german: absolute value) from the dataframe <code>Um... | <p>The reason you see no change is because <code>removecom</code> returns nothing. You should return a value from the function like this:</p>
<pre><code>def removecom(value):
return value.replace(',','.')
</code></pre>
<p>However, a better method I would recommend is using <code>df.str.replace</code>:</p>
<pre><... | python|string|pandas|dataframe|substitution | 4 |
371,916 | 45,590,650 | Combining rows of a dataframe with string columns | <p>I think this is a simple one, but I am not able to figure this out today and needed some help.</p>
<p>I have a pandas dataframe:</p>
<pre><code>df = pd.DataFrame({
'id': [0, 0, 1, 1, 2],
'q.name':['A'] * 3 + ['B'] * 2,
'q.value':['A1','A2','A3','B1','B2'],
'w.name':['Q', 'W', 'E', 'R', 'Q'],
'w... | <p><strong>UPDATE:</strong></p>
<pre><code>In [117]: df.groupby('id', as_index=False).agg(' '.join)
Out[117]:
id q.name q.value w.name w.value
0 0 A A A1 A2 Q W B1 B2
1 1 A B A3 B1 E R C3 C1
2 2 B B2 Q D2
</code></pre>
<p><strong>Old answer:</strong></p>
<pre><code>In... | python|pandas|dataframe | 2 |
371,917 | 45,627,813 | Drop empty time based groups in pandas | <p>I use group by to group a data frame into separate days and then split them into train and test groups based on the day using concat</p>
<pre><code>gp = dfs_0.groupby(pd.TimeGrouper('B'))
train = pd.concat([ gp.get_group(group) for i,group in enumerate( gp.groups) if i < len(gp)-1 ])
test = pd.concat([ gp.get_g... | <p>There is problem some no <code>Dates</code>, so get <code>KeyError</code>.</p>
<p>I try create custom function:</p>
<pre><code>rng = pd.to_datetime(['2014-04-16','2014-04-17','2014-04-22 00:11:00','2014-04-22',
'2014-04-23','2014-04-23 10:00:03','2014-04-23 14:01:08'])
dfs_0 = pd.DataFrame({'... | python|pandas | 1 |
371,918 | 45,466,947 | Include output from %matplotlib notebook backend as SVG in ipynb | <p><a href="https://stackoverflow.com/a/36622238/4288043">This</a> answer from a few years ago shows how you can make jupyter notebook create graphs as svg. The solution is to tell the InlineBackend to use <code>svg</code> as output. </p>
<pre><code>import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBack... | <p>Since apparently even after a bounty period noone was able to provide a solution, a workaround may be the following.</p>
<ol>
<li>Create you notebook with <code>%matplotlib notebook</code>. Once you're satisfied with the result, save it.</li>
<li><p>Use a copy of it and replace <code>%matplotlib notebook</code> wit... | python|pandas|matplotlib|jupyter-notebook | 2 |
371,919 | 45,325,453 | Slicing a box of certain width along arbitrary line through 3d array | <p>I have a big (600,600,600) numpy array filled with my data. Now I would like to extract regions from this with a given width around an arbitrary line through the box.</p>
<p>For the line I have the x, y and z coordinates of every point in separate numpy arrays. So let's say the line has 35 points in the data box, t... | <p>How about this?</p>
<pre><code># .shape = (N,)
x, y, z = ...
# offsets in [-3, 3), .shape = (6, 6, 6)
xo, yo, zo = np.indices((6, 6, 6)) - 3
# box indices, .shape = (6, 6, 6, N)
xb, yb, zb = x + xo[...,np.newaxis], y + yo[...,np.newaxis], z + zo[...,np.newaxis]
# .shape = (6, 6, 6, N)
extractions = data[xb, yb, ... | python-2.7|numpy|multidimensional-array|slice | 0 |
371,920 | 45,334,079 | Modelling a probability distribution as a fuzzy set in Python3 | <p>I'm trying to build a <strong>fuzzy set</strong> from a series of example values with <code>python3</code>.</p>
<p>For instance, given <code>[6, 7, 8, 9, 27]</code> I'd like to obtain a function that:</p>
<ul>
<li>returns <code>0.0</code> from 0 to 5ca,</li>
<li>goes gradually up to <code>1.0</code> from 5ca to 6,... | <pre><code>def pulse(x):
return np.maximum(0, 1 - abs(x))
def fuzzy_in_unscaled(x, xs):
return pulse(np.subtract.outer(x, xs)).sum(axis=-1)
def fuzzy_in(x, xs):
largest = fuzzy_in_unscaled(xs, xs).max()
return fuzzy_in_unscaled(x, xs) / largest
</code></pre>
<pre><code>>>> fuzzy_in(1.5, [1... | python|python-3.x|numpy|fuzzy-logic|probability-distribution | 0 |
371,921 | 45,283,182 | Writing exotic (non-ascii) characters to Oracle DB using pandas.to_sql in Python 3.6 | <p>I'm having difficulty writing values from a <code>pandas.DataFrame</code> which contain non-ASCII characters to an Oracle data base. Here is a reproducible example (given an real connection string):</p>
<pre><code>import pandas as pd
from sqlalchemy import create_engine, Unicode, NVARCHAR
connection_string = oracl... | <p>It is old question but I have struggled with same issue recently, and found a solution that worked for me.</p>
<p>I had to set</p>
<pre><code>os.environ['NLS_LANG'] = ".AL32UTF8"
</code></pre>
<p>And it worked for me. However I found that inserting data is very slow.</p> | python|oracle|pandas|encoding | 3 |
371,922 | 45,339,253 | Reading a Google Protocol buffer .pb file using protoc | <p>I have compiled Google Protobuf from the source and generated the <code>protoc</code> binary. Now, given a <code>.pb</code> file, i.e., <code>tensorflow_inception_v3_stripped_optimized_quantized.pb</code> how am I gonna be able to read its content <strong>without</strong> using the <code>Tensorflow</code> library ?<... | <p>Yes, <code>protoc</code> can also be used to decode .pb files.</p>
<pre><code>protoc --decode_raw < my_input.pb
</code></pre>
<p>will output the raw structure of the file. This is not very useful, because (contrary to, e.g., XML or JSON) protobuf files do not contain as much structural information (element nam... | tensorflow|protocol-buffers | 6 |
371,923 | 62,840,459 | Multiply two dataframes with same column names but different index | <p>I have two dataframes, one with data, one with a list of forecasting assumptions. The column names correspond, but the index levels do not (by design). Please show me how to multiply columns A, B, and C in df1 by the relevant columns in df2, as in my example below, <strong>and with the remainder of the original data... | <pre><code>>>> df[['A','B','C']] * df2.values
A B C
1 81 168 116
2 21 8 6
3 147 108 52
4 54 64 114
5 48 16 20
6 72 116 12
7 36 188 178
8 90 96 162
9 63 166 156
10 120 22 10
</code></pre>
<p>So to overwrite you can do:</p>
<pre><code>df.loc... | python|pandas|dataframe | 2 |
371,924 | 62,669,645 | RuntimeError: Expected object of scalar type Double but got scalar type Float for argument #2 'other' in call to _th_max | <blockquote>
<p>File
"/home/jake/venv/lib/python3.7/site-packages/torchvision/models/detection/rpn.py",
line 274, in assign_targets_to_anchors
match_quality_matrix = self.box_similarity(gt_boxes, anchors_per_image) File
"/home/jake/venv/lib/python3.7/site-packages/torchvision/ops/boxes.py",
line 1... | <p>It's hard to tell without any context.</p>
<p>But a fix is to call <code>mytensor = mytensor.double()</code> for each of your tensors and also <code>mymodel = mymodel.double()</code> to convert your data and model to the same double type.
Alternatively you can replace <code>.double()</code> with <code>.float()</code... | python|pytorch|tensor|torch|torchvision | 0 |
371,925 | 62,728,638 | How to compare values of certain columns of one dataframe with the values of same set of columns in another dataframe? | <p>I have three dataframes df1, df2, and df3, which are defined as follows</p>
<pre><code>df1 =
A B C
0 1 a a1
1 2 b b2
2 3 c c3
3 4 d d4
4 5 e e5
5 6 f f6
df2 =
A B C
0 1 a X
1 2 b Y
2 3 c Z
df3 =
A B C
3 4 d P
4 5 e Q
5 6 f R
</code></pre>
<p>I have defined a P... | <p>Use two consecutive <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> operations along with using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_suffix.html" rel="nofoll... | python|pandas|dataframe | 2 |
371,926 | 62,713,032 | How to change the column value depends on other column in pandas? | <p>I am trying to change the value of one column based on some other column value. Can you please help me how to do this?</p>
<p>Example:</p>
<pre><code>table sql object_type
VW_MDCL_INSIGT select * from MEDAFF_REF_SPECTRUM.MEDICAL_INSIGHT VIEW
TB... | <p>The reason your solution wasn't working it's because you were modifying a copy of the row of the dataframe, see this <a href="https://stackoverflow.com/a/17996532/13676202">helpful link</a> about setting a new value of the dataframe while looping. You could try with <code>np.where</code> better:</p>
<pre><code>df['s... | python|python-3.x|pandas|dataframe | 0 |
371,927 | 62,634,312 | pandas: count the number of unique occurrences of each element of list in a column of lists | <p>I have a dataframe containing a column of lists lie the following:</p>
<pre><code>df
pos_tag
0 ['Noun','verb','adjective']
1 ['Noun','verb']
2 ['verb','adjective']
3 ['Noun','adverb']
...
</code></pre>
<p>what I would like to get is the number of time each unique element occurred in the overall colu... | <p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>Series.explode</code></a> along with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_c... | python|pandas|list|count | 2 |
371,928 | 62,777,231 | Creating multiple dataframes from 2 data frames basis dates in Python | <p>I am new to Python and would need some help with my problem:</p>
<p>I have a dataframe that looks something like this:
df1</p>
<pre><code>date col1 col2 col3
01-01-2008 nan 16 19
02-01-2008 nan 25 20
03-01-2008 nan nan nan
04-01-2008 18 18 nan
</code></pre>
<p>I have another dataframe that looks like:
... | <p>Try this and let me know if you face any problem. Here you go:</p>
<pre><code>for i in range(len(df2)):
start = df2["start"][i]
end = df2["end"][i]
cols = df2["col4"][i].replace("[","").replace("]","").split(",")
print(df... | python|pandas|dataframe|date|join | 0 |
371,929 | 62,579,692 | Pandas Binning for different sets | <p>I have a dataframe of baseball players and some of their stats. For example</p>
<pre><code>id | position | gamesPlayed
---------------------------------
1 First Base 100
2 First Base 3
3 First Base 45
4 First Base 162
5 Second Base 145
6 Second Base 120
7 Seco... | <p>I believe the code below should work. I added [::-1] to the end of your list to reverse the order.</p>
<pre><code>labels = ['everyday','platoon','bench','scrub'][::-1]
df['category'] = df.groupby('position')['gamesPlayed'].transform(lambda x: pd.qcut(x,q=4, labels=labels))
</code></pre> | python|pandas|dataframe|binning | 1 |
371,930 | 62,672,620 | Reshaping data input for the model from (1, 5) to (1, 3000) | <p>The training and testing data for the model has a shape of (rows, 3000). I like to call the model to predict A which has a shape of (1, 5). How do I reshape the variable A so the model will take it to return prediction? This is a text classification model, hence the data has been vectorized.</p>
<pre><code>A = ['The... | <p>When you call <code>.fit_transform()</code> on <code>X</code>, you are refitting the vectorizer again on <code>X</code>. Use only <code>.transform()</code> and you should be okay:</p>
<pre><code>A = ['The dog is so cute']
A = vectorizer.transform(A) # <-- change this line
#pretrained model
classifier.predict(A)
... | python|numpy|scikit-learn|reshape | 1 |
371,931 | 62,543,665 | Iterating through DataLoader (PyTorch): RuntimeError: Expected object of scalar type unsigned char but got scalar type float for sequence element 9 | <p>I am new to PyTorch and am running into an expected error. The overall context is trying to build a building segmentation model off of <a href="https://spacenet.ai/" rel="nofollow noreferrer">Spacenet</a> imagery. I am forked off of this <a href="https://github.com/yangsiyu007/SpaceNetExploration" rel="nofollow nore... | <p>Ah nevermind.</p>
<p>Turns out <a href="https://stackoverflow.com/questions/75191/what-is-an-unsigned-char">unsigned char</a> comes from C++ where it gives you 0 to 255, so it makes sense that's what it expects from image data.</p>
<p>So I actually fixed this by doing:</p>
<pre><code> image = np.array(Image.o... | python|pytorch | 1 |
371,932 | 62,855,273 | GroupBy Column1, then get all elements with the first/last element on Column2 (Python) | <pre><code>df=(pd.DataFrame({'user_id':[1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4],'survey_id':[1,1,1,1,2,2,3,4,4,4,5,5,6,6,7,8,8,9,9,9,9,10,10,11,11,12,12],
'answer':["no","yes","no","no","yes","no","no","yes",&qu... | <p>Solution with no merging:</p>
<pre><code>df_head = df[df.survey_id.eq(df.groupby('user_id').transform('min').survey_id)]
</code></pre>
<p>result:</p>
<pre><code> user_id survey_id answer
0 1 1 no
1 1 1 yes
2 1 1 no
3 1 1 no
7 ... | python|pandas-groupby | 2 |
371,933 | 62,719,873 | ModuleNotFoundError: No module named 'bert' even after pip install bert-tensorflow and pip install bert-for-tf2 | <p>I have tensorflow 1.9.0 and after successful installation of bert using !pip install bert-tensorflow, I cannot import bert in Jupyter notebook. I even ran !pip install bert-for-tf2. Still no success.</p> | <p>It turns out I did not have tensorflow in my environment. Fixed after installing tensorflow.</p> | tensorflow|jupyter-notebook|bert-language-model | 0 |
371,934 | 62,614,611 | What is the equivalent of weight_filler from Caffe in Tensorflow? | <p>I'm trying to convert a TensorFlow to Caffe model, but in Caffe what about <code>weight_filler</code>? My model in tf is:</p>
<pre><code>model.add(Conv2D(16, kernel_size=(5, 5), padding="same", activation='selu',
input_shape=(64, 64, 1)))
model.add(Conv2D(16, kernel_size=(5, 5), padding=... | <p><code>weight_filler</code> is the type of generator used to initialize weights and biases. In tensorflow if it's not specified the default initializer is <code>glorot_uniform_initializer</code> which is also called <code>Xavier uniform initializer</code> so the equivalent initializer in Caffe is <code>xavier</code>:... | tensorflow|deep-learning|conv-neural-network|caffe | 0 |
371,935 | 62,560,243 | How to replace values in a Pandas Dataframe on a condition? | <p>I defined a list of values that I am searching for in a column of a dataframe and want to replace all values in that df that match.</p>
<pre><code> First_name
0 Jon
1 Bill
2 Bill
names = {'First_name': ['Jon','Bill', 'Bill']}
name_list = ['Bill']
df = DataFrame(names,columns=['First_n... | <p>Do you mean:</p>
<pre><code>name_list = ['Bill']
df.loc[df['First_name'].isin(name_list), 'First_name'] = 'Killed'
</code></pre> | python|pandas|string|dataframe | 0 |
371,936 | 62,660,886 | Search column, if value is not all digits, then cut&paste value to another column same row python pandas | <p>Wanted to ask for help on a question that has me twisting. I have a dataframe, three columns. First column is suppose to be all numbers. If letters exist in the column1 (anywhere in the value) then cut&paste value to 'Column3' within the same row. I have figured out how to use .loc to filter column for certain... | <p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.match.html" rel="nofollow noreferrer"><code>Series.str.match</code></a> along with the given <em>regex</em> pattern and optional parameter <code>na=False</code>(to treat <code>NaN</code> values as <code>False</code>) to create... | python|pandas|string|dataframe | 1 |
371,937 | 62,842,304 | Deploy exe Kivy with multi folder and files and TensorFlow | <p>I'm try to deploy a app kivy to Windows with PyInstaller like this tutorial: <a href="https://kivy.org/doc/stable/guide/packaging-windows.html" rel="nofollow noreferrer">Create a package for Windows</a></p>
<p>But's when i try execute, it crash.</p>
<p>I trying to use the <code>--onefile</code> command to create.</p... | <p>Well After many attempts the solution for me was to make a <strong>downgree of the tensorflow == 1.14</strong> compatible with PyInstaller. and change my .spec to</p>
<pre><code># -*- mode: python ; coding: utf-8 -*-
block_cipher = None
from kivy_deps import sdl2, glew, gstreamer
a = Analysis(['C:\\Users\\bababa\\... | python|tensorflow|kivy|pyinstaller|kivy-language | 0 |
371,938 | 62,578,989 | TFLiteConverter on tensorflow 1.14 in raspberry pi 3b+ | <p>I have a code for convert tflite. it is the code:</p>
<pre><code> from tensorflow import lite
from tensorflow.keras
import models
# Parameters
keras_model_filename =
'wake_word_stop_model.h5'
tflite_filename = 'wake_word_stop_lite.tflite'
# Convert model to TF Lite
model
model = ... | <p><code>from_keras_model</code> is an API of Tensorflow 2.x</p>
<p>You could use <code>from_keras_model_file</code> API</p>
<p>But I'd suggest to consider an upgrade to 2.x version</p> | python|tensorflow | 0 |
371,939 | 62,577,916 | Pandas: Write dataframe into multiple sheets grouped by name | <p>I have this dataframe:</p>
<pre class="lang-py prettyprint-override"><code>Receipt Description Card Member Account Cost Data
200a apple adam 08203928 $2 need more apples
200a apple adam 08203928 $2 need more apples
20022a pear bob 3214 $7
202a orange alice 411423432 $8
202a orange alice 321321 $8
202a orange alice 3... | <p>You can try this:</p>
<p><code>xlsxwriter</code> engine you need to install for creating <code>Excel</code> sheet.</p>
<pre><code># Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(r"sample.xlsx", engine='xlsxwriter')
</code></pre>
<p>Grouped by <code>Card</code> and sav... | python|pandas | 3 |
371,940 | 62,624,804 | Can't import sklearn ([WinError 126] The specified module could not be found) | <p><code>from sklearn import datasets</code></p>
<p>I can't import <code>sklearn</code></p>
<p>here is the error:</p>
<pre><code>OSError Traceback (most recent call last)
<ipython-input-13-f9e6334b9a20> in <module>
1 import torch
2 import numpy as np
----> 3 from... | <p>Just make sure OpenSlide DLL in your library search path</p>
<p>Otherwise:
download the OpenSlide Windows binaries, then you need to add the 'bin' folder to your environmental path</p> | python|pytorch | 2 |
371,941 | 62,780,835 | Pandas remove space after regex | <p>One of my columns currently has an extra space after a colon.</p>
<p>ex: <code>11-july-2011 11: 30:30</code></p>
<p>Is there a way to remove the space without removing the first one as well?</p> | <p>You can search for spaces which follow <code>:</code> and replace them:</p>
<pre><code>df['col_name'] = df['col_name'].str.replace(':\s+', ':')
</code></pre> | python|python-3.x|pandas|datetime|format | 4 |
371,942 | 62,706,361 | Replace String Value Digits based on their count in python? | <pre><code>df:
Col_A Month
0 March 2020 Mar
1 March 20 Mar
2 Ebg 2020 Mar
3 17 GOFE Mar
4 APR 17 Mar
5 16 HGN Nov
6 2015 ref May
7 18Jun Jul
</code></pre>
<p>How to replace digit from a string variable in pandas dataframe,
for Example i need to re... | <p>As the examples in the question contained strings of two and four strings I have assumed that the last two digits of strings of four digits are to be replaced with <code>"19"</code> and strings of two digits are to be replaced with <code>"19"</code>.</p>
<p>The following regular expression can b... | python|python-3.x|regex|pandas | 2 |
371,943 | 62,724,975 | Find intersection points for two stock timeseries | <h1>Background</h1>
<p>I am trying to find intersection points of two series. In this stock example, I would like to find the intersection points of SMA20 & SMA50. Simple Moving Average (SMA) is commonly used as stock indicators, combined with intersections and other strategies will help one to make decision. Below... | <pre><code>import numpy as np
f=close.values
g20=sma20.values
g50=sma50.values
idx20 = np.argwhere(np.diff(np.sign(f - g20))).flatten()
idx50 = np.argwhere(np.diff(np.sign(f - g50))).flatten()
priceSma_df = pd.DataFrame({
'BidClose' : close,
'SMA 20' : sma20,
'SMA 50' : sma50
})
priceSma_df.plot()
plt.scatte... | python|pandas | 3 |
371,944 | 62,783,857 | PyTorch TypeError: 'ToTensor' object is not iterable | <p>I'm trying to print an image name at each iteration. However, I'm getting an error TypeError: 'ToTensor' object is not iterable. Please could some advise where I am going wring please? Many Thanks</p>
<pre><code>from torchvision import datasets
import torch.utils.data
from torch.utils.data import DataLoader
from tor... | <p>It's because <code>transforms.Compose()</code> needs to be a list (probably some other iterables are accepted too). The problem is here:</p>
<pre><code>dataset = DataLoader(data_dir, transforms.Compose(transforms.ToTensor()))
</code></pre>
<p>Try:</p>
<pre><code>transforms = transforms.Compose([transforms.ToTensor()... | python|python-3.x|pytorch | 2 |
371,945 | 62,526,789 | Spark dataframe to pandas profiling | <p>I am trying to achieve a data profiling with pandas-profiling library. i am fetching data directly from hive. this is the error i am receiving</p>
<pre><code>Py4JJavaError: An error occurred while calling o114.collectToPython.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 2 in stage 14.0 ... | <p>Instead of setting the configuration in jupyter set the configuration while creating the spark session as once the session is created the configuration doesn't changes.</p>
<pre><code>from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("myApp") \
.config("spark.kryoserializ... | python|pyspark|pandas-profiling | 1 |
371,946 | 62,658,844 | How to add lemmatization and tokenization to scattertext | <p>I am using scattertext to parse a document in xlsx, but I am using non-English language and I will be most happy to add lemmatization and tokenization. I've checked these on spaCy alone and it works, but I have no clue how to integrate it in my scattertext plot.</p>
<pre><code>import pandas as pd
import spacy
import... | <p>Scattertext has a specific pipeline for displaying lemmas instead of tokens.</p>
<p>To start, please use spaCy to parse your data frame of documents instead of scattertext's whitespace tokenizer.</p>
<p>I'm using spaCy's English parser here, but you should be sure to use a Polish version, if available.</p>
<pre><cod... | python|pandas|spacy | 1 |
371,947 | 62,678,255 | How to install tensorflow or tensorflow-lite on raspberry Pi4? | <p>I have a raspberry Pi4 containning ubuntu 18.04. My ubuntu has been installed from a dockerfile and push thanks to balena OS in my raspberry.</p>
<p>Then I tried to install tensorflow for openvino project on it by following this tuto in an environment with python3.7.5:
<a href="https://qengineering.eu/install-tensor... | <p>If I understand your question correctly, you want to install TensorFlow on Docker running Ubuntu 18.04 on RPI4 with balena OS as host.</p>
<p>You could try to build TensorFlow from source as described in their <a href="https://www.tensorflow.org/install/source" rel="nofollow noreferrer">Build from source instruction... | tensorflow|tensorflow-lite|raspberry-pi4|openvino|balena | 0 |
371,948 | 62,705,058 | Read left channel of wav data into numpy array | <p>I'm using pyaudio to take input from a microphone or read a wav file, and analyze the stream while playing it. I want to only analyze the right channel if the input is stereo. I've been able to extract the data and convert to integers using loops:</p>
<pre><code> levels = []
length = len(data)
... | <p>You are here reading 16-bit integers from a binary file. It seems that you are first reading the data into <code>data</code> variable with something like <code>data = f.read()</code>, which is here not visible. Then you do:</p>
<pre><code>for i in range(length//2):
volume = abs(struct.unpack('<h', data[i:i+2]... | python|numpy|hex|numpy-ndarray|pyaudio | 1 |
371,949 | 62,716,279 | Saving numpy array to json | <p>Im trying to save a numpy array to a json but since a ndarray is not JSON serializable I am converting them to lists. My problem is that this consumes an excesive amount of RAM. Is there any other lightweight method?</p> | <p>You can use <a href="https://pypi.org/project/numpyencoder/" rel="nofollow noreferrer">numpyencoder</a>:</p>
<pre><code>import numpy as np
import json
from numpyencoder import NumpyEncoder
numpy_data = np.array([0, 1, 2, 3])
print(json.dumps(numpy_data, cls=NumpyEncoder))
</code></pre> | python|arrays|json|numpy | 1 |
371,950 | 62,719,641 | Why PyTorch model takes multiple image size inside the model? | <p>I am using a simple object detection model in PyTorch and using a Pytoch Model for Inferencing.</p>
<p>When I am using a simple iterator over the code</p>
<pre><code>for k, image_path in enumerate(image_list):
image = imgproc.loadImage(image_path)
print(image.shape)
with torch.no_grad():
y, featu... | <p>PyTorch has what is called a <a href="https://medium.com/intuitionmachine/pytorch-dynamic-computational-graphs-and-modular-deep-learning-7e7f89f18d1" rel="noreferrer">Dynamic Computational Graph</a> (<a href="https://ai.stackexchange.com/questions/3801/what-is-a-dynamic-computational-graph">other explanation</a>).</... | python|machine-learning|deep-learning|computer-vision|pytorch | 10 |
371,951 | 62,625,737 | Removing columns and rows from sparse dataset | <p>I have a sparse Pandas dataframe with many null values and I want to filter it such that only rows and columns with more than 10 float entries are retained in the final dataset. I have tried using an existing snippet of code but it doesn't seem to work:</p>
<pre><code>df.drop([col for col, val = df.count(axis=1, num... | <p>You can get the number of non-missing values in each row and column, check if it's greater than your threshold, then ask only for those rows/values where your condition is True.</p>
<pre><code>kept_rows, kept_columns = df.isnull().sum(1)>10, df.isnull().sum(0)>10
df = df.loc[kept_rows, kept_columns]
</code></p... | python|pandas | 0 |
371,952 | 62,710,093 | How do I install sklearn module properly? | <p>I'm trying to install <code>sklearn</code> module using <code>pip command</code> but after the installation is completed , all I can see is this folder</p>
<pre><code>C:\Users\Aditi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\sklearn-0.0-p... | <p>Try to install using command <code>pip install scikit-learn</code> or you can use <code>pip install sklearn</code> but I prefer the first one.</p>
<p>If it still not work for you, you can update the numpy or reinstall the numpy.</p>
<p>You can check <a href="https://scikit-learn.org/stable/install.html" rel="nofollo... | python|scikit-learn|data-science|sklearn-pandas | 3 |
371,953 | 62,730,078 | Selecting rows from a pandas dataframe based on the values of some columns in a list of the same dataframe? | <p>Let's suppose, there is a dataframe :</p>
<pre><code>df1 =
A B C
0 1 a a1
1 2 b b2
2 3 c c3
3 4 d d4
4 5 e e5
5 6 f f6
</code></pre>
<p>Created as :</p>
<pre><code>a1 = [1,2,3,4,5,6]
a2 = ['a','b','c','d','e','f']
a3 = ['a1','b2','c3','d4','e5','f6']
df1 = pd.DataFrame(list(zip(a1,a2,a3)),co... | <p>Here is how you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>pandas.DataFrame.merge()</code></a>:</p>
<pre><code>import pandas as pd
a1 = [1,2,3,4,5,6]
a2 = ['a','b','c','d','e','f']
a3 = ['a1','b2','c3','d4','e5','f6']
df1 ... | python|pandas|dataframe | 1 |
371,954 | 62,856,727 | How to get Max Value from group of Column Values for each Row | <p>I have a dataframe as below:</p>
<pre><code> F_Time BP BQ BO0 BO1 BO2 BO3 BO4
0 2020-07-10 09:30:00 10780.00 8550 1 28 1 1 2
1 2020-07-10 10:15:00 10788.00 8700 1 5 10 2 1
2 2020-07-10 10:20:00 10780.00 12150 1 1 1 3 76
3 2020-07-10... | <p>Try this.</p>
<pre><code>df["BO"] = df[["BO0", "BO1".....]].max(axis=1)
</code></pre> | python|python-3.x|dataframe|pandas-groupby | 2 |
371,955 | 62,786,605 | Remove values in rows, Pandas DataFrame | <p>im trying to "remove" some rows. This is my code</p>
<pre><code>popcoun = census_df.copy()
popcoun = popcoun[popcoun['SUMLEV'] == 50]
popcoun = popcoun[['STNAME','CTYNAME','CENSUS2010POP']]
popcoun = popcoun.set_index(['STNAME','CTYNAME'])
popcoun = popcoun.sort_values(by = ['STNAME','CENSUS2010POP'],ascen... | <p>Add this -</p>
<pre><code>popcoun = popcoun.groupby(['STNAME']).head(3)
</code></pre>
<p>This should work as long as the rows are sorted for each group as you have mentioned above.</p> | python|pandas|rows | 1 |
371,956 | 62,762,284 | For loop with if to detect variable change in dataframe columns | <p>I'm using a double for loop with a if condition inside to check if the variable change from 0 to 1.
The data are stored in a dataframe (the data I want to check are FAULT flag recorded by test bench).
I want to write a little tool that detect any change in the column of FAULT flag (column 164 to 211) and display the... | <p>I believe that @Rashan Arshad has identified the issue exactly. In the second <code>for</code> loop, the program will assign <code>data = df.iloc[i,j]</code> for each value of <code>i</code>, but it will not check if <code>data</code> is equal to 1 until it has exited the <code>for</code> loop. This is why you only ... | python|pandas|dataframe | 0 |
371,957 | 62,783,704 | Using Anaconda - Can import numpy into Jupyterlab but not Jupyter notebook | <p>Absolute newbie using Anaconda in Windows to launch apps. I can run this code successfully in JupyterLabs within either notebooks or console and also runs fine in Spyder, but I get an error running in Pycharm:</p>
<pre><code> import numpy as np
weights = np.array([0.1, 0.2, 0])
def neural_network(input,... | <p>In PyCharm, you'll need to set the environment you're using, so that it sees your already installed packages.
If you open the settings in PyCharm, you'll see the menu item starting with <code>Project: ...</code>. Under that, go to <code>Project Interpreter</code> and add a new environment. This should be the folder ... | python|numpy|jupyter-notebook|pycharm | 0 |
371,958 | 62,602,285 | Web scraping information from multiple pages into a pandas dataframe | <p>I would like to write some code that scrapes data from multiple pages in a job listing site. Currently however, when I run my code I only get the last page as opposed to a listing of all the pages I scraped.</p>
<p>This is my code</p>
<pre><code>url = 'https://ng.indeed.com/jobs?q=Business+Intelligence+Analyst&l... | <pre><code>import requests
from bs4 import BeautifulSoup
summaries = [] # <-- outside of the loop
jobs = [] # <-- outside of the loop
url = 'https://ng.indeed.com/jobs?q=Business+Intelligence+Analyst&l=Nigeria&start='
for i in range(0,80,10):
page = requests.get(url+str(i))
soup = Bea... | python|pandas|beautifulsoup|python-requests | 2 |
371,959 | 62,868,849 | Keras/Tensorflow in RStudio not referencing Python in Miniconda Environment | <p>so I've been trying to use Keras with Miniconda on my machine for a few weeks now (in Rstudio) and I've still been unable to make significant progress.</p>
<p>Most recently, here are the steps I followed:</p>
<ol>
<li>create an environment in Miniconda, using Python 3.6</li>
<li>Download R and RStudio (an older vers... | <p>I finally got it to work! Here were my steps for anyone who stumbles across this:</p>
<ol>
<li>Reinstall Anaconda</li>
<li>Create Anaconda Environment with Python 2.7 and R</li>
<li>Install Keras and Tensorflow packages and dependencies one by one into the environment through Anaconda</li>
<li>Install RStudio in the... | python|r|tensorflow|keras | 0 |
371,960 | 62,880,723 | Selecting a data frame row using a term in list found in the same data frame row | <p>I have a data frame that has two columns. One column host a term's name and the second column is a list of terms associated with the 1st column. It generally looks like this:</p>
<pre><code>Name Terms
Jupiter [5,planet, big,]
June [month,6,hot]
Neptune [blue, planet,big]
Seventeen [17, number,teen]... | <p>You can do this with <code>explode</code>:</p>
<pre><code>df.loc[df.explode('Terms').query('Terms == "planet"').index]
</code></pre>
<p>Output:</p>
<pre><code> Name Terms
0 Jupiter [5, planet, big]
2 Neptune [blue, planet, big]
</code></pre>
<hr />
<p>Or nested list comprehension... | python|pandas|search | 1 |
371,961 | 62,690,200 | Creating a Pandas column based on a value in a specific row and column with .map or similar | <p>I have a use case where I need to fill a new pandas column with the contents of a specific cell in the same table. There are 60 countries in Europe, so I need to fill a shared currency column with the content's of one country's currency (as an example only)</p>
<p>I need an SQL "Where" clause for Pandas - ... | <p>How about you take the value from that cell and just create a new column with it as below:</p>
<pre><code>p = w.loc["Britain"]["currency"]
w['Euro_currency'] = p
</code></pre>
<p>Does this work for you?</p> | python|pandas | 0 |
371,962 | 62,737,920 | How to make repeating column values empty in python dataframe? | <p>I'm working in a pandas dataframe in python and my output now looks like the following:</p>
<pre><code>1 abc 19
1 def 14
1 efg 9
2 abc 30
2 def 2
2 efg 5
</code></pre>
<p>etc...</p>
<p>I want to change my pandas to make it look like this:</p>
<pre><code>1 abc 1... | <pre><code>d = {'A': [1, 1, 1, 2, 2, 2], 'B':[i for i in range(6)], 'C': [i for i in range(10, 16)]}
x = pd.DataFrame(d)
x.set_index(['A', 'B'])
</code></pre> | python|pandas|dataframe | 1 |
371,963 | 62,482,536 | Convert column to row after pivot_table | <p>After <code>pivot_table</code>, I got the <code>dataframe</code> as below:</p>
<p><img src="https://i.stack.imgur.com/4pfJw.png" width="350"></p>
<p>I want:</p>
<pre><code>product_id 22200103 6902133 6902303 16900119 2600270
user_id
183503497 1 2 0 0 0
18... | <p>First, these three pandas commands are very similar, figure out which one of them you need:</p>
<ul>
<li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot.html" rel="nofollow noreferrer"><code>pd.pivot</code></a></li>
<li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/... | python|pandas | 0 |
371,964 | 62,801,631 | Replacing certain values in a column with messy data | <p>I have a very lengthy dataset, that is stored as a dataframe. The column I am looking at is called "Country". This column has quite a few countries within it. The issue is that I want to change various values to "USA".
The values I am trying to change are
U.S
United States
United states
etc.
Ther... | <p>One of thing you can do is to stick to the first letter of each word. For all of the instance the first letter is <code>U</code> and for the second part (if you split the whole string) is <code>S</code>. Here, I am using regular expressions package that is usually used when you are working with texts.</p>
<pre><code... | python|pandas | 1 |
371,965 | 62,617,733 | beautiful soup misses text when scraping html | <p>Here is a sample of my HTML. I need to parse all content for each record. This is one sample record.</p>
<pre><code><div class="list-group-item card-contact">
<div class="card-base">
<div class="card-name hot"><a href="contact.php?leaduuid=e888888e&... | <p>You can access the <code>data-score</code> attribute like this:</p>
<pre><code>soup.ul.attrs['data-score']
</code></pre>
<p>Output:</p>
<pre><code>'88888827'
</code></pre>
<p>More data:</p>
<pre><code>import re
new_line_re = re.compile('\n{2,}')
new_line_re.sub('\n', soup.div.text).strip().split('\n')
</code></pre>... | python|pandas|beautifulsoup | 0 |
371,966 | 62,522,094 | Extract tuples that are changing values in dataframe | <p>I possess two similar structure dataframes.
Take a dataframe A:</p>
<pre><code>Name | Col3 | Col4
------+------+------
P | 5 | 9 -1
Q | 0 | 1 -2
R | 2 | 7 -3
</code></pre>
<p>And another one B:</p>
<pre><code>Name | Col3 | Col4
------+------+------
P | ... | <p>Depending on how the two data frames are related, there probably is a smarter, i.e. faster, way (tracking indices or such) but one way to do it is</p>
<pre><code>B['is_in_A'] = B.apply(lambda x: int(~(A==x).all(axis=1).any()), axis=1)
</code></pre>
<p>This might be slow on large dataframes as for every row in <code>... | python|python-3.x|pandas|dataframe | 1 |
371,967 | 62,607,677 | How exactly does the .any() Python method work? | <p>I'm trying to write a script that simulates a system of chemical reactions over time. One of the inputs to the function is the following array:</p>
<pre><code>popul_num = np.array([200, 100, 0, 0])
</code></pre>
<p>Which contains the number of discrete molecules of each species in the system. Part of the main functi... | <p>You should use <code>.any()</code> on a boolean array <em>after</em> doing the comparison, not on the values of <code>popul_num</code> themselves. It will return <code>True</code> if any of the values of the boolean array are <code>True</code>, otherwise <code>False</code>.</p>
<p>In fact, <code>.any()</code> tests... | python|arrays|numpy|if-statement|any | 2 |
371,968 | 62,566,558 | Validation Accuracy stuck at .5073 | <p>I am trying to create a regression model but my validation accuracy stays at <code>.5073</code>. I am trying to train on images and have the network find the position of an object and the rough area it covers. I increased the unfrozen layers and the plateau for accuracy dropped to <code>.4927</code>. I would appreci... | <ol>
<li>The final activation function in your model should not be <code>sigmoid</code> since it will output numbers between <code>0</code> and <code>1</code> and I am assuming your labels (i.e., <code>positionx</code>, <code>positiony</code>, and <code>width</code> are not in this range). You could replace it with eit... | python|tensorflow|keras|linear-regression | 1 |
371,969 | 62,615,217 | how to merge a column from a dataframe to another based on a condition? | <p>I have the following csv files:</p>
<pre><code>file1.csv #dataframe is named dfFile1
Id,name,pos_neg,line
1,abc,pos,cas
2,cde,neg,work
3,efg,pos,cat
4,abc,pos,job
file2.csv #dataframe is named dfFile2
Id,ref,names,other
c10,n1,www,10.5
c11,m4,efg,5.4
c12,m5,cde,9.8
c13,m9,hhh,6.7
c14,n4,abc,12.5
c15,n9,kkk,3.4
</co... | <p>You can iterate through your dataframe with iterrows</p>
<pre><code>df3 = df2[df2.names.isin(names)]
for index, row in df3.iterrows():
row = df[row['names'] == df['name']]['pos_neg']
df3.loc[index,'pos_neg'] = row.iloc[0]
</code></pre>
<p>row.loc[0] stands for rows that has same 'name' field. Gets first of ... | python|pandas | 1 |
371,970 | 62,600,525 | Dataframe: get_dummies for arrays in coll | <p>Working with Python/Pandas</p>
<p>I have a csv file pretty simple except for one column: the source is an array.</p>
<p>An example of my table:</p>
<pre><code>Column A |Column B |Column C |Column D |
__________________________|__________|__________|__________|
[Water, Food, Groceries] | 0 ... | <p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>Series.explode</code></a> on <code>Column A</code>, then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html" rel="nofollow noref... | python|pandas|dataframe | 4 |
371,971 | 62,726,290 | Python wrong calculation with np.uint8 | <p>While trying to do some calculations in a Jupyter notebook. I tried to raise an array to the power of <code>2</code>, either using <code>**</code> or using <code>np.power</code>. Both yield the wrong results.</p>
<p><a href="https://i.stack.imgur.com/T5Dne.png" rel="nofollow noreferrer"><img src="https://i.stack.img... | <p>It's because the data type of your array is <code>uint8</code> which can only store 8-bit numbers i.e., 0-255. After that, overflow happens and your results get wrapped around which gives you <code>x mod 256</code> as representation for <code>x</code>. For example, <code>62*62=3844</code> but since 3844 can't be acc... | python|numpy | 3 |
371,972 | 62,796,775 | Make this code run for several excel files | <p>So I want to run this script for several excel files, so instead of df3, I will import several excel files, and merge all the results into a dataframe.</p>
<p>Here is the main code example</p>
<pre><code>
import pandas as pd
d = {'City': ['Tokyo','Tokyo','Lisbon','Tokyo','Tokyo','Lisbon','Lisbon','Lisbon','Tokyo','... | <p>The first problem is here:</p>
<pre><code>df3 = pd.read_excel(x &".xlsx").format(x)
</code></pre>
<p>In Visual Basic and VBA, strings are concatenated with <code>&</code>.</p>
<p>In Python, the operator is <code>+</code>, but you need to make sure that there's a string on both sides.</p>
<p>Since <... | python|pandas|numpy|dataframe | 1 |
371,973 | 62,818,306 | What is the most efficient way to fill missing values in this data frame? | <p>I have the following pandas dataframe :</p>
<pre><code>df = pd.DataFrame([
['A', 2017, 1],
['A', 2019, 1],
['B', 2017, 1],
['B', 2018, 1],
['C', 2016, 1],
['C', 2019, 1],
], columns=['ID', 'year', 'number'])
</code></pre>
<p>and am looking for the most efficient way to fill the missing years ... | <p>A slightly faster approach rather than using <code>explode</code> is to use pd.Series constructor. And you can use .iloc if years are already sorted from earliest to latest.</p>
<pre><code>idx = df.groupby('ID')['year'].apply(lambda x: pd.Series(np.arange(x.iloc[0], x.iloc[-1]+1))).reset_index()
df.set_index(['ID',... | python|pandas | 19 |
371,974 | 62,678,791 | Drop certain character in Object before converting to Datetime column in Pandas | <p>My dataframe has a column which measures time difference in the format HH:MM:SS.000</p>
<p>The pandas is formed from an excel file, the column which stores time difference is an Object. However some entries have negative time difference, the negative sign doesn't matter to me and needs to be removed from the time as... | <p>It looks like you need to clean your input before you can parse to timedelta, e.g. with the following function:</p>
<pre><code>import pandas as pd
def clean_td_string(s):
if s.count(':') > 2:
return '.'.join(s.rsplit(':', 1))
return s
</code></pre>
<p>Applied to a df's column, this looks like</p>... | python|pandas|python-datetime|timedelta | 0 |
371,975 | 62,697,785 | Multilabel classification with imbalanced dataset | <p>I am trying to do a multilabel classfication problem, which has an imabalnced dataset.
The total number of samples is 1130, out of the 1130 samples, the first class occur in 913 of them. The second class 215 times and the third one 423 times.</p>
<p>In the model architecture, I have 3 output nodes, and have applied ... | <p>I would try the label powerset method.</p>
<p>Instead of 3 output nodes, try setting that to the total number of combinations possible as per your labels and dataset. For example, for a multi-label classification with 3 distinct classes, there are 7 possible outputs.</p>
<p>Say, labels are A, B and C. Map output 0 t... | python|tensorflow|keras|neural-network|multilabel-classification | -1 |
371,976 | 62,502,584 | How to find out which pipes are facing wrong direction | <p>I am trying to calculate the district heating system. I get the info from shapefiles β for pipes I have a geometry of linestrings with start and end coordinates. I created a geopandas dataframe:</p>
<pre><code>+-------+--------------------------------------------------------------------------------------------------... | <p>Your idea from the comments to check where the endpoints meet is the way to go and it isn't as complex as you say. Start at the starting pipe of your network (where all the water comes from β I assume that's a single pipe) and work your way down the network with a recursive function:</p>
<pre><code>from shapely.geom... | pandas|shapefile|geopandas | 1 |
371,977 | 54,374,515 | Seaborn's No numeric types to aggregate error | <p>I have a pandas data frame in this form:</p>
<pre><code> Country Year Value
0 Thailand 1989 48587.03
1 Thailand 1990 55903.07
2 Vietnam 1989 100290.04
3 Vietnam 1990 118873.59
4 India 1989 147383.02
5 India 1990 178230.05
</code></p... | <p>I think this error has more to do with pandas.groupby() than with seaborn itself. Checking to make sure that all of my numeric columns were floats worked for me. In your case</p>
<p><code>df.Year = df.Year.astype(float)</code>
and
<code>df.Values = df.Values.astype(float)</code></p> | python|pandas|seaborn | 7 |
371,978 | 54,408,057 | TensorFlow code not giving intended results | <p>The following code has the irritating trait of making every row of "out" the same. I am trying to classify k time series in Xtrain as [1,0,0,0], [0,1,0,0], [0,0,1,0], or [0,0,0,1], according to the way they were generated (by one of four random algorithms). Anyone know why? Thanks!</p>
<pre><code>import numpy as n... | <p>Likely because your loss function is mean squared error. If you're doing classification you should be using cross-entropy loss </p> | tensorflow | 0 |
371,979 | 54,392,217 | Average time between timestamps per group not in order | <p>I would like to get the <code>mean</code> time between timestamps per group. However, the groups are not ordered.</p>
<p>Code to create df:</p>
<pre><code>d = {'ID': ['AI100', 'AI200', 'AI200', 'AI100','AI200','AI100'],
'Date': ['2019-01-10', '2018-06-01', '2018-06-11','2019-01-15','2018-06-21', '2019-01-22']... | <p>I think the issue you're having here is that you aren't calculating your diffs by the group so it's calculating the difference between the previous group's last value and the new group's first value.</p>
<p>Change your line to this and you should get the expected result:</p>
<pre><code>data['diffs'] = data.groupby... | python|pandas|dataframe | 1 |
371,980 | 54,524,992 | Tensorflow serving trained model saved with saved_model | <p>I find tf.saved_model documentation not clear, is there any valuable resources how to read trained model within other session?</p> | <p>It's as easy as:</p>
<pre><code># Clear the default graph if any
tf.reset_default_graph()
# Create a saver/loader object
loader = tf.train.Saver()
# Build the same graph architecture (Easiest to do with a class)
model = YourModel()
# Create a session
with tf.Session() as sess:
# Initialize the variables in the ... | tensorflow | 0 |
371,981 | 54,324,778 | Efficient way of redistributing (random.shuffle) | <p>So, I currently have code looking like:</p>
<pre><code>def shuffling(X,t):
n = 100
permute = list(range(n * 2))
random.shuffle(permute)
X = X[:, permute]
t = t[permute]
return X,t
</code></pre>
<p>X = 3 x 200 and t = 200 x 1, what I want to do is to shuffle these two matrices, so that each ... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html" rel="nofollow noreferrer"><code>np.random.permutation</code></a> to generate a shuffled index for both arrays:</p>
<pre><code>import numpy as np
def shuffling(X,t):
r = np.random.permutation(len(t))
X = X[:, r]... | python|numpy | 0 |
371,982 | 54,401,223 | Creating boxplot from Pandas DataFrame using Seaborn | <p>I have the following <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.html" rel="nofollow noreferrer">Pandas</a> <code>DataFrame</code> which I use comparing the performance of different classifiers over multiple iterations. After each iteration, I save the ranking of that spe... | <p>Firstly, we need to convert your data into numeric values rather than strings. Then, we melt the dataframe to get it into long format, and finally we apply a boxplot with a swarmplot on top</p>
<pre><code>df = df.apply(pd.to_numeric).melt(var_name='Classifier', value_name='AUC Rank')
ax = sns.boxplot(data=df, x='Cl... | python|pandas|dataframe|seaborn | 1 |
371,983 | 54,589,505 | Cannot feed value of shape (25, 2, 1) for Tensor 'Placeholder_24:0', which has shape '(?, 2)' tensorflow python | <p>Here I design a neural network using tensorflow.
when I run it it gave me this error. I tried to do inverse transform of prediction value.
Can anyone help me to solve this problem?
my code:</p>
<pre><code>data_train, data_test = train_test_split(data, test_size=0.2)
scaler = preprocessing.MinMaxScaler(feature_range... | <p>Looks like batch_x has shape (25, 2, 1), meaning it has a superfluous dimension 1. You can just reshape this array into shape (25, 2):</p>
<pre><code>batch_x = numpy.reshape(batch_x, (batch_x.shape[0], batch_x.shape[1]))
</code></pre> | python|tensorflow | 0 |
371,984 | 54,549,577 | Plot Line for Price and Dot for Volume in Twin Axis | <p>I have my code like:</p>
<pre><code>df.plot('Time', ['Price', 'Volume'], secondary_y='Volume', ax=axes[0])
</code></pre>
<p>By default both are plotted as line. I want the Volume in Second axis to be plotted as Dot(*)</p> | <p>You can pass a list of line styles to the <code>style</code> keyword:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
df = pd.DataFrame.from_dict({
'Time' : np.arange(10),
'Price' : np.random.rand(10)*10,
'Volume' : np.linspace(1,10,10)**2,
})
df.plot(
... | python-3.x|pandas|dataframe|matplotlib | 1 |
371,985 | 54,494,282 | Python adding two dataframes based on index (edited) | <p>(no idea how to introduce a matrix here for readability)
I have two dataframes obtained with Panda and Python. </p>
<pre><code> df1 = pd.DataFrame({'Index': ['0','1','2'], 'number':[3,'dd',1], 'people':[3,'s',3]})
df1 = df1.set_index('Index')
df2 = pd.DataFrame({'Index': ['0','1','2'], 'quantity':[3,2,'hi'], 'pers... | <p>You can try of concatenating both dataframes, then add based on the index group</p>
<pre><code>df1.columns = df.columns
df1.people = pd.to_numeric(df1.people,errors='coerce')
pd.concat([df,df1]).groupby('Index').sum()
</code></pre>
<p>Out:</p>
<pre><code> number people
Index
A 8 5.0
B 2 ... | python|pandas | 1 |
371,986 | 54,481,485 | is it possible to do the equivalent of SQL nested requests in pandas dataframe? | <p>it is possible to do in Pandas dataframe the equivalent of this SQL code</p>
<pre><code>delete * from tableA where id in (select id from tableB)
</code></pre> | <p>Don't know the exact structure of your DataFrames, but something like this should do it:</p>
<pre><code># Setup dummy data:
import pandas as pd
tableA = pd.DataFrame(data={"id":[1, 2, 3]})
tableB = pd.DataFrame(data={"id":[3, 4, 5]})
# Solution:
tableA = tableA[~tableA["id"].isin(tableB["id"])]
</code></pre> | pandas|dataframe|equivalent | 1 |
371,987 | 54,320,035 | find indices where one array is larger than an element in a second array | <p>I have two arrays </p>
<pre><code>a = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
b = np.array([0,5,10,15])
</code></pre>
<p>I want an output array with the length of <code>b</code> where each element <code>b[i]</code> is the index of the first element of <code>a</code> which is at least <code>b[i]</code>... | <p>If <code>a</code> is sorted, you can use <code>a.searchsorted(b)</code>.</p> | python|numpy | 3 |
371,988 | 54,634,771 | tensorflow keras fit, input validation data (data, (target1,target2)) ,got error :'expected no data, but got:' | <p>Build a subclassed model with multiple outputs, use tensorflow datasets as input. Custom defined datasets.</p>
<p>Use keras fit to train model.</p>
<p>When i only use train dataset, it could run. But once i use same type datasets as validation input, it goes wrong like:
'Error when checking model target: expe... | <p>Keras is not PyTorch, you should not subclass model without a very advanced reason.</p>
<pre><code>inputs = Input(input_shape)
out1 = Dense(16)(inputs)
out2 = Dense(16)(inputs)
model = tf.keras.Model(inputs, [out1,out2])
</code></pre>
<p>Separate <code>x</code> and <code>y</code> when training:</p>
<pre><code>x_... | python|tensorflow|keras|tensorflow-datasets | 1 |
371,989 | 54,272,099 | multiply all columns of DataFrame with a rows of another DataFrame | <p>I have two DataFrames:</p>
<p>df1</p>
<pre><code>DT D1 D2
0 1.0 0.50
</code></pre>
<p>df2</p>
<pre><code>DT D1 D2
C_Step
UNKNOWN 0.202899 0.325581
fair 0.253623 0.244186
good 0.289855 0.186047
poor 0.253623 0.244186
</code></pre>
<p>How I can multi... | <p>You can check with <code>mul</code> , before that you need also convert df1 to <code>Series</code></p>
<pre><code>df2.mul(df1.loc[0],axis=1)
D1 D2
DT
UNKNOWN 0.202899 0.162791
fair 0.253623 0.122093
good 0.289855 0.093023
poor 0.253623 0.122093
</code>... | python|pandas | -1 |
371,990 | 54,489,735 | How to select a tf-serving version? | <p>If I use tenserflow 1.8 or tensorflow 1.12, which version of tf-version I can use for inference?
Is it have a requirement that if I use tenserflow 1.8 then I should choose corresponding tf-serving r1.8?
Or we just use the master branch is ok?</p> | <p>Yes, it's best to use the version of TF Serving that corresponds to the version of TensorFlow your model was trained with. You can check out the releases of TF Serving on <a href="https://github.com/tensorflow/serving/releases" rel="nofollow noreferrer">github</a>. </p> | tensorflow-serving | 0 |
371,991 | 54,262,318 | How to use pre-trained BERT model for next sentence labeling? | <p>Iβm new to AI and NLP.
I want to check how bert works.
I use BERT pre-trained model:
<a href="https://github.com/google-research/bert" rel="nofollow noreferrer">https://github.com/google-research/bert</a></p>
<p>I ran extract_features.py example , described in extract features paragraph in readme.md.
I got vect... | <p>The answer is to use weights, what was used nor next sentence trainings, and logits from there. So, to use Bert for nextSentence input two sentences in a format used for training:</p>
<pre class="lang-py prettyprint-override"><code>def convert_single_example(ex_index, example, label_list, max_seq_length,
... | tensorflow|artificial-intelligence|natural-language-processing | 1 |
371,992 | 54,509,697 | from a set of x items, repeat each item y times such that, y follows a normal distribution | <p>From a set of x unique items, I need to repeat each item y times such that y follows a normal distribution.</p>
<p>For example, if number of items n = 5, and y_max = 50.
If we count how many times each item in my sorted list is repeated, the visual would look like this:</p>
<p><a href="https://i.stack.imgur.com/PM... | <p>Firstly, let us generate the desired result.</p>
<pre><code>my_set = ('a', 'b', 'c', 'd', 'e')
distribution = np.random.normal(len(my_set)/2, 1, 10000).round().astype(int)
result = [my_set[max(min(el, 4), 0)] for el in distribution]
np.unique(result, return_counts=True)
>>> (array(['a', 'b', 'c', 'd', 'e']... | python|numpy|scipy | 1 |
371,993 | 54,285,487 | How to format my Dataframe dates to one format | <p>I have no idea why but my DataFrame is showing the dates (index) in different formats. Not sure how to fix it.</p>
<p>My Code:</p>
<pre><code>csv_m = pd.read_csv('coins_mktcap.csv')
data_m = pd.DataFrame(csv_m)
data_m['date'] = pd.to_datetime(data_m['date'])
data_m.set_index('date', inplace = True)
df_m = data_m.... | <p>Add parameters <code>parse_dates</code> and <code>index_col</code> for <code>DatetimeIndex</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a>, also because format with starting days add <code>dayfirst=True</code>, check a... | python|pandas | 4 |
371,994 | 54,370,035 | When and where are the "shape" and weights of a keras / tensorflow layer determined and stored? | <p>Two concrete questions:</p>
<p>Why doesn't a keras <code>Dense</code> layer know its <code>input_shape</code> and <code>output_shape</code>, even after the model is run?</p>
<p>Why doesn't the layer know its parameter count until some training data is pumped through?</p>
<p>I train a simple keras / tensorflow mod... | <p>In TensorFlow, tensors have <a href="https://blog.metaflow.fr/shapes-and-dynamic-dimensions-in-tensorflow-7b1fe79be363" rel="nofollow noreferrer">two different types</a> of shapes: a <em>dynamic shape</em> and a <em>static shape</em>. Consider the static and dynamic shapes of a tensor named <code>my_tensor</code>.</... | python|tensorflow|keras | 1 |
371,995 | 54,539,062 | Is there a way to merge pandas dataframes on row and column index? | <p>I want to merge two pandas data frames that share the same index as well as some columns. pd.merge creates duplicate columns, but I would like to merge on both axes at the same time. </p>
<p>tried pd.merge and pd.concat but did not get the right result.</p>
<p>my try: df3=pd.merge(df1, df2, left_index=True, right_... | <p>IIUC, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>df.combine_first()</code></a>:</p>
<pre><code>df3=df1.combine_first(df2)
print(df3)
Var#1 Var#2 Var#3 Var#4 Var#5 Var#6 Var#7 Var#8 Var#9
ID ... | pandas|dataframe|merge | 3 |
371,996 | 54,366,441 | Merge information from rows with same index in a single row with pandas | <p>I am working to create a database from different existing ones. After merging the information I need from them I get some rows that were repeated in both of them.</p>
<p><code>2018-11-22 Iraq 13984.75 3000.0 NaN</code><br>
<code>2018-11-22 Iraq NaN NaN Heavy Rain</code></p>
<p>Desir... | <p>I believe you need:</p>
<pre><code>df1 = pd.DataFrame({
'A':list('abcdef'),
'B':[4,np.nan,4,50,5,np.nan],
'C':[7,np.nan,9,4,2,3],
'E':[np.nan,30,60,9,np.nan,4],
'F':['s','d','f',np.nan,'r',np.nan]
}, index=pd.date_range('2011-01-01', periods=6))
df2 = pd.DataFrame({
... | python|pandas|dataframe | 4 |
371,997 | 54,486,645 | pd.datetime not indexing correctly | <p>I have dataset with date of every transaction in restaurant. I tried to set date as index, before converting it with <em>df.to_datetime</em>:</p>
<pre><code>df['dateTransaction'] = pd.to_datetime(df['dateTransaction'])
df.info()
</code></pre>
<p>And I really get 'dateTransaction' type as datetime64[ns]. But than I... | <p>If you are reading it from CSV you can also try</p>
<pre><code>data=pd.read_csv('SomeData.csv',index_col=['Date'],parse_dates=['Date'],dayfirst=True)
</code></pre>
<p>without <code>dayfirst=True</code> the days read in as months and vice versa</p> | pandas|datetime|indexing | 0 |
371,998 | 54,348,892 | Python string conversion, take out spaces, add hyphens | <p>I have a column in a pandas data frame that is formatted like </p>
<blockquote>
<p>f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17</p>
</blockquote>
<p>and I want to convert it to look like:</p>
<blockquote>
<p>f1d3a40a-d06a-4b4a-83d4-4fc91f151117</p>
</blockquote>
<p>I know I can use <code>replace(" ", "")<... | <p>This looks like a UUID, so I'd just use that module</p>
<pre><code>>>> import uuid
>>> s = 'f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17'
>>> uuid.UUID(''.join(s.split()))
UUID('f1d3a40a-d06a-4b4a-83d4-4fc91f151117')
>>> str(uuid.UUID(''.join(s.split())))
'f1d3a40a-d06a-4b4a-8... | python|string|pandas|formatting|uuid | 13 |
371,999 | 54,333,467 | Lasso Regression with Python: Simple Question | <p>Assume I have a table of values:</p>
<pre><code>df = pd.DataFrame({'Y1':[1, 2, 3, 4, 5, 6], 'X1':[1, 2, 3, 4, 5, 6], 'X2':[1, 1, 2, 1, 1, 1],
'X3':[6, 6, 6, 5, 6, 4], 'X4':[6, 5, 4, 3, 2, 1]})
</code></pre>
<p>I want to make a simple Lasso regression using all of these values as my testing set, wher... | <p>I dont think you fully understand what the coefficients mean. First of all, you should not be regressing <code>'Y1'</code> on all of your variables (with <code>'Y1'</code> included). Don't include <code>'Y1'</code> in your independent variables:</p>
<pre><code>Lasso(alpha = 0.0001).fit(df[['X1','X2','X3','X4']], df... | python|pandas|scikit-learn|regression|lasso-regression | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.