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 |
|---|---|---|---|---|---|---|
367,400 | 39,667,277 | Pandas slicing by element in cell | <p>What is the best way to slice by looking for a single element within a cell? I know how to do it with the .isin() function where the cell element is in a list. But I am actually looking for the reverse:</p>
<pre><code>id vals
1 ['wow', 'very', 'such']
2 ['wow', 'such']
3 ['very', 'such']
... | <p>A <code>list-comprehension</code> to select rows which contain only the string <em>very</em> could be used:</p>
<pre><code>df[['very' in x for x in df['vals'].values]]
</code></pre>
<p><a href="https://i.stack.imgur.com/CwrgU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CwrgU.png" alt="Image"... | python|pandas|slice | 2 |
367,401 | 39,418,504 | Can't open csv file via command prompt on windows | <p>I'm having trouble with the first argument in the pd.read_table function used for Python via Pandas. If I hardcode in the file path of the csv file I want to open and use as a data frame, it works. However, when I receive the file path via a command argument, which saves it into a variable, it won't receive the vari... | <p>I tried the same and it worked for me(I am using Ubuntu, but that should not matter). I did the following please crosscheck and see</p>
<p>test.py</p>
<pre><code>import sys
import pandas as pd
pd.read_table(sys.argv[1])
</code></pre>
<p>Then called the function like :</p>
<pre><code>test.py /home/user/test.csv
... | python|windows|pandas|command-line | 3 |
367,402 | 39,725,419 | Solving sets of non-linear equations as an array | <p>I'm trying to solve for the intersection of the two equations: <code>y=Rx^1.75</code> and <code>y=ax^2+bx+c</code> for all rows in my dataframe (about 100K rows). Each value of <code>R,a,b,c</code> is different for each row. I can solve them one by one by iterating through the dataframe and calling <code>fsolve()<... | <p>You could get rid of one variable, then use Numpy's array broadcasting:</p>
<pre><code># Your `df`:
#R a b c x y
#0 0.5 -0.01 -0.50 32.42 9.69483 26.6327
#1 0.6 0.00 0.07 14.12 6.18463 14.5529
#2 0.7 -0.01 -0.50 32.42 8.17467 27.6644
# Solved in one go
coefs = df.values[:, 0:4]
def... | python|pandas|numpy|scipy | 0 |
367,403 | 39,483,427 | How to make dtype converter function in Pandas? | <p>I would like to make functions and pass pipe or apply method in <code>pandas</code> to avoid recursive assignment and for practice.</p>
<p>Here is my example dataframe.</p>
<pre><code>A
0 1
1 2
2 3
3 4
</code></pre>
<p>And I defined my converter function,to pass pipe method.</p>
<pre><code>def converter(df,cols,... | <p>You need add <code>[]</code> for select columns:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3,4]})
print (df)
A
0 1
1 2
2 3
3 4
def converter(df,cols,types):
df[cols]=df[cols].astype(types)
return df
print (converter(df, 'A', float))
A
0 1.0
1 2.0
2 3.0
3 4.0
</code></pre> | python|pandas|indexing|dataframe|casting | 1 |
367,404 | 39,837,546 | Converting List of Multidimensional Arrays to Single Multidimensional Array? | <p>Let Y be a list of 100 ndarrays, such that Y[i] is an ndarray of an image, its shape is 160x320x3.</p>
<p>I want X no be an ndarrays that contains all the images, I do as follows:</p>
<pre><code>x = [ y[i] for i in range(0,10) ]
</code></pre>
<p>But it produces a list of of 100 160X320X3 ndarrays. How can I modif... | <p>Calling <code>np.array</code> on <code>Y</code> (i.e <code>np.array(Y)</code>) should turn the list of ndarrays into one ndarray, with the size of the first axis corresponding to the length of the list.</p>
<p><em>Demo</em>:</p>
<pre><code>>>> x = np.array([[1,2], [3,4]])
>>> c = [x,x] # list of ... | python|numpy | 2 |
367,405 | 39,771,274 | Import Pandas Into Python | <p>I just installed Python 3.5.2. I am working in the shell/IDLE environment and attempting to import Pandas. </p>
<p>However when I write: import pandas </p>
<p>I get the following:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/bartogre/Desktop/Program1.py", line 1, in <module>
import... | <p>A bit of background: a system can have multiple Python installations. On Windows, each is a directory with python.exe and Lib/site-packages/. To use a package with a particular python.exe, you must install into the corresponding site-packages.</p>
<p>In your case, 'python' invokes 'C:\Program Files (x86)\Anaconda... | python|pandas|importerror|python-3.5 | 1 |
367,406 | 39,720,177 | numpy.cross and similiar functions: Do they allocate a new array on every call? | <p>When I use <code>numpy.cross</code>, it will <em>return</em> an array with the results. There's no way to compute <em>into</em> an existing array. The same holds for other functions.</p>
<ol>
<li>Isn't it extremely inefficient to allocate a new array upon each call?</li>
<li>If so, is there a way to speed it up?</l... | <p>There is an overhead with the function <code>np.cross</code> as it creates a new NumPy array. You can do <code>x = np.cross(x, y)</code> but it will not suppress the overhead.</p>
<p>If you have a program where this is actually a problem (as diagnosed by profiling the program, for instance), you are better off turn... | python|numpy | 2 |
367,407 | 39,508,021 | Pandas: Set variable to value in cell, if another cell on same row contains string | <p>Let's say my Pandas <code>DataFrame</code> contains the following:</p>
<pre><code>Row Firstname Middlename Lastname
…
10 Roy G. Biv
11 Cnyder M. Uk
12 Pan T. One
…
</code></pre>
<p>If a cell in <code>["Lastname"]</code> contains <code>"Biv"</code>, ... | <p>If you want just the scalar value then you can access the first value in the result array and assign this:</p>
<pre><code>firstname = df.loc[df['Lastname'].str.contains('Biv'), 'Firstname'][0]
</code></pre>
<p>Note that really you should check if it's not empty though:</p>
<pre><code>if len(df.loc[df['Lastname'].... | python|pandas | 1 |
367,408 | 44,232,900 | How to balance classes in a numpy array? | <p>I have 2 numpy arrays as follows:</p>
<p><strong><code>images</code></strong> contains the names of image files (<code>images.shape</code> is (N, 3, 128, 128)):
<code>
image_1.jpg
image_2.jpg
image_3.jpg
image_4.jpg
</code></p>
<p><strong><code>labels</code></strong> contains the corresponding labels (0-3) (<code>... | <p>You could use <code>np.random.choice</code> to create an integer-valued mask which you could apply to your labels and images to balance the dataset:</p>
<pre><code>n = 2488
mask = np.hstack([np.random.choice(np.where(labels == l)[0], n, replace=False)
for l in np.unique(labels)])
</code></pre... | python|arrays|numpy|multidimensional-array | 4 |
367,409 | 44,277,943 | How do I calculate the probability of every value in a dataframe column quickly in Python? | <p>I want to calculate the probability of all the data in a column dataframe according to its own distribution.For example,my data like this:</p>
<pre><code> data
0 1
1 1
2 2
3 3
4 2
5 2
6 7
7 8
8 3
9 4
10 1
</code></pre>
<p>And the output I expect like this:</... | <p>Its own distribution does not mean <code>kde</code>. You can use <code>value_counts</code> with <code>normalize=True</code></p>
<pre><code>df.assign(pro=df.data.map(df.data.value_counts(normalize=True)))
data pro
0 1 0.272727
1 1 0.272727
2 2 0.272727
3 3 0.181818
4 2 0.272... | python-3.x|pandas|probability|distribution | 6 |
367,410 | 44,055,916 | Left String Function on Pandas Dataframe that Finds Character Location to Stop | <p>I have a Pandas dataframe that has a column that looks like this: </p>
<pre><code>>>> df_clean['my_column']
my_column
0 COMPANY1 VIDEO
1 COMPANY2 VIDEO
2 COMPANY1 VIDEO
</code></pre>
<p>I want to create a new column <code>(df_clean['my_column_trim'] = pd.DataFrame(df_raw['my_column']...<... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>.str.split</code></a> to split on whitespace, then <code>.str[0]</code> to get the first item of the split:</p>
<pre><code>df_clean['my_column_trim'] = df_clean['my_column'].str.split().s... | python|string|pandas | 4 |
367,411 | 44,214,076 | Delete rows based on char in the index string | <p>I have the following dataframe:</p>
<pre><code>df = pd.DataFrame(np.random.randn(4, 1), index=['mark13', 'luisgimenez', 'miguel72', 'luis34'],columns=['probability'])
probability
mark13 -1.054687
luisgimenez 0.081224
miguel72 -0.893619
luis34 -1.576941
</code></pre>
<p>I wo... | <p>You can use the str accessor to check if the last character is a number:</p>
<pre><code>df[df.index.str[-1].str.isdigit()]
Out:
probability
mark13 -0.350466
miguel72 1.220434
luis34 -0.962123
</code></pre> | pandas | 1 |
367,412 | 44,085,769 | Use conda environment in VS2017 | <p>I want to use a conda virtual environment with VS2017, but I get the error that it could not identify a virtual environment in the selected path. The screenshot below is not mine, but it's from this <a href="https://stackoverflow.com/questions/40813236/add-cntk-virtualenv-to-visual-studio-python-project">SO question... | <p>Oops, it turns out that this <a href="https://stackoverflow.com/a/40839135/1161635">SO answer</a> is correct after all. It works after creating a custom environment within Visual Studio.</p> | python|tensorflow|anaconda|visual-studio-2017|pvts | 1 |
367,413 | 44,022,520 | Pandas: group with 10T but to have a 00:11:00 format | <p>after this </p>
<pre><code>grouper = pd.Grouper(key='datetime', freq='10T')
</code></pre>
<p>I will have datetime groups like </p>
<pre><code>2017-05-17 13:20:00
2017-05-17 13:30:00
</code></pre>
<p>I want to archieve this particular format:</p>
<pre><code>2017-05-17 13:21:00
2017-05-17 13:31:00
</code></pre>
... | <p>It seems you need parameter <code>base</code> which can found in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a>:</p>
<pre><code>rng = pd.date_range('2017-05-17 13:21:00', periods=10, freq='10T')
df = pd.DataFrame({'d... | python|pandas | 1 |
367,414 | 44,369,389 | Python DataFrame Copy | <p>I am trying to create a new dataframe based on some criteria based on an original dataframe. </p>
<pre><code>df = pandas.io.sql.read_sql(sql, conn)
Count_Row = df.shape[0]
for j in range(Count_Row - 1):
if df.iloc[j, 0] == df.iloc[j + 1, 0]:
print(df.iloc[j, 2] + df.iloc[j + 1, 2], df.iloc[j, 4], df.i... | <p>Don't use a slow "for" loop to do this. Instead, generate a mask which is True for the elements you want, then select those elements:</p>
<pre><code>matches = df.iloc[:-1,0] == df.iloc[1:,0]
new_df = df.iloc[:-1][matches]
</code></pre>
<p>This will be 10-100x faster than the approach you had before.</p>
<p>At th... | python|pandas | 1 |
367,415 | 44,221,473 | tensorflow string_input_producer gives empty queue | <p>I'm trying to make a queue in tensorflow from a list of file names. The list was made but it seems that the string input producer returned an empty queue. There might be other reasons that the code doesn't work. Below is the code:</p>
<pre><code>sess = tf.InteractiveSession()
def read_my_file_format(filename_queue... | <p>If you could provide the error message, it would help.</p>
<p>In the same time, here are a few remarks on your code:</p>
<ul>
<li>The method <code>input_pipeline</code> defines the TensorFlow operators associated to your queue and add them to the graph so you should call it before calling <code>sess.run(tf.global_... | python|tensorflow|computer-vision|deep-learning|image-recognition | 0 |
367,416 | 44,352,640 | Get CSV from Tensorflow summaries | <p>I have some very large tensorflow summaries. If these are plotted using tensorboard, I can download CSV files from them.</p>
<p>However, plotting these using tensorboard would take a very long time. I found in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tensorboard/README.md" rel="nofol... | <p>One possible way of doing it would be like this:</p>
<pre><code>from tensorboard.backend.event_processing import event_accumulator
import numpy as np
import pandas as pd
import sys
def create_csv(inpath, outpath):
sg = {event_accumulator.COMPRESSED_HISTOGRAMS: 1,
event_accumulator.IMAGES: 1,
... | python|csv|tensorflow | 2 |
367,417 | 44,012,431 | Pandas element-wise min max against a series along one axis | <p>I have a Dataframe:</p>
<pre><code>df =
A B C D
DATA_DATE
20170103 5.0 3.0 NaN NaN
20170104 NaN NaN NaN 1.0
20170105 1.0 NaN 2.0 3.0
</code></pre>
<p>And I have a series</p>
<pre><code>s =
DATA_DATE
20170103 4.0
20170104 0.0
20170105 2.2
</code></pre>
<p>I'd like t... | <p>Data:</p>
<pre><code>In [135]: df
Out[135]:
A B C D
DATA_DATE
20170103 5.0 3.0 NaN NaN
20170104 NaN NaN NaN 1.0
20170105 1.0 NaN 2.0 3.0
In [136]: s
Out[136]:
20170103 4.0
20170104 0.0
20170105 2.2
Name: DATA_DATE, dtype: float64
</code></pre>
<p>Solution:</p>
<pre><... | pandas|dataframe|max|min|elementwise-operations | 8 |
367,418 | 44,267,616 | bazel build tensorflow/python/tools:strip_unused compilation failure | <p>I am trying to run this bazel command from within my docker image</p>
<pre><code>docker run -it gcr.io/tensorflow/tensorflow:latest-devel
cd /tensorflow
bazel build tensorflow/python/tools:strip_unused
</code></pre>
<p>However it fails with this error:</p>
<pre><code>ERROR: /tensorflow/tensorflow/core/kernels/BU... | <p>This is probably because you ran out of RAM. Please post the output of <code>dmesg | tail</code> right after the build fails.</p> | tensorflow|bazel | 0 |
367,419 | 44,102,532 | Problems importing pandas.plotting | <p>When I import pandas, everything is fine and working. Yet, when I try to import something from <code>pandas.plotting</code> im getting an error. What could be the source of this? </p>
<p>Here is how the output looks like:</p>
<pre><code>>>> import pandas
>>> from pandas.plotting import scatter_ma... | <p>Unfortunately, it looks as though there has been some confusion around the movement of that module. The <code>plotting</code> module has been moved from <code>pandas.tools.plotting</code> to <code>pandas.plotting</code>. The difficulty is most likely stemming from the fact that as of version 0.19, the <code>pandas.p... | python|pandas | 53 |
367,420 | 44,282,185 | Pandas: need to create dataframe for weekly search per event occurrence | <p>If I have this events dataframe <code>df_e</code> below:</p>
<pre><code>|------|------------|-------|
| group| event date | count |
| x123 | 2016-01-06 | 1 |
| | 2016-01-08 | 10 |
| | 2016-02-15 | 9 |
| | 2016-05-22 | 6 |
| | 2016-05-29 | 2 |
| | 2016-05-31 | 6 |
| ... | <p>I'm not really sure if I get you but group one is not related to group two, right? if that's the case I think what you want is something like this:</p>
<pre><code>import pandas as pd
df_group1 = df_group1.set_index('event date')
df_group1.index = pd.to_datetime(df_group1.index) #convert the index to datetime so y... | pandas | 0 |
367,421 | 44,024,268 | MSBuild: 'error MSB6006: "cmd.exe" exited with code 1.' | <p>When attempting to <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/cmake" rel="nofollow noreferrer">build TensorFlow with CMake and MSBuild</a> on Windows 10, I get the following error when running MSBuild:</p>
<pre><code>"C:\work\tensorflow\tensorflow\contrib\cmake\build\tf_tutoria... | <p>This error commonly happens because the default cmake install location requires admin privileges (normally C:/Program Files/).</p>
<p>There are two simple ways around this:</p>
<p>Run visual studio as Administrator
Override the CMAKE_INSTALL_PREFIX variable to point somewhere not requiring admin privileges
Persona... | tensorflow|msbuild|cmake|windows-10 | 2 |
367,422 | 44,176,474 | About use keras for multi-label classification | <p>I try to train a multi-labels classifier, I used sigmoid units in the output layer and then use "binary_crossentrpy" loss. Current problem is the results of the training and testing were ideal, values of loss and accuracy were great.But when I used model.predict() predicted label, the output don't match the real lab... | <p>Have you tried to filter the values based on a threshold?</p>
<pre><code>pred = model.predict(x_test)
pred[pred>=0.5] = 1
pred[pred<0.5] = 0
print(pred[0:5])
</code></pre> | tensorflow|keras | 0 |
367,423 | 44,294,319 | Python - Pandas won't import because numpy version is incompatible. But numpy won't update | <p>I had to re-install anaconda and Jupyter now I can't import pandas in Jupyter notebook. It says to upgrade numpy to 1.7.0. Have done this, but problem still persists</p>
<p>This is the error:</p>
<pre><code>---------------------------------------------------------------------------
ImportError ... | <p>It looks like you don't have your path setup correctly. You are not linking to the anaconda distribution. Make sure you have your <code>.bash_profile</code> file is correctly setup--assuming you're on a bash shell. Add this line in your <code>.bash_profile</code> if not there:</p>
<pre><code># added by Anaconda3 4.... | python|pandas|numpy|anaconda|jupyter | 0 |
367,424 | 44,210,376 | Binary matrix, where 1 is located at the maximum value along the row | <p>Let say I have a tensor</p>
<pre><code>[[0.3, 0.7],
[0.9, 0.1]]
</code></pre>
<p>How can I create a tensor with 1.0 at maximum positions along axis, so the result should be for axis=1</p>
<pre><code>[[0., 1.],
[1., 0.]]
</code></pre>
<p>In my case first dimension is a batch size, so it's '?'</p> | <p>Both of the answers presented are inefficient in terms of memory/compute.</p>
<p>You can calculate it in linear time (no-matmul) without allocating unnecessary memory in just one line:</p>
<pre><code>tf.cast(tf.equal(a, tf.reshape(tf.reduce_max(a, axis=1), (-1, 1))), tf.int16)
</code></pre>
<p>The full example is... | tensorflow | 1 |
367,425 | 44,355,270 | plot 3d in python using three lists | <p>I followed this <a href="http://matplotlib.org/examples/mplot3d/surface3d_demo.html" rel="nofollow noreferrer">link</a> to plot the 3D figure.
My problem is I have already 3 lists for X, Y, Z</p>
<blockquote>
<p>X.shape (n,) , Y.shape (n,) , Z.shape (n,)</p>
</blockquote>
<p>How to pass these lists into <code>... | <p>The solution will depend on how the data is organized. </p>
<h3>Data on regular grid</h3>
<p>If the <code>X</code> and <code>Y</code> data already define a grid, they can be easily reshaped to a quadrilateral grid. E.g.</p>
<pre><code>#x y z
4 1 3
6 1 8
8 1 -9
4 2 10
6 2 -1
8 2 -8
4 3 8
6 3 -... | python|numpy|matplotlib|mplot3d | 2 |
367,426 | 44,295,919 | Elementwise comparison to None with ndarray of object dtype | <pre><code>x = np.empty([2], dtype=object)
> array([None, None], dtype=object)
x[0] = 'a'
> array(['a', None], dtype=object)
</code></pre>
<p>I'm trying to get a boolean array <code>[False, True]</code> from this object typed <code>ndarray</code> where the object type is <code>None</code>. </p>
<p>Things that ... | <p>In NumPy 1.12 and earlier, you'll need to explicitly call <code>numpy.equal</code> to get a broadcasted equality comparison. Leave a comment, so future readers understand why you're doing it:</p>
<pre><code># Comparisons to None with == don't broadcast (yet, as of NumPy 1.12).
# We need to use numpy.equal explicitl... | python|arrays|numpy | 8 |
367,427 | 44,365,209 | Generate a pandas dataframe from ordereddict? | <p>I am trying to create a pandas dataframe from an ordereddict to preserve the order of the values. But for some reason after creating the dataframe the fields are messed up again.</p>
<p>Here's the list of ordereddicts:</p>
<pre><code>[OrderedDict([
('key_a',
'value_a'),
('key_b',
'value_b'),
]),
OrderedDic... | <p>Following <a href="https://stackoverflow.com/questions/33752819/pandas-dataframe-from-dict-not-preserving-order-using-ordereddict">this</a> answer, you need to explicitly specify your column order:</p>
<pre><code>df = pd.DataFrame(orderedDictList, columns=orderedDictList.keys())
</code></pre>
<p>Of course, first y... | python|pandas|dataframe|ordereddictionary | 32 |
367,428 | 44,291,891 | How to efficiently store variable number of scipy sparse.csr_matrix in memory? | <p>I have around 10,000 sparse matrices each with size 50,000x5 with 0.0004 density on average.
For each loop (10000 times), I'm calculating numpy array and converting it into csr_matrix and appending that to a list. But memory consumption is as high as appending numpy arrays but not as appending csr_matrices.</p>
<p>... | <p>For the matrix:</p>
<pre><code><49688x5 sparse matrix of type '<type 'numpy.float64'>'
with 65 stored elements in Compressed Sparse Row format>
</code></pre>
<p>in <code>coo</code> format, the key attributes are <code>row</code>, <code>col</code> and <code>data</code>, all with 65 elements. <code>data... | python|numpy|scipy|sparse-matrix | 1 |
367,429 | 44,048,829 | How to round a numpy vectorize function returned list? | <p>I am using <code>numpy.vectorize()</code> for my function in order to apply the function to an array, it works fine:</p>
<pre><code>X = [-10000, -1000, -100, -10, -1, 0, 1, 10, 100, 1000, 10000]
def softplus(x):
return np.logaddexp(1.0,x)
y=numpy.vectorize(softplus)
</code></pre>
<p>The problem is that I want ... | <p>You don't need <code>vectorize</code> here because <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logaddexp.html" rel="nofollow noreferrer"><code>np.logaddexp</code></a> is already a vectorized function (as is <code>np.around</code>). But the <code>vectorize</code> gives the correct result:</p>
... | python|arrays|numpy | 2 |
367,430 | 43,984,857 | pandas(dataframe) select data | <h1>Hello guys,</h1>
<p>I use dataframe to create two tables(A and B) and both have the same columns.
(1st column is 'ID' and one table might have more than one row with same ID)</p>
<p>I want to create a new table(C) based on A and some rows from B.
If the ID in table B also occur in A then add this row into C.</p>
<h... | <p>Looking at what you're doing it will be more performant to just do:</p>
<pre><code>C_table = pd.concat([C_table, B_table[B_table['ID'].isin(A_table['ID'])]])
</code></pre>
<p>So firstly the inner statement:</p>
<pre><code>B_table[B_table['ID'].isin(A_table['ID'])]
</code></pre>
<p>Filters out the rows in <code>B... | python|pandas|dataframe | 0 |
367,431 | 44,021,004 | How to get the indices of the float numbers in the array after sorting with numpy partition | <p>I was trying to sort the array list using <code>np.partition</code> but it sorts the list wrongly. I think the reason is the float numbers in the list. How can I sort the array list consisting float numbers using <code>np.partition</code> and get the indices of the elements?</p>
<pre><code>x = np.array([0.056669, 0... | <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.partition.html" rel="nofollow noreferrer"><code>np.partition</code></a> just "partitions" your elements, it doesn't do a full sort. It's for "getting the lowest/highest <code>k</code> elements"-like operations. From the docs:</p>... | python|sorting|numpy | 1 |
367,432 | 44,147,701 | Split Pandas DataFrame into multiple columns | <p>I am new to Pandas and I have been trying to achieve the following but is struggling. Hope someone could assist.</p>
<p>I currently have the following Panda Dataframe</p>
<pre><code>Out[10]:
0.00632 18.00 2.310 0 0.5380 6.5750 65.20 4.0900 1 296.0 15.30 396.90 4.98 24.00
0 0.00632 18.00 ... | <p>It seems you dont change default separator (<code>,</code>) in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a>.</p>
<p>Solution is for tab separator:</p>
<pre><code>names = ['CRIM','ZN','INDUS','CHAS','NOX','RM','AGE','DIS','R... | python|pandas | 3 |
367,433 | 44,217,783 | python pandas dataframe merge | <p>I want to merge some dataframe from csv files using for loop in python. But the result is empty. Why is that so? Here is my code.</p>
<pre><code>result = pandas.DataFrame(columns = ['col_A', 'col_B'])
for i in range(0, 5):
#col_A is integer for numbering, col_B is float in range 0 to 1
temp = pandas.DataFra... | <p>You need to store the result of the merge:</p>
<pre><code>result = result.merge(temp)
</code></pre>
<p>From the (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">DOCS</a></p>
<blockquote>
<p>Returns: </p>
<p>merged : DataFrame</p>
<... | python|pandas|dataframe | 1 |
367,434 | 69,354,451 | How to add a button to a Plotly Express graph to update a specific value? | <h3>What I'm Trying To Do...</h3>
<p>I am trying to keep the formatting of a Plotly Express Scatterplot for data from the happiness report (2018). I simply want to create a button that can change the x-axis value between certain columns in a pandas dataframe (e.g. "GDP per Capita", "Social Support",... | <ul>
<li>there is a core concept with this approach. Need to be able to identify the traces that belong to a column. In this case where <strong>color</strong> is a categorical there are multiple traces per column</li>
<li>added a synthetic column to dataframe dynamically and included in <strong>hoverdata</strong> <em... | python|pandas|plotly | 1 |
367,435 | 69,443,466 | access an element inside another element serie and index | <p>i have an issue, i have a serie (pandas.core.series.Series) and inside that serie i have an index(?¡) (pandas.core.indexes.base.Index), how do i access the element in the index part?</p>
<pre><code>IPSA_COL[10]
</code></pre>
<p>Index(['Date', 'Open CHILE', 'High CHILE', 'Low CHILE', 'Adj Close CHILE',
'Volume CHILE... | <p>I believe pandas indexes are subscriptable, just like regular python lists. So if you wanted the third element in the list you have above, try:</p>
<p><code>IPSA_COL[10][2]</code></p> | python|pandas | 0 |
367,436 | 69,521,671 | Getting values from pandas dataframe in a particular order | <p>What would be the most efficient way to create a list of the labels from the dataframe below in the order of mylist?</p>
<pre><code>import numpy as np
import pandas as pd
mylist = ['a1.jpeg','a2.jpeg','b1.jpeg','b2.jpeg','c1.jpeg','c2.jpeg']
dat = np.array([(1, 2, 1, 1, 2, 2), ('a2jpeg', 'a1jpeg', 'c2jpeg'... | <p>Just use <code>sort_values</code>:</p>
<pre><code>>>> df.sort_values('filenames')
labels filenames
1 2 a1jpeg
0 1 a2jpeg
4 2 b1jpeg
3 1 b2jpeg
5 2 c1jpeg
2 1 c2jpeg
>>>
</code></pre>
<p>To convert to list:</p>
<pre><code>>>> df['filenames'... | python|pandas|numpy | 2 |
367,437 | 69,643,397 | How do I combine multiple NumPy boolean arrays? | <p>I have a two-dimensional (2D) array that contains many one-dimensional (1D) arrays of random boolean values.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def random_array_of_bools():
return np.random.choice(a=[False, True], size=5)
boolean_arrays = np.array([
random_array_of_bools(),... | <p>Use <code>min</code> with <code>axis=0</code>:</p>
<pre><code>>>> boolean_array.min(axis=0)
array([False, False, True, False, False])
>>>
</code></pre> | python|arrays|numpy | 2 |
367,438 | 69,490,570 | Is there a way to select the upper end of a bin using pandas.cut() function? | <p>I have a question regarding the bins in pandas. My code so far looks like this:</p>
<pre class="lang-py prettyprint-override"><code>africa_uhc = pd.cut(africa[("Universal health coverage (UHC) service coverage index")]/100, [0, 0.25, 0.50, 0.75, 1])
</code></pre>
<p>which prints out</p>
<pre><code>29 (... | <p>You can use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>labels</code></a> argument to control what to return.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'UHC': [60,30,60,70,40,50,70,10]})
bins = [0, 0.25, 0.50, 0.75, 1]
print(pd.cut(df.UHC/1... | python|pandas | 1 |
367,439 | 69,365,314 | How to feed the input images into ensemble of DNN models? | <p>I am trying to ensemble 5 transfer learning pre-trained DNN models (the base models trained on imagenet) using the code below</p>
<pre><code>def define_stacked_model(members):
# update all layers in all models to not be trainable
for i in range(len(members)):
model = members[i]
for layer in m... | <p>Well you can make this work only by changing this <code>history = stacked_model.fit(x = stacked_img_data, y = target_val, epochs=10)</code> to this</p>
<pre><code> history = stacked_model.fit(x = [img_data[0:300],img_data[0:300],img_data[0:300],img_data[0:300],img_data[0:300]], y = target_val, epochs=10)
</code></... | python|tensorflow | 1 |
367,440 | 69,324,901 | Problem adding column to Pandas DataFrame | <p>I have a Dataframe of raw data:</p>
<pre><code>df
Out:
Date_time 10a 10b 10c 40a 40b 40c 100a 100b 100c
120 2019-02-04 16:00:00 26.7 26.9 NaN 26.7 NaN NaN 24.9 NaN NaN
121 2019-02-04 17:00:00 23.4 24.0 23.5 24.3 24.1 24.0 25.1 24.8 25.1
122 2019-02-04 18:00:00 23... | <p>It was the Series issue. Turns out writing out the question helped me realise the issue! My solution was altering the initial creation of means using to_frame():</p>
<pre><code>means = df['Date_time'].copy().to_frame()
</code></pre>
<p>I'll leave the question up in case anyone else is having a similar issue, to save... | python|pandas | 2 |
367,441 | 69,457,604 | Pandas - using str.contains to match string | <p>I have a column in my pandas df that looks like this:</p>
<pre><code>Cycle 1 (0 h)
A
B
C
Cycle 2 (0 h 43 min)
A
B
C
</code></pre>
<p>I'm trying to match 'Cycle' and extract the digits. Ideally, I'd like for my output to look like this:</p>
<pre><code>... | <p>You can use</p>
<pre class="lang-py prettyprint-override"><code>rx = r'^Cycle\s+\d+\s+\((\d+)(?:\s*\w+\s*(\d+))?.*'
df['1'] = df['1'].str.replace(rx, lambda x: f'{x.group(1)},{x.group(2)}' if x.group(2) else x.group(1), regex=True)
</code></pre>
<p>See the <a href="https://regex101.com/r/6Ahe0K/2" rel="nofollow nore... | python|regex|pandas | 2 |
367,442 | 69,327,593 | How to get a 2D NumPy array with value 1 at indices represented by values in 1D NumPy array (Python) | <p>How to get a 2D np.array with value 1 at indices represented by values in 1D np.array in Python.</p>
<p><strong>Example:</strong></p>
<pre><code>[1, 2, 5, 1, 2]
</code></pre>
<p>should be converted to</p>
<pre><code>[[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, ... | <p>You can create a array with zeros using <a href="https://numpy.org/doc/stable/reference/generated/numpy.zeros.html" rel="noreferrer"><code>np.zeros</code></a>. The shape the array should be <code>(len(1D array), max(1D array)+1)</code>. Then use NumPy's indexing.</p>
<pre><code>idx = [1, 2, 5, 1, 2]
shape = (len(idx... | python|arrays|numpy | 8 |
367,443 | 69,366,407 | Append array to each element of other array in python | <p>I have this array:</p>
<pre><code>a = np.array(([11,12,13],[21,22,23],[31,32,33],[41,42,43]))
b = np.array([88,99])
</code></pre>
<p>I want to get:</p>
<pre><code>c = np.array(([11,12,13,88,99],[21,22,23,88,99],[31,32,33,88,99],[41,42,43,88,99]))
</code></pre>
<p>How can I do that? Thanks</p> | <p>Assuming you have numpy arrays, you could do:</p>
<pre><code>import numpy as np
np.concatenate([a, np.tile(b, (len(a), 1))], 1)
</code></pre>
<p>Or, using <code>numpy.broadcast_to</code>:</p>
<pre><code>np.concatenate([a, np.broadcast_to(b, (len(a), len(b)))], 1)
</code></pre>
<p>output:</p>
<pre><code>array([[11, 1... | python|numpy | 3 |
367,444 | 69,665,883 | Fast conversion of c char numpy array to list of python strings | <p>I'm making an interface between Python and Fortran code with Cython. One part of that is retrieving arrays of strings. In Fortran,</p>
<pre><code>character(len=3) :: str_array(:)
</code></pre>
<p>For the sake of this example, suppose <code>str_array</code> contains the following</p>
<pre><code>allocate(str_array(2))... | <p>Basically, avoid iteration over the array. This is a bit of a shot in the dark, but try:</p>
<pre><code>bs = c_str_arr.tobytes()
str_arr = [bs[i:i+str_len].decode() for i in range(0, str_len*arr_len, str_len)]
</code></pre> | python|numpy|cython|numpy-ndarray | 1 |
367,445 | 69,381,912 | Classify a value under certain conditions in pandas dataframe | <p>I have this dataframe:</p>
<pre><code>value limit_1 limit_2 limit_3 limit_4
10 2 3 7 10
11 5 6 11 13
2 0.3 0.9 2.01 2.99
</code></pre>
<p>I want to add another column called <code>class</code> that classifies the... | <p>We can use the <code>rank</code> method over the column axis (axis=1):</p>
<pre><code>df["CLASS"] = df.rank(axis=1, method="first").iloc[:, 0].astype(int)
</code></pre>
<pre><code> value limit_1 limit_2 limit_3 limi_4 CLASS
0 10 2.0 3.0 7.00 10.00 4
1 11 5... | pandas | 3 |
367,446 | 69,404,067 | Sum rows based on columns inside pandas dataframe | <p>I am quite new to pandas, but I use python at a good level.</p>
<p>I have a pandas dataframe which is organized as follows</p>
<pre><code>idrun idbasin time q
-192540 1 0 0
-192540 1 1 0.5
...
-192540 2 0 0
-192540 2 1 1
...
-192540 3 ... | <p>You can replace values of tuple by first value of tuple in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html" rel="nofollow noreferrer"><code>Series.mask</code></a> and then aggregate <code>sum</code>:</p>
<pre><code>tup = (1, 2)
df['idbasin'] = df['idbasin'].mask(df['idbasi... | python|python-3.x|pandas|dataframe|sum | 1 |
367,447 | 69,541,305 | How to combine two YOLOv5 models? | <p>I have two models, first one is for classifying images and crop to classes. <br>
After cropping classes from an image I send it to the second model, which classifies digits. <br>Both of them Yolo v5 models. <br>
But the problem is that I can't send the second one directly from GPU. <br>
First I need to crop, I will ... | <p>You will need to modify the source code for the model architecture to prevent the first model's outputs from being written as numpy type and instead output a pytorch tensor. Barring this, there is no way to prevent the GPU->CPU->GPU transfer.</p> | python|pytorch|yolo|yolov5 | 0 |
367,448 | 69,525,248 | Pandas dataframe 3d visualization with different colors | <p>Imagine a dataframe like this:</p>
<pre><code>i X Y Z label
1 23 45 23 0
2 56 67 24 0
3 34 87 25 0
4 43 78 26 0
5 45 45 37 1
6 34 98 38 1
7 23 45 39 1
8 34 76 40 1
9 54 87 41 1
</code></pre>
<p>I know h... | <p>You can do this with set color for each <code>label</code> and plot <code>scatter</code> like below:</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
np.random.seed(365)
df = pd.DataFrame({
'X': np.random.rand(200),
'Y': np.random.... | python|pandas|matplotlib | 0 |
367,449 | 69,361,251 | How to log table information using python | <p>I have the following table (df):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>finished</td>
<td>1234</td>
</tr>
<tr>
<td>A2</td>
<td>ongoing</td>
<td>1235</td>
</tr>
<tr>
<td>A3</td>
<td>NaN</td>
<td>123... | <p>You need to convert your table to string with <code>to_string</code>:</p>
<pre><code>logging.warning(tab_not_finished.to_string())
</code></pre>
<p>eventually prepend a newline, or the header will be on the timestamps' line:</p>
<pre><code>logging.warning('\n'+tab_not_finished.to_string())
</code></pre> | python|pandas|dataframe|logging|timestamp | 1 |
367,450 | 69,341,814 | Pandas Dataframe Groupby join string whilst preserving order of strings | <p>Similar questions have been asked i.e <a href="https://stackoverflow.com/questions/60597305/concatenate-strings-from-multiple-rows-using-pandas-groupby-and-remove-duplicate">Concatenate strings from multiple rows using Pandas groupby and remove duplicates from the comma separated cell</a></p>
<p>I would like to conc... | <p>Use the <code>sort=False</code> parameter in <code>groupby</code> and <code>drop_duplicates</code> instead <code>set</code>:</p>
<pre><code>df = df.sort_values(
['id', 'order_column']
).groupby('id', sort=False).agg(
{
'channel': lambda x: ' > '.join(x.drop_duplicates()),
... | python|pandas|string|lambda|pandas-groupby | 3 |
367,451 | 69,417,565 | Tensorflow datasets for translation - how to use the WMT14 manual download? | <p>I am following the guide here: <a href="https://www.tensorflow.org/datasets/catalog/wmt14_translate" rel="nofollow noreferrer">https://www.tensorflow.org/datasets/catalog/wmt14_translate</a> , but I am running into problems trying to download the dataset, basically it takes forever to download. Regarding the "m... | <p>Yeah, it does take a very long time to download as even the dataset is huge(around 1.5 Gb). And no, you don't need to download the data manually, just wait till the code runs and u are good to go.</p>
<p>P.S. In my case I had to run the</p>
<blockquote>
<p>dataset = tfds.load('wmt14_translate/de-en',
split='test',sh... | python|tensorflow|translation|tensorflow-datasets | 0 |
367,452 | 69,602,686 | ValueError: could not broadcast input array from shape (480,640,3) into shape (480,640) | <p>So I'm trying to do fft, and here is my code</p>
<pre><code>def fftImage(img_gray, rows, cols):
rPadded = cv2.getOptimalDFTSize(rows)
cPadded = cv2.getOptimalDFTSize(cols)
imgPadded = np.zeros((rPadded, cPadded), dtype=np.float32)
imgPadded[:rows, :cols] = img_gray
img_fft = cv2.dft(imgPadded, fl... | <p>Number of elements in your input array must be equal to elements of output array. for example if you are reshaping a 3-dimentional picture from shape (480,640,3) into 2-dimentional picture, your output shape could be (1440,640) or something like that.
In another word 480<em>640</em>3 should be equal to (a,b) which h... | python|numpy|image-processing|valueerror | 0 |
367,453 | 69,299,917 | How to modify a column of a pandas dataframe? | <p>One column of my dataframe its in the following format:</p>
<pre><code>{'name': 'Aimo'}
{'name': 'Aimo'}
{'name': 'Aimo'}
{'name': 'Aimo'}
{'name': 'Aimo'}
</code></pre>
<p>The <code>dtype</code> of the column is <code>object</code>. How can I modify this column in the following format?</p>
<pre><code>Aimo
Aimo
Aimo... | <p>I guess if they're dictionaries, do:</p>
<pre><code>df['column'] = df['column'].str['name']
</code></pre>
<p>Or parse them as dictionaries if they are not already:</p>
<pre><code>from ast import literal_eval
df['column'] = df['column'].map(literal_eval).str['name']
</code></pre> | python|pandas | 2 |
367,454 | 69,599,086 | How to sort a 2D array of two columns, from large to small, by the second column? | <p>Here is my code:</p>
<pre><code>unique_models, count_of_models = np.unique(my_data_frame["model"], return_counts=True)
print(unique_models, count_of_models)
[' A1' ' A2' ' A3' ' A4' ' A5' ' A6' ' A7' ' A8' ' Q2' ' Q3' ' Q5' ' Q7' ' Q8' ' R8' ... | <p>Here you go:</p>
<pre><code>import numpy as np
data = [[' A1', '1347'],
[' A4', '1381'],
[' Q3', '1417'],
[' A3', '1929'],
[' A6', '748'],
[' Q2', '822'],
[' Q5', '877'],
[' A5', '882']]
indices = np.argsort([int(d[1]) for d in data])
sorted_data = [data[i] for i in indices[::-1]]
</code></pre> | python|numpy|sorting|multidimensional-array|2d | 1 |
367,455 | 69,629,230 | ValueError: could not convert string to float: 'A1' using np.loadtxt | <p>I have a program that needs to process a csv file. This file needs to be converted into a dataset. The example that I am working with comes from the popular python tutorial with the <a href="https://github.com/navicto/Discretization-MDLPC/blob/master/example.py" rel="nofollow noreferrer">iris data set</a>. I am tryi... | <p>The first line of your CSV file is an header that displays text. You should skip this line in order to operate <em>string to float</em> conversion.</p>
<p>Please check this out: <a href="https://stackoverflow.com/questions/17151210/numpy-loadtxt-skip-first-row">numpy loadtxt skip first row</a></p> | python|numpy | 0 |
367,456 | 69,645,987 | Improving time and memory of a script based on numpy | <p>I need to implement in Python the formula in the image. The set B is a set of real numbers -1 <= t <= 1. Also, F_2 is a set with the elements 0 and 1. y_i is the i-th element of $y$. This formula is part of an iterative part of my program. The number of iterations is about 10K (over x) and n is 32. I tried a p... | <p>This is not a full answer but here are some ideas for optimization.</p>
<ol>
<li><p>f(y) returns only 0 or 1, correct? If so, only compute the product where f(y)=1. When f(y)=0, the product calculation is wasted. This becomes very important if the probability of f(y)=1 is low, less so if not.</p>
</li>
<li><p>The... | python|numpy | 1 |
367,457 | 69,625,436 | "Equation without an equality (=) or inequality (>,<)" error due to user-defined functions in GEKKO | <p>I try to develop a code for a discrete optimization making use of a catalogue of data via GEKKO. Please see the code below: Whenever I add the part with pandas dataframe (df) in my constraint function (con) I receive the error <strong>"Equation without an equality (=) or inequality (>,<)"</strong>.</... | <p>Running the code and opening the run folder with <code>m.open_folder()</code> reveals the <code>gk_model0.apm</code> file that is used by APMonitor to compile the problem into byte-code for solution.</p>
<pre><code>Model
Variables
int_v1 = 0.01, <= 1, >= 0
int_v2 = 0.01, <= 1, >= 0
v3 = 0, &l... | python|pandas|dataframe|optimization|gekko | 0 |
367,458 | 69,413,536 | How to map many to one relationship between two Pandas dataframes? | <p>I am having trouble mapping a many-to-one relationship across two DataFrames. In my best attempts, I return unique rows with ambiguous group keys (there should just be 1, but instead I get multiple).</p>
<p>Consider my approach:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as ... | <p>If I understand correctly what you are trying to achieve, there are a few issues here. First of all <code>df_items</code> has "items" in mixed order (i.e. <code>"364740, 369904"</code> vs <code>"369904, 364740"</code> or <code>"345262"</code> which appears by itself and withi... | python|pandas|many-to-one | 0 |
367,459 | 69,635,362 | Speed up millions of regex replacements in Dataframe | <p>I have:</p>
<ul>
<li><p>A location list of about 40k bigram/trigram words.<br />
<code>['San Francisco CA', 'Oakland CA', 'San Diego CA',...]</code></p>
</li>
<li><p>A Pandas DataFrame with millions of rows.</p>
</li>
</ul>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>string_column</th>
<... | <p>Use <a href="https://trrex.readthedocs.io/en/latest/" rel="nofollow noreferrer">trrex</a>, it builds an equivalent pattern as the same found in this <a href="https://stackoverflow.com/a/42789508/3832970">resource</a> (actually it is inspired by that answer):</p>
<pre><code>from random import choice
from string impor... | python|regex|pandas|performance|replace | 2 |
367,460 | 69,527,108 | How to transform list from database into dataframe? | <p>I have a following problem. My database returns a list:</p>
<pre><code>[Order(id=22617, frm=datetime.datetime(2020, 6, 1, 8, 0), to=datetime.datetime(2020, 6, 1, 10, 0), loc=Location(lat=14.491272455461, lng=50.130463596998), address='Makedonska 619/11, Praha', duration=600), datetime.datetime(2020, 6, 1, 11, 38, 46... | <p>Try this without guarantee of success:</p>
<pre><code>data = []
for order, time in zip(lst[::2], lst[1::2]):
data.append({'id': order.id, 'frm': order.frm, 'to': order.to,
'lat': order.loc.lat, 'lng': order.loc.lng,
'address': order.address, 'duration': order.duration,
... | python|pandas|database | 2 |
367,461 | 69,414,740 | python pandas avoiding dupulicated csv output | <p>I am using python, but I got a problem.</p>
<p>Ideally, I would like to have no duplicates, but if I make a csv file, the same words will be output.
How can I avoid duplication?
I am a beginner in programming, so please be gentle with me.
Thanks.</p>
<p><a href="https://i.stack.imgur.com/Q57JC.png" rel="nofollow nor... | <p>When you create the data frame using,</p>
<pre><code>df = pd.DataFrame(data=all_data)
</code></pre>
<p>you can check whether there are duplicates in the data frame by using,</p>
<pre><code>df.duplicated()
</code></pre>
<p>If there are duplicates, you can remove them by using</p>
<pre><code>df.drop_duplicates(subset=... | python|excel|pandas|csv|beautifulsoup | 0 |
367,462 | 69,584,828 | Match both dicitonary key-values with pandas dataframe rows | <p>I can match each row with each diciotnary key but I am wondering if there's a way I can get the related value (string) in a different column as well.</p>
<pre><code>import pandas as pd
entertainment_dict = {
"Food": ["McDonald", "Five Guys", "KFC"],
"Music": [&q... | <p>You could use:</p>
<pre><code>df['words'] = (df['text'].str.extractall(regex)
.groupby(level=0).first()
.apply(lambda x: ','.join(set(x).difference([None])),
axis=1)
)
</code></pre>
<p>output:</p>
<pre><code> ... | python|pandas | 1 |
367,463 | 69,499,108 | Missing values /pandas, Gender columns | <p>I have a dataset from a company with a gender column. This has a lot of missing values. I would like to replace all of this missing values , 50% female, 50 % male. How can I do it?</p>
<p><a href="https://i.stack.imgur.com/m0bvR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m0bvR.png" alt="enter... | <pre><code>from random import choice
mask = ~df["gender"].isin(['male','female'])
df.loc[mask,["gender"]] = df.loc[mask,["gender"]].applymap(lambda _: choice(["male","female"]))
</code></pre>
<p><strong>Update</strong></p>
<pre><code>from random import choice
mask = ... | python|pandas | 0 |
367,464 | 69,322,314 | Conditional column in pandas data frame | <p>I want to create a two new columns in below data frame.</p>
<pre><code>df = pd.DataFrame({"store_id": ["1", "1", "2", "2", "3", "3"],
"units": ["5 or less", "17", "5 or less", "5 or les... | <p>For column <code>sell</code> you can use <code>.apply()</code> with own function like</p>
<pre><code>def func(row):
if not row["unit_percent"]:
return 5
else:
return int(float(row["units"]) / float(row["unit_percent"]))
df['sell'] = df.apply(func, axis=1)
</code... | python|pandas | 0 |
367,465 | 69,620,683 | Explain - x = tf.Keras.layers.Dense(128, activation='relu')(pretrained_model.output) | <p>Could anyone explain this code in detail to me, I don't understand the highlighted part. I mean why did they put :</p>
<pre><code>x = tf.Keras.layers.Dense(128, activation='relu')(pretrained_model.output)
</code></pre>
<p>Dense()() followed by another bracket wat could be the reason?</p>
<p>Full Code:</p>
<pre><cod... | <p>In the first line, you define <em>inputs</em> to be equal to the inputs of the pretrained model. Then you define <em>x</em> to be equal to the pretrained models outputs (after applying an additional dense layer). Tensorflow now automatically recognizes, how <em>inputs</em> and <em>x</em> are connected. If we assume,... | tensorflow|deep-learning|computer-vision|artificial-intelligence | 0 |
367,466 | 69,462,930 | I can't create the confusion matrix | <p>I am trying to create the confusion matrix but I don't understand what the problem is.
Is it possible that I input incompatible things?</p>
<pre><code>score = model.evaluate(X_test, y_test, verbose=1)
print("Test Score:", score[0])
print("Test Accuracy:", score[1])
# %%
y_pred = model.predict(X... | <p>The y_true are the true labels, the predicted labels are saved in the variable predictions. X-test are the input labels the model has to predict on. Next we import confusion_matrix from sklearn and give it the y_true and y_pred values. Last we put in the output of the confusion matrix into the heatmap, you can modif... | python|deep-learning|sklearn-pandas | 0 |
367,467 | 69,409,596 | How can I create grid of coordinates from a center point in python? | <p>Is there a method to extract a grid of coordinates (purple dots) from a center coordinate, with a 100 meters distance between each coordinate for example?</p>
<p><a href="https://i.stack.imgur.com/ekzZ6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ekzZ6.png" alt="enter image description here" /></a></p>... | <p>Try this vectorized approach. The equation to offset a lat-long with meters is inspired from <a href="https://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters">this link</a> on stack exchange -</p>
<pre><code>import numpy as np
lat, lon = 50, -10 #center co... | python|python-3.x|numpy|shapely|pyproj | 6 |
367,468 | 69,542,196 | ufunc 'isnan' not supported for the input types | <p>I have a <code>df</code> where a particular col has several null values. I want to extract the first non null value.</p>
<pre><code>print(df.kst_erloes_stpfl.to_list())
[nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 'WH042700', 90510000, 90510000]
</code></pre>
<pre><code>import numpy as np
def n... | <p>The easiest way is to use pandas built-in function dropna:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
values = [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan, np.nan, np.nan, np.nan, 'WH042700', 90510000, 90510000]
df = pd.D... | python|pandas|dataframe|numpy|typeerror | 1 |
367,469 | 69,578,536 | How to calculate the mean of elements of a lists inside a dictionary in python? | <p>Hi I have a dict in python that looks like that:</p>
<pre><code>{{'NN3-001': {'diffe_1':[1,2,3,4],'mas_1':[10,20,30,40],'diffe_2':[5,6,7,8],'mas_2':[50,60,70,80]}},
{'NN3-002': {'diffe_1':[14,15,16,17],'mas_1':[100,200,300,400],'diffe_2':[18,19,20,21],'mas_2':[500,600,700,800]}}}
</code></pre>
<p>Where NN3-X is the ... | <p>First: your example is not correct dictionary. You missed <code>{}</code> in some places.</p>
<p>You should have</p>
<pre><code>{
'NN3-001': {'diffe_1':[1,2,3,4],'mas_1':[10,20,30,40],'diffe_2':[5,6,7,8],'mas_2':[50,60,70,80]},
'NN3-002': {'diffe_1':[14,15,16,17],'mas_1':[100,200,300,400],'diffe_2':[18,19,20... | python|numpy|dictionary|for-loop|mean | 1 |
367,470 | 69,465,571 | Rename strings in a python list using string matching based on existing strings | <p>Consider the following example of a list that contains dataframe headers based on a table I scraped:</p>
<pre><code>headers = ['0 Summary Compensation Table| for Fiscal Year End December 31, 2006| nan Name and Principal Position|', '1 Summary Compensation Table| for Fiscal Year End December 31, 2006| nan nan', ... | <p>You also have the case where both have already been used as header.</p>
<p>Try this:</p>
<pre><code>headers = df.columns.values.tolist()
words = ['Name','year','salary','bonus','Period']
for i, header in enumerate(headers):
for word in words:
if word in header:
headers[i]=word
wor... | python|pandas|web-scraping | 1 |
367,471 | 69,470,133 | how to achieve pandas dataframe in certain manner | <p>current data frame</p>
<p><a href="https://i.stack.imgur.com/4g7Yt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4g7Yt.png" alt="enter image description here" /></a></p>
<p>desired format
<a href="https://i.stack.imgur.com/0dLyN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/... | <p>Try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a>:</p>
<pre><code>output = df.pivot_table(["sale", "buy"], "users", "country") \
.swaplevel(axis=1) \
.sort_values... | python|python-3.x|pandas|dataframe | 2 |
367,472 | 69,655,526 | NLP on a xlsx worksheet - single column | <p>Hi I am seriously confused with how to conduct a NLP.
My goal is to conduct sentiment analysis on a 'Review' of a product.</p>
<pre><code>data = pd.read_excel('ProductData.xlsx')
print(data.dtypes)
Clothing ID int64
Age int64
Review Text object
</code></pre>
<p... | <p>You can use:</p>
<pre><code>blob = TextBlob(' '.join(df['Review Text'])
</code></pre>
<p>But this will combine all features as a single string. I don't know what type of processing you want to apply on each review. I think defining a function for processing and then using lambda to apply that function on each of you... | python|pandas|string|nlp|textblob | 0 |
367,473 | 69,590,932 | RuntimeWarning: overflow encountered in cosh -- Python. What does this mean? | <p>I'm running the following calculation:</p>
<pre><code>N = 2**15
dx = 0.1
x = np.arange(-N/2,N/2)
u0 = np.zeros([N, 1])
L = N * dx
x0 = x[1] + 2 * delta
delta = 15
while x0 < L - delta:
l1 = 1.267;
x0 = x0 + delta
r = 1/(l1*np.cosh(x)**2)
u0 = r + u0
</code></pre>
<p>Essentially, while x0< L -... | <p><code>cosh</code> grows very large:</p>
<pre><code>In [70]: np.cosh(2**10)
<ipython-input-70-c4511154ec1e>:1: RuntimeWarning: overflow encountered in cosh
np.cosh(2**10)
Out[70]: inf
</code></pre>
<p>Why is your <code>x</code> so wide? For most of the range, the inverse of this <code>cosh</code> will be 0.<... | python|numpy|runtime-error|hyperbolic-function | 1 |
367,474 | 69,514,006 | Python how to concatenate file names | <p>I'd like to include the month and year in my file name based on the month submitted.</p>
<p>I defined a variable that would be used to insert my file name.</p>
<pre><code> MTH = '20' + df['Month'].astype(str) + '/01'
MONTH = pd.to_datetime(MTH).dt.month
YEAR = pd.to_datetime(MTH).dt.year
</code></pre>
<p... | <p>You probably mean:</p>
<pre><code>df.to_excel(r'C:\OUTPUT\SALES_'+ MONTH.item() + '_' + YEAR.item() + '.xlsx', index=False )
</code></pre>
<p>Or:</p>
<pre><code>df.to_excel(r'C:\OUTPUT\SALES_'+ MONTH[0] + '_' + YEAR[0] + '.xlsx', index=False )
</code></pre> | python|pandas | 1 |
367,475 | 69,342,771 | AttributeError: 'NoneType' object has no attribute 'asfreq' | <p>I'm working on a small project trying to make a stock price prediction neural network with python on jupyter notebook.I have all the imports I need and I imported them correctly without an error. I also made sure that I'm importing the csv file correctly.</p>
<p>This is the cell that is giving me the error:</p>
<pre... | <p>Try to modify your function like below:</p>
<pre><code>PATH = "C:\\Users\\terry\\Documents\\jupyter projects\\stock\\"
HEADERS = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
def get_dataframe_from_csv(ticker):
return pd.read_csv(PATH + ticker + '.csv', index_col='DateTime',
... | python-3.x|pandas|dataframe|neural-network|jupyter-notebook | 1 |
367,476 | 69,543,416 | Creating a data frame from a list of lists with empty lists | <p>Suppose we have some lists <code>lst1</code> and <code>lst2</code> and we want to create a data frame from them. So:</p>
<pre><code>lst1 = ['Apple', 'Orange']
lst2 = []
</code></pre>
<p>When I try to create a data frame from these lists, it is empty:</p>
<pre><code>import pandas as pd
df_output = pd.DataFrame(list(z... | <p>There may be a more appropriate way to do this, but this'll work:</p>
<pre class="lang-py prettyprint-override"><code>>>> pd.DataFrame(map(pd.Series, (lst1, lst2)), index=["lst1", "lst2"]).T
lst1 lst2
0 Apple NaN
1 Orange NaN
</code></pre> | python|pandas|dataframe | 1 |
367,477 | 40,812,339 | How to train an lstm for speech recognition | <p>I'm trying to train lstm model for speech recognition but don't know what training data and target data to use. I'm using the <a href="http://www.openslr.org/12/" rel="noreferrer">LibriSpeech dataset</a> and it contains both audio files and their transcripts. At this point, I know the target data will be the transcr... | <p>To prepare the speech dataset for feeding into the LSTM model, you can see this post - <a href="https://stackoverflow.com/questions/34661818/building-speech-dataset-for-lstm-binary-classification">Building Speech Dataset for LSTM binary classification</a> and also the segment <a href="http://danielhnyk.cz/predicting... | tensorflow|speech-recognition|keras|speech-to-text|lstm | 14 |
367,478 | 40,974,914 | How to load images from LMDB in python without Caffe? | <p>I want to load my image and label data from a LMDB database I created. I assign a unique key to corresponding image-label pairs and add them to the LMDB (eg. image-000000001, label-000000001). While saving the images, I convert the numpy-array of the image to string using <code>image.tostring()</code>. Now while loa... | <pre><code>import lmdb
import cv2
import numpy as np
with lmdb.open(lmdb_dir,readonly=True).begin(write=False) as txn:
for idx,(key,val) in enumerate(txn.cursor()):
img = cv2.imdecode(np.fromstring(val,dtype=np.uint8),1)
</code></pre> | python|image|numpy|lmdb | 0 |
367,479 | 41,053,891 | Convert pandas dataframe to series | <p>Is there a way to convert pandas dataframe to series with multiindex? The dataframe's columns could be multi-indexed too.</p>
<p>Below works, but only for multiindex with labels.</p>
<pre><code>In [163]: d
Out[163]:
a 0 1
b 0 1 0 1
a 0 0 0 0
b 1 2 3 4
c 2 4 6 8
In [164]: d.stack(d.columns.na... | <p>I think you can use <code>nlevels</code> for find <code>length</code> of <code>levels</code> in <code>MultiIndex</code>, then create <code>range</code> with <code>stack</code>:</p>
<pre><code>print (d.columns.nlevels)
2
#for python 3 add `list`
print (list(range(d.columns.nlevels)))
[0, 1]
print (d.stack(list(ran... | python|pandas | 4 |
367,480 | 40,788,785 | How to average summaries over multiple batches? | <p>Assuming I have a bunch of summaries defined like:</p>
<pre class="lang-py prettyprint-override"><code>loss = ...
tf.scalar_summary("loss", loss)
# ...
summaries = tf.merge_all_summaries()
</code></pre>
<p>I can evaluate the <code>summaries</code> tensor every few steps on the training data and pass the result to ... | <p>Do the averaging of your measure in Python and create a new Summary object for each mean. Here is what I do:</p>
<pre class="lang-py prettyprint-override"><code>accuracies = []
# Calculate your measure over as many batches as you need
for batch in validation_set:
accuracies.append(sess.run([training_op]))
# Tak... | tensorflow | 49 |
367,481 | 41,135,894 | Python Pandas - Json to DataFrame | <p>I have a complicated Json File that looks like this:</p>
<pre><code>{
"User A" : {
"Obj1" : {
"key1": "val1",
"key2": "val2",
"key3": "val3",
}
"Obj2" : {
"key1": "val1",
"key2": "val2",
"key3": "val3"
}
}
"User B" : {
"Obj1" : {
... | <p>You can first read file to <code>dict</code>:</p>
<pre><code>with open('file.json') as data_file:
dd = json.load(data_file)
print(dd)
{'User B': {'Obj1': {'key2': 'val2', 'key4': 'val4', 'key1': 'val1', 'key3': 'val3'}},
'User A': {'Obj1': {'key2': 'val2', 'key1': 'val1', 'key3': 'val3'},
'Obj2': {'key2'... | python|json|pandas|dataframe | 3 |
367,482 | 41,225,408 | Converting dictionary with tuple key (key1,key2) into dataframe, when key1 is the index and key2 ,value is columns | <p>I have the following Dictionary:<code>dict = {('one','A'):8,('one','B'):19,('one','D'):29,('two','C'):18,('two','A'):10,('two','B'):4,('two','D'):2,('six','C'):4,('six','A'):4,('six','B'):4}</code></p>
<p>I convert it to dataFrame looking like:</p>
<pre><code> Score
one A 8
B 19
D 29
t... | <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a>:</p>
<pre><code>d = {('one','A'):8,('one','B'):19,('one','D'):29,('two','C'):18,
('two','A'):10,('two','B'):4,('two','D'):2,('six','C'):4,
('six','A'... | python-2.7|pandas|dictionary|dataframe|multi-index | 1 |
367,483 | 40,848,371 | how to understand the output of tf.nn.top_k() from tensorflow | <p>I used tf.nn.top_k()function from tensorflow to use the model's softmax probabilities to visualize the certainty of its predictions with 5 new images and with k=5. I have an output as follows which I am not sure how to exactly interpret. Could anyone explain the output please.</p>
<pre><code>TopKV2(values=array([[ ... | <p>From the <a href="https://www.tensorflow.org/api_docs/python/tf/nn/top_k" rel="nofollow noreferrer">documentation</a>, it returns two tensors: the first with the top K value and the second with the indices of these values in the original tensor.</p>
<p>So for your data what I see is that the original tensor is alwa... | tensorflow | 4 |
367,484 | 41,031,186 | What's the differences between a numpy matrix and a numpy.matrixlib.defmatrix.matrix? | <p>I read in a csv file and did some manipulations, and got an object x. When I use <code>type(x)</code>, it returns <code>numpy.matrixlib.defmatrix.matrix</code>. I have never seen this type before and wondering if there is any difference between it and a commonly seen 'numpy matrix'. Thanks!</p> | <p>They are the same:</p>
<pre><code>In [1]: import numpy as np
In [2]: np.matrix
Out[2]: numpy.matrixlib.defmatrix.matrix
In [3]: id(np.matrix)
Out[3]: 4300190472
In [4]: id(np.matrixlib.defmatrix.matrix)
Out[4]: 4300190472
In [5]: a = np.matrix([[1, 2], [3, 4]])
In [6]: type(a)
Out[6]: numpy.matrixlib.defmatrix... | python|numpy|matrix|types | 2 |
367,485 | 40,790,219 | Rigid transformation - Python - speedup | <p>I have following question about faster way to compute rigid transformation (yes, I know I can simply use library but need to code this by myself).</p>
<p>I need to compute x' and y' for every x,y in given image. My main bottleneck is dot product for all coordinates (interpolation after this is not a problem). Curre... | <p>You can use <code>np.indices</code> and <code>np.rollaxis</code> to generate a 3D array, where <code>coords[i, j] == [i, j]</code>. Here the coordinates need switching</p>
<p>Then all you do is append the <code>1</code> you ask for, and use <code>@</code></p>
<pre><code>coords_ext = np.empty((Y, X, 3))
coords_ext[... | python|performance|numpy|rigid-bodies | 3 |
367,486 | 41,000,880 | Pandas TimeGrouper by column | <p>I have a csv file with dates as columns headers and binary a matrix of 1, 0 or <code>np.nan</code>.</p>
<p>I'd like to take the mean of each index, grouped by month. I am running into a problem because my columns are not a datetimeindex, which I try to convert to with <code>pd.to_datetime()</code> with no luck.</p>... | <p>By default, pd.TimeGrouper works on the index (axis=0) so you need to tell it that it should group the columns instead:</p>
<pre><code>df.groupby(pd.TimeGrouper(freq='MS', axis=1), axis=1).mean()
Out:
2016-01-01 2016-02-01
0 1.0 0.5
1 0.5 1.0
</code></pre>
<p>You can directly u... | python|python-2.7|pandas | 2 |
367,487 | 40,966,850 | Difference between tf.clip_by_average_norm and tf.clip_by_norm in tensorflow | <p>I'm not completely sure of the difference between the two gradients clipping operator <code>clip_by_average_norm</code> and <code>clip_by_norm</code>. From the documentation, the difference seems to be that <code>clip_by_norm</code> uses <code>l2norm</code> instead of <code>l2norm_avg</code>.</p>
<p>I understand wh... | <p>The doc are a bit ambiguous, from <a href="https://github.com/tensorflow/tensorflow/blob/754048a0453a04a761e112ae5d99c149eb9910dd/tensorflow/python/kernel_tests/clip_ops_test.py#L280" rel="nofollow noreferrer">test</a> and <a href="https://github.com/tensorflow/tensorflow/blob/eb56a8af24695bf8258addf28b0c53fbabff72e... | tensorflow | 3 |
367,488 | 41,080,546 | Pandas DataFrames in Jupyter: formatting index and columns separately | <p>This is a variation of the question <a href="https://stackoverflow.com/questions/40990700/pandas-dataframes-in-jupyter-columns-of-equal-width-and-centered?answertab=votes#tab-top">"Pandas DataFrames in Jupyter: columns of equal width and centered"</a>. </p>
<p>How can we display an indexed dataframe with all column... | <p>Just add following style:</p>
<p><code>
style_index = dict(selector=".row_heading", props=[("text-align", "right")])
</code></p> | python|pandas|dataframe|jupyter|display | 1 |
367,489 | 41,003,352 | Problems when plotting integrated singular functions in matplotlib | <p>I want to plot the integral of an integral of (singular) function in matplotlib, but my code doesn't work. Mathematically I want this:</p>
<p><a href="https://i.stack.imgur.com/DEcpW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DEcpW.png" alt="enter image description here"></a></p>
<p>Code:</... | <p>There are a few errors in your code:</p>
<ul>
<li><p>When you run <code>g(X)</code>, the parameter is an array, while in the inside of the function you treat <code>X</code> as a value. <code>g(x)</code> is not applied to every element of <code>X</code>, it is applied to the whole array <code>X</code>. This explains... | python|numpy|math|matplotlib|scientific-computing | 2 |
367,490 | 40,814,385 | How to call pandas read_csv() without it parsing date string | <p>I am working with some data that I download from the web in csv format. The original data is shown as following.</p>
<pre><code>Test Data
"Date","T1","T2","T3","T4","T5","T6","T7","T8"
"105/11/01","123,855","1,150,909","9.30","9.36","9.27","9.28","-0.06","60",
"105/11/02","114,385","1,062,118","9.26","9.42","9.23"... | <p>This seems to work well:</p>
<pre><code>import pandas as pd
df = pd.read_csv("test.csv", skiprows=[0], usecols=[0,3,4,5], index_col=False)
df
# Date T3 T4 T5
#0 105/11/01 9.30 9.36 9.27
#1 105/11/02 9.26 9.42 9.23
#2 105/11/03 9.30 9.30 9.20
</code></pre>
<p>Also th... | python|pandas | 2 |
367,491 | 40,893,193 | TypeError when trying to add CSV entry into Spreadsheet using Pandas and XLSXwriter | <p>I am currently trying to create a program that scans a CSV file and searches entries in the file using the BING API, the results are then pasted into a spreadsheet.</p>
<p>Part of this macro involves also pasting onto the spreadsheet what term is being searched, so I am effectively copying an entry from the CSV int... | <p>Hey everyone I figured out a solution incase anyone else is as stupid as me to make the same mistake.</p>
<p>Basically, as I was using XLSXWRITER I had a variable called 'row' to tell the module where to start writing data to the spreadsheet.
In my haze I completely forgot that I had also used that same name when I... | python|csv|pandas|xlsxwriter | 1 |
367,492 | 41,066,373 | Can NumPy directly load data into a Fortran ordered array? | <p>I often work with data stored in text files with <code>[x, y, z]</code> like format. When loading the data into a NumPy array, it is convenient to maintain the ordering from the text file, where each column is a different element, x, y, or z. The downside to this is with the C ordering NumPy uses as the default, o... | <p>Both <code>loadtxt</code> and <code>genfromtxt</code> read the file line by line and collect results in a list of lists (or list of tuples). At the end they convert this to an array. Roughly:</p>
<pre><code>rows = []
for line in f.readline():
values = [float(i) for i in line.split(delimiter)]
rows.append... | python|arrays|numpy|memory | 4 |
367,493 | 40,824,903 | unorderable types error when importing sklearn | <p>I installed numpy(1.12.0b1), Scipy(0.18) on windows. I also installed sci-kit as well. When i wrote "import sklearn" in python console, it gives an error like this:
if np_version < (1, 12, 0):
TypeError: unorderable types: str() < int()
What will be the issue?</p> | <p>The problem is out on the version number, so maybe you could try to revise <code>fixs.py</code> in the <code>sklearn</code> folder. Add these script after the <code>try</code> in line 32:</p>
<pre><code>if not (x.isdigit()):
x='0'
</code></pre>
<p>so your codes will be:</p>
<pre><code>def _parse_version(versi... | python|numpy|scipy|scikit-learn|sklearn-pandas | 3 |
367,494 | 40,846,992 | alternative parametrization of the negative binomial in scipy | <p>In scipy the negative binomial distribution is defined as:</p>
<pre><code>nbinom.pmf(k) = choose(k+n-1, n-1) * p**n * (1-p)**k
</code></pre>
<p>This is the common definition, see also wikipedia:
<a href="https://en.wikipedia.org/wiki/Negative_binomial_distribution" rel="noreferrer">https://en.wikipedia.org/wiki/Ne... | <pre><code>from scipy.stats import nbinom
def convert_params(mu, theta):
"""
Convert mean/dispersion parameterization of a negative binomial to the ones scipy supports
See https://en.wikipedia.org/wiki/Negative_binomial_distribution#Alternative_formulations
"""
r = theta
var = mu + 1 / r * mu... | python|numpy|scipy|distribution | 10 |
367,495 | 40,974,626 | openpyxl module - can't find openpyxl.utils.dataframe.dataframe_to_rows function | <p>I am currently working with Pandas and Excel and am using the openpyxl module.</p>
<p>I am attempting to write a DataFrame to excel, and the openpyxl documentation states that one should use the "openpyxl.utils.dataframe.dataframe_to_rows()" function. (<a href="http://openpyxl.readthedocs.io/en/default/pandas.html"... | <p>Correct answer from Charlie Clark - I had version 2.3.2 and I upgraded to version 2.4.1 at which point the import worked. </p> | python|pandas|openpyxl | 1 |
367,496 | 41,126,036 | Separate out weeks in a year and calculate averages in a dataframe | <p>I have a data frame for hourly intervals of prices for a whole year that looks like this:</p>
<pre><code> DE FR NL CH BE AT peak offpeak
2015-12-14 00:00:00 30.93 36.56 32.44 45.53 32.44 28.50 0 1
2015-12-14 01:00:00 31.49 31.49 31.49 42.12 31.49 26.... | <p>Given this hourly fake dataset for a full year:</p>
<pre><code>cols = ['DE', 'FR', 'NL', 'CH', 'BE', 'AT']
df = pd.DataFrame(np.random.random((8760,len(cols))),
index=pd.date_range('2015-01-01', freq='H',periods=8760),
columns=cols)
</code></pre>
<p>You can use <code>DataFrame.r... | python|pandas|week-number | 1 |
367,497 | 41,134,393 | Multiplying matrices with different dimensions | <p>I have two matrices with different dimensions that I would like to multiply using einsum numpy:
C(24, 79) and D(1, 1, 24, 1). I want to obtain the matrix with the dimension (1, 1, 79, 1).</p>
<p>I have tried to multiply them in two ways:</p>
<pre><code>tmp = np.einsum('px, klpj ->klxj', C, D)
tmp = np.einsum(... | <p>Owing to the singleton dimensions that don't really result in <code>sum-reduction</code>, we can introduce matrix-multiplication with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow noreferrer"><code>np.tensordot</code></a> or <a href="https://docs.scipy.org/doc/nump... | python|numpy|matrix | 0 |
367,498 | 41,223,030 | how can I specify the memory address of a Numpy array using ctypes? | <p>I would like to construct a Numpy array that starts at a specific memory address. How would I do that? I assume the solution involves <code>ctypes</code> but I can't figure it out from the docs.</p>
<p><strong>More Details and Context</strong></p>
<p>I would like to create a number of arrays whose values are all a... | <p>Make an array of 10 bytes:</p>
<pre><code>In [287]: x = np.arange(10, dtype=np.uint8)
In [288]: x
Out[288]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8)
In [289]: x.__array_interface__
Out[289]:
{'data': (155596184, False),
'descr': [('', '|u1')],
'shape': (10,),
'strides': None,
'typestr': '|u1',
'vers... | python-3.x|numpy|ctypes | 4 |
367,499 | 41,068,363 | Pandas to SQL Server column limit for Cosine Similarity | <p>Im calculating Cosine Similarity using NLTK and exporting the cosine similarity values to SQL Server which i would like to use for other reporting purpose.</p>
<p>I have about 4773 columns with about 2k rows and SQL Server does not support these number of columns ? what would be a better alternative ? is there anot... | <p><a href="https://stackoverflow.com/a/41109092/3988268">https://stackoverflow.com/a/41109092/3988268</a></p>
<p>I have changed the schema and used the above link for the process</p> | sql-server|python-3.x|pandas|cosine-similarity | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.