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 |
|---|---|---|---|---|---|---|
19,600 | 46,872,385 | How to split a multiindex df in 80/20 parts based on date? | <p>In my df I have a multiindex like this: </p>
<pre><code>df.index.names
FrozenList([u'Ticker', u'Date'])
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 189667 entries, (AAPL, 1992-08-31 00:00:00) to (^DJI, 2017-08-31 00:00:00)
</code></pre>
<p>On a single index df I would do:</p>
<pre><code>from sklearn.... | <p>Here is one way of doing so:<br/>
first get the test group by groupby ticker(index level 0) then sorting each resulting group by date (descending order) then getting the first 20% of the data using selection</p>
<pre><code>df_test = stock_data.groupby(level=0).apply(
lambda group: group.sort_index(
asce... | python|pandas|scikit-learn | 4 |
19,601 | 38,569,663 | How to read in sequence of images as 3d tensor? | <p>As an input to a CNN I am working on, I want to use a sequence of images (with 3D convolution in the conv layers).</p>
<p>However, I already fail in reading in the images as a 3D tensor that I can use for the computation.</p>
<p>Here is my primitive attempt:</p>
<pre><code>def get_sequence_as_tensor(folder):
... | <p>I would recommend combining the images into a numpy array outside of tensorflow and then passing them in to a placeholder.</p>
<p>Something like this should work.</p>
<pre><code>filename = tf.placeholder("string")
png_string = tf.read_file(filename)
img = tf.image.decode_png(png_string)
img_float = tf.cast(img, tf... | python|tensorflow | 0 |
19,602 | 62,909,645 | TensorFlow Lite GPU Compute is much slower than CPU Compute | <p>I'm currently working to translate a model from TensorFlow to TensorFlow Lite. I have converted the model from a regular TF 1.x session into a .tflite file by first creating a checkpoint and a saved weightless graph (.pbtxt) and then freezing the model into a .pb with graph weights using the freeze_graph() function... | <p>check your model using benchmark app whether all Ops are running on GPU or not, issue might be model is falling back to CPU and that is costing to processing time.</p> | android-studio|tensorflow|tensorflow-lite | 0 |
19,603 | 63,018,289 | H10 Heroku App crashed when I try to deploy | <p>I'm having the following error message:</p>
<blockquote>
<p>at=error code=H10 desc="App crashed" method=GET path="/favicon.ico"
host=pets-vs-dogs.herokuapp.com
request_id=e191ffa5-3d2d-4ba5-a70f-e5eab32213d8 fwd="181.46.165.15"
dyno= connect= service= status=503 bytes= protocol=https</p... | <p>Solved this by changing my Procfile.
Now is</p>
<blockquote>
<p>web: python classifier/app.py</p>
</blockquote> | python|tensorflow|flask|heroku|deployment | 0 |
19,604 | 63,061,462 | python pandas.loc not finding row name: KeyError | <p>This is driving me crazy because it should be so simple and yet it's not working. It's a duplicate question and yet the answers from previous questions don't work.</p>
<p>My csv looks similar to this:</p>
<pre><code>name,val1,val2,val3
ted,1,2,
bob,1,,
joe,,,4
</code></pre>
<p>I want to print the contents of row 'jo... | <p>The problem with your logic is that you have not let pandas know which column it should search <code>joe</code> for.</p>
<pre><code>print(df.loc[df['name'] == 'joe'])
</code></pre>
<p>or</p>
<pre><code>print(df[df['name'] == 'joe'])
</code></pre> | python|python-3.x|pandas|csv|pycharm | 2 |
19,605 | 62,917,909 | Change dtype of none square numpy ndarray | <pre><code>a = np.array([1,2,3])
b = np.array([1,2,3,4])
c = np.array([a, b])
</code></pre>
<p>c has two <code>np.ndarrays</code> inside of different size, when I try to call <code>c.astype(np.int8)</code>, I would get a value error of <code>ValueError: setting an array element with a sequence.</code>. How can I change... | <p>To specify the type of your array during the creation, simply use <code>dtype=xxx</code>.
Ex:</p>
<pre><code>c = np.array([a,b], dtype=object)
</code></pre>
<p>If you want to change the type from <code>int64</code> to <code>int8</code>, you could use:</p>
<pre><code>a.dtype = np.int8
b.dtype = np.int8
</code></pre>
... | python|numpy|numpy-ndarray | 3 |
19,606 | 67,812,504 | Filter multiple dataframes with criteria from list using loop | <p>The code below creates multiple empty dataframes named from the report2 list. They are then populated with a filtered existing dataframe called dfsource.
With a nested for loop, I'd like to filter each of these dataframes using a list of values but the sub loop does not work as shown.</p>
<pre><code>import pandas as... | <p>You can reference a variable in a query by using @</p>
<pre><code>df_dict[i]=dfsource.query('COL1==@x')
</code></pre>
<p>So the total code looks like this</p>
<pre><code>import pandas as pd
report=['A','B','C']
suffix='_US'
report2=[s + suffix for s in report]
print (report2) #result: ['A_US', 'B_US', 'C_US']
sou... | python|pandas|dataframe|loops|for-loop | 1 |
19,607 | 67,876,032 | How to replace values by None if string contains character pattern? | <p>I want to <strong>replace</strong> every string in my pandas df column <code>departments</code> <strong>with None</strong> if it contains a <code>)</code></p>
<pre><code> departments var1 var1.1
1 transport aa uu
2 industry) bb tt
3 aviation) cc tt
</cod... | <p>With your shown samples, please try following. You could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a> function to find out whatever values in <code>departments</code> column has <code>)</code> then usi... | python-3.x|pandas|string|nonetype | 3 |
19,608 | 67,712,963 | Pandas Error Handling - "day is out of range for month" | <p>I wonder how do I handle and spot the data which has wrong format in pandas.</p>
<p>I tried to convert string into pd data form however,
somewhere in the middle the format is not in line with the format that was expected (I assume), an error message popped.</p>
<ol>
<li>I want to print what the data is</li>
<li>and ... | <p>Based on your comments I assume this will help:</p>
<p>Using as example (99/99/9999 is the incorrect data):</p>
<p><code>df = pd.DataFrame(["09/26/2016", "06/14/2017", "09/05/2018", "06/16/2017", "05/09/2018", "99/99/9999"], columns=['Issue Date'])</code>.<... | pandas|dataframe | 0 |
19,609 | 31,781,860 | Loop over multiple .csv files python/pandas | <p>I have two folders that contain +50 .csv files, I want to process al those files in my python code with pandas. At the beginning of my code I load two different .csv files: </p>
<pre><code>Location1 = path\tasks_01.csv'
Location2 = path\resource_01.csv'
dftask = pd.read_csv(Location1)
dfresourc... | <p>Create a list of files in each folder and then zip through both of them.</p>
<pre><code>import os
files_in_folder_1 = [os.path.join(path1, f) for f in os.listdir(path1) if os.path.isfile(os.path.join(path1, f))]
files_in_folder_2 = [os.path.join(path2, f) for f in os.listdir(path2) if os.path.isfile(os.path.join(... | python|csv|pandas | 0 |
19,610 | 31,816,831 | How do I replace the content of an entire Pandas' cell with a string? | <p>I have a dataframe with a row that contains the following:</p>
<pre><code>id animal
1 tiger
</code></pre>
<p>I would like to simply "set" the value of 1 to, say, "lion".</p>
<pre><code>contains_latlong.iloc[1]["animal"]="lion"
</code></pre>
<p>is something that Pandas doesn't like. Being new, I'm getting ... | <p>In general the approach is to use index and column identifiers:</p>
<pre><code>df.loc[1, 'id'] = 'Lion'
</code></pre>
<p>yields </p>
<pre><code> animal id
1 tiger Lion
</code></pre>
<p>without any warnings.</p>
<p>Your example uses "<code>iloc</code>" rather than "<code>loc</code>", which means you need t... | python|pandas | 3 |
19,611 | 31,755,900 | Python 3.x's dictionary view objects and matplotlib | <p>In python 3.x <code>keys()</code>, <code>values()</code> and <code>items()</code> return <a href="https://docs.python.org/3/library/stdtypes.html#dict-views" rel="nofollow noreferrer">views</a>. Now while views certainly have <a href="https://stackoverflow.com/a/8960727/1622937">advantages</a>, they also seem to cau... | <p>More of that error:</p>
<pre><code>--> 512 return array(a, dtype, copy=False, order=order, subok=True)
513
514 def ascontiguousarray(a, dtype=None):
TypeError: float() argument must be a string or a number, not 'dict_values'
</code></pre>
<p>So the minimal example is:</p>
<pre><code>np.array(d.ke... | python|python-3.x|numpy|matplotlib | 6 |
19,612 | 41,663,221 | Python: Optimizing data frame processing | <p>I have processed raw data in multiple pandas data frames. Each data frame contains <strong>individual user data and which social network they have clicked in time series</strong>. Each data frame roughly represent a year or two together and I want to get everything into one after processing.</p>
<p>Inside the loop ... | <p>This should be</p>
<pre><code>df.set_index(['year', 'month']) \
.iloc[:, 0].str.split(r',\s*').apply(pd.value_counts).fillna(0).reset_index()
</code></pre>
<p><a href="https://i.stack.imgur.com/VjlGh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VjlGh.png" alt="enter image description here">... | python|pandas|parallel-processing | 1 |
19,613 | 41,580,728 | Drawing Relationships Between Pandas Dataframe Columns | <p>I have a <code>Pandas</code> <code>Dataframe</code> that has multiple columns. There are 2 columns I'm interested in at this point, and they look something like this:</p>
<p><a href="https://i.stack.imgur.com/srBhI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/srBhI.png" alt="DataFrame data"></... | <p>consider the dataframe <code>df</code></p>
<pre><code>y, r, b, o = 'Yellow', 'Red', 'Blue', 'Orange'
df = pd.DataFrame(dict(
Color=[y, r, b, y, o, r, y, y],
Age=[10, 15, 20, 10, 20, 15, 15, 10]
))
df.groupby(['Color', 'Age']).size().loc[y].plot.bar()
</code></pre>
<p><a href="https://i.stack.imgur.com/H6d... | python|pandas|dataframe | 1 |
19,614 | 61,327,017 | I want to convert pandas data into date timeindex | <pre><code>names=['Ticker','Date','Time','open','high','low','close','Volume']
havellsdata = pd.read_csv('C:\\Users\\nEW u\Desktop\havellsjuly2015.csv',names=names,index_col= '
Ticker'])
k=havellsdata['high']-havellsdata['open']
havellsdata.insert(6,'openhighcheck',k)
havellsdata
#havellsdata[15]
Date Time ... | <p>Try this:</p>
<pre><code>havellsdata['Datetime'] = pd.to_datetime(havellsdata['Date'].apply(str) + ' ' + havellsdata['Time'])
havellsdata = havellsdata.set_index('Datetime')
</code></pre>
<p>Example:</p>
<pre><code>In [1723]: df ... | python|pandas|dataframe | 2 |
19,615 | 61,513,547 | Combine and concat only non empty columns | <pre><code>df_final["Full"] = df_final["A"] + "$" + df_final["B"] + "$" + df_final["C"] + "$" + df_final["D"] + "$" + df_final["E"] + "$" + df_final["F"]
</code></pre>
<p>However some columns may be empty and I only want to combine those cells where columns are not empty. Eg:</p>
<pre><code>A|B|C|D|E|F
1| |3| |5|6
<... | <p>Use <code>agg</code> with <code>join</code> and python genexp/listcomp to filter out those having empty string</p>
<pre><code>s = df.astype(str).agg(lambda x: '$'.join(word for word in x if word.strip()), axis=1)
Out[12]:
0 1$3$5$6
dtype: object
</code></pre> | pandas | 0 |
19,616 | 61,373,229 | set_weights() in Tensorflow model | <p>I have pretrained weights as np.array of shape <code>(3, 3, 3, 64)</code>. I want to initialize this Tensorflow CNN with those weights using <code>set_weights()</code> like I show below.</p>
<p>However, when I try that, the following error pops up: <code>ValueError: You called set_weights(weights) on layer "conv2d_... | <p>You could just use <code>kernel_initializer</code> and <code>bias_initializer</code> arguments like this:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
# init_kernel and init_bias are initialization weights that you have
init_kernel = np.random.normal(0, 1, (3, 3, 3, 64))
init_bias = np.ze... | python|tensorflow|keras|computer-vision | 4 |
19,617 | 61,427,359 | Passing list names as a list to create a numpy array in Python | <p>I have 100 lists :</p>
<pre class="lang-py prettyprint-override"><code>l0 = [35.467, 1785387, 9984670, 0.913]
l1 = [63.951, 2833687, 640679, 0.888]
l2 = [80.940, 3874437, 357114, 0.916]
l3 = [60.665, 2167744, 301336, 0.873]
l4 = [127.061, 4602367, 377930, 0.891]
l5 = [64.511, 2950039, 242495, 0.907]
l6 = [318... | <p>How do you get those lists? Load from a file? copy-n-paste?</p>
<p>If copy-n-paste your sample to an <code>ipython</code> session, I can get a list of lists with:</p>
<pre><code>In [866]: alist = [globals()[f'l{i}'] for i in range(0,6)]
In [867]: alist ... | python|arrays|numpy | 1 |
19,618 | 68,455,417 | torch Tensor add dimension | <p>I have a tensor with this size</p>
<pre><code>torch.Size([128, 64])
</code></pre>
<p>how do I add one "dummy" dimension such as</p>
<pre><code>torch.Size([1, 128, 64])
</code></pre> | <p>There are several ways:</p>
<p><strong><a href="https://pytorch.org/docs/stable/generated/torch.unsqueeze.html#torch.unsqueeze" rel="nofollow noreferrer"><code>torch.unsqueeze</code></a></strong>:</p>
<pre class="lang-py prettyprint-override"><code>torch.unsqueeze(x, 0)
</code></pre>
<hr />
<p><strong>Using <code>No... | python|pytorch | 3 |
19,619 | 68,733,104 | Pandas if condition is True perform function to next n rows | <p>I have a column of indicator functions(a), which when true I want to perform an action on the next n(3 in this example) rows of another column(b). The following achieves what I am looking for but will get very inefficient as n gets large :
<a href="https://i.stack.imgur.com/FFpjQ.png" rel="nofollow noreferrer"><img ... | <p>Tricky but possible using an apply:</p>
<pre><code>testing = pd.DataFrame({
'a': [0, 1, 0, 0, 0],
'b': [0, 0, 0, 0, 0]
})
def func(value, n):
if value.a == 0 and value.b != -1:
value.b = 0
elif value.a == 1 and value.b == 0:
value.b = 0
testing.loc[value.name + 1:value.name +... | pandas|array-broadcasting | 0 |
19,620 | 36,599,793 | numpy - printing *only one* column from matrix as hex | <p>i can't find an easy way in numpy to display a matrix with one column shown as hex, the rest as decimal.
found answer regarding <a href="https://stackoverflow.com/a/9448099/866439">how to print <em>everything</em> as hex</a>, but i want just one column.</p>
<p>here's what i have: data looks like this:</p>
<pre><co... | <p>For display purposes just iterate on the rows, and format each row as needed:</p>
<pre><code>In [303]: for row in data:
...: print hex(row[0])[:-1], row[1]
...:
0x72b0000 3
0xa000000 339
0x7170104 1
0x3000100 1
</code></pre>
<p>or with more formatting:</p>
<pre><code>In [307]: print '\n'.join([... | python|numpy|matrix|hex | 1 |
19,621 | 53,142,218 | Pandas keyerror while dropping value from a column | <p>I am a beginner in Python and getting an error while trying to drop values from a column in pandas dataframe. I keep getting Keyerror after sometime. Here is the code snippet:</p>
<pre><code>for i in data['FilePath'].keys():
if '.' not in data['FilePath'][i]:
value = data['FilePath'][i]
data = data[data['Fi... | <p>If I understand your logic correctly, then you should be be able to do this without a loop. From what I can see, it looks like you want to drop rows if the <code>FilePath</code> column does not begin with <code>.</code>. If this is correct, then below is one way to do this:</p>
<p>Create sample data using <a href="... | python|pandas | 0 |
19,622 | 65,560,180 | How can add tensorflow in bazel project? | <p>My project structure</p>
<pre><code>/PROJECT
WORKSPACE
BUILD
third_party
tensorflow <-- cloned repository
my_files
BUILD
</code></pre>
<p>In <strong>WORKSPACE</strong> file i added this</p>
<pre><code>local_repository(
name = "tensorflow",
path = "third_party/tenso... | <p>This issue solved my problem:
<a href="https://github.com/tensorflow/tensorflow/issues/46144" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/46144</a></p> | xcode|build|bazel|tensorflow-lite | 0 |
19,623 | 65,569,974 | python remove rows with the same keys and keep the row with the most recent date stamp | <p>I have a SharePoint excel sheet with the file name and format that updates every day with the most recent information. The rows are order numbers (as key for other dataframe), ordered qty and received qty for the current day.</p>
<p>Rows will be added if there are more orders placed today, and old orders will be del... | <p>In python you can compare strings based of their lexicographic order so
if we look at the logical expression</p>
<pre><code>'A' < 'B'
</code></pre>
<p>this comparison will result in True.
So then you could write a function which will sort out the biggest one with the same dates using this functionallity.</p>
<p>A... | python|pandas|automation|pandas-groupby | -1 |
19,624 | 63,529,587 | Pandas: How to filter on a parameter with both one to many and one to one relationships | <p>I have a dataset of several tables. Some of the fields overlap but on some tables they may have a one to many relationship while on other tables they may have a one to one relationship. I am trying to create a new dataframe where I can take the values associated with one field (one to one) and the values associate... | <p>You should show us what you tried! Makes it easier for people to answer.</p>
<p>Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">Merge</a> is how I'd approach it though. Something like:</p>
<pre><code>new_df = df2.merge(df1, on=["e... | python|pandas|dataframe|data-analysis|data-cleaning | 1 |
19,625 | 63,452,136 | raise IOError("%s not found." % path) | <p>In the past week, I spent my time trying to solve a big problem when compiling my program.py. My program script is:</p>
<pre><code>import numpy
import matplotlib
import matplotlib.pyplot as plt
import scipy.interpolate
from matplotlib.font_manager import FontProperties
import matplotlib.cm as cm
from mpl_toolkits.ax... | <p>Python knows how to handle windows paths with unix-like path strings using forward slashes.</p>
<p>Change <code>C:\Users\annyc\Desktop\gap.txt</code> to <code>C:/Users/annyc/Desktop/gap.txt</code></p>
<p>You can also check <code>os.path.exists("C:/Users/annyc/Desktop/gap.txt")</code> to make sure the file ... | python|numpy|matplotlib | 0 |
19,626 | 63,679,038 | numpy masked assignment through advanced indexing | <p>So I am learning numpy and in this book there is a question that tells me to create three arrays Z, M, and C.
In my Z array I'm suppose to create a (4,5) dimensional array and my M array is a boolean mask array which is the same size (4,5) but is True where
<code> M = abs(Z) < 2</code>
My C array is also the same... | <p>IIUC, you can do this: <code>z * z * c * m</code></p>
<p>In <code>m</code>, all the False values are represented as zero, and all the True values are represented as one. You can see this by <code>m * 1</code></p> | python|arrays|python-3.x|numpy | 0 |
19,627 | 21,928,814 | Pandas dataframe : Multiple Time/Date columns to single Date index | <p>I have a dataframe with a Product as a first column, and then 12 month of sales (one column per month). I'd like to 'pivot' the dataframe to end up with a <em>single</em> date index.</p>
<p>example data :</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(10, 1000, size=(2,12... | <p>I think pandas <code>melt</code> provides the functionality you are looking for </p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-melt" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-melt</a></p>
<pre><code>import pandas as pd
import nu... | python|pandas | 2 |
19,628 | 24,612,584 | How to delete all rows in a dataframe? | <p>I want to delete <em>all</em> the rows in a dataframe.</p>
<p>The reason I want to do this is so that I can reconstruct the dataframe with an iterative loop. I want to start with a completely empty dataframe.</p>
<p>Alternatively, I could create an empty df from just the column / type information if that is possib... | <p>Here's another method if you have an existing DataFrame that you'd like to empty without recreating the column information:</p>
<pre><code>df_empty = df[0:0]
</code></pre>
<p><code>df_empty</code> is a DataFrame with zero rows but with the same column structure as <code>df</code></p> | python|pandas | 106 |
19,629 | 24,791,379 | Ways to Create Tables and Presentable Objects Other than Plots in Python | <p>I have the following code that runs through the following:</p>
<p>Draw a number of points from a true distribution.
Use those points with curve_fit to extract the parameters.
Check if those parameters are, on average, close to the true values.
(You can do this by creating the "Pull distribution" and see if it retur... | <p>I would go with the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">CSV module</a> to generate a presentable table.</p> | python|matplotlib|pandas|graphic | 1 |
19,630 | 53,469,159 | Must pass DataFrame with boolean values only after 71 iterations | <p>I've checked posts and haven't found a solution to my problem. I'm getting the error I put in the subject after the code works fine. </p>
<p>I'm simply trying to add a row to a holder dataframe that only appends rows that aren't similar to previously appended rows. You'll see that friend is checked against 'Targ... | <p>I just want to update everyone. I was able to solve this. It took awhile, but the problem was located in line where I query holder. It was too complex. I simplified it into multiple, simpler queries. It works fine now.</p> | python|pandas|dataframe|append|valueerror | 0 |
19,631 | 53,796,851 | Pandas counter increment after comparing two columns | <p>I'd like to create a simple counter in pandas that increments by one every time a cycle is complete. This should be simple, but I can't figure it out... Here is what I would like to do, with an illustrative pandas DataFrame:</p>
<pre><code># Illustrative dataframe
df = pd.DataFrame({'a':[0,0,1,1,0,0,1,1], 'b':[0,1,... | <p>You can achieve what you want by</p>
<pre><code>df['c'] = ((df['a'] == 1) & (df['b'] == 0)).cumsum()
</code></pre> | python|pandas|apply | 5 |
19,632 | 71,927,621 | Python Groupby & Counting first in Series, sorting by month | <p>I have a pandas dataframe (this is an example, actual dataframe is a lot larger):</p>
<pre class="lang-py prettyprint-override"><code>data = [['345', 1, '2022_Jan'], ['678', 1, '2022_Jan'], ['123', 1, '2022_Feb'], ['123', 1, '2022_Feb'], ['345', 0, '2022_Mar'], ['678', 1, '2022_Mar'], ['901', 0, '2022_Mar'], ['678',... | <p>Here is another way to do that</p>
<p>Converting the sum to a boolean with astype(bool) to return True or False, based on values being 0 or non-zero, and then to 0 or 1 with astype(int)</p>
<pre><code>
df.groupby(['Year_Month','ID'])['Error Count'].sum().astype(bool).astype(int)
Year_Month ID
2022_Feb 123 1... | python|pandas-groupby | 0 |
19,633 | 71,948,300 | Running the same detection model on different GPUs | <p>I recently ran in to a bit of a glitch where my detection model running on two different GPUs (a Quadro RTX4000 and RTX A4000) on two different systems utilize the GPU differently.
The model uses only 0.2% of GPU on the Quadro system and uses anywhere from 50 to 70% on the A4000 machine. I am curious about why this ... | <p>Looks like the <code>Quadro RTX4000</code> does not use GPU.</p>
<p>The method <code>tf.test.is_gpu_available()</code> is deprecated and can still return <code>True</code> although the GPU is not used.</p>
<p>The correct way to verify the usage of the GPU availability + usage is to check the output of the snippet:</... | tensorflow|machine-learning|computer-vision|nvidia | 1 |
19,634 | 71,943,613 | how do i port my machine learning model from python to java web app? | <p>so I've been developing some machine learning models using sklearn and tensorflow in python .
and I want to integrate it into a java web app.
so far I've been saving my models as .joblib
any idea how i can do it ?
I know this is a general question, but if someone can tell me if its possible , or do i have to retrain... | <p>as @SamuelAudet said,i can integrate CPython scripts in Java applications using the JavaCPP Presets for CPython.
github.com/bytedeco/javacpp-presets/tree/master/cpython</p> | python|java|tensorflow|scikit-learn|web-applications | 1 |
19,635 | 72,035,933 | DataFrame is highly fragmented | <p>I have the following code, but when I run it I receive the error:</p>
<p>PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling <code>frame.insert</code> many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fra... | <p>Following the comments above</p>
<ul>
<li>issue with creating multiple columns</li>
</ul>
<p>I don't believe you need to create so many new temp columns - instead you can just update based on the data, and have a function which accepts a parameter <code>h</code>.</p>
<pre class="lang-py prettyprint-override"><code>a... | python|pandas|dataframe | 0 |
19,636 | 22,201,913 | Computing a binomial probability for huge numbers | <p>I want to compute binomial probabilities on python. I tried to apply the formula:</p>
<pre><code>probability = scipy.misc.comb(n,k)*(p**k)*((1-p)**(n-k))
</code></pre>
<p>Some of the probabilities I get are infinite. I checked some values for which p=inf. For one of them, n=450,000 and k=17. This value must be gre... | <p>Because you're using scipy I thought I would mention that scipy already has statistical distributions implemented. Also note that when n is this large the binomial distribution is well approximated by the normal distribution (or Poisson if p is very small).</p>
<pre><code>n = 450000
p = .5
k = np.array([17., 225000... | python|algorithm|numpy|probability|binomial-coefficients | 9 |
19,637 | 17,756,617 | Finding an unknown point using weighted multilateration | <p>I have a series of points (latitude/longitude coordinates) on the earth and a series of distance estimates from each point to an unknown location. I would like to use <a href="https://en.wikipedia.org/wiki/Multilateration" rel="nofollow noreferrer">multilateration</a> to estimate the location of this unknown locatio... | <p>While this probably not exactly what you are looking for you can use this as starting point:</p>
<pre><code>import numpy as np
import scipy.optimize as opt
#Returns the distance from a point to the list of spheres
def calc_distance(point):
return np.power(np.sum(np.power(centers-point,2),axis=1),.5)-rad
#Lati... | python|math|numpy|geolocation|scipy | 3 |
19,638 | 17,753,874 | What's the numpy equivalent of python's zip(*)? | <p>I think (hope) this question differs substantially from <a href="https://stackoverflow.com/questions/12744778/what-is-the-equivalent-of-zip-in-pythons-numpy">What is the equivalent of "zip()" in Python's numpy?</a>, although it might just be my ignorance.</p>
<p>Let's say I have the following:</p>
<p... | <p>Do you actually need to return tuples or do you want to reshape the array?</p>
<pre><code>>>> a
array([[[ 1, 2],
[ 3, 4],
[ 5, 6]],
[[ 7, 8],
[ 9, 10],
[11, 12]]])
>>> a.swapaxes(0,1)
array([[[ 1, 2],
[ 7, 8]],
[[ 3, 4],
[ 9, ... | python|numpy|zip | 7 |
19,639 | 4,260,645 | How to get running counts for numpy array values? | <p>OK, I think this will be fairly simple, but my numpy-fu is not quite strong enough. I've got a an array A of ints; it's tiled N times. I want a running count of the number of times each element is used.</p>
<p>For example, the following (I've reshaped the array to make the repetition obvious):</p>
<pre><code>[0, 1... | <p>Here's my take on it:</p>
<pre><code>def countify2(ar):
ar2 = np.ravel(ar)
ar3 = np.empty(ar2.shape, dtype=np.int32)
uniques = np.unique(ar2)
myarange = np.arange(ar2.shape[0])
for u in uniques:
ar3[ar2 == u] = myarange
return ar3
</code></pre>
<p>This method is most effective when ... | python|numpy | 3 |
19,640 | 55,411,359 | Create a category column in pandas based on string content in another column | <p>I want to tag Pandas rows based on their values in a string column.
The desired output is this:</p>
<p><a href="https://i.stack.imgur.com/1XmJB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1XmJB.png" alt="enter image description here"></a></p>
<p>I have this code:</p>
<pre><code>data = [{'ag... | <p>Here's an unconventional solution using <code>map</code>:</p>
<pre><code>(2*apes + monkeys).map({0: 'neither', 1: 'monkey', 2: 'ape', 3: 'both'})
0 both
1 monkey
2 ape
Name: name, dtype: object
</code></pre>
<p>The idea is to assign apes a value of 2 and monkeys a value of 1, then sum the two and lo... | python|pandas | 1 |
19,641 | 55,487,250 | Displaying bin min and max range when saving NumPy histogram via savetxt | <p>I've successfully constructed a basic histogram using NumPy, and I'm able to save it using <code>savetxt</code>.</p>
<p>What I haven't been able to figure out though is how to either modify the histogram itself, or <code>savetxt</code>, to output the bin range.</p>
<p>Rather than the output looking like this:</p>
... | <p>Look at your <code>bins</code>, the information is already there; <code>bins</code> is one element longer than <code>freqs</code>, but you cut the last bin border away by using <code>zip</code>, which iterates only over the smallest common length of its iterables.</p>
<p>Try e.g.</p>
<pre><code>h = np.array(list(z... | python|python-3.x|numpy|histogram | 0 |
19,642 | 55,553,759 | Combining similar rows within a dataframe column into one | <p>I'm working on the Chicago crimes dataset and I created a dataframe called primary which is just the type of crime. Then I grouped by the type of crime and got its count. This is the relevant code.</p>
<pre class="lang-py prettyprint-override"><code>primary = crimes2012[['Primary Type']].copy()
test=primary.groupby... | <p>You can look at <code>map</code> or <code>apply</code> here - <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html</a></p>
<p>You will have to create a mapping of your i... | python|python-3.x|pandas | 1 |
19,643 | 55,364,790 | Deleting specific columns pandas | <p>I have the following code:</p>
<pre><code>dfs = glob.glob(path + "/*.csv")
df = pd.concat([pd.read_csv(df) for df in dfs], axis=1, ignore_index=False)
df1 = df.loc[:,~df.columns.duplicated()]
df1.to_csv("userpath.csv")
</code></pre>
<p>The purpose of this code is to take random/multiple csv files all taken from t... | <p>From your image it seems that the columns you want to keep are the columns that begin with <code>GEO</code>. To do this, you can use <code>regex</code> to match the names, then get the indices of these columns, then splice the dataframe based on the column index.</p>
<pre><code>import re
pattern = r'GEO' # or just... | python|pandas | 0 |
19,644 | 56,767,192 | Python adding empty rows in open with function | <p>I have a few dfs looks like that:</p>
<pre><code>A B C D
1 2 3 4
11 22 33 44
111 222 333 444
</code></pre>
<p>I tried to write they in csv file. I use: </p>
<pre><code>with open(matchedLine + 'OUT', 'a') as f:
df.to_csv(f, header=False, index = False)
</code></pre>
<p>And in cs... | <p>just add the parameter : newline='' in your open function.</p>
<p>The line would be : </p>
<pre><code>with open(matchedLine + 'OUT', 'a', newline=''):
</code></pre> | python|pandas|file|csv | 1 |
19,645 | 56,665,942 | Extract all values in a certain year of a pandas DataFrame | <p>I want to obtain all values that have a certain year in the following pandas <code>DataFrame</code> instance:</p>
<pre><code>timestamps = np.array([pd.Timestamp('2016-01-01'), pd.Timestamp('2016-01-02'), pd.Timestamp('2017-01-01'), pd.Timestamp('2018-01-01')])
quantities = np.array([1.0, 10.0, 2.0, 3.0])
data = dic... | <p>You can extract the year of the <code>timestamps</code> column using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.year.html" rel="nofollow noreferrer"><code>dt.year</code></a>. </p>
<p>Here <code>dt</code> is an accessor object for datetimelike properties. Hence enables apply... | python|pandas|date | 3 |
19,646 | 56,517,295 | How to plot a histogram of numpy nans in a pandas dataframe | <p>I have a large pandas dataframe with many np.nan values in it. How do I plot a histogram showing how many nans are in each column using matplotlib.hist()?</p> | <p>You'll need to count up the NaNs first, and then plot the histogram.</p>
<p>something like this will work instead</p>
<pre><code># number of nulls for each column
vc_nulls = df.apply(lambda x: x.isnull().value_counts()).T[True]
vc_nulls.hist() # if you want a histogram of these counts
# or if you wanted to plot th... | pandas|numpy | 0 |
19,647 | 56,519,989 | Drop row with spesific string | <p>I have huge data frame:</p>
<pre><code>Data1 Data2
A BS2
A BS3
B BS6
B BS7
C BS7
C BS6
D BS8
D BS3
E BS7
E BS6
</code></pre>
<p>I just want to eliminate or drop row with a pair of data from data1 and "BS7 and BS6" from data2.</p>
<p>my expected result:... | <p>Same logic before using <code>transform</code> slightly different we need <code>join</code> this time </p>
<pre><code>df[df.groupby('Data1').Data2.transform(','.join).ne('BS7,BS6')]
Out[514]:
Data1 Data2
0 A BS2
1 A BS3
2 B BS6
3 B BS7
6 D BS8
7 D BS3
</code></pre> | python|pandas|row|multiple-columns | 3 |
19,648 | 56,829,525 | Object detection when the object occupies the full region on the image? | <p>I am working with object detection using Tensorflow. I have mix of 7-8 classes. Initially, we had an image classification model and now moving it to object detection model. For once class alone, the object to be detected occupies the entire image. Can we have the bounding box dimension to be the entire width and hei... | <p>It shouldn't hinder the performance as long as there's enough such examples in the training set.
the OD API clips detections outbounding the image, so in these cases the resulting bounding box would be the of the entire image (or one axis would be the entire size, and the other less, depending on the object occupati... | tensorflow|object-detection | 1 |
19,649 | 56,647,873 | How to create a pandas Series from dict with non unique keys? | <p>I am trying to create a pandas Series from dict that contains non-unique keys. But pandas keep discarding similar keys and loads only the last one.</p>
<pre class="lang-py prettyprint-override"><code> my_dict1= {'Country':'US','Country':'UK','Country':'Japan','Country':'China',}
pd.Series(my_dict1)
</code></... | <p>Dict needs unique keys. You need to do something as below, second option can be created by dict + zipping the list of countries with a range.</p>
<p><strong>Option 1</strong></p>
<pre><code>my_dict1= {'Country1':'US','Country2':'UK','Country3':'Japan','Country4':'China',}
</code></pre>
<p><strong>Option 2</strong... | python|pandas|series | 2 |
19,650 | 56,594,779 | How to crosstab columns from dataframe based on a condition? | <p>I often need cross tables for pre-analysis of my data. I can produce a basic cross table with <code>pd.crosstab(df['column'], df['column'])</code> but fail to add a crition (logical expression), to filter this cross table only to a subset of my dataframe. </p>
<p>I've tried <code>pd.crosstab(df['health'], df['money... | <p>Filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> before <code>crosstab</code>:</p>
<pre><code>df1 = df[df['year']==1988]
df2 = pd.crosstab(df1['health'], df1['money'])
</code></pre>
<p>EDIT: You can... | python|pandas|dataframe|crosstab | 2 |
19,651 | 67,092,895 | how to split a list of numpy arrays based on two other lists | <p>I have a list of numpy arrays stored in a list and want to split each array into two ones. This is my input data:</p>
<pre><code>all_data=[[np.array([[1., 2., 0],[4., 5., 0],[0., 0., 0]]), np.array([[8., 8., 0],[7., 7., 0],[3., 3., 0]]),\
np.array([[0., 0., 0],[1., 1., 0],[-1., 1., 0],[-2., -2., 0]])],\
... | <p>You could use Numpy's <a href="https://numpy.org/doc/stable/reference/generated/numpy.split.html#numpy-split" rel="nofollow noreferrer">split</a> function to split the arrays as you want.</p>
<p>Although not very efficient/elegant (your arrays have different shapes so vectorizing this seems impossible), the followin... | python|arrays|numpy|split | 1 |
19,652 | 67,025,592 | How to dimensionalize a pandas dataframe | <p>I'm looking for a more elegant way of doing this, other than a for-loop and unpacking manually...</p>
<p>Imagine I have a dataframe that looks like this</p>
<pre><code>| id | value | date | name |
| -- | ----- | ---------- | ---- |
| 1 | 5 | 2021-04-05 | foo |
| 1 | 6 | 2021-04-06 | foo |
| 5 | ... | <p>Think about this not as "splitting" the existing dataframe, but as creating two new dataframes from the original. You can do this in a couple of lines:</p>
<pre><code>meta = df[['id','name']].drop_duplicates() #Select the relevant columns and remove duplicates
records = df.drop("name", axis=1) #R... | python|pandas | 2 |
19,653 | 66,802,616 | Why is the figure size (y-axis) fluctuating in this example? | <p>I've got a map of the world on which I am iteratively plotting drought areas in a for-loop.</p>
<p>For reproducibility, data is here: <a href="https://data.humdata.org/dataset/global-droughts-events-1980-2001" rel="nofollow noreferrer">https://data.humdata.org/dataset/global-droughts-events-1980-2001</a></p>
<pre><c... | <p><code>ax.set_aspect('equal')</code> prevents the shifting on my end:</p>
<pre class="lang-py prettyprint-override"><code>for y in dr_geometry.year.unique():
clear_output(wait=True)
fig, ax = plt.subplots(1, 1, figsize=(15, 15))
world_geometry.plot(ax=ax)
dr_geometry[dr_geometry.year == y].plot(ax=ax,... | python|matplotlib|seaborn|geopandas | 0 |
19,654 | 47,378,149 | Python Pandas sorting multiindex by column, but retain tree structure | <p>Using pandas 0.20.3 I am trying to sort the n multilevels of a dataframe by a column ('D') with values (descendlingly) such that the hierarchy of the groups is maintained.</p>
<p>Example input:</p>
<pre><code> D
A B C
Gran1 Par1 Child1 3
Child2 7
Child3 2
... | <p>You need to create three separate arrays and sort by the combination of all them. In this example, I use Numpy's <code>np.lexsort</code> to do the sorting and then I use <code>iloc</code> to respect that sort. At the end, I use <code>a[::-1]</code> to get the reverse sort.</p>
<pre><code>a = np.lexsort([
df.D... | python|pandas|sorting|tree|multi-index | 0 |
19,655 | 47,175,464 | RNN can't learn integral function | <p>For studying deep learning, RNN, LSTM and so on I tried to make RNN fit integration function. I have put random signal from 0 to 1 as input to RNN and made integral from biased by -0.5 input signal, made the limit for integral between 0:1 and put it as RNN target to learn. <a href="https://i.stack.imgur.com/nZPLc.pn... | <p>I have found the problem by myself. The problem was in some case of overfitting on latest data, as in reinforcement learning case overfitting can occur with exploiting latest strategy. As I was not using any mini-batches and applied optimiser directly after a new point of data, and as because of data points similar ... | time-series|lstm|integral|pytorch|rnn | 0 |
19,656 | 47,338,632 | Python / Pandas - get_group that has partial string | <p>I have a dataframe like this:</p>
<pre><code>name . profession
Alex . Data Analyst
Markus . Sales Manager
Carlos . Credit Analyst
Otavio . HR Manager
...
</code></pre>
<p>I need to know how many people in this dataframe has the string "Analyst" in its profession. The answer should be 2.</p>
<p>I'm trying to u... | <p>If you want the scalar answer, you can use this command:</p>
<pre><code>df.profession.str.contains('Analyst').sum()
</code></pre>
<p>Output:</p>
<pre><code>2
</code></pre>
<p>Or as a dataframe with <code>groupby</code>:</p>
<pre><code>df.assign(is_analyst = df.profession.str.contains('Analyst'))\
.groupby('is... | python|pandas | 3 |
19,657 | 47,238,926 | Running ParseySaurus | <p>I've been hacking around with Parsey McParseface and Parsey Universal. Google released their next version of the parser:</p>
<p><a href="https://research.googleblog.com/2017/03/an-upgrade-to-syntaxnet-new-models-and.html" rel="nofollow noreferrer">https://research.googleblog.com/2017/03/an-upgrade-to-syntaxnet-new-... | <p>There has been a stall in the issue <a href="https://github.com/tensorflow/models/issues/2822" rel="nofollow noreferrer">#2822</a> on github which makes it problematic to build syntaxnet with bazel. Instead I have modified the syntaxnet docker file and use that in my project. <a href="https://github.com/shubham0704/... | python|tensorflow|parsey-mcparseface | 0 |
19,658 | 47,189,831 | Pandas Series and the `in` operator | <p>This seems like strange and counter-intuitive behavior. Can anyone explain why this is designed like this?</p>
<pre><code>lkup = pd.Series({'fred':'Fred','amy':'Amy'})
for n in lkup:
print(n,' --> ',n in lkup)
>>>
Amy --> False
Fred --> False
</code></pre>
<p>Why is it giving me the <em>... | <blockquote>
<p>Why is it giving me the Values instead of the keys?</p>
</blockquote>
<p>Because it was programmed to make the in operator iterate over values, for display purposes, since your keys are considered the series indices.</p>
<blockquote>
<p>The reason I ask is that this actually turned out to be messi... | python|pandas|series | 0 |
19,659 | 47,529,792 | No module named 'tqdm' | <p>I am running the following pixel recurrent neural network (RNN) code using Python 3.6</p>
<pre><code>import os
import logging
import numpy as np
from tqdm import trange
import tensorflow as tf
from utils import *
from network import Network
from statistic import Statistic
</code></pre>
<p>However, there was an e... | <p>You need to install tqdm module, you can do it by using python pip.</p>
<pre><code>pip install tqdm
</code></pre>
<p>for more info <a href="https://pypi.python.org/pypi/tqdm#latest-pypi-stable-release" rel="noreferrer">tqdm</a></p> | python|tensorflow|pixel|rnn|tqdm | 59 |
19,660 | 68,447,320 | How to read AM/PM times in pandas? | <p>I am dealing with a csv file containing a column called <strong>startTime</strong>, containing times.</p>
<p>When opening this file with <strong>Excel</strong>, the times appear as AM/PM times in the formula bar, although the timestamps in the column appear improperly formatted:</p>
<p><a href="https://i.stack.imgur... | <p>Your csv file has text, not datetime, so you need to first convert text stored in this column to pandas datetime object, then you can convert this pandas datetime object to the kind of format that you want via a <code>strftime</code> method:</p>
<pre><code>pd.to_datetime(df['startTime']).dt.strftime(date_format = '%... | python|excel|pandas|parsing|timestamp | 1 |
19,661 | 68,402,233 | Loop to find range that number does not equal to zero | <p>I'm trying to write a loop to find out the range when the numbers does not equal to 0.</p>
<p>Let me show you sample data</p>
<pre><code>index Window No. Fuel Consumption
0 0 0
1 1 100
2 2 101.1
3 3 102.2
4 4 107.5
5... | <p>Another option:</p>
<pre><code>import numpy as np
zero = df['Fuel Consumption'] == 0
nonzero = df['Fuel Consumption'] != 0
# find start indices of all non zero sequences
start = np.flatnonzero(nonzero & zero.shift(fill_value=True))
# find end indices of all non zero sequences
end = np.flatnonzero(nonzero &... | python|pandas|loops | 1 |
19,662 | 68,242,270 | What is the most likely cause for this error? AttributeError: 'int' object has no attribute 'lower' | <p>I was following a Youtube tutorial to create a basic chatbot with deep learning (<a href="https://www.youtube.com/watch?v=wypVcNIH6D4" rel="nofollow noreferrer">https://www.youtube.com/watch?v=wypVcNIH6D4</a>)and encountered this problem. I was careful to create an exact copy of the code the way it was written.</p>
... | <p>According to the error message the error is in the</p>
<pre><code>wrds = [stemmer.stem(w) for w in doc]
</code></pre>
<p>and occurs when trying to apply string <code>lower</code> method to one of the <code>w</code> values.</p>
<p><code>doc</code> comes from the prior iteration</p>
<pre><code>for doc in enumerate(doc... | python|numpy|tensorflow|nltk | 0 |
19,663 | 59,273,523 | Adding columns to dataframe that show boolean based on column data type in python | <p>I'm trying to add columns to the dataframe that are booleans based on a determination of whether the current column being iterated through is alphanumeric, alphabetical, or numerical. Unfortunately, each of the columns are giving False for each of the boolean tests. The goal is that for a given column, how can I add... | <p>You can utilize the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> function in Pandas and thus enjoy the efficiency, example:</p>
<pre><code>dataframe['column1_is_alphanumeric'] = dataframe['column1'].apply(lambda x: ... | python|pandas|dataframe|alphanumeric|non-alphanumeric | 1 |
19,664 | 59,157,907 | Pandas: How to combine nunique and sum | <p>I am working with a dataframe similar to this:</p>
<p><code>id year losses revenue expenses
2 2014 1500 5000 400
1 2013 1000 2000 5600
1 2018 500 10000 2100
3 2019 1500 15000 500
2 2011 100 2100 500
4 2010 1200 400 2000
4 2014 1000 22000 1000</cod... | <p>Add parameters <code>sort=False</code> and <code>as_index=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a>:</p>
<pre><code>df = df.groupby('id', sort=False, as_index=False)['losses', 'revenu... | python|pandas|dataframe|pandas-groupby | 1 |
19,665 | 59,335,634 | how to create a dict from row in sublist? | <blockquote>
<p>With this DataFrame:</p>
</blockquote>
<pre><code>Gp Wo Me CHi
1 0 1 0
2 1 0 0
3 0 1 0
4 1 0 0
5 0 2 0
6 1 0 0
</code></pre>
<p>I would like create a dictionary like :</p>
<pre><code>a={'Gp':['Wo', 'Me','CHi']}
</code></pre>
<p>but in the case column 'Gp' row... | <p>You can use <code>df.itterrows()</code> and check if the row value of the column 'Me' is equal to 2 and write an if statement:</p>
<pre><code>for index, row in df.iterrows():
if row['Me'] == 2:
print({row['Gp']: [row['Wo'], [1, 1], row['CHi']]})
else:
print({row['Gp']: [row['Wo'], row['Me'],... | python|pandas|dictionary | 0 |
19,666 | 59,178,472 | Python: Working with dataframes of different sizes to create new columns based on datetime conditions | <p>I have 2 dataframes of different sizes in Python. The smaller dataframe has 2 datetime columns, one for the beginning datetime and one for the ending datetime. The other dataframe is bigger (more rows and columns) and it has one datetime column. </p>
<p>df A</p>
<pre><code>Date_hour_beginning Date_hour_end
3/8/2... | <p>Here is my solution. It is kind of a more verbose (and maybe more readable?) version of eva-vw's. eva-vw's uses the <code>.apply()</code> method which is the fastest way of looping over the rows of your dataframe. However it should only make a significant difference in run time if your <code>df_A</code> has really m... | python|pandas|dataframe|datetime | 2 |
19,667 | 13,869,173 | Numpy: find index of the elements within range | <p>I have a numpy array of numbers, for example, </p>
<pre><code>a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
</code></pre>
<p>I would like to find all the indexes of the elements within a specific range. For instance, if the range is (6, 10), the answer should be (3, 4, 5). Is there a built-in function to do thi... | <p>You can use <code>np.where</code> to get indices and <code>np.logical_and</code> to set two conditions:</p>
<pre><code>import numpy as np
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(np.logical_and(a>=6, a<=10))
# returns (array([3, 4, 5]),)
</code></pre> | python|numpy | 187 |
19,668 | 56,970,347 | How to transpose and insert a Pandas column slice into a row slice? | <p>Trying to take a slice of a column from one Pandas dataframe, transpose the slice, and insert it into a similarly sized row slice, in a different dataframe. Labels and indexes in both dataframes are different. With large dataframes, am currently running a for loop to copy each individual value, cell-by-cell as it we... | <p>Convert values to numpy array for avoid data alignment - pandas try match index and columns each other and if failed, create missing values or not assign values:</p>
<pre><code>#pandas 0.22+
df1.loc[1, 'B':'E'] = df2.loc[1:4, 'M'].transpose().to_numpy()
#pandas below
#df1.loc[1, 'B':'E'] = df2.loc[1:4, 'M'].transpo... | python|pandas|insert|slice|transpose | 2 |
19,669 | 57,032,580 | Finding overlaps between millions of ranges/intervals | <p><strong>I am trying to find pairs of intervals that overlap by at least some minimum overlap length that is set by the user.</strong> The intervals are from this pandas dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pds
print(df1.head())
print(df1.tail())
</code></pre>
<pre><code>... | <p><a href="https://github.com/biocore-ntnu/pyranges" rel="nofollow noreferrer">pyranges</a> author here. Thanks for trying my library.</p>
<p>How big are your data? When both PyRanges were 1e7 rows, the heavy part done by pyranges took about 12 seconds using 24 cores on a busy server with 200 gb ram.</p>
<p>Setup:</... | python|pandas|algorithm|pyranges | 1 |
19,670 | 45,902,991 | Selectively converting float to whole number and decimals in Python pandas | <p>I am reading data from multiple csv, applying some filters and merging them into a dataframe. The original data in csv is only numbers/fractions. Pandas is converting them into float. Thats OK but I need just 1 column to remain as it is. To convert that back to integer, I tried :</p>
<pre><code>df['PRICE']=df['PRIC... | <p>You can re-initialise the dataframe using the <code>pd.DataFrame</code> constructor with <code>dtype=object</code>:</p>
<pre><code>print(df)
Col1
0 1152.00
1 1216.50
2 1226.65
df = pd.DataFrame(df, dtype=object)
print(df)
Col1
0 1152
1 1216.5
2 1226.65
</code></pre>
<p>Or, if it's just one... | python|pandas|dataframe|types|type-conversion | 4 |
19,671 | 46,035,082 | ImageProcessing with multiple threshold to binarize phases on skimage.io´s imread() | <p>i`m trying to figure out how to binarize a RGB.png file over its histogram intensities. </p>
<p><a href="https://i.stack.imgur.com/D3TEM.png" rel="nofollow noreferrer">Example: smoothed RGB intensities with estimated thresholds for R,G,B</a></p>
<p>This works so far that i can apply thresholding values for one int... | <p>after trying a lot of things, the inverse operator got it for me.
it seems like this works as </p>
<p>"give me all pixels, not included in phase1,phase3"</p>
<p><code>phase2 = ~(np.logical_and(phase1,phase3))</code></p>
<p>needing more than 3 phases, i would still not know how to handle this..</p> | python|numpy|image-processing | 0 |
19,672 | 23,028,897 | Explode a nested pandas dataframe out as columns, and repeat parent rows for each of its row | <p>I have a pandas DataFrame that's basically akin to something like this:</p>
<pre class="lang-py prettyprint-override"><code>import json
import pandas as pd
df = pd.DataFrame([
{'a': 1, 'b': 2, 'extra': 0},
{'a': 10, 'b': 20, 'extra': 0}
])
df_c1 = pd.io.json.read_json(json.dumps({'row1': {'c1': -1, 'c2'... | <p>I don't know why you create a column that every element is a dataframe. But you can use <code>pandas.concat</code> and <code>pandas.merge</code> to do the job:</p>
<pre><code># your setup code here
df2 = pd.concat(df['c'].tolist(), keys=df.index)
df3 = pd.merge(df[["a", "b"]], df2, left_index=True, right_on=df2.ind... | python|pandas|dataframe | 2 |
19,673 | 11,811,392 | How to generate a list from a pandas DataFrame with the column name and column values? | <p>I have a pandas dataframe object that looks like this:</p>
<pre><code> one two three four five
0 1 2 3 4 5
1 1 1 1 1 1
</code></pre>
<p>I'd like to generate a list of lists objects where the first item is the column label and the remaining list values are the column data... | <p>Simplest way is probably <code>list(dt.T.itertuples())</code> (where <code>dt</code> is your dataframe). This generates a list of tuples.</p> | python|pandas | 36 |
19,674 | 28,865,594 | Pandas Time Grouper: Custom Ranges | <p>Conditional on a <code>datetime</code> index, <code>pd.TimeGrouper("AS")</code> groups my data by calendar years. There is a <a href="http://pandas.pydata.org/pandas-docs/dev/timeseries.html#offset-aliases" rel="nofollow">variety of useful offsets</a> shipped with <code>pandas</code> - but what if I want my own one?... | <p>Looks like that's in the next section on <a href="http://pandas.pydata.org/pandas-docs/dev/timeseries.html#combining-aliases" rel="nofollow">combining offsets</a>, eg:</p>
<pre><code>In [40]: rng = date_range('1/1/2015', periods=365, freq='D')
In [41]: d = Series(range(0, len(rng)), index=rng)
</code></pre>
<p>Gro... | python|pandas | 3 |
19,675 | 28,770,963 | Wrapping custom type C++ pointer in Cython | <p>What is the best way to wrap a custom type C++ pointer using Cython? </p>
<p>For example:</p>
<pre><code>import numpy as np
cimport numpy as np
cdef extern from "A_c.h"
cdef cppclass A:
A();
void Foo(A* vec);
cdef class pyA:
cdef A *thisptr
def ___cinit___(self):
self.thisptr = ... | <p>Basically every time you want to pass an object of type <code>A</code> or a pointer to it you should use a Python object of type <code>pyA</code> - which is actually very similar to a pointer apart from the fact that it has reference counting, so it is like a <a href="http://en.cppreference.com/w/cpp/memory/shared_p... | python|c++|pointers|numpy|cython | 3 |
19,676 | 50,867,308 | pandas.read_csv() interprets TRUE as boolean, I need a string | <p>I'm reading stock tickers from comma delimited file using pandas.read_csv(). One of the tickers is TRUE, so pandas reader interprets it as a boolean, and fails, since it needs a string to retrieve prices. How can I force TRUE into a string?</p> | <p>Specify the dtype of the desired column in the <code>read_csv</code> method call:</p>
<pre><code>pd.read_csv('weirdly_formatted_csv.csv', dtype={'weird_column': str})
</code></pre> | python|pandas|type-conversion | 3 |
19,677 | 33,444,110 | Building / Installation NumPy | <p>i want to work with NumPy. Now i'm trying to install NumPy on Windows. I do not understand, what i have to do to get it working. What does "building" mean? is there any difference between the installation and "building from source".</p>
<p>Thanks for any help.</p> | <p>Probably the easiest approach to installing Numpy (and the rest of the Python 'scientific stack' including SciPy an many others) is to use Continuum Analytics' "Anaconda" tools. </p>
<p><a href="http://docs.continuum.io/anaconda/install#windows-install" rel="nofollow">http://docs.continuum.io/anaconda/install#windo... | numpy|building | 0 |
19,678 | 33,513,204 | Finding intersection of two matrices in Python within a tolerance? | <p>I'm looking for the most efficient way of finding the intersection of two different-sized matrices. Each matrix has three variables (columns) and a varying number of observations (rows). For example, matrix A:</p>
<pre><code>a = np.matrix('1 5 1003; 2 4 1002; 4 3 1008; 8 1 2005')
b = np.matrix('7 9 1006; 4 4 1007; ... | <p>If you don't mind working with NumPy arrays, you could exploit <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> for a vectorized solution. Here's the implementation -</p>
<pre><code># Set tolerance values for each column
tol = [1, 2, 10]
# Get abs... | python|numpy|matrix|vectorization|intersection | 5 |
19,679 | 9,112,071 | bpython configuration - importing numpy and matplotlib by default | <p>Is it possible to start the <a href="http://bpython-interpreter.org/" rel="noreferrer">bpython</a> interpreter so that it always runs some custom commands when it launches?</p>
<p>In my case I simply want to do:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
</code></pre>
<p>I can't see anythin... | <p>It is written in the docs, just not clearly labelled as such at: <a href="http://docs.bpython-interpreter.org/django.html">http://docs.bpython-interpreter.org/django.html</a></p>
<p>Gist of it is you can have an environment variable called <code>PYTHONSTARTUP</code>. bpython will execute this file before you get dr... | python|numpy|bpython | 5 |
19,680 | 66,722,985 | Delete duplicated rows in torch.tensor | <p>I have a <code>torch.tensor</code> of shape <code>(n,m)</code> and I want to remove the duplicated rows (or at least find them). For example:</p>
<pre><code>t1 = torch.tensor([[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]])
t2 = remove_duplicates(t1)
</code></pre>
<p><code>t2</code> should be now equal to <code>tensor(... | <p>You can simply exploit the parameter dim of torch.unique.</p>
<pre><code>t1 = torch.tensor([[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9]])
torch.unique(t1, dim=0)
</code></pre>
<p>In this way you obtain the result you want:</p>
<pre><code>tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
</code></pre>
<p><a... | python|python-3.x|duplicates|pytorch|unique | 4 |
19,681 | 66,752,774 | panda's dataset.column to numpy | <p><strong>dataset.columns[attribute_index]</strong></p>
<p>I don't understand what the line above does, and I can't figure it out how to do the same in NumPy.
Can anyone please guide me?</p> | <p>What you said should be "pandas" <code>DataFrame.columns[index]</code><br />
The method to convert <code>DataFrame.columns</code> to <code>numpy array</code> is:</p>
<pre><code>df.columns.to_numpy()
</code></pre> | python|pandas|dataframe|numpy | 0 |
19,682 | 66,523,039 | Reshaping Arrays in Python | <p>How do I reshape a numpy array ? The array that I want to reshape is called C4 and currently has a shape of:</p>
<p>C4 shape: (606976,)</p>
<p>I want to rehsape it to (1,)</p>
<p>or I want to reshape an array of shape (1,) to shape (606976,). How do I go about doing this ?</p> | <p>You can do this in two ways -</p>
<ul>
<li><p>using reshape method</p>
<pre><code>c4 = c4.reshape(1, 606976)
</code></pre>
</li>
<li><p>using transpose method</p>
<pre><code>c4 = c4.T
</code></pre>
</li>
</ul> | python|arrays|numpy|reshape | 0 |
19,683 | 16,058,020 | smart way to read multiple variables from textfile in python | <p>I'm trying to load multiple vectors and matrices (for numpy) that are stored in a single text file.
The file looks like this:</p>
<pre><code>%VectorA
1 2 3 4
%MatrixA
1 2 3
4 5 6
%VectorB
3 4 5 6 7
</code></pre>
<p>The ideal solution would be to have a dictionary object like:</p>
<pre><code>{'VectorB': [3, 4, 5, ... | <pre><code>from StringIO import StringIO
mytext='''%VectorA
1 2 3 4
%MatrixA
1 2 3
4 5 6
%VectorB
3 4 5 6 7'''
myfile=StringIO(mytext)
mydict={}
for x in myfile.readlines():
if x.startswith('%'):
mydict.setdefault(x.strip('%').strip(),[])
lastkey=x.strip('%').strip()
else:
mydict[lastke... | python|numpy | 5 |
19,684 | 57,429,837 | Unstack MultiIndex data frame | <p>I am writting a test case with this multi-index data frame but I am unable to unstack. The following function produces exactly the layout I am reading from an excel file just this like this sample: <a href="https://wetransfer.com/downloads/ea64ba2ede55f97949e37d78d10e499420190808094138/db4903" rel="nofollow noreferr... | <p>Here is problem one level <code>MultiIndex</code> in index, so <code>unstack</code> failed with very weird errors.</p>
<pre><code>print (df.index.nlevels)
1
#correct 2 level MultiIndex in columns
print (df.columns.nlevels)
2
print (df.index)
MultiIndex([('USER 1',),
('USER 2',),
('USER 3',)... | python|pandas|multi-index | 2 |
19,685 | 57,666,461 | How to prevent numpy from collapsing rows? | <p>I have a function which takes a numpy array and outputs a numpy array. However, when the output array contains a constant value, calling the function with a numpy array results in said value being "collapsed".</p>
<p>I'm trying to write a vector calculus library using numpy, and would like to pass vectors to vector... | <pre><code>In [183]: r1 = lambda t: np.array([2*t, 1])
...: r2 = lambda t: np.array([2*t, 1+0*t])
...: t = np.linspace(0, 1)
In [184]: r1(t) ... | python|numpy|numpy-ndarray|numpy-ufunc | 1 |
19,686 | 57,677,160 | Cannot Import Name 'keras_export' From 'tensorflow.python.util.tf_export' | <p>I am trying to use the BERT in Keras with keras_bert and tensorflow, the complete code is <a href="https://colab.research.google.com/github/CyberZHG/keras-bert/blob/master/demo/tune/keras_bert_classification_tpu.ipynb#scrollTo=gGzsxkLTpRrs&uniqifier=1" rel="nofollow noreferrer">here</a>, but I am getting this er... | <p>Tensorflow is not uninstalled when tensorflow-gpu is install. That is the problem in importing the keras_import. So if we uninstall the tensorflow then the problem is solved.</p>
<blockquote>
<p>tensorflow_version 2.x<br />
!pip uninstall -y tensorflow<br />
!pip install tensorflow-gpu==1.14.0</p>
</blockquote>
<p>H... | python|python-3.x|tensorflow|keras | 4 |
19,687 | 57,632,477 | organize collected entries in a dataframe | <p>I have a dataframe with answers of a survey. Each person answers 3 questions. Unfortunately, each line of the dataframe correspond to an answer of a question, rather than a person entry.</p>
<p>How can I reformat that?</p>
<p>Currently I have a dataframe that has columns set as:</p>
<p><code>person_id</code>, <co... | <p>Simpler way to do is to use <code>unstack</code> with <code>set index</code>:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame([
[1,'James', 20, 'question 1', 'Yes'],
[1,'James', 20, 'question 2', 'No'],
[1,'James', 20, 'question 3', 'Maybe'],
[2,'Elle', 20, 'question 1', 'No'],... | python|pandas|jupyter-notebook | 3 |
19,688 | 57,559,071 | Setting index using commonly occurring column value as index of the data frame | <p>I have a <code>df</code> as follows:</p>
<pre><code>ID MAHACEB ID MOROPEX ID OTX01 ID MAPOXUB
A0AVT1 48 A0AVT1 23 A0A0B4J2F0 22 A0AVT1 38
A0FGR8 35 A0FGR8 19 A0A0U1RRE5 3 A0FGR8 10
A0JLT2 28 A0JLT2 50 A0A1B0GUS4 10 A0JLT2 56
A0JNW5 35 A0JNW5 23 A0AV96 71 A0JNW5 26
A0MZ66 37 ... | <p>Your DataFrame is not easy to work with, as the column names are not unique. You should reshape your table into an appropriate format with columns <code>ID</code>, <code>Key</code> (the values of which would be <code>MAHACEB</code>, <code>MOROPEX</code>, etc. and <code>Value</code>. Then, you can obtain your result ... | python|pandas|dataframe | 1 |
19,689 | 57,539,335 | How to fix "ResourceExhaustedError: OOM ...."? | <p>i'm trying to train a simple MLP with a own dataset in Python with Keras. This dataset includes normalized images in a size of <strong>1024 x 1204</strong>, i need this resolution for therefore i can't decrease the size of the images. I use a <strong>Tesla V100 with 16GB</strong> for the training. </p>
<p>My aim i... | <p>There are three main things playing in this situation: the size of your inputs, the size of your network (number of parameters), and the GPU ram. Sadly those are considered large inputs, so your first bet is going to be turning down batch size. take it to 1, and if you still get this, either reduce your network or (... | python|tensorflow|machine-learning|memory|keras | 0 |
19,690 | 24,297,600 | Numpy extract values on the diagonal from a matrix | <p>My question is similar(the expanded version) to this post:<a href="https://stackoverflow.com/questions/24261347/numpy-extract-row-column-and-value-from-a-matrix">Numpy extract row, column and value from a matrix</a>. In that post, I extract elements which are bigger than zero from the input matrix, now I want to ext... | <p>You can use following method:</p>
<ol>
<li>get the mask array</li>
<li>fill diagonal of the mask to True</li>
<li>select elements where elements in mask is True</li>
</ol>
<p>Here is the code:</p>
<pre><code>m=np.array([[0,2,4],[4,0,0],[5,4,0]])
mask = m > 0
np.fill_diagonal(mask, True)
m[mask]
</code></pre> | python|arrays|numpy|indexing|diagonal | 1 |
19,691 | 43,811,743 | Convert nd array to key, value dictionary | <p>Is there a function in python to convert an nd-array into a dictionary where key is a tuple of index and value is the matrix value at that index?</p>
<p>For example:</p>
<pre><code>A = np.random.random([3,4,5])
</code></pre>
<p>Result:</p>
<pre><code>{(i,j,k): A[i,j,k]}
</code></pre> | <p>Sure: you can use <code>np.ndenumerate</code> to accomplish this:</p>
<pre><code>{ index: v for index, v in np.ndenumerate(A) }
</code></pre>
<p>Or simply, as DSM pointed out:</p>
<pre><code>dict(np.ndenumerate(A))
</code></pre> | python|arrays|numpy | 21 |
19,692 | 43,727,664 | TensorFlow Inference Graph - Loading and Restoring Variables impact | <p>This is closely related to a lot of questions, including one of my own here: <a href="https://stackoverflow.com/questions/43708616/tensorflow-inference">TensorFlow Inference</a> </p>
<p>Every sample in TensorFlow for inference appears to follow this form:</p>
<pre><code>import tensorflow as tf
import CONSTANTS
imp... | <p>So after a ton of review this is what happens...</p>
<ol>
<li><p>If you add anything to the graph before restoring the graph; the restored graph is appended to the already created graph.</p></li>
<li><p>Restoring variables looks for variable names in your graph at the time of restoring variables with the same name ... | python|tensorflow | 0 |
19,693 | 43,585,791 | Python: Apply function to groupby | <p>I have some dataframe in the form</p>
<pre><code>userid | event_time | activity
A 2017-01-01 02:20:34 E1
A 2017-01-01 02:20:50 E2
A 2017-03-01 11:23:43 E1
A 2017-03-01 11:23:55 E6
B 2017-01-01 08:24:32 E1 ... | <p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="noreferrer"><code>cumcount</code></a>, <code>df</code> has to be sorted by <code>userid</code> and <code>event_time</code> first:</p>
<pre><code>df['count'] = df.sort_values(['userid','ev... | python|pandas|group-by|apply | 5 |
19,694 | 43,507,491 | Imprecision with rotation matrix to align a vector to an axis | <p>I've been banging my head against the wall with this for several hours and I can't seem to figure out what I'm doing wrong. </p>
<p>I'm trying to <strong>generate a rotation matrix which will align a vector with a particular axis</strong> (I'll ultimately be transforming more data, so having the rotation matrix is ... | <p>You need to norm <code>uvw</code> for that to work. So replace</p>
<p>u, v, w = np.cross(i_v, unit)</p>
<p>With</p>
<pre><code>uvw = np.cross(i_v, unit)
uvw /= np.linalg.norm(uvw)
</code></pre>
<p>Which is basically the same as the <code>i_v = np.divide(i_v, np.sqrt(np.dot(i_v, i_v)))</code> line you already had... | python|numpy|rotation|linear-algebra|rotational-matrices | 3 |
19,695 | 43,578,258 | Pandas read_excel, csv; names column names mapper? | <p>Suppose you have a bunch of excel files with ID and company name. You have N number of excel files in a directory and you read them all into a dataframe, however, in each file company name is spelled slightly differently and you end up with a dataframe with N + 1 columns.</p>
<p>is there a way to create a mapping f... | <p>Are you concatenating the files after you read them one by one? If yes, you can simply change the column name once you read the file. From you question, I assume your dataframe only contains two columns - Id and CompanyName. So, you can simply change it by indexing.</p>
<pre><code>df = pd.read_csv(one_file)
df.rena... | python|excel|pandas | 1 |
19,696 | 72,997,487 | Find columns in Pandas DataFrame containing dicts | <p>I have a pandas DataFrame with several columns containing <code>dicts</code>. I am trying to identify columns that contain at least 1 dict.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'i': [0, 1, 2, 3],
'd': [np.nan, {'p':1}, {'q':2}, np.nan],
... | <p>You can do :</p>
<pre><code>s = df.applymap(lambda x:isinstance(x, dict)).any()
dict_cols = s[s].index.tolist()
</code></pre>
<p>print(dict_cols)</p>
<pre><code>['d', 't']
</code></pre> | python|pandas | 3 |
19,697 | 72,876,505 | what is the difference between df.drop(inplace=True) and df = df.drop()? | <p>I usually use below two types of code to drop columns in pandas.</p>
<pre><code>df = df.drop([columns], axis=1)
# or
df.drop([columns], axis=1, inplace=True)
</code></pre>
<p>the result is perfectly same, but I'm curious</p>
<p>which one spent lesser memory&CPU and why?</p> | <ol>
<li><em>df.dropna(inplace=true)</em></li>
</ol>
<p>If you set inplace = True , the dropna method will modify your DataFrame directly. That means that if you set inplace = True , dropna will drop all missing values from your original dataset.</p>
<ol start="2">
<li><em>df = df.dropna()</em></li>
</ol>
<p>Remove all... | pandas | 1 |
19,698 | 72,971,576 | Can we get columns names sorted in the order of their tf-idf values (if exists) for each document? | <p>I'm using sklearn TfIdfVectorizer. I'm trying to get the column names in a list in the order of thier tf-idf values in decreasing order for each document? So basically, If a document has all the stop words then we don't need any column names.</p>
<pre><code>import pandas as pd
from sklearn.feature_extraction.text im... | <p>The combination of the following function and to_dict() method on dataframe can give you the desired output.</p>
<pre>
def ret_dict(_dict):
# Get a list of unique values
list_keys = list(set(_dict.values()))
processed_dict = {key:[] for key in list_keys}
# Prepare dictionary
for key, value i... | python-3.x|pandas|tf-idf|columnsorting|tfidfvectorizer | 1 |
19,699 | 73,163,617 | My tensorflow defaults to using my GPU instead of CPU, which is like 10 times slower. How do I fix this and make it use the CPU? | <p>I have one of those gaming laptops with a discrete GPU and dedicated GPU (NVIDIA GeForce RTX 3070).</p>
<p>I was getting very slow speeds training neural networks on tensorflow. Many, many times slower than another laptop with vastly inferior specs in CPU and GPU.</p>
<p>I think the reason for this slowness is becau... | <p>Just tell tensorflow to do so:</p>
<pre><code>with tf.device("/CPU:0"): #name might vary
model.fit(...)
</code></pre> | tensorflow|anaconda | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.