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 |
|---|---|---|---|---|---|---|
372,000 | 54,600,851 | numpy assignment with masking | <p>I am a newbie to Python. During an exercise I am supposed to use a mask to multiply all values below 100 in the following list by 2:</p>
<pre><code>a = np.array([230, 10, 284, 39, 76])
</code></pre>
<p>So I wrote the following code:</p>
<pre><code>import numpy as np
a = np.array([230, 10, 284, 39, 76])
cut = 100
... | <p>Not exactly sure what you want, if you want to assign to places where <code>a < cut</code> holds (<code>a < cut = [0, 1, 0, 1, 1]</code> is the boolean index), when you assign to <code>a[a < cut]</code>, you assign to the places where the element is 1, meaning on the right side it expects a numpy array of s... | python|numpy | 5 |
372,001 | 54,635,294 | Pandas: check if a value error is in an interval, error message: InvalidOperation: [<class 'decimal.InvalidOperation'>] | <p>My dataframe looks like this:</p>
<pre><code>target_price interval
0.001767 [0.00318240, 0.00318624]
0.002978 [0.00318576, 0.00319673]
0.000174 [0.00319581, 0.00319617]
0.002740 [0.00318881, 0.00319617]
</code></pre>
<p>The code is used:
<code>for index,interval in df.iterrows():
if interval.ta... | <p>If it is <code>list</code> </p>
<pre><code>df['check']=[y[0]<=x<=y[1] for x , y in zip(df.target_price,df.interval)]
Out[43]: [False, False, False, False]
</code></pre>
<p>If it is interval </p>
<pre><code>df['check']=[x in y for x , y in zip(df.target_price,df.interval)]
</code></pre>
<p>---More info </p>... | pandas | 1 |
372,002 | 54,616,753 | Calculating readmission rate | <p>I am fairly new to Python and I am trying to calculate if a patient was readmitted to the hospital within 30 days or not. </p>
<p>The data is in the form of Pandas dataframe with columns for Patient Id, Arrival Date, Departure Date and Status (Discharged, Admitted, Did Not Wait). The question is similar to this pas... | <p>You can use the below:</p>
<pre><code>df.groupby('Patient').apply(lambda x : (x['Admission Date'].\
shift(-1)-x['Discharge date']).dt.days.le(30).astype(int)).reset_index(drop=True)
</code></pre>
<p><strong>Full code</strong>:</p>
<p>Considering the df looks like:</p>
<pre><code> Visit Patient Admission D... | python|python-3.x|pandas|dataframe | 2 |
372,003 | 54,310,257 | How to zip two lists of tuples by row? | <p>I have two lists like so:</p>
<pre><code>list1 = [{'id':'1','id2':'2'},{'id':'2','id2':'3'}]
list2 = [{'fname':'a','lname':'b'},{'fname':'c','lname':'d'}]
</code></pre>
<p>How do I combine the lists into one set of tuples for a pandas dataframe?</p>
<p>like so:</p>
<pre><code>final_list = [{'id':'1','id2':'2','f... | <p>A "pure" Python answer (ie no Pandas):</p>
<pre><code>[{**x[0], **x[1]} for x in zip(list1, list2)]
> [{'id': '1', 'id2': '2', 'fname': 'a', 'lname': 'b'},
{'id': '2', 'id2': '3', 'fname': 'c', 'lname': 'd'}]
</code></pre>
<p>Edited by Scott Boston</p>
<pre><code>pd.DataFrame([{**x[0], **x[1]} for x in zi... | python|python-3.x|pandas|list|dataframe | 5 |
372,004 | 54,291,381 | Why is there a problem when loading saved weights on a model | <p>I'm trying to modify a classifier model with many tools (dropout, autoencoder, etc...) to analyse what gets the best results. Thus, I am using the <code>save_weights</code> and <code>load_weights</code> methods. </p>
<p>The first time I am launching my model, it works fine. However when loading the weights, the <co... | <p>To restart a training for a model, which was already used by the <code>fit()</code> function, you have to recompile it. </p>
<pre><code>model.compile(optimizer='adam', loss = 'categorical_crossentropy', metrics = ['acc'])
</code></pre>
<p>The reason why is that the model has an optimizer assigned, which is in alre... | tensorflow|keras|google-colaboratory | 1 |
372,005 | 54,429,176 | Pandas DataFrame max, min and mean fails on columns with Nan | <p>I am trying to compute the max, min and mean of every column in a pandas DataFrame. I am however running into some trouble sanitizing my columns.</p>
<p>One of my columns contains some "?"s instead of a value I tried to clean this by doing:</p>
<pre><code>df = pd.read_csv("Auto.csv")
df["horsepower"].replace("?",... | <p>As I mentioned in comment above , <code>dropna</code> will drop the entire row when there are any <code>NaN</code> values in it </p>
<pre><code>df = pd.read_csv("Auto.csv")
df["horsepower"].replace("?", np.nan, inplace=True)
df["horsepower"]=pd.to_numeric(df["horsepower"],errors='coerce')
</code></pre>
<p>Using <... | python|pandas|numpy | 2 |
372,006 | 54,457,331 | How to type a variable that is passed to numpy.asarray to produce a 2D float array? | <p>I often write functions/methods that take some variable which can come in many forms, i.e., lists of lists, lists of tuples, tuples of tuples, etc. all containing numbers, that I want to convert into a numpy array, kinda like the following:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def... | <p>Try the <a href="https://github.com/numpy/numpy-stubs" rel="nofollow noreferrer">numpy-stubs: experimental typing stubs for NumPy</a>.</p>
<p>It defines the type of the <code>np.array()</code> function like this:</p>
<pre class="lang-py prettyprint-override"><code>def array(
object: object,
dtype: _DtypeLi... | python|numpy|type-hinting|mypy | 1 |
372,007 | 54,583,072 | Pandas read_sql - ignoring error if table does not exist | <p>I have a list of SQL scripts I have narrowed down and want to execute. The data in the list follows this pattern more or less:</p>
<pre><code>[DROP TABLE ABC ....;, CREATE TABLE ABC ....;, INSERT INTO TABLE ABC .....;,UPDATE TABLE ABC .....;]
</code></pre>
<p>Then it repeats itself for the next table. All of thi... | <p>I figured it out, thanks to a combo of comments above. First, my Try/Except was in the incorrect location and also I switched from using pandas read_sql to just using regular session execute and it worked as expected. If table exists, drop it first, if not then create it.</p>
<p>Revised code below:</p>
<pre><cod... | python|pandas|teradata | 1 |
372,008 | 54,370,302 | Changing the order of entries for a geopandas choropleth map legend | <p>I am plotting a certain categorical value over the map of a city. The line of code I use to plot is the following:</p>
<pre><code>fig = plt.figure(figsize=(12, 12))
ax = plt.gca()
urban_data.plot(column="category", cmap="viridis", ax=ax, categorical=True, /
k=4, legend=True, linewidth=0.5, /
... | <p>The bad news is that categories in legends produced by geopandas are sorted and this is hardcoded (<a href="https://github.com/geopandas/geopandas/blob/ddaa26fdba668a9afb53d9fd86158e6d25dc5ead/geopandas/plotting.py#L449" rel="noreferrer">see source-code here</a>).</p>
<p>One solution is hence to have the categorica... | python|matplotlib|legend|geopandas|choropleth | 5 |
372,009 | 54,514,564 | Python and pandas pivot table sum between dates | <p>I have a pivot table which I have created using:</p>
<pre><code>df = df[["Ref", # int64
"REGION", # object
"COUNTRY", # object
"Value_1", # float
"Value_2", # float
"Value_3", # float
"Type", # object
"Date", # float64 (may need to convert to date)
]... | <p>First use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a> with column <code>Year</code> and then aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow nore... | python-3.x|pandas|pivot-table | 2 |
372,010 | 54,452,973 | Pandas Dataframe TypeError: translate() takes exactly one argument (2 given) | <p>I am trying to delete punctuation and numbers to my pandas dataframe. here is my sample of code : </p>
<pre><code>import re
import string
df.text = df.text.apply(lambda x: x.lower())
df.text = df.text.apply(lambda x: x.translate(None, string.punctuation))
</code></pre>
<p>and it gives me error : </p>
<blockquote>... | <p>You can use pandas' built-in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.translate.html" rel="nofollow noreferrer"><code>Series.str.translate</code></a>:</p>
<pre><code>In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'text': ['f!!o..o!', 'b""a??r', 'b?.?a!.!z']})
I... | python|pandas|python-2.7|dataframe | 1 |
372,011 | 54,430,260 | Pandas: Add a scalar to multiple new columns in an existing dataframe | <p>I recently answered a question where the OP was looking multiple columns with multiple different values to an existing dataframe (<a href="https://stackoverflow.com/a/54421876/6163621">link</a>). And it's fairly succinct, but I don't think very fast.</p>
<p>Ultimately I was hoping I could do something like:</p>
<... | <p>Why not using <code>assign</code> </p>
<pre><code>df.assign(**dict.fromkeys(['b','c'],0))
Out[781]:
a b c
0 1 0 0
1 2 0 0
</code></pre>
<p>Or create the <code>dict</code> by <code>d=dict(zip([namelist],[valuelist]))</code></p> | python|pandas|dataframe | 1 |
372,012 | 54,351,019 | numpy matrix multiplication raises weird error | <p>The following surprisingly fails:</p>
<pre><code># in a loop
.
try:
pressure_book[element] = c @ np.matrix([1] + point).T
except TypeError as e:
print(c, type(c), d.type)
print(point, type(point))
raise e
.
.
</code></pre>
<p>And outputs:</p>
<pre><code>[[-1.52088384e+08 5.39161089e+03 9.0857665... | <p>It seems that depending on what<sup>1</sup> <code>point</code> contains, the conversion to <code>numpy.matrix</code> with the <code>dtype</code> unspecified might yield <code>object</code>.</p>
<p><code>object</code>-<code>dtype</code> arrays \ matrices do not support matrix multiplication.</p>
<p>To solve this is... | python|python-3.x|numpy|matrix-multiplication | 0 |
372,013 | 54,402,611 | How to properly build a tensor array dataset from a series of single values - tensorflow newbie | <p>I'm new to tensorflow and the dataset APIs. looks like I'm not feeding the correct lists of dicts to the tensorflow. I get the following output:</p>
<pre><code>tensorflow.python.framework.errors_impl.InvalidArgumentError: In[0] is not a matrix. Instead it has shape [] [Op:MatMul]
</code></pre>
<p>My code is:</p>
... | <p>I have few observations:</p>
<p>1) As far as I understood, the problem is with the format of the data you fill in.
In the comments you said that your CSV file has a (100, 2) shape.
However, you have specified a 10 nodes input layer. So, your neural network is expecting to receive 10 variables as input, but you onl... | python|tensorflow|tensorflow-datasets | 0 |
372,014 | 54,417,710 | add a column in Pandas | <p>I have problems to add a specific column "happiness_average" form variable pd_dictionnary of type "pandas" to another variable <code>pd_dictionnary_treat</code> of type "pandas"</p>
<p>I tried to tape <code>pd_dictionnary_treat.append(pd_dictionnary["happiness_average"]</code>) in my code below: </p>
<pre><code>i... | <p>Why are you use <code>append</code> function?
You can directly add at the time of assigning <code>word</code> column to <code>pd_dictionnary_treat</code>.
I think this will help you:</p>
<pre><code>import pandas as pd
pd_dictionnary=pd.read_csv("/Users/stefanhanssen/Dropbox/hse/word_list/131278/Data_Set_S1.txt",sep... | python|pandas | 0 |
372,015 | 73,585,171 | How to add a timestamp as the last column of an existing Pandas DataFrame | <p>I was looking for the most Pythonic solution available, but didn't see it published anywhere to my liking, so am submitting this as a self-answered question.</p> | <pre><code>df.insert(df.columns.size, 'createts', pd.to_datetime('now').replace(microsecond=0))
</code></pre> | python|pandas|dataframe | 0 |
372,016 | 73,813,382 | Pandas - take maximum/minimum of columns within group | <p>I have a Pandas dataframe df with column names par1,par2,..,par7.
I want to select a subset of the total dataframe.
Within the group par1,par2,par3 I want to select the rows for which par4 has the lowest value and par5 has the highest value in that group.
So from the dataframe:</p>
<pre><code>Par1,Par2,Par3,Par4,Par... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>Dat... | pandas | 1 |
372,017 | 73,785,154 | Plotting multiple y-values versus x using Matplotlib | <p>I am trying to plot <code>y1,y2,y3</code> all as a function of <code>x</code> and show all the three on a single plot. But it is showing only two plots. I present the current output.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-1,0,10)
print(x)
y1=36.554+5.418*np.exp(-1.327*x)
y2... | <p>Try this:</p>
<pre><code>plt.plot(x, y1, x, y2, x, y3)
</code></pre> | python|numpy|matplotlib | 1 |
372,018 | 73,739,854 | How to merge semi-duplicated rows in a Dataframe | <p>I have a dataframe that looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">ID</th>
<th style="text-align: center;">Name</th>
<th style="text-align: center;">app_A</th>
<th style="text-align: center;">app_B</th>
<th style="text-align: center;">app... | <p>Simple..aggregate <code>app</code> like columns with <code>sum</code> and <code>Total</code> with <code>first</code></p>
<pre><code>c = df.filter(like='app_')
df.groupby(['ID', 'Name']).agg({**dict.fromkeys(c, 'sum'), 'Total': 'first'})
</code></pre>
<h4>Result</h4>
<pre><code> app_A app_B app_C ... | python|pandas|dataframe|merge|duplicates | 2 |
372,019 | 73,799,999 | Issues with datetime and isinstance() | <p>I want to find if any variable in a dataset is a datetime. I'm having some serious problems with this seemingly simple task. In the dataset below, 'time' is transformed to datetime using pandas to_datetime(). It becomes a datetime64[ns] type, and, if I'm reading the documentation correct, to_datetime() should return... | <p>IIUC select one value to scalar, in your solution pass <code>Series</code>, so correctly failed:</p>
<pre><code>print(isinstance(df.time.iat[0], datetime.datetime))
True
</code></pre> | python|pandas|datetime | 2 |
372,020 | 73,656,968 | How to plus a number to a specific cell in pandas dataframe | <p>I am trying to +1 to a cell in pandas dataframe</p>
<pre><code>staff['pax'][0]= staff['pax'][0]+1
</code></pre>
<p>staff is the dataframe name, pax is the column name while 0 is the row I want to +1.
However below is the error..</p>
<pre><code>A value is trying to be set on a copy of a slice from a DataFrame
See th... | <p>Please refer this documentation <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.at.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.at.html</a></p>
<pre><code>df.at[0, 'pax'] = df['pax'][0]+1
</code></pre> | python|pandas|dataframe | 1 |
372,021 | 73,673,387 | How to I make a PyQtGraph scrolling graph clear the previous line within a loop | <p>I wish to plot some data from an array with multiple columns, and would like each column to be a different line on the same scrolling graph. As there are many columns, I think it would make sense to plot them within a loop. I'd also like to plot a second scrolling graph with a single line.</p>
<p>I can get the sing... | <p>You <em>could</em> clear the plot of all curves each time with <code>.clear()</code>, but that wouldn't be very performant. A better solution would be to keep all the curve objects around and call <code>setData</code> on them each time, like you're doing with the single-curve plot. E.g.</p>
<pre class="lang-py prett... | python|numpy|pyqtgraph | 0 |
372,022 | 73,769,086 | How to use multiple background colors for different string value in a particular row of csv file | <p>I have CSV file with multiple columns and I am searching some string in column 5 and highlighting the row for diffrent string.
As of now I am able to use just two colours but I want to use more colors for more string into it.
Example for</p>
<pre><code> x['4']="abc" --->I want to use yellow color
... | <p>Create dictionary for background colors by values and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.applymap.html" rel="nofollow noreferrer"><code>Styler.applymap</code></a> for mapping by <code>dict.get</code>, if no match is returned empty value:</p>
<pre... | python|pandas|dataframe|csv|data-analysis | 0 |
372,023 | 73,652,149 | Reducing the column to one element? | <p>I see a code like this:</p>
<pre><code>boston=datasets.load_boston()
X=boston.data[:, None, 6]
y= boston.target
</code></pre>
<p>The site says "To match the X and y dimensionality the X is reduced to 1 element in each row, by the following code". How is it 1 element? I am a total newbie in this field.</p>... | <p>Take a look at X:</p>
<pre><code>from sklearn import datasets
boston=datasets.load_boston()
X=boston.data[:, None, 6]
y= boston.target
X[:10]
</code></pre>
<p>It looks like this:</p>
<pre><code>array([[ 65.2],
[ 78.9],
[ 61.1],
[ 45.8],
[ 54.2],
[ 58.7],
[ 66.6],
[ ... | pandas|dataframe | 0 |
372,024 | 73,709,128 | Interconversion and difference | <p>I have two types of tensors.</p>
<pre><code>1) <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
2) <class 'tensorflow.python.framework.ops.Tensor'>
</code></pre>
<p>What is the difference between the two? Can interconversion be done? In particular if I want to convert the second typ... | <p>A <a href="https://www.tensorflow.org/api_docs/python/tf/Tensor" rel="nofollow noreferrer"><code>tf.Tensor</code></a> is basically a multidimensional array of elements, while a <code>tf.ResourceVariable</code> is pretty much like a <a href="https://stackoverflow.com/q/40817665/14774959">fancier</a> <a href="https://... | loops|tensorflow|type-conversion|tensor | 1 |
372,025 | 73,701,660 | how to solve IndexError : single positional indexer is out-of-bounds | <pre><code>CODE:-
from datetime import date
from datetime import timedelta
from nsepy import get_history
import pandas as pd
import datetime
# import matplotlib.pyplot as mp
end1 = date.today()
start1 = end1 - timedelta(days=365)
stock = [
'RELIANCE'... | <p>The "out-of-bounds" error indicates you're trying to access a part of the dataframe series that doesn't exist. It's most likely caused by df['D_vol'] being less than 90 items long when you try to do</p>
<pre><code>df['D_vol'].iloc[-91:-1]
</code></pre>
<p>Edit:
add a length check before the offending line:... | python|pandas|numpy|datetime | 1 |
372,026 | 73,673,540 | Understanding the [:,1] in tf.stack | <p>Hello I am new to python and tensorflow. I read the code about swapping x and y coordiantes from bounding boxes and i am not sure if i understand the code correctly.</p>
<pre><code>def swap_xy(boxes):
return tf.stack([boxes[:, 1], boxes[:, 0], boxes[:, 3], boxes[:, 2]], axis=-1)
</code></pre>
<p>with tf.stack I pac... | <p>well this : is use to select all value
example</p>
<pre><code>lst=[1,2,3,4]
print(lst[:2])
#output
[1,2]
</code></pre> | python|tensorflow | 0 |
372,027 | 73,825,153 | Subtract values from different groups | <p>I have the following DataFrame:</p>
<pre><code> A X
Time
1 a 10
2 b 17
3 b 20
4 c 21
5 c 36
6 d 40
</code></pre>
<p>given by <code>pd.DataFrame({'Time': [1, 2, 3, 4, 5, 6], 'A': ['a', 'b', 'b', 'c', 'c', 'd'], 'X': [10, 17, 20, 21, 36, 40]}).set_index('Time')</code></p>
<p>The de... | <p>Aggregate by <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> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nofollow noreferrer"><code>... | pandas|numpy | 3 |
372,028 | 73,638,557 | Pandas DataFrame: Based on a string in a row of col 'C', look that value up in col 'A', if found return the value of col 'B' for that matched row | <p>I'm looking for a cleaner solution to this problem than the one I have come up with:</p>
<p>Based on the string value of a row in column 'C', look that value up in the string values of column 'A', and if found return the string value of column 'B' for that row.</p>
<p>I have a df that looks like this (notice loc[1][... | <p>I prefer to apply a function in these scenarios:</p>
<pre><code>def find_value(row: pd.Series) -> pd.Series:
val = df.query("@df['A'] == @row['C']")
return row["B"] if val.empty else val["B"].squeeze()
df["BB"] = df.apply(lambda x: find_value(x), axis=1)
</code><... | python|pandas|dataframe|merge|lookup | 0 |
372,029 | 73,733,590 | Pandas - drop rows based on two conditions on different columns | <p>Although there are several related questions answered in Pandas, I cannot solve this issue. I have a large dataframe (~ 49000 rows) and want to drop rows the meet two conditions at the same time(~ 120):</p>
<ul>
<li>For one column: an exact string</li>
<li>For another column: a NaN value</li>
</ul>
<p>My code is ign... | <p>Instead of calling <code>drop</code>, and passing the <code>index</code>, You can create the mask for the condition for which you want to keep the rows, then take only those rows. Also, the logic error seems to be there, you are checking two different condition combined by <code>AND</code> for the same column values... | python|pandas|conditional-statements | 2 |
372,030 | 73,805,458 | PyTorch Datapipes and how does overwriting the datapipe classes work? | <p>Pytorch Datapipes are a new inplace dataset loaders for large data that can be fed into Pytorch models through streaming, for reference these are</p>
<ul>
<li>Official Doc: <a href="https://pytorch.org/data/main/tutorial.html" rel="nofollow noreferrer">https://pytorch.org/data/main/tutorial.html</a></li>
<li>A crash... | <p>It looks like you're trying to chain together a series of torch <code>DataPipe</code>s, namely:</p>
<ol>
<li><a href="https://pytorch.org/data/0.4/generated/torchdata.datapipes.iter.FileOpener.html" rel="nofollow noreferrer">FileOpener</a> / <code>open_files</code></li>
<li><a href="https://pytorch.org/data/0.4/gene... | python|machine-learning|pytorch|dataset|torchdata | 1 |
372,031 | 73,680,250 | Parquet File Encoding - Storing Azure Blob Storage - Failing with Error Error:encoding RLE_DICTIONARY is not supported | <p>I have a pandas dataframe(after pivoted) which i am trying to save the file as parquet and store it in azure blob storage . The file is getting stored in the storage account, however when i try to read the parquet file, i am getting the error - "encoding RLE_DICTIONARY is not supported." Can some one help ... | <p>After reproducing from my end, I could able to make this work by uploading Iterable data using <code>upload_blob</code>. In my case I'm iterating over the Bytes of the file. Below is the code that worked for me.</p>
<pre><code>from azure.storage.blob import BlobServiceClient
import pandas as pd
storage_account_name... | python|pandas|dataframe|azure-blob-storage|parquet | 0 |
372,032 | 73,613,734 | Use modulo with numbers greater than 64bit integer in numpy/numba | <p>I‘m trying to implement a prime factorization algorithm leveraging the GPU/CUDA for parallelization as a pet project.</p>
<p>I‘m using python with numpy and numba for the parallelization part.</p>
<p>My problem is now that I hit the 64 bit integer boundary quite fast and I am searching for solutions to work around t... | <p>You can reduce the dividend much more efficiently using modulus thanks to basic congruent identity rules. Indeed:</p>
<pre><code>Assuming:
a ≡ x [d]
b ≡ y [d]
c ≡ z [d]
Then:
a * b + c ≡ x * y + z [d]
</code></pre>
<p>This is an interesting property if <code>d</code> is small. Additionally, all number can b... | python|numpy|math|cuda|numba | 1 |
372,033 | 73,621,359 | How to obtain source tables from a merged table (Cypher/SQL/Pandas)? | <p>Suppose I have the following table--</p>
<pre><code>PersonID | cityID_which_personID_likes | city_longitutde | city_latitude | city_country
</code></pre>
<p>And I would like to obtain the following two tables--</p>
<pre><code>A) PersonID | cityID_which_personID_likes
B) cityID | city_longitutde | city_latitude | cit... | <p>you can select a subset of a dataframe like so :</p>
<pre><code>df = pd.dataframe({..;})
subset_1= df [["PersonID" , "cityID_which_personID_likes"]]
subset_2= df [["cityID" , "city_longitutde ", "city_latitude", "city_country"]]
</code></pre>
<p>more info ... | sql|pandas|rdbms | 0 |
372,034 | 73,769,707 | Splice two different dataframes based on similar value | <p>I have two dataframes with different dimensions. Lets say it´s displacement measurements but the readings are slightly different values and one has more data. Looks like this:</p>
<p>df1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Index</th>
<th>displacement</th>
</tr>
</thead>
<tbod... | <p>I used the <strong>merge_asof</strong> function to find the nearest value base on two DataFrames' <strong>displacement</strong> columns, and then filtered the resulting DataFrame by a threshold.</p>
<pre><code>df1['displacement'] =df1['displacement'].astype(float)
df1 = df1.drop_duplicates('displacement', keep='last... | python|pandas|dataframe|merge | 2 |
372,035 | 73,805,047 | Highlight duplicate rows in Pandas | <p>I'm trying to highlight duplicate rows in several dataframes and export them to excel after. It seems to work when I do it with one dataframe, but as soon as I apply it to another dataframe is highlights the index from the last dataframe for all of them.</p>
<p>Here is my code:</p>
<pre><code>import pandas as pd
imp... | <p>You can use:</p>
<pre><code>def highlight_yellow(df, cols):
style = 'background-color: yellow'
a = np.broadcast_to(np.where(df.duplicated(subset=cols), style, '')[:,None], df.shape)
return pd.DataFrame(a, index=df.index, columns=df.columns)
df.style.apply(highlight_yellow, cols=['colB'], axis=None)
<... | python|pandas|dataframe|numpy | 1 |
372,036 | 73,535,844 | How to split a string column into two column by varying space delimiter on its last occurence | <p>I am trying a way to split a string column in python to two different columns by space delimiter. I have tried with below code:</p>
<pre><code>df[['A', 'B']] = df['AB'].str.split(' ', 1, expand=True)
</code></pre>
<p>But this will work only if the space delimiter is having only single space. I would like to know if ... | <p>You can use this regex to split on:</p>
<pre><code>\s+(?!.*\s)
</code></pre>
<p>This looks for a sequence of spaces which has no spaces after it in the string, so will only split into two values at most.</p>
<p>Usage:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'AB': ['aa bb cc', 'dd ee ... | python|python-3.x|pandas|dataframe | 1 |
372,037 | 73,655,140 | Converting a TF model to TFLite and then to EdgeTPU | <p>I am trying to take a simple keras model with an Add operation and convert to TFLite and then to EdgeTPU.
Quantization for int8 needs to take place, but depending on the conversion parameters provided it results in either an unsupported operation FlexAddV2, or unsupported data type int32, or an error with AddV2 Erro... | <p>This was resolved here:
<a href="https://github.com/google-coral/edgetpu/issues/655" rel="nofollow noreferrer">https://github.com/google-coral/edgetpu/issues/655</a></p>
<p>Here is the python conversion code to accomplish this:</p>
<pre><code>import tensorflow as tf
from tensorflow import keras
import numpy as np
im... | tensorflow|keras|tflite|edge-tpu | 0 |
372,038 | 73,787,467 | Time since last trade on symbol | <p>I have a pandas DataFrame that contains rows. Each row represents a trade that took place on a particular symbol. The first column has the symbol name, and the second column has the time at which the trade took place. The other details about the trade (e.g., price or quantity) are not important to this question. The... | <p>My input:</p>
<pre><code>df = pd.DataFrame(
["AAPL", "GOOG", "AAPL", "MSFT", "GOOG"],
[1, 3, 6, 8, 10],
columns=["trade"]
)
</code></pre>
<p>My solution:</p>
<pre><code>for stock in df.trade.unique():
#compute the distances between actual tim... | python|pandas | 0 |
372,039 | 73,573,156 | Change Numpy array values in-place | <p>Say when we have a randomly generated 2D 3x2 Numpy array <code>a = np.array(3,2)</code> and I want to change the value of the element on the first row & column (i.e. a[0,0]) to 10. If I do</p>
<p><code>a[0][0] = 10</code></p>
<p>then it works and a[0,0] is changed to 10. But if I do</p>
<p><code>a[np.arange(1)][... | <p><code>a[x][y]</code> is <em>wrong</em>. It <em>happens</em> to work in the first case, <code>a[0][0] = 10</code> because <code>a[0]</code> returns a <em>view</em>, hence doing <code>resul[y] = whatever</code> modifies the original array. However, in the second case, <code>a[np.arange(1)][0] = 10</code>, <code>a[np.a... | python|numpy|numpy-ndarray | 4 |
372,040 | 73,560,570 | How to solve Tensorflow 1 becomes unsupported in Google Colab | <p>As Tensorflow 1 becomes unsupported in Google Colab and StyleGAN2-ADA only works with Tensorflow 1.
Can anyone help what I should do to solve this issue?</p> | <p>This <em>might</em> work, if you want to run TF1 code under a recent version of TF2</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
</code></pre>
<p>(Instead of <em>import tensorflow as tf</em>, of course)</p>
<p>In TF 2.9.1 this is available but depreca... | python|tensorflow|google-colaboratory | 0 |
372,041 | 73,691,780 | unicode decode error while importing Medical Data on pandas | <p>I tried importing a medical data and I ran into this unicode error, here is my code:</p>
<pre><code>output_path = r"C:/Users/muham/Desktop/AI projects/cancer doc classification"
my_file = glob.glob(os.path.join(output_path, '*.csv'))
for files in my_file:
data = pd.read_csv(files)
print(data)
</code></... | <p>Try other encodings, default one is utf-8</p>
<p>like</p>
<pre><code>import pandas
pandas.read_csv(path, encoding="cp1252")
</code></pre>
<p>or ascii, latin1, etc ...</p> | python|pandas|numpy|unicode | 0 |
372,042 | 73,581,508 | In pandas / python, ternary operator to replace NaN in string column with value from different column | <p>We are trying to replace NaN values that are appearing in a string column in our pandas dataframe:</p>
<pre><code>d = {'col1': [np.nan, 'Team3'], 'col2': ['Team1', 'Team2']}
dd = pd.DataFrame(data=d)
dd
</code></pre>
<p><a href="https://i.stack.imgur.com/B0Lj0m.png" rel="nofollow noreferrer"><img src="https://i.stac... | <p>Try this</p>
<pre><code>d = {'col1': [np.nan, 'Team3'], 'col2': ['Team1', 'Team2']}
dd = pd.DataFrame(data=d)
def check_missing_values(value):
if value is np.nan:
return True
return False
dd['col3'] = dd.apply(lambda row: row['col2'] if check_missing_values(row['col1']) else row['col1'], axis=1)
<... | python|pandas|dataframe | 0 |
372,043 | 73,612,885 | Numbers in three different formats | <p>I am working with a dataset; below you can see a small example.</p>
<pre><code>import pandas as pd
import numpy as np
data = {
'id':['9.','09', 9],
}
df = pd.DataFrame(data, columns = [
'id',])
df['id'] = df['id'].replace(".","")
df
</cod... | <p>You could turn them all into doubles and then into integers</p>
<pre><code>df['id'].astype('double').astype(int)
</code></pre>
<p>But this can be a problem for large numbers that exceed the 53 bit significand of the double. If the errant period is always at the end of the string, you could do</p>
<pre><code>df['id']... | python|pandas | 3 |
372,044 | 73,799,702 | finding the element in a list closest to the mean of elements in python? | <p>This is my array <code>a= [5, 25, 50, 100, 250, 500] </code>.
The mean value of a is 155 (i calculated using <code>sum(a)/len(a)</code>) but i have to store 100 in a variable instead of 155.</p>
<p>Is there any easy way to solve this problem.</p> | <p>IIUC, use <a href="https://numpy.org/doc/stable/reference/generated/numpy.argmin.html" rel="nofollow noreferrer"><code>numpy.argmin</code></a> to find the the index of the value closest to the mean by computing the absolute difference to the mean:</p>
<pre><code>a = np.array([5, 25, 50, 100, 250, 500])
out = a[np.a... | python|arrays|list|numpy|mean | 1 |
372,045 | 73,620,291 | Averaging values with if else statement of a Pandas DataFrame and creating a new resulting DataFrame | <p>I have a df which looks like this:</p>
<pre><code>A B C
5.1 1.1 7.3
5.0 0.3 7.2
4.9 1.7 7.0
10.2 1.1 7.9
10.3 1.0 7.0
15.4 2.0 7.1
15.1 1.0 7.3
0.0 0.9 7.3
0.0 1.3 7.9
0.0 0.5 7.5
-5.1 1.0 7.3
-10.3 0.8 7.3
-10.1 1.0 7.1
</code></pre>
<p>... | <p>Groups are defined by difference of values in <code>A</code> is greater like <code>5</code>, pass to <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> and aggregate <code>mean</code> with <code>std</code>:</... | python|pandas | 2 |
372,046 | 73,650,263 | Applying function after Conditional Group By in Python | <p>This is a simplified version of my problem:
given this dataset</p>
<pre><code>| link | category |
| ---- | -------- |
| 1 | 0 |
| 1 | 0 |
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 3 | 1 |
</code></pre>
<p>I would like to obtain the following:</p>
<pre><code>| link | ... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a>:</p>
<pre><code>(pd.crosstab(df['link'], ... | python|pandas|group-by|conditional-statements | 2 |
372,047 | 73,527,167 | Calculate daily and monthly averages for categories in dataframe | <p>I have the following dataframe</p>
<pre><code>date sales cat
29/4/2022 2 a
30/4/2022 5 a
30/4/2022 1 b
1/5/2022 1 a
1/5/2022 8 b
1/5/2022 4 c
1/6/2022 7 a
1/6/2022 9 b
1/6/2022 5 c
</code></pre>
<p>I... | <p>USE-</p>
<pre><code>#Monthly Average
df['monthly_avg'] = df.groupby(pd.PeriodIndex(df['date'], freq="M"))['Value'].mean()
#Daily Average
df['daily_avg'] = df.groupby(pd.PeriodIndex(df['date'], freq="D"))['Value'].mean()
</code></pre>
<p><code>This is untested code,always share reproducible code ... | python|pandas|dataframe|statistics | 0 |
372,048 | 73,695,764 | Add column from another dataframe if two column matches | <p>I am working with huge volume of data and trying to map values from two dataframe. Looking forward for better Time complexity.</p>
<p>Here I am trying to match Code from df2 which are in df1 and take MLC Code from df1 if values match.</p>
<p>df1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr... | <p>Try this</p>
<pre class="lang-py prettyprint-override"><code>df2.merge(df1[['Code', 'MLC Code']], how='left', on='Code')
</code></pre> | python|pandas|dataframe|concatenation|enumerate | 0 |
372,049 | 73,805,285 | Python Pandas Select columns contains different values | <p>I would like to select from DF columns contains only PF_20 and PF_70 values
Original Table:
<a href="https://i.stack.imgur.com/YFWF6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YFWF6.png" alt="enter image description here" /></a></p>
<p>Expected Result:</p>
<p><a href="https://i.stack.imgur.co... | <p>This might not be the fastest way to do it, but try this:</p>
<pre><code>values = ["PF_20", "PF_70"]
columns = []
for col in df.columns:
for value in values:
if value in df[col].values:
columns.append(col)
columns = set(columns) #to get rid of duplicates.
new_df = df[colum... | python|pandas|dataframe|indexing | 0 |
372,050 | 73,746,451 | How to extract the the key and values from list of dictionary? | <p>How to extract the the key and values from list of dictionary?</p>
<p>Below is my data, i want to extract the key and values from list of dictionary.</p>
<pre><code>data = [{'index': 0,
'MaterialCode': '67567412',
'DP_Category': 'HAIR CARE'},
{'index': 1,
'MaterialCode': '67567412',
'DP... | <pre class="lang-py prettyprint-override"><code>data = [
{"index": 0, "MaterialCode": "67567412", "DP_Category": "HAIR CARE"},
{"index": 1, "MaterialCode": "67567412", "DP_Category": "HAIR CARE"},
]
for idx, ele... | python|pandas | 1 |
372,051 | 73,807,196 | numpy: efficient sum of kronecker products | <ul>
<li>I have three sets of matrices {A_i}, {B_i}, and {C_i} with n matrices in each set</li>
<li>The A_i are of dimension l x m, the B_i are of dimension m x o and the C_i are of dimension p x q</li>
<li>I would like to compute the following: <a href="https://i.stack.imgur.com/jEdHs.png" rel="nofollow noreferrer"><i... | <p>As suggested, I had a look into <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html" rel="nofollow noreferrer">numpy.einsum</a>. This turned out to be quite nice. A solution is:</p>
<pre><code>np.einsum('ijk,imn->jmkn', np.einsum('ijk,ikm->ijm', A, B), C).reshape(A.shape[1] * C.shape[1]... | numpy|vectorization|kronecker-product | 1 |
372,052 | 73,573,038 | Recording the real time face expression detection | <p>I have coded the face expression detection using <code>Jupyter notebook</code>, detecting seven expressions of the face (Anger, Sad, Disgust, Happy, ...) and tried the real-time detection using the camera of my laptop. Now I want to record those expressions detected by the model in the real-time detection and create... | <p>You could do something like this:</p>
<pre><code>from tensorflow import keras
import cv2
all_labels = ["Anger", "Sad", "Disgust", "Happy"]
# load the trained model, or train a model
model = keras.models.load_model('path/to/location')
# Open the camera
cap = cv2.VideoCaptur... | python|tensorflow|keras|jupyter-notebook|tf.keras | 1 |
372,053 | 73,822,435 | Pandas: How to convert list to data frame | <p>This is code that I have</p>
<pre><code>import pandas as pd
data = [[1,"credit"],[1,"cash"],[1,"credit"],[2,"credit"],[2,"credit"],[2,"credit"],[3,"credit"],[3,"credit"],[3,"credit"]]
df = pd.DataFrame(data, columns=['account_... | <p>Before using groupby, you can do a filtering process to filter out rows of not credit.</p>
<pre><code>result = df[df['type'] == 'credit'].groupby('account_id').value_counts()
account_id type
1 credit 2
2 credit 3
3 credit 3
dtype: int64
</code></pre>
<p>You can use <code>re... | python|pandas|dataframe | 0 |
372,054 | 73,585,293 | Switch between the heads of a model during inference | <p>I have 200 neural networks which I trained using transfer learning on text. They all share the same weights except for their heads which are trained on different tasks. Is it possible to merge those networks into a single model to use with Tensorflow such that when I call it with input (text, i) it returns me the pr... | <p>You probably have a model like the following:</p>
<pre><code># Create the model
inputs = Input(shape=(height, width, channels), name='data')
x = layers.Conv2D(...)(inputs)
# ...
x = layers.GlobalAveragePooling2D(name='penultimate_layer')(x)
x = layers.Dense(num_class, name='task0', ...)(x)
model = models.Model(input... | tensorflow|deep-learning | 1 |
372,055 | 73,742,257 | Python (numpy?) - build transformation matrix from sets of source and destination points | <p>Let's imagine I have two sets points in a 2d Euclidean system:</p>
<pre><code>src = [
[722.6, 1571.4],
[832, 1466],
[419, 1482],
[1005, 2804],
<snip>
]
dst = [
[35839.65, 49808.55],
[42771.08, 41488.07],
[15764.26, 44065.95],
[72760.36, 76645.15],
<snip>
]
</code><... | <p>You are probably looking for a <em>rigid registration</em>, which aligns the point sets allowing rotation and translation, or you may be looking for an <em>affine registration</em>, which also allows changes in scale, shear or reflection.</p>
<p>You can use the function <a href="https://matthew-brett.github.io/trans... | python|numpy|matrix|2d|transformation | 1 |
372,056 | 73,622,517 | pandas group by custom column | <p>For example, I have a following df:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>score</th>
<th>var1</th>
</tr>
</thead>
<tbody>
<tr>
<td>0.465</td>
<td>jack, jones, phil</td>
</tr>
<tr>
<td>0.712</td>
<td>don, sam, bob</td>
</tr>
<tr>
<td>0.112</td>
<td>jones, alex, sam</td>
</tr>
</... | <p>You can try</p>
<pre class="lang-py prettyprint-override"><code>out_ = (df.assign(score=df['score'].round(1),
var1=df['var1'].str.split(', '))
.explode('var1'))
out = pd.crosstab(out_['var1'], out_['score'])
</code></pre>
<pre><code>print(out_)
score var1
0 0.5 jack
0 0.5 jones... | python|pandas | 1 |
372,057 | 71,242,456 | Saving accuracy and loss with callback on colab | <p>So im trying to train a model on colab, and it is going to take me roughly 70-72 hr of continues running. I have a free account, so i get kicked due to over-use or inactivity pretty frequently, which means I cant just dump history in a pickle file.</p>
<pre><code>history = model.fit_generator(custom_generator(train_... | <p>Think you want to write your callback as follows</p>
<pre><code>class STOP(tf.keras.callbacks.Callback):
def __init__ (self, model, csv_path, model_save_dir, epochs, acc_thld): # initialization of the callback
# model is your compiled model
# csv_path is path where csv file will be stored
... | python|tensorflow|google-colaboratory|tf.keras|custom-training | 0 |
372,058 | 71,211,208 | How can I obtain a cell value from the last line of a list? | <p>I'm struggling to figure out how, using Pandas, to obtain the last value in the second column of a list which is updating regularly (i.e. an every increasing list over time) and assign that to a value.</p>
<pre><code> 1 2
15 21/02/2022 18:07:40 38055.3966
16 21/02/2022 18:07:49 ... | <p>One approach is to use <code>iloc</code>. For example, <code>df.iloc[-2,1]</code> gives the second to last entry of the second column.</p> | python|pandas|dataframe | 1 |
372,059 | 71,100,624 | Check if columns have a nan value if certain column has a specific value in Dataframe | <p>I'm trying to add column in Dataframe which has a result of checking if other columns have value in it.</p>
<p>This is a test df I made:</p>
<pre><code>df = pd.DataFrame({"condition":[1,np.nan,np.nan,np.nan,1],"a":[np.nan,4,5,6,np.nan],"b":[np.nan,2,"e",2,np.nan],"c"... | <p>so you have an if-elif-else situation. Then we can use <code>np.select</code> for it. It needs the conditions and what to do when they are satisfied:</p>
<ul>
<li>your if is: "condition is 1 and a,b,c has all nan"</li>
<li>your elif is: "condition is nan"</li>
<li>what remains is else, as us... | python-3.x|pandas|dataframe | 1 |
372,060 | 71,178,104 | In pytorch, torch.unique is returning repititions | <p>I have this 2-D tensor:</p>
<pre><code>tmp = torch.tensor([[ 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5,
5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11,
11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 17,
17, 17, 18, ... | <p>It is because you specified <code>dim=1</code>. PyTorch is thus checking for unique <em>pairs</em> (which it correctly does). Like (0, 0), (1, 1), (16, 0): these are the unique pairs that it generated. In general the pair <code>(temp[0,i], temp[1,i])</code> is unique for all <code>i</code>.</p>
<p>If you want all th... | pytorch | 0 |
372,061 | 71,321,630 | How to convert each row of a dataframe to new column use concat in python | <p>If I have dataframes,</p>
<pre><code>df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "C2", "C3"],
... | <p>IIUC, you could <code>stack</code> the individual dataframes, <code>concat</code> and reshape:</p>
<pre><code>dfnew = pd.concat([df1.stack(), df2.stack()]).droplevel(0).to_frame().T
</code></pre>
<p>output:</p>
<pre><code> A B C D A B C D A B C D A B C D A B C D A B C ... | python|pandas|concatenation | 3 |
372,062 | 71,319,221 | Merging data from a separate .csv file using Pandas | <p>I want to create two new columns in job_transitions_sample.csv and add the wage data from wage_data_sample.csv for both Title 1 and Title 2:</p>
<p>job_transitions_sample.csv:</p>
<pre><code> Title 1 Title 2 Count
0 administrative assistant office manager 20
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> by dictionary <code>d</code> - cannot use <code>dict</code> for varialbe name, because python code name:</p>
<pre><code>df = pd.read_csv('job_transitions_sample.csv')
w... | python|python-3.x|pandas|csv | 1 |
372,063 | 71,211,177 | How to export an Excel file from a dictionary? | <p>I want to make an excel file from a dictionary that I have.
It simply is an dictionary with information about images, like the size, how many paragraphs, how many words, etc.</p>
<p>Let's say the dictionary is:</p>
<pre><code>{'Screenshot_1.jpg': {'SIZE': 214649,
'HEIGHT': 664,
... | <p><code>pandas</code> has <code>to_csv</code> function to export dataframe as a .csv file, as follows:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
dict1 = {'Screenshot_1.jpg': {'SIZE': 214649, 'HEIGHT': 664, 'WIDTH': 1351, 'PARAGRAPHS': 3, 'WORDS': 427,
'Parag... | python|excel|pandas|dataframe|dictionary | 1 |
372,064 | 71,346,892 | how to match a string from a list of strings and ignoring regex special characters? | <p>I have this string:</p>
<pre><code>d = {'col1': ['Digital Forms - how to spousal information on DF 2,0']}
</code></pre>
<p>I turned it into a dataframe :</p>
<pre><code>df = pd.DataFrame(d)
</code></pre>
<p>From this dataframe, I want to match this list of words:</p>
<pre><code>wordlist = ['Digital Forms', 'how', 's... | <p>You may form a regex alternation from your word list using <code>re.escape</code> to escape the metacharacters:</p>
<pre class="lang-py prettyprint-override"><code>wordlist = ['Digital Forms', 'how', 'spousal', 'DF 2.0']
regex = r'\b(' + '|'.join([re.escape(x) for x in wordlist]) + r')\b'
words = df['col1'].str.find... | python|pandas|dataframe | 3 |
372,065 | 71,119,338 | How to find the intersection between two columns from two different dataframes | <p>I'm trying to compare two different columns from two different DataFrames.</p>
<pre><code>test_website1
Domain
0 www.google.com
1 www.facebook.com
2 www.yahoo.com
test_website2
Domain
0 www.bing.com
1 www.instagram.com
2 www.google.com
</code></pre>
<hr />
<pre><cod... | <p>The standard way to do this in pandas is an inner <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> (default is <code>how='inner'</code>):</p>
<pre><code>pd.merge(df1['Domain'], df2['Domain'])
# Domain
# 0 www.google.com
<... | python|pandas|dataframe | 1 |
372,066 | 71,388,201 | Checking a Column of Lists Against Another Column of Lists and Returning Multiple Column Values | <p>I am comparing the list values of <code>sb_list</code> against <code>psr_list</code>. If all list items from <code>sb_list['ASINs']</code> are found in any of the lists from <code>psr_list['Child ASIN']</code>, <code>sb_list['bucket']</code> is marked <code>'clean'</code>. This part of the code is running fine...</p... | <p>You could use <code>set.issubset</code> in a list comprehension to check if any list in <code>sb_list</code> is contained in any list in <code>psr_list</code>. If a list exists, then get "Group" value where it exists, if not fill in with <code>""</code>. Note that this assumes only one list in <c... | python|pandas|dataframe|numpy | 1 |
372,067 | 71,399,557 | Unique combination of two columns in Pandas | <p>I would like to keep the unique combination of two columns. For example, A and B is the same as B and A.</p>
<pre><code>df = pd.DataFrame({'col1': [1,2,4,3], 'col2': [2,1,3,4]})
col1 col2
0 1 2
1 2 1
2 4 3
3 3 4
</code></pre>
<p>Desired outcome:</p>
<pre><code> c... | <p>You can do <code>np.sort</code> then <code>drop_duplicates</code></p>
<pre><code>df[:] = np.sort(df.values,1)
out = df.drop_duplicates()
Out[625]:
col1 col2
0 1 2
2 3 4
</code></pre> | python|pandas | 0 |
372,068 | 71,211,228 | Problem with pytorch hooks? Activation maps allways positiv | <p>I was looking at the activation maps of vgg19 in pytorch.
I found that all the values of the maps are positive even before I applied the ReLU.</p>
<p>This seems very strange to me... If this would be correct (could be that I not used the register_forward_hook method correctly?) why would one then apply ReLu at all?<... | <p>You should <a href="https://pytorch.org/docs/stable/generated/torch.clone.html" rel="nofollow noreferrer"><code>clone</code></a> the output in</p>
<pre><code>def get_activation(name):
def hook(model, input, output):
activation[name] = output.detach().clone() #
return hook
</code></pre>
<hr />
<p>Note... | python-3.x|pytorch | 1 |
372,069 | 71,416,560 | How to get y_train in model | <p>For some reason I need to use y_train (the target) in my model (not only in loss function), but I didn't find a way to get it.</p>
<p>I get my training dataset like this:</p>
<pre><code> train_ds = DataGenerator("train", args).fetch()
<PrefetchDataset shapes: ((2, None), (2, 4000, 22)), types: (tf.f... | <p>Hi guys I just find some ways to solve this.</p>
<ol>
<li><p>Use tf.concat() to concatenate the data in y_train to x_train and
send them together into the model, them separate them. But the
dimension of both thing should be the same. (My input and target
don't have the same size so I didn't try this.)</p>
</li>
<li>... | python|tensorflow|keras | 0 |
372,070 | 71,169,941 | Error with installation of pycocotools for Detr Tensorflow | <p>I'm trying to use Detr Tensorflow models and need to install pycocotools. On a Windows 10 PC, I'm executing this in a Visual Studio Code. I'm following the steps provided in this
GitHub repo : <a href="https://github.com/Visual-Behavior/detr-tensorflow#install" rel="nofollow noreferrer">https://github.com/Visual-Be... | <p>The solution is in the error output.</p>
<p>You need to install Microsoft C++ Build Tools.</p> | tensorflow|pycocotools | 0 |
372,071 | 71,336,067 | How to freeze some layers of BERT in fine tuning in tf2.keras | <p>I am trying to fine-tune 'bert-based-uncased' on a dataset for a text classification task. Here is the way I am downloading the model:</p>
<pre><code>import tensorflow as tf
from transformers import TFAutoModelForSequenceClassification, AutoTokenizer
model = TFAutoModelForSequenceClassification.from_pretrained(&quo... | <p>I found the answer and I share it here. Hope it can help others.
By the help of <a href="https://raphaelb.org/posts/freezing-bert/" rel="nofollow noreferrer">this article</a>, which is about fine tuning bert using pytorch, the equivalent in tensorflow2.keras is as below:</p>
<pre><code>model.bert.encoder.layer[i].tr... | python-3.x|keras|tensorflow2.0|huggingface-transformers|bert-language-model | 0 |
372,072 | 71,100,132 | How to make a pivot table from a dataframe with multiple columns? | <p>Please help me.</p>
<p>My dataframe looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th><strong>date</strong></th>
<th><strong>account</strong></th>
<th><strong>action</strong></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>2021-01-11</td>
<td>504</td>
<td>login</t... | <p>Could this work?</p>
<p>Get the piece of dataframe during a certain period of time:</p>
<pre><code>new_df = df[start_date < df['date'] < end_date]
</code></pre>
<p>new_df now has all the rows during a certain period of time.
Get all the unique account values:</p>
<pre><code>accounts = new_df['account'].unique(... | python|pandas|dataframe|group-by|pivot-table | 0 |
372,073 | 71,114,265 | Why are my train/valid set loss curves dropping and plateau after X epochs? | <p>I am training a deep model for MRI segmentation. The models I am using are U-Net++ and UNet3+. However, when plotting the validation and training losses of these models over time, I find that they all end with a sudden drop in loss, and a permanent plateau. Any ideas for what could be causing this plateau? or any id... | <p>Due to the high number of parameters it is hard if not impossible to reason about the optimization landscape, so any speculations are really just that, speculations.</p>
<p>If you assume that the model got stuck somewhere, that is, that the gradient is getting very small (it's sometimes worth plotting the distributi... | machine-learning|deep-learning|pytorch|statistics|evaluation | 0 |
372,074 | 71,289,730 | Pandas: How do I delete first two rows of headers? | <p>I'm using an excel file and would like to drop first two rows of headers that has 3 rows of headers.</p>
<p>Current File Example:</p>
<pre><code> Type1, Type2, Type3, Type4
SubType1, SubType2, SubType3, SubType4
SubSubType1-3,,,SubSubType4
0 Blah, Blah1, Blah2, Blah4
1
2
</code></pre>
<p>After dropping ... | <p>Use header parameter with a value = 2.</p>
<pre><code>data = pd.read_csv("file_name.csv", header=2)
</code></pre> | python|pandas|data-science | 2 |
372,075 | 71,228,810 | Transposing a list of dicts | <p>Having some trouble trying to come up with the most pythonic way to rearrange this list of dictionaries...</p>
<pre><code>[{1: ['s1e1.csv', 's1e2.csv']},
{2: ['s2e1.csv', 's2e2.csv']}]
</code></pre>
<p>So that it is arranged like this...</p>
<pre><code>[{1: 's1e1.csv', 2: 's2e1.csv'},
{1: 's1e2.csv', 2: 's2e2.csv... | <p>Something like this should work:</p>
<pre class="lang-py prettyprint-override"><code>vals = [{1: ['s1e1.csv', 's1e2.csv']}, {2: ['s2e1.csv', 's2e2.csv']}]
newvals = [{1: vals [0][1][x], 2: vals [1][2][x]} for x in range(2)]
# Output: [{1: 's1e1.csv', 2: 's2e1.csv'}, {1: 's1e2.csv', 2: 's2e2.csv'}]
</code></pre> | python|pandas|numpy|csv|dictionary | 0 |
372,076 | 71,386,143 | Trying to save image from numpy array with PIL, getting errors | <p>trying to save an inverted image, saved inverted RGB colour data in array pixelArray, then converted this to a numpy array. Not sure what is wrong but any help is appreciated.</p>
<pre><code>from PIL import Image
import numpy as np
img = Image.open('image.jpg')
pixels = img.load()
width, height = img.size
pixelArr... | <p>Your np.array creates an array shape (4000000, 3) instead of (2000, 2000, 3).</p>
<p>Also, you may find that directly mapping the subtraction to the NumPy array is faster and easier</p>
<pre><code>from PIL import Image
import numpy as np
img = Image.open('image.jpg')
pixelArray = np.array(img)
pixelArray = 255 - p... | python|numpy|python-imaging-library | 1 |
372,077 | 71,412,932 | Pandas DataFrame - row comparision and isolation problem | <p>I have those DataFrame where I have fathers that are their own grandchild.
I want to isolate the corresponding rows to treat them separately.</p>
<pre><code>df = pd.DataFrame({
'father' : ['a', 'b', 'e', 'f', 'j', 'k'],
'son' : ['b', 'a', 'f', 'g', 'k', 'j']
})
df
df2 = pd.DataFrame({
'father' : [1, 2, 4... | <p>You can use <code>frozenset</code> to group your rows:</p>
<pre><code>df['group'] = df.apply(frozenset, axis=1)
print(df)
# Output
father son group
0 a b (a, b)
1 b a (a, b)
2 e f (e, f)
3 f g (g, f)
4 j k (j, k)
5 k j (j, k)
</code></pre>
<p>After, you can use a ... | python|pandas|dataframe | 1 |
372,078 | 71,274,535 | How do I change my legend labels to other words? | <p><a href="https://i.stack.imgur.com/3GnQI.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>I have tried several different ways, but I have had no luck so far. I am trying to change my bar chart legend labels from (0,1,2,3,4,5,6) to (Monday, Tuesday, Wednesday Thursday, Friday, Saturday). Help pl... | <p>Try:</p>
<pre><code>legend_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
plt.legend(labels = legend_labels, title = 'Weekdays', loc = 'upper left')
plt.show()
</code></pre> | python|pandas|matplotlib|legend | 0 |
372,079 | 71,125,097 | Pandas fillna() does not apply values from one column to an entire dataframe | <p>Please explain, why this won't work (hc is pandas dataframe on below example):</p>
<pre><code>import pandas as pd
import numpy as np
hc = pd.DataFrame([['Adolf', np.nan],
['Hans', 'Johan']],
columns=('First Name', 'Second Name'))
hc.fillna(value=hc["First Name"])
</cod... | <p>IIUC, you want to <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> with a Series as reference, per row.</p>
<pre><code>hc = hc.fillna(hc['First Name'])
</code></pre>
<p>This is not currently supported on the columns for all pandas v... | python|pandas | 0 |
372,080 | 71,298,402 | Is there a better way to search a sorted list if the other list is sorted too? | <p>In the numpy library, one can pass a list into the <code>numpy.searchsorted</code> function, whereby it searched through a different list one element at a time and returns an array of the same sizes as the indices needed to preserve order. However, it seems to be wasting performance if both lists are sorted. For exa... | <p>You could use <a href="https://pypi.org/project/sortednp/" rel="nofollow noreferrer">sortednp</a>, unfortunately it does not give too much flexibility, In the code snippet below I used its <a href="https://gitlab.sauerburger.com/frank/sortednp#index-tracking-and-duplicates" rel="nofollow noreferrer">merge</a> tracki... | python|numpy | 2 |
372,081 | 71,330,409 | How can I calculate the F1-score and other classification metrics from a faster-RCNN? (object detection in PyTorch) | <p>I'm trying to wrap my head around this but struggling to understand how I can compute the f1-score in an object detection task.</p>
<p>Ideally, I would like to know false positives, true positives, false negatives and true negatives for every target in the image (it's a binary problem with an object in the image as ... | <p>The use of the terms precision, recall, and F1 score in object detection are slightly confusing because these metrics were originally used for binary evaluation tasks (e.g. classifiation). In any case, in object detection they have slightly different meanings:</p>
<p>let:
TP - set of predicted objects that are succe... | python|deep-learning|pytorch|computer-vision|object-detection | 1 |
372,082 | 71,385,637 | What Loss function to use for binary classification in CNN using float labels? | <p>So I am building a CNN that gets images using labels that go from 0 to 1.</p>
<p>What I mean is that I am trying to perform detection of <strong>one</strong> thing in the image and each image has a label between 0 and 1 that stands for the probability of said type of event being in that image.</p>
<p>I want to outpu... | <p>This solution is for <code>logits</code> (output of last linear layer) not for output probabilities</p>
<pre class="lang-py prettyprint-override"><code>def loss(logits, soft_labels):
anti_soft_labels = 1 - soft_labels
return soft_labels * tf.nn.softplus(-logits)
+ anti_soft_labels * tf.nn.softplus(logits) +... | tensorflow|deep-learning|conv-neural-network|classification|loss-function | 1 |
372,083 | 71,160,692 | Parallelization of for loop: pandas | <p>I have 1000 Tables and what I need to do:</p>
<ol>
<li>Extract data from table x</li>
<li>Do some Calculation based on the data</li>
<li>Save results in one big table</li>
</ol>
<p>Here is my code</p>
<pre><code>table_names = pd.read_sql("SELECT table_name FROM information_schema.tables where table_schema = 'so... | <p>If you are looking to simply get one value (count) from each sql query then it likely makes more sense to let SQL DB do the hard work and just bring the result back into pandas.</p>
<pre><code>table_names = pd.read_sql("SELECT table_name FROM information_schema.tables where table_schema = 'some_schema';",s... | python|pandas | 0 |
372,084 | 71,127,140 | Is there a faster or better way to segregate dataset into 80 20 ratio in python? | <pre><code>X.shape #output is => (2555904, 1024, 2)
X[0] #Output is => array([[ 0.0420274 , 0.23476323], [-0.2728826 , 0.40513492], [-0.26707262, 0.22749889], ..., [-0.7055947 , -0.28693035], [-0.41157472, 0.66826206], [ 0.06487698, 0.6358149 ]], dtype=float32)
total = len(X)
n_train = int(0.8*total) #80% sample... | <p>You can use <strong>sklearn.model_selection.train_test_split</strong>.
Check out the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer">official documentation</a> with an example. You have to split the data in target variable and explan... | python|pandas | 0 |
372,085 | 71,423,135 | Python Plotting Grouped Data | <p>The grouped data looks like</p>
<p><a href="https://i.stack.imgur.com/4s4NJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4s4NJ.png" alt="The Grouped Data looks like" /></a></p>
<p>My approach yields to</p>
<p><a href="https://i.stack.imgur.com/q7A05.png" rel="nofollow noreferrer"><img src="http... | <p>As the test DataFrame I used:</p>
<pre><code> MAPPING CREATED_DTM counts
0 Beschaedigung 2020-04-30 22738
1 Beschaedigung 2020-05-31 21523
2 Beschaedigung 2020-06-30 18516
3 Beschaedigung 2020-07-31 21436
4 Beschaedigung 2020-08-31 22325
5 Verlust 2020-04-30 20000
6 Verl... | python|pandas|plot|pandas-groupby | 1 |
372,086 | 71,364,802 | How to overide NumPy ndarray attributes / properties? | <p>I have a class that has <code>real</code> and <code>imag</code> attributes,</p>
<pre><code>class A():
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __repr__(self):
return repr((self.real, self.imag))
def conjugate(self):
return A(s... | <p>Your class, with repr tweaked:</p>
<pre><code>In [181]: class A:
...: def __init__(self, real, imag):
...: self.real = real
...: self.imag = imag
...:
...: def __repr__(self):
...: return f"A: {repr((self.real, self.imag))}"
...:
...... | python|arrays|numpy | 0 |
372,087 | 71,277,555 | Avoid for-loops when getting mean of every positive-value-interval in an array | <p>I want to get the mean of every interval with values above a threshold. Obviously, I could do a loop and just look if the next value is under the threshold etc., but I was hoping that there would be an easier way. Do you have ideas that are similar to something like masking, but include the "interval"-prob... | <p>The trick I am using here is to calculate where there are sudden differences in the mask which means we switch from a contiguous section to another. Then we get the indexes of where those sections start and end, and calculate the mean inside of them.</p>
<pre><code># Imports.
import matplotlib.pyplot as plt
import n... | python|numpy|masking|threshold | 2 |
372,088 | 71,139,246 | groupby transform valueerror length of passed values | <p>Hello can you help me understand what is the issue here and how to solve it?</p>
<pre><code>dft = pd.DataFrame({'B': [0, 1, 2, 5, 4, 7, 2, 2, 2, 5, 6, 7]})
dft['user'] = ['a','b','c','b','a','c','a','b','b','c','a', 'c']
dft.groupby('user')['B'].transform(lambda row: row.ewm(span=2)).mean()
</code></pre>
<p>gives <... | <p>I suppose that invocation of <code>mean()</code> should be a part of your lambda function.</p>
<p>So maybe your code should be:</p>
<pre><code>dft.groupby('user')['B'].transform(lambda row: row.ewm(span=2).mean())
</code></pre>
<p>For your sample data I got:</p>
<pre><code>0 0.000000
1 1.000000
2 2.00000... | python|pandas | 1 |
372,089 | 71,109,317 | Not being able to change the data type of a column in a dataframe | <p>I want to change the data type of the values in the column "id" from integer to string and then save the new dataframe to a CSV file. This is what I have tried:</p>
<pre><code>import pandas as pd
df = pd.read_csv ('DataSet.csv', header=[0], on_bad_lines='skip', sep = ';')
df["id"] = df["id&... | <p>In <code>csv</code> file are all values saved like strings, pandas by default converting types like <code>int, float</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> metdod.</p>
<p>So is necessary always converting ... | python|pandas|dataframe|csv | 2 |
372,090 | 71,185,591 | How to replace values in a matrix based on specific indices? | <p>I'm trying to index a matrix based on an array of coordinates, so that I can replace the values in those positions with 1, and leave the rest as is. Here's what I mean:</p>
<p>I have the following 3x3 matrix</p>
<pre><code>matrix = np.zeros((3,3), dtype=int)
matrix
>>> array([[0, 0, 0],
[0, 0, 0... | <p>You can run e.g.:</p>
<pre><code>matrix[tuple(coords.T)] = 1
</code></pre> | python|arrays|numpy|matrix|indexing | 1 |
372,091 | 71,267,401 | Key-Error: KeyError: "None of [Float64Index([15.593, 15.577, 15.563], dtype='float64')] are in the [columns]" | <p>I'm trying to calculate a column, but I get the following error:</p>
<pre><code>Key-Error: KeyError: "None of [Float64Index([15.593, 15.577, 15.563], dtype='float64')] are in the [columns]"
</code></pre>
<p>Where is my error coming from? and how can I fix it?</p>
<pre><code>import pandas as pd
import numpy... | <p>Try refactoring your function like this:</p>
<pre class="lang-py prettyprint-override"><code>def absolute_humidity(temp, humidity):
return (
(
(610.78 * np.exp((17.08085 * temp) / (234.175 + temp)) * humidity / 100)
/ (462 * (273.1 + temp))
* 1000
)
if ... | python-3.x|pandas|dataframe | 0 |
372,092 | 71,300,849 | How to check if a string value of one row is contained in the string value of another row in the same column in pandas dataframe | <p>I have a dataframe as follows :</p>
<p>The "docid" is the exploded column of "DocID".
I want to check if a string in the "Term" column is contained in another row in the same column. For example, rows 3 and 4 have "in the treatment" and "in the treatment of".</p>
<p>... | <p>What you can do is substract the docfreq of "in the treatment" by "in the treatment of" which will return the number of only "in the treatment", then for docID, remove any inctances of docID "in the treatment of" from "in the treatment"</p> | python|pandas|string|dataframe|pandas-groupby | 0 |
372,093 | 71,232,030 | how does array.shape[:] works? | <p>I think I am just confused with how <strong>array.shape[]</strong> works.<br />
The output of <strong>array.shape[:]</strong> is the shape of the array in tuple which is fine.<strong>output:(4,5)</strong><br />
The output of <strong>array.shape[1:]</strong> is <strong>(5,)</strong> and the output of <strong>array.sh... | <p>You got a problem with tuples here, not with <code>array.shape</code> in itself.
As pointed out in the comments, <code>x[:1]</code> gives you the first element of a tuple as a singleton tuple, because you are indexing "all" elements of the tuple up to the first (included).</p>
<p>Instead, <code>x[1:]</code... | python|numpy | 1 |
372,094 | 71,331,781 | RegEx negation to handle decimal values in Pandas dataframe using .replace() | <p>I have the following Pandas dataframe:</p>
<pre><code>foo = {
'Sales' : [200, 'bar', 400, 500],
'Expenses' : [70, 90, 'baz', 170],
'Other' : [2.5, 'spam', 70, 101.25]
}
df = pd.DataFrame(foo)
Sales Expenses Other
200 70 2.5
bar 90 spam
400 baz 70
500 170 ... | <p>Regex will only work on strings.
You can cast all values to strings using .astype(str)</p>
<pre><code>df['Other'].astype(str).replace('[^0-9]', np.NaN, regex=True)
</code></pre> | python|regex|pandas|regex-negation | 1 |
372,095 | 71,117,376 | Python - Sum values for all dates prior to a specific date | <p>I currently have two dataFrames that look like this:</p>
<pre><code>Df3 - which is the output dataFrame:
| CompanyNm | CpID | Date |
:--------|:-----------------------------------|:-------------|:----------|
0 | {Converting) | {C} ... | <p>EDIT: I misunderstood your problem definition earlier. Now corrected it:</p>
<pre><code>def func(g):
mask = (df4['CustID'] == g.name[0]) & (df4['InvoiceDt'] <= g.name[1])
return df4[mask]['SalesAmt'].sum()
df3.groupby(['CpID','Date']).apply(func)
</code></pre> | python|pandas | 0 |
372,096 | 71,165,950 | Stacked Bar Chart Y axis Values Missing | <p>I have a wide data frame and am using the following code to produce a stacked bar graph; however, the values on the Y axis are missing and I'm not sure why. I assume it has something to do with stacking the columns. You can see I tried to manually set the Y axis within my code but the graph did not capture that comm... | <p>This code provided the desired results:</p>
<pre><code>ALL_BOARD_C=ALL_BOARD.drop(['Acute_Hours','ICU_Hours','PSYCH_Hours','index'],axis=1)
ALL_BOARD_C.plot(ax=g9,x='Day' ,kind='bar', stacked=True, title='ED Total Boarders by Unit')
loc = WeekdayLocator(byweekday=MO, interval=1)
g9.xaxis.set_major_locator(loc)
g9.se... | python|pandas|matplotlib | 0 |
372,097 | 71,296,457 | How to use np.where on 3D array with all() | <p>I've been stuck for quite some time on this problem.</p>
<p>I have an array of shape (4,3,3). In my real case, the shape is much bigger.</p>
<pre><code>a = np.array([
[[1,2,3], [3,4,2], [1,3,4]],
[[1,2,3], [3,6,2], [1,4,4]],
[[1,2,3], [3,6,2], [1,4,4]],
[[1,2,3], [3,6,2], [1,2,4]]
])
</code></pre>
<p... | <p>The <code>cond</code> array is central to the workings of <code>where</code>:</p>
<pre><code>In [167]: a == [1, 2, 3]
Out[167]:
array([[[ True, True, True],
[False, False, False],
[ True, False, False]],
[[ True, True, True],
[False, False, False],
[ True, False, False]],... | python|numpy | 0 |
372,098 | 52,053,522 | Summing up values from one column based on values in other column | <p>I have a dataframe something like below,</p>
<pre><code>Timestamp count
20180702-06:26:20 50
20180702-06:27:11 10
20180702-07:05:10 20
20180702-07:10:10 30
20180702-08:27:11 40
</code></pre>
<p>I want output something like below,</p>
... | <p>Use</p>
<pre><code>In [252]: df.groupby(df.Timestamp.dt.strftime('%Y-%m-%d-%H'))['count'].sum()
Out[252]:
Timestamp
2018-07-02-06 60
2018-07-02-07 50
2018-07-02-08 40
Name: count, dtype: int64
In [254]: (df.groupby(df.Timestamp.dt.strftime('%Y-%m-%d-%H'))['count'].sum()
.reset_index(name='Sum... | python|python-2.7|pandas | 0 |
372,099 | 52,250,710 | How do I covert an Excel Date in MMM-YYYY to datetime or strings? | <p>My dataframe is taken from a Excel file which formats their dates as e.g Jan 2018. </p>
<p>I want to change to datetime such as 01-2018 or even as a string like 01/2018.</p>
<p>I have two problems:</p>
<ol>
<li><p>When attempting to convert to datetime I have an out of bound error (nanosecond)</p>
<pre><code>two... | <p>I have managed to successfully solve my own question. Thank you for your interest. If there any better solutions I am all ears</p>
<pre><code>twoyear_df['Date'] = pd.to_datetime(twoyear_df['Date'], format='%b %y')
</code></pre> | python|pandas|datetime|dataframe | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.