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 |
|---|---|---|---|---|---|---|
14,100 | 61,045,806 | Loading from Keras checkpoint | <p>I am training a model in Keras where I saved everythinig using following codes.</p>
<pre><code>filepath = "project_model.hdh5"
checkpoint = ModelCheckpoint("project_model.hdf5", monitor='loss', verbose=1,
save_best_only=False, mode='auto', period=1)
</code></pre>
<p>Then I used the following codes to run the ... | <blockquote>
<p>Now after running the training loop for a while if I decide to change the learning rate to say .002, would I have to run all the codes that are related to the models (the model structure, then the optimization, etc)?</p>
</blockquote>
<p>You can <em>update</em> the learning rate either during trainin... | python|tensorflow|keras | 3 |
14,101 | 42,230,629 | Pandas sum of subset rows and re-merge in DF | <p>I have a DF according to below:</p>
<pre><code> id_var1 id_var2 num_var1 num_var2
1 1 1 1
1 2 1 0
1 3 2 0
1 4 2 3
1 5 3 3
1 6 3 ... | <p>Let me know if this works for you.</p>
<p>First create a list of values from num_var1 column.
Then get sum of sub list- Created from num_var1 , from the current index to the required number items (taken from column num_var2).</p>
<p>sublst() function is called only when the previous record's num_var2 not matching ... | python|pandas | 0 |
14,102 | 42,295,928 | Dataframe from CSV gives AttributeError when accessing column | <p>While putting this trivial table in Ipython I cannot handle it.</p>
<p>I am using pandas '0.19.2' on 3.6.0 |Anaconda 4.3.0 (64-bit)|
and I am getting this kind of error, handling almost every csv table.</p>
<pre><code>df = pd.read_csv('Fatt_eng.csv')
df
Out[82]:
Type;Price;Numbers
0 Purse;13.90;86
... | <p>The reason you're getting <code>AttributeError: 'DataFrame' object has no attribute 'Type'</code>, is because your dataframe has no attribute called <code>'Type'</code> and pandas then has a magic method that falls back to look for if there is a column with that name, which there isn't in your dataframe.</p>
<p>The... | python-3.x|csv|pandas|anaconda | 2 |
14,103 | 69,906,952 | Why is "numpy.int32" not able to be printed here? (Using geopandas + python 3.9.5) | <p>Here is the relevant code:</p>
<pre><code>import geopandas as gpd
#A shape file (.shp) is imported here, contents do not matter, since the "size()" function gets the size of the contents
shapefile = 'Data/Code_Specific/ne_50m_admin_1_states_provinces/ne_50m_admin_1_states_provinces.shp'
gdf = gpd.read_fi... | <p><a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.read_file.html" rel="nofollow noreferrer"><code>gpd.read_file</code></a> will return either a <code>GeoDataFrame</code> or a <code>DataFrame</code> object, both of which have the attribute <code>size</code> which returns an integer. The attribute ... | python|numpy|geopandas|python-3.9 | 0 |
14,104 | 69,743,134 | How to perform a Window Function operation in a Pandas Dataframe using a cumulative sum? | <p>I have an initial dataframe</p>
<pre><code>df1 =
+---+---+---+
| A| B| C|
+---+---+---+
| 1| 1| 10|
| 1| 2| 11|
| 1| 2| 12|
| 3| 1| 13|
| 2| 1| 14|
| 2| 1| 15|
| 2| 1| 16|
| 4| 1| 17|
| 4| 2| 18|
| 4| 3| 19|
| 4| 4| 19|
| 4| 5| 20|
| 4| 5| 20|
+---+---+---+
</code></pre>
<p>Using pyspa... | <p>In pandas we can <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.sum.html" rel="nofollow noreferrer"><code>groupby sum</code></a> on <code>A</code> and <code>B</code>. Then <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.cumsum.html" rel="nofollow n... | pandas|dataframe|apache-spark|pyspark|group-by | 3 |
14,105 | 69,890,798 | strange implicit conversion after append an empty list in numpy | <p>After the thread <a href="https://stackoverflow.com/questions/69881602/strange-implicit-conversion-of-data-type-in-numpy">strange implicit conversion of data type in numpy</a>, I found another strange conversion with numpy</p>
<pre><code>import numpy as np
a = np.array([1,2,3], dtype=int)
c = np.append(a, [])
</code... | <p>The empty list has to be first turned into an array:</p>
<pre><code>In [149]: np.array([])
Out[149]: array([], dtype=float64)
</code></pre>
<p><code>np.append</code> actually does:</p>
<pre><code>In [151]: np.ravel([])
Out[151]: array([], dtype=float64)
</code></pre>
<p>The <code>append</code> code:</p>
<pre><code>d... | numpy | 0 |
14,106 | 72,439,254 | Changing boolean value in pandas dataframe through function | <p>i'm super new to coding and trying to change a boolean set in a pandas df from True to False.
I want to select a certain row, based on a name.
My df, df_contacts looks like this:</p>
<pre><code> name gender relationship category access timestamp proof
0 Emma female ex-girlfriend True 165... | <p>This will change it using numpy</p>
<pre><code>import numpy as np
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access (name):
if block.lower() == 'yes':
condition_list = [df_contacts['category'] == True, df_contacts['category'] == False]
... | python|pandas|function|conditional-statements|boolean | 0 |
14,107 | 50,563,250 | changing columns to column header pandas | <p>I have a dataframe like this-</p>
<pre><code> A B C
a 2 4
b 4 6
c 4 8
</code></pre>
<p>I want to create a new empty dataframe with columns like this-</p>
<pre><code>a b c class
</code></pre>
<p>where the rows of first column of first dataframe become the columns in new dataframe and another column['c... | <p>You can first take all Col A data as list</p>
<pre><code>>>> col = df.A.tolist()
>>> col.append('Class')
>>> new_df = pd.DataFrame(columns=col)
Empty DataFrame
Columns: [a, b, c, Class]
Index: []
</code></pre> | python|pandas | 3 |
14,108 | 50,321,326 | Combine columns along the same index | <p>I'm trying to use <code>pandas</code> to wrangle a ~500mb tab-separated data file in the following format:</p>
<pre><code>+-------+---------+-------+---------+-------+---------+
| Time1 | Sensor1 | Time2 | Sensor2 | Time3 | Sensor3 |
+-------+---------+-------+---------+-------+---------+
| 0 | x | 0 ... | <p>You can create a list of series and then use <code>pandas.concat</code> to combine them into a single dataframe.</p>
<p>The solution is functionally identical to @DyZ, but laid out differently.</p>
<pre><code>series_list = [df.set_index('Time'+str(i))['Sensor'+str(i)].dropna() \
for i in range(1, in... | python|pandas|dataframe | 1 |
14,109 | 45,286,696 | How to Display Dataframe next to Plot in Jupyter Notebook | <p>I understand how to display two plots next to each other (horizontally) in Jupyter Notebook, but I don't know if there is a way to display a plot with a dataframe next to it. I imagine it could look something like this:</p>
<p><a href="https://i.stack.imgur.com/Dlsl9.png" rel="noreferrer"><img src="https://i.stack.... | <p>I'm not aware of how to control the location of where the DataFrame will display directly - but one work around I have used in the past is to render the DataFrame as a matplotlib table and then it should behave like any other matplotlib plot. You can use:</p>
<pre><code>import matplotlib.pyplot as plt
import pandas ... | python|python-2.7|pandas|matplotlib|jupyter-notebook | 20 |
14,110 | 62,472,438 | With the HuggingFace transformer, how can I return multiple samples when generating text? | <p>I'm going off of <a href="https://github.com/cortexlabs/cortex/blob/master/examples/pytorch/text-generator/predictor.py" rel="nofollow noreferrer">https://github.com/cortexlabs/cortex/blob/master/examples/pytorch/text-generator/predictor.py</a></p>
<p>But if I pass <code>num_samples=5</code>, I get:</p>
<pre><code... | <p>As far as I can see this code doesn't provide multiple samples, but you can adjust it with a some adjustments.</p>
<p>This line uses already multinomial but returns only 1:</p>
<pre class="lang-py prettyprint-override"><code>next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)
</code></p... | python|pytorch|huggingface-transformers | 1 |
14,111 | 62,780,290 | More efficient way to add columns with same string values in multiple dataframes with loops or lambdas? | <p>I want to add a new column, Category, in each of my 8 similar dataframes.
The values in this column are the same, they are also the df name, like <code>df1_p8</code> in this example.
I have used:</p>
<pre><code>In: df61_p8.insert(3,"Category","df61_p8", True)
# or simply, df61_p8['Category']=... | <p>You can use <code>pd.concat</code> with <code>keys</code> parameter then <code>reset_index</code>:</p>
<pre><code>pd.concat([df0,df1,df2,df3], keys=['df0', 'df1', 'df2', 'df3']).reset_index(level=0)
</code></pre>
<p>MCVE:</p>
<pre><code>df0 = pd.DataFrame(np.ones((3,3)), columns=[*'ABC'])
df1 = pd.DataFrame(np.ze... | python|python-3.x|pandas|loops|lambda | 3 |
14,112 | 71,270,457 | I want to resample the columns in a group of 7 based on weeks starting sunday and ending saturday | <pre><code>Cid 2021-05-01| 2021-05-02 | 2021-05-03 | 2021-05-04| 2021-05-05|2021-05-06|2021-05-07|2021-05-08
120 25 30 40 10 15 20 5 5
220 10 20 30 10 50 15 35 55
430 16 4... | <p>You can use <code>resample</code> to do 7 days aggregation.</p>
<pre class="lang-py prettyprint-override"><code># Convert columns to DatetimeIndex if it is not yet
df = df.set_index('Cid')
df.columns = pd.to_datetime(df.columns)
</code></pre>
<p>Then, aggregate the sum over 7 days. "W-SAT" is weekly interv... | python-3.x|pandas|dataframe|python-datetime | 0 |
14,113 | 71,303,438 | Transform values in a list of dictionaries using lambda | <p>I have a list of dictionaries, like so:</p>
<pre><code>matrices = [
{ "name": 'dark_matter_and_gas', 'matrix': dark_matter_a_matrix},
{ "name": 'dark_matter_and_gas', 'matrix': dark_matter_b_matrix},
{ "name": 'dark_matter_and_gas', 'matrix': dark_matter_c_matrix},
{ &qu... | <p>You could iterate over the dictionaries in <code>matrices</code> and apply <code>function</code> to each of the DataFrames in each dictionary:</p>
<pre><code>for d in matrices:
d['matrix'] = d['matrix'].apply(lambda x: function(x))
</code></pre>
<p>I guess you could write it as a list comprehension as well:</p>
... | python|pandas|dataframe|dictionary|lambda | 0 |
14,114 | 71,427,531 | Access certain values in python pandas | <p>The following code gives me.</p>
<pre><code>import yfinance as yf
import pandas as pd
tickers = ['AAPL', 'MSFT', 'AMZN']
start_date = datetime.date(2019, 1, 2)
end_date = datetime.date(2020, 1, 1)
delta = datetime.timedelta(days=21)
tickers = ['AAPL', 'MSFT', 'AMZN']
daily_data = yf.download(tickers, start=start_da... | <p>Instead of just printing the mean, you could store those values into a dataframe and then get the top 3 values using <code>head()</code>. See code below.</p>
<pre><code>df = pd.DataFrame(columns=['AAPL','AMZN', 'MSFT'])
for i in f:
z = i.pct_change().mean()
df.loc[-1] = [z['AAPL'], z['AMZN'], z['MSFT']]
... | python|pandas | 0 |
14,115 | 71,284,717 | How to save output from tf.random.normal() | <pre><code>random_vector = tf.random.normal(shape = (25, latent_dim,)
</code></pre>
<p>I am training my model with the above random vector and saving the outputs as a gird of 5x5.jpg file. But since my dataset has 60k images I am unable to find the corresponding input images.
My question is how can I save the random_ve... | <p>You could use a similar code that you are using for saving the output images, on the <code>input_</code> that you feed into the function <code>save_images</code>, giving</p>
<pre><code>fig, axes = plt.subplots(5,5, figsize = (latent_dim,))
idx = 0
for row in range(5):
for column in range(5):
image = inpu... | python|tensorflow|matplotlib|operating-system | 0 |
14,116 | 71,139,185 | Get proportion of missing values per Country | <p><a href="https://i.stack.imgur.com/sZka0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sZka0.png" alt="enter image description here" /></a></p>
<p>I would like to find the proportion of missing values of my features on each country and on all years to select the countries.</p>
<p>I tried this:</... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> for reshape and then aggregate <code>mean</code> of missing values:</p>
<pre><code>df1 = (df.melt(id_vars='Country Name', value_vars=indicators)
... | python|pandas|missing-data | 0 |
14,117 | 52,284,076 | Plot multiple graph using same graph | <p>I have written one code where I want to plot multiple graphs in a same plot. When I run this, I do not get any result or any error. I am trying to take each value of a and plot graph using the program. So i suppose to have 4 graph as a have 4 elements. Most importantly all graphs shall be in a same figure. Though I ... | <p>The problem is that you are putting the plot command outside the <code>for</code> loop and so the 4 curves will not be plotted. Moreover some of your variables needed to be redefined. Following is the working solution (without the <code>if else</code> statements):</p>
<pre><code>import numpy as np
import matplotlib... | python|python-3.x|numpy|matplotlib | 0 |
14,118 | 60,460,861 | Value Error when using conditional on groupedby dataframe | <pre><code>avgTop5 = df[df.groupby(['batter', 'game_date'])['launch_speed'] >= df.groupby(['batter', 'game_date'])['launch_speed'].quantile(.95)].mean()
</code></pre>
<p>This code returns the error below</p>
<p>ValueError: operands could not be broadcast together with shapes (3695,) (3695,2) </p>
<p>The 'batter'... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.quantile.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.quantile.html</a></p>
<p>If I understood correctly, then</p>
<pre><code>df[df.groupby(['batter', 'game_date'])['l... | python|pandas|pandas-groupby | 0 |
14,119 | 60,355,037 | Calculating cosine distances for a pandas dataframe | <p>I have a pandas dataframe (say df) of shape (70000 x 10). Head of the data frame shown below:</p>
<pre><code> 0_x 1_x 2_x ... 7_x 8_x 9_x
userid ...
1000010249674395648 0.000007 0.9999... | <p>I am using spark 2.4 and python 3.7</p>
<pre><code># build spark session
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.master("local") \
.appName("cos_sim") \
.config("spark.some.config.option", "some-value") \
.g... | python|pandas|dataframe|pyspark|pyspark-sql | 0 |
14,120 | 72,815,706 | Pyspark read all files and write it back it to same file after transformation | <p>Hi I have files in a directory
Folder/1.csv
Folder/2.csv
Folder/3.csv</p>
<p>I want to read all these files in a pyspark dataframe/rdd and change some column value and write it back to same file.
I have tried it but it creating new file in the folder part_000 something but I want to write the data in to same file wh... | <p>Let's say after your transformations that df_1, df_2 and df_3 are the datafames that will be saved back into the folder with the same name.</p>
<p>Then, you can use this function:</p>
<pre><code>def export_csv(df, fileName, filePath):
filePathDestTemp = filePath + ".dir/"
df\
.coalesce(1)\
... | scala|apache-spark|pyspark|apache-spark-sql|pyspark-pandas | 0 |
14,121 | 72,597,988 | Picking up where program left off after error encountered | <p>I am running a program row-wise on a pandas dataframe that takes a long time to run.</p>
<p>The problem is, the VPN connection to the database can suddenly be lost, so I lose all my progress.</p>
<p>Currently, what I am doing is splitting the large dataframe into smaller chunks (500 rows at a time), and running the ... | <p>You could use the existing csv files to remember where to pick up:</p>
<pre class="lang-py prettyprint-override"><code>size = 500
list_of_dfs = np.split(large_df, range(size, len(large_df), size))
together_list = []
for count, chunk in enumerate(list_of_dfs):
csv_file = f"processed_{count}.csv"
... | python|pandas | 1 |
14,122 | 72,732,126 | count of occurances in pandas dataframe | <p>my dataset looks likes this after executing groupby. How can I sum the common systems in column 3</p>
<p><img src="https://i.stack.imgur.com/8ZY0j.png" alt="enter image description here" /></p> | <p>You can achieve this by using pandas <code>.value_counts()</code> method:</p>
<pre><code>df['col3'].value_counts()
</code></pre>
<p>Yields:</p>
<pre><code>sys1 3
sys4 1
sys5 1
sys2 2
Name: col3, dtype: int64
</code></pre> | python|pandas|dataframe | 0 |
14,123 | 59,532,929 | Python ASK signal plot | <p>I need to plot the following 3 signals in Python (Spyder). Bellow, I have indicated photos of the signal that my code needs to plot. (The first one I manage to plot it successfully.)
<a href="https://i.stack.imgur.com/mpRAl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mpRAl.jpg" alt="enter imag... | <p>Your error comes from incompatible shape between your arrays.
You have to make sure that both <code>pliroforia</code> and <code>our_signal</code> have the same number of elements before computing their product.</p>
<p>I think that is what you try to achieve with your <code>for</code> loop.
But it should not work as... | python|numpy|matplotlib | 1 |
14,124 | 59,771,061 | Using inverse_transform MinMaxScaler from scikit_learn to force a dataframe be in a range of another | <p>I was following <a href="https://stackoverflow.com/a/47054147/5081366">this answer</a> to apply an inverse transformation over a scaled dataframe. My question is how can I do to transform a new one dataframe to a range of values of the original dataframe?.
So far, I did this:</p>
<pre><code>import pandas as pd
imp... | <p>To explain you what is <code>MinMaxScaler</code> <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html" rel="nofollow noreferrer">doing</a>:</p>
<pre><code>X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
</code></pre>
<p>... | python|pandas|dataframe|scikit-learn | 2 |
14,125 | 59,686,992 | Getting a unique count within a range of months in a Pandas DataFrame | <p>I have a Dataframe which contains customer names, amount of orders and the date in which they ordered.</p>
<p>I want to know, how many customers I had in a range of months. So, count the unique customer names within June to October, to put an example.</p>
<p>I have tried <code>Cust_per_month = raw_data[['Customer'... | <p>I would <code>mask</code> the original DataFrame then calculate. <code>groupby</code> is more useful with unique, non-overlapping groups, or with a fixed window (<code>groupby.rolling</code>), neither of which are applicable here. </p>
<h3>Sample Data</h3>
<pre><code>import string
import pandas
import numpy
np.ra... | python|pandas|dataframe | 1 |
14,126 | 59,720,062 | Pandas cut function with None in data set | <p>In my data set, there's a column that looks like, for example:</p>
<p><code>[111, 112, None, 113, 114, 115, 116, None, 117, 118, 119]</code></p>
<p>I want to bin this column into, let's say 3 bins, so that I'd get</p>
<p><code>[0, 0, None, 0, 1, 1, 1, None, 2, 2, 2]</code></p>
<p>How do I do this with pandas.cut... | <p>IIUC,</p>
<pre><code>s = pd.Series([111, 112, None, 113, 114, 115, 116, None, 117, 118, 119])
pd.cut(s, bins=[0, 113, 116, 120], labels=[0, 1, 2])
</code></pre>
<p>Output:</p>
<pre><code>0 0
1 0
2 NaN
3 0
4 1
5 1
6 1
7 NaN
8 2
9 2
10 2
dtype: category
... | python|pandas | 3 |
14,127 | 62,029,177 | Best way to load a Pillow Image object from binary data in Python? | <p>I have a program that modifies PNG files with Python's Pillow library. I was wondering how I could load binary data into a PNG image from PIL's Image object. I receive the PNG over a network as binary data (e.g. the data looks like b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR...'). What is the best way to accomplish this t... | <p>I'd suggest receiving the data into a <code>BytesIO</code> object from the <code>io</code> standard library package. You can then treat that as a file-like object for the purposes of Pillow.</p> | python|numpy|python-imaging-library|png | 1 |
14,128 | 57,982,948 | How to index a list by csv file names in pandas? | <p>I am running a data analysis where I am running many CSV files.
I used the code below </p>
<pre><code>filelist = ["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
for location in filelist:
df = pd.read_csv(location)
out_put, productivity = timeresult.input_data.outbuild(df, year, days)
filelis... | <p>I did not understand this part </p>
<blockquote>
<p>Is there a way to have the index be the CSV name</p>
</blockquote>
<p>For the last part, instead of doing <code>filelist.append(productivity)</code>, append it to an empty list like:</p>
<pre><code>filelist=["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\ma... | python|pandas|dataframe|csv|path | 0 |
14,129 | 57,905,977 | Importing one Databricks Notebook into another error | <p>I am trying to run a Jupyter Notebook within another, in Databricks. </p>
<p>The code below fails, the error is 'df3 is not defined'. But, df3 is defined.</p>
<pre><code>input_file = pd.read_csv("/dbfs/mnt/container_name/input_files/xxxxxx.csv")
df3 = input_file
%run ./NotebookB
</code></pre>
<p>The first line of... | <p>I see you want to pass the structured data like DataFrame from an Azure Databricks Notebook to the other one by calling.</p>
<p>Please refer to the offical document <a href="https://docs.azuredatabricks.net/user-guide/notebooks/notebook-workflows.html" rel="nofollow noreferrer"><code>Notebook Workflows</code></a> t... | python|pandas|jupyter-notebook|databricks|azure-databricks | 0 |
14,130 | 54,970,880 | Custom Layers in tensorflow | <p>I am trying to make some changes to the inbuilt dropout function in tensorflow. What is the best procedure to do so?</p>
<p>I'd like to make some changes in forward and backpropogation steps. In <a href="https://%20https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/python/ops/nn_ops.py" rel="nofollow no... | <p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/custom_gradient" rel="nofollow noreferrer">tf.custom_gradient</a> to define your own forward and backprop step in a single method. Here is a simple example:</p>
<pre><code>import tensorflow as tf
tf.InteractiveSession()
@tf.custom_gradient
def cus... | python|tensorflow|dropout | 1 |
14,131 | 49,633,765 | Remove single quotations & split parentheses | <p>I am new to Python and am playing around with data sets. I need help trying to:
1.Remove the single quotations for the dates within the parentheses
2.Split the parenthesis into an array (31312 x 4)</p>
<p>Code:
import csv
import numpy as np
import pandas as pd</p>
<pre><code>text_file = open("Claims1.t... | <p>Data from jpp, should be fast </p>
<pre><code>pd.DataFrame(df[0].tolist())
Out[779]:
0 1 2 3
0 1 2000-01-04 328647 5000
1 2 2000-01-09 465858 5000
2 3 2000-01-09 378115 5000
3 4 2000-01-14 121895 5000
4 5 2000-01-16 325172 5000
5 6 2000-01-16 156062 5000
6 7 2000-01... | python|python-3.x|pandas|csv|dataframe | 2 |
14,132 | 73,506,156 | Filter duplicate records in a dataframe using pandas and perform operations | <p>I have the below dataframe and trying to filter rows with duplicate records present only in col 1, col2, col3, col 4 using the below code.</p>
<pre><code>df = pd.DataFrame({'col1': ["A", "X", "E", "A", "X", "X"],
'col2': ["B", &... | <p>You can leave one value per group right away like this:</p>
<pre class="lang-py prettyprint-override"><code>columns = ['col1', 'col2', 'col3',"col4"]
grouped = dup_df.groupby(columns)
grouped[['Sex', 'Count']].apply(
lambda sub_df: (sub_df.groupby('Sex')
.agg(sum).T
... | python|python-3.x|pandas|dataframe|duplicates | 0 |
14,133 | 73,248,138 | Python plot histogram based on date (datetime64) | <p>I have a csv dataframe that I've reduced to two columns; <code>uploadDate</code> and <code>clubName</code>.</p>
<p><code>uploadDate</code> has been set to datetime64.</p>
<p>I would like to query the dataframe for all rows with a particular <code>clubName</code> and then take all of the associated dates into a histo... | <pre class="lang-py prettyprint-override"><code>df["uploadDate"] = pd.to_datetime(df["uploadDate"])
df.groupby(df["uploadDate"].dt.date).size()
print(df)
</code></pre> | python|pandas|matplotlib | 0 |
14,134 | 73,416,493 | Is there any way to map values using the column index? | <p>I am new to python I was trying to automate some processes through pandas.</p>
<pre><code>df['x'] = df['ID'].map(df5.set_index('x')['y'])
</code></pre>
<p>I want to make it generic like:</p>
<pre><code> df['x'] = df['ID'].map(df5.set_index('x')[iloc[:,[5]]])
</code></pre> | <p>You are close, need seelct 6th column without <code>[]</code>:</p>
<pre><code>df['x'] = df['ID'].map(df5.set_index('x').iloc[:,5])
</code></pre> | python|pandas|dataframe | 3 |
14,135 | 67,314,368 | what dose newshape (, -1) do? | <p>could you explain the role of newshape in reshape and what dose <code>newshape=(n_channels, -1)</code> mean? I wanna use the below code to reshape my signal matrix, but I don't understand the last part</p>
<pre><code>np.reshape(np.transpose(signal, axes=[1, 2, 0]), newshape=(n_channel, -1))
</code></pre> | <p>Let's say, You want to <a href="https://numpy.org/doc/stable/reference/generated/numpy.reshape.html" rel="nofollow noreferrer">reshape your NumPy array</a> with <code>10*2</code> dimension to <code>5*4</code>. You need:</p>
<pre><code>a = np.zeros((10, 2)) # Generates 10*2 zero matrix
np.reshape(a, newshape=(5, 4))
... | python|function|numpy|reshape | 2 |
14,136 | 67,253,190 | LineCollections for few lines with a single colorbar | <p>I'm trying to plot some lines using LineCollection in a plot. Each of these lines is needed to be mapped to colorbar whose range varies for each lines. I tried as explained here</p>
<p><a href="https://matplotlib.org/stable/gallery/lines_bars_and_markers/multicolored_line.html?highlight=line%20collection" rel="nofol... | <p>I have modified your code. Essentially what you need to do is create a norm instance for the entire dataset and then assign color values to the segments according to the colormap you have with the given norm. You can then pass it to the colorbar accordingly.</p>
<p>As such</p>
<pre class="lang-py prettyprint-overrid... | numpy|matplotlib|matplotlib-basemap | 0 |
14,137 | 60,197,989 | Groupby/cumsum for dataframe with duplicate names | <p>I'm trying to perform a cumulative sum on a dataframe that contains multiple identical names. I'd like to create another df that has a cumulative sum of the points scored per player, while also recognizing that names sometimes are not unique. The school would be the 2nd criteria. Here's an example of what I'm lookin... | <pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'Player':['John Smith', 'John Smith', 'John Smith', 'John Smith', 'John Smith'],
'School':['Duke', 'Duke', 'Duke', 'Kentucky', 'Kentucky'],
'Date':['1-1-20', '1-3-20', '1-7-20', '1-3-20', '1-08-20'],
'Points Scored':[20, 30, ... | python|pandas|group-by|cumsum | 1 |
14,138 | 60,271,288 | Dask array mean throws "setting an array element with a sequence" exception where pandas array mean works | <p>I have a pandas data frame that consist of a single column of numpy arrays. I can use the <code>numpy.mean</code> function to calculate the mean of the arrays.</p>
<pre><code>import numpy
import pandas
f = pandas.DataFrame({"a":[numpy.array([1.0, 2.0]), numpy.array([3.0, 4.0])]})
numpy.mean(f["a"]) # returns array(... | <p>It would be good if Dask Dataframe handled this case, but it doesn't today. It's not actually that surprising given the situation.</p>
<p>Your dataframe is a bit odd, in that elements of that dataframe are themselves Numpy arrays. </p>
<pre><code>>>> f
a
0 [1.0, 2.0]
1 [3.0, 4.0]
</code></... | python|arrays|numpy|dask | 1 |
14,139 | 65,450,684 | Converting JSON into a DataFrame within FastAPI app | <p>I am trying to create an API for customer churn at a bank. I have completed the model and now want to create the API using FastAPI. My problem is converting the JSON passed data to a dataframe to be able to run it through the model. Here is the code.</p>
<pre><code>from fastapi import FastAPI
from starlette.middlewa... | <p>Ok so I fixed this by changing the <code>customer_input</code> class. Any <code>int</code> types I changed to a <code>float</code> and that fixed it. I don't understand why though. Can anyone explain?</p>
<p>Fundamentally those <code>int</code> values are only meant to be an integer because they are all discrete val... | json|python-3.x|pandas|dataframe|fastapi | 2 |
14,140 | 65,278,045 | Keras: No gradients provided for any variable | <p>I am working on a GAN based problem and I am getting this issue where the gradients are not visible. I was hoping if someone can help me here. I have two main piece of codes that might be able to help you identify the issue. First piece of code loads the data in the variables.</p>
<p><div class="snippet" data-lang="... | <p>You are using <code>numpy</code> operations in several places inside the scope of <code>GradientTape</code>, for example in the line</p>
<pre><code>fake_hr_patchs = np.reshape(fake_hr_patchs, (8,128,128))
</code></pre>
<p>Replace all <code>numpy</code> functions inside <code>GradientTape</code>'s scope with their <c... | python-3.x|tensorflow|keras|generative-adversarial-network | 1 |
14,141 | 65,174,646 | Pandas DataFrame - mixed date formatting | <p>I am trying to analyse some covid data I pulled from a csv file available online - <a href="https://api.covid19india.org/csv/latest/tested_numbers_icmr_data.csv" rel="nofollow noreferrer">https://api.covid19india.org/csv/latest/tested_numbers_icmr_data.csv</a></p>
<p>I trimmed it down to only use the Tested As Of an... | <p>If the formatting of the dates in the original file are consistent, you can supply the "format" argument in the pd.to_datetime() function. It follows the same formatting rules as Python's datetime module: <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes" rel="nofo... | python|pandas | 2 |
14,142 | 65,287,095 | Merge rows with the same date and id and append to the right side | <p>I want to merge rows with the same date and empIdn
from this dataframe:</p>
<pre><code>,empIdn,date,time_0,time_1,time_2,time_3,time_4
0,191206,2020-12-02,07:22:50,12:15:21,12:15:23,12:35:35
1,191206,2020-12-02,17:27:46,17:27:49,,
</code></pre>
<p>and I want to achieve like this:</p>
<pre><code>,empIdn,date,time_0,t... | <p>You need to first <code>melt</code> your dataframe, order it by the current <code>index</code>, <code>empIdn</code> and <code>date</code>.</p>
<p>Then use a <code>groupby.cumcount()</code> method to create a new <code>time_</code> counter based of the above ordering.</p>
<p>The final step is to create a new <code>in... | python|pandas|dataframe | 1 |
14,143 | 65,229,797 | Loop through each column | <p>I have a dataframe with n columns and I am trying to create a function which recurses through the columns.</p>
<p>for instance say I have the following data frame:</p>
<pre><code>| left | center | right |
|:---- |:------:| -----:|
| One | Two | Three |
</code></pre>
<p>I want to run a function that uses the left... | <pre><code>for i in range(1,df.shape[1]):
print(df[df.columns[0:i]])
</code></pre> | python-3.x|pandas | 1 |
14,144 | 63,884,654 | Combinations in Pandas Python (more than 2 unique) | <p>I have a dataframe where each row has a particular activity of a user:</p>
<pre><code> UserID Purchased
A Laptop
A Food
A Car
B Laptop
B Food
C Food
D Car
</code></pre>
<p>Now I want to find all the unique combinations of purchased prod... | <pre><code># updated sample data
d = {'UserID': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B', 5: 'C', 6: 'D', 7: 'C'},
'Purchased': {0: 'Laptop',
1: 'Food',
2: 'Car',
3: 'Laptop',
4: 'Food',
5: 'Food',
6: 'Car',
7: 'Laptop'}}
df = pd.DataFrame(d)
# groupby user id and combine the purchases to a tuple
new_d... | pandas | 1 |
14,145 | 64,133,696 | Pixel values change when loading image with TensorFlow Keras preprocessing | <p>I use the function tf.keras.preprocessing.image_dataset_from_directory() and when I check the content of the loaded image, I see that it contains random pixel values, inconsistent with the original image.</p>
<p>Here is how I call the funtion:</p>
<pre><code>ds = tf.keras.preprocessing.image_dataset_from_directory(
... | <p>To use the original values, use 'nearest' as interpolation to resize the image.</p>
<pre><code>ds = tf.keras.preprocessing.image_dataset_from_directory(
images_path,
label_mode=None,
shuffle=False,
seed=None,
interpolation='nearest',
image_size=(input_height, input_width),
batch_size=batc... | tensorflow|keras|deep-learning|tensorflow-datasets|preprocessor | 0 |
14,146 | 67,644,899 | What is better iteration in python? | <p>I got the result I was looking for. However, I suppose that there are a couple of ways to refactor my code below with pandas library.</p>
<p>code is simple. through 2012 - 2021, I rewrote my data from '1'(value of each year) to age of the year.</p>
<p>df:</p>
<div class="s-table-container">
<table class="s-table">
<... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>df_out = df.loc[:, "2012":].cumsum(axis=1).add(df["age"] - 1, axis=0)
df_out[df.loc[:, "2012":].eq(0)] = 0
df_out = pd.concat([df[["sex", "age", "siblings", "payment"]], df_out], axis=1)
# ... | python|pandas | 1 |
14,147 | 67,703,260 | XLM/BERT sequence outputs to pooled output with weighted average pooling | <p>Let's say I have a tokenized sentence of length 10, and I pass it to a BERT model.</p>
<pre class="lang-py prettyprint-override"><code>bert_out = bert(**bert_inp)
hidden_states = bert_out[0]
hidden_states.shape
>>>torch.Size([1, 10, 768])
</code></pre>
<p>This returns me a tensor of shape: [<em>batch_size, ... | <p>There are two simple ways to get a sentence representation:</p>
<ul>
<li>Get the vector for the <code>CLS</code> token.</li>
<li>Get the <code>pooler_output</code></li>
</ul>
<p>Assuming the input is <code>[batch_size, seq_length, d_model]</code>, where <code>batch_size</code> is the number of sentences, then to get... | python|nlp|pytorch|bert-language-model|attention-model | 1 |
14,148 | 67,957,935 | sklearn naive bayes MultinomialNB: Why do I get only one array with coefficients although I have 2 classes? | <p>I have trained a naive bayes MultinomialNB model to predict if an SMS is spam or not.</p>
<p>I get 2 classes as expected:</p>
<pre><code>nb = MultinomialNB(alpha=0.0)
nb.fit(X_train, y_train)
print(nb.classes_)
#Output: ['ham' 'spam']
</code></pre>
<p>but when I output the coefficients I get only 1 array.</p>
<pre>... | <p><strong>TL;DR</strong>:<br />
Access the <code>feature_log_prob_</code> attribute to retrieve all log probabilities of features for all classes. The <code>coef_</code> is mirroring those but returns only the values for class 1 (True) in the binary case.</p>
<hr />
<p>The problem with <code>MultinomialNB</code> is th... | python|pandas|scikit-learn|naivebayes|multinomial | 3 |
14,149 | 61,200,803 | Dose pd.read_csv skiprows parameter support skip empty lines? | <p>I have a csv file like below:</p>
<pre><code>
SUMMARY OF SURFACE ENERGY BALANCE
INCOMING NET SOLAR RADIATION BY MATERIAL NET LONG-WAVE RADIATION BY MATERIAL
SOLAR REFLECTED --... | <p>I took a quick look at the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">documentation</a> and it seems like not, the reason is because <code>header</code> ignores lines when the parameter <code>skip_blank_lines</code> is set to <code>True</code> ... | python|pandas | 0 |
14,150 | 61,518,919 | Merge tuples and numpy arrays | <p>I would like to know how to turn some tuples with numpy arrays containing different numbers, into a unique tuple, with just an array, containing all the numbers. For example:</p>
<pre><code>a=(array([0,11]),)
b=(array([12]),)
c=merge(a,b)=(array([0,11,12]),)
</code></pre>
<hr>
<p>Could someone help me? I am sti... | <pre><code>def merg():
a=(np.array([0,11]),)
b=(np.array([12]),)
return tuple(np.hstack([a,b]))
</code></pre>
<p>Results:</p>
<pre><code>>>> merg()
(array([ 0, 11, 12]),)
</code></pre> | arrays|numpy|tuples|fusion|or-operator | 0 |
14,151 | 61,514,678 | dataframe argument being changed by a function. How to avoid it being mutated? | <p>I know that the pandas dataframe is mutable. </p>
<p>I am passing a dataframe to a function and I do not want the original dataframe to be changed, but it is.
I thought as long as I reassigned the dataframe variable and avoided using .drop(inplace=True) and .reset_index(inplace=True), it would be OK, but it is not.... | <p>You can send a copy of the dataframe to the function in case if you don't want to modify change the methods inside the function:</p>
<pre><code>b = testFunc3(a.copy())
</code></pre> | python|pandas|dataframe|mutability | 2 |
14,152 | 61,370,870 | Faster RCNN only detects 20 objects per Image | <p>So I have the tensorlfow API implementation of the Faster RCNN model and I have trained it with the default values of max objects/classes (100/300) but <strong>it only detects 20 objects in every image</strong>! Not fewer nor more than 20! The problem is...there is no limit to 20...The limit was 100/300. Does anyone... | <p>maybe you use the vis_util.visualize_boxes_and_labels_on_image_array(...) to visualize your bbox, try to first modify the function, this function limits the bbox to 20...</p> | python|tensorflow|object-detection|object-detection-api|faster-rcnn | 0 |
14,153 | 68,568,479 | how to aggregate daily activities of users into weekly | <p>I have the following tables,first one (vle) has behavioral activities ( many types of activities, some shown in the activity type column), and the other (UsersVle) has users' activities.The date column represents a day and starts from 0 till 222. I want to aggregate users' activities into weeks based on the activity... | <ol>
<li>Derive a new field called <code>WEEK</code> from <code>date</code> (you haven't provided enough info about <code>date</code> to suggest how to translate it to a week (e.g. 1 = Jan 1st?))</li>
<li>Join your two tables. Is <code>id_site</code> in table 2 a foreign key for <code>id_site</code> in table 1? If so... | python|pandas-groupby|aggregate-functions | 1 |
14,154 | 68,622,639 | How is the AUC calculated for multi-class data in tensorflow? | <p>The documentation for <a href="https://www.tensorflow.org/api_docs/python/tf/keras/metrics/AUC" rel="nofollow noreferrer"><code>tf.keras.metrics.AUC</code></a> says that when estimating the AUC for multi-class data (i.e., <code>multi_label=False</code>),</p>
<blockquote>
<p>the data should be flattened into a single... | <p>To my understanding, 'flattened' means that the data will be reshaped into a one dimensional array as follows: <code>[[0, 0, 1, 0], ..., [1, 0, 0, 0]]</code> --> <code>[0, 0, 1, 0, ..., 1, 0, 0, 0]</code></p>
<p>If <code>multi_label=True</code>, AUC will be computed separately for each label, then averaged across... | python|tensorflow|keras | 1 |
14,155 | 68,826,749 | Randomly sample rows based on year-month | <pre><code>data = {'date':['2019-01-01', '2019-01-02', '2020-01-01', '2020-02-02'],
'tweets':["aaa", "bbb", "ccc", "ddd"]}
df = pandas.DataFrame(data)
df['daate'] = pandas.to_datetime(df['date'], infer_datetime_format=True)
</code></pre>
<p>So I have an object type date... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> per years and months or month periods and use custom lambda function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFr... | python|pandas|dataframe|time-series | 1 |
14,156 | 53,021,240 | Find the dictionary from List which has key-pair 'isGeo':True | <p>How to Find the dictionary from List which has key-pair 'isGeo':True</p>
<pre><code>dimensions = [{'key': 2600330, 'id': 'location', 'name': 'Location', 'isGeo': True, 'geoType': 'region'}, {'key': 2600340, 'id': 'subject', 'name': 'Subject', 'isGeo': False, 'geoType': None}, {'key': 2600350, 'id': 'measure', 'name... | <p>Use <a href="https://docs.python.org/3/library/functions.html#next" rel="nofollow noreferrer"><code>next</code></a> with a <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow noreferrer">generator expression</a>:</p>
<pre><code>res = next((d for d in dimensions if d['isGeo']), None)
{'key': 2600330, ... | python|python-3.x|pandas|list|dictionary | 2 |
14,157 | 53,301,512 | Find the frequency distribution of the first character of the name in the table in python 3 | <p>I have a table like </p>
<pre><code>key Name
1 snake
2 panda
3 parrot
4 catipie
5 cattie
</code></pre>
<p>Now I want to find the count of occurrence of first character of each row and sort in descending order and if there is a tie , it should sort in lexical order , so my output looks like :</p>
<p... | <p>Select first value by indexing <code>str[0]</code> and count by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a>:</p>
<pre><code>s = df['Name'].str[0].value_counts()
print (s)
p 2
c 2
s 1
Name: Name, dtyp... | python|python-3.x|python-2.7|pandas|jupyter-notebook | 0 |
14,158 | 65,561,379 | Problem when saving a machine learning keras model | <p>I follow this tutorial on keras
<a href="https://keras.io/examples/nlp/semantic_similarity_with_bert/" rel="nofollow noreferrer">https://keras.io/examples/nlp/semantic_similarity_with_bert/</a></p>
<p>I wanted to save the model with this command</p>
<pre><code>model.save("saved_model/my_model")
</code></pr... | <p>your first structure is inside a dict. You must extract the item from the dict to be able to get rid of your error. Try checking <a href="https://www.tutorialspoint.com/python/python_dictionary.htm" rel="nofollow noreferrer">this</a> out.</p> | tensorflow|machine-learning|keras | 0 |
14,159 | 63,333,212 | Summing values under a specific cell in pandas? | <p>I have a dataframe that looks like this, only is significantly larger. This is also part of a recurring issue I have to run monthly, so the values will always be changing:</p>
<pre><code>| Name | Category | Sales|
|-----------|----------|------|
| Product 1 | Sports | 50 |
| Friends | | 30 |
| ... | <p>One of the hardest parts of using dataframes is having the data in the right format. The best way to represent this data for working in pandas may be something like this:</p>
<pre><code>| product | group | category | sales |
| :-------|--------:|----------|-------|
| 1 | friends | sports | 30 |
| 1 ... | python|pandas | 1 |
14,160 | 53,738,873 | efficient method to read and store data which is in JSON | <pre><code>tweets_data = []
print('Opening file')
tweets_file = open('twitter_data.txt') #Its a file which has twitter data in JSON
start_time = time.time()
print('List generation in process')
for line in tweets_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
tweet... | <p>If you move your try except clause into a generator function such as this it might help:</p>
<pre><code>def readline(tweets_file):
for line in tweets_file:
try:
tweet = json.loads(line)
yield tweet
except:
continue
</code></pre>
<p>Doing this makes it so it wont ... | python|json|pandas|twitter|time | 0 |
14,161 | 53,367,921 | Adding multiple columns to dataframe and skip empty values | <p>I have a dataframe like this:</p>
<pre><code>s = {'B1': ['1C', '3A', '41A'], 'B2':['','1A','28A'], 'B3':['','','3A'],
'B1_m':['2','2','2'], 'B2_m':['2','4','2'],'B3_m':['2','2','4'],
'E':['0','0','0']}
s = DataFrame(s)
print(s)
B1 B2 B3 B1_m B2_m B3_m E
0 1C 2 2 2 0
1 3A ... | <p>One way is to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>str.replace</code></a> single digits using regex and concat column <code>E</code> as:</p>
<pre><code>s['Results'] = s['Results'].str.replace(r'\b\-[0-9]\b','')+'-'+s['E']
</c... | python|pandas|numpy|dataframe | 2 |
14,162 | 55,491,846 | Keras - How to get time taken by each layer in training? | <p>I have implemented a Keras sequential model using Tensorflow backend for the image classification tasks. It has a few custom layers to replace the Keras layers like conv2d, max-pooling, etc. But after adding these layers, though the accuracy is preserved, the training time has increased by multiple times. So I need ... | <p>This is not straightforward since each layer gets trained during each epoch. You can use callbacks to get epoch training time across the whole network however you have to do a sort of patchwork to get what you need (approximate training time of each layer).</p>
<p>The steps -</p>
<ol>
<li>create a callback to record... | python|tensorflow|keras | 6 |
14,163 | 55,153,915 | AttributeError: 'Tensor' object has no attribute 'append' | <p>I can't figure out why this code isn't working. When I make rewards into a list, I get an error telling me that the dimensions are incorrect. I'm not sure what to do.</p>
<p>I am implementing a reinforcement deep q network. r is a numpy 2d array giving 1 divided by the distance between stops. This is so that closer... | <p>the row <code>rewards.append(reward)</code> causes the error, an it is because your <code>rewards</code> variable is a Tensor, as you defined it in <code>rewards = tf.placeholder('float32',shape=[None])</code> and you can not append values to tensor like that.
You probably wanted to call <code>rewards_list.append(r... | python|tensorflow | 2 |
14,164 | 56,844,884 | Wide to Long MiltiIndex dataset using pandas | <p>I've solved a part of this question <a href="https://stackoverflow.com/questions/56801010/wide-to-long-dataset-using-pandas">Wide to long dataset using pandas</a> but still need more help.</p>
<p>I've a dataset which has columns as:
<code>IA01_Raw_Baseline</code>,<code>IA01_Raw_Midline</code>,<code>IA01_Class1_End... | <p>Since you mentioned wide to long , we using <code>wide_to_long</code></p>
<pre><code>s=pd.wide_to_long(df,['IA01_Raw'],i=['ID', 'Country', 'Type', 'Region', 'Gender','IA02_Raw', 'QA_Include',
'QA_Comments'],j='Timeline',suffix='\w+',sep='_')
s.columns=pd.MultiIndex.from_tuples(s.columns.str.split('_').map(tu... | python|pandas|multi-index | 1 |
14,165 | 47,169,313 | TensorFlow strange (random?) output expected for RegisterGradient | <p>I have created a custom op using the <a href="https://www.tensorflow.org/extend/adding_an_op" rel="nofollow noreferrer">tutorial</a>, and modified it a bit. I want to use this op as input for the <code>compute_gradients</code> method.</p>
<p>My op expects three inputs: target values, predicted values, and another m... | <p>I had the same error before. The error message was generated in tensorflow function <code>gradients_impl.py</code>.</p>
<pre><code>def _VerifyGeneratedGradients(grads, op):
"""Verify that gradients are valid in number and type.
Args:
grads: List of generated gradients.
op: Operation for which the gradi... | python|tensorflow | 0 |
14,166 | 47,220,595 | Why the 6 in relu6? | <p>I've hacked a deep feed forward NN from scratch in R, and it seems more stable with "hard sigmoid" activations - max(0,min(1,x)) - than ReLU. Trying to port it to TensorFlow, and noticed that they don't have this activation function built in, only relu6, which uses an upper cutoff at 6. Is there a reason for this?
... | <p>From <a href="https://www.reddit.com/r/MachineLearning/comments/3s65x8/tensorflow_relu6_minmaxfeatures_0_6/" rel="noreferrer">this reddit thread</a>:</p>
<blockquote>
<p>This is useful in making the networks ready for fixed-point inference.
If you unbound the upper limit, you lose too many bits to the Q part
... | tensorflow | 71 |
14,167 | 68,229,366 | How do I change the units shown on the x-axis labels on a Matplotlib bar chart | <p>I'm trying to make it so the ticks on the x-axis for revenue show the value as a factor of a million rather than as a factor of a hundred million as they are now. I can't seem to figure out how to accomplish this. My code and the resulting bar chart is below.</p>
<pre><code>import numpy as np
import pandas as pd
imp... | <p>Right now, the data is shown in ones, not millions or hundreds of millions. Notice the <code>1e8</code> on the right of the plot. You can plot the value in millions by dividing the input by a million:</p>
<pre><code>ax.barh(y_pos, average_revenue * 1e-6, ...)
</code></pre>
<p>Alternatively, you can adjust the <a hre... | python|pandas|numpy|matplotlib|bar-chart | 0 |
14,168 | 68,116,081 | Convert string in 1d array to 2d array with each character as seperate element | <p>I have a data of type pandas.core.series.Series as follows:</p>
<pre><code>print(x)
0 'School'
1 'Boy'
</code></pre>
<p>My aim is to convert it to something like (converted to 2d):</p>
<pre><code>s1 = [ ['S']['c']['h']['o']['o']['l'],
['B']['o']['y']]
</code></pre>
<p>I tried various things like <code>np.r... | <p>Calling <code>list</code> on a <code>str</code> will split it into a list of its characters:</p>
<pre><code>df = pd.DataFrame(data = ["School", "Boy"])
df[0] = df[0].map(lambda x : [list(char) for char in list(x)])
</code></pre>
<p>Now, <code>df</code> is</p>
<pre><code> ... | python|arrays|pandas|numpy | 0 |
14,169 | 68,406,189 | Import JSON file with dicts of dicts of nested dicts into Pandas | <p>I am downloading <a href="https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json" rel="nofollow noreferrer">a json file from the RKI in Germany</a> (CDC equivalent). It seems to have dictionaries inside diction... | <p>I think that your <code>features = data["features"]</code> is now a <code>list</code> of <code>dict</code>s.</p>
<p>You can iterate over those:</p>
<pre class="lang-py prettyprint-override"><code>features = data["features"]
for feature in features:
attributes = feature["attributes"]... | python|json|pandas|list|dictionary | 0 |
14,170 | 57,186,244 | How to apply LabelEncoder to a Dask DataFrame to Encode the Categorical Values | <p>I have a Dask Data Frame which is made up of categorical data and numerical (float and int) data. When I try LabelEncode the categorical columns using the code below, I get error.</p>
<pre><code>from dask_ml.preprocessing import LabelEncoder, Categorizer
encoder = LabelEncoder()
encoded = encoder.fit_transform(tr... | <p>In scikit-learn / dask-ml, LabelEncoder transforms a 1-D input. So you would use it on a pandas / dask Series, not a DataFrame.</p>
<pre><code>>>> import dask.dataframe as dd
>>> import pandas as pd
>>> data = dd.from_pandas(pd.Series(['a', 'a', 'b'], dtype='category'),
... ... | pandas|data-science|dask|dask-distributed|dask-ml | 2 |
14,171 | 57,064,546 | Grabbing a single Excel worksheet from multiple workbooks into a pandas dataframe and saving this | <p>I need to extract an Excel worksheet from multiple workbooks and saving it to a dataframe and in turn saving that dataframe. </p>
<p>I have a spreadsheet that is generated at the end of each month (e.g.<br>
June 2019.xlsx, May 2019.xlsx, April 2019.xlsx).<br>
I need to grab a worksheet 'Sheet1'from each of these w... | <p>I interpreted your statement that you want to save the dataframe as that you want to save it as a combined Excel file. This will combine all files in the folder specified that end in xlsx.</p>
<pre><code>import os
import pandas as pd
from pandas import ExcelWriter
os.chdir("H:/Python/Reports/") #edit this to be yo... | python|excel|pandas | 0 |
14,172 | 50,761,069 | Two Pandas + Map + Group by (two variables) + count | <p>I have two data frames: clients & messages</p>
<p>For each client there are several messages. Both have dates (from which I extract the day). That means for the client is the day they sign up; for the messages the day when the message is sent.</p>
<p>I can know the total messages sent for each client just with... | <p>I think need <code>join</code>:</p>
<pre><code>s = messages.groupby(['ID','Day']).size().rename('totalDay1')
clients = clients.join(s, on=['ID','Day'])
</code></pre>
<p>Sample:</p>
<pre><code>messages = pd.DataFrame({'ID':[1,2,3], 'Day':[1,2,2], 'col':[3,4,5]})
clients = pd.DataFrame({'ID':[1,2,5], 'Day':[1,2,2],... | python|pandas|dictionary|pandas-groupby | 0 |
14,173 | 66,473,286 | Package the model weights of a trained neural network to make it usable for transfer learning | <p>I have trained and evaluated a neural network on a movie's dataset. Basically, I am trying to predict the multi-class dependent variable <em>movie_genre</em> using text inputs like the plot, actors, reviews etc.</p>
<p>The model weights are saved in <code>.h5</code> format in a local path of my computer. Let's say h... | <p>If I were you I would create a small simple package and upload it to PyPI.</p>
<p>You could add your model as part of the package (if it isn’t large) using <code>MANIFEST.in</code> as described <a href="https://packaging.python.org/guides/using-manifest-in/" rel="nofollow noreferrer">here</a>.</p>
<p>On the downside... | python|tensorflow|keras|neural-network | 2 |
14,174 | 66,376,482 | Attempting to load in data and return a GeoDataFrame, getting error | <p>For a challenge, I'm trying to write a function that takes the file name of a shape file and the file name of a CSV as parameters. I want it to merge the two files at columns named <code>CTIDFP00</code> and <code>CensusTract</code> (respectively).</p>
<p>I want the function to return a GeoDataFrame.
This is currentl... | <p>You need to load the dataframes before you merge them.</p>
<pre class="lang-py prettyprint-override"><code>def loading_data(shapefile, csvfile):
df1 = #load the shapefile
df2 = #load the csvfile
merged = df1.merge(df2, left_on='CTIDFP00', right_on='CensusTract')
print(load_in_data('filepath','otherfilepath'))
</... | python|pandas|geopandas | 0 |
14,175 | 66,529,945 | Convert column vector into multi-column matrix | <p>I have a column vector with say 30 values (1-30) I would like to try to manipulate this vector so that it becomes a matrix with 5 values in the first column, 10 values in the second and 15 values in the third column. How would I implement this using Pandas or NumPy?</p>
<pre><code>import pandas as pd
#Create data
d... | <p>Try this by slicing with reindexing:</p>
<pre><code>df['T1'] = df[0][0:5]
df['T2'] = df[0][5:15].reset_index(drop=True)
df['T3'] = df[0][15:].reset_index(drop=True)
</code></pre>
<p><strong>Original data before operation:</strong></p>
<pre><code>df = pd.DataFrame(np.linspace(1,30,30))
print(df)
0
0 1.0
1 2.... | python|arrays|pandas|numpy | 1 |
14,176 | 66,651,043 | Sin2x mclaurin series python matplotlib numpy | <pre><code>import numpy as py
import matplotlib.pyplot as plt
from math import factorial as fact
def maths(x, b):
maths = np.zeros(x.shape)
for i in range(b):
maths = maths + (-1)**i * (2*x)**(2*i + 1)/fact(2*i +1)
return maths
x = np.linspace(0, 4*np.pi, 100)
img = plt.figure()
img = plt.clf()
ax ... | <p>There is nothing wrong with the math part in your code, however the coding part is a little bit off.</p>
<p>Here are a few points:</p>
<p>You should <code>import numpy as np</code> and not <s><code>import numpy as py</code></s>. Later you use it as <code>np</code> anyway.</p>
<p>The function named <code>maths</code>... | python|numpy|matplotlib | 2 |
14,177 | 66,534,643 | count of the fraction of each category | <p>I have a dataframe similar to this</p>
<pre><code>ID category fraction_0 fraction 1
A 1 1/3 2/3
A 1 1/3 2/3
A 0 1/3 2/3
C 1 0/1 1/1
B 0 1/1 0/1
</code></pre>
<p>fraction_0 and fraction_1 are output.
fraction_0 is group... | <p>Use <code>groupby</code> + <code>value_counts</code> with <code>normalize=True</code> to get the fractions. Then we need to reshape and <code>merge</code> the result back to the original.</p>
<pre><code>res = (df.groupby('ID')['category'] # For category within each ID
.value_counts(normalize=True) # ... | python|pandas | 3 |
14,178 | 57,349,824 | Recurrent neural network, time series prediction with newer Tensorflow 1.14 | <p>How to use new tf.keras API with recurrent neural network? I have checked the documentation but there is no example of such a situation.
There is this great book Hands on machine learning from 2017. Since that year the API of tensorflow has evolved and I am trying to rewrite recurrent neural network for time series ... | <p>So the answer is:</p>
<pre><code>rnn_outputs, rnn_states = tf.keras.layers.RNN(cell,dtype=tf.float32, name="hidden1", return_state=True, return_sequences=True)(X)
</code></pre>
<p>instead of </p>
<pre><code>rnn_outputs = tf.keras.layers.RNN(cell,dtype=tf.float32, name="hidden1")(X)
</code></pre>
<p>so the param... | tensorflow|keras|neural-network|time-series|recurrent-neural-network | 1 |
14,179 | 73,041,897 | Searching for a 1D torch tensor in a 2D torch tensor | <p>This seems like a very simple thing, but I couldn't find a good answer for it anywhere. Say I have a 2D Pytorch tensor <code>x</code>:</p>
<pre class="lang-py prettyprint-override"><code>tensor([[1, 2],
[3, 4],
[1, 4],
[1, 2]])
</code></pre>
<p>I want to find the indices of the row <code>[1,2... | <p>The answer that I've come up with is <code>torch.nonzero(torch.all(x==torch.tensor([1,2]), dim=1))</code>. This will output:</p>
<pre class="lang-py prettyprint-override"><code>tensor([[0],
[3]])
</code></pre>
<p>which are the precise indices I'm looking for.</p>
<p>As a further example, <code>torch.nonzero(... | python|indexing|pytorch | 0 |
14,180 | 51,532,414 | How to detect word presence and flag the issue in a separate column? | <p>I have many lists, each containing certain words i.e.</p>
<pre><code>fruits = ['apple','banana','cherry']
colours = ['red','blue','yellow']
pets = ['dog','cat','fish']
</code></pre>
<p>I have a column of text in Pandas. I want to check if my text contains any of the words within each list, and create new columns i... | <p>First create dictionary of lists with keys for columns names, then loop and for each list create pattern - join valus by <code>|</code> for regex <code>OR</code> and for more general solution use word boundary, what is used for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains... | python|pandas|text | 2 |
14,181 | 70,846,163 | Python Pandas; How do I integrate a table in another table without changing first table's total count? | <p>I have two datasets about a city. One with the persons who receive social welfare, about 50.000 persons, and one with all ca. 500.000 people living in the city. In the first table it is one person per row with the information "district, sex, age, nationality, kind of welfare". The Second table is already g... | <p>Once you calculated the aggregate function from the DataFrame you wanted (let's suppose 'myDF', and you saved it in a new variable (let's suppose 'myNewDF'), you save the results, so now worries about that.</p>
<p>However, you won't be able to merge the tables as you want, as you are comparing different data (you do... | python|pandas | 1 |
14,182 | 51,750,212 | Add list to end of a list of array in Python | <p>I want to add a list of elements at the end of the arrays of a list. I tried to use <code>np.insert</code>function like this :</p>
<pre><code>dataForModel=np.insert(dataForModel, -1, output_recoded, axis=1)
</code></pre>
<p>where <code>dataForModel</code> is a list of arrays and <code>sampling_times</code>is a 1-... | <p>Try this:</p>
<pre><code>dataForModel=np.insert(dataForModel, dataForModel.size, sampling_times, axis=1)
</code></pre>
<p>Example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-ove... | python|numpy|insert | 3 |
14,183 | 51,984,993 | Remove rows corresponding to last subgroup in each group | <p>Suppose I have the following DataFrame</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(['eggs', np.nan, 'ham', 'eggs', 'spam', 'spam',
'eggs', 'spam', np.nan], columns=['ingredients'])
df['customer'] = (['Badger']*3 + ['Shopkeeper']*3 + ['Pepperpots']*2
+ [np.nan])
df[... | <p>You can create a series consisting of groupwise "last" ingredients, then filter these out. Note, for this purpose, that <code>NaN</code> ingredients don't get removed.</p>
<pre><code>s = df.sort_values('ingredients')\
.groupby('customer')['ingredients']\
.transform('last').sort_index()
df = df[df['ingr... | python|pandas|dataframe|grouping|pandas-groupby | 2 |
14,184 | 35,919,053 | Making nonzero elements in grayscale array equal to 1 in 'G' column in an RGB array in Python | <p>So this is a problem that has stumped me for a while now. It's probably more simple than I think but lets say I have a 2D array that contains grayscale values and I am converting to RGB:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
grayscale = [[0, 0, 146, 150], [162, 0, 0, 60]]
gray = np.arr... | <p>Assuming you want to make any element that is <code>nonzero</code> in the grayscale array equal to <code>1</code> in the <code>G</code> channel and set all elements in <code>R</code> and <code>B</code> channels to <code>0</code>, irrespective of the corresponding values in grayscale, one short way would be with <a h... | python|arrays|numpy|rgb|grayscale | 2 |
14,185 | 36,156,087 | pandas warning with pd.to_datetime | <p>Using <code>pandas 0.6.2</code>. I want to change a dataframe to <code>datetime</code> type, here is the dataframe</p>
<pre><code>>>> tt.head()
0 2015-02-01 00:46:28
1 2015-02-01 00:59:56
2 2015-02-01 00:16:27
3 2015-02-01 00:33:45
4 2015-02-01 13:48:29
Name: TS, dtype: object
</code></pre>
... | <p>Just do it on the entire <code>Series</code> as <code>to_datetime</code> can operate on array-like args and assign directly to the column:</p>
<pre><code>In [72]:
df['date'] = pd.to_datetime(df['date'])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 1 column... | python|pandas | 1 |
14,186 | 36,121,122 | Inconsistent Immutability of Python Index | <p>I am relatively new to Python, and have encountered this interesting case</p>
<p>We know that Python Index objects are Immutable, meaning we can not modify the each Index value. But consider the below example</p>
<pre><code>data = DataFrame(np.arange(12).reshape((3, 4)),
index=['Ohio', 'Colorado',... | <p>Based on the documentation of <a href="https://docs.python.org/2/library/functions.html#id" rel="nofollow noreferrer"><code>id()</code></a>:</p>
<blockquote>
<p>Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. ... | python|python-2.7|pandas|indexing|immutability | 0 |
14,187 | 37,266,512 | Pandas: Timeseries data: How to select rows of an hour or a day or a minute? | <p>I have huge time series dataset in a .csv file. There are two columns in the file: </p>
<ol>
<li><code>values</code>: These are sample values.</li>
<li><code>dttm_utc</code>: These are the timestamps when the samples are collected.</li>
</ol>
<p>I've imported the data into pandas using <code>pd.read_csv(..., parse... | <p>Your example data is a <code>Series</code> but your question is asking about summing and averaging values of rows so I'm unclear on what you're trying to sum and average without example data.</p>
<p>I think what you're interested in is <code>resampling</code> but this can only be done when the datetime column (<cod... | python|python-2.7|pandas|time-series | 2 |
14,188 | 37,581,145 | Connect line of scatter plot on pandas DataFrame | <p>I'd like to add lines between dots of a scatter plot drawn by pandas. I tried this, but does not work. Can I put lines on a scatter plot?</p>
<pre><code>pd.DataFrame([[1,2],[10,20]]).plot(kind="scatter", x=0, y=1, style="-")
pd.DataFrame([[1,2],[10,20]]).plot.scatter(0,1,style="-")
</code></pre>
<p><a href="https:... | <p>A solution is to replot the line on top of the scatter:</p>
<pre><code>df = pd.DataFrame([[1,2],[10,20]])
ax = df.plot.scatter(x=0, y=1, style='b')
df.plot.line(x=0, y=1, ax=ax, style='b')
</code></pre>
<p>In this case, forcing points and lines both to be blue.</p>
<p>If you don't need the properties of the scatt... | python|pandas|matplotlib | 8 |
14,189 | 37,736,562 | pandas plugin for python in a canopy environment not sorting? | <p>I've been working on this for a few hours and am giving up at this point. I have a scientific tool that is slightly glitching and creating a .csv database with datapoints out of order, i.e.</p>
<pre><code>Test_ID Data_Point Test_Time Step_Time etc...
1 1439 1441.044976 1328.572329
1 1440 1442.046983 1... | <p>You are using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort.html" rel="nofollow noreferrer"><code>sort_values</code></a> wrongly. The parameters of the argument <code>ascending</code> have to be boolean<code>(True/False)</code> and not binary<code>(1/0)</code> values.</p>
<p>I... | python|csv|pandas | 1 |
14,190 | 37,797,093 | Creating new dataframe from existing - SettingWithCopyWarning | <p>I have a csv file that I import as a dataframe. This dataframe goes through multiple filtering steps. Data is also moved between columns based on conditionals.</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.read_csv('my_csv_file.csv', names=headers)
df2 = df.drop_duplicates(['Column_X'])
series1 = d... | <p>I believe the issue is that <code>df2</code> is a view of <code>df1</code>. Instead put a <code>.copy()</code> at the end of the <code>.drop_duplicates</code> call. </p>
<pre><code>df2 = df.drop_duplicates(['Column_X']).copy()
</code></pre> | python|pandas|chained-assignment | 1 |
14,191 | 37,866,877 | Pycharm anaconda import tensor flow library issue | <p>The following program works well under anaconda from command line interface (I am using Mac OS), but it has errors about cannot import/find tensorflow module from PyCharm (using Python 2.7). I already set Python interpreter to be anaconda in PyCharm, still got this error. If anyone have any ideas, it will be great.<... | <p>Under <code>Preferences => Project Interpreter</code> setting, is tensorflow listed among the packages?</p>
<p>Apparently No (from your screenshots).</p>
<p>Are there any other python conda installations when you use the drop down on project interpreter? If there are, try those and see what happens. The <code>t... | python|python-2.7|pycharm|tensorflow|anaconda | 8 |
14,192 | 31,287,552 | Logarithmic returns in pandas dataframe | <p>Python pandas has a pct_change function which I use to calculate the returns for stock prices in a dataframe:</p>
<pre><code>ndf['Return']= ndf['TypicalPrice'].pct_change()
</code></pre>
<p>I am using the following code to get logarithmic returns, but it gives the exact same values as the pct.change() function:</p... | <p>Here is one way to calculate log return using <code>.shift()</code>. And the result is similar to but not the same as the gross return calculated by <code>pct_change()</code>. Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?</p>
<pre><code>import pandas as pd
im... | python|pandas | 92 |
14,193 | 64,408,817 | Counting tokens in a document | <p>I would need to calculate the frequency for every token in the training data, making a list of the tokens which have a frequency at least equal to N.
To split my dataset into train and test I did as follows:</p>
<pre><code>X = vectorizer.fit_transform(df['Text'].replace(np.NaN, ""))
y=df['Label']
X_train,... | <p>Assuming you say the following works fine</p>
<pre><code>s = df.Text.str.split(expand=True).stack().value_counts()
</code></pre>
<p>Then you can do</p>
<pre><code>s[s>=15].index
</code></pre>
<p>to get the tokens with at least <code>15</code> counts.</p>
<p>However, the first line doesn't give the same tokenizati... | python|pandas|nltk | 2 |
14,194 | 64,487,579 | Adaptive rolling mean in Pd.DataFrame | <p>I'm looking to do a rolling mean on a dataframe, but the rolling mean has to cover the length of the column in a timestamp.</p>
<p>For example, in time[1] (with one row), compute rolling mean on all the column rows(1), then on time[2], do the same on all rows(2), and so on. Progressing the window as the timestamp pr... | <p>Simple moving average has a sliding window of constant size. Rolling mean is calculated by averaging data of the time series within x (generally constant) periods of time. However, you need to calculate the cumulative moving average of <code>answered_correctly</code> for each group. The cumulative moving average tak... | python|pandas|dataframe | 1 |
14,195 | 64,455,167 | Pandas dataframe replace value on condition | <p>I have the following dataframe:</p>
<pre><code> limit1 limit2
a 123 567
b 65 0
c 123 1233
d 0987 0
e 231451 0998
</code></pre>
<p>I want to create a new frame with the lower limit for each row. Except when there is a 0, in which case the value from the other column is taken.</p>
... | <p>Use <code>np.where(condition, outcome if condition is True, outcome ifcondition false)</code></p>
<pre><code>df['limit2']=np.where(df.limit2==0,df.limit1,df.min(1))
limit1 limit2
a 123 123
b 65 65
c 123 123
d 987 987
e 231451 998
</code></pre> | python|pandas | 1 |
14,196 | 47,586,251 | How to read trace file(timeline) in Tensorflow | <p>The timeline trace file is introduced here:
<a href="https://www.tensorflow.org/versions/r1.1/performance/xla/jit" rel="noreferrer">https://www.tensorflow.org/versions/r1.1/performance/xla/jit</a></p>
<p>It seems useful for performance analyzing. But there is something I can't understand.</p>
<p>1, What does "pid"... | <ol>
<li><p>'pid' stands for process identifier. According to a comment from a developer <a href="https://github.com/tensorflow/tensorflow/issues/1824#issuecomment-244251867" rel="nofollow noreferrer">here</a>, "All of the numeric 'PID's and 'TID's in the UI should be ignored- they were just invented to get CTV [Chrom... | tensorflow|timeline | 2 |
14,197 | 58,672,305 | Problem with Numba jit nonpython and numpy: All templates rejected with literals | <p>I am implementing a program that do random sampling in Python 3.6.7 and there is one function that I just can't get to compile with Numba. The most recent version of it is:</p>
<pre><code>import numpy as np
from numba import jit
@jit(nopython=True)
def bs_stat_numba(data, iter_n=1000):
iter_mean = np.mean(np... | <p>Now it works:</p>
<pre><code>@jit(nopython=True)
def bs_stat_numba(data, iter_n=1000):
iter_mean = np.mean(np.random.choice(data, size =(len(data),iter_n)))
iter_std = np.std(np.random.choice(data, size =(len(data),iter_n)))
bs_mean = np.float32(iter_mean)
bs_std = np.float32(iter_std)
retu... | python|numpy|numba | 1 |
14,198 | 58,743,424 | Unnecessary duplication is created while creating new dataframe that takes values from another by iterating over column values | <p>I am trying to add values taken from one dataframe column by iterating over unique values (contract numbers). For smaller numbers of iteration, the script works perfectly. However, iterating over 1000 unique values, it creates duplicate values in the resulting dataframe, which in turn slows the processing speed and ... | <p>This is a way without using the <code>for</code> loop to achieve the exact same result. For readability I used multiple lines to add explantion.</p>
<pre><code>df = pd.DataFrame([["AB1111",'2018-08-15 00:00:00','164'],
["AB1111",'2018-08-15 00:03:00','564'],
["AB1111",'2018-08-... | python|pandas|loops|dataframe|iteration | 1 |
14,199 | 70,262,011 | Faster way to operate columns with if conditions | <p>I need to operate a column with an IF as shown in my code. It takes quite a time to compute, is there a faster, cleaner way to do this?</p>
<p>For reference, the column "coin" have pairs like "ETH_ARS", "DAI_USD" and so on, that´s why I split it.</p>
<pre><code>for i in range(merged.sha... | <p>You can vectorize your code. The trick here is to set <code>valueUSD=1</code> when <code>coin</code> column ends with <code>USD</code>. After that the operation is the same for all rows: <code>total = price * amount / valueUSD</code>.</p>
<p>Setup a <a href="https://stackoverflow.com/help/minimal-reproducible-exampl... | pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.