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 |
|---|---|---|---|---|---|---|
20,800 | 68,836,125 | Pandas Handling overflows without a loop | <p>I have a device that collects data. Type of values are 64 bit unsigned integers in two columns of this data (col1, col2). These values may overflow in some extreme cases and I need to handle them, but with conditions.</p>
<p>There are 4 columns: uptime, type, col1, col2. The conditions will be checked on <strong>upt... | <p>So if I understand well, you’re saying that for any <code>type</code> value, <code>col1</code> and <code>col2</code> need to be monotonically increasing over <code>time</code>.</p>
<p>First we can construct a variable that’s <code>True</code> every time we go back in time or change <code>type</code>:</p>
<pre><code>... | python|pandas | 1 |
20,801 | 68,596,292 | How to re-number strings after sorting a dataframe | <p>Description:
I have a GUI that allows the user to add variables that are displayed in a dataframe. As the variables are added, they are automatically numbered, ex.'FIELD_0' and 'FIELD_1' etc and each variable has a value associated with it. The data is actually row-based instead of column based, in that the 'FIELD' ... | <p>It appears you're looking to overwrite the Field values so that they always appear in order starting with 0.</p>
<p>We can filter to only rows which <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a> the word FIELD. Then assi... | python|pandas|sorting | 1 |
20,802 | 5,393,205 | Condition checking when using numpy.piecewise to generate a piecewise periodic plot | <p>I'm trying to generate a piecewise periodic plot using Numpy and matplotlib, like this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
Q1 = lambda t, f, Q_max: Q_max * np.sin(2 * np.pi *f * t)
Q2 = lambda t, f, Q_max: 0
def Q_true(t, f, stat):
while(t >= 1/f):
t -= 1/f
while... | <p>The following version of <code>Q_true</code> works:</p>
<pre><code>def Q_true(t, f, stat):
period = 1/f
return (t % period < period/2) == stat
</code></pre>
<p>Note that you are naming your anonymous functions (<code>Q1 = lambda ...</code>). In this case you should just define the function using <code>d... | python|numpy|matplotlib|piecewise | 2 |
20,803 | 53,315,282 | Cannot read .7z file in Google Colab | <p>I am using Google Colab to create a deep learning model, and I face an issue when I run this code at the <strong>first time</strong>.</p>
<pre><code>!p7zip -d filename.7z
</code></pre>
<p>I get the following message:</p>
<pre><code>/usr/bin/p7zip: cannot read filename.7z
</code></pre>
<p><strong>But</strong> whe... | <p>First, you have to specify path before the file name
in my case</p>
<pre><code>!mkdir ~/data
!cd ~/data
!mkdir planet
!cd planet
# -c: competition name
# -f: which file you want to download
# -p: path to where the file should be saved
!kaggle competitions download -c planet-understanding-the-amazon-from-space -f ... | tensorflow|keras|neural-network|deep-learning|google-colaboratory | 0 |
20,804 | 52,987,371 | Python versatile Index slicing | <p>Hoping someone can help me with the logic of transforming this Excel logic to python</p>
<pre><code>=IF(LEFT(A8,5)="Total",A9,I8)
</code></pre>
<p>So I am looking to find everything in a range and then creating a new column with the first element in the range. The problem is that the names of the ranges can change... | <p>Use:</p>
<pre><code>df = pd.read_csv('PL2.csv', encoding='cp1252', engine='python')
#create helper df for total strings
df1 = df.loc[df.iloc[:, 0].str.startswith('Total', na=False), df.columns[0]].to_frame('total')
#first column without Total -
df1['first'] = df1['total'].str.replace('Total - ', '')
print (df1.h... | python|pandas|indexing|data-modeling|data-cleaning | 1 |
20,805 | 65,714,756 | how to train GANs properly | <p>I started experimenting with gans and on the internet, there are a lot of options the thing I worry about now is which one should I use Keras fit or Keras train_on_batchs which one is the proper way to train the model thanks</p> | <p>According to tensorflow's documentation, the combination of <code>tf.data</code> & <code>model.train_on_batch()</code> is the fastest way to train a model.
You can check more about <code>tf.data</code> in the link below:
<a href="https://www.tensorflow.org/guide/data" rel="nofollow noreferrer">https://www.tensor... | python|tensorflow|keras|deep-learning|generative-adversarial-network | 0 |
20,806 | 65,900,172 | How to create subplots using a for loop on different dataframes | <p>I've made the function "correlationCalculator" which is intended to visualize the correlation between two variables at 36 different locations.</p>
<pre><code>def correlationCalculator(location):
df_testLocation = getLocationDF(location, '2019-01-1', '2020-01-1')
plt.figure(figsize=(4,3))
plt.scat... | <p>I got it to work</p>
<pre><code>def correlationCalculator(location, ax, j):
df_testLocation = getLocationDF(location, '2019-01-1', '2020-01-1')
ax[j].scatter(df_testLocation['gem_intensiteit'], df_testLocation['gem_snelheid'], s = 0.5)
z = np.polyfit(df_testLocation['gem_intensiteit'], df_testLocation['gem_snelhei... | pandas|dataframe|matplotlib | 2 |
20,807 | 20,990,538 | How can I cluster a list of a list of tuple (tag, probability)? - python | <p>I have a bunch of text and they are classified into categories and then each document is tagged 0, 1 or 2 with a probability for each tag.</p>
<pre><code>[ "this is a foo bar",
"bar bar black sheep",
"sheep is an animal"
"foo foo bar bar"
"bar bar sheep sheep" ]
</code></pre>
<p>The previous tool in the pi... | <p>If I understood correctly, this is what you wanted.</p>
<pre><code>import numpy as np
N_TYPES = 3
instream = [ [(0,0.3), (1,0.5), (2,0.1)],
[(0,0.5), (1,0.3), (2,0.3)],
[(0,0.4), (1,0.4), (2,0.5)],
[(0,0.3), (1,0.7), (2,0.2)],
[(0,0.2), (1,0.6), (2,0.1)] ]
instr... | python|numpy|machine-learning|scikit-learn | 2 |
20,808 | 63,634,711 | How to filter only specific dates from a dataframe in python? | <p>I have a dataframe with 1000 records. I am trying to filter only the below Dates record from the <code>df</code></p>
<p>2020-06-09</p>
<p>2020-08-06</p>
<p>2020-08-25</p>
<p>I have tried the below code hoping that my code will filter only those records available for that particular date.</p>
<p><code>df[(df['Date'] ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html" rel="nofollow noreferrer"><code>isin</code></a>:</p>
<pre><code>df = df[df['date'].isin(['2020-06-09', '2020-08-06', '2020-08-25'])]
</code></pre>
<hr />
<p><strong>Method 2</strong></p>
<pre><code>dates = ['2... | python|pandas | 1 |
20,809 | 63,615,386 | Saving images to csv file and then reading it from csv file | <p>I have converted images into csv using below code:</p>
<pre><code>import pandas as pd
from PIL import Image
import numpy as np
image_array = []
for name in combined_df['path']:
image_array.append(np.array(Image.open(name)))
image_df_1 = pd.DataFrame(image_array) #Then coverted list to dataframe
image_d... | <p><strong>Short answer:</strong></p>
<p>The answer is 1: while saving into csv, the multidimentional DataFrame becomes simple strings. So after reading from csv, the DataFrame cell types become str.
=> The type of <code>csv_df.iloc[0][0]</code> is <code>str</code> after reading from a csv. but the type of <code>ima... | python|pandas|numpy|csv|python-imaging-library | 1 |
20,810 | 21,876,585 | Array assignment in Python | <p>I am a novice as far as python programming is introduced. Currently I am trying to understand one python program as per my requirement. While going through program,I found this confusing statement:</p>
<pre><code>circleMap = [np.average(map[:, 0]), np.average(map[:, 1]), np.average(map[:, 2])]
map= globalMap[sel... | <ol>
<li>the <code>map</code> here is an numpy array with <strong><em>at least</em></strong> 2 dimensions;</li>
<li><code>circleMap</code> is a 1D builtin list, because <code>np.average</code> here returns a float;</li>
<li><code>circleMap = [np.average(map[:, 0]), np.average(map[:, 1]), np.average(map[:, 2])]</code> c... | python|python-2.7|numpy | 0 |
20,811 | 21,639,825 | Cannot install scipy on Mac OS X | <p>I have repeatedly tried to install SciPy on my mac, using various different tutorials, but whenever I run the nosetests or try to use SciPy I always get "ImportError: No module named scipy." Even <a href="http://www.scipy.org/install.html" rel="nofollow">http://www.scipy.org/install.html</a> didn't work, even though... | <p>Resolved: I couldn't get it to work at all so I just downloaded Enthought Canopy. Not ideal that MacPorts tutorials failed so completely but it doesn't matter now.</p> | python|macos|numpy|installation|scipy | 0 |
20,812 | 21,790,505 | Missing data in Python | <p>I'm trying to import a JSON file into Python to do some data analysis. Each JSON object has a lot of different variables in it (about 7-10). Some objects have certain variables, while other objects don't. I am interested in specifically five variables from each json line. However, some objects have missing data. How... | <p>Rather than filling in the missing data, when you try to retrieve the data from the object, instead of the usual: <code>x['field']</code>, try <code>x.get('field')</code>. </p>
<p>e.g.:</p>
<pre><code>with open('test.json') as json_data:
for line in json_data:
dataline = json.loads(line)
row... | python|json|numpy|pandas|bigdata | 6 |
20,813 | 24,840,028 | To print the elements lying within a bin | <p>I wanted my code to print only when the if condition is satisfied and then empty the array to print the next results </p>
<pre><code>import numpy as np
r = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.000570290882095, 0.0107443912719, 0.0124509177244,
0.0125, 0.0125, 0.025, 0.025, 0.025,
... | <p>What you seem to want is to split <code>r</code> into bins with width <code>0.05</code>. A more NumPyish way of doing this could be to search the break-point indices:</p>
<pre><code># find the indices for the break points (0, 0.05, 0.10, .., 1.00)
bpoints = np.searchsorted(r, np.arange(0, 1+.01, 0.05), side='left')... | python|numpy | 1 |
20,814 | 30,242,323 | pandas - drop rows under Datetime criteria | <p>I'm working on a Dataframe df:</p>
<pre><code>Datetime,User
2013-12-04 08:00:01,111
2013-12-04 09:00:02,111
2013-12-04 10:00:03,111
2013-12-04 09:00:04,112
2013-12-04 10:00:05,112
2013-12-04 11:00:06,112
2013-12-04 11:00:07,113
2013-12-04 11:00:08,113
2013-12-04 11:00:09,113
2013-12-04 13:00:10,114
2013-12-04 13:00... | <p>There is probably a nicer way to do this, but that's how I would do it:</p>
<pre><code>import pandas as pd
# First set up the dataframe
Datetime = ['2013-12-04 08:00:01',
'2013-12-04 09:00:02',
'2013-12-04 10:00:03',
'2013-12-04 09:00:04',
'2013-12-04 10:00:05',
... | python|datetime|pandas | 2 |
20,815 | 53,772,787 | tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)) in tensorflow | <p>What is purpose of <code>tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS))</code> in tensorflow?</p>
<p>With more context:</p>
<pre><code> optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
train_op = op... | <p>The method <code>tf.control_dependencies</code> allow to ensure that the operations used as inputs of the context manager are run before the operations defined inside the context manager.</p>
<p>For example: </p>
<pre><code>count = tf.get_variable("count", shape=(), initializer=tf.constant_initializer(1), trainabl... | python|tensorflow|deep-learning | 6 |
20,816 | 53,765,203 | How can I turn this DataFrame into a DataFrame with average score by Index Value? | <p>I have the below DataFrame, with wine variety, reviewer and score. I'd like to make a new DataFrame that outputs variety as the column labels and lists the average score by reviewer and variety. Simply stated I'd like to output a DataFrame with variety at the top and reviewer as the index with the average score by... | <p>More like a <code>pivot</code> problem </p>
<pre><code>pd.pivot_table(df,index='Reviewer',columns='Variety',values='Score',aggfunc='mean')
Out[29]:
Variety Cabernet Pinot
Reviewer
Bill 87.000000 87.666667
Sally 84.666667 93.000000
</code></pre> | python|pandas|dataframe | 3 |
20,817 | 12,606,619 | Creating a dynamic Array in numpy Capi | <p>I have a dynamic 2 dimensional C array, for example an array that created by this code:</p>
<pre><code>double **multiDyArr=(double**)malloc(sizeof(double*)*3);
multiDyArr[0]=(double*)malloc(sizeof(double)*3);
multiDyArr[1]=(double*)malloc(sizeof(double)*17);
multiDyArr[2]=(double*)malloc(sizeof(double)*11);
</code>... | <p>Numpy arrays are always a single block of memory, the closest python datatype to map this to is a python list, tuple or object array of arrays. Even if you had it all in one memory block that would not help as numpy arrays have to be regular.</p> | python|c|numpy|multidimensional-array|python-c-api | 1 |
20,818 | 71,845,644 | When I combine two pandas columns with zip into a dict it reduces my samples | <p>I have two colums in pandas: <code>df.lat</code> and <code>df.lon</code>.
Both have a length of 3897 and 556 NaN values.
My goal is to combine both columns and make a dict out of them.</p>
<p>I use the code:</p>
<pre><code>dict(zip(df.lat,df.lon))
</code></pre>
<p>This creates a dict, but with one element less than ... | <p>You may have a different length if there are repeated values in <code>df.lat</code> as you can't have duplicate keys in the dictionary and so these values would be dropped.</p>
<p>A more flexible approach may be to use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html" rel="nofo... | python-3.x|pandas|dictionary|zip | 1 |
20,819 | 72,061,934 | UserWarning: Using a target size (torch.Size([1])) that is different to the input size (torch.Size([1, 1])) | <p>I have this code:</p>
<pre><code> actual_loes_score_g = actual_loes_score_t.to(self.device, non_blocking=True)
predicted_loes_score_g = self.model(input_g)
loss_func = nn.L1Loss()
loss_g = loss_func(
predicted_loes_score_g,
actual_loes_score_g,
)
</code></pre>
<p>where <code>pred... | <pre><code>predicted_loes_score_g = tensor([[-24.9374]], grad_fn=<AddmmBackward0>)
</code></pre>
<p>which is size [1,1]</p>
<pre><code>actual_loes_score_g = tensor([20.], dtype=torch.float64)
</code></pre>
<p>which is size [1]</p>
<p>You need to either remove a dimension from your prediction or add a dimension to... | deep-learning|pytorch | 1 |
20,820 | 72,048,624 | exporting list into a csv file using python | <p>first of all im still learning python and im having a good time so far. while learning I ran into this issue
I have a variable named MyList as follows</p>
<pre><code>MyList = [{'orange', 'Lemon'},
{'Apple', 'Banana', 'orange', 'Lemon'},
{'Banana', 'Lemon'},
{'Apple', 'orange'}]
</code></pre>
<p>I want to dump the... | <p>You'll need to use the <code>csv</code> module and open a file for write:</p>
<pre><code>import csv
MyList = [{'orange', 'Lemon'},
{'Apple', 'Banana', 'orange', 'Lemon'},
{'Banana', 'Lemon'},
{'Apple', 'orange'}]
with open('MyList.csv', 'w') as f:
# using csv.writer method from csv module
write =... | python|pandas|dataframe|csv|export-to-csv | 1 |
20,821 | 71,997,452 | Insert in list comprehension | <p>I have two lists, both containing numpy arrays of the same dimensions.</p>
<p>To simplify, <code>a</code> and <code>b</code> are here represented as ints and strings:</p>
<pre><code>a = [0, 1, 2, 3]
b = ['a', 'b', 'c']
</code></pre>
<p>I would like to insert a value for <code>b</code> in <code>a</code>, at each pos... | <p>You could try:</p>
<pre><code>a = [0, 1, 2, 3]
b = ['a', 'b', 'c']
arr = np.tile(np.array(a, dtype='str'), (len(a) - 1, 1))
idx = np.arange(len(arr) + 1)
arr[idx[:-1], idx[1:]] = b
result = list(arr)
</code></pre>
<p>Result:</p>
<pre><code>[array(['0', 'a', '2', '3'], dtype='<U1'),
array(['0', '1', 'b', '3'], d... | python|numpy | 0 |
20,822 | 71,840,283 | How to crop an image based on its coordinates in Python Opencv | <p>I am drawing a cv2 rectangle by using below line</p>
<pre><code>cv2.rectangle(rightImg, (x, y), (x + w, y + h), (0, 0, 255), 2)
</code></pre>
<p>Now values are</p>
<pre><code>x = 93
y = 62
w = 6
h = 3
</code></pre>
<p>Now I want to crop that part of the rectangle. Does below line of code make sense:</p>
<pre><code>c... | <p>you should try</p>
<pre><code>cropImg=rightImg[y:y+h,x:x+w].
</code></pre> | python|numpy|opencv|image-processing|crop | 1 |
20,823 | 19,293,316 | Pandas importing CSV and Excel file error | <p>I am trying to use Python Pandas to import a CSV file. The example data in this file is as follows where the first row is the column names separated by commas.</p>
<pre><code>End Customer Organization ID,End Customer Organization Name,End Customer Top Parent Organization ID,End Customer Top Parent Organization Name... | <p>I guess your main problem has to do with encoding. I have suffered the pain of dealing with weird encodings in csv files. What helped me in those cases was to try to detect the real encoding of the file and load it correctly with pandas.</p>
<p>give this next code a try:</p>
<pre><code>from chardet.universaldetector... | python|pandas|import-from-excel|import-from-csv | 3 |
20,824 | 22,162,391 | Setting a pandas index or transposing | <p>I imported a table with 30 columns of data and pandas automatically generated an index for the rows from 0-232. I went to make a new dataframe with only 5 of the columns, using the below code:</p>
<pre><code>df = pd.DataFrame(data=[data['Age'], data['FG'], data['FGA'], data['3P'], data['3PA']])
</code></pre>
<p>W... | <p>The correct approach is actually much simpler. You just need to pull out the columns simultaneously with a list of column names:</p>
<p><code>df = data[['Age', 'FG', 'FGA', '3P', '3PA']]</code></p> | python|pandas|dataframe | 4 |
20,825 | 18,104,654 | From numpy matrix to C array. Segmentation fault (memory corruption) on 64bit architecture | <p>I'm trying to build up a python C extension in order to pass a numpy matrix to a C array. I was following the suggestions reported here: </p>
<p><a href="http://wiki.scipy.org/Cookbook/C_Extensions/NumPy_arrays" rel="nofollow">http://wiki.scipy.org/Cookbook/C_Extensions/NumPy_arrays</a></p>
<p>but when Python trie... | <p>Here you want to allocate memory for pointers to <code>float</code>:</p>
<pre><code>float **v;
v=(float **)malloc((size_t) (n*sizeof(float)));
</code></pre>
<p>but you do allocated memory for <code>float</code>s themselfes. On a 32bit system pointers need 4 bytes, so this works.</p>
<p>On a 64bit system pointers ... | c|numpy | 2 |
20,826 | 55,400,530 | Not sure if current data structure is appropriate | <p>I have the following pandas DataFrame:</p>
<pre><code>PN | LastS | CurrentS | Price
111111 | 100001 | 100002 | 28
111111 | 100001 | 100001 | 32
111111 | 100001 | 100004 | 48
111111 | 100001 | 100003 | 19
222222 | 100004 | 100001 | 200
222222 | 100004 | 100003 | 236
222222 | 100002 | 100005 | 397
222222 | 100003 | ... | <p>You really have one condition; if the values are all the same then you still want to take the last <code>LastS</code> value.</p>
<p>We get that last value, then merge to select the correct <code>CurrentS</code> row, and bring the price for each PN back with a map:</p>
<pre><code>df1 = df.groupby('PN').LastS.last()... | python|pandas | 1 |
20,827 | 56,490,018 | How to add a random value to many rows in a Pandas Dataframe iteratively? | <p>Suppose I have a Pandas Dataframe named <code>df</code>, which has the following structure:-</p>
<pre><code> Column 1 Column 2 ......... Column 104
Row 1 0.01 0.55 3
Row 2 0.03 0.14 1
...
Row 100 0.75 0.56 0
</c... | <p>One idea is create 2d array with same size like new appended <code>DataFrame</code> and add to joined lists with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p>
<pre><code>N = 10
arr = np.random.uniform(0,0.05, size=(N, le... | python|pandas|dataframe|random | 1 |
20,828 | 56,551,333 | Setting the value and style (color) of a cell in pandas Dataframe at the same time in a loop | <p>I've written a python program to look for and fix syntax errors in an excel spreadsheet. This part works. </p>
<p>If a cell has a correctable syntax error, the value in the cell should be fixed and the cell highlighted in yellow. </p>
<p>If the syntax error is not correctable (there is not enough information ava... | <p>@user545424 Thanks for suggesting I post a short example. In doing so I solved my own issue. </p>
<p>My original issue was that I had to separate dataframes, one for the data, and a separate one for the style. In coming up with a short example I found a way to do everything with one dataframe (I'm very new to bot... | python-3.x|pandas|numpy | 1 |
20,829 | 26,098,710 | Rename unnamed column pandas dataframe | <p>My csv file has no column name for the first column, and I want to rename it. Usually, I would do <code>data.rename(columns={'oldname':'newname'}, inplace=True)</code>, but there is no name in the csv file, just ''. </p> | <p>You can view the current dataframe using
<code>data.head()</code></p>
<p>if that returns <code>'Unnamed: 0'</code> as the column title, you can rename it in the following way:</p>
<pre><code>data.rename( columns={'Unnamed: 0':'new column name'}, inplace=True )
</code></pre> | python|pandas|csv | 55 |
20,830 | 67,163,457 | Pandas - Get the value from the previous datetime minute for specific rows | <h1>Get the value from the previous datetime minute per user</h1>
<h3>Original Dataframe</h3>
<p>I have a Dataframe structured like this:</p>
<p><a href="https://i.stack.imgur.com/j7lBX.jpg" rel="nofollow noreferrer">Original Dataframe</a></p>
<pre><code> User Datetime Hits
0 A 2021-03-10 15:25:26 10
1 A... | <p>Let's do this in a few small steps.</p>
<p>First we create a copy of your dataframe, called <code>df1</code> - we then <code>floor</code> the <code>Datetime</code> column to remove any seconds from the column so we can measure the changes in minutes.</p>
<p>We then apply a series of conditional checks to apply your ... | python|pandas|datetime|pandas-groupby | 0 |
20,831 | 67,103,904 | Which is the correct way to use `to_csv` after reading `json` from restapi ? How to get data in tabular format? | <p>I am trying to read data from : <code>http://dummy.restapiexample.com/api/v1/employees</code> and trying to put it out in tabular format.</p>
<p>I am getting the output. But columns are not created from json file.
How can do this in right way?</p>
<p><strong>Code</strong>:</p>
<pre><code>import pandas as pd
impo... | <p>Here are the different steps (note: the data is in [data] array of the JSON response):</p>
<pre><code>import json
import pandas as pd
import requests
res = requests.get('http://dummy.restapiexample.com/api/v1/employees')
data_str = res.content
data_dict = json.loads(data_str)
data_df = pd.DataFrame(data_dict['data... | python|json|pandas | 0 |
20,832 | 67,019,091 | Replacing NaN values in a column from a second column | <p>I would like to replace <code>NaN</code> values in <code>Target</code> with the corresponding <code>Node</code> value.
My data is:</p>
<pre><code> Node Target Color
node1 node7 Red
node1 node9 Red
node3 node5 Green
node1 node3 Red
node3 node1 Red
node5 NaN Yellow
</code></pre>
<p>I would... | <p>Yes, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><strong><code>df.fillna(value, ...)</code></strong></a> will allow the <strong><code>value</code> (replacement) arg to be a Series (column)</strong>, not just a constant:</p>
<pre><code>df... | python|pandas | 1 |
20,833 | 67,170,833 | Implementing a minmax maxpooling layer | <p>I need to implement a minmax pooling layer. I have 4-dimensional tensor,(batch_size,height,width,activation_maps).</p>
<p>I want to implement a method where the number with the largest <strong>absolute</strong> value gets propagated to the next layer instead of max element being chosen.</p>
<p>I have attached an ex... | <p>You could just pool the absolute values of the input tensor directly using <code>tf.abs</code>:</p>
<pre class="lang-py prettyprint-override"><code>X = tf.random.normal([4,4,4,3], dtype=tf.dtypes.float32, seed=None, name=None)
# Pool the absolute of the input tensor
result = MaxPool2d()(tf.abs(X))
</code></pre> | tensorflow|keras|deep-learning|tensorflow2.0|keras-layer | 0 |
20,834 | 66,874,373 | Pandas Resample Monthly data to Weekly within Groups and Split Values | <p>I have a dataframe, below:</p>
<pre><code>ID Date Volume Sales
1 2020-02 10 4
1 2020-03 8 6
2 2020-02 6 8
2 2020-03 4 10
</code></pre>
<p>Is there an easy way to convert this to weekly data using resampling? And dividing the volume and sales column by the number of weeks in the mon... | <p>After review, a much simpler solution can be used. Please refer to subsection labeled <em><strong>New Solution</strong></em> in Part 1 below.</p>
<p>This task requires multiple steps. Let's break it down as follows:</p>
<h2>Part 1: Transform Date & Resample</h2>
<p><em><strong>New Solution</strong></em></p>
<... | python|pandas|dataframe|numpy | 3 |
20,835 | 47,111,361 | How to get the dataframe row, and when the column reaches a value | <p>I have a pandas dataframe,</p>
<pre><code>df = pd.DataFrame([['@1','A',2],['@2','A',1],['@3','A',4],['@4','B',1],['@5','B',1],['@6','B',3],['@7',
'B',3],['@8','C',4]],columns=['id','channel','people'])
id channel people
0 @1 A 2
1 @2 A 1
2 @3 A 4
3 @4 B 1
4 ... | <h3>Solution</h3>
<pre><code>df = pd.DataFrame([['@1','A',2],['@2','A',1],['@3','A',4],['@4','B',1],
['@5','B',1],['@6','B',3],['@7','B',3],['@8','C',4]],
columns=['id','channel','people'])
>>> df
Out[]:
id channel people
0 @1 A 2
1 @2 A 1
2 ... | python|pandas | 1 |
20,836 | 47,148,683 | Pandas explode list of dictionaries into rows | <p>Have this:</p>
<pre><code> items, name
0 { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], this }
1 { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], that }
</code></pre>
<p>But would like to have the list of dictionary objects exploded into (flattened?) into actual rows like this:</p>
<pre><code> ... | <p>Another way to use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>concat</code></a> perhaps more cleanly:</p>
<pre><code>In [11]: pd.concat(df.group.apply(pd.DataFrame).tolist(), keys=df["name"])
Out[11]:
a b
name
this 0 2 1
1 4 3
that 0 ... | python|pandas|dataframe | 6 |
20,837 | 47,162,644 | Stemming Pandas Dataframe 'float' object has no attribute 'split' | <pre><code>import pandas as pd
from nltk.stem import PorterStemmer, WordNetLemmatizer
porter_stemmer = PorterStemmer()
df = pd.read_csv("last1.csv",sep=',',header=0,encoding='utf-8')
df['rev'] = df['reviewContent'].apply(lambda x : filter(None,x.split(" ")))
</code></pre>
<p><a href="https://i.stack.imgur.com/0HLbd.... | <p>When tokenising your data, you don't need the <code>apply</code> call. <code>str.split</code> should do just fine. Also, you can split on multiple whitespace, so you don't have to look for empty strings.</p>
<pre><code>df['rev'] = df['reviewContent'].astype(str).str.split()
</code></pre>
<p>You can now run your st... | python|pandas|dataframe|stem | 4 |
20,838 | 11,278,836 | Fitting data to system of ODEs using Python via Scipy & Numpy | <p>I am having some trouble translating my MATLAB code into Python via Scipy & Numpy. I am stuck on how to find optimal parameter values (k0 and k1) for my system of ODEs to fit to my ten observed data points. I currently have an initial guess for k0 and k1. In MATLAB, I can using something called 'fminsearch' whic... | <p>For these kind of fitting tasks you could use the package <a href="https://lmfit.github.io/lmfit-py/" rel="noreferrer"><code>lmfit</code></a>. The outcome of the fit would look like this; as you can see, the data are reproduced very well:</p>
<p><a href="https://i.stack.imgur.com/gtU4w.png" rel="noreferrer"><img sr... | python|numpy|scipy|differential-equations|data-fitting | 6 |
20,839 | 68,161,194 | Unique function in python | <pre><code>for i in df["col"].unique():
...
</code></pre>
<p>Here <code>unique</code> function is called after each iteration of loop or is it just called once and stores the result in memory??</p>
<p>Asking this just to check if <code>unique</code> function is executed after every iteration then there is ... | <p>The construction you are using first calculates the .unique() function and uses the result of that function, if iterable, to loop over.</p>
<p>If you'd want the loop to evaluate a function every iteration, you could use structures like:</p>
<pre><code>list = [x.function() for x in items]
</code></pre>
<p>check this ... | python-3.x|pandas|dataframe|memory|unique | 1 |
20,840 | 68,180,384 | Reading multiple CSV files and merge Python Pandas | <p>I am reading specific csv files names based on their name with this code:</p>
<pre><code>csv_names = [s for s in files_csv if "drive" in s]
</code></pre>
<p>output:</p>
<pre><code>['drive_1.csv',
'drive_2.csv',
'drive_3.csv',
'drive_4.csv']
</code></pre>
<p>How can i merge those files easy?</p>
<p>I am ... | <p>You can use <code>pd.concat</code> and a list comprehension:</p>
<pre><code>df = pd.concat([pd.read_csv(csv_name, sep=';', header=None) for csv_name in csv_names])
</code></pre> | python|pandas|merge | 1 |
20,841 | 68,239,122 | Python: Error when converting NaN values to 0 | <p>I'm converting NaN data to 0 in Python. It seems to be translated but then when I look at the dataframe the values still show as NaN how can I fix this.</p>
<p>After processing the data, it still returns NaN</p>
<pre><code>df.fillna(0)
</code></pre>
<p><a href="https://i.stack.imgur.com/5IL6j.png" rel="nofollow no... | <p>The answer really should be obvious. <code>fillna</code> does not change the dataframe in place. It returns a new dataframe. Do:</p>
<pre><code>df = df.fillna(0)
</code></pre> | python|arrays|pandas | 0 |
20,842 | 59,436,582 | NameError: ("name 'true' is not defined", 'occurred at index 0') | <pre><code>import pandas as pd
df = pd.read_csv(r'C:\Users\dd\Desktop\test.csv')
df
</code></pre>
<p>Out</p>
<pre><code>userid url
0 123 x.com
1 345 y.com
</code></pre>
<p>Code</p>
<pre><code>def create_dict(row):
return ({"userid" : row.userid ,"data": {"url": row.url},"bool":true})
</code></pre>
<p>I do... | <p>If use <code>true</code> it means variable <code>true</code>, if use <code>True</code> it is boolean value <code>true</code> in python.</p>
<p>So correct way is:</p>
<pre><code>def create_dict(row):
return ({"userid" : row.userid ,"data": {"url": row.url},"bool":True})
</code></pre> | pandas | 0 |
20,843 | 59,416,557 | Pandas read_csv randomly skip rows with specific entries | <p>I have a csv file where I want to skip a random percentage of rows but only for rows where one of the columns has a specific entry. For example I might have a csv with contents below and I want to skip a certain percentage of all the apple entries:</p>
<pre><code> | a | b | c | d | e |
|----|----|----|---... | <p>You can do it as follows, But I would prefer doing it in later stage.</p>
<pre><code>df = pd.read_csv('fruit.csv').query("e != 'apple'")
</code></pre> | python-3.x|pandas|dataframe | 0 |
20,844 | 59,115,795 | I have a .csv file I'd like to use instead of manually entering the details to add a 'click box' to a marker point | <p>If I manually enter data, when I click the Google Map marker, the data appears in the box on Google Maps as I'd like.</p>
<p>This section is all fine.</p>
<pre><code>import gmaps
gmaps.configure(api_key='AI...')
file_name = [
{'name': 'House A', 'location': (42.162913, 139.487541), 'price': 250},
{'name':... | <p>You can concatenate lat/long after creating the dataframe. Here's an example:</p>
<pre><code>In [175]: import pandas as pd
In [176]: df = pd.read_csv(r"test.csv")
#null values for location series
In [202]: df
Out[202]:
name location lat long price
0 house A NaN 42.1629 139.4875 250
1... | python|pandas|csv|google-maps | 0 |
20,845 | 59,201,654 | Variable bins for each row in pandas dataframe | <p>Given a coordinate dataframe such as <code>df1 = pd.DataFrame({'x': np.tile(np.arange(20),5), 'y': np.repeat(np.arange(5),20)})</code></p>
<p>I would like to bin each x value however, the number of bins varies for each row. More specifically, the number of bins is dependent on the y value.</p>
<p>e.g. point x=6 an... | <p>IIUC:</p>
<pre><code>df1['xbinned'] = (df1.groupby('y')
.apply(lambda d: pd.cut(d['x'], bins=d['y'][0]+1))
.reset_index(level=0, drop=True)
)
</code></pre>
<p>Output (partial)</p>
<pre><code> x y xbinned
18 18 0 (-0.019, 19.0]
19 19 0 (... | python|pandas|dataframe|cut|bins | 1 |
20,846 | 59,178,969 | Adding letters to numbers in Pandas column | <p>I need to add letters to a series of numbers in Pandas the following way: </p>
<ol>
<li><p>In one column I have <code>[1,1,1,2,2,3,3,3,3]</code></p></li>
<li><p>I need to get another column where I'll have <code>[1a,1b,1c,2a,2b,3a,3b,3c,3d]</code></p></li>
</ol>
<p>In Excel it's done by applying the following form... | <p>If you are certain you don't have more repetition than the letters in alphabet, you can do this:</p>
<pre><code>s = pd.Series([1,1,1,2,2,3,3,3,3] )
letters = np.array(list('abcdefgh'))
s.astype(str) + letters[s.groupby(s).cumcount()]
</code></pre>
<p>Output:</p>
<pre><code>0 1a
1 1b
2 1c
3 2a
4 2... | python|excel|pandas | 4 |
20,847 | 59,230,837 | Pandas index error running apply function | <p>I have created the following function: </p>
<pre><code>def stripnum(str):
array = re.findall(r'\d+', str)
return array[0]
</code></pre>
<p>Testing this function on a single row works perfectly fine. </p>
<pre><code>stripnum(dataset.loc[4,'Description'])
>> 11
</code></pre>
<p>Now I would like to... | <p><em>Unless you are confident that every row value of the column you are passing to function is non-empty and has digit value</em>, it may be problem with your function. What happens if there is no digit in string and what is value of array?
Suppose you try to use <code>findall</code> as above in string value <code>... | python|pandas|indexing|apply | 0 |
20,848 | 59,347,796 | Minimizing overhead due to the large number of Numpy dot calls | <p>My problem is the following, I have an iterative algorithm such that at each iteration it needs to perform several matrix-matrix multiplications dot(<strong>A_i</strong>, <strong>B_i</strong>), for i = 1 ... k. Since these multiplications are being performed with Numpy's dot, I know they are calling BLAS-3 implement... | <h2>It depends on the size of the matrices</h2>
<p><strong>Edit</strong></p>
<p>For larger nxn matrices (aprox. size 20) a BLAS call from compiled code is faster, for smaller matrices custom Numba or Cython Kernels are usually faster.</p>
<p>The following method generates custom dot- functions for given input shapes... | performance|numpy|linear-algebra|matrix-multiplication | 6 |
20,849 | 59,208,090 | Extract Date and fie name using Regex | <p>I have a file with following name format and I want to split date time and file name and parse it to CSV file into different columns<br>
Example file name<br>
<code>2019-12-05_18:02:28.801656_104_1_1575549141338.jpg</code></p>
<p>and I only need <code>2019-12-05, 18:02:28,104, 1575549141338</code></p>
<p>How do I... | <p>You could do this without using regex.</p>
<pre><code>filename = '2019-12-05_18:02:28.801656_104_1_1575549141338.jpg'
date1 = filename.split('_')[0]
time1 = filename.split('_')[1].split('.')[0]
number2 = filename.split('_')[2]
number1 = filename.split('_')[-1].split('.')[0]
</code></pre>
<p>or as a one-liner,</p>... | python|regex|pandas | 0 |
20,850 | 59,272,076 | Read table in pandas with lowercase column using sqlalchemy | <p>I would like to read a table in my database as pandas dataframe. I am working with <code>sqlalchemy</code> and it seems to me that it only executes queries in uppercase.</p>
<p>The table XYZ in my schema has a column name "pred_pred" in lowercase. When I do the following:</p>
<pre><code>import pandas as pd
import ... | <p>As also described in comment, you should just add double quotes to wrap your <code>columns</code> as oracle converts it to upper case if it is not wrapped with double quotes.</p>
<p>I think you need something like following:</p>
<pre><code>input = pd.read_sql_query('SELECT "pred_pred" FROM XYZ', connection)
</code... | python|sql|pandas|oracle|sqlalchemy | 2 |
20,851 | 14,262,433 | "Large data" workflows using pandas | <p>I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.</p>
<p>One day I hope to replace my use of SAS with python and pan... | <p>I routinely use tens of gigabytes of data in just this fashion
e.g. I have tables on disk that I read via queries, create data and append back.</p>
<p>It's worth reading <a href="http://pandas-docs.github.io/pandas-docs-travis/io.html#hdf5-pytables" rel="noreferrer">the docs</a> and <a href="https://groups.google.c... | python|mongodb|pandas|hdf5|large-data | 708 |
20,852 | 45,099,554 | How to simplify DataLoader for Autoencoder in Pytorch | <p>Is there any easier way to set up the dataloader, because input and target data is the same in case of an autoencoder and to load the data during training? The <a href="http://pytorch.org/docs/master/data.html" rel="nofollow noreferrer">DataLoader</a> always requires two inputs.</p>
<p>Currently I define my dataloa... | <p>Why not subclassing TensorDataset to make it compatible with unlabeled data ?</p>
<pre class="lang-python prettyprint-override"><code>class UnlabeledTensorDataset(TensorDataset):
"""Dataset wrapping unlabeled data tensors.
Each sample will be retrieved by indexing tensors along the first
dimension.
... | autoencoder|pytorch | 4 |
20,853 | 45,120,767 | Panda's merge returning empty, can't see why | <p>I have the following dataframe:</p>
<p><a href="https://i.stack.imgur.com/XLpko.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XLpko.png" alt="enter image description here"></a></p>
<p>I then summarize the value 'Hp' by the column 'Dia', obtaining the following dataset using the following synta... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a>:</p>
<pre><code>df['sum'] = df.groupby(df.Dia.dt.date)['Hp'].transform('sum')
</code></pre>
<p>You get <code>empty</code> df, beca... | python|pandas|join|merge | 1 |
20,854 | 45,114,656 | error while executing 'import tensorflow as tf' | <p>I am just getting started with python/tensorflow.
Using <a href="https://www.tensorflow.org/install/install_windows" rel="nofollow noreferrer">this</a> link to get started.
I have I have successfully installed tensor-flow, at least from the log it seems like that. My issue is when I try to import tenser-flow I am ge... | <p>I am putting this answer just for tensor-flow beginners.
If you occur with above issue, what fixed my issue is</p>
<ol>
<li>Put the installation of python 3.5(which is supported), install it in C:\ or any other locations other than the default.</li>
<li>download msvcp140.dll and place it in System32 and SysWOW64. ... | windows|python-3.x|tensorflow | 2 |
20,855 | 57,032,157 | How to encode multiple categorical columns for test data efficiently? | <p>I have multiple category columns (nearly 50). I using custom made frequency encoding and using it on training data. At last i am saving it as nested dictionary. For the test data I am using map function to encode and unseen labels are replaced with 0. But I need more efficient way?</p>
<p>I have already tried panda... | <p>Firstly, when you want to encode categorical variables, which is not ordinal (meaning: there is no inherent ordering between the values of the variable/column. ex- <code>cat</code>, <code>dog</code>), you must use one hot encoding. </p>
<pre><code>import pandas as pd
from sklearn.preprocessing import OneHotEncoder ... | python-3.x|pandas|encoding|scikit-learn | 1 |
20,856 | 57,064,501 | Pandas - Calculate rolling cumulative product with variable window size | <p>I have some financial time series data that I would like to calculate the rolling cumulative product with a variable window size.</p>
<p>What I am trying to accomplish is using the following formula but instead of having window fixed at 12, I would like to use the value stored in the last column of the dataframe la... | <pre><code>
def get_window(row, df):
return (1 + df).rolling(window=int(row['labels_y'])).apply(np.prod, raw=True).loc[row.name]-1
result = df1.apply(get_window, axis=1, df=df1)
</code></pre>
<p>Does this do the trick? Highly inefficient, but I don't see another way except for tedious for-loops.</p> | python|pandas|dataframe | 2 |
20,857 | 57,180,346 | How to merge values from each array to get one new array | <p>I'm trying to combine two merge values from two arrays to get one whole new array. However, I have no idea how to do.</p>
<p>I want to get a random float number for two variables like 5 times because I want to store them for future use. Hence, I used math.random but it doesn't work as expected because it will repla... | <p>You can specify a <code>size</code> of the output array when using <code>np.random.uniform</code>, no need for looping:</p>
<pre><code>randomReleaseAngle = np.random.uniform(20.0, 77.0, size=(5, 2))
randomVelocity = np.random.uniform(40.0, 60.0, size=(5, 2))
array([[41.34878677, 74.19071547],
[61.72365468, ... | python|numpy | 1 |
20,858 | 57,044,081 | building keras Model ValueError | <p>Here is a snippet code to design a Keras deep <code>Model()</code> based some simple blocks:</p>
<pre><code>def conv_bn_activation(x, filters, kernel_size, strides, data_format, is_training, activation=relu,
name=None):
"""
Parameters
----------
x
filters
kernel_size... | <p>The problem is in the addition <code>conv + short_cut</code></p>
<pre><code>def conv_bn_activation(x, filters, kernel_size, strides, data_format, is_training, activation=relu,
name=None):
"""
Parameters
----------
x
filters
kernel_size
strides
data_format
... | python|tensorflow|keras|tf.keras | 1 |
20,859 | 57,153,071 | How to read a formatted text file with some header, column names, and data? | <p>I am essentially using pandas to read in a formatted text file with a header, column names, and data but I am unable to get the final product. I want the header info in a variable, the column names and data in a dataframe. What am I doing wrong here?</p>
<p>I have tried using <code>pandas.read_csv</code>...see belo... | <p>From your file it shows that first row is the header and thereafter comes the dataframe.</p>
<p>in order to SKIP the first line (header) you should read it with the skiprows (credit to @Erfan from the comments):</p>
<pre><code>data=pd.read_csv(a, sep= '\s+', names=cols, skiprows=1, header=None)
</code></pre>
<p>F... | pandas | 1 |
20,860 | 57,227,273 | get minimum value across array of indices | <p>I have an n-by-3 index array (think of triangles indexing points) and a list of float values associated with the triangles. I now want to get for each index ("point") the <em>minimum</em> value, i.e., check all rows which contain the index, say, 0, and get the minimum value from <code>vals</code> across the respecti... | <p><strong>Approach #1</strong></p>
<p>One approach based on array-assignment to setup a <code>2D</code> array filled up <code>NaNs</code>, using those <code>a</code> values as column indices (so assumes those to be integers), then mapping <code>vals</code> into it and looking for nan-skipped min values for the final ... | python|numpy | 2 |
20,861 | 46,138,110 | How to create bucketed tensors from TensorFlow Dataset object? | <p>I created an <code>TextLineDataset</code> object using following code:</p>
<pre><code>dataset = TextLineDataset([text_path])
</code></pre>
<p>Then I want to create bucketed tensors from this Dataset. I know there is an API called <code>bucket_by_sequence_length</code>. I tried to feed this API with iterator by cal... | <p>As result of some investigation, I found that <code>bucket_by_sequence_length</code> is designed to process tensors, which could be enqueued into <code>Queue</code>s. But <code>iterator</code> of <code>Dataset</code> is different.</p>
<p>Then I found that <code>Dataset</code> support <code>group_by_window</code> op... | tensorflow | 1 |
20,862 | 46,109,166 | Converting 'CategorizedPlaintextCorpusReader' into dataframe | <p>I want to convert <code>movie_reviews</code> dataset from <code>nltk.corpus</code> into dataframe.
The purpose is to use this data for sentiment analysis.
while converting the data using pandas, I'm getting an error:</p>
<pre><code> from nltk.corpus import movie_reviews
import pandas as pd
mr=movie_rev... | <p>An NLTK's <code>CategorizedPlaintextCorpusReader</code> object isn't a <code>dtype</code> for <code>pandas</code>.</p>
<p>That being said, you can convert the movie reviews into list of tuples and then populate a dataframe as such:</p>
<pre><code>import pandas as pd
from nltk.corpus import movie_reviews as mr
re... | python|python-3.x|pandas|nltk | 4 |
20,863 | 28,708,233 | Indexing/selecting by year in Pandas when MultiIndex is in use | <p>Longtime lurker trying to more actively engage in the community here.</p>
<p>Here goes: </p>
<p>When I set the index of the dataframe as just a single-level DatetimeIndex, everything works as expected. When I Index by the below, I get the following returns: </p>
<p><strong>Input:</strong> </p>
<pre><code>sample_... | <p>I don't think this form of "fuzzy indexing" is possible (yet?) when using a MultIndex. However, as a workaround, you could extract the single-level index from the multiindex, and use its <code>get_loc</code> method to find the integer indices corresponding to the desired dates in 2012:</p>
<p>For example,</p>
<pre... | python|datetime|indexing|pandas|dataframe | 1 |
20,864 | 50,840,749 | Segmentation fault (core dumped) when training more than one Keras NN models | <p>I am optimizing the hyper-parameters of my neural-network, for which I am recursively training the network using different hyper-parameters. It works as expected until after some iterations, when creating a new network for training, it dies with the error "<code>Segmentation fault (core dumped)</code>".</p>
<p>Furt... | <p>If you run K.clearsession() on a GPU with Keras 2, you may get a segmentation fault.
If you have this in your code, try removing it!</p> | python-3.x|tensorflow|segmentation-fault|keras|nvidia-jetson | 2 |
20,865 | 33,461,664 | seaborn time series from pandas dataframe | <p>I'm struggling with what seems to be a very easy problem: how to get seaborn to plot a time series line chart from a pandas dataframe. What am I doing wrong here?</p>
<pre><code>import seaborn as sns
import pandas as pd
df=pd.DataFrame({"Date":["2015-03-03","2015-03-02","2015-03-01"],"Close":[1,3,2]})
df["Date"]=pd... | <p>The <code>tsplot</code> of seaborn is not meant to plot a simple timeseries line plot, but to plot uncertainties, see:<a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.tsplot.html">https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.tsplot.html</a>. </p>
<p>For a line plot, you ... | python|pandas|seaborn | 11 |
20,866 | 5,760,754 | How can I debug (potentially C-library related) memory issues using 64-bit Python on Windows? | <p>I have a python program that processes image frames with Python 2.7, PIL, OpenCV, and numpy/scipy. To the best of my knowledge, it does not maintain any lists of previous frame. Nevertheless, memory consumption increases steadily as the program processes more and more frames.</p>
<p>There are <a href="https://sta... | <p>I had a similar sort of problem tracking down a severe memory leak in a numpy/scipy heavy code where none of the usual Python memory management tools and diagnostics detected the leak or hinted at its source. </p>
<p>In my case, the source of the leak was scipy interface code to the UMFPACK solver package, which w... | python|memory-management|profiling|numpy|scipy | 1 |
20,867 | 66,663,932 | Select the first row from each group after groupby (Multiindex) | <p>I am doing data analysis, and conducted the groupby to get the 'count' and 'sum' by 'year' and 'product' (already sort by count in each year)</p>
<p>The df is like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th></th>
<th>count</th>
<th>sum</th>
</tr>
</thead>
<tbody>
<tr>
<td... | <p>To select the first row from the each year, you can do:</p>
<pre><code>print(
df.reset_index(level="product")
.groupby(level="year")
.first()
.set_index(["product"], append=True)
)
</code></pre>
<p>Prints:</p>
<pre><code> count sum
year product ... | pandas|group-by|multi-index | 1 |
20,868 | 66,411,712 | getting an RunTime Error (mat1 and mat2....) when trying to use a trained FNN model in pytorch | <p>In my model there are 5 float inputs and one output (LWS= 1\0).
while training the model there was no problem, but when I tried to load the model and check it on new data I got the "mat1 and mat2..." error.
i used this website to build my model(<a href="https://curiousily.com/posts/build-your-first-neural-... | <p>This is the wrong way of saving the model...and often throws error when you use it from different folder / different path</p>
<p>Recommended approach for saving a model
There are two main approaches for serializing and restoring a model.</p>
<p>The first (recommended) saves and loads only the model parameters:</p>
<... | python|machine-learning|pytorch | 0 |
20,869 | 66,609,739 | Numpy.log() equivalent for C#? | <p>Is there anything equivalent to the python function numpy.log() in c#?</p>
<p>The function takes in array of doubles. I've been trying to find something for quite a while now..</p>
<p>Trying to convert the code below to C# (from python)</p>
<pre><code>def func(money, intervals, dig=5):
log_section = [2, 10] # must ... | <p>I guess maybe this?</p>
<pre><code>using System.Linq;
...
double[] list = get_list_of_doubles();
double[] result = list.Select(d => Math.Log(d)).ToArray();
</code></pre>
<p>there is no real equivelent to numpy.linspace i dont think (but here is a rough equivelent borrowed from <a href="https://stackoverflow.com/a... | python|c#|numpy|math | 1 |
20,870 | 66,444,101 | Tflite inference is very slower than keras model inference | <p>I converted the keras model to tflite. I am converting model like this</p>
<pre><code>from keras import backend as K
from keras.models import load_model
from keras.engine.base_layer import Layer
import tensorflow as tf
# This line must be executed before loading Keras model.
K.set_learning_phase(0)
# custom layer
c... | <p>I know this is not a direct answer to your question but if you're looking for a faster way to infer, I'd recommend trying <a href="https://docs.openvino.ai/latest/openvino_docs_install_guides_overview.html#" rel="nofollow noreferrer">OpenVINO</a>. OpenVINO is optimized for Intel hardware but it should work with any ... | tensorflow|machine-learning|keras|deep-learning|tensorflow-lite | 0 |
20,871 | 57,722,072 | Colab Kernel Restarts Whenever Loading a Model From Tensorflow-hub | <p>I wanted to try out the embeddings provided in tensorflow-hub, the 'universal-sentence-encoder' to be specific. I tried the examples provided (<a href="https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/semantic_similarity_with_tf_hub_universal_encoder.ipynb" rel="nofollow noreferrer"... | <p>I had similar issues with the multilingual sentence encoder. I resolved it by specifying tensorflow version to 1.14.0 and tf-sentencepiece to 0.1.83, so before running your code in colab try:</p>
<pre><code>!pip3 install tensorflow==1.14.0
!pip3 install tensorflow-hub
!pip3 install sentencepiece
!pip3 install tf-se... | tensorflow|tensorflow-hub | 0 |
20,872 | 57,723,668 | Skip lines with strange characters when I read a file | <p>I am trying to read some data files '.txt' and some of them contain strange random characters and even extra columns in random rows, like in the following example, where the second row is an example of a right row:</p>
<blockquote>
<p>CTD 10/07/30 05:17:14.41 CTD 24.7813, 0.15752, 1.168, 0.7954, ... | <p>You could use the csv module to read the file one line at a time and apply your desired filter.</p>
<pre><code>import csv
def isascii(s):
len(s) == len(s.encode())
with open('file.csv') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
if len(row)==expected_length and all((is... | python-3.x|numpy|io | 0 |
20,873 | 57,511,790 | Pandas Groupby with Multiple Criteria | <p>Suppose I have a pandas dataframe containing addresses, first names, and last names. I want to group records (rows) based on the first 3 characters in either of these three fields. </p>
<p>For examples, if we have </p>
<pre><code>| index | address | first_name | last_name |
| 1 | 1800 St. | John |... | <p>You can do:</p>
<pre><code>df['g1'] = df.groupby(df['address'].str[:3]).ngroup()
df['g2'] = df.groupby(df['first_name'].str[:3]).ngroup()
</code></pre>
<p>Output:</p>
<pre><code> index address first_name last_name g1 g2
0 1 1800 St. John Adams 0 1
1 2 1800 Street J. ... | python|pandas | 2 |
20,874 | 57,558,476 | Training a Keras model yields multiple optimizer errors | <p>So I need to retrain Tiny YOLO using my own dataset. The model I am using can be found here: <a href="https://github.com/qqwweee/keras-yolo3" rel="noreferrer">keras-yolo3
</a>.</p>
<p>I started training and I get multiple optimizer errors, added the code of the errors to stop confusion.
And I noticed the training i... | <p>I have found solution here: <a href="https://github.com/tensorflow/tensorrt/issues/118" rel="noreferrer">https://github.com/tensorflow/tensorrt/issues/118</a></p>
<p>You have to change lines(140/141) in yolo3/model.py:</p>
<pre><code>box_xy = (K.sigmoid(feats[..., :2]) + grid) / K.cast(grid_shape[::-1], K.dtype(fe... | python|tensorflow|neural-network|yolo | 21 |
20,875 | 43,678,978 | Accessing column value within loc gives error "'Series' objects are mutable, thus they cannot be hashed" | <p>I have a dataframe with two columns of interest, <code>station</code> and <code>hall</code>, where a hall has multiple stations. I want to filter the dataframe so that I only keep certain stations for each hall.</p>
<p>So for every row in the dataframe, keep it only if <code>hall == A and station in [A1, A2, A3] o... | <pre><code>df = pd.DataFrame({'Date': {0: '04/10', 1: '04/10', 2: '04/10', 3: '04/10'},
'Food': {0: 'pizza', 1: 'burger', 2: ' hot dog', 3: 'pasta'},
'Hall': {0: 'de neve', 1: 'de neve', 2: 'covel', 3: 'covel'},
'Meal': {0: 'lunch', 1: 'lunch', 2: 'lunch', 3: 'lunch'},
'Station': {0: 'the grill',
1: 'the kitchen'... | python|pandas | 0 |
20,876 | 73,095,613 | How do I group by the outcome and severity header in xlsxwriter | <p>can anybody help me categorize the header of outcome and severity to show the FAIL and HIGH values highlighted in red at the top while the rest will be in descending order using xlsxwriter. I really can't understand how the structure works.</p>
<p><a href="https://i.stack.imgur.com/VRt0e.png" rel="nofollow noreferr... | <p>Given:</p>
<pre><code>df = pd.DataFrame({'Outcome':['Pass', 'Fail', 'Pass', 'Fail', 'Fail'], 'Severity':['High', 'Medium', 'Low', 'Medium', 'High']})
Outcome Severity
0 Pass High
1 Fail Medium
2 Pass Low
3 Fail Medium
4 Fail High
</code></pre>
<p>Doing:</p>
<pre><code># Make your c... | pandas|xlsxwriter | 0 |
20,877 | 70,490,037 | how do I filter rows that come before the row that contains certain value for each group in dataframe | <p>How do I get only the rows that come after the 'click' in the column 'action_type' for each client_id
the toy data.</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({
'user_client_id': [1,1, 1, 1, 1,1, 1,1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
'timestamp'... | <p>You can use a mask with <code>groupby</code> and <code>cummax</code>. This will set all values per group to True after the first "click'</p>
<pre class="lang-py prettyprint-override"><code>m = (df['action_type'].eq('click')
.groupby(df['user_client_id'])
.cummax()
)
df[m]
</code></pre>
<p>Ou... | python|pandas|filter | 3 |
20,878 | 70,733,251 | Strange error when an array is assigned to a row of a pandas data frame | <p>I have below code:</p>
<pre><code>import pandas as pd
import numpy as np
data = [['tom', 10], ['harry', 10]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])
Y = [10, 100]
df.loc[0:(df.shape[0] - 1), ['a'+str(x) for x in [10, 100]]] =Y
</code></pre>
<p>With this I am getting below error:</p>
<p><a href="https://i... | <p>In last line of your code</p>
<pre class="lang-py prettyprint-override"><code>df.loc[0:(df.shape[0] - 1), ['a'+str(x) for x in [10, 100]]] =Y
</code></pre>
<p>you are querying for columns <code>a10, a100</code> by
<code>['a'+str(x) for x in [10, 100]]</code>.</p>
<p>These columns are not available in <code>df</code>... | python|python-3.x|pandas | 0 |
20,879 | 42,653,598 | Grouping dates by 5 minute periods irrespective of day | <p>I have a DataFrame with data similar to the following </p>
<pre><code>import pandas as pd; import numpy as np; import datetime; from datetime import timedelta;
df = pd.DataFrame(index=pd.date_range(start='20160102', end='20170301', freq='5min'))
df['value'] = np.random.randn(df.index.size)
df.index += pd.Series([t... | <p>IIUC then the following should work:</p>
<pre><code>In [62]:
df.groupby(df.index.floor('5min').time).mean()
Out[62]:
value
00:00:00 -0.038002
00:05:00 -0.011646
00:10:00 0.010701
00:15:00 0.034699
00:20:00 0.041164
00:25:00 0.151187
00:30:00 -0.006149
00:35:00 -0.008256
00:40:00 0.021389
00:45:00... | python|pandas|datetime|dataframe | 3 |
20,880 | 27,228,964 | read csv-data with missing values into python using pandas | <p>I have a CSV-file looking like this:</p>
<pre><code>"row ID","label","val"
"Row0","5",6
"Row1","",6
"Row2","",6
"Row3","5",7
"Row4","5",8
"Row5",,9
"Row6","nan",
"Row7","nan",
"Row8","nan",0
"Row9","nan",3
"Row10","nan",
</code></pre>
<p>All quoted entries are strings. Non-quoted entries are numerical. Empty field... | <p>You can try with <code>numpy.genfromtxt</code> and specify the <code>missing_values</code> parameter</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html</a></p> | python|csv|pandas|missing-data | 1 |
20,881 | 25,211,380 | Operations within DataFrameGroupBy | <p>I am trying to understand how to apply function within the 'groupby' or each groups of the groups in a dataframe. </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Stock' : ['apple', 'ford', 'google', 'samsung','walmart', 'kroger'],
'Sector' : ['tech', 'auto', 'tech', 'te... | <p>You provided random data, so there is no way we can get the exact number that you got. But based on what you just described, I think the following will do:</p>
<pre><code>In [121]:
(df.Price/df.Signal).groupby(df.Sector).sum()
Out[121]:
Sector
auto -1.693373
retail -5.137694
tech -0.984826
dtype: float64... | python|numpy|pandas|dataframe | 1 |
20,882 | 30,566,994 | Solving System of Differential Equations using SciPy | <p>I'm trying to solve the following system of differential equations using scipy:</p>
<pre><code>q1''(t) + M/L1 * q2''(t) + R1/L1 * q1'(t) + 1/(C1 * L1) * q1(t) = 0
q2''(t) + M/L2 * q1''(t) + R2/L2 * q2'(t) + 1/(C2 * L2) * q2(t) = 0
</code></pre>
<p>I'm trying to use scipy.integrate.odeint to obtain a numerical sol... | <p>You have two coupled second order equations. When this system is converted to a system of first order equations, there will be four equations, not six.</p>
<p>Do a little algebra by hand to solve for the vector [q1''(t), q2''(t)] in terms of q1(t), q1'(t), q2(t) and q2'(t). (For example, you can use that fact the ... | python|numpy|scipy|differential-equations|numerical-integration | 1 |
20,883 | 30,621,887 | Return a column vector in pandas.apply(), with different length? | <pre><code>import numpy as np
import pandas as pd
np.percentile([0,10], [10,50,90])
# array([ 1., 5., 9.])
df = pd.DataFrame({'a':[0,10], 'b':[0,30]})
print(df)
# a b
# 0 0 0
# 1 10 30
df.apply(np.percentile, axis=0, q=[10,20,30,40,50,75,100])
</code></pre>
<p>Should ideally return a dataframe with... | <p>You can construct a Series from the result:</p>
<pre><code>In [27]:
df.apply(lambda x: pd.Series(np.percentile(x, axis=0, q=[10,20,30,40,50,75,100])))
Out[27]:
a b
0 1.0 3.0
1 2.0 6.0
2 3.0 9.0
3 4.0 12.0
4 5.0 15.0
5 7.5 22.5
6 10.0 30.0
</code></pre>
<p>So that it doesn't moan a... | python|pandas|apply | 2 |
20,884 | 30,321,932 | conditional column output for pandas dataframe | <p>I have a pandas DataFrame looking like this:</p>
<pre><code>nameA statusA nameB statusB
a Q x X
b Q y X
c X z Q
d X o Q
e Q p X
f Q r Q
</code></pre... | <pre><code>> data['con'] = data['statusA'] + data['statusB']
> data.apply(lambda v: v['nameA'] if v['con'] == 'QX' else v['nameB'] if v['con'] == 'XQ' else v['nameA']+ ','+ v['nameB'], axis=1)
0 a
1 b
2 z
3 o
4 e
5 f,r
dtype: object
</code></pre>
<p>You can use string concatenation for pro... | python|pandas|dataframe | 0 |
20,885 | 39,183,471 | Write multiple Numpy arrays of different dtype as columns of CSV file | <p>What would be the best way to write multiple numpy arrays of different dtype as different columns of a single CSV file?</p>
<p>For instance, given the following arrays:</p>
<pre><code>array([[1, 2],
[3, 4],
[5, 6]])
array([[ 10., 20.],
[ 30., 40.],
[ 50., 60.]])
</code></pre>
<p>I ... | <pre><code>In [38]: a=np.arange(1,7).reshape(3,2)
In [39]: b=np.arange(10,70.,10).reshape(3,2)
In [40]: c=np.concatenate((a,b),axis=1)
In [41]: c
Out[41]:
array([[ 1., 2., 10., 20.],
[ 3., 4., 30., 40.],
[ 5., 6., 50., 60.]])
</code></pre>
<p>All values are float; default <code>savetxt</c... | python|csv|numpy | 1 |
20,886 | 12,962,765 | Pandas DataFrame reindex column issue | <p>I've been trying to figure this out for the last couple of hours...</p>
<p>I have a list that I want to use as columns for DataFrames:</p>
<pre><code>totalColumns = [a, b, c, d, e, f.....z]
</code></pre>
<p>I have several data frames that look like this:</p>
<p>DataFrameOne:</p>
<pre><code> b f j
1 12 ... | <p>Do you have repeating columns in the two DataFrames? If yes, try to resolve that to have unique column names in the two frames, and execute the reindex again.</p> | python|pandas | 3 |
20,887 | 33,742,767 | Filter numpy structured array based on multiple values | <p>I have a numpy structured array. :</p>
<pre><code>myArray = np.array([(1, 1, 1, u'Zone3', 9.223),
(2, 1, 0, u'Zone2', 17.589),
(3, 1, 1, u'Zone2', 26.95),
(4, 0, 1, u'Zone1', 19.367),
(5, 1, 1, u'Zone1', 4.395)],
dtype=[('ID', '<i4'), ('Flag1', '<i4'), ('Flag2', '<... | <p>You need to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a> to test for membership of your <code>criteriaList</code>:</p>
<pre><code>In [1]: myArray["ZoneName"] in criteriaList
-----------------------------------------------------------------... | python|arrays|numpy|structured-array | 1 |
20,888 | 33,879,767 | How can I use Pandas or Numpy to infer a datatype from a list of values? | <p>I have an array of boolean values which is currently classed as an array of <code>object</code>. How can I get Pandas/Numpy to re-run the type inference engine?</p>
<pre><code>0 True
1 False
2 True
Name: b, dtype: object
</code></pre>
<p>The only solution I've found is to explicitly cast it to a Python ... | <p>Because you have a mixed <code>dtype</code> initially even after calling <code>dropna</code> then you can coerce the dtype, seeing as all you're interested in is preserving numeric and bool types then calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html" rel="n... | python|arrays|numpy|pandas | 2 |
20,889 | 29,370,057 | Select DataFrame rows between two dates | <p>I am creating a DataFrame from a csv as follows:</p>
<pre><code>stock = pd.read_csv('data_in/' + filename + '.csv', skipinitialspace=True)
</code></pre>
<p>The DataFrame has a date column. Is there a way to create a new DataFrame (or just overwrite the existing one) which only contains rows with date values that f... | <p>There are two possible solutions:</p>
<ul>
<li>Use a boolean mask, then use <code>df.loc[mask]</code></li>
<li>Set the date column as a DatetimeIndex, then use <code>df[start_date : end_date]</code></li>
</ul>
<hr>
<p><strong>Using a boolean mask</strong>:</p>
<p>Ensure <code>df['date']</code> is a Series with d... | python|pandas|dataframe | 639 |
20,890 | 62,353,970 | How to change ytick label colors based on a condition | <p>Here is some <a href="https://drive.google.com/file/d/1KHokKsjAIuCS8lNVRJ9NQJzk0-5q6JYA/view?usp=sharing" rel="nofollow noreferrer">data</a> I will use to demonstrate my question. This is a question branching from one of my old questions found <a href="https://stackoverflow.com/questions/60099737/gantt-chart-for-us... | <p>Tick labels are Text Artists and have a color properties. You can <a href="https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.axes.Axes.get_xticklabels.html#matplotlib.axes.Axes.get_xticklabels" rel="nofollow noreferrer">get a list of the labels</a> from the plot's Axes and use those two lists as indices to change ... | python|python-3.x|pandas|matplotlib|plot | 1 |
20,891 | 62,375,816 | How plot shaded area with date time in Matplotlib and Pandas? | <p>I plot a graph like below</p>
<pre><code># Retrieve data from FRED, check my notebook for pandareader's user guide
start = dt.datetime(1951, 1, 1)
end = dt.datetime.today()
V_M1 = pdr.data.DataReader('M1V', 'fred', start, end)
V_M2 = pdr.data.DataReader('M2V', 'fred', start, end)
fig, ax = plt.subplots(figsize = (... | <p>Using this dataframe:</p>
<pre><code> Peak Trough
0 1960-04-01 1961-02-01
1 1969-12-01 1970-11-01
2 1973-11-01 1975-03-01
3 1980-01-01 1980-07-01
4 1981-07-01 1982-11-01
5 1990-07-01 1991-03-01
6 2001-03-01 2001-11-01
7 2007-12-01 2009-06-01
</code></pre>
<p>conversion to datetime:</p... | python|pandas|matplotlib|time-series | 3 |
20,892 | 62,145,631 | Custom metrics for image segmentation in Keras | <p>I am trying to print and log the custom metrics (dice score) for all classes for validation set during training. I want the Keras to calculate custom metrics on validation set after each epoch. My current program is working but I have to use some tricks that ultimately cause memory problems during training.</p>
<p... | <p>As far as i understand, <code>temp_predict</code> and <code>temp_predict</code> are numpy arrays. So the only way you can end up with tensors is because you are using <code>tf.reduce_mean</code>. You can replace it with <code>np.mean</code>. This will only work if <code>dice_coef</code> has no tensorflow ops. If i... | tensorflow|keras | 1 |
20,893 | 62,141,567 | Can only use .str accessor with string values, which use np.object_ dtype in pandas | <p>Trying to create year to use in date from a number of columns, getting number with trailing zeros.
I use the calculation below to calculate year,</p>
<pre><code>f2.loc[:,'frt_elig_year'] = (f2['FrstElAge']-f2['iss_age']) + f2['eff_date'].dt.year
</code></pre>
<p>Get the year but with <code>4 0's</code> after i.e. ... | <p>Maybe try</p>
<pre><code>f2['frt_elig_year']=f2['frt_elig_year'].astype('str')
</code></pre>
<p>before making the substring .str[:4]</p>
<p>you can check the types of the variables of the dataframe by using</p>
<pre><code>f2.dtypes
</code></pre> | python|pandas | 0 |
20,894 | 62,223,016 | Single Prediction Image doesn't need to be rescaled? | <p>I followed a tutorial to make my first Convolutional Neural Network using Keras and I have a small question regarding the rescaling step.</p>
<p>So when we are importing the training set and test set, we create an instance of the <code>tf.keras.preprocessing.image.ImageDataGenerator</code> class and use it as:</p>... | <p>The image should be normalized that it should be divided by 255, if it's done during the training. Network will not be able to interpret that.</p>
<p>Also, when we use test_datagen, we apply Rescaling by 1/255 for the predict generator. </p>
<p>Normalization, mean subtraction and std deviation needs to be done at ... | python|keras|tensorflow2.0 | 1 |
20,895 | 62,323,334 | Python pandas - Dataframe getting second highest value with pd.groupby().agg() | <p>I have a DF [named cleanData] with some values and 2 columns which are custom_critirea and total_count.</p>
<p>Here is a section of my DF : </p>
<pre><code> CUSTOM_CRITERIA TOTAL_CODE_SERVED_COUNT
8 2768012 27
9 3307322 1
10 3270374 ... | <p>Sample data:</p>
<pre><code>cleanData = pd.DataFrame({
'TOTAL_CODE_SERVED_COUNT':[5,3,6,9,2,4,1],
'CUSTOM_CRITERIA':list('aaabbac')
}).sort_values('CUSTOM_CRITERIA')
print (cleanData)
TOTAL_CODE_SERVED_COUNT CUSTOM_CRITERIA
0 5 a
1 3 ... | python|pandas|numpy|aggregate | 3 |
20,896 | 51,417,242 | dstack with no multiple layers | <p>I have the following dataset with a numeric outcome and several columns that represent tags for the numeric outcome</p>
<pre><code>outcome tag1 tag2 tag3
340 a b a
123 a a b
23 d c b
54 c a c
</code></pre>
<p>I would like to unstack the dataset... | <p>Use:</p>
<pre><code>df1 = (df.melt('outcome', value_name='tag')
.sort_values('tag')
.drop('variable', axis=1)
.dropna(subset=['tag'])
.drop_duplicates()[['tag','outcome']])
</code></pre>
<p><strong>Explanation</strong>:</p>
<ol>
<li>Reshape by <a href="http://pandas.pydata.org/pandas-docs/... | python|pandas|dataframe|reshape | 0 |
20,897 | 51,471,573 | Pandas create new columns base on all existing columns' values, except the first column | <p>I have a dataframe like this:</p>
<pre><code>id day1 day2 day3 day4 day5
1 24 0 0 0 0
2 35 0 0 0 0
3 9 0 0 0 0
4 20 0 0 ... | <p>considering <code>id</code> is the index,</p>
<pre><code> df['new']=np.where(df.iloc[:,1:].eq(0).all(1),0,-1)
</code></pre> | python|pandas|conditional | 3 |
20,898 | 51,147,281 | Remove all words containing '@' from list in DataFrame | <p>I have a DataFrame in which one column contains lists of words.</p>
<pre><code>>>dataset.head(1)
>> contain
0 ["name", "Place", "ect@gtr", "nick"]
1 ["gf@e", "nobel", "play", "hi"]
</code></pre>
<p>I want to remove all the words which contain <code>'@'</code>. In... | <p>Try This one</p>
<pre><code>ab= np.column_stack([~df[col].str.contains(r"@") for col in df])
new_df=df.loc[ab.any(axis=1)]
print(new_df)
</code></pre> | regex|python-3.x|list|pandas|dataframe | 0 |
20,899 | 51,139,280 | append two data frames with unequal columns | <p>I am trying to append two dataframes in pandas which have two different no of columns. </p>
<pre><code>Example:
df1
A B
1 1
2 2
3 3
df2
A
4
5
Expected concatenated dataframe
df
A B
1 1
2 2
3 3
4 Null(or)0
5 Null(or)0
</code></pre>
<p>I am using
<code>df1.append(df2)</code> when the columns are sam... | <p>How about <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat</code></a>?</p>
<pre><code>>>> pd.concat([df1,df2])
A B
0 1 1.0
1 2 2.0
2 3 3.0
0 4 NaN
1 5 NaN
</code></pre>
<p>Also, <code>df1.append(df2)</code> still ... | python|pandas | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.