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 |
|---|---|---|---|---|---|---|
10,200 | 43,570,315 | Array of strings to dataframe with word columns | <p>What's the easiest way to get from an array of strings like this:</p>
<pre><code>arr = ['abc def ghi', 'def jkl xyz', 'abc xyz', 'jkl xyz']
</code></pre>
<p>to a dataframe where each column is a single word and each row contains 0 or 1 depending if the word appeared in the string. Something like this:</p>
<pre><c... | <p>EDITED - reduced to 3 essential lines:</p>
<pre><code>import pandas as pd
arr = ['abc def ghi', 'def jkl xyz', 'abc xyz', 'jkl xyz']
words = set( ' '.join( arr ).split() )
rows = [ { w : int( w in e ) for w in words } for e in arr ]
df = pd.DataFrame( rows )
print( df )
</code></pre>
<p>Result:</p>
<pre><c... | python|string|pandas|dataframe | 3 |
10,201 | 72,889,711 | Save a date when a condition is met | <p>I would like to know how to get the first Date when the futures_price is higher that prices_df. In this case I want 2022-05-05 because 2100 > 1082.77. Once the condition is met I don't need to save more dates, so even though 2000 is also higher than 1074.52 I don't want to get '2022-05-06'.</p>
<pre><code>price... | <p>You could do it like this:</p>
<pre><code>future_prices.loc[future_prices['High'] > prices_df].index[0]
</code></pre>
<p><strong>Result</strong></p>
<pre><code>'2022-05-05'
</code></pre>
<p>You would need to add additional error checking to handle the situation where the condition was not met.</p>
<p><strong>Hand... | python|pandas|if-statement|conditional-statements | 2 |
10,202 | 72,845,343 | Groupby range of numbers in Pandas and extract start and end values | <p><strong>Question</strong></p>
<p>Is it possible to groupby a range of numbers (int) in Pandas as per example below? If not, how would I achieve the desired output?</p>
<p><strong>Data</strong></p>
<pre><code>df = pd.DataFrame(
{"price": [9, 8, 9, 10, 11, 6, 7, 8, 9, 9, 9, 9, 10, 11, 5]},
index=pd.... | <p>IIUC you can use <code>diff</code> and <code>cumsum</code> to group, then check if the group has more than 1 element:</p>
<pre><code>df["group"] = df["higher_count"].diff().ne(1).cumsum()
print (df.loc[df.groupby("group")["higher_count"].transform(len)>1]
.rename_a... | python|pandas | 1 |
10,203 | 72,998,901 | SOLVED - Python Pandas not importing .csv. Error: pandas.errors.EmptyDataError: No columns to parse from file | <p>I am writing information into 2 .csv files (2 columns, separated by comma). I have ensured with time.sleep() that my desktop has enough time to write all the data to the file before pandas tries loading the information into the dataframe. It also seems like the issue remains with archorg.csv since I tried reversing ... | <p>Your csv sample worked fine for me, the puzzling part is that your other file worked fine.
i would suggest you try a work around and i hope it works</p>
<pre><code>import pandas as pd
df = pd.read_csv("filepath", delim_whitespace=True)
df[['Package', 'Version']] = df['package,version'].str.split(',', expan... | python|pandas|dataframe|csv | 0 |
10,204 | 72,908,197 | Join into one list in Python | <p>I had a DataFrame which I processed like so:</p>
<pre><code>df = my_table[0]
df_position = df['Position'].replace({'-':','}, regex=True)
</code></pre>
<p>That gave me a result like this:</p>
<pre><code>0 1,2,3,4
1 4,5,6,7
2 7,8,9,10
3 10,11,12,13
</code></pre>
<p>How can I put the data in a single list, like th... | <p>Use <code>Series.str.split(',')</code> to split the values on comma, then call <code>explode</code> to make it vertically long, then call <code>to_list</code> to get list out of it. Using <code>df.iloc[:,0]</code> assuming that you are interested in first column's values.</p>
<pre class="lang-py prettyprint-override... | python|pandas | 2 |
10,205 | 72,870,124 | For loop values to dataframe | <p>I have a question. (See at the end)</p>
<p>Code:</p>
<pre class="lang-py prettyprint-override"><code>def bin_to_raw(file):
header_len = 12
field_names = ['time', 'count']
for i in range(0, len(file), 12):
data = struct.unpack('< q i', file[i:i + 12])
for values in data:
pri... | <p>You can define a dictionary, store the values with <code>time</code> as a key and <code>count</code> as the value and convert it to a dataframe when returning like this:</p>
<pre><code>def bin_to_raw(file):
data_dict = {}
header_len = 12
field_names = ['time', 'count']
for i in range(0, len(file), 12... | python|pandas|dataframe|struct | 0 |
10,206 | 70,471,317 | Python: Groupby with conditions in pandas dataframe? | <p>I have a dataframe like below.</p>
<p>I need to do groupby(country and product) and <strong>Value</strong> column should contain <strong>count(id) where status is closed</strong> and I need to return remaining columns. Expected output format as below.</p>
<pre><code>Sample input
id status ticket_time ... | <p>When you group-by, typically, you're aggregating the data according to some category, so you won't keep all of the individual records, but will only be left with the columns that you've grouped-by and the column of aggregated data (a count, a mean, etc). However, the transform function will do what you want it to. I... | python|python-3.x|pandas|dataframe|pandas-groupby | 1 |
10,207 | 70,571,533 | Sorting 2d array into bins and add weights in each bin | <p>Suppose I have a series of 2d coordinates <code>(x, y)</code>, each corresponding to a weight. After I arrange them into bins (i.e. a little square area), I want to find the sum of the weights that fall into each bin. I used <code>np.digitize</code> to find which bins my data falls into, then I added weights in eac... | <p>You can do this with simple indexing. First get the bin number in each direction. You don't need <a href="https://numpy.org/doc/stable/reference/generated/numpy.digitize.html" rel="nofollow noreferrer"><code>np.digitize</code></a> for evenly spaced bins:</p>
<pre><code>xbin = (x // 1).astype(int)
ybin = (y // 1).ast... | python|numpy|histogram|binning | 2 |
10,208 | 70,660,531 | How to sort dataframe rows by multiple columns | <p>I'm having trouble formatting a dataframe in a specific style. I want to have data pertaining to one <code>S/N</code> all clumped together. My ultimate goal with the dataset is to plot Dis vs Rate for all the <code>S/N</code>s. I've tired iterating over rows to slice data but that hasnt worked. What would be the bes... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a>, which can accept a list of sorting targets. In this case it sounds like you want to sort by <code>S/N</code>, then <code>Dis</code>, then <code>Rate</code... | python|python-3.x|pandas|dataframe | 4 |
10,209 | 42,997,335 | Count the amount of a specific row elements combinations in an array | <p>I want to find how many times a certain combination of row elements occur in an array. I tried to use the numpy.where command, but I can not get it to work. As an example:</p>
<pre><code> array([['a', '2', 'b'],
['c', '4', 'a'],
['b', '2', 'c'],
['a', '5', 'b'],
['b', '7', ... | <p>Provided your matrix is contained in variable <code>arr</code>, you can do:</p>
<pre><code>import numpy as np
arr = arr.astype('U')
arr[np.logical_and(arr[:,0]=='a', arr[:,2]=='b')]
#array([['a', '2', 'b'],
# ['a', '5', 'b'],
# ['a', '3', 'b']],
# dtype='<U1')
</code></pre> | python|arrays|numpy | 0 |
10,210 | 42,716,882 | Stacking rows with common column values in pandas | <p>What would be a way to have put rows with same time_req together and not grouped according to ErrorCode. Currently I am gettting all 0 ErrorCode report and then all Errocode 1 report like below</p>
<pre><code>>>> data.groupby([data['ErrorCode'], pd.Grouper(freq='15T')])['latency'].describe().unstack().rese... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> for add m... | python|pandas | 1 |
10,211 | 42,611,192 | Trying to remove square brackets and apostrophe's dataframe list when i output to excel | <p>I am successful, to output my dataframe into excel, but there are extra unwanted brackets and apostrophe i want to remove.</p>
<pre><code>data1 = [x.split(',') for x in self.ismyFirstrange1]
data2 = [y.split(',') for y in self.isFirst1]
dataf1 = pd.DataFrame({'range 2456500 - 2556499': data1})
dataf2 = ... | <p>Try to preprocess your first column:</p>
<pre><code>df.iloc[:, 0] = df.iloc[:, 0].str[0].astype(int)
</code></pre> | python|list|pandas|dataframe | 0 |
10,212 | 42,961,672 | Cutting down the nr of decimals in the training data | <p>I use Keras backed by Tensorflow to train my models and i have a question about the nr of decimals in the training data.
Is cutting down the nr of decimals in the training data affecting the output? My original data has 15 decimals and i would like to cut that down to 8 because that data is well represented with 8 ... | <p>You answered your question already. If you know that your data is well represented with 8 decimal places, you can cut the rest without losing accuracy. In the end, it will not matter much as internally the places will be used anyway. Just because you leave some places in the input, does not mean that the precision o... | floating-point|tensorflow|neural-network|deep-learning|keras | 0 |
10,213 | 42,737,840 | Numpy: Compare float with threshold | <p>I found how to compare floats with equality here:</p>
<p><a href="https://stackoverflow.com/questions/18106975/compare-float-and-float64-in-python">Compare `float` and `float64` in python</a></p>
<p><a href="https://stackoverflow.com/questions/39757559/working-with-floating-point-numpy-arrays-for-comparison-and-re... | <p>In most practical circumstances an exact comparison will be not be possible because of the little errors you collect while doing calculations.</p>
<p>If you want to do proper numerics you'll have to carry an error estimate along with all your results which is quite tedious.</p>
<p>(There is a library called flint ... | python|numpy|floating-point | 0 |
10,214 | 27,320,641 | Imposing a threshold on values in dataframe in Pandas | <p>I have the following code:</p>
<pre><code>t = 12
s = numpy.array(df.Array.tolist())
s[s<t] = 0
thresh = numpy.where(s>0, s-t, 0)
df['NewArray'] = list(thresh)
</code></pre>
<p>while it works, surely there must be a more pandas-like way of doing it.</p>
<p><strong>EDIT:</strong><br>
<code>df.Array.head()</co... | <p>IIUC you can simply subtract and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.clip_lower.html" rel="nofollow"><code>clip_lower</code></a>:</p>
<pre><code>In [29]: df["NewArray"] = (df["Array"] - 12).clip_lower(0)
In [30]: df
Out[30]:
Array NewArray
0 10 0
1 ... | pandas | 2 |
10,215 | 14,611,250 | Mask specific columns of a numpy array | <p>I have a 2D numpy array A of (60,1000) dimensions.<br>
Say, I have a variable <code>idx=array([3,72,403, 512, 698])</code>.</p>
<p>Now, I want to mask all the elements in the columns specified in <code>idx</code>. The values in these columns might appear in other columns but they shouldn't be masked.</p>
<p>Any he... | <pre><code>In [22]: A = np.random.rand(5, 10)
In [23]: idx = np.array([1, 3, 5])
In [24]: m = np.zeros_like(A)
In [25]: m[:,idx] = 1
In [26]: Am = np.ma.masked_array(A, m)
In [27]: Am
Out[27]:
masked_array(data =
[[0.680447483547 -- 0.290757600047 -- 0.0718559525615 -- 0.334352145502
0.0861242618662 0.52706809... | python|numpy|mask | 11 |
10,216 | 24,958,233 | Mapping a Series with a NumPy array -- dimensionality issue? | <p>When I'm using 2d array maps, everything works fine. When I start using 1d arrray's this error occurs; <code>IndexError: unsupported iterator index</code>. This is the error I'm talking about:</p>
<pre><code>In [426]: y = Series( [0,1,0,1] )
In [427]: arr1 = np.array( [10,20] )
In [428]: arr2 = np.array( [[10,20],... | <p>You need to either convert the Series to a array, or vice-versa. Indexers must be 1-d for a 1-d object.</p>
<pre><code>In [11]: arr1[y.values]
Out[11]: array([10, 20, 10, 20])
In [12]: Series(arr1)[y]
Out[12]:
0 10
1 20
0 10
1 20
dtype: int64
</code></pre> | numpy|pandas | 2 |
10,217 | 30,443,883 | How to smoothen data in Python? | <p>I am trying to smoothen a scatter plot shown below using SciPy's B-spline representation of 1-D curve. The data is available <a href="https://drive.google.com/file/d/0BwwhEMUIYGyTaUZ3bThoNXc2UW8/view?usp=sharing" rel="nofollow noreferrer">here</a>.</p>
<p><img src="https://i.stack.imgur.com/0Dbij.png" alt="enter im... | <p>Use a larger smoothing parameter. For example, <code>s=1000</code>:</p>
<pre><code>tck = interpolate.splrep(x, y, k=3, s=1000)
</code></pre>
<p>This produces:</p>
<p><img src="https://i.stack.imgur.com/ql7A9.png" alt="interpolation"></p> | python|numpy|scipy|smoothing | 4 |
10,218 | 39,187,009 | TensorFlow: how to name operations for tf.get_variable | <p>My question is related to this <a href="https://stackoverflow.com/questions/36612512/tensorflow-how-to-get-a-tensor-by-name">Tensorflow: How to get a tensor by name?</a></p>
<p>I can give names to operations. But actually they named differently.
For example:</p>
<pre><code>In [11]: with tf.variable_scope('test_sco... | <p>I disagree with @rvinas answer, you don't need to create a Variable to hold the value of a tensor you want to retrieve. You can just use <code>graph.get_tensor_by_name</code> with the correct name to retrieve your tensor:</p>
<pre class="lang-py prettyprint-override"><code>with tf.variable_scope('test_scope') as sc... | python|tensorflow | 4 |
10,219 | 33,896,521 | How to add a number to a portion of dataframe column in pandas? | <p>I have a dataframe with two columns A and B.</p>
<pre><code>A B
1 0
2 0
3 1
4 2
5 0
6 3
</code></pre>
<p>What I want to do is to add column A with with column B. But only with the corresponding non zero values of column B. And put the result on column B.</p>
<pre><... | <p>use <code>.loc</code> with a boolean mask:</p>
<pre><code>In [49]:
df.loc[df['B'] != 0, 'B'] = df['A'] + df['B']
df
Out[49]:
A B
0 1 0
1 2 0
2 3 4
3 4 6
4 5 0
5 6 9
</code></pre> | python-2.7|pandas | 0 |
10,220 | 22,693,533 | Why am I getting an empty row in my dataframe after using pandas apply? | <p>I'm fairly new to Python and Pandas and trying to figure out how to do a simple split-join-apply. The problem I am having is that I am getting an blank row at the top of all the dataframes I'm getting back from Pandas' apply function and I'm not sure why. Can anyone explain?</p>
<p>The following is a minimal exampl... | <p>The groupby/apply operation returns is a new DataFrame, with a named index. The name corresponds to the column name by which the original DataFrame was grouped.</p>
<p>The name shows up above the index. If you reset it to <code>None</code>, then that row disappears:</p>
<pre><code>In [155]: sorbet_vals.index.name ... | python|python-3.x|pandas | 12 |
10,221 | 22,893,703 | increasing NumPy memory limit | <p>I am currently doing coding some NN for huge dataset, for example MNIST dataset (about 700*50000). But when I test it, my code got MemoryError. I have a computer with 12 GB ram, but I think Python or Numpy can't use all of them. </p>
<p>Can I push Python or Numpy to use all remaining available memory in my PC ?</p>... | <p>I believe that the Python(x, y) distribution of Python is still only a 32-bit build <a href="https://code.google.com/p/pythonxy/wiki/Roadmap" rel="nofollow">(64-bit support is still on its roadmap)</a>, so you are limited to 32 bits of address space even though you are using a 64-bit OS. You will need to install a 6... | python|numpy | 5 |
10,222 | 22,638,099 | Pause Python program on the fly (and resume) | <p>I am building a machine learning algorithm(like neural network) where <strong>class variables</strong>(i.e numpy <strong>matrices</strong>) represent various parameters of the system</p>
<p>Training the system is done by iteratively update all class variables. The more iterations the better. I want to get up every ... | <p>I'm not familiar with numpy, but here is a simple class that can stop and resume:</p>
<pre><code>class Program():
def run(self):
while 1:
try:
self.do_something()
except KeyboardInterrupt:
break
def do_something(self):
print("Doing so... | python|numpy|pandas|machine-learning|neural-network | 4 |
10,223 | 15,008,252 | How to do a data frame join with pandas? | <p>Can somebody explain data frame joins with <code>pandas</code> to me based on this example?</p>
<p>The first dataframe, let's call it <code>A</code>, looks like this:</p>
<p><img src="https://i.stack.imgur.com/GncfD.png" alt="enter image description here"></p>
<p>The second dataframe, <code>B</code>, looks like t... | <p>I think I would use <code>merge</code> here:</p>
<pre><code>>>> a = pd.DataFrame({"graph": ["as-22july06", "belgium", "cage15"], "running": [2, 879, 4292], "mod": [0.28, 0.94, 0.66], "eps": [220, 176, 1096]})
>>> b = pd.DataFrame({"graph": ["as-22july06", "astro-ph", "cage15"], "running": [395.186... | join|dataframe|pandas|ipython-notebook | 5 |
10,224 | 29,501,823 | Numpy: Filtering rows by multiple conditions? | <p>I have a two-dimensional numpy array called <code>meta</code> with 3 columns.. what I want to do is :</p>
<ol>
<li>check if the first two columns are ZERO</li>
<li>check if the third column is smaller than X</li>
<li>Return only those rows that match the condition</li>
</ol>
<p>I made it work, but the solution see... | <p>you can use multiple filters in a slice, something like this:</p>
<pre><code>x = np.arange(90.).reshape(30, 3)
#set the first 10 rows of cols 1,2 to be zero
x[0:10, 0:2] = 0.0
x[(x[:,0] == 0.) & (x[:,1] == 0.) & (x[:,2] > 10)]
#should give only a few rows
array([[ 0., 0., 11.],
[ 0., 0., 1... | python|numpy|conditional-statements | 20 |
10,225 | 29,525,120 | Pandas: Creating a histogram from string counts | <p>I need to create a histogram from a dataframe column that contains the values "Low', 'Medium', or 'High'. When I try to do the usual df.column.hist(), i get the following error.</p>
<pre><code>ex3.Severity.value_counts()
Out[85]:
Low 230
Medium 21
High 16
dtype: int64
ex3.Severity.hist()
TypeErr... | <pre><code>ex3.Severity.value_counts().plot(kind='bar')
</code></pre>
<p>Is what you actually want.</p>
<p>When you do:</p>
<pre><code>ex3.Severity.value_counts().hist()
</code></pre>
<p>it gets the axes the wrong way round i.e. it tries to partition your y axis (counts) into bins, and then plots the number of stri... | pandas | 59 |
10,226 | 62,291,701 | How can I build a class around a pandas dataframe that contains extra columns that are ignored when accessing the dataframe | <p>I am trying to rework some code that contains a class with a Pandas DataFrame container for it's data. I have implemented the class with a large number of columns that encompass all the possible data, but are often not all full, ie: some columns are all null valued. I would like to introduce a mechanism that will ... | <p>To drop columns when they contain NaN values, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>.dropna()</code></a> with the <code>axis=1</code> parameter.</p>
<p>Try with this;</p>
<pre><code>class MyData:
def __init__(self)... | python|pandas | 0 |
10,227 | 62,270,525 | In PyTorch, what's the difference between training an RNN to predict the last word given a sequence, vs predicting the entire sequence shifted? | <p>Let's say I'm trying to train an RNN language model in PyTorch. Suppose I iterate over batches of word sequences, and that each training batch tensor has the following shape:</p>
<pre><code>data.shape = [batch_size, sequence_length, vocab_dim]
</code></pre>
<p>My question is, what's the difference between using on... | <p>Consider the sequence prediction problem <code>a b c d</code>
where you want to train an RNN via teacher forcing.</p>
<p>If you only use the last word in the sentence, you are doing the following classification problem (on the left is the input; on the right is the output you're supposed to predict):</p>
<p><code>... | python|machine-learning|pytorch|recurrent-neural-network|language-model | 1 |
10,228 | 62,137,103 | Getting practice with pandas & numpy | <p>I just finished reading some books about pandas, numpy & matplotlib and thought about getting some practice.
Unfortunately, I am a bit lost on how to start.
Can anyone recommend a site, which provides csv-files to practice on?
I have found some sites like kaggle or data.gov, but they just have files, which are ... | <p>Just Search the Web. Using e.g. Google seach for <em>Pandas tutorial</em>,
<em>Numpy tutorial</em> and so on.</p>
<p>Even the home site of <em>matplotlib</em> contains a couple of introductory
tutorials. See e.g. <a href="https://matplotlib.org/tutorials/index.html" rel="nofollow noreferrer">https://matplotlib.org/... | python|pandas|numpy|matplotlib | 1 |
10,229 | 62,471,058 | I'm unable to transform my DataFrame into a Variable to store data-values/features (Linear Discriminant Analysis) | <p>I'm using LDA to reduce two tables I've created, holds and latency, down from 9 and 18 features respectively (along with a target each). I planned on using LDA for this and am currently trying to parse in the features into a variable. However that doesn't seem to be working. I receive a KeyError(<a href="https://i.s... | <p><strong>This error has nothing to do with the LDA or scikit-learn in general.</strong></p>
<p><strong>The error is coming from the way you try to index the pandas dataframe that you have.</strong></p>
<hr>
<p>Use this:</p>
<pre><code>X = holds.iloc[: , [0,1,2,3,4,5,6,7,8]].values
Y = holds.iloc[:, 9].values
</co... | python|pandas|scikit-learn|sklearn-pandas | 0 |
10,230 | 62,268,523 | Amount of rows that contain a specific word in a dataframe | <p>I have a data frame in which each row represents a customer message. I want a data frame with a Document Frequency - count the number of documents that contain that word. How can I get that?</p>
<p>For example, I have this</p>
<pre><code>DATAFRAME A
customer message
A hi i need help i want a card
B ... | <p>From your original DataFrame, set the index, split the strings, explode and reset the index. This splits each word into its own cell, and the index manipulation makes it so we maintain the <code>'customer'</code> it was attached with. </p>
<p><code>drop_duplicates</code> so words are only counted once within each <... | python|pandas|dataframe | 2 |
10,231 | 51,433,415 | Seaborn not changing data in lineplot facets of facetgrid | <p>I'm trying to use a <code>seaborn</code> <code>facetgrid</code> to plot timeseries data from a large file.</p>
<pre><code>from matplotlib import pyplot as plt
import seaborn as sb
import pandas as pd
df_ready=pd.read_hdf('data.hdf')
... # drop null rows, etc.
fg=sb.FacetGrid(data=df_ready[ df_ready.medium == 'LS... | <p>D'oh!</p>
<p>The answer is that I'm passing kwargs to the mapped function, which is not supported. They should be positional instead. cf. <a href="https://stackoverflow.com/questions/24878095/plotting-errors-bars-from-dataframe-using-seaborn-facetgrid">Plotting errors bars from dataframe using Seaborn FacetGrid</a>... | python|pandas|seaborn | 1 |
10,232 | 51,532,581 | Create barplot from string data using groupby and multiple columns in pandas dataframe | <p>I'd like to make a bar plot in python with multiple x-categories from counts of data either "yes" or "no". I've started on some code but I believe the track I'm on in a slow way of getting to the solution I want. I'd be fine with a solution that uses either seaborn, Matplotlib, or pandas but <em>not</em> Bokeh becau... | <p>Not exactly sure if I understand the question correctly. It looks like it would make more sense to look at the proportion of answers per boat type <em>and</em> color.</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
data = [{'ship': 'Yes','canoe': 'Yes', 'cruise': 'Yes', 'kayak': 'No','color': 'Re... | python|pandas|dataframe|plot|group-by | 4 |
10,233 | 51,424,613 | How to remove some rows in a group by in python | <p>I'm having a dataframe and I'd like to do a <code>groupby()</code> based a column and then sort the values within each group based on a date column. Then, from a each I'd like to remove records whose value for <code>column_condition == 'B'</code> until I reach to a row whose <code>column_condition == 'A'</code>. For... | <p>I think I finally understand your question: you wish to <code>groupby</code> a <code>dataframe</code> by <code>'ID'</code>, sort by date, and keep the rows after the first ocurrence of <code>'A'</code> in your <code>condition</code> column. I've come up with the following one liner solution:</p>
<p><strong>Setting ... | python|group-by|pandas-groupby | 4 |
10,234 | 51,422,855 | Pandas dividing every N column by a fixed column | <p>Given a dataframe like this</p>
<pre><code> ImageId | Width | Height | lb0 | x0 | y0 | lb1 | x1 | y1 | lb2 | x2 | y2
0 abc | 200 | 500 | ijk | 4 | 8 | zyx | 15 | 16 | www | 23 | 42
1 def | 300 | 800 | ijk | 42 | 23 | zyx | 16 | 15 | www | 8 | 4
2 ghi | 700 | 400 | ijk | 9 | 16 | ... | <p>Use <code>div</code> with <code>axis=0</code> parameter:</p>
<pre><code>df.iloc[:, 4::3].div(df['Width'], axis=0)
</code></pre>
<p>Output:</p>
<pre><code> x0 x1 x2
0 0.020000 0.075000 0.115000
1 0.140000 0.053333 0.026667
2 0.012857 0.024286 0.061429
</code></pre> | python|pandas|dataframe | 2 |
10,235 | 48,202,955 | Concatenate dataframes with the same column names but different suffixes | <p>I have used pandas merge to bring together two dataframes (24 columns each), based on a set of condition, to generate a dataframe which contains rows which have the same values; naturally there are many other columns in each dataframe with different values. The code used to do this is:</p>
<pre><code> Merged=pd.... | <p>You can do something with the <code>suffixes</code>, split the columns to a <code>MultiIndex</code>, and then unstack</p>
<pre><code>Merged=pd.merge(Buy_MD,Sell_MD, on= ['ID','LocName','Sub-Group','Month'], how = 'inner', suffixes=('_buy', '_sell')
Merged.columns = pd.MultiIndex.from_tuples(Merged.columns.str.rspl... | python|pandas|dataframe|merge | 1 |
10,236 | 48,512,090 | numpy apply along axis not working with weekday | <p>I have a numpy array:</p>
<pre><code>>>> type(dat)
Out[41]: numpy.ndarray
>>> dat.shape
Out[46]: (127L,)
>>> dat[0:3]
Out[42]: array([datetime.date(2010, 6, 11), datetime.date(2010, 6, 19), datetime.date(2010, 6, 30)], dtype=object)
</code></pre>
<p>I want to get weekdays for each date... | <p><code>np.apply_along_axis</code> doesn't make much sense with a 1d array. In a 2d or higher array, it applies the function to 1d slices from that array. Regarding that function:</p>
<blockquote>
<p>This function should accept 1-D arrays. It is applied to 1-D
slices of <code>arr</code> along the specif... | python|pandas|numpy|datetime|weekday | 2 |
10,237 | 70,949,306 | Filter Dataframe Based on Local Minima with Increasing Timeline | <p>EDITED:</p>
<p>I have the following dataframe of students with their exam scores in different dates (sorted):</p>
<pre><code>df = pd.DataFrame({'student': 'A A A B B B B C C'.split(),
'exam_date':[datetime.datetime(2013,4,1),datetime.datetime(2013,6,1),
datetime.datet... | <p>We could try the following:</p>
<ol>
<li><p>Find the difference between consecutive scores for each student using <code>groupby</code> + <code>diff</code>.</p>
</li>
<li><p>using <code>where</code>, assign NaN values to all rows where the score difference is less than 10</p>
</li>
<li><p>use <code>groupby</code> + <... | python|pandas|dataframe|datetime|data-manipulation | 1 |
10,238 | 70,817,047 | How to handle .to_sql if dataframe is empty | <p>I am collecting data points from google books, converting the data to a dataframe, then ingesting into mysql database.</p>
<p>For each datapoint, I will create a dataframe, ingest into a staging table, fetch from that staging table into a main table, then drop the staging table.</p>
<p>Sometimes, some batches of boo... | <p>Check if dataframe is empty, if it is empty print as empty and in the else block run the create table SQL script.</p>
<pre><code>if adaptation.empty:
print('adaptation is empty')
else:
adaptation.to_sql(name='adaptation_staging', con=mysql_conn, if_exists='append', index=False)
</code></pre> | python|mysql|pandas | 2 |
10,239 | 51,860,307 | Is there a way to append data in distributed Tensorflow? | <p>I am using distributed TensorFlow not to distribute the network, but to distribute the work. </p>
<p>With distributed TensorFlow we get framework to distribute the work and a communication between the workers for the status. This lighted weighted communication protocol, inbuilt recovery and device selection for spe... | <p>I tired this and able to get the updates from local workers information to global network</p>
<pre><code>import tensorflow as tf
import numpy as np
import os
import time
def main(server, log_dir, context):
#create a random array
a = np.arange(10).reshape((5, 2))
with tf.device(tf.train.replica_device_se... | python|tensorflow|distributed | 0 |
10,240 | 51,901,170 | Apply average function to MultiIndex dataframe with external condition | <p>A dataframe (<strong>A</strong>) has 3 MultiIndex columns.
Another dataframe (<strong>B</strong>) has the information of the <em>quote_date</em>, <em>expiration</em> and <em>strike</em>.</p>
<p>The goal of this task is to filter the dataframe <strong>A</strong> using the dataframe <strong>B</strong>, in order to c... | <p>Redefine <code>B</code> as "MultiIndex Only" dataframe, and then mask <code>A</code> by <code>B</code> using the <code>index</code>, followed by <code>groupby</code>. Finally, combine dataframes with and without <code>groupby</code>.</p>
<pre><code># create "index only" dataframe
B = B.set_index(['quote_date', 'exp... | python|pandas|dataframe | 1 |
10,241 | 51,716,241 | Batch Normalization vs Batch Renormalization | <p>As someone who doesn't have a strong background in statistics, could someone explain to me the main limitation(s) of batch normalization that batch renormalization aims to solve, especially in terms of how it differs from batch normalization?</p> | <p>Very briefly, batch normalization simply re-scales each batch to a common mean and deviation. Each batch is scaled independently. Batch <strong>re</strong>normalization includes prior normalization parameters as part of the new computation, so that each batch is normalized to a standard common to all batches. Thi... | tensorflow|machine-learning|keras|deep-learning|batch-normalization | 6 |
10,242 | 51,768,789 | Pandas use multiple conditions for assigning values in a column: | <p>I have a dataframe with 3 columns: <code>Role</code>, <code>to_group1</code>, <code>to_group2</code>, <code>remove</code> and i would like to assign <code>True</code> where the value in <code>to_group1</code> AND <code>to_group2</code> are nan, but it seems that my code is not working, what am I doing wrong?</p>
<p... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.isnull.html" rel="nofollow noreferrer"><code>isnull()</code></a> instead of <code>== np.nan</code></p>
<pre><code>df['remove'] = np.where(df.to_group1.isnull() & df.to_group2 .isnull(), True, np.nan)
0 NaN
1 1
2 NaN
</code></pr... | python|pandas|numpy|dataframe | 2 |
10,243 | 64,293,953 | Count values in Pandas data Frame -Python | <p>I have a data set as such
<a href="https://i.stack.imgur.com/T3dKY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T3dKY.png" alt="enter image description here" /></a></p>
<p>For simplicity -Let's say I want to calculate the number of type of each manufacturer of the plane.
<a href="https://i.stac... | <p>You can use <code>dataframe['manufacturer'].value_counts()</code> to get the result that you want;</p>
<p>However, note that you have <code>NaNs</code> in your column; so prior to applying the function above, use:</p>
<pre><code>dataframe.dropna(subset=['manufacturer'],inplace=True)
</code></pre>
<p>Summing it up:</... | python|python-3.x|pandas|dataframe | 2 |
10,244 | 64,486,513 | How can I give a separate value to each index with the loc function? | <p>It applies the last value obtained by putting the loc function into the for loop to all indexes in the index list.What I am trying to do is to assign different values with each indexe for loop. I tried a lot but couldn't.</p>
<p>My unsuccessful attempt to give last for loop value to selected directories:</p>
<pre>... | <p>I'm not sure what you want to do, but perhaps you can achieve what you want by assigning the whole value list to your index-value desired combination:</p>
<pre><code>data.loc[index_list, 'VEHICLE_YEAR'] = value_list
</code></pre> | python|python-3.x|pandas|numpy|dataframe | 1 |
10,245 | 64,206,194 | Append value to list inside a column manipulates all rows instead of one | <p>I have the following Dataframe:</p>
<pre><code> text values
0 a text []
1 another text []
2 some more text []
3 and again some text []
</code></pre>
<p>I want to append items to a specific list by index. For example I want to add "value" to the first row... | <p>This is probably due to the fact that values within the 'values' column always refer to the same object. Look at the following example:</p>
<pre><code>import pandas as pd
lst = []
df = pd.DataFrame({'values': [[] for i in range(5)]})
df2 = pd.DataFrame({'values': [lst for i in range(5)]})
df.iloc[0]['values'].appe... | python|pandas | 1 |
10,246 | 49,235,611 | How to convert from numpy array to file byte object? | <p>I read an image file as</p>
<pre><code>with open('abc.jpg', 'rb') as f:
a = f.read()
</code></pre>
<p>On the other hand, I use <code>cv2</code> to read the same file</p>
<pre><code>b = cv2.imread('abc.jpg', -1)
</code></pre>
<p>How to convert <code>b</code> to <code>a</code> directly?</p>
<p>Thanks.</p> | <h2>Answer to your question:</h2>
<pre><code>success, a_numpy = cv2.imencode('.jpg', b)
a = a_numpy.tostring()
</code></pre>
<h2>Things you should know:</h2>
<p>First, <code>type(a)</code> is a binary string, and <code>type(b)</code> is a numpy array. It's easy to convert between those types, since you can make <cod... | python|numpy|opencv | 4 |
10,247 | 49,019,469 | IndexError: while running generalized hough transform on my data, why? | <p>I am trying to apply the <a href="https://github.com/adl1995/generalised-hough-transform" rel="nofollow noreferrer">available generalized hough transform (GHT)</a> on my own data. the program is running very well on the provided sample data, however, for my data once it reaches to <a href="https://github.com/adl1995... | <p>This error message states that the indices should be <code>only integers</code>. And as you can see, <code>table</code> is a list of <code>vectors</code> and each <code>vector</code> is a 2d-vector as you stated in the question.</p>
<p>So, <code>vector[0]</code> and <code>vector[1]</code> are mostly <strong>float</... | python|python-2.7|numpy|image-processing|hough-transform | -1 |
10,248 | 48,898,124 | cannot fine-tune a Keras model with 4 VGG16 | <p>I build a model with 4 VGG16 (not including the top) and then concatenate the 4 outputs from the 4 VGG16 to form a dense layer, which is followed by a softmax layer, so my model has 4 inputs (4 images) and 1 output (4 classes).</p>
<p>I first do the transfer learning by just training the dense layers and freezing t... | <p>It turns out that it has nothing to do the number of VGG16 in the model. The problem is due to the batch size.</p>
<p>When I said the model with 1 VGG16 worked, that model used batch size 8. And when I reduced the batch size smaller than 4 (either 1, 2, or 3), then the same errors happened.</p>
<p>Now I just use b... | tensorflow|keras|keras-layer | 0 |
10,249 | 58,909,521 | Python: float() argument must be a string or a number, not 'Period' | <p>Have the following piece of code through which I am trying to plot a graph:</p>
<pre class="lang-py prettyprint-override"><code>df:
date qty
0 2016-01-01 21.523810
1 2016-02-01 20.476190
2 2016-03-01 20.523810
3 2016-04-01 26.666667
4 2016-05-01
...
</code></pre>
<pre class="lang-py pre... | <p>One idea is convert periods to datetimes before ploting:</p>
<pre><code>df['date'] = df['date'].dt.to_timestamp()
</code></pre>
<p>Also for me working your solution, maybe you can try upgrade to last version of pandas/matplotlib.</p> | python|pandas|matplotlib | 1 |
10,250 | 58,830,402 | How to resolve ??AttributeError: 'NoneType' object has no attribute 'head' | <p>I am working with stock data from Google, Apple, and Amazon. All the stock data was downloaded from yahoo finance in CSV format. I have a file named GOOG.csv containing the Google stock data, a file named AAPL.csv containing the Apple stock data, and a file named AMZN.csv containing the Amazon stock data. I am getti... | <p><code>inplace=True</code> makes it update without assigning, so either use:</p>
<pre><code>google_stock.rename(columns={'Adj Close':'google_stock'},inplace=True)
# Change the Adj Close column label to Apple
apple_stock.rename(columns={'Adj Close':'apple_stock'},inplace=True)
# Change the Adj Close column label to... | python|pandas | 4 |
10,251 | 58,771,436 | Plot polylines on top of OSMnx map | <p>Using the OSMnx library, I'm trying to draw lines as polygons on top of a base map (with per-defined coordinates not adhering to the underlying network), but with no luck. I'm certain that the coordinates I have are inside of the boundary, and I get no error when adding them. </p>
<p>Here's my current code, which g... | <p>In geopandas dataframes, the geo-coordinates are (longitude, latitude). Here is a simple demonstration code that plots some sample data.</p>
<pre><code>import geopandas as gpd
import pandas as pd
import matplotlib.pyplot as plt
import osmnx as ox
from shapely import wkt #need wkt.loads
# simple plot of OSM data
g... | python|geospatial|geopandas|shapely|osmnx | 1 |
10,252 | 58,628,645 | Delete rows of pandas df under variance threshold | <p>My df looks as follows (I got it with pivot_table):</p>
<pre><code>ID_column Test1 Test2 Test3 Test4
ID1 0 1 3 0
ID2 4 2 0 0
ID3 3 1 3 5
</code></pre>
<p>I want to delete all <strong>rows</strong> that fall under a variance threshold x when calculating the vari... | <p>You can use the following code to do this:</p>
<pre><code>threshold = 1 # define variance threshold
row_vars = df.var(axis=1) # calculate variance over rows.
rows_to_drop = df[row_vars>threshold].index
# drop the rows in place
df.drop(rows_to_drop, axis=0, inplace=True)
</code></pre>
<p>To summarise: </p>... | python|pandas|variance | 2 |
10,253 | 70,066,081 | DataFrame Pandas Python select data from date | <pre><code>df1 = df1[df1['TIME STAMP'].between('2021-01-27 00:00:00', '2021-10-10 23:59:59')]
</code></pre>
<p>The above code is selecting a dataframe from two specific dates and it works fine.</p>
<p>I want to select a from date and to date (infinity/the last date of dataframe) or any option to select only from date.<... | <p>You can use comparison operators between timestamps:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df1 = df1[df1['TIME STAMP'] >= pd.Timestamp('2021-01-27 00:00:00')]
</code></pre> | python|pandas | 1 |
10,254 | 70,335,049 | Sagemaker Serverless Inference & custom container: Model archiver subprocess fails | <p>I would like to host a model on Sagemaker using the new <a href="https://aws.amazon.com/about-aws/whats-new/2021/12/amazon-sagemaker-serverless-inference/?nc1=h_ls" rel="nofollow noreferrer">Serverless Inference</a>.</p>
<p>I wrote my own container for inference and handler following several guides. These are the re... | <p>So the issue really was related to hosting the model using the sagemaker inference toolkit and MMS which always uses the multi-model scenario which is not supported by serverless inference.</p>
<p>I ended up writing my own Flask API which actually is nearly as easy and more customizable. Ping me for details if you'r... | amazon-web-services|amazon-sagemaker|huggingface-transformers|mxnet | 0 |
10,255 | 56,115,736 | What wrong when i load state_dict of resnet50.pth with pytorch | <p>i load the resnet50.pth and KeyError of 'state_dict'
pytorch version is 0.4.1 </p>
<p>i tried delete/add torch.nn.parallel but it didn't help
and resnet50.pth loaded from pytorch API</p>
<p>related code</p>
<pre><code>model = ResNet(len(CLASSES), pretrained=args.use_imagenet_weights)
if cuda_is_available:
mod... | <p>Did you perhaps mean the following?</p>
<pre><code>state_dict = torch.load(args.model['state_dict'])
</code></pre>
<hr>
<p>From your edit, it seems that your model is the model itself. There is no state_dict. So just use </p>
<pre><code>state_dict = torch.load(args.model)
</code></pre> | python|pytorch|resnet | 1 |
10,256 | 56,310,448 | basinhopping_bounds() got an unexpected keyword argument 'f_new' | <p>I'm getting this error when using basin-hopping:
<code>basinhopping_bounds() got an unexpected keyword argument 'f_new'</code></p>
<p>I'm trying to implement the analysis of <a href="https://www.sciencedirect.com/science/article/pii/S016501149600334X" rel="nofollow noreferrer">X,F models</a> in Python to solving a ... | <p><a href="https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.basinhopping.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.basinhopping.html</a></p>
<p>This docs describes the <code>accept_test</code> argument. It must be callable tha... | python|numpy|scipy|scipy-optimize|scipy-optimize-minimize | 0 |
10,257 | 56,015,171 | Repeat an array over channels | <p>For an array of shape(No of examples, row, height, channel). How can I simply replace channels with No of examples? I have searched for <code>np.repeat()</code> but I failed in applying it.</p>
<pre><code>import numpy as np
array = np.array([
[
[[0],[1]],
... | <p>You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html" rel="nofollow noreferrer"><code>np.tile</code></a>:</p>
<pre><code>np.tile(array, (1, 1, 1, array.shape[0]))
</code></pre>
<p>or <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollo... | python|python-3.x|numpy|tensorflow|numpy-ndarray | 3 |
10,258 | 56,093,294 | Time Series with Pandas / Cumulative average of previous values for different groups (lagged variabled for different groups) | <p>I am trying to get the cummulative average of previous values for different gropus using Pandas.</p>
<p>My original dataframe(df) is:</p>
<pre><code>idx = [np.array(['Jan-18', 'Jan-18', 'Feb-18', 'Mar-18', 'Mar-18', 'Mar-18','Apr-18', 'Apr-18', 'May-18', 'Jun-18', 'Jun-18', 'Jun-18','Jul-18', 'Aug-18', 'Aug-18', '... | <p>I am using <code>expanding</code></p>
<pre><code>df.groupby('type')['xx'].expanding(min_periods=2).mean().\
reset_index(level=0,drop=True).reindex(df.index)
date type
2018-01-01 A NaN
B NaN
2018-02-01 B 4.000000
2018-03-01 A 1.500000
B 5... | python|pandas|dataframe|time-series | 1 |
10,259 | 56,324,543 | How to calculate mean of columns from array lists in python using numpy? | <p>I am trying to calculate the mean average of columns from a list of arrays.</p>
<pre><code>f1_score = [array([0.807892 , 0.91698113, 0.73846154]),
array([0.80041797, 0.9056244 , 0.72017837]),
array([0.80541103, 0.91493384, 0.70282486])]
</code></pre>
<p>I also tried as mentioned below, but... | <p>You can use numpy's mean function and set the axis as 0.</p>
<pre><code>mean(f1_score, axis=0)
</code></pre>
<p>And then you get the required answer</p>
<pre><code>array([0.80457367, 0.91251312, 0.72048826])
</code></pre> | arrays|python-3.x|numpy | 4 |
10,260 | 56,042,264 | pct_change between 2 columns in Pandas, with row offset | <p>My dataframe looks like this:</p>
<pre><code> Date_Time Open Close
0 2004-05-10 16:00:00 12.88 12.54
1 2004-05-11 16:00:00 12.87 12.68
2 2004-05-12 16:00:00 12.79 12.88
3 2004-05-13 16:00:00 12.84 12.88
4 2004-05-14 16:00:00 12.64 12.88
5 2004-05-17 16:00:00 12.72 12.6... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>Series.shift</code></a>:</p>
<pre><code>overnight_change = (df['Open'].shift(-1) - df['Close']) / df['Close']
df = df.assign(overnight_change=overnight_change)
print (df)
Dat... | python|pandas | 3 |
10,261 | 65,050,398 | Pandas read_csv failing on gzipped file with OSError: Not a gzipped file (b'NU') | <p>I used the code ask below to load the csv.gz file but I got the error</p>
<pre><code>OSError: Not a gzipped file (b'NU')
</code></pre>
<p>How can I solve it?
Code:</p>
<pre><code>import pandas as pd
data = pd.read_csv('climat.202010.csv.gz', compression='gzip')
print(data)
</code></pre>
<p>Or:</p>
<pre><code>import ... | <p>Try</p>
<pre><code>import gzip
with gzip.open(filename, 'rb') as fio:
df = pd.read_csv(fio)
</code></pre> | pandas|gzip | 0 |
10,262 | 39,933,633 | unorderable types: dict() <= int() in running OneVsRest Classifier | <p>I am running a multilabel classification on the input data with 330 features and about 800 records. I am leveraging RandomForestClassifier with following param_grid:</p>
<pre><code>> param_grid = {"n_estimators": [20],
> "max_depth": [6],
> "max_features": [80, 150],
> ... | <p>Why are you trying to initialize RandomForestClassifier with parameter grid?</p>
<p>If you want to do a Grid Search - look at examples here:
<a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV" rel="nofollow">http://scikit-learn.or... | python|scikit-learn|sklearn-pandas | 1 |
10,263 | 44,270,272 | Getting average of rows in dataframe greater than or equal to zero | <p>I would like to get the average value of a row in a dataframe where I only use values greater than or equal to zero.</p>
<p>For example:
if my dataframe looked like:</p>
<pre><code>df = pd.DataFrame([[3,4,5], [4,5,6],[4,-10,6]])
3 4 5
4 5 6
4 -10 6
</code></pre>
<p>currently if I get the ave... | <p>You can use <code>df[df > 0]</code> to query the data frame before calculating the average; <code>df[df > 0]</code> returns a data frame where cells smaller or equal to zero will be replaced with <code>NaN</code> and get ignored when calculating the <code>mean</code>:</p>
<pre><code>df[df > 0].mean(1)
#0 ... | python|pandas | 6 |
10,264 | 69,350,549 | Generator not working as expected in python | <p>I've been working on a genetic algorithm in PyTorch, and I've run into an issue while trying to mutate my model's parameters. I've been using the <code>.apply()</code> function to randomly change a model's weights and biases. Here is the exact function I made:</p>
<pre><code>def mutate(m):
if type(m) == nn.Linea... | <p>When <code>x</code> is a mutable object and you write <code>[x]*n</code> you are essentially creating a list of n references to the same object <code>x</code>.</p>
<p>What you want in your case is something like</p>
<pre><code>[nn.Linear(1,1) for _ in range(population_size)]
</code></pre> | python|python-3.x|pytorch | 0 |
10,265 | 69,468,001 | groupby max value of each year in initial pandas dataframe | <p>I have the following dataframe:</p>
<pre><code>date = ['2015-02-03 21:00:00','2015-02-03 22:30:00','2016-02-03 21:00:00','2016-02-03 22:00:00']
value_column = [33.24 , 500 , 34.39 , 34.49 ]
df = pd.DataFrame({'V1':value_column}, index=pd.to_datetime(date))
print(df.head())
... | <p>You can use <code>.transform("max")</code>:</p>
<pre class="lang-py prettyprint-override"><code>df["max V1"] = df["V1"].groupby(df.index.year).transform("max")
print(df)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code> V1 ... | pandas|pandas-groupby | 3 |
10,266 | 41,030,418 | python append error index 1 is out of bounds for axis 0 with size 1 | <p>I used sklearn LogisticRegression and want to see the param C because my model seems overfitting.So I do this:</p>
<pre><code>weightes,params = [],[]
for c in np.arange(-5,5):
lr = LogisticRegression(C=10**c,random_state=0,n_jobs=-1)
lr.fit(trainDataX,trainDataY)
weightes.append(lr.coef_[1])
params... | <p>The array stored in <code>lr.coef_</code> has only one element in it. The logistic regression model stores the fit intercept in <code>lr.intercept</code> and the coefficients of the predictor variables in <code>lr.coef</code>. You must have a model with a single predictor variable.</p> | python|pandas|machine-learning|scikit-learn | 1 |
10,267 | 53,925,776 | When is a random number generated in a Keras Lambda layer? | <p>I would like to apply simple data augmentation (multiplication of the input vector by a random scalar) to a fully connected neural network implemented in Keras. Keras has nice functionality for image augmentation, but trying to use this seemed awkward and slow for my input (1-tensors), whose training data set fits i... | <p>Using this will create a constant that will not change at all, because <code>random.uniform</code> is not a keras function. You defined this operation in the graph as <code>constant * tensor</code> and the factor will be constant.</p>
<p>You need random functions "from keras" or "from tensorflow". For instance, you... | tensorflow|lambda|keras | 6 |
10,268 | 54,040,574 | The correct way to build a binary classifier for CNN | <p>I created a neural network on pytorch using the pretraining model VGG16 and added my own extra layer to define belonging to one of two classes. For example bee or ant.</p>
<pre><code>model = models.vgg16(pretrained=True)
# Freeze early layers
for param in model.parameters():
param.requires_grad = False
n_inputs... | <p>It is indeed not surprising that a 2-class classifier fails with an image not belonging to any class.</p>
<p>To train your new one-class classifier, yes, use in our test set bees images and a set of non bee images. You need to accommodate for the imbalance between the classes as well to avoid overfitting just the b... | machine-learning|conv-neural-network|pytorch | 1 |
10,269 | 66,319,541 | What does indices!= index_to_remove mean? | <p>I’m supposed to write a helper function that returns a list with an element removed by the value, in an unchanged order. In this case, I don't have to remove any values multiple times.</p>
<p>This is the picture
<a href="https://i.stack.imgur.com/b0PrO.png" rel="nofollow noreferrer">image of the code</a></p>
<p>And ... | <p><code>indices!=index_to_remove</code> evaluates to an array of booleans, and we are using that boolean array to mask <code>indices</code>. See the numpy docs <a href="https://numpy.org/doc/stable/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow noreferrer">here</a></p> | python|numpy|generative-adversarial-network | 0 |
10,270 | 66,311,271 | Calculate the number of conenected pixels of a particular value in Numpy/OpenCV | <pre><code>def get_area(center_x: int, center_y: int, mask: np.ndarray) -> int:
if mask[center_x][center_y] != 255:
return -1
return ...
</code></pre>
<p>Now I got this function above that takes in a value for the x and y and finds the number of pixels that are connected to this pixel with the value ... | <pre><code>from PIL import Image
import numpy as np
from scipy import ndimage
imgMtx = [
[255,255, 0, 0, 0, 0, 0,255,255],
[255, 0, 0,255,255,255, 0, 0,255],
[ 0, 0,255, 0, 0, 0,255, 0, 0],
[ 0,255, 0, 0,255, 0, 0,255, 0],
[ 0,255, 0,255,255,255, 0,255, 0],
[ 0,255, ... | python-3.x|opencv|numpy-ndarray | 0 |
10,271 | 66,136,622 | Tensorflow Keras preprocessing layers | <p>At the moment i apply all preprocessing to the dataset.
But i saw that i can make the preprocessing as part of the model.
I read that the layer preprocessing is inactive at test time but what is about the rezizing layer?
For example:</p>
<pre><code>model = Sequential([
layers.experimental.preprocessing.Resizing(18... | <p>Only the preprocessing layers starting with <code>Random</code> are disabled at evaluation/test time.</p>
<p>In your case, the layers <code>Resizing</code> and <code>Rescaling</code> will be enabled in every case.</p>
<p>You can check in the source code whether or not the layer you are interested takes a <code>train... | tensorflow|keras | 1 |
10,272 | 66,325,301 | change color of bar for data selection in seaborn histogram (or plt) | <p>Let's say I have a dataframe like:</p>
<pre><code>X2 = np.random.normal(10, 3, 200)
X3 = np.random.normal(34, 2, 200)
a = pd.DataFrame({"X3": X3, "X2":X2})
</code></pre>
<p>and I am doing the following plotting routine:</p>
<pre><code>f, axes = plt.subplots(2, 2, gridspec_kw={"height_ratio... | <p>I think I found the solution for this using the inspiration from the previous answer and <a href="https://www.youtube.com/watch?v=mmjMQkUych8&ab_channel=Amulya%27sAcademy" rel="nofollow noreferrer">this</a> video:</p>
<pre><code>import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pand... | pandas|matplotlib|seaborn|distribution | 2 |
10,273 | 66,177,050 | Convertted tensorflow model to tflite outputs a int8 which I cannot dequantize | <p>I currently have quantized a tensorflow model using the following class script:</p>
<pre><code>class QuantModel():
def __init__(self, model=tf.keras.Model,data=[]):
'''
1. Accepts a keras model, long term will allow saved model and other formats
2. Accepts a numpy or tensor data of the format such that ... | <p>I think you can simply remove the <code>converter.inference_input_type = tf.int8</code> and <code>converter.inference_output_type = tf.int8</code> flags and treat the output model as a float model. Here is some detail:</p>
<p>The "optimization" flag in the Converter quantizes the float model to int8. By de... | tensorflow2.0|tensorflow-lite | 0 |
10,274 | 52,708,259 | DataFrame Multiobjective Sort to Define Pareto Boundary | <p>Are there any multiobjective sorting algorithms built into Pandas? </p>
<p>I have found <a href="https://github.com/matthewjwoodruff/pareto.py" rel="nofollow noreferrer">this</a> which is an NSGA-II algorithm (which is what I want), but it requires passing the objective functions in as separate files. In an ideal w... | <p>As it turns out... the <code>pareto</code> package referenced above <em>does</em> handle DataFrame inputs.</p>
<pre><code>import pareto
import pandas as pd
# load the data
df = pd.read_csv('data.csv')
# define the objective function column indices
# optional. default is ALL columns
of_cols = [4, 5]
# define the ... | python|pandas|sorting|optimization | 2 |
10,275 | 52,829,502 | sentences contain the exactly word in python | <p>I want to return the sentences that contain the exactly words in the searchfor list </p>
<pre><code>df = pd.read_excel('C:/Test 1012/UOI.xlsx')
a = df['Content']
searchfor =['hot' ,'yes' and 200 more words in it]
b = a[a.str.contains('|'.join(searchfor))]
print(b)
</code></pre>
<p>for example:</p>
<pre><code>... | <p>Use word boundary which are added for each value of <code>searchfor</code>:</p>
<pre><code>df = pd.DataFrame({'Content':['the photo is good','nice picture']})
print (df)
Content
0 the photo is good
1 nice picture
searchfor =['hot','yes','nice']
pat = '|'.join(r"\b{}\b".format(x) for x in search... | python|pandas|word | 1 |
10,276 | 52,490,951 | Keras Python script sometimes runs fine, sometimes fails with Matrix size-incompatible: In[0]: [10000,1], In[1]: [3,1] | <p>I want Keras to recognize selfies and non-selfies, first I am developing with only 4 pictures before using the full data.</p>
<p><strong>Problem</strong>: The script sometimes runs and exits normally, sometimes it fails with the error <code>Matrix size-incompatible: In[0]: [10000,1], In[1]: [3,1]</code> below:</p>
... | <p>The problem seems to be in the following line:</p>
<pre><code>image = tf.image.rgb_to_grayscale(image)
</code></pre>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/image/rgb_to_grayscale" rel="nofollow noreferrer"><code>tf.image.rgb_to_grayscale</code></a> expects the given image tensor to have a last d... | python|tensorflow|keras|classification | 2 |
10,277 | 52,504,732 | GPU memory not released tensorflow | <p>I have the issue that my GPU memory is not released after closing a tensorflow session in Python. These three line suffice to cause the problem:</p>
<pre><code>import tensorflow as tf
sess=tf.Session()
sess.close()
</code></pre>
<p>After the third line the memory is not released. I have been up and down many for... | <p>Refer to <a href="https://github.com/tensorflow/tensorflow/issues/17048#issuecomment-367948448" rel="nofollow noreferrer">this</a> discussion. You can reuse your allocated memory but if you want to free the memory, then you would have to exit the Python interpreter itself.</p> | tensorflow|memory-leaks | 1 |
10,278 | 52,796,947 | Tensorflow: Matrix size-incompatible error on Tensors | <p>I am attempting to do binary classification on a univariate numerical dataset with Tensorflow. My dataset contains 6 features/variables including the label with about 90 instances. Here is a preview of my data:</p>
<pre><code>sex,age,Time,Number_of_Warts,Type,Area,Result_of_Treatment
1,35,12,5,1,100,0
1,29,7,5,1,96... | <p>I think it should be</p>
<pre><code>model.add(layers.Dense(16, activation='relu', input_shape=(6,)))
</code></pre>
<p>You should refer to the columns and not the rows</p> | python|tensorflow|machine-learning|tensorflow-datasets|supervised-learning | 6 |
10,279 | 46,497,057 | Pandas Conditional Drop | <p>I'm trying to conditionally drop rows out of a pandas dataframe, using syntax as such:</p>
<pre><code>if ((df['Column_1'] == 'value_1') & (df['Column_2'] == 'value_2')):
df['Columns_3'] == df['Column_4']
else:
df.drop()
</code></pre>
<p>Thanks in advance for the help. </p> | <p>Try something like</p>
<pre><code>df = df.drop(df[(df['Column1'] != 'value_1') & (df['Colum2'] != 'value_2')].index)
df['Column3'] = df['Column4']
</code></pre> | python|pandas|if-statement|dataframe|conditional-statements | 1 |
10,280 | 69,120,908 | Convert Duplicate Entries into Dictionaries: Python | <p>I have a database of about 300 computers and I am trying to figure out which computers do and do not have a particular software.</p>
<p>The issue is: this database lists each piece of software individually, with the duplicated computer name on each one.</p>
<p>Example:</p>
<div class="s-table-container">
<table clas... | <p>You can use <code>.groupby</code>, <code>.filter</code> out the groups that have "Microsoft Edge" and then use <code>.unique</code> to print the computer names. For example:</p>
<pre class="lang-py prettyprint-override"><code>x = df.groupby("Computer Name").filter(
lambda x: "Microsoft E... | python|pandas|list|dataframe|dictionary | 1 |
10,281 | 69,224,533 | Unable to impute missing numerical values | <p>I want to impute missing values for both numerical and nominal values. My code for the finding missing numerical values did not return anything even though one of the columns <code>HDI for year</code> actually has null values. What is wrong with my code?</p>
<pre><code>import numpy as np
import pandas as pd
import s... | <p>As stated in the comments, there's no point in using a <code>for loop</code> and iterate through your columns. You can just impute your numeric columns and your categorical columns separately, using <code>select_dtypes</code>:</p>
<p>Assumed <code>DF</code>:</p>
<pre><code>>>> df
year sex age incom... | python|pandas|missing-data|imputation | 0 |
10,282 | 44,791,173 | Pandas: Resample grouped dataframe column, get discrete feature that corresponds to max value | <p>This is similar to a previous question I've asked but sufficiently different as the solution doesn't work when the data is grouped:</p>
<p>Given some data:</p>
<pre><code>import pandas as pd
import numpy as np
import datetime
data = {'group':['a', 'a', 'a','b','a', 'b'],
'value': [1,2,3,4,3,5], 'names': ... | <p>You can use <code>apply</code> after grouping to sort the value, names columns by value and then take the first row.</p>
<pre><code>g = df.groupby(['group', pd.Grouper(freq='2D')])[['value', 'names']]
g.apply(lambda x: x.sort_values(['value', 'names'], ascending=[False, True]).iloc[0])\
.reset_index('group')
... | python|pandas|group-by|max|resampling | 1 |
10,283 | 44,638,406 | Error while using plt.text() in scatter plot | <p>I have a dataframe like this:</p>
<pre><code> batsman balls runs strike_rate 6's 4's Team Highest_score
A Ashish Reddy 196 280 142.857143 16 15 DC 10
A Ashish Reddy 196 280 142.857143 16 15 SRH 36
A Chandila 7 4 57.... | <p>You don't appear to be using <code>mlt.text()</code> correctly. See the Matplotlib documentation <a href="https://matplotlib.org/1.5.3/api/text_api.html?highlight=text#module-matplotlib.text" rel="nofollow noreferrer">here</a>. I believe the <code>text()</code> function can only be applied at a single point. I think... | python|pandas|matplotlib | 0 |
10,284 | 60,819,581 | Pandas split list inside a column into separate columns | <p>I have a dataset with 71 columns and 113 rows. Each column is a array of values. I want to split these arrays into separate columns. Then rename the columns with the prefix </p>
<pre><code>!wget https://raw.githubusercontent.com/pranavn91/sample/master/audioonly.csv
audio = pd.read_csv("audioonly.csv")
zcr = pd.Dat... | <p>you can use <code>concat</code> and a list comprehension:</p>
<pre><code>audio_exploded = pd.concat([pd.DataFrame(audio[col].str.split().values.tolist())\
.add_prefix(f'{col}_')
for col in audio.columns],
axis=1)
</code></pre> | pandas | 1 |
10,285 | 60,932,166 | How to configure a tf.data.Dataset for variable size images? | <p>I'm setting up a image data pipeline on Tensorflow 2.1. I'm using a dataset with RGB images of variable shapes (h, w, 3) and I can't find a way to make it work. I get the following error when I call <code>tf.data.Dataset.batch()</code> :</p>
<p><code>tensorflow.python.framework.errors_impl.InvalidArgumentError: Can... | <p>I just hit the same problem. The solution turned out to be loading the data as 2 datasets and then using dataet.zip() to merge them.</p>
<pre><code>images = dataset.map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)
images = dataset_images.apply(
tf.data.experimental.dense_to_ragged_batch(batch... | python|tensorflow|tensorflow2.0|tensorflow2.x | 1 |
10,286 | 60,946,532 | Logarithmic x-axis with custom xticks with pandas dataframe | <p>Using the plot functionality in pandas dataframe I try to get a proper logarithmic x-axis: sample code:</p>
<pre><code>import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
df = pd.DataFrame({'Freq':[63,125,250,500],'A':[1,2,3,4]})
ax.set_xscale('log')
ax.set_xticks(df['Fre... | <p>Try using the <code>logx</code> in the Pandas plotting interface directly. </p>
<pre><code>import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
df = pd.DataFrame({'Freq':[63,125,250,500],'A':[1,2,3,4]})
df.set_index('Freq').plot(ax=ax, logx=True)```
</code></pre> | python|pandas|plot | 0 |
10,287 | 71,580,518 | Convert String into 1d numpy float array from csv | <p>I have a csv file looking like this:</p>
<pre><code>COL0;COl1;COL2;COL3;...;COL9999
SomeText0;[-3.45,0.23];[-1.40,0.21];[-1.35,0.13];...;[-1.87,0.12]
SomeText1;[-3.05,0.20];[-0.40,0.01];[-0.05,0.03];...;[-1.65,0.33]
SomeText2;[-0.40,0.03];[-1.00,0.20];[-0.35,0.03];...;[-1.43,0.12]
...
</code></pre>
<p>All cells are ... | <p>Just read the CSV normally and then use the built-in function <code>ast.literal_eval</code> to parse the strings into arrays of floats:</p>
<pre><code>import ast
df = pd.read_csv('YOUR FILE.csv', sep=';')
df.loc[:, 'COl1':] = df.loc[:, 'COl1':].apply(lambda col: col.apply(ast.literal_eval).apply(np.asarray))
</code>... | python|pandas|numpy | 1 |
10,288 | 42,339,373 | Pandas with Matplotlib switch axis | <p>(Using python 3.5)
I have pandas dataframe tables with colums:</p>
<pre><code>Price| Quantity|Price| Quantity|Price|...
2 | 1 |4 | 5 | 13 |...
</code></pre>
<p>Not when I Plot this</p>
<pre><code>import matplotlib.pyplot as plt
plt.plot(my_table, their_table)
plt.show()
</code></pre>
<p>It put... | <p>You can use <code>lreshape</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html" rel="nofollow noreferrer"><code>Series.plot</code></a>:</p>
<pre><code>print (df)
Price Quantity Price Quantity Price Quantity
0 2 1 4 5 13 10
1... | pandas|matplotlib | 1 |
10,289 | 42,265,950 | how to feed DNNClassifier with numpy arrays | <p>I'm trying to create a DNNClassifier but i don't know how to pass my data into the object.My data files are .npy files created with np.save().</p>
<ul>
<li>Training data: an array of shape (106398,338) where 106398 is the number of instances of data.</li>
<li>Training labels: an array of shape (106398,97) where 97 ... | <p>If look at other SO questions about that <code>ValueError..</code> you'll that this arises when you try to do some sort True/False test on an array. </p>
<pre><code>if X>0:....
</code></pre>
<p>produces this error if <code>X</code> is a multielement array. <code>X>0</code> is then an array of True/False va... | python|numpy|tensorflow | 1 |
10,290 | 43,045,483 | Numpy 3d array to 2d array by outermost index | <p>I have an array of 2d arrays like</p>
<pre><code>+------+ +------+
| | | |
| A | | B |
| | | |
+------+ +------+
</code></pre>
<p>and I want to "delete" the outermost parentheses, as in to get</p>
<pre><code>+------+------+
| | |
| A | B |
| | |
+... | <p>One approach with swapping of axes between first and second ones and then reshape to merge the last two axes -</p>
<pre><code>arr.swapaxes(0,1).reshape(arr.shape[1],-1)
</code></pre>
<p>Sample run -</p>
<pre><code>In [9]: arr = np.array([[[1,1,1],[2,2,2]],[[3,3,3],[4,4,4]]])
In [10]: arr.swapaxes(0,1).reshape(ar... | python|arrays|numpy | 2 |
10,291 | 43,397,160 | python, find waiting time until next occurrence for continuous value time series | <p>Given a pandas time series (or numpy array or a simple python list, if easier), I want, for each point in the series, find the waiting time until next time the series is at this level. So if day T is 0 and day T+1 is positive, I want to find the number of days to wait until the series is 0 or below. If day T+1 is ne... | <p>Here is an approach using two stacks. It's unfortunately very hard to vectorise. Nonetheless, in my 10,000 sample test it runs several 100-fold faster than the original loop:</p>
<pre><code>import numpy as np
freqs = np.random.randn(20)/10
N = 10**4
data = np.sin(np.arange(N)[:, None] * freqs).sum(axis=-1)
test =... | python|pandas|numpy | 1 |
10,292 | 72,444,605 | How can I get a selection of one data frame for each row in another data frame based on conditions in that row? | <p>I have the following 2 dataframes:</p>
<pre><code>df1
x p s
0 2 1 1
1 4 2 1
2 6 1 3
3 8 2 4
df2
ts 1 2
0 1000 45 44
1 1001 46 46
2 1002 47 46
3 1003 48 48
4 1004 49 48
5 1005 50 50
6 1006 51 50
7 1007 52 52
8 1008 53 52
</code></pre>
<p>I would like to create a 3... | <p>I'm not sure how large the datasets are, but try the following</p>
<pre class="lang-py prettyprint-override"><code># We need to do "CROSS JOIN" so we add a dummy key to both datasets to allow this
df1["temp_key"] = 0
df2["temp_key"] = 0
# Next we need to shift the index into the DataFr... | python|pandas|dataframe | 0 |
10,293 | 72,212,596 | Pandas apply function with additional arguments | <p>I'm trying to use a function "multiply" to create a new column in a dataframe, and I'm using the apply() method to do it. the code currently looks like this:</p>
<pre><code>import pandas as pd
var_a = 10
var_b = 20
def multiply(row):
if 0.1 in row['Alpha 1']:
result = row['Alpha 2'] * var_a
... | <p>You can use a lambda function or use <code>args</code> argument</p>
<pre class="lang-py prettyprint-override"><code>pdf['Calc'] = pdf.apply(lambda row: multiply(row, var_a, var_b), axis = 1)
# or
pdf['Calc'] = pdf.apply(multiply, axis = 1, args=(var_a, var_b))
</code></pre> | python|pandas|dataframe | 0 |
10,294 | 72,390,538 | How to change the color of a dataframe header with python pandas | <p>I'm using this function to change the color of a specific cells:</p>
<pre><code>def cell_colours(series):
red = 'background-color: red;'
yellow = 'background-color: yellow;'
green = 'background-color: green;'
default = ''
return [red if data == "failed" else yellow if data == "error" else g... | <p>You can use <code>.col_heading</code> selector</p>
<pre class="lang-py prettyprint-override"><code>headers = {
'selector': 'th.col_heading',
'props': 'background-color: #000066; color: white;'
}
s = df.style.set_table_styles([headers])\
.apply(cell_colours)
s.to_html('output.html')
</code></pre>
... | python|pandas|dataframe|colors|background-color | 1 |
10,295 | 50,257,430 | Why does the shape of an element and logical indexed array seem to transpose dimensions? | <p>Let's say we have a multi-dimensional array.</p>
<pre><code>import numpy as np
foo = np.random.random((2,4,3,5))
</code></pre>
<p>Each axis is relevant for a specific feature of the data and I'm interested in a subset of the data.</p>
<p>I can use a logical index on axis 2 and an element index on axis 0 and 3.</p... | <p>I think this is how it's working.
When you have slices and array indexes, it broadcasts it as you said and also the <a href="https://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html" rel="nofollow noreferrer">documentation</a> . Now the first and last dimensions are also indexing, so numpy is not broadcasti... | python|numpy|array-broadcasting | 0 |
10,296 | 50,256,984 | Changing 2-dimensional list to standard matrix form | <pre><code>org = [['A', 'a', 1],
['A', 'b', 2],
['A', 'c', 3],
['B', 'a', 4],
['B', 'b', 5],
['B', 'c', 6],
['C', 'a', 7],
['C', 'b', 8],
['C', 'c', 9]]
</code></pre>
<p>I want to change the 'org' to the standard matrix form like below.</p>
<pre><code>transform ... | <p>Here's another "manual" way using only <code>numpy</code>:</p>
<pre><code>org_arr = np.array(org)
key1 = np.unique(org_arr[:,0])
key2 = np.unique(org_arr[:,1])
values = org_arr[:,2].reshape((len(key1),len(key2))).transpose()
np.block([
["\t", key1 ],
[key2[:,None], values]
])
""" # alternatively,... | python|arrays|python-3.x|numpy|matrix | 1 |
10,297 | 50,440,807 | pandas advanced splitting by comma | <p>There have been a lot of posts concerning splitting a single column into multiples, but I couldn't find an answer to a slight modification to the idea of splitting. </p>
<p>When you use str.split, it splits the string independent of order. You can modify it to be slightly more complex, such as ordering it by sortin... | <p>Using <code>get_dummies</code></p>
<pre><code>s=df.row.str.get_dummies(sep=' ,')
s.mul(s.columns)
Out[239]:
a b c d e f
0 a b c e
1 a b d
2 a b c d e
3 d f
</code></pre> | python-3.x|pandas|split | 1 |
10,298 | 45,432,370 | do I have to reinstall tensorflow after changing gpu? | <p>I'm using tensorflow with gpu. My computer have NVIDIA gforce 750 ti and I'm gonna replace it with 1080 ti. do I have to re install tensorflow(or other drivers etc.)? If it is true, what exactly do I have to re-install? </p>
<p>One more question, Can I speed up the training process by install one more gpu in the c... | <p>As far as I know the only thing you need to reinstall are the GPU drivers (CUDA an/or cuDNN). If you install the exact same version with the exact same bindings Tensorflow should not notice you changed the GPU and continue working...</p>
<p>And yes, you can speed up the training process with multiple GPUs, but tell... | tensorflow|cuda|gpu|cudnn | 3 |
10,299 | 73,712,894 | How can I copy values from one dataframe column to another based on the difference between the values | <p>I have two csv mirror files generated by two different servers. Both files have the same number of lines and should have the exact same unix timestamp column. However, due to some clock issues, some records in one file, might have asmall difference of a nanosecond than it's counterpart record in the other csv file... | <p>If you're sure that the timestamps should be identical, why don't you simply use the timestamp column from dataframe A and overwrite the timestamp column in dataframe B with it?</p>
<p>Why even check whether the difference is there or not?</p> | python|pandas|csv|dask | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.