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,200 | 56,201,572 | How to make bar graph of 2 variables based on same DataFrame and I want to choose 2 or until 5 data | <p>I have a DataFrame:</p>
<pre><code>wilayah branch Income Januari 2018 Income Januari 2019 Income Febuari 2018 Income Febuari 2019 Income Jan-Feb 2018 Income Jan-Feb 2019
1 sunarto 1000 1500 2000 3000 3333 ... | <p>Consider a <code>groupby</code> aggregation then run <code>DataFrame.plot</code>. Below will line all branches on x-axis with different income columns as color_coded keys in legend.</p>
<pre><code>agg_df = df.groupby('branch').sum()
fig, ax = plt.subplots(figsize=(15,5))
agg_df.plot(kind='bar', edgecolor='w', ax... | python|pandas|matplotlib | 0 |
14,201 | 55,674,289 | How to combine multiple columns in CSV file using pandas? | <p>I have a csv file for lyrics songs that I took from Genius. Right now, I m preparing my data. I have two column "songs" and "artist". In the "songs" columns I have a lot information: title, album, year, lyrics and URL. I need to separate the column "songs" in 5 columns.</p>
<p><img src="https://i.stack.imgur.com/9d... | <p>Try this.</p>
<pre class="lang-py prettyprint-override"><code>import ast
import pandas as pd
raw = pd.read_csv("output.csv")
raw["songs"] = raw["songs"].apply(lambda x: ast.literal_eval(x))
songs = raw["songs"].apply(pd.Series)
result = pd.concat([raw[["artist"]], songs], axis=1)
result.head()
</code></pre> | python-3.x|pandas | 0 |
14,202 | 55,584,823 | keras activation function layer: model.add Activation('relu') gives invalid syntax error | <p>Trying to build layer by following code and an error come out</p>
<pre><code>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
X = pickle.load(open("X.pickle","rb"))
y = pickle.load(open("y.pickle","r... | <p>This error usually means that the line <strong><em>above</em></strong> the reported line didn't end correctly. Notice that you have an extra parenthesis on line 15. ;)</p>
<pre><code>model.add((Conv2D(64, (3,3))) # <--- 4 open, 3 closed
model.add(Activation("relu"))
</code></pre> | python|tensorflow|keras|deep-learning | 0 |
14,203 | 55,962,513 | Update values in a column while looping over through a pandas dataframe | <p>I am working on a script to extract some details from images. I am trying to loop over a dataframe that has my image names. How can I add a new column to the dataframe, that populates the extracted name appropriately against the image name?</p>
<pre class="lang-py prettyprint-override"><code>for image in df['images... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> to apply a function on each row:</p>
<pre><code>def get_name(image):
# Code for getting the name
return name
df['names'] = df['images'].apply(get_name)
</cod... | python|pandas|dataframe | 1 |
14,204 | 64,691,217 | How to merge two dataframes in Pandas using the most recent time | <p>position =</p>
<pre><code> id time x y z
T1 1000 100 100 120
T1 2000 50 50 120
T2 1200 100 200 120
</code></pre>
<p>event =</p>
<pre><code> id time event
T1 1500 stopped
T2 1200 travelling
</code></pre>
<p>desired result =</p>
<pre><code> id time ev... | <p>You can try using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer">.merge_asof()</a> for this problem. <br>
For this both your df's need to be sorted by time.<br></p>
<p>Code example:</p>
<pre><code>import pandas as pd
from io import StringIO
posi... | python|python-3.x|pandas|dataframe | 1 |
14,205 | 64,861,095 | Remove groupby and optimize the pandas code | <p>I am trying to replace for loop to gain more performance in pandas. Using for loop in pandas is performance killer, read it in many blogs. Right now, I have to apply a some logic to set of items and group by <code>emp_id</code>. the chunk of code is below. Right now, below code works, however the complaints are rela... | <p>The <code>item</code> in the grouped object is just a <code>DataFrame</code>, so you can vectorize your logic if possible and combine with the <code>agg</code> function to speed things up - for example</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [100, 100, 200, 200, 300, 400], 'B': ... | python|pandas | 1 |
14,206 | 40,093,627 | Align image columns by max value | <p>I have an image where I would like to offset each column so that the maximum value of each column is vertically centered in the image. Here's some toy data:</p>
<pre><code>unaligned = np.array([[0,0,1,2,3,2,1,0,0,0],
[0,0,0,1,2,3,2,1,0,0],
[0,1,2,3,4,3,2,1,0,0],
... | <p>Here's an approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>
<pre><code>m,n = unaligned.shape
col_shifts = m//2 - unaligned.argmax(0)
row_idx = np.mod(np.arange(m)[:,None]-col_shifts,m)
aligned_out = unaligned[row_idx,np.arange(n... | python|numpy|image-processing | 1 |
14,207 | 39,802,232 | How does numpy handle data files with uncertainty values, e.g., 0.6499(6)? | <p>Here is a snippet of a large data set I am working with:</p>
<pre><code># p* T* P* U* P*_cs U*_cs Steps dt*
0.1 6.0 0.6499(6) -0.478(2) 0.6525 -0.452 30000 0.002
0.2 6.0 1.442(1) -0.942(2) 1.452 -0.890 30000 0.002
0.3 6.0 2.465(3) -1.376(1) 2.489 -1.298 ... | <pre><code>In [1]: txt=b"""# p* T* P* U* P*_cs U*_cs Steps dt*
...: 0.1 6.0 0.6499(6) -0.478(2) 0.6525 -0.452 30000 0.002
...: 0.2 6.0 1.442(1) -0.942(2) 1.452 -0.890 30000 0.002
...: 0.3 6.0 2.465(3) -1.376(1) 2.489 -1.298 30000 0.002"""
In [2]: ... | python|numpy|uncertainty | 2 |
14,208 | 44,158,593 | How can I change specific elements in all samples of a .csv file? | <p>As input, I have a .csv file like:</p>
<pre><code>user, withdraw, date
50D8BF0DA22D6C914777D8F59DAAB4D8, -125, 01-02-2015
674BCF0CD236621E5680073334A73C32, -5, 01-02-2015
E17E1691D35FB2FB675E3B787B8BEDF1, -845, 01-02-2015
50D8BF0DA22D6C914777D8F59DAAB4D8, -250, 01-02-2015
674BCF0CD236621E5680073334A73C32, -98, 01-0... | <p>first read CSV into Pandas DF:</p>
<pre><code>df = pd.read_csv('/path/to/file.csv', skipinitialspace=True)
</code></pre>
<p>yields:</p>
<pre><code>In [84]: df
Out[84]:
user withdraw date
0 50D8BF0DA22D6C914777D8F59DAAB4D8 -125 01-02-2015
1 674BCF0CD236621E5680073334A... | python|csv|pandas | 5 |
14,209 | 69,474,381 | spacy remove only org and person names | <p>I have written the below function which removes all named entities from text. How could I modify it to remove only org and person names? I don't want to remove <code>6</code> from <code>$6</code> from below. Thanks</p>
<pre><code>import spacy
sp = spacy.load('en_core_web_sm')
def NER_removal(text):
document = sp... | <p>I think <code>item.ent_type_</code> will be useful here.</p>
<pre><code>import spacy
sp = spacy.load('en_core_web_sm')
def NER_removal(text):
document = sp(text)
text_no_namedentities = []
# define ent types not to remove
ent_types_to_stay = ["MONEY"]
ents = [e.text for e in document.en... | python|pandas|nlp|spacy | 1 |
14,210 | 69,379,412 | Three columns A B C, take A*B while cumsum is less than 10 then take A*C | <p>Assume I have the following dataframe</p>
<pre><code>A B C
5 1 0.7
7 1 0.7
-1 1 0.7
-3 1 0.7
12 1 0.7
</code></pre>
<p>I'd like to multiply A and B or A and C based on a the cumulative sum of previous multiplications.</p>
<p>First iteration, the cum sum is 0 so we shall multiply A and B t... | <p>A <code>for</code> loop would work</p>
<pre><code>cs = [0]
for _, row in df.iterrows():
if cs[-1] > 10:
curr = cs[-1] + row.A * row.C
else:
curr = cs[-1] + row.A * row.B
cs += [curr]
pandas.Series(cs[1:])
# 0 5.0
# 1 12.0
# 2 11.3
# 3 9.2
# 4 21.2
# dtype: float64
</... | python|pandas | 2 |
14,211 | 53,985,081 | Conditional writing to xlsx | <p>Folks,</p>
<p>I'm currently working with a huge excel sheet, python 3.7.1 and pandas 0.23.4.
My task is to write to cells based on conditional matching. Something like this:</p>
<pre><code>val = lincoln@gmx.net
if val in Cell_3A:
write something to Cell_3B
</code></pre>
<p>To make a complete example, let's sa... | <p>filter the <code>Protection</code> column where the email is not <code>'trump@gmail.net'</code> and assign them 'on' and vice versa.</p>
<pre><code>df.loc[df['Email']!='trump@gmail.net', 'Protection']='on'
df.loc[df['Email']=='trump@gmail.net', 'Protection']='off'
</code></pre>
<p>using <code>np.where</code>:</p>
... | python|pandas | 6 |
14,212 | 54,125,639 | Pandas issue in python 2.7.0 | <p>I have a running code on <code>Python 2.7.0</code> with <code>pandas==0.23.4</code>. Now when I am trying to deploy this on a new server, my df looks like below but my filter is not working? What is the issue here? This is a conda distribution. Can I reinstall python or is there a change in pandas implementation. </... | <p>Are you sure the column KPIID is an integer and not a string?</p>
<p>Try using dtypes to check the type of variable stored in this column </p>
<pre><code>data_df.dtypes
</code></pre>
<p>If it is a string you should change it to</p>
<pre><code>data_df[data_df.KPIID == '21']
</code></pre> | python|pandas|python-2.7 | 1 |
14,213 | 38,405,707 | Error when theres zero ocurrence of word | <p>First of all, sorry for my broken english.</p>
<p>I’m using this code to count the number of times the words “LeBron” or “Curry” appear on tweets. The problem is that if none of the tweets contains the word “LeBron” or “Curry” the program crash. Is the words are there, the program run perfectly.</p>
<pre><code>twe... | <p>Use exception handling by surrounding the code on line 44 with try/catch:</p>
<pre><code>try:
LeBron = tweets['LeBron'].value_counts()[True]
except IndexError:
LeBron = 0
</code></pre> | python|pandas|twitter|tweepy | 2 |
14,214 | 38,122,639 | Loading of text data file | <p>I have a text file in below format </p>
<pre><code>id x, y
0[0.0, 1.0]
1[0.0, 2.0]
2[0.1, 2.5]
:
:
</code></pre>
<p>I need to load this text file. I have tried:</p>
<pre><code>numpy.genfromtxt('FileName', delimiter=",", names=True)
</code></pre>
<p>but the existence of <code>[</code> prevents it from reading the... | <p>You need to convert the file to the format that NumPy expects, before feeding it to <code>genfromtxt()</code>. Fortunately, you can do that in Python itself.</p>
<pre><code>f1 = open("file.txt", "rU")
f2 = open("output.txt", "wt")
for line in f1:
line = line.replace("[", ",")
line = line.replace("]", "")
... | python|numpy|text-files | 3 |
14,215 | 66,201,553 | How to create a Boolean Mask which preserves a column? | <p>for example:
say I have</p>
<pre><code>x = np.array[['positive','a'],['negative','b'],['positive','c'], ['negative','d']]
</code></pre>
<p>and I want a new array with the value</p>
<pre><code>v = [['positive','a'], ['positive','c']]
</code></pre>
<p>How could this be done? Thank you your time!</p> | <p>Correcting the syntax:</p>
<pre><code>In [359]: x = np.array([['positive','a'],['negative','b'],['positive','c'], ['ne
...: gative','d']])
In [360]: x
Out[360]:
array([['positive', 'a'],
['negative', 'b'],
['positive', 'c'],
['negative', 'd']], dtype='<U8')
</code></pre>
<p>Just select ... | python|arrays|numpy|boolean|mask | 0 |
14,216 | 52,538,777 | Pandas covariance returning zero | <p>I'm having trouble using the cov function for a pandas dataframe. Can someone explain why the first version is erroneously returning zeros?</p>
<pre><code>In[2]: temp.cov()
Out[2]:
dogs cats
dogs 0.0 0.0
cats 0.0 0.0
In[3]: temp.iloc[1:,:].cov()
Out[3]:
dogs cats
dogs 271... | <p>This appears to be a known issue with numpy and a recent version MKL. Running <code>update conda --all</code> seems to fix my issue. </p>
<p>It's well documented here... <a href="https://github.com/numpy/numpy/issues/9758" rel="nofollow noreferrer">https://github.com/numpy/numpy/issues/9758</a></p> | pandas|formatting|covariance | 0 |
14,217 | 46,562,991 | Unable to load csv file into Dataframe using Surprise in Python | <h2>The Scenario</h2>
<p>The Dataset is to be imported which consists has considerable <code>NaN</code> values in it. For same I'm using SurPRISE package (written by Nicholas Hug) in Python rather than using Pandas. Reason being the Method of predicting NaN values is good with mentioned package.</p>
<h2>The Problem</... | <p>It seems like this error arise because of header of each column in post_df1.csv, which is in string format. When you remove first row with column names from csv file, your snippet of code should be working.</p> | python|python-2.7|pandas|csv|dataframe | 2 |
14,218 | 69,040,301 | How to loop through a vector in TCL? | <p>I am new to tcl, and I couldn't figure out how to translate this code from python to TCL</p>
<pre><code>import numpy as np
g0 = 7.88e12
Eox = np.array([155473, 15573, 1553, 1557473, 5473, 473, 1573, 19553])
E1 = 0.55e6
m = 0.7
fot= 1
D = float(input("rad dose"))
Fy = np.array([(abs(Eox)/(abs(Eox)+E1))**... | <p>Tcl doesn't process lists of values like <em>numpy</em> does (it's closer to standard Python) without an extension. I remember there being such a thing, but I've not used it and I can't remember the name right now. So I'll use standard Tcl. The closest analogy for a numpy array in standard Tcl is a list of values (t... | python|numpy|tcl | 2 |
14,219 | 69,059,907 | How to increase/change a value in a dataset with a condition in python | <p>What I want to do is: create a for loop that iterates through the data, if the probability ends in an even number I want to add 0.1 to it, if the color is red I want to increase the cost of that item by 10%.</p>
<p>Something is wrong with my syntax. I can't figure how to correctly do what I want. I keep getting this... | <p>You can create a boolean auxiallry column and multiply the values with 0.1 and add them, because if the boolean is False it will basically mean <code>value + 0 * 0.1</code></p>
<pre><code>df['Probability'] = df['Probability'] + ((df['Probability'] %2 == 0) * 0.1)
</code></pre>
<hr />
<p>Or you directly use numpy whe... | python|pandas|for-loop | 0 |
14,220 | 69,199,999 | Comparing two df's of different lengths, receiving "Can only compare identically-labeled Series objects" error | <p>Hi I am trying to compare two df's. If the same ID appears in df2 I want to add it to df1 to a "count" column.</p>
<p>After this, I want to then add all rows from df2 with unique ID's to df1.</p>
<p>The first time I run the code it works (df1 count is increased and the new ID's are added as new rows), the ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>.isin()</code></a> which does not require same number of rows and index for <code>df1</code> and <code>df2</code>, as follows:</p>
<p>replace your code <code>df1.loc[(df3["ID&... | python|pandas|dataframe | 1 |
14,221 | 44,743,109 | plotting average by each genres; pandas | <pre><code>import numpy as np
df = df.dropna(subset=['genres']).reset_index(drop=True)
splitted = df['genres'].str.split('|')
l = splitted.str.len()
x = df['gross'] / df['budget']
df = pd.DataFrame({x: np.repeat(df[x], l), 'genres':np.concatenate(splitted)})
d = {'mean':'Average Income'}
df1 = df.groupby('gen... | <p>I think if need aggregate only one function more common is used <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.mean.html" rel=... | pandas|matplotlib | 1 |
14,222 | 44,794,881 | KeyError: ('count', 'occurred at index 0') | <p>I am trying to do the example in <a href="http://www.austintaylor.io/d3/python/pandas/2016/02/01/create-d3-chart-python-force-directed/" rel="noreferrer">Use Python & Pandas to Create a D3 Force Directed Network Diagram</a></p>
<p>But in the below line I am getting an error 'KeyError: ('count', 'occurred at ind... | <p>I think there is problem with column name <code>count</code> - missing or some witespace like <code>' count'</code>.</p>
<pre><code>#check columns names
print (grouped_src_dst.columns.tolist())
['count', 'source', 'target']
</code></pre>
<p>Sample:</p>
<pre><code>grouped_src_dst = pd.DataFrame({'source':['a','s',... | python-3.x|pandas|d3.js | 8 |
14,223 | 44,558,853 | Put WHERE clause on Pandas Merge | <p>I have two pandas data frames that I am trying to merge together on three different keys ... kind of. Each data frame has a gender column, and a country_destination column which I want to do the outer join on. One data frame has an age_bucket column which is a string representing the age range e.g. 45-49, 50-54, 55-... | <p>I think you need expand rows by values in <code>age_list</code> column and then <code>merge</code>:</p>
<pre><code>#get lengths of each list
l = age_gender['age_list'].str.len()
#get all columns without age_list
cols = age_gender.columns.difference(['age_list'])
#repeat values by lengths to new DataFrame
df = pd.Da... | python|pandas|merge|where | 4 |
14,224 | 60,937,962 | Unable to append a list with numpy values | <p>I want to calculate the average vector length from a file that contains coordinates. Ultimately I want to store <code>vector_length</code> as a list called <code>pair_length</code>. I will calculate the average of the <code>pair_length</code> list later on in my program using <code>average()</code> function. Here is... | <p>Here <code>vector_length</code> stores a <code>float</code> value, and hence append operation won't work with it.
Append operation works with lists, in python.</p>
<p>So, what we can do is:</p>
<p>Instead of </p>
<pre class="lang-py prettyprint-override"><code>vector_length.append(pair_length)
</code></pre>
<p>W... | python|list|numpy | 1 |
14,225 | 60,879,228 | pandas merge header rows if one is not NaN | <p>I'm importing into a dataframe an excel sheet which has its headers split into two rows:</p>
<pre><code>Colour | NaN | Shape | Mass | NaN
NaN | width | NaN | NaN | Torque
green | 33 | round | 2 | 6
etc
</code></pre>
<p>I want to collapse the first two rows into one header:</p>
<pre><code>Colour | ... | <p>Let's use list comprehension to flatten multiindex column header:</p>
<pre><code>df.columns = [f'{j}' if str(i)=='nan' else f'{i}' for i, j in df.columns]
</code></pre>
<p>Output:</p>
<pre><code>['Colour', 'width', 'Shape', 'Mass', 'Torque']
</code></pre> | python|pandas|dataframe|pandas-groupby | 1 |
14,226 | 60,923,511 | Convert Pandas Column with hour range 01:00 to 24:00 | <p>I have hourly data for an entire year stored in a Pandas column that's an object dtype. The data was imported from a .CSV file with the following structure:</p>
<pre><code>Date/Time,kWh
01/01 01:00:00,1.14168620105289
01/01 02:00:00,0.998495769210657
01/01 03:00:00,0.949679309420898
01/01 04:00:00,0.9380801... | <p>Short Answer: I did some string manipulation to decrease all of the hours by one hour</p>
<pre><code>df['temp_col'] = df['Date/Time,kWh'].str.split(':').str[0]
df['temp_col'] = (pd.to_numeric(df['temp_col']) - 1).astype(str)
df['temp_col'] = df['temp_col'].apply(lambda x: f'0{x}' if len(x)==1 else x)
df['temp_col']... | python|pandas|datetime | 0 |
14,227 | 60,959,871 | How to convert 3-D Numpy array to Pandas Dataframe? | <p><strong>The problem</strong>:
I have a 3-D Numpy Array:</p>
<p><code>X</code></p>
<p><code>X.shape: (1797, 2, 500)
</code></p>
<pre><code>z=X[..., -1]
print(len(z))
print(z.shape)
count = 0
for bot in z:
print(bot)
count+=1
if count == 3: break
</code></pre>
<p>Above code yields following output:</p... | <p>Here's a solution with sample data:</p>
<pre><code>a,b,c = X.shape
# in your case
# a,b,c = 1797, 500
pd.DataFrame(X.transpose(1,2,0).reshape(2,-1).T,
index=np.repeat(np.arange(c),a),
columns=['X_coord','Y_coord']
)
</code></pre>
<p>Output:</p>
<pre><code> X_coord Y_coor... | python|pandas|numpy|numpy-ndarray | 1 |
14,228 | 71,610,702 | Numpy: reshape list of tuples | <p>I have the following list of tuples:</p>
<pre><code>>>> import itertools
>>> import numpy as np
>>> grid = list(itertools.product((1,2,3),repeat=2))
>>> grid
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
</code></pre>
<p>I'd like to reshape this list in ... | <p><code>18</code> comes from the fact that you have a list of <code>9</code> tuples, each containing <code>2</code> items; thus, <code>9 * 2 = 18</code>. numpy automatically converts the tuples to part of the array.</p>
<p>You can either use <a href="https://stackoverflow.com/a/71610738/17242583">LeonardoVaz's answer<... | python|numpy|reshape|numpy-ndarray | 1 |
14,229 | 71,728,983 | How to export .csv file from python and using pandas DataFrame | <p>I am trying to export some filtered data from Python using Pandas DF to <code>.csv</code> file (Personal Learning project)</p>
<p>Code : <code>df5.to_csv(r'/C:/Users/j/Downloads/data1/export.csv')</code></p>
<pre class="lang-py prettyprint-override"><code>Error:
Traceback (most recent call last):
File "C:\Us... | <p>Try</p>
<p><code>df.to_csv(r'C:\path\to\directory\filename.csv')</code></p> | python|pandas|dataframe|csv|export-to-csv | 0 |
14,230 | 69,708,558 | mutate a column with column names if it contains 1 | <p>I want to Mutate a column h, which contains respective column names [A,B,C,D] if it contains 1</p>
<pre><code>import pandas as pd
dfz = pd.DataFrame({'A' : [1,0,0,1,0,0],
'B' : [1,0,0,1,0,1],
'C' : [1,0,0,1,3,1],
'D' : [1,0,0,1,0,0]})
dfz['h'] = dfz.loc[:,... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dot.html" rel="nofollow noreferrer"><code>DataFrame.dot</code></a> with filtered columns and compared values by <code>1</code>, last use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.htm... | python|pandas | 2 |
14,231 | 69,741,519 | Concat/Transpose/Groupby pandas column | <p>So I have the following <code>DataFrame</code> within pandas:</p>
<pre><code>Column 1 | Column 2
Name | A
Number | B
Age | C
Name | D
Number | E
Age | F
</code></pre>
<p>Each Name, Number and Age grouped togther all relate to one feature and are repeated throughout the date... | <p>This is a pivot, but you first need to create a label to group the sets of 3 rows together. If the data are clean enough such that the DataFrame is always ordered Name, Number, Age, Name, Number, Age, ..., you can <code>cumsum</code> a Boolean Series checking which rows are 'Name' to group them together.</p>
<pre><c... | python|pandas|concatenation | 2 |
14,232 | 69,822,474 | Multi-task learning with ANN? | <p>I am trying to implement a simple multi-task learning with the following network:</p>
<pre><code>y_train_target1 = Y_train.iloc[:, 0]
y_test_target1 = Y_test.iloc[:, 0]
y_train_target2 = Y_train.iloc[:, 1]
y_test_target2 = Y_test.iloc[:, 1]
input_dim_train=X_train.shape[1]
#shape of X_train is: (30000,126)
inputs =... | <p>If the objective is to share the layers between the two outputs then you can write your code as shown below, see also <a href="https://stackoverflow.com/a/59571814/11989081">this answer</a>.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import tensorflow as tf
from tensorflow.keras.layers im... | python|tensorflow|keras|deep-learning|neural-network | 1 |
14,233 | 69,719,331 | How to Convert Pandas Week to User Supported Business Logic? | <p>The goal is to convert a pandas timestamp object to week of the year according to the following user defined calendars for 2021 and 2022 respectively.</p>
<p><a href="https://i.stack.imgur.com/sTKe0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sTKe0.png" alt="enter image description here" /></a... | <p>One solution is to create a custom calendar for the input year. The dates in the year will be converted to a Period representing weeks that start on Saturday and end on Friday.</p>
<pre><code>import pandas as pd
def week(in_date: pd.Timestamp) -> int:
"""Convert the date to a week according t... | python|pandas|datetime|week-number | 1 |
14,234 | 43,383,120 | How to load tensorflow checkponit by myself without c++ api? | <p>I am using tensorflow 1.0. </p>
<p>My production environment cannot build tensorflow-cpp because low gcc&glibc version.</p>
<p>Is there any doc about how to load a checkponit or freezed-graph in C++ <strong>without api</strong>? </p>
<p>1、 how to save network parameter? (embeding...)</p>
<p>2、 how to save gr... | <p>There is no documentation on doing this that I know of. Loading a checkpoint without the C++ runtime won't be very useful to you because you won't be able to run it.</p>
<p>The checkpoint by default does not include the graph structure, but if you export a metagraph you will get it in a serialized protocol buffer f... | tensorflow|tensorflow-serving | 0 |
14,235 | 72,385,172 | How to group pandas dataframe by column headers and run summary statitics? [python] | <p>I am trying to make a summary statistic table from a dataframe and am having a really tough time trying to wrap my head around how to get the columns grouped correctly.</p>
<p>I have the following dataframe:</p>
<pre><code> Year Value_1 Value 2
------------------------------------
0 2012 ... | <p>IIUC you want it to look like this:</p>
<p><strong>EDIT</strong>:
Have another (shorter) attempt:</p>
<p>(1)</p>
<pre><code>df = pd.DataFrame(
{'Year': [2012, 2012, 2012, 2012, 2013, 2013, 2015, 2015, 2015, 2016, 2016],
'Value_1': [43, 45, 35, 32, 35, 65, 34, 74, 63, 54, 25],
'Value_2': [34, 24, 44, 44... | pandas | 2 |
14,236 | 72,265,098 | Pandas Group by and create new column with 25th and 75th percentiles | <p>I have the following pandas DataFrame:</p>
<pre><code>df = pd.DataFrame({
'id': [1, 1, 1, 2],
'r': [1000, 1300, 1400, 1100],
's': [650, 720, 565, 600]
})
</code></pre>
<p>I'd like to aggregate the DataFrame and create a new column which is a r... | <p>Here is one option, using <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html" rel="nofollow noreferrer"><code>Groupby.agg</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.quantile.html" rel="nofollow noreferrer"><code>quantile</... | python|pandas | 2 |
14,237 | 72,436,409 | Error -> The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() | <p>Could you please help me sort out the below if condition:
(could be also possible with apply and lambda but don't know how to put so many conditions in single line)</p>
<pre><code>test = pd.DataFrame({'index' : ['DS','VS','VB','FS','HB'],
'bid' : [np.nan,102,103,104,np.NaN],
'mid' : [106,107,108,109,110],
... | <p>When your condition is quite complicated, it might be easier to write the condition in afunction and apply it to every rows by using <code>df.apply(func, axis=1)</code></p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
test = pd.DataFrame({'index' : ['DS','VS','VB','FS','HB']... | python|pandas|dataframe | 3 |
14,238 | 72,325,794 | reordering terms by a "standard" order | <p>I want to be able to read in my files and reorder the lines according to my "standard" order below:</p>
<pre><code>array([(1., 1., 1., 1., 0., 1., 0.244 ),
(1., 1., 1., 1., 1., 0., -4.29215),
(2., 1., 1., 1., 1., 0., 1.2047 ),
(2., 1., 2., 1., 1., 0., -6.5627 ),
(2., 1., 2., ... | <p>Clarify a couple of things.</p>
<p>How are you reading these files? The exact statement would help. In particular are spelling out the <code>dtype</code>, or using the <code>dtype=None</code> option, and getting the field names from the file. A sample of csv might help.</p>
<p>Once you have an array, you can 'vie... | python|numpy|sorting | 0 |
14,239 | 50,323,744 | How to used a tensor in different graphs? | <p>I build two graphs in my code, graph1 and graph2. </p>
<p>There is a tensor, named <code>embedding</code>, in graph1. I tied to use it in graph2 by using get_variable, while the error is <code>tensor must be from the same graph as Tensor</code>. I found that this error occurs because they are in different graphs.</... | <p>expanding on @jdehesa's comment,</p>
<p>embedding could be trained initially, saved from graph1 and restored to graph2 using tensorflows saver/restore tools. for this to work you should assign embedding to a name/variable scope in graph1 and reuse the scope in graph2</p> | python|tensorflow|graph | 0 |
14,240 | 50,561,123 | Python Pandas Dataframe replace cell value by value of another cell of the same session | <p>I'm using Python Pandas Dataframe for Data Analyse of some logs.
I have a csv with something like:
number_items event_type ... ... ... session_id ... ... ... </p>
<p>My problem is that in my session there are different types of events, and only one of them has something for number_items. Or, numbers_items is what i... | <p>The rows you get back from iterrows are copies so they dont overwrite your original dataframe. Use another form of iterator that references the original dataframe.</p>
<p>see here <a href="https://stackoverflow.com/questions/25478528/updating-value-in-iterrow-for-pandas">Updating value in iterrow for pandas</a></p>... | python-3.x|pandas|dataframe|bigdata|data-analysis | 0 |
14,241 | 50,658,763 | Counting values for each unique entity in a pandas dataframe object | <p>I have a csv file with 3 columns. users, text and labels. each user has multiple texts and labels.
i want to know the label with the highest frequency of occurrence in order to determine the category of each user.</p>
<p>I have tried:</p>
<pre><code>for i in df['user'].unique():
print (df['class'].value_count... | <p>For counting values by group, you can use <code>groupby</code> with <code>pd.value_counts</code>:</p>
<pre><code>df = pd.DataFrame([[1, 1], [1, 2], [1, 3], [1, 1], [1, 1], [1, 2],
[2, 1], [2, 3], [2, 2], [2, 2], [2, 3], [2, 3]],
columns=['user', 'class'])
res = df.groupby('user... | python|pandas|counting | 1 |
14,242 | 50,626,058 | psycopg2: can't adapt type 'numpy.int64' | <p>I have a dataframe with the dtypes shown below and I want to insert the dataframe into a postgres DB but it fails due to error <strong><em>can't adapt type 'numpy.int64'</em></strong></p>
<pre><code>id_code int64
sector object
created_date float64
updated_date float64
</code></... | <p>Add below somewhere in your code:</p>
<pre><code>import numpy
from psycopg2.extensions import register_adapter, AsIs
def addapt_numpy_float64(numpy_float64):
return AsIs(numpy_float64)
def addapt_numpy_int64(numpy_int64):
return AsIs(numpy_int64)
register_adapter(numpy.float64, addapt_numpy_float64)
registe... | numpy|psycopg2 | 23 |
14,243 | 50,557,669 | how to rotate mutiple rectangle coordinates around image center | <p>When it comes to test a computer vision algorithm object detection, by rotating a test image one can detect some missed objects. By doing so, those detected object locations represented by (x,y) coordinates for each point in rectangles should be rotated back. The output of object detector is a Numpy array which cont... | <p>The problem is that you are trying to subtract "center" - a 2-element vector from a <code>(100, 8)</code> "array of coordinates". In what space? 8D? If so, the center also should be a list of 8 coordinates because a point in an 8D space is defined by providing its coordinates along each of the 8 axes.</p>
<p>Your c... | python|image|numpy|scipy | 3 |
14,244 | 45,445,894 | str.match ignoring blank values | <p>when i'm trying to use str.mtach on blank values it is simply ignoring the blanks all together. </p>
<p>Before I resort to using an If statement, I want to see if I can get some help figuring this one out.</p>
<pre><code>df={'Original Litigation':['yes','','','',"No"]}
df=pd.DataFrame(df)
df["Suit Filed (Y/N)"]=""... | <p>You could use the regex pattern <code>^$</code> (beginning-of-string followed by end-of-string)
to match empty strings:</p>
<pre><code>mask = df["Original Litigation"].str.match("N|^$", case=False)
df.loc[mask, "Suit Filed (Y/N)"]='No'
</code></pre>
<p>or, alternatively, you could use <code>str.len</code> to measu... | python|pandas | 2 |
14,245 | 45,618,827 | Pandas - Sum series of columns from 1-N | <p>I have some spend columns from week 1 to 52
I am looking to sum the first 26 and the last 26 separately.</p>
<p>I have the following:</p>
<pre><code>column_names = [x for x in df.columns.values.tolist()
if x.startswith("spend_")
]
</code></pre>
<p>This gives me all the columns i'm ... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> for select columns by labels:</p>
<pre><code>a = df.loc[:, 'spend_1':'spend_26'].sum(axis=1)
b = df.loc[:, 'spend_27':'spend_52'].sum(axis=1)
</code></... | python|pandas | 3 |
14,246 | 62,589,918 | Auto Increment Index against Unique Column Values in a DataFrame | <p>I have unique values in a column, but they all have strange codes, and I want to instead have a numeric counter to identify these values. Is there a better way to do this?</p>
<pre><code>class umm:
inc = 0
last_val = ''
@classmethod
def create_new_index(cls, new_val):
if new_val != cls.last_... | <p>Method 1</p>
<pre><code>#take the unique Doc ID's in the column
new_df=pd.DataFrame({'Doc_ID':df['Doc_ID'].unique()})
#assign a unique id
new_df['Doc_ID_index'] = new_df.index +1
#combine with original df to get the whole df
pd.merge(df,new_df,on='Doc_ID')
</code></pre>
<p>Method 2</p>
<pre><code>df['Doc_ID_index']... | python|pandas|dataframe|indexing | 2 |
14,247 | 62,785,184 | How to set a threshold when coloring and labeling scatterplot points in python | <p>I saw a python graph that looks like the following:</p>
<p><a href="https://i.stack.imgur.com/1IegH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1IegH.jpg" alt="enter image description here" /></a></p>
<p>I think doing something like this really puts emphasis on certain data points and takes aw... | <p>Calling <code>scatter</code> for each point isn't the most efficient. You can call <code>scatter</code> twice: once for data below and once for above the threshold:</p>
<pre><code>threshold = 5
ix = df.y < threshold
ax.scatter(df.x[ix], df.y[ix], c='gray')
ax.scatter(df.x[~ix], df.y[~ix], c=COLORS[df.color[~ix]]
... | python|pandas|dataframe|matplotlib|data-visualization | 0 |
14,248 | 62,502,172 | Any way to optimize the running time? Trying to add data to a new column from different dataframe | <p>I've got 2 dataframe: Nodes and Edges.
The edges DF only contains the From ID and to ID, my goal is to add two more columns (From Age, To Age) in order to do some statistics. the age data sits in the Nodes DF.
<strong>There are about 1.2M of nodes and 14M of edges in the dataframes</strong></p>
<p>right now this is ... | <p>assuming you have integer id's starting from zero you can just:</p>
<pre><code># Create some example dataframes
n_nodes=int(10E6)
n_edges=int(1.4*10E6)
edges = pd.DataFrame.from_dict({'From': np.random.randint(0,n_nodes,size=n_edges), 'To': np.random.randint(0,n_nodes,size=n_edges)})
nodes = pd.DataFrame.from_dict({... | python|pandas|numpy|graph|networkx | 0 |
14,249 | 54,324,968 | How do i add column header, in the second row in a pandas dataframe? | <p>I have a data frame frame from pandas and now I want to add columns names, but only for the second row. Here is an example of my previous output:</p>
<p><a href="https://i.stack.imgur.com/FBNoj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FBNoj.png" alt="enter image description here"></a></p>
... | <p>You should have a look at <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>DataFrame.read_csv</code></a>. The <code>header</code> keyword parameter allows you to indicate a line in the file to use for header names.</p>
<p>You could probably do it ... | python|python-3.x|pandas|csv | 2 |
14,250 | 54,347,081 | Locate dataframe and concatenate based on specific headers in Python | <p>If I have lots of excel files as follows (here are just two examples):</p>
<p>data1.xlsx</p>
<p><a href="https://i.stack.imgur.com/fvKwp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fvKwp.png" alt="df1"></a></p>
<p>data2.xlsx</p>
<p><a href="https://i.stack.imgur.com/HesSP.png" rel="nofollo... | <p>Extending @Charles R's answer with your requirement of multiple excel files.</p>
<pre><code># get all the files
os.chdir('C:\ExcelWorkbooksFolder')
FileList = glob.glob('*.xlsx')
print(FileList)
</code></pre>
<p>and then:</p>
<pre><code>for File in FileList:
for x in File:
# the rest of the code for r... | python|pandas | 1 |
14,251 | 71,366,015 | Discrepancy between log_prob and manual calculation | <p>I want to define multivariate normal distribution with mean <code>[1, 1, 1]</code> and variance covariance matrix with <code>0.3</code> on diagonal. After that I want to calculate log likelihood on datapoints <code>[2, 3, 4]</code></p>
<p><strong>By torch distributions</strong></p>
<pre><code>import torch
import tor... | <p>You are passing the covariance matrix to the <code>scale_tril</code> instead of <code>covariance_matrix</code>. From the docs of <a href="https://pytorch.org/docs/stable/distributions.html#multivariatenormal" rel="nofollow noreferrer">PyTorch's Multivariate Normal</a></p>
<blockquote>
<p>scale_tril (Tensor) – lower-... | python|pytorch | 2 |
14,252 | 71,256,458 | For a numpy array, is there a difference between assigning to array and array[:]? | <p>This a quite basic and subtle question that I've never considered before, but I recently stumbled across the notation <code>a[:]</code> again and this time it caught my attention. Consider the two following examples:</p>
<p><strong>Example A</strong></p>
<pre><code>a = numpy.zeros(10)
vals = numpy.arange(10)
a ... | <p>Yes, the difference is that <code>a = </code> changes the value associated with the name <code>a</code> and <code>a[:] = </code> internally mutates <code>a</code>.</p>
<p>Mutating <code>a[:]</code> internally should take up a little less memory, since the original value of <code>a</code> doesn't need to be separatel... | python|arrays|numpy | 3 |
14,253 | 71,165,317 | Why does "in" work for a pandas Series in a list comphrension and not as a logical expression | <p>If I want to loop through values in a Series, I can do that using the <code>in</code> operator</p>
<pre><code>[x for x in pd.Series(['Hello, World!'])]
> ['Hello, World!']
</code></pre>
<p>but if I use <code>in</code> to check if <code>Hello, World!</code> is in the Series, it returns <code>False</code>.</p>
<pr... | <p>I'm not quite sure if you're asking a practical question or a theoretical one. The theoretical answer is that whoever wrote the Panda code made a specific design decision.</p>
<ul>
<li><p>Python interprets <code>x in thing</code> by calling <code>y.__contains__(x)</code>.</p>
</li>
<li><p>Python interprets <code>fo... | python|pandas|logic|list-comprehension|series | 1 |
14,254 | 60,590,437 | How do I select a particular ROW in a single column CSV file containing a particular "substring" and add to a new list with python Pandas? | <p>I have a single column CSV file with a large number of rows. How do I extract a row containing a particular "substring" and then add the row to a new list?</p>
<p>Regards</p>
<p>Prabhat</p> | <p>Perhaps this gets you moving towards a solution...</p>
<p>Input list (need to return all rows with the letters a and t together ('at')...</p>
<pre><code> Col1
0 the
1 cat
2 sat
3 on
4 the
5 mat
6 for
7 a
8 very
9 long
10 time
11 ... | python|pandas | 0 |
14,255 | 60,343,587 | same string from all the row python | <p>I have some data, the first column is the login, the second column is comment which is string or numbers or both, the data is this:</p>
<pre><code>Login Comment
256 qq456
257 msn176453
</code></pre>
<p>I want to find all the rows that the the begining of the comment is qq. I was trying to use:</p>
<pre><code>... | <p>Try using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.startswith.html" rel="nofollow noreferrer"><code>str.startswith</code></a>:</p>
<pre><code>orders[orders['Comment'].str.startswith('qq')]
</code></pre> | python|regex|pandas | 3 |
14,256 | 72,562,107 | How to chang the output of the concrete function in Tensorflow 2.x? | <p>I have trained a TensorFlow model and saved it to a local disk. when I loaded it and do inference, how can I get the output of the intermediate layer?</p>
<p>I use the example in the <a href="https://www.tensorflow.org/tutorials/quickstart/advanced" rel="nofollow noreferrer">tutorial</a> as a demo.</p>
<p>The model ... | <p>You can try running:</p>
<pre><code>print([var for var in concrete_fun.trainable_variables])
</code></pre>
<p>to get your each layer's weights and biases. To access the graph of your model, you can run <code>concrete_fun.graph</code>. See <a href="https://www.tensorflow.org/api_docs/python/tf/Graph#get_operations" r... | python|tensorflow|deep-learning|pytorch | 1 |
14,257 | 72,663,111 | Cutting a string after the last occurrence of certain sign | <p>Can you please help me how to disentangle the following issue. I have a column in pandas df called "names" that contains links to webpages. I need to create a variable called "total categories" that will contain the parts of the link that appears after the last appearance of "/" sign. E... | <p>If you have these set up as columns in a pandas DataFrame, you can do the following:</p>
<pre class="lang-py prettyprint-override"><code>df['total categories'] = df['names'].str.split('/').str[-1]
</code></pre>
<p>This will split the string based on the passed delimiter, <code>'/'</code>, and then take the last elem... | python|pandas|string | 1 |
14,258 | 72,809,395 | Pandas: How can I move certain columns into rows? | <p>Suppose I have the <code>df</code> below. I would like to combine the price columns and value columns so that all prices are in one column and all volumes are in another column. I would also like a third column that identified the price level. For example, <code>unit1</code>, <code>unit2</code> and <code>unit3</code... | <p>Try with <code>melt</code> , then <code>pivot</code> after <code>split</code></p>
<pre><code>s = df.melt(['uid','location'])
s[['unit','type']] =
s['variable'].str.split('_',expand=True)
s = s.pivot(index = ['uid','location','unit'],columns = ['type'],values = 'value').reset_index()
s
Out[967]:
type uid locatio... | python|pandas|dataframe|unpivot | 8 |
14,259 | 72,764,788 | Implement multiprocessing to test two videos simultaneously in opencv for object detection | <p>I am implementing an object detection model using a YOLO algorithm with PyTorch and OpenCV. Running my model on a single video works fine. But whenever I am trying to use multiprocessing for testing more videos at once it is freezing. Can you please explain what is wrong with this code ??</p>
<pre><code>import torch... | <p>I got it to work by adding <code>torch multiprocessing</code> code.</p>
<pre><code>from torch.multiprocessing import Pool, Process, set_start_method
try:
set_start_method('spawn', force=True)
except RuntimeError:
pass
videos = ['videos/video1.mp4', 'videos/video2.mp4']
for i in videos:
process = Proces... | python|multithreading|opencv|pytorch|multiprocessing | 2 |
14,260 | 59,866,119 | Build a dataframe from a dict with specified labels from a txt | <p>i want to make a dataframe with defined labels. Dont know how to tell panda to take the labels from the list. Hope someone can help</p>
<pre><code>import numpy as np
import pandas as pd
df = []
thislist = []
thislist = ["A","D"]
thisdict = {
"A": [1, 2, 3],
"B": [4, 5, 6],
... | <p>Use:</p>
<pre><code>df = pd.DataFrame(thisdict)[thislist]
print(df)
A D
0 1 7
1 2 8
2 3 9
</code></pre>
<p>We could also use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>DataFrame.drop</code></a></p>
<pre><code>df = pd.Da... | python|python-3.x|pandas|dataframe | 8 |
14,261 | 59,635,147 | Looping through multiple arrays & concatenating values in pandas | <p>I've a dataframe with list of items separated by <code>, commas</code> as below.</p>
<pre><code>+----------------------+
| Items |
+----------------------+
| X1,Y1,Z1 |
| X2,Z3 |
| X3 |
| X1,X2 |
| Y2,Y4,Z2,Y5,Z3 |
| X2,X3,Y1,Y2,Z2,Z4,... | <p>Assuming a column of <code>list</code>s, <code>explode</code> the lists, then this is a simple <code>isin</code> check that we sum along the original index. I'd suggest a different output, which gets across the same information but is much easier to work with in the future.</p>
<h3>Example</h3>
<pre><code>import p... | python|arrays|pandas | 8 |
14,262 | 40,668,974 | Python3 pandas: data frame grouped by a columns(such as name), then extract a number of rows for each group | <p>There is data frame called df as following:</p>
<pre><code>name id age text
a 1 1 very good, and I like him
b 2 2 I play basketball with his brother
c 3 3 I hope to get a offer
d 4 4 everything goes well, I think
a 1 1 I will visit china
... | <p>Try using head() instead.</p>
<pre><code>import pandas as pd
from io import StringIO
buff = StringIO('''
name,id,age,text
a,1,1,"very good, and I like him"
b,2,2,I play basketball with his brother
c,3,3,I hope to get a offer
d,4,4,"everything goes well, I think"
a,1,1,I will visit china
b,2,2,"no one can understan... | pandas|dataframe|python-3.5 | 1 |
14,263 | 40,566,541 | Efficient chain merge in pandas | <p>I found that straightforward chain merging with pandas library is quite inefficient when you merge a lot of datasets with a big number of columns by the same column.</p>
<p>The root of the problem is the same as when we join a lot of str's dumb way:</p>
<pre><code>joined = reduce(lambda a + b, str_list)
</code></pre... | <p>If you have a list of your dataframes <code>dfs</code>:</p>
<pre><code>dfs = [df1, df2, df3, ... , dfn]
</code></pre>
<p>you can join them using panda's <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects" rel="noreferrer"><code>concat</code></a> function which as far as I can t... | python|pandas|merge | 6 |
14,264 | 61,809,844 | Class Instantiation with @jitclass decorator | <p>I am attempting to use Numba's @jitclass decorator in order to, obviously, speed up my code. I am getting errors that seem to be for a fundamental understanding of the @jitclass</p>
<hr>
<p>ss decorator.</p>
<pre><code>import numba
from numba import jitclass
spec = [('raster',numba.float32[:,:]),('height', numba... | <p>I haven't used <code>numba</code> much, and this <code>jitclass</code> none, but by reading the docs, and some trial and error I got this to work:</p>
<pre><code>In [308]: spec = [('raster',numba.float32[:,:]),('height', numba.int32),('width', numba.int32),('azis', numba.int64[:])]
In [309]: @numba.jitclass(spec) ... | python|numpy|numba | 0 |
14,265 | 61,808,326 | How to replace all RGB values in an Numpy Image Arrray based on an Target Pixel | <p>I have an Image in an Numpy Array.
I will replace an specific Color with Black and all others in White.
For loops are to slow and my numpy condition ist not working.</p>
<p>All pixels that matches an array --> [121, 112, 131] must complete replace with another array --> [0, 0, 0]</p>
<p>All other with --> [255, 25... | <p>Your image shape is <code>(768, 1024, 3)</code>. You want to make a mask of where it is equal to a 3-element array. You have found that a correct way to do this is</p>
<pre><code>mask = np.all(img == target_color, axis=2)
</code></pre>
<p>This works because the shapes are broadcast from the rightmost dimension. Yo... | python|numpy|image-processing|multidimensional-array | 3 |
14,266 | 61,736,578 | Store response type to dataframe | <p>I am trying yo gave the download results to a dataframe download portion works but at the end the dataframe is blank</p>
<pre><code>df = pd.DataFrame()
url = 'https://www.cms.gov/files/zip/monthly-contract-summary-report-april-2020.zip'
FolderYear = '2020'
FolderName = 'ContractSummary'
FileName = 'monthly-contrac... | <p>Do this instead of your last few lines:</p>
<pre><code>rows = []
columns = ['Status', 'headers', 'FileName', 'FullWritePath', 'ZipFileDowlondLink']
rows.append([r.status_code, r.status_code, FileName, FullWritePath, url])
df = pd.DataFrame(rows, columns=columns)
print(df)
Status headers ... | python|pandas | 0 |
14,267 | 57,793,966 | Replace Function of pandas Giving same value | <p>I'm trying to replace a Number from .csv row with some constant string value. But somehow the code rewrites entire content of csv but doesn't replace it.</p>
<p>I have tried using delimiter but didn't work.</p>
<pre><code>newfile = pd.read_csv(file,delimiter = ',')
for B in Testnumber:
files=newfile.replace(to... | <p>There's a problem with your logic. For each B, files is newly generated from newfile, so any previous changes made are overwritten. A better solution would be:</p>
<pre><code>newfile = pd.read_csv(file, delimiter=',')
for B in Testnumber:
newfile = newfile.replace(to_replace=B, value="BlacklistedNumber")
newfil... | python|pandas|csv | 0 |
14,268 | 57,769,694 | Error while trying to connect to ibm db2 database through pandas: Can't load plugin: sqlalchemy.dialects:ibm_db_sa | <p>Hello I'm getting this error while trying to save a Pandas dataframe into the ibm db2 database: </p>
<blockquote>
<p>Can't load plugin: sqlalchemy.dialects:ibm_db_sa</p>
</blockquote>
<p>I tried this solution but is does not work:</p>
<pre><code>df = pd.read_csv('https://data.cityofchicago.org/resource/jcxq-k9x... | <p>Resolved by installing the required pre-requisite module (<strong>ibm_db_sa</strong> ) which will also install the <strong>ibm_db</strong> module and the <strong>ibm_db_dbi</strong> module, and (by default, unless otherwise directed) will also install the <code>Db2 ODBC and CLI driver</code> into your site_packages ... | python|sql|pandas|db2 | 2 |
14,269 | 57,849,602 | How to create the matrix for chord diagram based on coloumn value: | <p>Say I have a data-frame which has data in the following format.</p>
<pre><code>UID | Name | ID
----------------
1 | ABC | IM-1
2 | XYZ | IM-2
3 | XYZ | IM-2
4 | PQR | IM-3
5 | PQR | IM-4
6 | PQR | IM-5
7 | XYZ | IM-5
8 | ABC | IM-5
</code></pre>
<p>I need to create a matrix that feeds into the chord diagram code. ... | <p>Updated my answer but the approach is basically the same. Parse the data into a data frame, do an <a href="https://en.wikipedia.org/wiki/Join_(SQL)" rel="nofollow noreferrer">inner join</a> on <code>ID</code> to get the pairs of names that are linked by sharing a common <code>ID</code>. Then convert this edge list i... | python-3.x|pandas|numpy|matplotlib|chord-diagram | 1 |
14,270 | 34,391,644 | different rendering results using jinja2 between centos and windows | <p>I am trying to output a custom styled pandas dataframe to html.
One problem I can not figure is that when the code is rendered in Centos integers are rendered as float. This does not happen on windows.</p>
<pre><code>> /usr/local/lib64/python2.6/site-packages/pandas/core/style.py(267)render()
266 ... | <p>I found a workaround.</p>
<p>By inspecting the code I found out that the given template was not rendering correctly. The <code>round(precision)</code> was the cause. </p>
<p>So, I changed the original template a little bit to "fix" it.
Specifically, I changed</p>
<pre><code> {% if c.value is number and c.... | python|pandas|jinja2 | 0 |
14,271 | 55,010,497 | Why can I not import numpy in terminal while being able to import it in Jupyter notebook? | <p>Today I decided to update my Anaconda distribution. But after the update, when I try to import numpy in the terminal or in VScode, I get the following error message (which I just quote the last lines)</p>
<pre><code>import numpy
ImportError:
Importing the multiarray numpy extension module failed. Most
likely you... | <p>Anaconda comes with its own Numpy and that is why you can access it in Jupyter.You will have to find the correct install file for you version of Python. You should be able to see this when you open your terminal.</p> | python|numpy|anaconda|jupyter-notebook | 0 |
14,272 | 55,050,445 | Multi-type storage array in Python | <p>I'm programming a game in <strong>python3.6</strong>. There is some <strong>pawns</strong> on the board which are instance of the class 'pawn'. There is also <strong>boulders</strong> on the board which are instance of the class boulder. I just want to store these pawns and boulders in an <strong>array</strong>, lik... | <p>Use <code>np.dtype(object)</code>: <code>np.array(board, dtype=np.dtype(object))</code></p>
<p>As for empty cells: just set them to <code>None</code>.</p>
<hr>
<p><strong>Edit</strong>: as some people have suggested, you might not need a numpy array at all. A list of lists or a dict with tuple indexes might solve... | python|arrays|numpy|types|storage | 2 |
14,273 | 49,517,830 | Incorrect regex identification using pandas | <p>I wrote a small program for data type detection using regular expressions. I worked on this project in the past and got a lot of help from this wonderful community. I was going to use this code for a current project but I found that I am having an issue with properly identifying floats. </p>
<p>The objective of thi... | <p>It's not identifying address as a float; it's identifying it as an integer, failing on <code>to_numeric</code>, and thus ignoring the <code>downcast</code>. Try this:</p>
<pre><code>pd.to_numeric(df['Address'], errors='coerce', downcast='integer')
</code></pre>
<p>You'll see that what it returns is a column of Na... | python|regex|pandas | 0 |
14,274 | 27,968,028 | Add row with duplicate index in a panda dataframe | <p>Let's say you have a data frame:</p>
<pre><code>df = pd.DataFrame(columns = ['item'], index = ['datetime'])
</code></pre>
<p>You can add an item on a specific date index:</p>
<pre><code>df.loc[pd.datetime(2015, 1, 15)] = 23
</code></pre>
<p>Is there any way I can add/append new items on the same index?</p>
<p>D... | <p>You could try:</p>
<pre><code>df.groupby(df.index).sum()
</code></pre>
<p>This would group the rows with duplicate indices and then sum them up. </p> | python|pandas | 3 |
14,275 | 28,196,024 | Python Pandas Index Sorting/Grouping/DateTime | <p>I am trying to combine 2 separate data series using one minute data to create a ratio then creating Open High Low Close (OHLC) files for the ratio for the entire day. I am bringing in two time series then creating associated dataframes using pandas. The time series have missing data so I am creating a datetime var... | <p>Years later...</p>
<p>This fixes the problem.</p>
<h1>df is a dataframe</h1>
<pre><code>import pandas as pd
df.index = pd.to_datetime(df.index) #convert the index to a datetime object
df = df.sort_index() #sort the converted
</code></pre>
<p>This should get the sorting back into chronological order</p> | python|sorting|datetime|pandas | 2 |
14,276 | 73,402,810 | can't open camera by index in Colab | <p>I am using <a href="https://github.com/theAIGuysCode/yolov4-custom-functions" rel="nofollow noreferrer">https://github.com/theAIGuysCode/yolov4-custom-functions</a> this repository. I want to crop and save pictures while running on webcam. I'm using Colab. But when I run the following code:</p>
<pre><code>!python de... | <p>If you're somehow able to use the webcam through Colab, make sure that the format of the video stream from your camera is supported by cv2.
I had a quick <a href="https://stackoverflow.com/a/20865122/14774959">look</a> and apparently only <code>.avi</code> is supported. So make sure that your input is in avi format.... | python|tensorflow|yolo|yolov4 | 0 |
14,277 | 35,329,681 | Pandas Fill Column with Dictionary | <p>I have a data frame like this:</p>
<pre><code> A B C D
0 1 0 nan nan
1 8 0 nan nan
2 8 1 nan nan
3 2 1 nan nan
4 0 0 nan nan
5 1 1 nan nan
</code></pre>
<p>and i have a dictionary like this:</p>
<pre><code>dc = {'C': 5, 'D' : 10}
</code></pre>
... | <p>You could use <a href="https://www.google.ru/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwj27de76-7KAhVDIpoKHXDXBK0QFggbMAA&url=http%3A%2F%2Fpandas.pydata.org%2Fpandas-docs%2Fstable%2Fgenerated%2Fpandas.DataFrame.fillna.html&usg=AFQjCNHbdi5xNDvPutmhleTYH7... | python|dictionary|pandas|dataframe | 5 |
14,278 | 35,036,622 | Float Tiff image to numpy array | <p>I have the problem that I have a float image (*.tif) with values from 0-1 and want to use this in my python program as a numpy array. But every module I've found so far that is capable of reading .tif converts it into a UINT8 which comes with information loss. </p> | <p>For large tiff images you can try to use <a href="https://github.com/mapbox/rasterio" rel="nofollow noreferrer">rasterio</a> library for geospatial data.</p>
<pre><code>with rasterio.open('/path/to/your/image.tif') as src:
bands = src.read()
</code></pre>
<p>the data type is inferred from the input image.</p> | python|numpy|tiff | 1 |
14,279 | 30,829,270 | Pandas: creating dataframe rows from other dataframe information | <p>I'm working with aggregated data, which I need to dis-aggregate in order to process it further. The original df contains a value 'no. of students' per row and I need one row in the new df per student:</p>
<p>Original df:</p>
<blockquote>
<pre><code> faculty A faculty B faculty x
male students ... | <p>I think the easiest way to "disaggregate" the data is to use a generator expression
to simply enumerate all the desired rows:</p>
<pre><code>(key for key, val in series.iteritems() for i in range(val))
</code></pre>
<hr>
<pre><code>import pandas as pd
df = pd.DataFrame({'faculty A': [2,4], 'faculty B':[7,3]},
... | python|pandas|dataframe | 1 |
14,280 | 31,036,148 | How to standardize/normalize a date with pandas/numpy? | <p>With following code snippet</p>
<pre><code>import pandas as pd
train = pd.read_csv('train.csv',parse_dates=['dates'])
print(data['dates'])
</code></pre>
<p>I load and control the data.</p>
<p>My question is, how can I standardize/normalize data['dates'] to make all the elements lie between -1 and 1 (linear or gau... | <pre><code>import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import time
def convert_to_timestamp(x):
"""Convert date objects to integers"""
return time.mktime(x.to_datetime().timetuple())
def normalize(df):
"""Normalize the DF using min/max"""
scaler = MinMaxScale... | python|numpy|pandas | 7 |
14,281 | 67,374,115 | Count sublists with the same values in a list | <p>How to count sublists with the same values (order doesn't matter) in a list?</p>
<p>I tried this:</p>
<pre class="lang-py prettyprint-override"><code>from collections import Counter
Input = [
[
'Test123', 'heyhey123', 'another_unique_value',
],
[
'Test123', 'heyhey123', 'another_unique_v... | <p>You can replace</p>
<pre><code>Counter(str(e) for e in li)
</code></pre>
<p>with</p>
<pre><code>Counter(tuple(sorted(e)) for e in li)
</code></pre>
<p>Giving output:</p>
<pre><code>Counter({('Test123', 'another_unique_value', 'heyhey123'): 3,
('heyhey123',): 1,
('Test123', 'heyhey123'): 1})
</code>... | python|pandas|counter | 1 |
14,282 | 34,855,600 | Split a numpy array by a key array | <p>I have an numpy array which looks like this:</p>
<pre><code>+----+-------+----------------+
| id | class | probability |
+----+-------+----------------+
| 0 | 0 | 0.371301944865 |
| 0 | 1 | 0.317619162391 |
| 0 | -1 | 0.311078922721 |
| 1 | 0 | 0.401434454687 |
| 1 | 1 | 0.316000976419 |
... | <p>Here is the solution by pandas:</p>
<pre><code>import pandas as pd
import numpy as np
x = np.array([[ 0.00000000e+00, 0.00000000e+00, 3.71301945e-01],
[ 0.00000000e+00, 1.00000000e+00, 3.17619162e-01],
[ 0.00000000e+00, -1.00000000e+00, 3.11078923e-01],
[ 1.00000000e+00, 0.000... | arrays|numpy | 3 |
14,283 | 34,598,204 | Check if values are contained within a Tensor | <p>Unfortunately I was unable to find a function that achieved the following:</p>
<p>Inputs:</p>
<ul>
<li>test: Tensor of values that may exist within target</li>
<li>target: Tensor of values</li>
</ul>
<p>Outputs:</p>
<ul>
<li>output: Tensor of boolean, same shape as test. <code>output[i] = targets.contains(test[i... | <p>Answer updated 2020-03-23 to use setdiff.</p>
<p>You want to use <a href="https://www.tensorflow.org/api_docs/python/tf/sets/difference" rel="nofollow noreferrer"><code>tf.sets.difference</code></a>.</p>
<p>Given two tensors <code>test</code> and <code>target</code>,</p>
<pre><code>not_in_target = tf.sets.differe... | python|tensorflow | 6 |
14,284 | 59,914,714 | Transforming columns into numerical values when copying | <p>I have a data frame which I read in via </p>
<p><code>data = pd.read_csv("animals_clean.csv")</code></p>
<p>It contains a column which has over 67000 values and the same 80+ values are repeated throughout.<br>
such as:</p>
<pre><code> Ailurus
Harpia
Alligator
Branta
Araucaria
Branta
Alligator
... | <p>You can try </p>
<pre><code>df['num_A']=df.A.astype('category').cat.codes
</code></pre>
<p>Or </p>
<pre><code>df['num_A']=df.A.factorize()[0]
</code></pre>
<p>Or </p>
<pre><code>df.groupby('A').ngroup()
</code></pre> | python|pandas|data-conversion|columnsorting | 4 |
14,285 | 60,104,737 | Extract ID and value from set of strings in an array | <p>I'm having difficulty solving the following problem.</p>
<p>I have a pandas <code>df['subjects']</code> which has a list of strings.</p>
<pre><code>df['subjects'].head(3) =
0['B:1187', 'B:1188', 'P:123456', 'B:62']
1['G:1', 'G:1C', 'G:21', 'G:3', 'G:30']
2['B:71', 'E:D', 'G:6J', 'P:125467', 'B:1296', 'P:789456']... | <p>We can do <code>explode</code> then using <code>startswith</code> + <code>split</code> before <code>groupby</code> </p>
<pre><code>s=df['subjects'].explode()
s=s[s.str.startswith('P:')].str.split(':').str[-1].groupby(level=0).agg(list).reindex(df.index)
0 [123456]
1 NaN
2 [125467, 7894... | python|pandas | 5 |
14,286 | 59,945,083 | Find NaN's in pandas.Dataframe | <p>This is my code to check if a certain cell in my Dataframe is empty.
Bfore there is a for loop to iterate over the rows. the counter is <code>i</code> </p>
<pre><code>if change.isna(change.iloc[i,3]):
continue
</code></pre>
<p>Can't figure out why I receive the </p>
<pre><code>**TypeError**: isna() t... | <p>The positional argument <code>isna</code> takes is <code>self</code>, because you're calling the method of <code>pd.Dataframe</code> (<code>change.isna()</code>). You're passing one argument, but that's the <em>second</em> argument to the function, hence the error.</p>
<p>Take a look at <a href="https://pandas.pyda... | python|pandas|dataframe | 1 |
14,287 | 60,068,367 | How do I write the result of tf.Data.dataset.take() using TFRecordWriter? | <p>I am attempting to read in a tfrecord file, shuffle and split it, and then save to two tfrecords so I can use the same validation data in multiple runs.</p>
<p>The problem I'm getting is that what I assumed would be a Dataset object is a TakeDataset object.</p>
<p>I'm on Ubuntu 16.04 and using Tensorflow 2.1.0.</p... | <p>It depends on what type of data your <code>tf.data.Dataset holds</code>, I have taken string data as example and given the method below, to complement the solution I have provided helper functions for other types of data as well. </p>
<p>In order to write data to <code>TFRecords</code>, we need to convert each data... | tensorflow|keras|tfrecord | 4 |
14,288 | 59,990,774 | Python find size of each sublist in a list | <p>I have a big list of floats and integers as given below. I want to find the length of each sublist by neglecting empty or single elements. </p>
<pre><code>big_list = [[137.83,81.80,198.56],0.0,[200.37,151.55,165.26, 211.84],
0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]
</code></pre>
<p>My present code: </p>
... | <p>I would go for: </p>
<pre><code>big_list = [(137.83,81.80,198.56),0.0,np.array([200.37,151.55,165.26, 211.84]),
0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]
list_len = [len(x) for x in big_list if hasattr(x, '__len__') and len(x)>0]
</code></pre>
<p>which works with numpy arrays and tuple as well</p> | python|pandas|numpy | 2 |
14,289 | 60,030,130 | How to read multiple text files into arrays? | <p>I have multiple text files, each containing several columns. I need to read each file into an array in python, called RDF. The point is that I used to read <strong>one</strong> file into <strong>one</strong> array as following:</p>
<pre><code>RDF_1 = numpy.loadtxt("filename_1.txt", skiprows=205, usecols=(1,), unpak... | <p>You can use dictionaries as a proper way:</p>
<pre><code>files_mapping = dict()
for i in range(100):
files_mapping[f'RDF_{i}'] = numpy.loadtxt(f"filename_{i}.txt", skiprows=205, usecols=(1,), unpak=True)
</code></pre>
<p>But if for some unknown reasons you really need to dynamically create variables then you c... | python|arrays|numpy|loops|text-files | 1 |
14,290 | 65,129,065 | Problems filling DataFrames in dict of dicts | <p>I have something like a matrix of empty dataframes.</p>
<pre><code>A = {'folder1':{'case1':pd.Dataframe(), 'case2':pd.Dataframe(),... , 'case8':pd.Dataframe()}\
{'folder2':{'case1':pd.Dataframe(), 'case2':pd.Dataframe(),... , 'case8':pd.Dataframe()}\
...
{'foldern':{'case1':pd.Dataframe(), 'case2':pd.Datafra... | <p>I found a mistake. Sorry for everyone who lost time reading it.
The problem was:
Since my language is portuguese, sometimes I iterate the Folders in portuguese, as "pasta",
I was iterating "folder" and using "pasta"
As my last value of pasta was relative to the last folder (pasta = 'fol... | python|pandas|dataframe|dictionary | 0 |
14,291 | 65,420,982 | Importing only specific variable from different file to current file | <p>I have 2 files on the same folder <code>alice.py</code> and <code>bob.py</code>. These are the program I wrote:</p>
<pre><code>#alice.py
import random
import numpy as np
from numpy.random import randint
equal_to = {"upl":"u_plus", "EPR":"u_minus", "vpl":"v_plu... | <p>here, do this in <code>alice.py</code>
replace</p>
<pre class="lang-py prettyprint-override"><code>print(alice_bits)
print(dict((i,e) for i,e in enumerate(bell_state)), len(bell_state))
print(str(encrypted_bits).replace(',', ''), len(encrypted_bits))
</code></pre>
<p>with</p>
<pre class="lang-py prettyprint-override... | python|python-3.x|numpy|quantum-computing | 1 |
14,292 | 63,799,424 | Concurrent access to pandas.Dataframe slow | <p>I have an application with a shared data (<code>pandas.DataFrame</code>). This data is updated from a background task (WebSocket) and also read via web interface. What I noticed, during an update the read is totally blocked.</p>
<p>I update DataFrame using <code>loc()</code>, and I have also tried <code>append()</co... | <blockquote>
<p>I am using <code>aiohttp</code> web framework.</p>
</blockquote>
<p>I assume your code looks something like</p>
<pre><code>df = pd.DataFrame() # Probably loaded from somewhere
async def some_handler(request):
some_data = get_some_data_from_request()
for ... in some_data:
df.loc[...] = ..... | python|pandas|dataframe | 1 |
14,293 | 32,764,825 | Filter pandas DataFrame through list of dicts | <p>I have DataFrame of arbitrary length, with X columns (lets say 10):</p>
<pre><code>>>> names = ['var_' + str(x) for x in range(1, 11)]
>>> names
['var_1', 'var_2', 'var_3', 'var_4', 'var_5', 'var_6', 'var_7', 'var_8', 'var_9', 'var_10']
>>> df = pd.DataFrame(np.random.randint(100, size=(1... | <p>I'm not sure if I get it right, but if you want to filter your dataframe by few criteria from a dictionnary you could do something like this :</p>
<pre><code>In [107]: df
Out[107]:
var_1 var_2 var_3 var_4 var_5 var_6 var_7 var_8 var_9 var_10
0 45 36 84 24 86 26 44 6 ... | python|pandas|indexing|filter | 0 |
14,294 | 32,635,911 | convert elements of an array from scientific notation to decimal notation in python | <p>I have a numpy array come of whose elements are in scientific format and I want to convert them into decimal format. My numpy array looks like this:</p>
<pre><code>[array([ 93495052.96955582, 98555123.06146193])]
[array([ 1.00097681e+09, 9.98276347e+08])]
[array([ 6.86812785e+09, 6.90391125e+09])]
[array([ ... | <p>First off, as several people have noted, there's a very large difference between how the numbers are displayed and how they're stored.</p>
<p>If you want to convert them to strings, then use <code>'{:f}'.format(x)</code> (or the <code>%</code> equivalent).</p>
<p>However, it sounds like you're only wanting the num... | python|arrays|numpy | 20 |
14,295 | 38,798,033 | Fast query in formatted data | <p>In my program I need to query through metadata.</p>
<p>I read data into <code>numpy</code> record array <code>A</code> from csv-like text file ** without duplicate rows**.</p>
<pre><code>var1|var2|var3|var4|var5|var6
'a1'|'b1'|'c1'|1.2|2.2|3.4
'a1'|'b1'|'c4'|3.2|6.2|3.2
'a2'|''|'c1'|1.4|5.7|3.8
'a2'|'b1'|'c2'|1.2|... | <p>With your file sample ('b' for py3)</p>
<pre><code>In [51]: txt=b"""var1|var2|var3|var4|var5|var6
...: 'a1'|'b1'|'c1'|1.2|2.2|3.4
...: 'a1'|'b1'|'c4'|3.2|6.2|3.2
...: 'a2'|''|'c1'|1.4|5.7|3.8
...: 'a2'|'b1'|'c2'|1.2|2.2|3.4
...: 'a3'|''|'c2'|1.2|2.2|3.4
...: 'a1'|'b2'|'c4'|7.2|6.2|3.2"""
</c... | python|database|numpy|indexing|mapping | 0 |
14,296 | 63,158,103 | Tensorflow keras model to opencv error when loading custom model (C++) | <p>i wanna put this model (<a href="https://www.pyimagesearch.com/2020/05/04/covid-19-face-mask-detector-with-opencv-keras-tensorflow-and-deep-learning/" rel="nofollow noreferrer">https://www.pyimagesearch.com/2020/05/04/covid-19-face-mask-detector-with-opencv-keras-tensorflow-and-deep-learning/</a>) to works in a C++ ... | <p>I ran into the same issue and managed to fix it by using only the frozen .pb file. OpenCV gives only the model + config function declaration in the documentation:</p>
<pre><code>cv::dnn::readNetFromTensorflow (const String & model, const String & config = String())
</code></pre>
<p>But the one with only... | python|c++|tensorflow|opencv|keras | 0 |
14,297 | 63,252,818 | How do I grab the last available value in a row to fill an NaN value | <p>I have the following DataFrame -</p>
<pre><code>dfx = pd.DataFrame(
{
'city': ['Monroe', 'Montgomery'],
2005: [144, 205],
2006: [173, 211],
2007: [np.NaN, np.NaN],
2008: [np.NaN, 206],
2009: [np.NaN, np.NaN],
2010: [128, 273]
}
)
</code></pre>
<p... | <p>You can consider this one-liner</p>
<pre><code>dfx.T.ffill().T
</code></pre> | pandas | 0 |
14,298 | 63,195,290 | ValueError: The truth value of a Series is ambiguous in one hot encoding error | <p>I have below piece of code where i am trying use one hot encoder. But i get the the errorValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p>
<pre><code> from sklearn.preprocessing import LabelEncoder, OneHotEncoder
import pandas as pd
target=train_feature... | <p>Invictus,</p>
<p>The error is caused by the fact that you are passing in <code>categories</code> parameter something that is not expected by encoder function.
If you want to select just categorical columns using selection, do this:</p>
<pre><code>ohe = OneHotEncoder(categories = 'auto', sparse=False )
selection = t... | python|pandas|one-hot-encoding|label-encoding | 2 |
14,299 | 63,271,897 | Splitting TensorFlow Dataset created with make_csv_dataset into 3 parts (X1_Train, X2_Train and Y_Train) for multi-input model | <p>I am training a deep learning model with Tensorflow 2 and Keras. I read my big CSV file with <code>tf.data.experimental.make_csv_dataset</code> and then split it into train and test datasets. However, I need to split my train dataset into three parts since my deep learning model takes two set of inputs in different ... | <p>As mentioned in the comments sections, you can use <code>map</code> method <code>Dataset</code> object which is returned by <code>make_csv_dataset</code> in order to split and combine the samples according to your model's expected input format.</p>
<p>For example, suppose we have a CSV file containing the following ... | python|tensorflow|machine-learning|keras|tensorflow-datasets | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.