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 |
|---|---|---|---|---|---|---|
353,200 | 62,763,104 | Problems in installing Numpy in Pycharm | <p>I don't know for what reasons I am getting this error while installing Numpy in Pycharm. Although I have already installed Numpy in my system which is Windows based with the help of command prompt. But still I am still getting this error and also I have latest version of Pycharm.</p>
<p>RuntimeError: Broken toolchai... | <p>To properly install Numpy in Pycharm, you have to go to <strong>File/Settings/Project Interpreter</strong> click on add and search for numpy in the search bar.</p>
<p>Click on install package, it should run and install with no problem</p> | python|python-3.x|numpy|installation|pycharm | 0 |
353,201 | 62,797,505 | change gaps in numpy array according to gap size | <p>I need to filter out short nonzero series, that lies between zeros. For example, this array:</p>
<pre><code>t = np.array([1, 3, 1, 0, 0, 1, 8, 3, 0, 8, 2, 4, 7, 0,0,4,1])
</code></pre>
<p>should become:</p>
<pre><code>array([1, 3, 1, 0, 0, 0, 0, 0, 0, 8, 2, 4, 7, 0, 0, 4, 1])
</code></pre>
<p>I found the first indic... | <p>You can use image-processing based <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.binary_closing.html" rel="nofollow noreferrer"><code>binary_closing</code></a> -</p>
<pre><code>from scipy.ndimage.morphology import binary_closing
def remove_small_nnz(a, W):
K = np.ones(W, dtype=int)... | python|numpy|conditional-statements|sequence | 2 |
353,202 | 62,783,083 | Can't find a way to go through csv to check URL-Status in Python | <p>I am working on a Python-script that goes through a CSV and does two checks:</p>
<ol>
<li>Is there one or more URLs in this text?</li>
<li>What is the returned status-code when making a request via requests.get</li>
</ol>
<p>The CSV has 2 columns</p>
<pre><code>richAnswer,kbid
"<p>This answer has one URL ... | <p>Here's a solution that has each URL on its own row and retains the corresponding ID. Some suggestions:</p>
<ul>
<li>Use an XML/HTML parser to parse the markup column (<code>richAnswer</code>)</li>
<li>Use xpath for find the link URLs in the HTML <code>a</code> tags. Sometimes they have relative links, so they won't ... | python|pandas|python-requests | 1 |
353,203 | 62,601,489 | Create a new column with frequency-based categories in pandas | <p>I would need to create a new column as follows:</p>
<ul>
<li>if the frequency of an item is greater or equal than 5 then set 'best seller';</li>
<li>if the frequency of an item is between 2 (inclusive) and 5 then set 'ok';</li>
<li>if the frequency of an item is lower than 2 then set 'bad'.</li>
</ul>
<p>Suppose th... | <p>The code below should work.</p>
<pre><code>df['category'] = pd.cut(df['sold_items'],bins = [0,1,4,df['sold_items'].max()],labels = ['bad','ok','best seller'])
</code></pre> | python|pandas|dataframe | 3 |
353,204 | 62,542,601 | SettingwithCopyWarning: How to Fix This | <p>I have a column with strings and I'm trying to find number of tokens in it and then creating a new column in the same dataframe with those values.</p>
<pre><code> data['tokens'] = data['query'].str.split().apply(len)
</code></pre>
<p>I get <code>SettingWithCopyWarning</code>. I'm not sure how to fix this. I understa... | <p>a <code>SettingWithCopyWarning</code> happens when you have made a <strong>copy</strong> of a slice of a DataFrame, but pandas thinks you might be trying to modify the underlying object.</p>
<p>To fix it, you need to understand the difference between a <strong>copy</strong> and a <strong>view</strong>. A <strong>cop... | python|pandas|numpy|dataframe | 1 |
353,205 | 54,369,823 | Running selected TensorFlow test with bazel | <p>I'd like to run selected tests from Tensor Flow unit tests using bazel, but I cannot get good enough granularity.</p>
<p>For example I am interested in running test <code>SessionClusterSpecPropagationTest.testFullDeviceNames</code> from <code>//tensorflow/tools/graph_transforms:transform_graph_py_test</code></p>
<... | <p>You can refer <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/test_util.py" rel="nofollow noreferrer">this</a> for Tensorflow test cases. This are the <a href="https://www.tensorflow.org/community/contribute/tests" rel="nofollow noreferrer">best practises</a>. You should try... | tensorflow|googletest|bazel | 0 |
353,206 | 54,375,979 | Multi-index slicing (involving a time series / date range) does not work with DataFrame but does for Series | <p>Slicing a multi-index DataFrame for a date range does not appear to work (dataframe is returned un-sliced), while performing the same operation for a multi-indexed Series does. </p>
<p>For example:</p>
<pre><code># Create a multi-indexed DataFrame with time series as 'inner' index
idx = pd.MultiIndex.from_product(... | <p>You need specify column <code>colA</code> in second position in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p>
<pre><code>print(example_df.loc[idx[:, '2019-01-3':], 'colA'])
id date
id1 2019-01-03 1.... | python|pandas | 4 |
353,207 | 54,633,643 | Update a dataframe's columns, if the value is between the intervals of another dataframe's column | <p>My first dataframe(df1) looks like this: </p>
<pre><code>Un s spread_bin gamma_star exp_star gamma_zero interval
0 0 0.000000 NaN NaN NaN NaN [0.0, 2.828e-05)
1 1 0.000110 A 1.5466 -1.210453e-07 1.5466 [8.485e-05, 0.0001131)
2 2 0.000308 A 1.5466 -1.007298e... | <p>I'm sure there's a nicer way to do this, but a fast way is doing:</p>
<pre><code>def in_interval(value, lower, upper):
if lower <= value <= upper:
return True
else:
return False
df2['gamma'] = 0
for i, s in enumerate(df2['s']):
for j, interval in enumerate(df1['interval']):
... | python|pandas|dataframe | 1 |
353,208 | 54,261,360 | Retrieve the rows of data-frames with NAN values and not NAN values | <p>I have a data frame df:</p>
<pre><code> DT RE FE SE C_Step
0 D1 E1 F1 S1 poor
1 D2 E3 F2 NaN NaN
2 D1 E3 NaN S2 good
3 D1 NaN F1 S1 poor
4 D2 NaN F1 S2 poor
5 D2 E3 NaN S1 fair
6 D1 E3 F1 S2 fair
7 D2 E2 F1 S1 NaN
</code></pre>
<p>I want to... | <p>Using dropna</p>
<pre><code>df1 = df.dropna(subset = ['DT','RE','FE','SE'])
df2 = df.loc[~df.index.isin(df.dropna(subset = ['DT','RE','FE','SE']).index)]
df1
DT RE FE SE C_Step
0 D1 E1 F1 S1 poor
6 D1 E3 F1 S2 fair
7 D2 E2 F1 S1 NaN
df2
DT RE FE SE C_Step
1 D2 E3 F2 NaN N... | python-3.x|pandas|dataframe | 2 |
353,209 | 54,285,619 | Running Tensorflow in OSX | <p>I wrote simple MNIST tensorflow code...</p>
<p>Code executes very well when I run the code with PyCharm.<br>
But actually, I wanted to run this script in terminal using <code>python ./mnist.py</code> command, so when I run the code in terminal, I get the following error. </p>
<pre><code>dyld: warning, LC_RPATH $O... | <p>I solved my problem. Error and warning was independent.<br>
Mac OS can run tensorflow in terminal whether the warning occurs or not.<br>
The main problem was python couldn't recognize google.protobuf module even if it was installed... </p>
<ul>
<li><p>First check protobuf module and google module was already insta... | python|tensorflow|importerror|macos-mojave | 0 |
353,210 | 54,459,554 | numpy: find index in sorted array (in an efficient way) | <p>I would like to sort a numpy array and find out where each element went.</p>
<p><a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.argsort.html#numpy.argsort" rel="nofollow noreferrer"><code>numpy.argsort</code></a> will tell me for each index in the sorted array, which index in the unsorted... | <p>You can just use <code>argsort</code> twice on the list.
At first the fact that this works seems a bit confusing, but if you think about it for a while it starts to make sense.</p>
<pre><code>a = np.array([1, 4, 2, 3])
argSorted = np.argsort(a) # [0, 2, 3, 1]
invArgSorted = np.argsort(argSorted) # [0, 3, 1, 2]
</co... | python|arrays|numpy | 3 |
353,211 | 54,413,726 | Training Estimators less than one epoch using dataset API? | <p>I am trying to train a model on a large dataset. I would like to run the evaluation step multiple times before one epoch of training has been completed. Looking at the implementation of Dataset API with Estimators it looks like every time I restart the training after the evaluation step, Estimator creates a fresh da... | <p>If you want to evaluate multiple times during training, you can check <a href="https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/contrib/estimator/InMemoryEvaluatorHook" rel="nofollow noreferrer">InMemoryEvaluatorHook</a>.</p>
<p>You can probably refer <a href="https://github.com/tensorflow/tensorflow/iss... | tensorflow | 0 |
353,212 | 54,575,992 | Matrix inversion in python: bottom diagonal always wrong | <p>I am writing a program that inverts an n*n dimensional square matrix without explicit dependence on the numpy.linalg.inv function, however the bottom left triangular matrix is always incorrect, whereas the rest of the matrix elements are always correct. I have combed through the code multiple times but I can't figur... | <p>Just realised the main issue with the code. In the transposition function I call tempmat = mat which raises errors as it should be tempmat = np.array(mat)</p> | python|numpy|matrix|inversion | 0 |
353,213 | 54,657,646 | Collapsing columns with the same name contains different data | <p>I have difficulties with dataframe of such structure:</p>
<pre><code>| Depart | Employee | Employee_card | 1 | 2 | 1 | 2 |
|:------:|:--------:|:-------------:|:--:|:--:|:--:|:--:|
| Dep_1 | Emp_1 | 101 | 97 | 16 | 38 | 86 |
| Dep_2 | Emp_2 | 102 | 7 | 10 | 3 | 58 |
| Dep_2 | Emp... | <p>No sure about performance, but you may try something like getting the unique column names and then selecting:</p>
<pre><code>_, i = np.unique(df.columns, return_index=True)
df_with_unique_cols = df.iloc[:,i]
</code></pre> | python|pandas|dataframe|multi-index | 0 |
353,214 | 54,628,504 | Adding a new column in my existing dataframe in pandas | <p>Original Dataframe is</p>
<pre><code>column_one
1
1
1
45
45
55
55
56
Expected Output
column-new
i_1
i_1
i_1
i_2
i_2
i_3
i_3
i_4
</code></pre>
<p>Based on Column-1 I want to add another new column in my dataframe.
Where there is a consecutive values than add 'i' with the same index. Thank you in advance.</p> | <p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.factorize.html" rel="nofollow noreferrer"><code>pd.factorize</code></a>. From the docs:</p>
<blockquote>
<p>Useful for obtaining a numeric representation of an array when all that matters is identifying distinct values.</p>
<... | python|pandas | 2 |
353,215 | 54,526,828 | How to delete the second consecutive/occurrence of duplicate rows from pandas dataframe with condition by python? | <p>My dataframe looks like as follows</p>
<pre><code>import pandas as pd
uid=[1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3]
pid=[1,1,1,2,2,1,1,7,7,8,7,7,7,6,6,7,6,1,5,1,1,2,2,2,1]
sid=[1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,4,4,4,5,5,5,5,5]
df=pd.DataFrame({'uid':uid, 'pid':pid,'sid':sid})
print(df)
uid pid ... | <p>You are almost there. This can be achieved using <code>groupby</code> function and keeping only the top 2 rows.</p>
<p><strong>Code:</strong></p>
<pre><code>df.groupby(['pid', 'sid']).head(2)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code> uid pid sid
0 1 1 1
1 1 1 1
2 1 2 1
3 1 ... | python-3.x|pandas|pandas-groupby | 2 |
353,216 | 54,255,415 | How to count nulls in a group rowwise in pandas DataFrame | <p>According to this topic <code>https://stackoverflow.com/questions/19384532/how-to-count-number-of-rows-per-group-and-other-statistics-in-pandas-group-by</code> I'd like to add one more stat - count null values (a.k.a. NaN) in DataFrame:</p>
<pre><code>tdf = pd.DataFrame(columns = ['indicator', 'v1', 'v2', 'v3', 'v4... | <p>First <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> and check all missing values with count by <code>sum</code> and then aggregate <code>count</code> with <code>sum</code>:</p>
<pre><code>df = tdf.set_index('indic... | pandas | 1 |
353,217 | 54,405,063 | Why can't I apply sort_values to a dataframe more than once? | <p>Say for example I have a multi-column dataframe. I want to arrange my data by sorting column <code>a</code> ascending first, then by column <code>b</code> ascending also.</p>
<p>I am able to achieve this by the ff. code: <code>df.sort_values(['b','a'])</code>. Note the reversed order of the arguments.</p>
<p>My qu... | <p>When you use <code>.sort_values(['a', 'b'])</code> you are first sorting the dataframe by the column <code>a</code>, and then <em>within</em> those sortings, sorting by <code>b</code>. Think of it almost as grouping by the first sort, then sorting <em>within</em> those groupings. If there was a <code>c</code>, it wo... | python|pandas|data-analysis | 2 |
353,218 | 54,394,020 | Numpy select matrix specified by a matrix of indices, from multidimensional array | <p>I have a numpy array <code>a</code> of size <code>5x5x4x5x5</code>. I have another matrix <code>b</code> of size <code>5x5</code>. I want to get <code>a[i,j,b[i,j]]</code> for <code>i</code> from 0 to 4 and for <code>j</code> from 0 to 4. This will give me a <code>5x5x1x5x5</code> matrix. Is there any way to do this... | <p>Let's think of the matrix <code>a</code> as 100 <code>(= 5 x 5 x 4)</code> matrices of size <code>(5, 5)</code>. So, if you could get a liner index for each triplet - <code>(i, j, b[i, j])</code> - you are done. That's where <code>np.ravel_multi_index</code> comes in. Following is the code.</p>
<pre><code>import nu... | python|arrays|numpy|indexing | 1 |
353,219 | 54,352,195 | Set dataframe values based on both row-dependent and column-dependent conditions | <h2>Situation</h2>
<p>Consider a dataframe <code>df</code> that contains the following columns:</p>
<ul>
<li>One column named <code>amount</code>. All values in this column are either a whole number > 0, or NaN.</li>
<li>Multiple columns named <code>property_1</code>, <code>property_2</code>, <code>property_3</code>,... | <p>You can construct Boolean masks for your first condition using <code>np.subtract.outer</code>. The second null condition is handled via <code>fillna(0)</code> since all positive integers are greater than 0.</p>
<pre><code># extract integers from columns
ints = df.columns[1:].str.rsplit('_', n=1).str[-1].astype(int)... | python|pandas|dataframe | 2 |
353,220 | 54,452,974 | ValueError: The shape invariant specified for ones_1:0 is not compatible with the initial shape of the loop variable | <pre><code>import tensorflow as tf
import numpy as np
x = np.array([1.0, 1.0, 1.0])
z = tf.ones((1, 3))
out = tf.ones((1, 3))
print('out:', out)
i = tf.constant(0)
def cond(i, _):
return i < 10
def body(i, out):
i = i + 1
out = tf.concat([out, out], axis=0)
return [i, out]
_, out = tf.while_loo... | <p>You should change to follow code.</p>
<pre><code>_, out = tf.while_loop(cond, body, [i, out], shape_invariants=[i.get_shape(), tf.TensorShape([None,3])])
</code></pre>
<p><strong>Edit</strong></p>
<p>The above code is used to solve the error. If you want to output (10,3), you should modify <code>body()</code>.</p... | tensorflow | 0 |
353,221 | 54,351,051 | Cyrillic symbols decode in numpy array | <p>I need to get pieplot with labels in Cyrillic symbols, that is in df.index</p>
<pre><code>plt.pie(df['reg_created'], labels = df.index)
</code></pre>
<p>So, it's return error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)
</code></pre>
<p>df.inde... | <p>You got your answer in the error message, the charters are decoded as ASCII and not as UTF-8</p>
<p><a href="https://stackoverflow.com/a/10406161">https://stackoverflow.com/a/10406161</a></p>
<p><a href="https://stackoverflow.com/a/36454865">https://stackoverflow.com/a/36454865</a></p> | python|numpy | 1 |
353,222 | 54,555,540 | Save histogram during evaluation with estimator api | <p>Is it possible to save a histogram during evaluation using the estimator API?</p>
<p>I couldn't find a solution since the estimator api does not write down any summaries during evaluation and I can only add scalars to the evaluates metrics.</p> | <p>For the sake of those who came here and haven't found a solution, I will update that I used the above approach, with a slight modification:</p>
<pre><code> summary_writer = tf.compat.v1.summary.FileWriter(
logdir=self.model_dir + '/eval_histograms/',
filename_suffix='.host_call')
summary_ops =... | tensorflow|histogram|tensorboard | 1 |
353,223 | 54,431,557 | xarray - Use groupby to group by every day over a year's climatological hourly netCDF data | <p>I have a hourly netCDF climatological data for a geographic extent over a year, e.g. from <code>2017-01-01T00:00:00</code> to <code>2017-12-31T23:00:00</code>.</p>
<pre><code><xarray.Dataset>
Dimensions: (latitude: 106, longitude: 193, time: 8760)
Coordinates:
* latitude (latitude) float32 -39.2 -39.14... | <p>You should use the <a href="http://xarray.pydata.org/en/stable/generated/xarray.Dataset.resample.html#xarray.Dataset.resample" rel="noreferrer"><code>resample</code></a> method instead of <a href="http://xarray.pydata.org/en/stable/generated/xarray.Dataset.groupby.html#xarray.Dataset.groupby" rel="noreferrer"><code>... | python|pandas|netcdf|python-xarray | 5 |
353,224 | 54,252,106 | While resampling, put NaN in the resulting value if there are some NaN values in the source interval | <p>Example:</p>
<pre><code>import pandas as pd
import numpy as np
rng = pd.date_range("2000-01-01", periods=12, freq="T")
ts = pd.Series(np.arange(12), index=rng)
ts["2000-01-01 00:02"] = np.nan
ts
</code></pre>
<pre><code>2000-01-01 00:00:00 0.0
2000-01-01 00:01:00 1.0
2000-01-01 00:02:00 NaN
2000-01-01... | <p>For one or more <code>NaN</code> values:</p>
<pre><code>ts.resample('5min').agg(pd.Series.sum, skipna=False)
</code></pre>
<p>For a <em>minimum</em> of 2 non-<code>NaN</code> values:</p>
<pre><code>ts.resample('5min').agg(pd.Series.sum, min_count=2)
</code></pre>
<p>For a <em>maximum</em> of 2 <code>NaN</code> v... | python|pandas|series | 12 |
353,225 | 54,655,811 | get 50 state abbreviations | <p>I'm trying to get the 50 state abbreviations in one column with a usable column name using html5lib.</p>
<pre><code>import pandas as pd
import html5lib
fiddy_states = pd.read_html('https://en.wikipedia.org/wiki/List_of_U.S._state_abbreviations')
fs = fiddy_states[0]
</code></pre>
<p>Here I can't change the column... | <p>the list of states isn't likely to change any time soon, you might be better served just putting them in an array manually:</p>
<p>states = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO... | python|python-3.x|pandas | 5 |
353,226 | 54,498,373 | Combine odd and even indexed rows in pandas | <p>I have a data frame <code>df</code> like this,</p>
<pre><code> Name Net Quantity
0 Auto 1010 10
1 NaN NaN 12
2 Rtal 4145 18
3 NaN NaN 14
4 Indl 6223 16
5 NaN 7222 18
</code></pre>
<p>My output data frame should be like this,</p>
... | <p>If you're okay with floats in 'Net', you can use <code>groupby</code> and <code>agg</code>:</p>
<pre><code>df.groupby(df.index // 2).agg(lambda x: x.dropna().astype(str).str.cat(sep=','))
Name Net Quantity
0 Auto 1010.0 10,12
1 Rtal 4145.0 18,14
2 Indl 6223.0,7222.0 16,18... | python|python-3.x|pandas|dataframe|pandas-groupby | 3 |
353,227 | 54,385,568 | Tensorflow DQN can't solve OpenAI Cartpole | <p>I've been learning tensorflow and rl for months, and for the past few days I've been trying to solve <em>OpenAI</em> <em>Cartpole</em> with my own code but my <em>Deep Q-Network</em> can't seem to solve it. I've checked and compared my code to other implementations and I don't see where I am going wrong? Can anyone ... | <p>Your initial epsilon is set to 1 <code>self.epsilon = 1.0</code>. And yet, when you perform an action, instead of decaying it, you increase it.</p>
<pre><code>self.epsilon *= .995 + .01
</code></pre>
<p><em>1.0 x 0.995 + 0.01 = 0.995 + 0.01 = 1.005</em></p>
<p>The exploration factor (epsilon) should be <strong>de... | python-3.x|tensorflow|reinforcement-learning|openal|openai-gym | 1 |
353,228 | 54,600,151 | Create a new column that is the concatenation of all preceeding columns | <p>I would like to concatenate all columns in a pandas dataframe separated by spaces (" "). Is there a more pythonic way other than df['newcolumn'] = df['a'] + " " df['b'] + " " ...</p>
<pre><code>a b c combined
1 2 3 1 2 3
a d 3 a d 3
p 0 k p 0 k
</code></pre> | <p><code>lambda</code> can be useful along <code>axis=1</code></p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a':['1','a','p'],
'b':[2,'d',0],
'c':[3,3,'k']})
df=df.astype(str)
df['combined']=df[df.columns].apply(lambda x: ' '.join(x), axis=1)
</code></pre> | python|pandas | 2 |
353,229 | 54,395,858 | How to load a model using .ckpt.data and .ckpt.index | <p>In the code, I have been using it uses a .ckpt like incption_v4.ckpt to load a model. am trying to use the pretrained pnesnet model and it comes as two separate file .ckpt.data and .ckpt.index. can someone please show me how to load from these two files.</p>
<p>In the code to evaluate the model it used the path of... | <p>Just using the name of the model as <code>model.ckpt</code> works. Don't have to care about the <code>.data</code> and <code>.index</code> part</p> | python|tensorflow|classification|pre-trained-model | 1 |
353,230 | 54,313,461 | Pandas - convert float to proper datetime or time object | <p>I have an observational data set which contain weather information. Each column contain specific field in which date and time are in two separate column. The time column contain hourly time like 0000, 0600 .. up to 2300. What I am trying to do is to filter the data set based on certain time frame, for example betwee... | <p>When you read the excel file specify the <code>dtype</code> of col <code>itime</code> as a <code>str</code>:</p>
<pre><code>df = pd.read_excel("test.xlsx", dtype={'itime':str})
</code></pre>
<p>then you will have a time column of strings looking like:</p>
<pre><code>df = pd.DataFrame({'itime':['2300', '0100', '05... | python|pandas|datetime|time | 6 |
353,231 | 54,548,842 | TensorFlow: Image cannot be converted to float when creating confusion matrix | <p>I am trying to create a confusion matrix in TensorFlow but I am getting a </p>
<blockquote>
<p>TypeError: Image data cannot be converted to float.</p>
</blockquote>
<p>The images are predicted accurately but now I want to show the confusion matrix using matplotlib. I tried converting to to np.array() but the err... | <p>I have not tested it in my PC. Your description is a little bit ambiguous for me (the line of error, etc.), but the main difference of your code and the documentation you linked is <code>confusion_matrix()</code>. Just try to go with <code>confusion_matrix()</code> of <em>sckit-learn</em> instead of <code>confusion_... | python|tensorflow|scikit-learn|confusion-matrix | 1 |
353,232 | 54,538,706 | Tensorflow Object Detection - Best practice | <p>As mentioned in my other thread (<a href="https://stackoverflow.com/questions/54538497/tensorflow-object-detection-avoid-overlapping-boxes">Tensorflow Object Detection - Avoid overlapping boxes</a>) I'm new to machine learning and I have to implement an algorithm for detecting traffic lights. </p>
<p>Regarding Tens... | <p>You should use configuration to tune all the aspects. As mentioned in <a href="https://stackoverflow.com/q/49148962">Tensorflow object detection config files documentation</a>, configuration parameters can be browser in the protocol buffers message definitions. For example, for the model, if you are using faster RCN... | python|object|tensorflow|detection | 2 |
353,233 | 54,544,059 | concatenating two tables relative many objects in cell | <p>I've a problem with a connection between two tables. And more specifically I've a first table (Df_1), which has a column 'B' and tree rows. In each row in column 'B', I have a cell with three values (nine values in column B in three rows), precisely, each cell has an array with three values. In addition, I have two ... | <p>Maybe someone knows a more efficient way, but you could just brute force it and use a loop.</p>
<pre><code>temp_list = []
for index,row in Df_1.iterrows():
for e in row['B']:
temp_list.append((row['A'],row['C'],e))
temp_df = pd.DataFrame(temp_list,columns = ['A','C','B'])
Df_3 = Df_2.merge(temp_df, l... | python|pandas|numpy | 0 |
353,234 | 54,466,392 | Why do two methods of numpy array multiplication give different answers? | <p>In this small example the two "res" variables give different results. Can someone explain why this is? I expect them to both return roughly 5.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
dist1 = np.random.normal(100., 10., 10000)
dist2 = np.random.normal(0.05, 0.005, 10000)
res1 = dist1
res1... | <p><code>res1 = dist1</code> does <strong>not</strong> copy <code>dist1</code>. You are modifying it in place with <code>*=</code> hence those are two different operations.</p>
<p>Use <code>copy</code> to copy the array:</p>
<pre><code>>>> dist1 = np.random.normal(100., 10., 10000)
>>> dist2 = np.ra... | python|numpy | 1 |
353,235 | 54,514,979 | Why is pandas.grouby.mean so much faster than paralleled implementation | <p>I was using the pandas grouby mean function like the following on a very large dataset: </p>
<pre><code>import pandas as pd
df=pd.read_csv("large_dataset.csv")
df.groupby(['variable']).mean()
</code></pre>
<p>It looks like the function is not using multi-processing, and therefore, I implemented a paralleled versi... | <p>Short answer - use <a href="https://dask.org/" rel="nofollow noreferrer">dask</a> if you want parallelism for these type of cases. You have pitfalls in your approach that it avoids. It still might not be faster, but will give you the best shot and is a largely drop-in replacement for pandas.</p>
<p>Longer answer<... | python|python-3.x|pandas|cython|pandas-groupby | 4 |
353,236 | 54,430,270 | Is there a way to dynamically query a postgres db from Flask user inputs? | <p>I need to dynamically query my Postgres database based on a Flask web app user input. I had it working in Python, but when I moved it to Flask it stopped working. I've narrowed it down to an issue with variable insertion into the query. </p>
<pre><code>def predict_page():
address_lookup = '10 West 28 Street'
... | <p>I think all you are missing are the single quotes in the <code>sq</code> string:</p>
<pre><code>address_lookup = '10 West 28 Street'
sq = """SELECT noise, population_density, median_home_value,
median_household_income, yearbuilt, vacant FROM
lookup_table WHERE address = '%s';""" % address_lookup
print sq
</code><... | python|pandas|flask | 1 |
353,237 | 54,345,237 | String conversion to dataframe | <p>In this screenshot data (string datatype) and df2 (pandas dataframe) store the same data - a timestamp and a value.</p>
<p><a href="https://i.stack.imgur.com/lkHnc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lkHnc.png" alt="enter image description here"></a></p>
<p>How do I get data in a sim... | <pre><code>import ast
import pandas as pd
data = "[[1212.1221, -10.5],[2232.55, -19.44],[32432.87655, -445.88]]"
df = pd.DataFrame(ast.literal_eval(data),
columns=['index', 'data'])
</code></pre> | python|pandas|dataframe | 1 |
353,238 | 54,401,755 | win10 pro 64 bit + python 3.6.0 ImportError: DLL load failed: The specified module could not be found | <p>I was running Tensorflow command in anaconda with python 3.6 and it's giving me an error <strong>ImportError: DLL load failed: The specified module could not be found.</strong>
Though, I have installed tensorflow-gpu with conda command and checked the packages , but i am not able to figure out the problem.
Below are... | <p>Check your CUDA and cudnn version.I refer to the <a href="https://github.com/tensorflow/tensorflow/issues/22794" rel="nofollow noreferrer">link</a>.</p>
<p>I also met the problem you said, but I installed the following to fix it.</p>
<pre><code>cuda 9.0
tensorflow-gpu 1.12.0
cudnn 7.4.1.5
</code></pre> | python|tensorflow|anaconda|image-recognition|cudnn | 1 |
353,239 | 54,467,726 | How to copy one column into another new one properly(without copy error)? | <p>I want to copy one column into a new one.
I use this code:</p>
<pre><code>df['income10']=df['income'].copy(deep=False)
</code></pre>
<p>I get this error:</p>
<pre><code>/Users/hairy/ipykernel/ipykernel_launcher.py:2: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try u... | <p>Try doing this way:</p>
<pre><code>df['income10']=df.loc[:, ['income']]
</code></pre> | python|pandas | 1 |
353,240 | 54,677,880 | Does Pandas ExcelWriter work with excel 365, or which version of excel it supports | <p>same code for excelwriter working with excel 2013, but not excel365. what version of excel pandas excelwriter supports?</p>
<p>have code as below: </p>
<p>tested workign with excel 2013, but not excel 365, could not find the excek version support for pandas. </p>
<pre><code>writer = pd.ExcelWriter(fname1, engine=... | <p>it turned out not the excel version problem, but a problem that can not write to external flash driver</p> | excel|python-3.x|pandas|pandas.excelwriter | 1 |
353,241 | 54,332,759 | How to change several nested numpy arrays into one multidimensional array? | <p>I have a numpy <code>a = np.load('test.npy')</code> file with these nested numpy array:</p>
<pre><code>In [21]: a.shape
Out[21]: (6886, 3)
In [22]: a[0].shape
Out[22]: (3,)
In [23]: a[0][0].shape
Out[23]: (787, 6)
</code></pre>
<p>Is there a simple way to change <code>a</code> to be a 4 dimensional array with sh... | <p>I would hate to do it this way, but all that comes to mind is making a second array of the desired shape and slice your data into it. I have to admit that I am having difficulty understanding the shapes of each sub-array...it seems counter intuitive. Anyway, this solution will be slow, but you can do it once and s... | python|numpy | 1 |
353,242 | 54,568,230 | Use Unsupervised Nearest Neighbors with NaN | <p>I want to use unsupervised nearest neighbors and I have NaN in my data. I want that when a feature for a record is NaN, it does not count for the distance with any other record. Filling NaN with 0, would make it close to other records with a value close of 0 and far from value far from 0, so it would not work.</p>
... | <p>I had the same problem when implementing a kNN classifier for data with missing values. When calling the fit() method, scikit-learn checks if there are nans in the data and then raises the error. I didnt found a solution and ended up with writing my own kNN classifier.</p>
<p>Assuming your data is scaled to 0 mean ... | python|numpy|scikit-learn|nan|knn | 0 |
353,243 | 54,515,072 | Excel SUMIFS Array in Python Pandas | <p>I have an Excel sheet of time series data of prices where each day consists of 6 hourly periods. I am trying to use Python and Pandas which I have setup and working, importing a CSV and then creating a df from this. That is fine it is just the sorting code I am struggling with. In excel I can do this using a Sum(sum... | <p>You need filter by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow noreferrer"><code>between</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and the... | python|pandas | 2 |
353,244 | 54,590,570 | Related to installing of tensorflow in python 3.7 | <p>As I am using the command prompt to run python when installing tensorflow it is saying requirment satisfied but when importing giving an error</p>
<pre class="lang-none prettyprint-override"><code>ImportError
Traceback (most recent call last)
c:\users\chirag\appdata\local\programs\pyt... | <p>The <a href="https://www.tensorflow.org/install/source_windows" rel="nofollow noreferrer">TensorFlow build from source on Windows guide</a> mentions it only supports Python 3.5 and Python 3.6.</p>
<p>Last time I installed tensorflow on Windows, if I recall correctly I used <a href="https://www.python.org/downloads/... | tensorflow | 0 |
353,245 | 54,415,083 | Indexing matrix elements when input arrays are equal | <p>I have a matrix and I want to be able to change the value of certain elements when indexing them with two array without using loops</p>
<p>For example</p>
<pre><code>import numpy as np
A = np.array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
b = np.array([0, 1, 2])
c = np.array([2, 3, ... | <p>You can use <code>numpy.meshgrid</code> to expand your 1D indexing arrays to 2D indexing arrays:</p>
<pre><code>import numpy as np
A = np.array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
b = np.array([0, 1, 2])
c = np.array([2, 3, 1, 1])
C,B = np.meshgrid(c,b)
A[B==C] = 1
print(A)
</... | python|arrays|numpy|matrix|indexing | 1 |
353,246 | 54,625,377 | why MSE on test set is very low and doesn't seem to evolve (not increasing after increasing epochs) | <p>I am working on a problem of predicting stock values using LSTMs. </p>
<p>My work is based on the following <a href="https://www.datacamp.com/community/tutorials/lstm-python-stock-market" rel="nofollow noreferrer">project</a> .
I use a data set (time series of stock prices) of total length 12075 that I split into t... | <p>The reason behind above difference in MSE between training and test is that we are not computing the same thing. During training, the MSE is the average of the sum of errors over time steps for every sample in the training data and so it is big. During test, we are making N=50 predictions and computing the average e... | tensorflow|machine-learning|lstm|recurrent-neural-network|mse | 0 |
353,247 | 73,826,966 | TypeError: cannot do positional indexing on Int64Index with these indexers [Int64Index([5], dtype='int64')] of type Int64Index | <p>I have a dataframe (small sample) like this:</p>
<pre><code>import pandas as pd
data = [['A', False, 2], ['A', True, 8], ['A', False, 25], ['A', False, 30], ['B', False, 4], ['B', False, 8], ['B', True, 2], ['B', False, 3]]
df = pd.DataFrame(data = data, columns = ['group', 'indicator', 'val'])
group indicator ... | <p>You can use a <code>groupby.rolling</code> with a centered window of 2*n+1 to get the n rows before and after each True, then perform <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean indexing</a>:</p>
<pre><code>n = 1
mask = (df.group... | python|pandas|dataframe|typeerror | 1 |
353,248 | 73,549,209 | Changing the value of a column based off of another column in a pandas dataframe | <p>I have a pandas dataframe, and whenever the classification column is 1, I want to add the string "black" to it.
This is what my dataframe is right now:</p>
<pre><code> Explanation Classification:
blue, red, pink 1
green, red ... | <p>This should do:</p>
<pre class="lang-py prettyprint-override"><code>df.loc[df.Classification == 1, "Explanation"] += ", black"
</code></pre>
<p>NB: Depending on your application, it might be a good idea to split the color column into separate columns for each color (e.g. if you ever need to count... | python|pandas | 0 |
353,249 | 73,591,270 | Create subset of multiple pandas dataframes using for statement | <p>I am working with multiple dataframes in pandas, and am looking to only select certain columns from each of them.</p>
<pre><code>AUD = [AUD2yr,AUD5yr,AUD10yr,AUD30yr]
for df in AUD:
df = df[['Date','Open']]
</code></pre>
<p>I would ideally like to keep the names of the dataframes, but i receive the following er... | <blockquote>
<p>'NoneType' object is not subscriptable</p>
</blockquote>
<p>This means in your program somewhere <code>None[...]</code> is attempted. From the snippet you shared, that happens with <code>df[...]</code>, i.e., somehow <code>df</code> became <code>None</code>.</p>
<p>Apart from that, doing <code>df = df[[... | python|pandas|dataframe | 1 |
353,250 | 73,806,969 | Is there a way to remove the access rectangle at the end of an open plot when using this methon to claculate the upper and lower sum of a function? | <p>When using this bit of code to calculate the upper and lower sum of a function (using the Archimedes strip method) and the plot doesn't end on y = 0 but "in the air", an access rectangle at the end appears, what would be a way to remove this and make it look cleaner? Please excuse me if I made some stupid ... | <p>When you print your x-axis values:</p>
<pre><code>print(lower_bar)
print(upper_bar)
</code></pre>
<p>You'll notice that they are shifted:</p>
<pre><code>[-0.05235988 0.05235988 0.15707963 0.26179939 0.36651914 0.4712389
0.57595865 0.68067841 0.78539816 0.89011792 0.99483767 1.09955743
1.20427718 1.308... | python|numpy|matplotlib|math|plot | 0 |
353,251 | 73,540,096 | Drastic difference in accuracy for varying batch sizes? | <p>When training my CNN image classifier using PyTorch I noticed a ~20+% difference in accuracy when using a batch size of 4 vs 32. What might be causing such drastic differences?</p>
<p><strong>batch_size 4</strong></p>
<pre><code>100%|██████████| 10/10 [02:50<00:00, 17.04s/it, TestAcc=71%, TrainAcc=74%, loss=0.328... | <p>You can try to adjust your learning rate too.<br />
With a larger batch size you should also use a larger learning rate.<br />
<a href="https://www.baeldung.com/cs/learning-rate-batch-size" rel="nofollow noreferrer">This</a> article has additional explanations for the relation of learning rate and batch size.</p> | machine-learning|pytorch|conv-neural-network | 0 |
353,252 | 73,765,041 | mask duplicate entries while merging in pandas | <p>Dataframe 1 :</p>
<pre><code>id status
A Pass
A P_Pass
A C_Pass
B Fail
B A_Fail
</code></pre>
<p>Dataframe 2 :</p>
<pre><code>id Category group
A pxe 1
B fxe 2
</code></pre>
<p>After merging the Dataframe 2 on Dataframe 1 with left join... | <p>you use np.where and cumcount after merging:</p>
<pre><code>#df_final
id status Category group
0 A Pass pxe 1
1 A P_Pass pxe 1
2 A C_Pass pxe 1
3 B Fail fxe 2
4 B A_Fail fxe 2
df_final['Category'] = np.where(df_final.groupby('Category').c... | pandas | 0 |
353,253 | 73,691,492 | How to load one model’s output as another model’s parameters and do end-to-end optimization | <p>Here we have an abstract of this problem:</p>
<p>Assuming that we have two models: ResNet and EfficienNet, respectively.</p>
<p>The first model is as follow <em><strong>(ResNet)</strong></em>:</p>
<pre><code>def __init__(self, in_channels, out_channels, num_classes):
super().__init__()
self.conv1_0 = _conv3... | <p>The <code>params</code> argument of the optimizer specifies all the parameters you want to optimize. Here, as you are only passing the parameters of EfficientNet, only those get optimized, as you suspect.</p>
<p>To optimize for all parameters end-to-end, simply pass them all when initializing the optimizer. This can... | deep-learning|pytorch|google-colaboratory | 0 |
353,254 | 73,623,625 | Applying string transformations from a file to a pandas df | <p>I have a <code>file.txt</code>, whose content is something like:</p>
<pre><code>5th => fifth
av, ave, avn => avenue
91st => ninety first
ny => new york
91st => ninety first
nrth => north
91st => ninety first
nrth => northwest
</code></pre>
<p>I have 1500 lines, approximately. There are repeti... | <p>Here is a regex solution, runs in ~800ms for 60k rows and 7 replacement values:</p>
<pre><code>words = pd.read_csv('file.txt', sep=r'\s*=>\s*',
engine='python', names=['word', 'repl'])
mapper = (words
.assign(word=words['word'].str.split(r',\s*'))
.explode('word')
.drop_duplicates('w... | python|pandas|regex | 0 |
353,255 | 73,574,491 | Groupby id and create a dummy if a column value does not include zeros | <p>I have the following df, and i want to create a dummy =1 if and only if each id does not contain any zeros in column "count".</p>
<pre><code>id count
A 9
A 0
A 2
A 1
B 2
B 5
B 2
B 1
C 1
C 9
D 7
D 2
D 0
</code></pre>
<p>desired output</p>
<... | <p><code>groupby().transform</code> is the way to go, but I'd groupby on the logic series itself</p>
<pre><code># transform `min` would work as well
df['dummy'] = df['count'].ne(0).groupby(df['id']).transform('all').astype(int)
</code></pre>
<p>Output:</p>
<pre><code> id count dummy
0 A 9 0
1 A 0... | python|pandas|dataframe | 2 |
353,256 | 73,718,219 | Pandas map, check if any values in a list is inside another | <p>I have the following list</p>
<pre><code>x = [1,2,3]
</code></pre>
<p>And the following df</p>
<p>Sample df</p>
<pre><code>pd.DataFrame({'UserId':[1,1,1,2,2,2,3,3,3,4,4,4],'Origins':[1,2,3,2,2,3,7,8,9,10,11,12]})
</code></pre>
<p>Lets say I want to return, the userid who contains any of the values in the list, in h... | <p>IIUC, OP wants, for each <code>Origin</code>, the <code>UserId</code> whose number appears in list <code>x</code>. If that is the case, the following, using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>pandas.Series.isin</code></a> and <a href="https:... | python|pandas | 1 |
353,257 | 73,672,773 | Access images after tf.keras.utils.image_dataset_from_directory | <p>I'm using tf.keras.utils.image_dataset_from_directory to load my images into a dataset for tensorflow. However, I'm confused about how it works. I simply want to be able to imshow each image from the dataset.</p>
<pre><code>data = tf.keras.utils.image_dataset_from_directory('/content/gdrive/MyDrive/Skyrmion Vision/... | <p>You created batches of one element each by setting <code>batch_size=1</code>.</p>
<p>So if you do:</p>
<pre><code>data_iterator = data.as_numpy_iterator()
batch = data_iterator.next()
</code></pre>
<p>You are only accessing one image because your batch only has one image in it. To get the next batch, and so, the nex... | python|tensorflow|keras | 1 |
353,258 | 73,673,638 | using pandas dataframe multiply & add each row based on each year on a group by condition user_id & customer_id | <p>am having pandas dataframe, it has 7 columns customer_id, user_id, year_month, values, 01,02,03 i have to multiply & add each row based on group by customer_id, user_id considering month from year_month column</p>
<pre><code>Input Dataframe
df
###
customer_id user_id year_month values 01 02 03
... | <p>No so straightforward, there are 3 layers to achieve (pivoting, multiplying with MultiIndex, merging).</p>
<p>You can use:</p>
<pre><code>df2 = df['year_month'].str.split('-', expand=True)
df['year'] = df2[0]
out = df.merge(
df.set_index(['customer_id', 'user_id', 'year', 'year_month'])
.mul(df.assign(month=df... | python|python-3.x|pandas|dataframe | 1 |
353,259 | 73,532,080 | Pandas check if duplicate value from one column has value in another column | <p>The logic that I'm looking for is that, if in x column there is a duplicate value, indicate if that value in any row has a specific string in another column. This might work with a binary function.</p>
<p>For instance:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>X</th>
<th>Y</th>
<th... | <p>Try with</p>
<pre><code>df['Corr_Y'] = df['X'].isin(df.loc[df['Y'] == 'Correct','X'])
</code></pre> | python|pandas|dataframe | 3 |
353,260 | 73,541,397 | Concat pandas dataframes | <p>How to concat without column names?</p>
<pre><code>>> df = pd.DataFrame({'col1': [1], 'col2': [4]})
>> df1 = pd.DataFrame([[5,5]])
>> pd.concat([df, df1])
col1 col2 0 1
0 1.0 4.0 NaN NaN
0 NaN NaN 5.0 5.0
</code></pre>
<p>Also the types changed into <co... | <p>Temporarily <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_axis.html" rel="nofollow noreferrer"><code>set_axis</code></a> with that of <code>df</code> on <code>df1</code>:</p>
<pre><code>pd.concat([df, df1.set_axis(df.columns, axis=1)], ignore_index=True)
</code></pre>
<p><em>NB. <a href=... | python|pandas|dataframe | 3 |
353,261 | 73,826,504 | Two constraints setting together in optimization problem | <p>I am working on an optimization problem, and facing difficulty setting up two constraints together in Python. Hereunder, I am simplifying my problem by calculation of area and volume. Only length can be changed, other parameters should remain the same.</p>
<p>Constraint 1: Maximum area should be 40000m2
Constraint 2... | <p>I believed the code below solve the current problem you are facing.
If I can help any further let me know.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Name': ['A', 'B', 'C', 'D'],
'Length': [1000, 2000, 3000, 5000],
'Width': [5, 12, 14, 16],
... | python|pandas|dataframe|optimization|constraints | 0 |
353,262 | 73,804,743 | Python - search spreadsheet for cell containing datetime string | <p>I'm a Python newbie and this is my first SO post. I'm trying to use python to extract a datestamp from a cell in a spreadsheet. I tried the following:</p>
<pre><code> df = pd.read_excel(fileName, sheet_name=0)
df_columns = dict(zip(df.columns,range(len(df.columns))))
df_start = df.rename(columns=df_column... | <p>Considering that your Excel files has only timestamps values distributed in multiple rows/cols (see example/dataframe below) :</p>
<pre><code>import pandas as pd
df = pd.read_excel("myinnernerd.xlsx")
print(df)
0 1 2 3 4 5 ... | python|excel|pandas|string|datetime | 0 |
353,263 | 73,784,865 | How to convert float into date and time in pandas | <p>I have a date column in my dataframe that I want to use at an index in that dataframe. I tried to convert this columns using <code>pd.to_datetime()</code> but it did not work.</p>
<p>my columns containing date looks like:</p>
<pre><code>0 9.2017
1 10.2017
2 11.2017
3 12.2017
4 1.2018
... | <p>you need to convert the column to string first:</p>
<pre><code>pd.to_datetime(df['date_col'].astype(str), format='%m.%Y')
</code></pre> | python-3.x|pandas|dataframe|datetime | 1 |
353,264 | 73,837,595 | custom colors in matplotlib | <p>Hi I have two columns in my dataframe gender, countries</p>
<p>I am trying to get a bar graph of population of countries, for example:
India - Male - 40
- Female-20
US - Male - 20
- Female-15
.....</p>
<p>I want to give custom color to male and female for example "Blue" for men and "pink" for ... | <p>Use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.bar.html" rel="nofollow noreferrer">color parameter</a>, for example like this:</p>
<pre><code>import pandas as pd
import seaborn as sns #To load some data
df = sns.load_dataset('iris')
df2 = df['species'].groupby(df['species']).val... | python|pandas|matplotlib | 0 |
353,265 | 73,684,871 | Exporting a pivot table to csv | <p>When creating a pivot table using the following code:</p>
<pre><code>df = df.pivot_table(index=['Player', 'Pos'], values=['Min'], aggfunc='sum')
</code></pre>
<p>The csv export returns:</p>
<pre><code>Player Pos Min
A GK 450
B CM 1
B DM 166
C RB ... | <p>Use custom lambda function for remove duplicated values after join <code>Pos</code> strings in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a>:</p>
<pre><code>#if there is space or not space after separato... | python|pandas|dataframe|pivot-table | 2 |
353,266 | 73,602,930 | Forcing PyTorch Neural Net to output a specific datatype | <p>I am learning how to create a GAN with PyTorch 1.12 and I need the instance returned by my generator to fall into a specific feature space.</p>
<p>The model in my generator class looks like this:</p>
<pre><code>self.model = nn.Sequential(
nn.Linear(2, 16),
nn.ReLU(),
nn.Linear(16,... | <p>You can try clipping negative values and casting to <code>torch.int32</code>:</p>
<pre class="lang-py prettyprint-override"><code>from torch import nn
import torch
class TransformOutput(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return torch.clamp_min(x, min=0... | python|deep-learning|neural-network|pytorch|generative-adversarial-network | 0 |
353,267 | 73,757,451 | Remove nan from list if some of the elements are data-frame | <p>I have below <code>list</code></p>
<pre><code>import pandas as pd
import numpy as np
dat = pd.DataFrame({'name' : ['A', 'C', 'A', 'B', 'C'], 'val' : [1,2,1,2,4]})
List = [dat, np.nan, dat, np.nan, np.nan]
List
</code></pre>
<p>I want to retain only those elements where they are not <code>nan</code>.</p>
<p>There is ... | <p>You can do:</p>
<pre><code>[x for x in List if isinstance(x, pd.DataFrame)]
</code></pre>
<p>If you insist on filtering on filter out <code>nan</code> only, then remember that it is a float instance, so:</p>
<pre><code>[x for x in List if not(isinstance(x, float) and np.isnan(x))]
</code></pre> | python-3.x|pandas|numpy | 1 |
353,268 | 73,612,917 | Python export dataframe complete column as hyperlinks | <p>I am exporting dataframes to excel sheets. Two columns have https addresses. I want to make them these columns hyperlinks. So, when I open the excel sheet, I can simply click the hyperlink.</p>
<p>Present:
<a href="https://i.stack.imgur.com/L5mvy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L5m... | <p>You can try editing the cells so that whenever they are converted to excel they are automatically read as a hyperlink. Provided I am correct with the excel formatting, the change would go like this.</p>
<pre><code>jobsdf['Job Url'] = jobsdf['Job URL'].map('=HYPERLINK("{}")'.format)
jobsdf['Apply Url'] = jo... | python|excel|pandas|dataframe|hyperlink | 1 |
353,269 | 73,624,721 | Remove special characters from object type columns of Data Frame and combine all string letter to form a sentences | <p><img src="https://i.stack.imgur.com/jwUu3.png" alt="enter image description here" /></p>
<p>I have this column in my dataset. Tried to solve it by removing [ and { symbols from this as the whole column is a type string. Each character is a string including , : and spaces. while removing {. it only removes starting a... | <pre><code>def convt(str):
return eval(str)
df['genre'] = df['genre'].apply(convt)
</code></pre> | python-3.x|pandas|dataframe | 0 |
353,270 | 73,571,425 | How to fix the issue of Input has undefined rank in TensorFlow? | <p>I am trying to define a custom DensNet. But, I am getting a weird error and mot understand why. The code is as follows:</p>
<pre><code>def densenet(input_shape, n_classes, filters = 32):
#batch norm + relu + conv
def bn_rl_conv(x,filters,kernel=1,strides=1):
x = BatchNormalization()(x)
... | <p>You are calling <code>Input</code> layer incorrectly. You're passing <code>input_shape</code> to the <code>__call__()</code> method instead of the <code>shape</code> parameter.</p>
<p>Change:</p>
<pre><code>inp = Input (input_shape)
</code></pre>
<p>To:</p>
<pre><code>inp = Input(shape=input_shape)
</code></pre> | tensorflow|keras|jupyter-notebook | 2 |
353,271 | 73,619,180 | Scipy minimize.optimize LBFGS vs PyTorch LBFGS | <p>I have written some code with <code>scipy.optimize.minimize</code> using the LBFGS algorithm. Now I want to implement the same with PyTorch.</p>
<p>SciPy:</p>
<pre><code>res = minimize(calc_cost, x_0, args = const_data, method='L-BFGS-B', jac=calc_grad)
def calc_cost(x, const_data):
# do some calculations with ar... | <p>The problem is that I was using the wrong "objective" function. What I am trying to optimize is the <code>x_0</code> array, therefore I had to alter my code as follows:</p>
<pre><code>for i in range(10):
optimizer.zero_grad()
x_0.backward(gradient = calc_gradient(x_0, const_data))
optimizer.step(l... | python|optimization|scipy|pytorch | 0 |
353,272 | 73,808,940 | how to keep unique or most frequent value(s) per row for a pandas column? | <p>I Have a dataframe with a list of words and I was to keep the words unique words if mentioned multiple times or keep all word if only mentioned once.</p>
<p>My dataframe looks like this:</p>
<pre><code>cars
[honda, toyota]
[honda, none, honda, toyota, toyota]
[lexus, mazda]
[honda, mazda, lexus, mazda, honda]
</co... | <p>Make them into sets, a set inherently only has unique values.</p>
<p>Optionally, you can convert them back to lists again afterwards.</p>
<pre><code>df.cars = df.cars.apply(set)#.apply(list)
</code></pre> | pandas|dataframe | 1 |
353,273 | 73,627,634 | copy-paste short one dimensional dataframe to an empty column in other bigger dataframe | <p>need to copy this vector/one dimensional dataframe (df1) to its respective column in different(and longer) dataframe (df2):
<strong>df1</strong>:</p>
<pre><code>ID
44
22
66
77
</code></pre>
<p><strong>df2:</strong></p>
<pre><code>ID c2 c3 c4 c5
nan 1 2 2 1
nan 1 3... | <pre><code>df2.update(df['ID'].astype(str))
</code></pre>
<pre class="lang-none prettyprint-override"><code> ID c2 c3 c4 c5
0 44 1 2 2 1
1 22 1 3 2 3
2 66 3 4 4 3
3 77 4 5 6 5
4 NaN 5 6 9 7
5 NaN 1 3 1 5
</code></pre> | pandas|dataframe|copy-paste | 0 |
353,274 | 73,789,471 | How to Melt a column into another melted column within Pandas? | <p>I have a file consisting of sales for different items. I have a column of model predictions named <code>outputs</code> and which model produced those predictions named, <code>model</code>. I need to take the current model's (that's in production) predictions in a column named 'FCAST_QTY<code>and make them part of ... | <p>Create a new dataframe with your logic and append it to the original dataframe:</p>
<pre class="lang-py prettyprint-override"><code>fcast_qty = (df
.drop(columns = ['output', 'model'])
.rename(columns={"FCAST_QTY":"output"})
.assign(model="FCAST_QTY&quo... | pandas|pandas-melt | 3 |
353,275 | 73,529,782 | numpy structured array inconsistency | <p>I'm writing a library that uses NumPy arrays and I have a scalar operation I would like to perform on <em>any</em> dtype. This works fine for most structured arrays, however I run into a problem when creating structured arrays with multiple dimensions for structured elements. As an example,</p>
<pre><code>x = np.zer... | <p>Use the same <code>dtype</code> notation as displayed in the first working example:</p>
<pre><code>In [92]: x = np.zeros(3, np.dtype([('f0','<f4',(3,))]))
In [93]: x
Out[93]:
array([([0., 0., 0.],), ([0., 0., 0.],), ([0., 0., 0.],)],
dtype=[('f0', '<f4', (3,))])
</code></pre>
<p>I don't normally use th... | python|arrays|numpy|structured-array | 0 |
353,276 | 73,744,731 | Color distinct values in pandas columns from the other column | <p>I have 4 columns of string values and I want to visiually compare distinc values in 3 columns to the values in the first columns.</p>
<p>So, <strong>if value in column 2, 3 and 4 is not in column 1, I want to color this cell in corresponding column</strong>.</p>
<p>I don't know how can it be implemented, as I never ... | <p>You could try as follows.</p>
<pre><code>import pandas as pd
import numpy as np
def f(col):
return np.where(col.isin(df['column 1']),'','background-color: IndianRed')
df.style.apply(f, subset=['column 2', 'column 3', 'column 4'])
</code></pre>
<p>Result:</p>
<p><a href="https://i.stack.imgur.com/wdizd.png" rel... | python|pandas|dataframe|visualization | 1 |
353,277 | 73,558,855 | InvalidSchema: No connection adapters were found for "link"? | <p>I have a dataset with multiple links and I'm trying to get the text of all the links using the code below, but I'm getting a error message "InvalidSchema: No connection adapters were found for "'https://en.wikipedia.org/wiki/Wagner_Group'".</p>
<p>Dataset:</p>
<pre><code> links
'https://en.wikipe... | <p><code>df['links'].apply(get_data)</code> is not compatible with requests and bs4.
You can try one of the right ways as follows:</p>
<p><strong>Example:</strong></p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
links =[
'https://en.wikipedia.org/wiki/Wagner_Group',
'https://en.... | python|pandas|url|beautifulsoup | 0 |
353,278 | 73,719,021 | Two 2D arrays to coordinate sets | <p>I have two 2-dimensional arrays:</p>
<pre><code>x
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]])
y
array([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])
</code></pre>
<p>What I would like to do is to genera... | <p>This seems to do the trick, please say if there's a better way.</p>
<pre><code>x = x.flatten()
y = y.flatten()
xy = list(zip(x, y))
points = MultiPoint(xy)
points_gdf = gpd.GeoDataFrame(index=[0], crs=crs, geometry=[points])
points_gdf = points_gdf.explode(index_parts=True)
</code></pre> | python|geopandas | 1 |
353,279 | 73,539,388 | How to count observation per time interval in pandas? | <p>I have a following dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
dict = {
"id": [1, 2, 2, 3, 3],
"start_time": [
"2022-08-30 08:00:02",
"2022-08-30 08:03:07",
"2022-08-30 08:06:52",
"... | <p>If possible use input data from <a href="https://stackoverflow.com/q/73538538/2901002">previous solution</a> use:</p>
<pre><code>dict_df = {
"id": [1, 2, 2, 2, 3, 3, 3, 3],
"time": [
"2022-08-30 08:00:02",
"2022-08-30 08:03:07",
"2022-08-30... | python|pandas | 2 |
353,280 | 73,615,322 | Alternative to reset_index().apply() to create new column based off index values | <p>I have a df with a multiindex with 2 levels. One of these levels, <code>age</code>, is used to generate another column, <code>Numeric Age</code>.</p>
<p>Currently, my idea is to reset_index, use apply with <code>age_func</code> which reads <code>row["age"]</code>, and then re-set the index, something like.... | <p>We can set a new column using <code>.loc</code>, and modify the rows we need using masks. To use the correct col values, we also use a mask.</p>
<p>First step is to make a mask for the rows to target.</p>
<pre><code>mask_foo = df.index.get_level_values("age") == "foo"
</code></pre>
<p>Later we wi... | pandas|multi-index | 0 |
353,281 | 73,595,549 | Calculate the centroid of a rectangle geometry in python | <p>I have the following Polygon geometry. When I calculate the <code>centroid</code>, I get an invalid / inaccurate <code>POINT</code>. I am using <code>geopandas</code> <code>centroid</code> to calculate the point.</p>
<p><a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoSeries.centroid.html" re... | <p>Your code is fine, your polygon is not and does not represents a rectangle area in Dallas, TX. Let's split it into vertices to make it apparent:</p>
<pre><code>g = "POLYGON ((-96.8115234375 32.87109375,
-96.8115234375 -96.767578125,
32.8271484375 -96.767578125,
32... | python|geospatial|geopandas | 3 |
353,282 | 73,694,605 | Create 3 dataframes from original dataframe using existing values | <p>I have the following dataframe which I'm wanting to create 3 new dataframes from using the values in specific columns (<strong>ppbeid</strong>, <strong>initpen</strong> and <strong>incpen</strong>) and using the unique entries in the <strong>benid</strong> and <strong>id</strong> columns:</p>
<p><a href="https://i.s... | <p>It seems like what you want can be done with the <code>pivot</code> method, which is similar to Excel's pivot table.</p>
<p>First let's set up the data:</p>
<pre><code>df = pd.DataFrame(
{
"id": [92, 92, 133, 133, 133, 705, 705, 705, 588, 588],
"initpen": [0] * 8 + [606.32, 15... | python|pandas|dataframe | 1 |
353,283 | 73,583,250 | Target encoding multiple columns in pandas python | <p>I have the following table.</p>
<pre><code>id col1 col2 col3 col4 target
1 A B A 101 1
2 B B A 191 1
3 A B A 81 0
4 C B C 67 1
5 B C C 3 0
</code></pre>
<p>I want to target encode every column except <code>col4</code>.</p>
<p><strong>Expected Output:<... | <h5>update after clarification:</h5>
<p>You need to use the same approach as in your original attempt, but using <code>map</code></p>
<pre><code>df.update(df[['col1', 'col2', 'col3']]
.apply(lambda s: s.map(df['target'].groupby(s).mean()))
)
</code></pre>
<p>output:</p>
<pre><code> id col1 col2 ... | python|pandas | 3 |
353,284 | 73,636,817 | asfreq in pandas returns an empty dataframe | <p>I'm tring to use infer_freq and asfreq and the return data frame is empty</p>
<p>Original data set:</p>
<pre><code> month interest
0 2004-01 13
1 2004-02 15
2 2004-03 17
3 2004-04 19
4 2004-05 22
</code></pre>
<p>Trying to convert the data with different frequency</p>
<pre><code>ice_cream_interest = p... | <p>I want to quote from the documentation of <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.asfreq.html" rel="nofollow noreferrer"><code>asfreq()</code></a>.</p>
<blockquote>
<p>The values corresponding to any timesteps in the new index which were not present in the original index will be null (... | python|pandas|datetime | 1 |
353,285 | 73,649,612 | how to change the particuler elements of an array | <p>I have an array for an example:</p>
<pre><code>import numpy as np
data=np.array([[4,4,4,0,1,1,1,1,1,1,0,0,0,0,1],
[3,0,1,0,1,1,1,1,1,1,1,1,1,1,0],
[6,0,0,0,1,1,1,1,1,1,1,1,1,1,0],
[2,0,0,0,1,1,1,0,1,0,1,1,1,0,0],
[2,0,1,0,1,1,1,0,1,0,1,0,1,0,0]])
</code></... | <p>You can use a 2D convolution on the 1s with a 3x3 kernel of 1s to identify the centers of the 3x3 squares, then dilate them and restore the non 1 numbers</p>
<pre><code>from scipy.signal import convolve2d
from scipy.ndimage import binary_dilation
# get 1s (as boolean)
m = data==1
kernel = np.ones((3, 3))
# get ce... | python|numpy|scikit-learn|scikit-image | 1 |
353,286 | 73,604,662 | How to sample random datapoints from a dataframe | <p>I have a dataset X in panda dataframe with about 48000 datapoints. In the dataset here is a feature called gender, 1 representing male and 0 representing female.
How do I sample entries from my original dataset? Say I want a new dataset Y with 1000 random datapoint samples from X with 700 males and 300 females? I ca... | <p>Use:</p>
<pre><code>males = X[X['gender']==1].sample(n=700)
females = X[X['gender']==0].sample(n=300)
ndf = males.append(females).sample(frac=1)
</code></pre>
<p>Or:</p>
<pre><code>weights = [.7 if x==1 else .3 for x in X['gender']]
X.sample(n=1000, weights = weights)
</code></pre> | python|pandas|dataframe|dataset | 1 |
353,287 | 71,127,580 | How to index elements of list in a dataframe in Python? | <p>I have the following dataframe:</p>
<pre><code>pandas as pd
df = pd.DataFrame({'Text': ['Hello, I have some text.</p> I would like to split it into sentences. </p> However, when it comes to splitting I want sentences to be indexed so that I can re-join them correctly.</p> I also need to convert li... | <p>You could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> to split the strings, then <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>explode</code></a> to crea... | python|pandas|dataframe | 2 |
353,288 | 71,441,663 | concat index and create list as value of the cell, with values that have been affected by the concat in (python pandas) | <p>This is a bit weird to describe, basically I have this initial dataframe:</p>
<pre><code>test_df
Out[149]:
value
timestamp
2019-01-01 00:00:00+00:00 0.640
2019-01-01 01:00:00+00:00 0.224
2019-01-01 02:00:00+00:00 0.320
2019-01-01 03:00:00+00:00 0.304
2019-01-01 ... | <p>figured it out:</p>
<pre><code>df2 = test_df.groupby('timestamp_type')['value'].apply(list)
df2
Out[33]:
timestamp_type
0,0,1 [0.784, 0.8, 0.352, 0.784]
0,0,10 [0.336, 0.608, 0.624, 0.336]
0,0,11 [0.752, 0.32, 0.736, 0.512]
0,0,12 [0.72, 0.768, 0.752, 0.624, 0.608]
0,0,2 ... | python|pandas|dataframe|datetime | 0 |
353,289 | 71,282,058 | How to interpret the output format of a model? | <p>Noob here, hard to elaborate my question without an example,
so I use a model on the MNIST data that classifies digits based on number images.</p>
<pre><code># Load data
trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(train... | <p>We usually have our data in the form of (BATCH SIZE, INPUT SIZE) which here in your case would be (64, 784).</p>
<p>What this means is that in every batch you have 64 images and each image has 784 features.</p>
<p>Regarding your model this is what it outputs :</p>
<pre><code>model = nn.Sequential(nn.Linear(784, 128)... | python|pytorch | 0 |
353,290 | 71,246,376 | Plotting with with datetime64[ns] objects in Seaborn | <p>I have a large (> 1 mil rows) dataset that has datetime timestamps inside of it. I want to look at trends that may occur throughout the day. So to start if I do: <code>print(df['timestamp'])</code> it will show my data as:</p>
<p>0 2014-01-01 13:11:50.3</p>
<p>1 2011-02-13 04:12:45.0</p>
<p>Name: timestamp, Len... | <p>This works for me.
Difference is in converting column "timestamp" from datetime to time.</p>
<pre><code>import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame([['2014-01-01 13:11:50.3',10],['2011-02-13 04:12:45.0',15]], columns=['timestamp','Task_Length'])
df['timestam... | python|pandas|datetime|seaborn | 0 |
353,291 | 71,211,264 | Built-in index dependent weight for tensordot in numpy? | <p>I would like to obtain a tensordot of two arrays with the same shape with index-dependent weight applied, without use of explicit loop. For example,</p>
<pre><code>import numpy as np
A=np.array([1,2,3])
B=np.array([-2,6,9])
C=np.zeros((3,3))
for i in range(3):
for j in range(3):
C[i,j]=A[i]*B[j]*... | <p>Here's a vectorized solution:</p>
<pre><code>N = 3
C = np.tril(A[:, None] * B * np.exp(np.arange(N)[:, None] - np.arange(N)), k=-1)
</code></pre>
<p>Output:</p>
<pre><code>>>> C
array([[ -2. , 0. , 0. ],
[-10.87312731, 12. , 0. ],
[-44.33433659, 48.92... | numpy|weighted|tensordot | 1 |
353,292 | 71,099,666 | Trying to find repeated names in a database | <p><a href="https://i.stack.imgur.com/LjGHe.png" rel="nofollow noreferrer">Database at hand</a></p>
<p>I have this database at hand and i want to mess around with it trying to learn what i can.
I'm trying to see if names in the "EmployeeName" column has the names that have been around for at least 3 years so ... | <p>You probably want something like this.</p>
<pre><code>SELECT * FROM YourTable WHERE COUNT(EmployeeName) > 1 ORDER BY Year;
</code></pre> | python|pandas | 0 |
353,293 | 71,426,849 | Loop in pd.DataFrame(columns = X) where X is variable | <p>So I've written a program that reads from a monthly released Excel file and converts it all into nice numpy arrays. In order to write this into an Excel file, I have to convert the numpy arrays back into DataFrames. The problem is that the "columns = " argument only takes in the names of each column, but e... | <p>The solution in my case was literally just to write <code>columns = funds[0]</code>, so the code would be</p>
<pre><code>fundsdf = pd.DataFrame(funds[1:], columns = funds[0])
</code></pre> | python|pandas | 0 |
353,294 | 71,169,005 | pandas - explanation of unstack method description | <p>Please explain what the unstack function description <code> DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels</code> means.</p>
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.unstack.html#pandas.DataFrame.unstack" rel="nofollow norefe... | <p>Yes, it is possible, but first is necessary create <code>MultiIndex</code> for possible use <code>unstack</code>, because:</p>
<blockquote>
<p>Returns a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels.</p>
</blockquote>
<p>Here <code>inner-most</code> level o... | pandas|dataframe|pivot | 0 |
353,295 | 71,432,094 | convert a dictionary in a series to dataframe | <p>I have a dictionary object in a <pandas.core.series.series> and I want to convert it to dataframe. please find the example below</p>
<p><code>file["floordetails"]</code> is column of a dataframe, that has a below series</p>
<pre><code>print(file["floordetails"])
0 {'floorname':'2'... | <p>Try using <code>.tolist()</code></p>
<pre><code>new_df = pd.DataFrame(file["floordetails"].dropna().tolist())
</code></pre> | python|pandas|dataframe|data-analysis | 0 |
353,296 | 71,094,874 | How do I create a new column in a dataframe using values from another dataframe? | <p>I have two dataframes, df_1 and df_2, where df_1 has several columns of "codes" and df_2 has the definitions for all of those codes:</p>
<pre><code>df_1 = pd.DataFrame({
'Age': [42, 35, 64, 53],
'Code 1': [1234, 3452, 9583, 8753],
'Code 2': [3857, np.nan, np.nan, 1234]})
df_2 = pd.DataFrame({
... | <p>You could first <code>stack</code> and <code>groupby</code>+<code>agg</code> to form the new column, then <code>merge</code> with the original dataset:</p>
<pre><code>s = df_2.set_index(['Code'])['Code Def']
df_1.merge(df_1.set_index('Age')
.stack().map(s)
.groupby(level='Age').agg(','... | python|pandas|dataframe|join|conditional-statements | 0 |
353,297 | 71,359,291 | Dataframe users who did not purchase item for user-item collaborative filtering | <p>I intend to use a hybrid user-item collaborative filtering to build a <strong>Top-N recommender system</strong> with TensorFlow Keras</p>
<p>currently my dataframe consist of |user_id|article_id|purchase</p>
<p><a href="https://i.stack.imgur.com/ZkQnA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.co... | <blockquote>
<ol>
<li>How do I process it such that I will have 20% purchase = true and 80% purchase = false to train the model?</li>
</ol>
</blockquote>
<p>Since you only have True values, it means that you'll have to generate the False values. The only False that you know of are the user-item interactions that are no... | pandas|tensorflow|machine-learning|recommendation-system | 0 |
353,298 | 71,183,159 | How can I filter by numbers in an excel sheet using Python codes? | <p>I am trying to filter out the data from my excel sheet using Python.
When I filter by car "Make" and "Model," it works fine, but when I add a "Year," it does not return any data(Empty). It works with me only if I add any text at the beginning of each cell for the "Year" Column... | <p><code>car_year</code> is user input and <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow noreferrer">input</a> are strings in Python. Presumably "Year" is dtype int column, so <code>df['Year']==car_year</code> returns a Series of Falses. To get your desired outcome, convert <c... | python|excel|pandas|dataframe|filter | 2 |
353,299 | 71,214,712 | pandas reducer like method | <p>I'm familiar with the <code>JavaScript</code> reducer method, and I'm trying to accomplish something similar with a <code>DataFrame</code>.</p>
<p>I believe in the method shown below I violate the guidance described in pandas.</p>
<p><code>You should never modify something you are iterating over. This is not guaran... | <p>A more efficient (and more pandas-esque :) solution would be to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.cummax.html" rel="nofollow noreferrer"><code>cummax</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.ffill.html" rel="nofollow noreferrer"><code>ff... | python|python-3.x|pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.