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 |
|---|---|---|---|---|---|---|
371,000 | 70,221,420 | Rolling aggegrates per date in pandas with duplicate date entries | <p>I'm working with a dataset that contains the sale prices of different objects per day. What I would like to achieve is that for any given date in the dataset to compute the overall average for a fixed number of days preceding a sale (not including the sale date), ideally in a vectorized manner since the original dat... | <p>Since the rolling windows include previous members of the same day, you can use this less intuitive approach to calculate a closed 2-day interval, sample the last value from each day, and then join/merge those results with the <em>following</em> day.</p>
<pre><code>totals_3day_window = df.set_index('date').rolling('... | python|pandas|dataframe | 1 |
371,001 | 70,293,606 | Compute percentage changes with next row Pandas | <p>I want to compute the percentage change with the next n row. I've tried pct_change() but I don't get the expected results</p>
<p>For example, with n=1</p>
<pre><code> close return_n
0 100 1.00%
1 101 -0.99%
2 100 -1.00%
3 99 -4.04%
4 95 7.37%
5 102 NaN
</code></pre>
<p>With n=2</... | <p>You can do <code>shift</code> with <code>pct_change</code></p>
<pre><code>n = 2
df['new'] = df.close.pct_change(periods=n).shift(-n)
df
Out[247]:
close return_n new
0 100 1.00% 0.000000
1 101 -0.99% -0.019802
2 100 -1.00% -0.050000
3 99 -4.04% 0.030303
4 95 7.37% NaN
5 ... | python|pandas | 2 |
371,002 | 70,139,705 | Selecting specific values out of a column in pandas dataframe | <p>I have a column, 'state', that has the values 'failed', 'successful', and two or three other values.</p>
<p>I am trying to create a dataframe with only the rows that contain 'failed' and 'successful' in the 'state' column.</p>
<p>I have implemented the following code:</p>
<pre><code>df = df[df['state'].str.contains(... | <p>The issue is that the expression <code>"failed" or "successful"</code> evaluates to <code>"failed"</code> since the non-empty string <code>"failed"</code> is truthy. Read <a href="https://stackoverflow.com/questions/47007680/how-do-and-and-or-act-with-non-boolean-values">this ... | python|pandas | 1 |
371,003 | 70,336,182 | Extracting Floating Values from A String In A Dataframe | <p>I have the following dataframe, <code>df</code>:</p>
<pre><code>name result
AAA 4.5
BBB UNK
CCC less than 2.45
DDD Men > 40: 2.5-3.5
</code></pre>
<p>The <code>dtypes</code> of the <code>result</code> column is <code>dtype('O')</code></p>
<p>I need to extract the float values... | <p>You can use <code>extractall</code> to extract all float number occurrences, then use <code>max</code> to take only the max value.</p>
<pre><code>>>> ext = (df.result.str.extractall(r'(\d+.\d+)')
.astype(float)
.unstack()
.max(axis=1))
>>> ext
0 4.50
2 2.45
3 3.50
</c... | python|pandas|string|dataframe|data-manipulation | 2 |
371,004 | 70,240,387 | AttributeError: module 'keras.utils' has no attribute 'to_categorical' | <pre><code>from keras.preprocessing.text import text_to_word_sequence
import pandas as pd
from keras.preprocessing.text import Tokenizer
import numpy as np
# from __future__ import print_function
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activa... | <p>Newer versions of keras==2.4.0 and tensorflow==2.3.0 would work as follows
so use:</p>
<pre><code>from keras.utils import np_utils
</code></pre>
<p>and then replace <code>keras.utils.to_categorical</code> with</p>
<pre><code>keras.utils.np_utils.to_categorical
</code></pre> | python|tensorflow|keras | 19 |
371,005 | 70,099,593 | pandas find start and stop point of non-null values | <p>I'd like to find the start and stop points of a column and flag them as shown below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>value</th>
<th>flag</th>
</tr>
</thead>
<tbody>
<tr>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>1</td>
<td>start</td>
</... | <ul>
<li><code>start</code> occurs when the current value is <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.notnull.html" rel="nofollow noreferrer"><code>notnull</code></a> and the previous value <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isull.html" rel="nofollow noreferre... | python|pandas|dataframe | 5 |
371,006 | 70,215,894 | Pandas - find second largest value in each row | <p>Good morning! I have a three column dataframe and need to find the second largest value per each row</p>
<pre><code>DATA=pd.DataFrame({"A":[10,11,4,5],"B":[23,8,3,4],"C":[12,7,11,9]})
A B C
0 10 23 12
1 11 8 7
2 4 3 11
3 5 4 9
</code></pre>
<p>I tried using n... | <pre><code>import pandas as pd
df=pd.DataFrame({"A":[10,11,4,5],"B":[23,8,3,4],"C":[12,7,11,9]})
# find the second largest value for each row
df['largest2'] = df.apply(lambda x: x.nlargest(2).iloc[1], axis=1)
print(df.head())
</code></pre>
<p>result:</p>
<pre><code> A B C larg... | python|pandas|dataframe | 3 |
371,007 | 70,216,222 | Pytorch is throwing an error RuntimeError: result type Float can't be cast to the desired output type Long | <p>How should I get rid of the following error?</p>
<pre><code>>>> t = torch.tensor([[1, 0, 1, 1]]).T
>>> p = torch.rand(4,1)
>>> torch.nn.BCEWithLogitsLoss()(p, t)
</code></pre>
<p>The above code is throwing the following error:</p>
<p><strong>RuntimeError: result type Float can't be cast to... | <p><code>BCEWithLogitsLoss</code> requires its target to be a <code>float</code> tensor, not <code>long</code>. So you should specify the type of <code>t</code> tensor by <code>dtype=torch.float32</code>:</p>
<pre class="lang-py prettyprint-override"><code>import torch
t = torch.tensor([[1, 0, 1, 1]], dtype=torch.floa... | python-3.x|pytorch|torch | 3 |
371,008 | 70,043,222 | adding one day to a dataframe date column..keeps returning an error | <p>I have downloaded some data from yahoo finance, but the displayed date is out by one day IE the last row of the data frame has the date of 11/19 when it should 11/20. Even though I have a dirty fix for this that seems to work, I keep getting this error and it concerns me</p>
<p>:2: SettingWithCopyWarning:
A value is... | <p>This should remove the warning</p>
<pre><code>S1 = S1.assign(NewDate=S1['Date']+pd.Timedelta(days=1))
</code></pre> | python|pandas | 0 |
371,009 | 70,209,472 | Python : How can i iterate 3 row values from dataframe at a single time? And then again next 3 values at a single time? | <p>I have a data frame -</p>
<pre><code>Name Rank
A 2
B 3
C 6
D 7
E 4
F 3
G 9
H 2
I 5
</code></pre>
<p>I want Rank Column 3 values at a time.
such as -</p>
<pre><code>2
3
6
</code></pre>
<p>and Next again I want to Rank Column 3 values at a time.
such as -</p>
<pre><code>3
6
7
</cod... | <p>Let us do</p>
<pre><code>[df.Rank.tolist()[x:x+3] for x in df.index[0:-2]]
[[2, 3, 6], [3, 6, 7], [6, 7, 4], [7, 4, 3], [4, 3, 9], [3, 9, 2], [9, 2, 5]]
</code></pre> | python|pandas|loops|iteration | 0 |
371,010 | 70,042,123 | How to substitute 2D IndexedBase variable in Sympy | <p>Can I substitute a 2D IndexedBase that is in an expression for a numpy array using <code>sympy.subs()</code> or <code>sympy.evalf(subs=())</code>?</p>
<p>So something like:</p>
<pre><code>i, j, m, n = sp.symbols('i j m n', integer=True)
x = sp.IndexedBase('x')
a = sp.IndexedBase('a')
b = sp.IndexedBase('b')
f = sp.... | <p>You can do this with <code>lambdify</code> like this:</p>
<pre><code>In [36]: i, j, m, n = sp.symbols('i j m n', integer=True)
...: x = sp.IndexedBase('x')
...: a = sp.IndexedBase('a')
...: b = sp.IndexedBase('b')
...:
...: f = sp.ln(sp.Sum(sp.exp(sp.Sum(a[i, j]*x[j]+b[i], (j, 0, n-1))), (i, 0, ... | python|numpy|sympy | 1 |
371,011 | 70,081,416 | np.log in a for loop, I always get TypeError: 'numpy.float64' object is not callable | <p>I have a really easy dataset with just one column, and I would like to have a for loop over each row of the dataframe so that for each row it calculate the log of <code>current_close_price/first_row_close_price</code>. Whatever I do, it says:</p>
<blockquote>
<p>TypeError: 'numpy.float64' object is not callable</p>
... | <p>Consider we have the table in <code>a.csv</code> file, which have two columns <em>Date</em> and <em>Close</em>, and writing <code>first_row_price</code> instead of <code>reference_price</code> in your code:</p>
<pre><code>with open("a.csv", 'r') as a:
price = pd.read_csv(a, usecols=[1]) # which get da... | python|numpy | -1 |
371,012 | 70,114,244 | Unbelievable difference of custom metric between fit and evaluate | <p>I run a tensorflow u-net model without dropout (but BN) with a custom metric called "average accuracy". This is literally the section of code. As you can see, datasets must be the same as I do nothing in between <code>fit</code> and <code>evaluate</code>.</p>
<pre><code>model.fit(x=train_ds, epochs=epochs,... | <p>I tried to reproduce this behavior but could not find the discrepancies you noted. The only thing I changed was <code>not tf.equal</code> to <code>tf.math.not_equal</code>:</p>
<pre class="lang-py prettyprint-override"><code>import pathlib
import tensorflow as tf
dataset_url = "https://storage.googleapis.com/d... | python|tensorflow | 1 |
371,013 | 70,163,018 | Python: Generate weekly timestamps | <p>How can I generate weekly timestamps in Python?</p>
<p>I want something that looks like this:</p>
<pre><code>2021-01-07 12:00:00
2021-01-14 12:00:00
2021-01-21 12:00:00
etc...
</code></pre>
<p>I also want to convert these to UNIX timestamps.</p>
<p>Is there a way to do all this in one step?</p>
<p>Thank you!</p> | <p>Check <a href="https://pandas.pydata.org/docs/reference/api/pandas.date_range.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.date_range.html</a></p>
<pre class="lang-py prettyprint-override"><code>pd.date_range('2021-01-07 12:00:00', '2021-01-21 12:00:00', freq='7D')
</code></pre... | python|pandas|datetime|unix|timestamp | 1 |
371,014 | 70,376,102 | How Can I extract class value and save in csv using selenium? | <p>How Can I extract the value using selenium and python, My end goal is to store this value in a csv.</p>
<p>What I have tried:</p>
<pre class="lang-py prettyprint-override"><code>#element= driver.find_element_by_xpath("//*[@class='rt-tr-group']")
elements = driver.find_elements_by_class_name("product-... | <p>Looks like you are missing a wait / delay.<br />
Try this</p>
<pre class="lang-py prettyprint-override"><code>wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".product-form__price")))
time.sleep(0.5)
elements = driver.find_elements_by_class_name("product-form__price")
for value in e... | python|pandas|selenium|web-scraping|beautifulsoup | 0 |
371,015 | 70,323,357 | Opposite of factorize function (Map numeric to categorical values) | <p>I am searching for a way to map some numeric columns to categorical features.</p>
<p>All columns are of categorical nature but are represented as integers. However I need them to be a "String".</p>
<p>e.g.</p>
<pre><code>col1 col2 col3 -> col1new col2new col3new
0 1 1 -> "0" ... | <p>You can use <code>applymap</code> method. Cosider the following example:</p>
<pre><code>df = pd.DataFrame({'col1': [0, 2, 1], 'col2': [1, 2, 3], 'col3': [1, 3, 2]})
df.applymap(str)
col1 col2 col3
0 0 1 1
1 2 2 3
2 1 3 2
</code></pre>
<p>You can convert all elements of <code>col1</co... | python|pandas|numpy|categorical-data | 0 |
371,016 | 70,340,795 | Replacing a column in a dataframe with another dataframe column using partial string match | <p>I have the large CSVs with following sample dataframes:</p>
<pre><code>df1 =
Index Fruit Vegetable
0 Mango Spinach
1 Berry Carrot
2 Banana Cabbage
</code></pre>
<pre><code>df2 =
Index Unit Price
0 Mango_123 30
1 234_Artichoke_CE ... | <p>You can use fuzzy matching with <a href="https://github.com/seatgeek/thefuzz" rel="nofollow noreferrer"><code>thefuzz.process.extractOne</code></a>, that will compute the closest match using <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Levenshtein Distance</a>:</p>
<pre><cod... | python|pandas|string|dataframe|merge | 3 |
371,017 | 70,048,861 | Why pandas dataframe doesn't change when i used it as a input of a function with multiprocessing | <p>I have a code like this:</p>
<pre><code>df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "C2", &... | <p>Serializing <code>df1</code> & <code>df2</code> for multiprocessing means that you're making a copy.</p>
<p>Return your dataframe from the function and it'll work fine.</p>
<pre><code>def changeDF(df):
df['Signal'] = 0
return(df)
with multiprocessing.Pool(processes=2) as pool:
df1, df2 = pool.map(ch... | python|pandas|list|dataframe|python-multiprocessing | 2 |
371,018 | 70,242,838 | How to find row with the highest value for the day in pandas and gets the categorial percentages? | <p>Here is my dataset:</p>
<pre><code>date CAT_A CAT_B CAT_C
2018-01-01 5:00 12 223 155
2018-01-01 6:00 199 68 72
...
2018-12-31 23:00 56 92 237
</code></pre>
<p>The data shows every hour for every day of the year. So I want to know in pandas how I c... | <p>We sum the three columns:</p>
<pre><code>df["sum_categories"] = df.sum(axis=1)
</code></pre>
<p>We groupby on daily basis and obtain the index of the max daily row:</p>
<pre><code>idx = df.resample("D")["sum_categories"].idxmax()
</code></pre>
<p>We select the rows with this index and c... | python|pandas | 1 |
371,019 | 70,340,131 | How to make Date a column in dataframe | <p>I have the below dataframe and i am trying to display how many rides per day.<br/>
But i can see only 1 column "near_penn" is considered as a column but "Date" is not.</p>
<pre><code>c = df[['start day','near_penn','Date']]
c=c.loc[c['near_penn']==1]
pre_pandemic_df_new=pd.DataFrame()
pre_pande... | <pre><code>df[['Date','near_penn']] = df[['Date_new','near_penn_new']]
</code></pre>
<p>Once you created your dataframe you can try this to add new columns to the end of the dataframe to test if it works before you make adjustments</p>
<p>OR</p>
<p>You can check for a value for the first row corresponding to the first ... | python|pandas|date | 0 |
371,020 | 70,301,787 | Decide which category to drop in pandas get_dummies() | <p>Let's say I have the following df:</p>
<pre><code>data = [{'c1':a, 'c2':x}, {'c1':b,'c2':y}, {'c1':c,'c2':z}]
df = pd.DataFrame(data)
Output:
c1 c2
0 a x
1 b y
2 c z
</code></pre>
<p>Now I want to use pd.get_dummies() to one hot encode the two categorical columns c1 and c2 and drop the fir... | <p>One trick is replace values to <code>NaN</code>s - here is removed one value per rows:</p>
<pre><code>#columns with values for avoid
d = {'c1':'b', 'c2':'z'}
d1 = {k:{v: np.nan} for k, v in d.items()}
df = pd.get_dummies(df.replace(d1), columns = ['c1', 'c2'], prefix='', prefix_sep='')
print (df)
a c x y
0 1... | python|pandas|categorical-data|one-hot-encoding|dummy-variable | 1 |
371,021 | 70,224,409 | How to count the number of occurrences on comma delimited column in Python Pandas | <p>How can to count the number of occurrences of comma-separated values from the whole list of columns</p>
<p>data frame is like this:</p>
<pre><code>id column
1
2 1
3 1
4 1,2
5 1,2
6 1,2,4
7 1,2,4
8 1,2,4,6
9 1,2,4,6
10 1,2,4,6,8
11 1,2,4,6,8
</code></pre>
<p>Desired output is:</p>
<pre><code>id c... | <p>You can do as follows:</p>
<pre><code>df['count'] = df['id'].apply(lambda x: df['column'].fillna('X').str.contains(str(x)).sum())
</code></pre>
<p>This is basically counting the number of occurence of each <code>id</code> in the column.</p>
<p>Output:</p>
<pre><code> id column count
0 1 None 10
1 ... | python|pandas|dataframe|csv|spreadsheet | 1 |
371,022 | 70,164,347 | Put a dictonary in a single cell of excel in python (pref w/o pandas) | <p>I have a dictonary which i want to put in an single excel cell.</p>
<pre><code>import datetime
my_dict = {
'key1': 'MOCK-12345-67890:09876',
'key2': 'MOCK-abcdef-ghijklmnop',
'key3': datetime.datetime.now(), # datetime format
# ...
'key15': 15029.62946216, ... | <p>As you can see in your code, pandas uses 'openpyxl' as an engine. So it is quite a way-around method. You can just use openpyxl directly as below.</p>
<pre><code>import openpyxl as xl
import datetime
my_dict = {
'key1': 'MOCK-12345-67890:09876',
'key2': 'MOCK-abcdef-ghijklmnop',
'key3':... | python|excel|pandas | 0 |
371,023 | 70,058,055 | Use any() command in Python if statement | <p>I'm trying to write an <code>if</code> statement in Python that iterates over the rows of a DataFrame. If that row meets one of several possible conditions, it does a calculation. My MWE is:</p>
<pre><code>import numpy as np
import pandas as pd
coin = ['a','b','c'] # conditions
xlist = pd.DataFrame() # data
xlist[... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a>:</p>
<pre><code>In [846]: l = np.where(xlist['... | python|pandas | 2 |
371,024 | 70,363,817 | How to zero particular elements using a mask in python? | <p>I ran into a simple problem, where I wanted to assign values according to a mask that represents a position of elements in an array. For instance <code>array[*,1] = 0</code> but this code obviously would not work.</p>
<p>After a little thought I have come up with this:</p>
<pre><code>import numpy as np
a = np.rando... | <p>Just slice the array with <code>a[:, 1] = 0</code> if you want all entries of the first column to be zero.</p>
<p>If you want to use a condition statement look into np.where, which can be used to index the array according to <code>a[np.where(condition)] = 0</code></p> | python|arrays|python-3.x|numpy | 1 |
371,025 | 70,256,975 | Why is this function not paralleled? | <p>I have a dataframe <code>df2</code> which is a copy of <code>df</code>. For each unique value c in column <code>col_2</code>. I would like to extract at random 2 rows whose corresponding values in <code>col_2</code> is c. If the number of available rows is less than 2, then I extract all the rows. Then I label the s... | <p>I'm not sure <code>multiprocessing</code> is the right answer. Save the code below and execute it. I created a DataFrame with 40,000,000 records and 2500 groups. In this code, you have 2 implementations for multi processing and single processing.</p>
<p>Output:</p>
<pre><code>Dataframe: 40000000 records for 2500 gro... | python|pandas|multiprocessing | 1 |
371,026 | 70,317,646 | Replace multiple column values if a value is the same in both data frames | <pre><code> 0 1 2 3 4 5 6 7 8 9
0 1 Биир биир NUM num NumType=Card _ _ _ _
1 2 паартаҕа паарта NOUN n Case=Dat|Number=Sing _ _ _ _
2 3 киһи киһи NOUN n Case=Nom|Number=Sing _ _ _ _
3 4 олорор олор VERB v Person=3|Tense=Pr... | <p>one way is to: 1.concat, 2.drop_duplicates, 3.filter, 4.sort, here goes:</p>
<pre><code>df = pd.concat([df2, df1]).drop_duplicates('1', keep='last')
df = df[df['1'].isin(df2['1'])].sort_values('0')
</code></pre>
<p>df:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: ri... | python|arrays|pandas|dataframe|numpy | 1 |
371,027 | 70,236,736 | Pytorch - skip calculating features of pretrained models for every epoch | <p>I am used to work with tenserflow - keras but now I am forced to start working with Pytorch for flexibility issues. However, I don't seem to find a pytorch code that is focused on training only the classifciation layer of a model. Is that not a common practice ? Now I have to wait out the calculation of the feature ... | <p>Assuming you already have the features ìn <code>features_x</code>, you can do something like this to create and train the model:</p>
<pre><code># create a loader for the data
dataset = torch.utils.data.TensorDataset(features_x, Y_train)
loader = torch.utils.data.DataLoader(dataset, batch_size=16, shuffle=True)
# de... | keras|pytorch|feature-extraction|pre-trained-model | 0 |
371,028 | 70,179,159 | Columns must be same length as key. Why I'm getting such error? can anyone help me out? | <pre><code>cols = ["Gender", "Married", "Education", "Self_Employed", "Property_Area", "Loan_Status", "Dependents"]
for col in cols:
df[col] = pd.get_dummies(df[col], drop_first=True)
</code></pre> | <p><code>get_dummies</code> generates <code>DataFrame</code> which may have many columns (even if you use <code>drop_first=True</code>) and you need <code>join()</code> to add all new columns.</p>
<p>And later you can use <code>del df[col]</code> to remove old column.</p>
<hr />
<p>Minimal example:</p>
<pre><code>impor... | python|pandas | 0 |
371,029 | 70,098,916 | ImportError after installing torchtext 0.11.0 with conda | <p>I have installed <code>pytorch</code> version 1.10.0 alongside <code>torchtext</code>, <code>torchvision</code> and <code>torchaudio</code> using conda. My PyTorch is cpu-only, and I have experimented with both <code>conda install pytorch-mutex -c pytorch</code> and <code>conda install pytorch cpuonly -c pytorch</co... | <p>So in order to fix the problem, I had to change my <code>environment.yaml</code> in order to force <code>pytorch</code> to install from the <code>pytorch</code> channel.</p>
<p>So this is my <code>environment.yaml</code> now:</p>
<pre><code>channels:
- defaults
- pytorch
- conda-forge
dependencies:
# ML sect... | pytorch|conda|torchtext | 0 |
371,030 | 70,359,626 | Apply arithmetic operation from json file to dataframe without using eval function | <p>I have json file contains arithmetic operation list to apply in dataframe columns,
I used <strong>eval</strong> function , but i could not use eval function due to security issue, how can apply arithmetic operation from json file without using <strong>eval</strong> function
my df function will be like the below tab... | <p>I think security problem is with python <code>eval</code>, in pandas is <a href="https://pandas.pydata.org/docs/user_guide/enhancingperf.html#expression-evaluation-via-eval" rel="nofollow noreferrer">no this problem</a>:</p>
<blockquote>
<p>Neither simple nor compound statements are allowed. This includes things lik... | python|pandas|dataframe | 2 |
371,031 | 70,143,714 | Optimize the use of numpy for creating a 3d-matrix | <p>I've been trying to optimize the construction of matrix C (see below) by using NumPy.
How could my code be further optimized so as to make the building of matrix C faster?</p>
<p>Given the following matrixes:</p>
<pre><code>Q: array([[78.66 , 47.196 , 31.464 ],
[40.3875, 24.2325, 16.155 ],
[... | <p>you can remove the loop in k since it's used by all of the arrays as follows:</p>
<pre class="lang-py prettyprint-override"><code># # Matrix C_ijk
C = np.zeros((n,o,p))
for i in range(n):
for j in range(o):
for u in range(m-1):
if np.isin(i,S[j][u]):
C[i,j,:] = Q[j,:] * gamma... | python|numpy|matrix|numba | 2 |
371,032 | 70,219,700 | Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) error | <p>I try to train a tensorflow model. But I got error.</p>
<p><code>Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).</code></p>
<p>Here my fit codes:</p>
<p><code> model.fit(self.datas.trainImages, self.datas.trainLabels,self.datas.batch_size, epochs =self.datas.epochs)</code></p>
<p... | <p>Would it be possible to print out some type of error output?</p>
<p>Personally, I was having a similar issue and by coating my input with "np.stack()" it added an extra dimension, changed the shape of the array and allowed it to work.</p>
<p>i.e.</p>
<pre><code>images = np.stack(self.data.trainImages)
</co... | python|numpy|tensorflow | 2 |
371,033 | 70,033,704 | How to interpret the output of a RNN with Keras? | <p>I would like to use a RNN for time series prediction to use 96 backwards steps to predict 96 steps into the future. For this I have the following code:</p>
<pre><code>#Import modules
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import StandardScaler
from tensorflow import... | <p>I disagree with @danielcahall on just one point:</p>
<blockquote>
<p>The output tensor from your model contains the predicted values for 96 steps into the future, for each sample</p>
</blockquote>
<p>The output does contain 96 time steps, one for each input time step, and you can take an output to mean whatever you ... | python|tensorflow|keras|time-series|recurrent-neural-network | 2 |
371,034 | 70,148,757 | Seaborn heatmap change date frequency of yticks | <p>My problem is similar to the one encountered on this topic: <a href="https://stackoverflow.com/questions/66897981/change-heatmaps-yticks-for-multi-index-dataframe">Change heatmap's yticks for multi-index dataframe</a></p>
<p>I would like to have yticks every 6 months, with them being the index of my dataframe. B... | <p>Here are a couple ways to adapt that link for your use case (1 label per 6 months):</p>
<ol>
<li><p><strong>Either:</strong> Show an empty string except on Jan 1 and Jul 1 (i.e., when <code>%m%d</code> evals to <code>0101</code> or <code>0701</code>)</p>
<pre><code>labels = [date if date.strftime('%m%d') in ['0101',... | python|pandas|datetime|matplotlib|seaborn | 4 |
371,035 | 70,328,027 | Code optimisation using numpy array. Is there a better solution? | <p>I am trying to optimise a function that calculates : <em><strong>a*exp(b*x)+c</strong></em></p>
<p>I tested three methods using numpy arrays :</p>
<pre><code>def model(a,b,c,x):
return a*np.exp(b*x)+c
def myFoo1(modelParam,x):
return([model(*i,x) for i in modelParam])
def myFoo2(modelParam,x):
return([i... | <p>I got small improvement by using slightly different way of broadcasting</p>
<pre><code>def myFoo4(modelParam,x):
return modelParam[:, 0:1] * np.exp(modelParam[:, 1:2] * x) + modelParam[:, 2:3]
</code></pre>
<p>And another small improvement by switching to <code>np.float32</code></p>
<pre><code> x_float32 = np... | python|numpy|optimization|numpy-ndarray | 2 |
371,036 | 56,434,404 | How can I reduce loss with my keras TensorFlow model? | <p>So I have a dataset of about 140,000 samples with 5 inputs, the velocity of the car, the acceleration of the car, the velocity of the lead car gathered with radar, the distance of the lead car, and the acceleration of the lead car. The output is from 0 to 1, 0 being maximum brake, and 1 being max acceleration.</p>
... | <p>I'd like to help but there's not too much info there.</p>
<p>First what's the aim of the network? It's hard to tell what you're trying to reduce the loss <strong>of</strong>. What's your loss function? What are your labels? This seems like a classic reinforcement learning question, rather than a traditional supervi... | python|tensorflow|keras | 0 |
371,037 | 56,266,607 | Iterate through each dataframe header and update int month to str month if and only if the header string has '20' in it | <p>A few Django formatting issues which require df header changes. </p>
<p>Test data:</p>
<pre><code>Test_Data = [
('Year_Month', ['Done_RFQ','Not_Done_RFQ','Total_RFQ']),
('2018_11', [10, 20, 30]),
('2019_06',[10,20,30]),
('2019_12', [40, 50, 60]),
... | <p>IIUC</p>
<pre><code>s=pd.Series(df.columns)
s2=pd.to_datetime(s,format='%Y_%m',errors ='coerce').dt.strftime('%Y_%b')
df.columns=s2.mask(s2=='NaT').fillna(s)
df
Out[368]:
2018_Nov 2019_Jun 2019_Dec Year_Month
0 10 10 40 Done_RFQ
1 20 20 50 Not_Done_RFQ
2 ... | python|pandas|dataframe | 1 |
371,038 | 56,216,884 | SSDmobilenet pets config -> Faced error when tried to created tflite pb file from customize checkpoint created from transfer training | <p>Faced error when tried to created tflite pb file from customize checkpoint created from transfer training</p>
<p>System information :</p>
<pre><code>ubuntu - 18.0
tf.VERSION = 1.14.1-dev20190517
tf.GIT_VERSION = v1.12.1-2154-g3df6d99f3f
tf.COMPILER_VERSION = v1.12.1-2154-g3df6d99f3f
env : LD_LIBRARY_PATH /usr/loca... | <p>This is a bug with the script. We will fix it shortly.
Thanks for flagging!</p> | tensorflow | 0 |
371,039 | 56,177,445 | Change column format from Seconds to Minutes | <p>I have a DF with several columns with the data in seconds e.g: 600, which I want to convert to minutes with the following format 00:10:00. </p>
<p>I have found the following code and ran some tests it does work as expected, however, I have several columns which I want to change the format and I'm looking for the mo... | <pre><code>df = pd.DataFrame({'Time': [600,1200,1800,2000]})
pd.to_timedelta(df['Time'], 's')
0 00:10:00
1 00:20:00
2 00:30:00
3 00:33:20
</code></pre>
<p>You can make it a timedelta, and tell it that your column is seconds.</p> | python|pandas | 3 |
371,040 | 56,014,482 | Pandas : Optimizing, deleting a loop | <p>I am working on a set of data which i need to clean, around <strong>400.000 lines</strong>.</p>
<p>Two actions to make: </p>
<ol>
<li><p>Resale Invoice Month are objects <code>'M201705'</code>. I want to make a column named <code>'Year'</code> with only the year in that case <code>2017</code>. </p></li>
<li><p>Som... | <p>To get the year as characters 1-4 use <code>Series.str[indices]</code>:</p>
<pre><code>Ndata['Year'] = Ndata['Resale Invoice Month'].str[1:5]
</code></pre>
<p>To remove 'TR' from the end of the string use <code>Series.str.replace</code>. Here <code>$</code> matches the end of the string:</p>
<pre><code>Ndata['Com... | python|pandas | 3 |
371,041 | 56,221,185 | Refer to column of a data frame that is being defined | <p>I am trying to create a dataframe in pandas <em>and directly use one of the generated columns</em> to assign a new column to the same df.<br>
As a simplified example, I tried to multiply a column of a df using assign:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([['A', 1], ['B', 2], ['C', 3]] , columns = ['... | <p>Use lambda function, more information in <a href="http://pandas.pydata.org/pandas-docs/stable/getting_started/dsintro.html#dsintro-chained-assignment" rel="nofollow noreferrer">Assigning New Columns in Method Chains</a>:</p>
<pre><code>df = (pd.DataFrame([['A', 1], ['B', 2], ['C', 3]] , columns = ['col1', 'col2'])
... | python|pandas | 2 |
371,042 | 56,023,054 | Rename substring of column values of a python DataFrame | <p>My problem:
I have a datetime columns, with formats like </p>
<pre><code>'27SEP18:05:02:11'
</code></pre>
<p>When trying to convert the datetime values I started like</p>
<pre><code>df['dtimes'] = pd.to_datetime(df['dtimes'],format = '%d%b%Y:%H:%M:%S')
</code></pre>
<p>and ran into the problem that 'SEP' is not... | <p>Use <code>%y</code> for match year in format <code>YY</code>, <code>%Y</code> is used for <code>YYYY</code> format:</p>
<pre><code>#YY format of year - %y
df = pd.DataFrame({'dtimes':['27SEP18:05:02:11','27JAN18:05:02:11']})
df['dtimes'] = pd.to_datetime(df['dtimes'],format = '%d%b%y:%H:%M:%S')
print (df)
... | python-3.x|pandas|dataframe|bigdata|data-conversion | 1 |
371,043 | 56,012,767 | How to index multiple values in place of a single value, but maintain shape as though it was a single value? | <p>I have a problem for which I cannot find a solution regarding some Numpy code I'm writing. To give some background, I want to implement latency in a neural network. The neural network has an input array <code>x</code> which has a size <code>[time, trials, neurons]</code>, and I'd like to assign a certain temporal ... | <p>If I understand you correctly, you just need basic indexing:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
time, trials, neurons = (100, 256, 16)
a, b = (8, 12)
x = np.random.rand(time, trials, neurons)
L = np.random.randint(a, b, size=neurons)
# let's say the time t=50
x1 = []
for n in r... | python|numpy|indexing | 1 |
371,044 | 56,178,261 | Real Time FFT Plotting In Python ( MatPlotLib) | <p>I have an incoming audio stream via my microphone which pyaudio is reading, im performing FFT calculations to that data and what i would like is to plot the FFT amplitude data on the Y axis, and the FFT frequency Data on the X axis and have it update at (lets say 20fps for example), basically to look like this ( <a ... | <p>I can't generate data for you but I wrote an example which updates a matplotlib graph in a loop:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import time
plt.ion() # Stop matplotlib windows from blocking
# Setup figure, axis and initiate plot
fig, ax = plt.subplots()
xdata, ydata = [], []
ln... | python|numpy|matplotlib|fft|pyaudio | 3 |
371,045 | 56,246,583 | How to output a 2-D matrix from a neural network in Keras with softmax applying for each column? | <p>I am trying to implement a neural network, which output a 2-D matrix with softmax activation for each column.</p>
<p>I have done this with the code below, but it seems very slow when the number of columns increase.</p>
<pre><code>input = Input(shape=[100])
h1 = Dense(200, activation='relu')(input)
output = []
for ... | <p>You could try using a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehension</a>, which are known to be <em>generally</em> faster than for-loops.</p>
<p>Instead of:</p>
<pre><code>output = []
for i in range(n_cols):
output.append(Dense(... | python-3.x|tensorflow|keras|neural-network | 0 |
371,046 | 56,337,844 | How to compare all entries in columns of 2 csv files (csv1 and csv2) in python/pandas? | <p>I have 2 CSV files:</p>
<p>CSV1:</p>
<pre><code>"Hypervisor","IP","ABCD","Operating System","Domain","Memory","No. CPU","Availability (%)","Last Collection Time","lol"
"lglac125.lss.com","10.247.52.125","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599031E9"
"lglac126.lss.com","10.... | <p>You can try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> and <code>indicator=True</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow norefer... | python|python-3.x|pandas|csv|file-io | 2 |
371,047 | 56,072,283 | How can I append data from a old dataframe onto a new, blank dataframe | <p>So I am trying to do something relatively simple, create a blank dataframe and add a new dataframe to it, however this won't work, everything I have looked at has told me to due it this way with append. However, it is not working.
For example:</p>
<pre><code>import pandas as pd
new = pd.DataFrame()
new2 = pd.DataFr... | <p>You need to assign <code>append</code> operation like below</p>
<pre><code>import pandas as pd
new = pd.DataFrame()
new2 = pd.DataFrame([["A", 1], ["B", 2], ["C", 3]], columns = ["H", "I"])
new = new.append(new2, ignore_index=True)
print(new)
</code></pre>
<p>Output:</p>
<pre><code> H I
0 A 1
1 B 2
2 C ... | python|pandas|dataframe | 1 |
371,048 | 56,370,283 | Pytorch nn Module generalization | <p>Let us take a look at the simple class:</p>
<pre class="lang-py prettyprint-override"><code>class Temp1(nn.Module):
def __init__(self, stateSize, actionSize, layers=[10, 5], activations=[F.tanh, F.tanh] ):
super(Temp1, self).__init__()
self.layer1 = nn.Linear(stateSize, layers[0])
self... | <p>The problem is that most of the <code>nn.Linear</code> layers in the "generalized" version are stored in a regular pythonic list (<code>self.fcLayers</code>). <a href="/questions/tagged/pytorch" class="post-tag" title="show questions tagged 'pytorch'" rel="tag">pytorch</a> does not know to look for <code>nn.... | python|machine-learning|pytorch | 1 |
371,049 | 56,114,233 | How can I solve this "UserWarning: Attempting to use a closed FileWriter " error when trying to train my object detection model | <p>I have made an object detection model which trained perfectly but now I removed some images from the training set to add newer better images and I'm getting the following errors</p>
<pre><code>C:\Users\Swayam\Anaconda3\envs\tensor\lib\site-
packages\tensorflow\python\summary\writer\writer.py:386: UserWarning:
Att... | <p>The maximum number of steps in the training which was 200000 was reached and so it could not train further.
Need to change the limit in the python file</p> | python|tensorflow|object-recognition | 1 |
371,050 | 56,030,933 | Compute Slope for Each Point in Dataframe | <p>Using Python 2.7: So I have this dataframe called <code>edge_err</code> that looks like this:</p>
<pre class="lang-py prettyprint-override"><code># Simplified DF
d = {'model_id': [1, 2, 4, 8, 16], 't_err':[.715130, .236947, .002106, .001043, .000512]}
pd.DataFrame(data=d)
# Slope is the variable I want to compute
... | <p>You can also do all in one chain using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer">assign()</a>:</p>
<pre><code>edge_err.assign(transformx = -np.log10(edge_err.model_id)
, transformy = np.log10(edge_err.t_err)) \
.... | python|pandas | 1 |
371,051 | 56,148,987 | Plot a histogram, based on percentiles | <p>I have a frame with the folowing structure:</p>
<pre><code>df = pd.DataFrame({'ID': np.random.randint(1, 13, size=1000),
'VALUE': np.random.randint(0, 300, size=1000)})
</code></pre>
<p>How could i plot the graph, where on the X-axis there will be percentiles (10%, 20%,..90%)
and on the Y-axis t... | <pre><code>q = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
for name, group in df.groupby('ID'): # Groupy by ID column
_, bins = pd.qcut(group.VALUE, q, retbins=True, grid=False) # Splits data in defined quantiles
plt.figure()
group.VALUE.hist(bins=bins) # Plots histogram of data with specified bins
ax.... | python|pandas|matplotlib|visualization|percentile | 2 |
371,052 | 56,319,850 | Problem overlaying additional percentile markers on seaborn boxplot | <p>I want to plot additional markers on a boxplot to show 95th and 5th percentiles. I want the whiskers to show 90th and 10th percentiles which I believe I can do with whis = [10,95]</p>
<p>To test this is working correctly I set both my markers and my whiskers to 5 and 95.</p>
<pre class="lang-py prettyprint-overrid... | <p>Simply sort the boxplot data using: </p>
<pre class="lang-py prettyprint-override"><code>ordered=sorted(assay['STRAT'].unique())
</code></pre>
<p>and do the same for the percentile data:</p>
<pre class="lang-py prettyprint-override"><code>ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'])
ax.scatt... | python|pandas|seaborn|boxplot | 1 |
371,053 | 56,330,269 | Why does multi layer perceprons outperform RNN in CartPole? | <p>Recently, I compared two models for a DQN on CartPole-v0 environment. One of them is a multilayer perceptron with 3 layers and the other is an RNN built up from an LSTM and 1 fully connected layer. I have an experience replay buffer of size 200000 and the training doesn't start until it is filled up.
Although MLP ha... | <blockquote>
<p>Contrary to what I expected the simpler model gave much better result that the other; even though RNN's supposed to be better in processing time series data.</p>
</blockquote>
<p>There is no time series in the cart-pole, the state contains all the information needed for optimal decision. It would be ... | pytorch|recurrent-neural-network|reinforcement-learning|openai-gym | 2 |
371,054 | 56,374,848 | How to vectorize this for loops in python? | <p>Code is as below</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
data = np.random.randint(0, 10, 12).reshape(3, 4)
print(data)
h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)
r = 2
for i in range(h):
for j in range(w):
for ir in range(i - r, i + r):
... | <p>Here is one method using <code>cumsum</code>:</p>
<pre><code>import numpy as np
data = np.random.randint(0, 10, 1200).reshape(30, 40)
print(data)
h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)
r = 20
from time import time
T = []
T.append(time())
for i in range(h):
for j in range(w):
... | python|numpy|vectorization | 2 |
371,055 | 56,085,421 | Extract integers and store them as new variable from a list of tuple | <p>In a data frame column, I have list of tuples containing int, str, float.
My objective is to extract the numeric value and store it in new column.
If there are two numeric value in the list of tuple, then two variables should be created for the two extracted values.</p>
<p>Input data -</p>
<pre><code>List_Tuple
[... | <pre><code>final = []
for tup in my_tuple:
for item in tup:
if item.isdigit():
final.append(item)
</code></pre>
<p>or as a list comprehension:</p>
<p><code>[item for item in tup for tup in my_list if item.isdigit()]</code></p>
<p>if you want to check for floats as well use <code>isinstance(it... | python|pandas|tuples | 0 |
371,056 | 56,261,631 | Make placeholder dimensions that were previously dynamic for existing models static | <p>I trained a tensorflow model for object detection with the input as a placeholder with the dimension [1,None,None,3] since my training images have various sizes. I then converted the frozen graph (.pb file) to a tensorRT graph for faster inference, but tensorRT gave me the warning that the input tensor has unknown n... | <p>I think you are using the static mode.</p>
<p>The default operating mode of TF-TRT is called static mode, and it is active whenever the parameter <code>is_dynamic_op</code> is set to False. In static mode, it is required that all shapes in the model are fully defined (dimensions cannot be None or -1). When the argu... | tensorflow|machine-learning|neural-network|conv-neural-network|tensorrt | 0 |
371,057 | 56,032,640 | Deeplab: how to separate segmentation of overlapping objects? | <p>I'm using the tensorflow deeplab to dolphins segmentation, according to the following images.</p>
<p><a href="https://user-images.githubusercontent.com/307129/57341524-20c9f580-7111-11e9-9a98-641695ab214d.jpg" rel="nofollow noreferrer">https://user-images.githubusercontent.com/307129/57341524-20c9f580-7111-11e9-9a9... | <p>Tiago Zis.. I went through your question.. As per your need, you are in need of separation between the instances of dolphin, which is somewhat beyond the scope of Deeplab. Still it can be done by training the model with a separation layer in middle and when doing so, you need to make sure that you see the ignore_lab... | tensorflow|image-segmentation|deeplab | 2 |
371,058 | 56,239,366 | Python search column of text and return if there are any matching keywords from a list of words | <p>I have a dataframe with two columns, message_id and msg_lower. I also have a list of keywords called terms. My goal is to search the msg_lower field for any words that are in the terms list. If they match, I would like to return a tuple that contains the message_id and keyword.</p>
<p>the data looks like this:</p>
... | <p>You can zip both columns for possible loop by tuples, loop by terms and test is membership in splitted values:</p>
<pre><code>terms = ['text', 'nothing']
a = [(x,i) for x, y in zip(df['message_id'],df['msg_lower']) for i in terms if i in y.split()]
print (a)
[(1116193453, 'text'), (9023746237, 'text'), (9023746237,... | python|pandas | 1 |
371,059 | 56,015,575 | Tensorflow code ends during "session.run()" with no error output on my 1050 Ti GPU | <p>I'm trying to run a GitHub repository "Face-Aging-CAAE",
<a href="https://github.com/ZZUTK/Face-Aging-CAAE" rel="nofollow noreferrer">https://github.com/ZZUTK/Face-Aging-CAAE</a>
The code works on my CPU (takes about 3 days), but on GPU it terminates during execution of session.run() with no error output.</p>
<p>He... | <p>Using VSCode, this message showed up:</p>
<pre><code>Check failed: stream->parent()->GetConvolveAlgorithms( conv_parameters.ShouldIncludeWinogradNonfusedAlgo<T>(), &algorithms) Aborted (core dumped)
</code></pre>
<p>I checked for compatibility and found out I have cudnn 7.3 while this version of tf... | python-2.7|tensorflow | 0 |
371,060 | 56,136,557 | How to search and find a syntax error and then correct the syntax by adding to the string? | <p>If the string in a row is missing the syntax or have uncorrect syntax, i would like to locate that row and edit/correct that syntax for sorting purposes.</p>
<p>What i've come up with so far:</p>
<pre><code>df.loc[~df['Syntax'].str.contains('x')] = '1x'+ df['Syntax'].astype(str)
</code></pre>
<p>provides the erro... | <p>Using <code>np.where</code> with <code>str.contains</code></p>
<pre><code>df.Syntax=np.where(df.Syntax.str.contains('x'),df.Syntax,'1x'+df.Syntax)
df
Out[48]:
Item Syntax Date
0 1 1x12 5/14/2019
1 2 4x16 5/14/2019
2 3 1x32 5/14/2019
3 4 3x10 5/14/2019
</code></pre> | pandas|replace|dataset|locate | 2 |
371,061 | 56,275,130 | Filter DataFrame columns with regex | <p>I count statistics for the dataset, and I want to filter columns that contain specific strings. How I could do it with regex?</p>
<p>Here in <code>volumes_c</code> I filtered some structures, that have Volume in there names</p>
<pre><code>Select_list = ["Amygdala", "Hippocampus", "Lateral-Ventricle", "Pallidum", "... | <p>Suppose DataFrame data is in the variable <em>df</em>, so the filter will be:</p>
<pre><code> df.filter(like="SurfArea", axis=1)
</code></pre>
<p>Actually, 'axis' arg has a default value 1 and you can omit it, but if you want to filter by rows set it up as 0.</p> | python|regex|pandas | 1 |
371,062 | 56,251,934 | update a specific dataframe field based on a condition involving a different field + iteration | <p>I have a dataframe (screenshot below) with a Month column and some categorical and numerical columns.
The categorical columns together form a key to define the row.</p>
<p>I would like to adjust some numbers such that:</p>
<ol>
<li><p>If Obj_col3 == XY and Month == 2018-12:
then pick the Num_col3 corresponding val... | <p>Idea is create <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> in columns for groups, here <code>Obj_col1</code> and <code>Obj_col2</code>, then set values by conditions and l... | python|pandas | 2 |
371,063 | 56,062,306 | Filtering a dataframe column for rows that contain certain text | <p>I have a dataframe that contains certain columns, one of which is Position and another one is Years of Service. Based on these, I want to create a new column 'Life Cover'. I have created this function for that.</p>
<pre><code>def LifeCover(row):
if row['Years of Service']>5:
val = 8
elif row['Years of Servic... | <p>The <code>str.contains</code> method is a vectorized string operation ( <a href="https://jakevdp.github.io/PythonDataScienceHandbook/03.10-working-with-strings.html" rel="nofollow noreferrer">see here</a>). This means that it is a method for for pandas Series and not string types. When you use <code>df.apply</code>,... | python|pandas|dataframe | 1 |
371,064 | 56,398,306 | Using Pandas to write file creates blank lines | <p>I am using the pandas library to write the contents of a mysql database to a csv file.</p>
<p>But when I write the CSV, every other line is blank:</p>
<p><a href="https://i.stack.imgur.com/1BPI2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1BPI2.png" alt="blank lines in csv"></a></p>
<p>Also, it's pr... | <p>Have a look at the options for to_csv: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" rel="noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html</a></p>
<p>For convenience, I have posted some items of interest here:</p>
... | python|pandas | 29 |
371,065 | 56,156,895 | Custom week calculation where week starts from thursday 7PM in pandas; | <p>I am trying to write a function for calculating ordinal work week starting from Thursday 7 PM. How should I approach this problem using pandas ?</p> | <p>Try using an Epoch based date, and then the delta between to calculate</p> | python|pandas|date | 0 |
371,066 | 56,366,435 | Tensorflow giving random answers on a regression problem | <p>I am trying to reproduce a Python exercise with Node.js using Tensorflow.js.</p>
<p>The objective is to simply convert Celsius to Fahrenheit using machine learning. </p>
<p>However, I am a noob with Tensorflow.js and it keeps giving me random answers.</p>
<p>I have tried multiple things like many different shapes... | <p>Adam optimizer works when i added another 3 dense more layers to the the model. but i got it to work on adam on python with just one layer.</p>
<pre><code>xs = []
ys = []
for (var i = -100; i < 100; i++) {
xs.push(i)
ys.push( i*1.8 + 32)
}
console.log(xs,ys)
model = tf.sequential({
layers: [
tf.laye... | javascript|node.js|tensorflow|artificial-intelligence|tensorflow.js | 3 |
371,067 | 56,325,408 | input_shape not recognised in Keras model | <p>I am trying to use Tensorflow's 2.0 new MirroredStrategy but I am receiving an error saying:
</p>
<pre class="lang-sh prettyprint-override"><code>ValueError: We currently do not support distribution strategy with a `Sequential` model that is created without `input_shape`/`input_dim` set in its first layer or a subc... | <p>I would do away with the <strong>Sequential</strong> approach and use the <strong>Model</strong> class directly:</p>
<pre class="lang-py prettyprint-override"><code>
def create_model(input_shape, conv_sizes, fc_sizes, num_outputs):
num_outputs = num_outputs
rows, cols, depth = input_shape
input_layer = ... | tensorflow|keras|tensorflow2.0 | 0 |
371,068 | 56,129,844 | I would like to extract x and y values from a txt file | <p>I have some code which stores x and y values into a txt file. The txt file stores the values on each line every time I tell the program to store the data. </p>
<p>It reads like this in the txt file:</p>
<p><code>[(1.0, 1.80), (2.0, 1.80), (3.0, 0.70), etc...]</code></p>
<p>I tried to extract the values using the ... | <p>Use <code>ast</code> module</p>
<p><strong>Ex:</strong></p>
<pre><code>import ast
with open(filename) as infile: #Read file
for line in infile: #Iterate Each line
print(ast.literal_eval(line)) #Convert to python object
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>... | python|numpy|scipy | 3 |
371,069 | 56,082,389 | How to check columns and put a specific value to another column in another dataframe accordingly in an efficient way? | <p>I have two dataframes, <code>df1</code> and <code>df2</code>.
Both have the same IDs. In <code>df2</code>, one ID is in multiple rows (none or one of the <code>columnB</code> can have value 'a' and on every row, there is another value in `columnC).</p>
<pre><code>df1 = pd.DataFrame({'ID': ['111.111', '222.222', '33... | <pre><code>df2IDs = df2[(df2['columnB'] == 'a') | (df2['columnC'].isin(validValues))][ID].tolist()
df1.loc[df1['ID'].isin(df2IDs), 'columnA'] = 'a'
</code></pre>
<p>1) First filter df2 for the where columnB is a or columnC is in your validvalues, look at the ID column and save it to a list.</p>
<p>2) Take that list,... | python|pandas|dataframe|pandas-groupby|sklearn-pandas | 0 |
371,070 | 56,185,493 | How can I get the inverse matrix of pretrained VGG16 weights? | <p>Currently I'm trying to build a Convolutional Autoencoder based on pretrained vgg16 or vgg19. I'm wondering how I get the inverse matrix of the weights..</p> | <p>I just figured it out.. :) hope it's helpful for others. Below is the code:</p>
<pre><code>weights = model.get_weights()
needed_weight = weights[index_number]
</code></pre>
<p>Weights will return a list of all weights in the neural network, then select the one you're looking for.</p>
<p>that's all.</p> | tensorflow | 0 |
371,071 | 56,113,777 | Plot two columns of data with different number of data points | <p><a href="https://i.stack.imgur.com/W8G0R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W8G0R.png" alt="enter image description here"></a>Hi, I have two columns of data. They are over the same time period but column one generates data every 1000ms, and column 2 generates data every 500ms. How can... | <p>Try this:</p>
<pre><code>x = np.linspace(0, 100,100)
x2 = np.linspace(0,200,200)
f, ax = plt.subplots(1,1)
ax2 = ax1.twiny()
ax.plot(x,y1,color='r', label='column1',linewidth=2)
ax2.plot(x,y2,color='b', label='column2',linewidth=2)
</code></pre> | pandas|matplotlib|graph | 1 |
371,072 | 56,102,886 | How to convert a week number with year into datetime format in python pandas? | <p>I have a dataframe <code>df</code>:</p>
<pre><code>df = pd.DataFrame({'id': [1,2,3,4,5],
'week': [201613, 201714, 201715, 201716, 201717]})
</code></pre>
<p>which looks like:</p>
<pre><code> id week
0 1 201613
1 2 201714
2 3 201715
3 4 201716
4 5 201717
</code></pre>
<p>The we... | <p>df['week_timestamp'] = pd.to_datetime(df['week'].astype(str) + '1', format='%Y%W%w')</p> | python|regex|pandas|datetime | -3 |
371,073 | 56,172,630 | Most efficient way to turn a list of strings of integers to an array of integers | <p>I've got a simple problem - I need to convert a string of integers to a list of integers and insert it into a numpy array.</p>
<p>I have code that works but I'm interested in a more efficient method if there is one. The starting condition is that I have a list of strings of integers (line 4) and the goal is to get ... | <p>I'm not sure this is better in speed, but it's simpler:</p>
<pre><code>In [68]: np.array([list(astr) for astr in listOfStringOfINTs],int)
Out[68]:
array([[1, 2, 3, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1],
[1, 2, 3, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1],
[1, 2, 3, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,... | python|performance|numpy | 3 |
371,074 | 56,332,197 | Rotate 3D object with Euler angles in Python | <p><a href="https://i.stack.imgur.com/fj0DP.png" rel="nofollow noreferrer">See this picture. In this the cuboid has to rotate along the other axes that were marked in the picture but it stays in the same axis x,y,z</a><a href="https://i.stack.imgur.com/EXcp9.png" rel="nofollow noreferrer">The image attached gives the c... | <p>First calculate the position vectors (the xyz coordinates) of the corners then use <code>scipy.spatial.transform.Rotation</code> on each corner.</p> | python|numpy|3d|rotation|euler-angles | 0 |
371,075 | 55,817,459 | Using the pandas module can I take part of a column instead of all of it? | <pre><code> 0 1 2 3 4 5 6
0 2018.12.0400:00 0.73572 0.73614 0.73544 0.73550 520 0
1 2018.12.0401:00 0.73550 0.73594 0.73545 0.73553 1181 0
2 2018.12.0402:00 0.73553 0.73606 0.73510 0.73539 1960 0
3 2018.12.0403:00 0.73539 0.73621 0.73481 0.7360... | <p>Try this</p>
<pre><code>df.loc[0:1, '2'].mean()
</code></pre>
<p>and</p>
<pre><code>df.loc[2:3, '2'].mean()
</code></pre> | python|pandas | 1 |
371,076 | 55,711,388 | When using df.drop in pandas make the index of rows shift | <p>I am working on a program where I take a random value find coordinates that are similar in distance to them add them to a group and remove them from the Dataframe. </p>
<p>So assuming I have the list of these coordinates </p>
<p><a href="https://i.stack.imgur.com/2BpLg.png" rel="nofollow noreferrer"><img src="http... | <p>Try to reset index</p>
<p><code>
df = df.reset_index(drop=True)</code></p> | python|pandas | 5 |
371,077 | 55,897,148 | Is there any way to convert this to train the convolutional autoencoder? | <p>I have this issue when trying to create a convolutional autoencoder.</p>
<pre class="lang-none prettyprint-override"><code>________________________________________________________________
Layer (type) Output Shape Param #
==============================================================... | <p>The input to the UpSampling1D layer has shape <code>(batch, steps, features)</code> and output has shape <code>(batch, upsampled_steps, features)</code>. Therefore, the UpSampling1D layer won't change the channel dimension. So the choice you have is to convert the filters number of <code>conv1d_150</code>. </p>
<pr... | python|tensorflow|keras | 0 |
371,078 | 55,930,157 | Creating new column containing Booleans or NaN based on values in other columns in the same pandas dataframe | <p>I want to create a new column in a pandas dataframe that evaluates to either True, False, or NaN depending on values found in two other columns in the same dataframe, which also only contain either True, False, or NaN values. Specifically, as shown below, row values in the new column should be:
(a) True if either of... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html" rel="nofollow noreferrer">.any</a></p>
<p>Set up the dataframe: </p>
<pre><code>dict = {
'col_A': [True, True, True, False, False, False, np.NaN, np.NaN, np.NaN],
'col_B': [True, False, np.NaN, False, True, ... | pandas | 1 |
371,079 | 55,822,497 | "not all arguments converted during string formatting" when to_sql | <p>I'm trying the following piece of code, which I found in a 2016 book:</p>
<pre><code>import MySQLdb
import pandas as pd
# database setup omitted for the sake of brevity
nr_customers = 100
colnames = ["movie%i" %i for i in range(1, 33)]
pd.np.random.seed(2015)
generated_customers = pd.np.random.randint(0,2,32 * nr... | <p>Nevermind. Just changed to use sqlalchemy with pymysql and saved a lot of time and LOCs:</p>
<pre><code>from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://user:password@localhost/database')
...
data.to_sql(table, con = engine)
</code></pre> | python|pandas|mysql-python | 18 |
371,080 | 55,826,937 | Tensorflow : How to use ResidualWrapper and HighwayWrapper in tensorflow? | <p>I am trying to use ResidualWrapper and HighwayWrapper in my network structure but I am getting shape mismatch error.</p>
<p>So What I have tried :</p>
<pre><code>import tensorflow as tf
from tensorflow.contrib import rnn
tf.reset_default_graph()
a = tf.placeholder(tf.float32,[2,5,10])
with tf.variable_scope(... | <p>They are actually a problem. Let me take <code>ResidualWrapper</code> as an example. Residual network connects input in front of layer directly to output layer behind layer. As shown in the following figure:</p>
<p><a href="https://i.stack.imgur.com/QRdxQ.png" rel="nofollow noreferrer"><img src="https://i.stack.img... | python|tensorflow|deep-learning | 0 |
371,081 | 55,663,782 | Time Dependant 1D Schroedinger Equation using Numpy and SciPy solve_ivp | <p>I am trying to solve the 1D time dependent Schroedinger equation using finite difference methods, here is how the equation looks and how it undergoes discretization</p>
<p><a href="https://i.stack.imgur.com/KmqJQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KmqJQ.png" alt="enter image descript... | <p>The problem is probably that <code>solve_ivp</code> expects a function for its first parameter, and you provided <code>ode_system(psi,t,delta_x,N)</code> which results in a matrix instead (therefore you get <code>type error - ndarray</code>). </p>
<p>You need to provide <code>solve_ivp</code> a function that accept... | numpy|scipy|numeric|numerical-methods|differential-equations | 1 |
371,082 | 56,008,135 | How can I recover transformation that was applied in the DataLoader? | <p>We define some some <code>DataSet</code> with some randomized <code>transform</code>s that will be reapplied each time some particular image is loaded. Is it possible to also extract the transformation that was applied to the image with the image?
(I'd like to apply the transformation that was applied to the image t... | <p>I don't think there is an API to get the applied transforms.</p>
<p>Can you just reimplement <code>__call__</code> methods of the randomized transforms so they also log what was applied? (it's just couple of lines: <a href="https://pytorch.org/docs/stable/_modules/torchvision/transforms/transforms.html#RandomHorizo... | python-3.x|pytorch|torchvision | 0 |
371,083 | 55,703,416 | Why learning rate does not change? | <p>I use Tensorflow Object Detection API tutorial <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/index.html</a> to train my custom model. Follow this instructions, I have u... | <p>In the API, the optimizer was built in this <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/builders/optimizer_builder.py" rel="nofollow noreferrer">file</a>. And <a href="https://github.com/tensorflow/models/blob/b4b8c723d377caae2f4243cf8fc711eab71736a1/research/object_detection/... | python|tensorflow|object-detection-api | 4 |
371,084 | 55,690,664 | Issue converting tensorflow into unity backend (barracuda) | <p>I'm trying to convert a UNet model that I created with Keras into a .nn for use in unity's neural networking backend. However I'm getting this error. For my model export I exported an '.h5' which I converted into a binary '.pb', and later I used the <a href="https://github.com/Unity-Technologies/ml-agents/blob/maste... | <p>I found out that this framework wasn't developed far enough yet.
What worked for me was compiling the Tensorflow Lite source for all platforms and using that backend. Converting to Tensorflow Lite is still a bit tricky, because only certain layers are supported. Lastly you need to wrap the C binaries in C# which is ... | unity3d|tensorflow|machine-learning|barracuda | 1 |
371,085 | 55,804,991 | Reshaping groupby dataframe to fixed dimensions | <p>I have dataframe df with following data. </p>
<pre><code>A B C D
1 1 3 1
1 2 9 8
1 3 3 9
2 1 2 9
2 2 1 4
2 3 9 5
2 4 6 4
3 1 4 1
3 2 0 4
4 1 2 6
5 1 2 4
5 2 8 3
grp = df.groupby('A')
</code></pre>
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for counter column with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow norefer... | python|pandas|numpy | 2 |
371,086 | 55,672,644 | expected input_1 to have 3 dimensions, but got array with shape (3, 4) | <p>This is a simplified version of my code which throws the error mentioned in the title:</p>
<pre><code>import tensorflow as tf
BATCH_SIZE = 3
SEQ_LENGTH = 4
NUM_CLASSES = 2
LSTM_UNITS = 64
NUM_SHARDS = 4
NUM_CHANNELS = 2
tf.enable_eager_execution()
def keras_model():
inputs = tf.keras.layers.Input(shape=(SEQ_... | <p>I looked into this again today and I think you could solve this by modifying the parse function like this:</p>
<pre><code>def parse_values(f1, f2, label):
features = tf.stack([f1, f2], 0)
return features, label
</code></pre> | tensorflow|reshape|tf.keras | 1 |
371,087 | 55,802,463 | perform math calculations across two columns in pandas dataframe with one query? | <p>My question is relevant to my previous question, which may be too long. </p>
<p>So, I decompose it to short components.</p>
<p>I would like to do some calculations for mutiple columns in pandas dataframe.</p>
<p>my table: </p>
<pre><code> id1 date_time adress a_size
reom 20... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>groupby.apply</code></a> with an own defined <code>lambda function</code>:</p>
<pre><code>new_df = df.groupby('id1').apply(lambda x: x['date_time'].count() / x['a_s... | python|python-3.x|pandas | 2 |
371,088 | 55,917,217 | Removing a date from a date array | <p>I created an array of <code>datetime</code> objects from <code>2014-12-1</code> to <code>2014-12-31</code>, but i need to remove the <code>2014-12-29</code> entry from it. How do i do that ?</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.drop.html" rel="nofollow noreferrer"><code>Index.drop</code></a>:</p>
<pr... | python|pandas | 3 |
371,089 | 55,986,947 | Tensorboard Exporting Incomplete Scalar SVG | <p>For reference, I am using:
Keras 2.2.4
Tensorflow GPU 1.12.0
Tensorboard 1.12.0</p>
<p>I have a bunch of scalar graphs in tensorboard I would like to export as an SVG. Unfortunately, this just doesn't seem to work. The SVG I get seems to be just the y axis and an error I can't make sense of, and that my googling do... | <p>Not sure why my perfectly legitimate question got downvoted, but after hours of research I solved my problem.</p>
<p>Tensorflow 1.2's Tensorboard is broken like this. I installed a separate venv on which I installed TF 1.3 just for tensorboard. Then I was able to export an actually complete svg file.</p>
<p>Note t... | tensorflow|keras|tensorboard | 0 |
371,090 | 55,683,793 | how to return columns values with the input of other column values of same row using pandas? | <p>I have a data frame like this:</p>
<pre><code>df
col1 col2 col3 col4
1 2 P Q
4 2 R S
5 3 P R
</code></pre>
<p>I want to create a function which returns the col1 and col2 values with the input of col3 and col4 values,</p>
<p>for examp... | <p>If need most efficient way compare numpy arrays:</p>
<pre><code>def f(a, b):
#pandas 0.24+
mask = (df['col3'].to_numpy() == a) & (df['col4'].to_numpy() == b)
#all pandas versions yet
#mask = (df['col3'].values == a) & (df['col4'].values == b)
return df.loc[mask, ['col1','col2']]
</code... | python|pandas|dataframe | 3 |
371,091 | 55,812,149 | How can I get pcolor to plot NaN values in white while using cartopy? | <p>I am plotting some integer-valued labels on an ocean map using cartopy and pcolor in python. I would like the NaN values to show up as white patches. However, at present, the NaN values are plotted using the lowest color in the colormap. How can I get pcolor to display NaN values in white?</p>
<p><a href="https://i... | <p>your code works for me, I get white values instead of a color.</p>
<p>I'm using numpy 1.15.0, mpl 2.2.2 and cartopy 0.16.0</p>
<p>on a mac.</p> | numpy|matplotlib|nan|colormap|cartopy | 1 |
371,092 | 55,838,695 | Altair Choropleth Map Encoding Dataframe Color Issue | <p>I'm trying to create a choropleth map with zipcode and temperature data to overly the counties, however I continue to have a Javascript error when trying to encode my data. I've looked at the github support and found that this was an issue with sometimes pulling in dataframes, but I also tried using a csv file as th... | <p>The map data you reference, <code>data.us_10m</code>, does not have any zipcode information, so it will not work to join this data on zipcode.</p>
<p>If you would like to make the chart you have in mind, you'll need to find a source of geographic data indexed by zipcode rather than by county.</p> | python|pandas|altair | 0 |
371,093 | 55,888,292 | How to map this in Pandas? | <p>I need help transforming a 3 columns df into an array 3x3. See picture attached (Pandas mapping). Thanks in advance.</p>
<p><a href="https://i.stack.imgur.com/Ch74M.png" rel="nofollow noreferrer">Pandas mapping</a></p> | <p>Not sure if Vlad's comment means I shouldn't be answering this but:</p>
<pre><code>df = pd.DataFrame({'a':['C1', 'C1', 'C1', 'C2', 'C2', 'C2', 'C3', 'C3', 'C3'],
'b':[0.00, 0.20, 0.10, 0.30, 0.00, 0.10, 0.00, 0.00, 0.00],
'c':['C1', 'C2', 'C3', 'C1', 'C2', 'C3', 'C1', 'C2', 'C3... | python|pandas | 0 |
371,094 | 55,756,555 | How to combine 2 dataframe histograms in 1 plot? | <p>I would like to use a code that shows all histograms in a dataframe. That will be <code>df.hist(bins=10)</code>. However, I would like to add another histograms which shows CDF <code>df_hist=df.hist(cumulative=True,bins=100,density=1,histtype="step")</code></p>
<p>I tried separating their matplotlib axes by using <... | <p>It is possible to draw them together:</p>
<pre><code># toy data frame
df = pd.DataFrame(np.random.normal(0,1,(100,20)))
# draw hist
fig, axes = plt.subplots(5,4, figsize=(16,10))
df.plot(kind='hist', subplots=True, ax=axes, alpha=0.5)
# clone axes so they have different scales
ax_new = [ax.twinx() for ax in axes.... | python|pandas|matplotlib | 3 |
371,095 | 56,001,487 | Pandas Create DataFrame with two lists behaving differently | <p>I am trying to create a pandas data frame using two lists and the output is erroneous for a given length of the lists.(this is not due to varying lengths)</p>
<p>Here I have two cases, one that works as expected and one that doesn't(commented out):</p>
<pre><code>import string
d = dict.fromkeys(string.ascii_lowerc... | <p>If I understand this correctly, you want to make dataframe which will have all pairs of groups and numbers. That operation is called cartesian product.
If the difference in lengths betweens those two arrays is exactly 1, it works with your approach, but this is more by pure accident. For general case, you want to d... | python|pandas | 1 |
371,096 | 55,882,255 | regex text parser | <p>I have the dataframe like </p>
<pre><code>ID Series
1102 [('taxi instructions', 13, 30, 'NP'), ('consistent basis', 31, 47, 'NP'), ('the atc taxi clearance', 89, 111, 'NP')]
1500 [('forgot data pages info', 0, 22, 'NP')]
649 [('hud', 0, 3, 'NP'), ('correctly fotr approach', 12, 35, 'NP')]
</code></pre>
<p>I... | <p>The format of your final result is not easy to understand, but maybe you can follow the concept to create your new columns:</p>
<pre><code>def process(ls):
return ' '.join([x[0] for x in ls])
df['Series_new'] = df['Series'].apply(lambda x: process(x))
</code></pre>
<p>And if you want to create N new columns (... | pandas | 0 |
371,097 | 55,630,790 | Aggregate columns values by string column numerated name in pandas | <p>I have a table </p>
<p><a href="https://i.stack.imgur.com/s5P6R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s5P6R.png" alt="enter image description here"></a></p>
<p>I want to sum values of the columns beloning to the same class h.*. So, my final table will look like this:</p>
<p><a href="h... | <p>The solution above works great, but is vulnerable in case the h.X goes beyond single digits. I'd recommend the following:</p>
<p><strong>Sample Data:</strong></p>
<pre><code>cols = ['h.%d.%d' %(i, j) for i in range(1, 11) for j in range(1, 11)]
df = pd.DataFrame(np.random.randint(10, size=(4, len(cols))), columns=... | python|pandas | 1 |
371,098 | 55,917,259 | Python function transfering the pandas Dataframe attributes doesn't work | <p>It'a simple example.</p>
<pre><code>d=pd.DataFrame({'a':[1,2,3,4],
'b':[6,6,7,8]})
</code></pre>
<p>I write a function f(x).I want to print d.x. The function is:</p>
<pre><code>def f(x):
print(d.x)
</code></pre>
<p>Run <code>f(a)</code>. I expect it to print <code>d.a</code></p>
<p>But it retu... | <p>You can't approach it that way, you would need a function that get's column by <code>[</code> <code>]</code>, and enter a string as well:</p>
<pre><code>def f(x):
print(d[x])
</code></pre>
<p>And to call it:</p>
<pre><code>f('a')
</code></pre> | python|pandas|function | 4 |
371,099 | 55,803,236 | do calculations for multiple columns with some conditions in pandas dataframe | <p>My question is relevant to my previous question. But it is different. So, I created a new post even though the data is same. </p>
<p>I would like to do some calculations for multiple columns with some conditions in pandas dataframe.</p>
<p>my table: </p>
<pre><code> id1 date_time adress ... | <p>Just use <code>df.groupby('address')['flag'].mean()</code>.</p> | python|sql|python-3.x|pandas|dataframe | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.