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 |
|---|---|---|---|---|---|---|
377,100 | 63,410,790 | plots in matploblib become noisy | <p>so my code are :</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
x1 = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 14, 25]
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)
plt.figure(1)
plt.subplots(211)
plt.plot(x, y)
plt.subplots(212)
plt.plo... | <p>You have a small typo inside your code.
In the plots belonging to <code>figure(1)</code> change your <code>subplots()</code> to <code>subplot()</code> (remove the trailing s)</p> | python|linux|numpy|matplotlib | 2 |
377,101 | 63,553,184 | Get the row number from given indeces in Pandas | <pre><code>import pandas as pd
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]},
index=['first','second','third'])
</code></pre>
<p>Retrieving the corresponding indeces from a given list of row numbers is simple:</p>
<pre><code>df.iloc[[1,2]].index
</code></pre>
<p>But what about the converse? Suppose I ... | <p>Try:</p>
<pre><code>df.index.get_indexer(['second', 'third'])
</code></pre>
<p>Output:</p>
<pre><code>array([1, 2], dtype=int64)
</code></pre> | pandas|dataframe | 2 |
377,102 | 63,497,760 | pandas group by with isin statement return index true/false | <p>I have the following dataframe:</p>
<pre><code> balance
currency
JPY 2342
USD 33245
BTC 23424
ETH 19080
CNY 89678
</code></pre>
<p>The following code return the sum from the dataframe within only 2 categories, true and false:</p>
<pre><code>bal = df.groupby(~user_bal.index.isi... | <p>You could try with <code>where</code> first and then <code>groupby</code> + <code>sum</code>:</p>
<pre><code>groups=df.index.where(df.index.isin(['BTC', 'ETH']),'JPY')
df.groupby(groups).sum()
</code></pre>
<p>Output:</p>
<pre><code> balance
currency
BTC 23424
ETH 19080
JPY 1... | python|pandas | 1 |
377,103 | 63,445,562 | pandas Timestamp to datetime.date | <p>I have problem with converting pandas Series to datetime.datetime.</p>
<p>I got DataFrame - df, with column <strong>Timestamp</strong> of type: <code>pandas._libs.tslibs.timestamps.Timestamp</code> and column <strong>Timestamp-end</strong> of type: <code>pandas._libs.tslibs.timedeltas.Timedelta</code>
<a href="https... | <p>I beleive you need convert column to dates:</p>
<pre><code>df['Timestamp1'] = df['Timestamp'].dt.date
</code></pre>
<p>Or beter should be remove times, set them to <code>00:00:00</code>:</p>
<pre><code>df['Timestamp1'] = df['Timestamp'].dt.normalize()
</code></pre>
<p>And then subtract.</p>
<p>EDIT: You can subtract... | python|pandas|datetime | 2 |
377,104 | 63,645,473 | Python Pandas: Combine Dataframes that are unevenly filled | <p>Good day,</p>
<p>from one of our clients we're getting csv-exports that are looking something like this:</p>
<pre><code>id | name | object_a | amount_a | object_b | amount_b | object_c | amount_c
1 abc object_1 12 none none none none
id | name | obj... | <p>First <code>concat</code> all the csvs, and then use <code>pd.wide_to_long</code>:</p>
<pre><code>csv_paths = ["your_csv_paths..."]
df = pd.concat([pd.read_csv(i) for i in csv_paths]).replace("none", np.NaN)
print (pd.wide_to_long(df, stubnames=["object","amount"],
... | python|pandas|dataframe|sorting | 2 |
377,105 | 63,639,993 | Dataframe values pre-processing - readexcel drop apostrophe in values during importing or other ways to convert string to int values after importing | <p>I have an excel file with the data format below to import in dataframe.</p>
<p>My current code allows me to extract the exact rows as show in the picture into the dataframe.</p>
<pre><code>df_gdp = pd.read_excel (open(gdp_path,'rb'), sheet_name='T2', skiprows= 5, skipfooter= 29)
</code></pre>
<p>Below is the data in... | <p>Instead of:</p>
<pre><code>df_gdp.iloc[1:, 1] = df_gdp.iloc[1:, 0].str.replace("'", "").astype(float)
</code></pre>
<p>You must use:</p>
<pre><code>lst = df_gdp.iloc[0,1:].to_list()
lst = [s.replace(',', '') for s in lst]
lst = [float(i) for i in lst]
</code></pre>
<p>Now lst is: <code>[69124.4 ... | python|pandas|dataframe | 1 |
377,106 | 63,656,778 | How to load a trained TF1 protobuf model into TF2? | <p><em><strong>Update:</strong> This is a bug in tensorflow. Track progress <a href="https://github.com/tensorflow/tensorflow/issues/42980" rel="noreferrer">here</a>.</em></p>
<p>I have created and trained a model using stable-baselines, which uses Tensorflow 1.
Now I need to use this trained model in an environment wh... | <p>You can use compatibility layer of TensorFlow.</p>
<p>All <code>v1</code> functionality is available under <code>tf.compat.v1</code> namespace.</p>
<p>I managed to load your model in TF 2.1 (nothing special about that version, I just have it locally):</p>
<pre class="lang-py prettyprint-override"><code>import tensor... | tensorflow|tensorflow2.0|stable-baselines | 9 |
377,107 | 63,639,345 | tf.data.experimental.save VS TFRecords | <p>I have notice that the method <a href="https://www.tensorflow.org/api_docs/python/tf/data/experimental/save" rel="nofollow noreferrer"><code>tf.data.experimental.save</code></a> (added in r2.3) allows to save a <code>tf.data.Dataset</code> to file in just one line of code, which seems extremely convenient. Are there... | <p>TFRecord have several benefits especially when using the large datasets. <a href="https://medium.com/mostly-ai/tensorflow-records-what-they-are-and-how-to-use-them-c46bc4bbb564" rel="nofollow noreferrer">TFRecord</a> - If you are working with large datasets, using a binary file format for storage of your data can ha... | tensorflow|dataset | 0 |
377,108 | 63,530,609 | using rolling functions, in pandas, with a series where the time index is very sparse | <p>I have a time series where the index is in milliseconds and is quite sparse. You can have many entries a few ms apart and nothing for seconds.</p>
<p>I would like to compute a rolling min / max, but I can't get it to work.</p>
<p>The index is built that way:</p>
<pre><code>df['timestamp'] = pd.to_datetime(df['timest... | <p>When you do the following: <code>df['rolling_low'] = df['price'].rolling('1m').min()</code> you've got to make sure that
your timestamp is the index of the dataframe. This is done in: <code>df = df.set_index("timestamp")</code>
in the code example below, otherwise you will get <code>ValueError: window mus... | python|pandas | 0 |
377,109 | 63,450,286 | pd.groupby on another groupby, transposing results of pd.cut | <p>Another rather complicated question I'm stuck at regarding Pandas and its groupby and cut function. Situation is as follows, let's say I have a DataFrame that looks like this:</p>
<pre class="lang-py prettyprint-override"><code>import Pandas as pd
pd.DataFrame(data)
A B C ipv4
0 1 3 3 0.0.0.0
1 2... | <p>what you can do is to <code>join</code> a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>pd.get_dummies</code></a> of the column cut_group and then use <code>sum</code> in the <code>groupby</code>, something like:</p>
<pre><code># get dumm... | python|pandas|dataframe|pandas-groupby | 2 |
377,110 | 63,607,320 | How to group rows based on first and last review date columns for each ID and forward fill N/A values using python? | <p>I have the following data frame:</p>
<p><a href="https://i.stack.imgur.com/sAjHy.png" rel="nofollow noreferrer">Data frame</a></p>
<p>Here both Hotel_id and Chef_Id are unique(both can act as a primary key).</p>
<p>I need to fill the missing rows in Month_Year column(should add consecutive month_year between first a... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.last.html" rel="nofollow noreferrer"><cod... | python|pandas | 1 |
377,111 | 63,348,945 | Write DF to existing Excel file with pandas and openxlpy | <p>I am trying to write a df to an existing work sheet. Initially the programme opens a dialog box to select a new sheet name to be added, then find the path of the excel sheet.</p>
<pre><code>#reload window to select new sheet name
root = tk.Tk()
root.geometry('500x200+350+150')
root.configure(bg='#072462')
#set butt... | <p>Managed to find the syntax error. After setting the entry button</p>
<pre><code>ws_new_title = Entry(root, width=45, bg='#0A1944', fg='white', highlightthickness=0, borderwidth=0)
</code></pre>
<p>I needed to change this entry to a string variable before using as a new sheet name in existing Excel sheet. To do this ... | python|excel|pandas|dataframe | 0 |
377,112 | 63,732,828 | How do I load multiple already saved models | <p>I trained 5 different classifiers and save to disk, like so:</p>
<pre><code>for e in range(len(ensemble)): #..ensemble: -list of 5 models
save_file = "Model_" + str(e) + ".h5"
ensemble[e].save(save_file)
print("MODEL ", e, " SAVED!")
</code></pre... | <p>That's because you are loading from the wrong path</p>
<p>the files that you are iterating from the <code>files</code> list are relative paths</p>
<p>there an example:</p>
<pre><code>import os
model.save('/tmp/test.h5')
for root, dirs, files in os.walk('/tmp/'):
print(root) # root path 'tmp'
for file in files:
... | python|python-3.x|tensorflow|keras | 1 |
377,113 | 63,541,279 | Is there a way to loop through a dataframe and assign a value in a new column based on a list? | <p>I have one dataframe with 2 columns and I want to add a new column;</p>
<p>This new column should be updated based on a list that I have:</p>
<pre><code>list = [0,1,2,3,6,7,9,10]
</code></pre>
<p>The new column is only updated with the list value if the flag (in col2) is 1.
If flag is 0, do not populate row in new c... | <p>Let us try</p>
<pre><code>l = [0,1,2,3,6,7,9,10]
df['New']=''
df.loc[df.flag==1,'New']=l
df
Out[80]:
context flag New
0 0 1 0
1 0 1 1
2 0 0
3 2 1 2
4 2 1 3
5 2 1 6
6 2 1 7
7 2 0
8 4 1... | python|pandas|list|dataframe | 3 |
377,114 | 63,584,149 | Virtual Environment Settings for Rasa | <p>I have been building a Chatbot following Rasa for a while. I create a venvs for it, called Chatbot. T have tried many versions of different packs or frameworks, such as Python(3.8, 3.7, ...), Tensorflow (1.13, 1.15, 2.1, 2.2), conda (4.5.12, 4.8, ...) and pip (20.1.1, 20.2). However, I couldn't train and run my Rasa... | <p>I use conda and it works well with rasa (conda-4.8.4, python-3.7.7, pip-20.2.2, rasa-1.10.10). Note: Rasa requires Python 3.6 or 3.7</p>
<pre><code>conda create --name rasa_test python=3.7
conda activate rasa_test
conda install -c anaconda pip
conda update --all
pip install rasa
</code></pre> | python|tensorflow|compatibility|rasa | 1 |
377,115 | 63,652,270 | Keep column index after pandas.melt? | <p>I have a data frame of values varying over time. For example, the number of cars I observe on a street:</p>
<pre><code>df = pd.DataFrame(
[{'Orange': 0, 'Green': 2, 'Blue': 1},
{'Orange': 2, 'Green': 4, 'Blue': 4},
{'Orange': 1, 'Green': 3, 'Blue': 10}
])
</code></pre>
<p>I want to create graphs th... | <p>You can make a <code>MultiIndex</code> on the columns, then stack both levels.</p>
<pre><code># Map color to importance
d = (df.max().rank(method='dense', ascending=False)-1).astype(int)
df.columns = pd.MultiIndex.from_arrays([df.columns, df.columns.map(d)],
names=['color', 'i... | python|pandas|dataframe|seaborn | 1 |
377,116 | 63,589,810 | Create pandas dataframe based on row search substring value | <p>I am struggling to shape my Python data into a dataframe. Can anyone help me with the code that might get me there? It seems the easiest solution would be to create columns based on substrings of text from the rows but I cannot find documentation to get me the shape I am seeking from the rows.</p>
<p><a href="http... | <p>Without supplying your data or an explanation this mostly does what you want.</p>
<ol>
<li>comments explain approach</li>
<li>there is more work to be done on <em>linekey</em> however I cannot see the relationship between the actual data and the outcome you posted as an image</li>
</ol>
<pre><code>import re
import n... | python-3.x|pandas|dataframe | 0 |
377,117 | 63,471,524 | String Contains and String Does Not Contain in Same Command | <p>I have a dataset that looks like this. There are thousands of variations of the <code>symptom</code> column.</p>
<pre><code>ID Symptoms
1 neck infection, fever
2 tonsil wound
3 lymph laceration
4 tonsil sore
5 Leg break
5 ear ache, headache
</code></pre>
<p>I want all IDs who HAD either "neck", &qu... | <p><code>SyntaxError: unexpected EOF while parsing</code></p>
<p>This is a syntax error, meaning it's not even attempting to execute your code yet. EOF means End Of File. So it's reached the end of the file, but it was expecting to see some other syntax. In this case a closing parenthesis:</p>
<pre><code>LABS_TAT.loc[:... | python|pandas | 1 |
377,118 | 63,719,559 | How to check for vertex matches and replace the repeat index on the edge? | <p>After developing code for Delaunay triangulation I made a list of node coordinates and found that there are a few numbers of duplicate nodes.</p>
<p>So I avoid duplicate nodes:</p>
<pre><code>distort = tri.Triangulation(mesh_x, mesh_y) #triangulation
#making list of nodes coordinates
data = np.array([mesh_x, mesh_y... | <p>Every time you remove a node you need to subtract one to all the indices of triangles vertices bigger of the removed node index.</p> | python|numpy|triangulation|vertex | 0 |
377,119 | 63,539,890 | convert a list in rows of dataframe in one column to simple string | <p>I have a dataframe which has list in one column that I want to convert into a simple string</p>
<pre><code> id data_words_nostops
26561364 [andrographolide, major, labdane, diterpenoid]
26561979 [dgat, plays, critical, role, hepatic, triglyc]
26562217 [despite, success, imatinib, inh... | <p>Try this :</p>
<pre class="lang-py prettyprint-override"><code>df['data_words_nostops'] = df['data_words_nostops'].apply(lambda row : ','.join(row))
</code></pre>
<p>Complete code :</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
l1 = ['26561364', '26561979', '26562217']
l2 = [['andrographoli... | python|pandas | 3 |
377,120 | 63,401,585 | torch.jit.script(module) vs @torch.jit.script decorator | <p>Why is adding the decorator "@torch.jit.script" results in an error, while I can call torch.jit.script on that module, e.g. this fails:</p>
<pre class="lang-py prettyprint-override"><code>import torch
@torch.jit.script
class MyCell(torch.nn.Module):
def __init__(self):
super(MyCell, self).... | <p>Reason for your error is <a href="https://pytorch.org/docs/master/jit_language_reference.html#id2" rel="nofollow noreferrer">here</a>, this bulletpoint precisely:</p>
<blockquote>
<p>No support for inheritance or any other polymorphism strategy, except
for inheriting from object to specify a new-style class.</p>
</b... | pytorch|torchscript | 2 |
377,121 | 63,402,635 | Finding intersection of Pandas dataframes within range | <p>A project I'm working on requires merging two dataframes together along some line with a delta. Basically, I need to take a dataframe with a non-linear 2D line and find the data points within the other that fall along that line, plus or minus a delta.</p>
<h3>Dataframe 1 (Line that we want to find points along)</h3>... | <p>Have taken an approach of using <code>merge()</code> where x,y have been placed into bins from <em>good</em> curve <code>df1</code></p>
<ol>
<li>generated a uniform line, <em>y=x^2</em></li>
<li>randomised it a small amount to generate <code>df1</code></li>
<li>randomised it a large amount to generate <code>df2</cod... | python|pandas|dataframe|filter | 1 |
377,122 | 63,569,448 | Dataframe merge creates multiple columns | <pre><code>import numpy as np
import pandas as pd
np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})
right = pd.DataFrame({'key': [ 'E', 'F', 'G', 'H'], 'value': np.random.randn(4)})
df = left.merge(right, on='key', how='outer', indicator=True)
df
</code></pre>
<p><a... | <p>I think you want some thing like this, or please share how you want your output to look like :</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})
right = pd.DataFrame({'key': [ 'E', 'F', 'G', 'H'], 'value': np.r... | pandas|dataframe | 0 |
377,123 | 63,330,365 | How does pandas groupby() function makes a difference in this code? | <pre><code> import pandas as pd
data = {'Company':['GOOG','MSFT','FB','GOOG','MSFT','FB'],
'Dates':["1970-01-01 01:00:00","1970-01-01 01:00:02","1970-01-01 01:00:03","1970-01-01 01:00:04","1970-01-01 01:00:05","1970-01-01 01:00:06"]}
df = pd.Dat... | <p>The reason why , you have three <code>NaN</code> ,due to you have three different company name in df, so when we do <code>groupby</code> , it will split the dataframe into 3, then do <code>diff</code> for each of them, and <code>concat</code> the result back</p>
<p>Detail :</p>
<pre><code>df["Dates"] = pd.... | python|python-3.x|pandas|numpy|data-science | 1 |
377,124 | 63,629,615 | Numpy.array indexing | <pre><code>import numpy as np
arr = np.array([[0, 1, 0],
[1, 0, 0],
[1, 0, 0]])
mask = arr
print('boolean mask is:')
print(mask)
print('arr[mask] is:')
print(arr[mask])
</code></pre>
<p>Result:</p>
<pre><code>boolean mask is:
[[0 1 0]
[1 0 0]
[1 0 0]]
arr[mask] is:
[[[0 1 0]
[1 0... | <pre><code>import numpy as np
l = [[0,1,2],[3,5,4],[7,8,9]]
arr = np.array(l)
mask = arr[:,:] > 5
print(mask) # shows boolean results
print(mask.sum()) # shows how many items are > 5
print(arr[:,1]) # slicing
print(arr[:,2]) # slicing
print(arr[:, 0:3]) # slicing
</code></pre>
<p>output</p>
<pre><code>[[Fals... | python|numpy | 1 |
377,125 | 63,650,263 | Mapping value from dictionary to dataframe | <p>I have this <code>df</code>:</p>
<pre><code> opponent pontos_num
0 262 29.1
1 265 28.8
2 284 21.4
3 282 16.3
4 266 14.8
5 292 12.4
6 373 9.6
7 354 6.8
8 277 6.3
9 294 5.... | <p>As sushanth already commented, you need to swap <code>teams_dict</code> to have <code>value: key</code> pairs instead.</p>
<p>Then you should prefer the built-in <code>.replace</code> over <code>.map</code></p>
<pre><code>df['opponent_name'] = df.opponent.replace(
{v: k for k, v in teams_dict.items()})
</code></... | python|pandas | 0 |
377,126 | 63,426,561 | How to get a link in a dataframe | <p>with attached screenshot my question can be explained quite well.
<a href="https://i.stack.imgur.com/tqpry.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tqpry.png" alt="Screenshot" /></a></p>
<p>I am <strong>scraping</strong> the following page: <a href="https://www.transfermarkt.de/tsg-1899-hof... | <p>as I know <code>read_html</code> gets only text from table and it doesn't care of links, hidden elements, attributes, etc.</p>
<p>You need module like <code>BeautifulSoup</code> or <code>lxml</code> to work with full HTML and manually get needed information.</p>
<pre><code> soup = BeautifulSoup(response.text, 'htm... | python|pandas|hyperlink | 1 |
377,127 | 63,580,402 | Create cumulative list pandas | <p>I have this DataFrame</p>
<pre><code>lst = [[1,0],[None,1],[2,0],[2,0],[None,1],[None,1],[3,0],[None,1] ]
df1 = pd.DataFrame(lst,columns = ['id','is_cumulative'])
</code></pre>
<p>output</p>
<pre><code> id is_cumulative
0 1.0 0
1 NaN 1
2 2.0 0
3 2.0 0
4 NaN ... | <p>Let us try only with the id with <code>dropna</code> and drop the duplicate , <code>cumsum</code> the result then <code>reindex</code> and <code>fillna</code></p>
<pre><code>s = (df1.id.dropna().drop_duplicates().astype(str)+',').cumsum().str[:-1].str.split(',').reindex(df1.index).ffill()
df1.id = df1.id.fillna(s)
d... | python|pandas | 2 |
377,128 | 63,415,624 | Normalising a 2D histogram | <p>I have a 2D histogram h1 with var1 on the x axis and var2 on the y axis, which I've plotted from a <code>dataframe</code>. I have normalised it as I want in c++ but now need to do the same in python and am struggling with how to get and set bin content.</p>
<p>The idea is to remove the effect of having more events i... | <p>To manipulate the contents of the bins, you could first calculate them, change them and only then draw the plot.</p>
<p><code>plt.hist2d()</code> returns the bin contents (a 2D matrix) together with the bin edges in both directions. To get the same information without plotting, <code>np.histogram2d()</code> returns ... | python|c++|pandas|dataframe|matplotlib | 4 |
377,129 | 63,351,521 | How to group and get three most frequent value? | <p>i want to group by id and get three most frequent city. For example i have original dataframe</p>
<pre><code> ID City
1 London
1 London
1 New York
1 London
1 New York
1 Berlin
2 Shanghai
2 Shanghai
</code></pre>
<p>and result i want is like this:</p>
<pre><... | <p>First step is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="nofollow noreferrer"><code>SeriesGroupBy.value_counts</code></a> for count values of <code>City</code> per <code>ID</code>, advantage is already values are sorted, then get c... | python|pandas | 4 |
377,130 | 63,595,213 | Hadamard product for each unique pair of columns in numpy array | <p>Using Python (3.7.7) and numpy (1.17.4), I am working with medium sized 2d numpy arrays (from 5000x80 up to 200,000x120). For a given array, I want to calculate the Hadamard product between all possbible uniqe pairs of column-vectors of that array.</p>
<p>I have:</p>
<pre><code> A A
[a,b,c,d] [a,b,c,d... | <p><strong>Approach #1</strong></p>
<p>Simplest one with <a href="https://numpy.org/doc/stable/reference/generated/numpy.triu_indices.html" rel="nofollow noreferrer"><code>np.triu_indices</code></a> -</p>
<pre><code>In [45]: a
Out[45]:
array([[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 1]])
In [46]: r,c = np.... | python|arrays|numpy|unique | 3 |
377,131 | 63,697,309 | python, pandas - selecting group in multi indexing series | <p>I would like some advice to selecting a group.</p>
<p><a href="https://i.stack.imgur.com/Q1m9x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q1m9x.png" alt="https://i.stack.imgur.com/Q1m9x.png" /></a></p>
<p>for instance, I have try to select warehouse(JobTitle) and PA(loc):</p>
<pre><code>fdO2.... | <p>You can extract the "<code>Location</code>" and "<code>Sum of Spend</code>" for the <code>Warehouse</code> and <code>PA</code>:</p>
<pre><code>fdO2 = fdO2.loc[(fdO2["JobTitle"]=="Warehouse") & (fdO2["loc"]=="PA"),['Location','Sum of Spend']]
</code></pr... | python|pandas|dataframe|multi-index | 0 |
377,132 | 63,596,240 | Why error appear when I apply function to dataframe? | <pre><code>def function(s):
if (s['col1'] == 'something1')|(s['col1'] == 'smth2')|(s['col1'] == 'smth3'):
return 'A'
elif (s['col1'] == 'smth4')|(s['col1'] == 'smth5'):
return 'B'
elif (s['col1'] == 'smth6')|(s['col1'] == 'smth7'):
return 'C'
else:
return 'D'
</code></pre... | <p>For me working correct, here ia alternative solution with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> and <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code... | python|pandas|function|dataframe|typeerror | 1 |
377,133 | 63,455,140 | How to multiply two pandas columns from seperate dataframes together? | <p>I have two pandas dataframes, one as a look up table and one 'main' table.</p>
<p>The look up table is so.</p>
<pre><code>import pandas as pd
lu_dict = {'state': ['OH', 'TX', 'IA', 'WY', 'KS'], 'fire_pct':[0.542630,.174425,0.206752,0.004621,0.441946]
, 'hail_pct':[0.008787,0.440272,0.422005,0.434709,0.3123... | <p>IIUC, you need to do some renaming to get pandas to align data correctly.</p>
<pre><code>mults = (lu.rename(columns=dict(zip(lu.columns, preds.columns))).set_index('state') *
preds.set_index('state'))
print(mults)
</code></pre>
<p>Output:</p>
<pre><code> fire_preds hail_preds tw_preds other_preds ... | pandas | 1 |
377,134 | 63,442,862 | Unable to load images from a Google Cloud Storage bucket in TensorFlow or Keras | <p>I have a bucket on Google Cloud Storage that contains images for a TensorFlow model training. I'm using <code>tensorflow_cloud</code> to load the images stored in the bucket called <code>stereo-train</code> and the full URL to the directory with images is:</p>
<pre><code>gs://stereo-train/data_scene_flow/training/da... | <p>If you are using Linux or OSX you can use <a href="https://cloud.google.com/storage/docs/gcs-fuse" rel="nofollow noreferrer">Google Cloud Storage FUSE</a> which will allow you to mount your bucket locally and use it like any other file system. Follow the <a href="https://github.com/GoogleCloudPlatform/gcsfuse/blob/m... | python|tensorflow|keras|google-cloud-platform | 2 |
377,135 | 63,394,131 | Loading CSV with Pandas - Array's not parsed correctly | <p>I have a dataset which I transformed to CSV as potential input for a keras auto encoder.
The loading of the CSV works flawless with <code>pandas.read_csv()</code> but the data types are not correct.</p>
<p>The csv solely contains two colums: <strong>label</strong> and <strong>features</strong> whereas the label colu... | <p>You are reading the file as string but you have a python list as a column you need to evaluate it to get the list.
I am not sure of the use case but you can split the labels for a more readable dataframe</p>
<pre><code>import pandas as pd
features = ["featurea","featureb","featurec",&qu... | python|pandas|dataframe|csv | 1 |
377,136 | 63,651,243 | Your input ran out of data | <pre><code>history = model.fit_generator(
train_generator,
steps_per_epoch=50,
epochs=10,
verbose=1,
validation_data = validation_generator,
validation_steps=50)
</code></pre>
<p>tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator ... | <p>To solve this problem, we need to pay attention two items:</p>
<ol>
<li>How to define batch size and batch_size and steps_per_epoch.
The simple answer is steps_per_epoch=total_train_size//batch_size</li>
<li>How to define max number of epochs for the training process.
This is not as straightforward as the first one... | tensorflow2.0|tensorflow-datasets | 1 |
377,137 | 63,716,828 | Extract a particular value from categorical column using Python | <p>Following is the sample table which consists of transaction data of bank customers. I need to create a separate column as annual salary of customer taking the data from <code>txn_description</code> column.</p>
<pre><code>Customer_ID txn_description Amount Type
01 POS 345 Dr
02 SALAR... | <p>you could try this,</p>
<pre><code>df= df[df["txn_description"]=="SALARY"]
df["Annual"] = df["Amount"]*12
</code></pre>
<p>O/P:</p>
<pre><code> Customer_ID txn_description Amount Annual
1 2 SALARY 2000 24000
3 4 SALARY 1500 ... | python|pandas|data-science|data-analysis | 1 |
377,138 | 21,908,375 | R parameter DROP equivalent in Pandas | <p>I would like to know what is the Python (Pandas) equivalent of the following R code:</p>
<pre><code>outDataFrame <- myDataFrame[, rownames(inputDataFrame), drop=FALSE]
</code></pre>
<ul>
<li>row names of inputDataFrame are the same as the column names of myDataFrame.</li>
<li>each row of myDataframe contains on... | <p>Here is another way, using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow">np.argmax</a>:</p>
<pre><code>In [55]: myDataFrame = pd.DataFrame([(True,False,False), (False,False,True), (False,False,True)], index=list('ABC'), columns=list('XYZ'))
In [56]: myDataFrame
Out[... | python|r|select|pandas | 0 |
377,139 | 21,866,930 | left hand side eigenvector in python? | <p>How do calculate the left hand side eigenvector in python?</p>
<pre><code> >>> import from numpy as np
>>> from scipy.linalg import eig
>>> np.set_printoptions(precision=4)
>>> T = np.mat("0.2 0.4 0.4;0.8 0.2 0.0;0.8 0.0 0.2")
>>> print "T\n", T
T
... | <p>Your result is correct to my understanding.</p>
<p>However, you might be misinterpreting it. The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html" rel="noreferrer">numpy docs</a> are a bit clearer on what the left eigenvectors should be.</p>
<blockquote>
<p>Finally, it is emphas... | python-2.7|numpy|eigenvector | 6 |
377,140 | 21,469,261 | Extract subarray between certain value in Python | <p>I have a list of values that are the result of merging many files. I need to pad some of the values. I know that each sub-section begins with the value -1. I am trying to basically extract a sub-array between -1's in the main array via iteration.</p>
<p>For example supposed this is the main list:</p>
<pre><code>-1 1... | <p>You mentioned <code>numpy</code> in the tags. If you're using it, have a look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow"><code>np.split</code></a>.</p>
<p>For example:</p>
<pre><code>import numpy as np
x = np.array([-1, 1, 2, 3, 4, 5, 7, -1, 4, 4, 4, 5, 6, 7,... | python|arrays|list|numpy | 4 |
377,141 | 21,566,379 | Fitting a 2D Gaussian function using scipy.optimize.curve_fit - ValueError and minpack.error | <p>I intend to fit a 2D Gaussian function to images showing a laser beam to get its parameters like <code>FWHM</code> and position. So far I tried to understand how to define a 2D Gaussian function in Python and how to pass x and y variables to it.</p>
<p>I've written a little script which defines that function, plots... | <p>The output of <code>twoD_Gaussian</code> needs to be 1D. What you can do is add a <code>.ravel()</code> onto the end of the last line, like this:</p>
<pre><code>def twoD_Gaussian((x, y), amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
xo = float(xo)
yo = float(yo)
a = (np.cos(theta)**2)/(2*sigm... | python|numpy|scipy|data-fitting | 46 |
377,142 | 21,769,010 | Removing list comps from numpy code | <p>I'm in the middle of constructing a geometric neural net, and I'm running up against an issue with vectorization. Basically there is a lambda function I have defined that really should run on each sample provided as input. Problem being that it would be most convenient to pass in the inputs as an array with the last... | <p>You should checkout numpy's apply_along_axis method: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html</a></p>
<pre><code>>>> def my_func(a):
... """Average first and l... | python|arrays|numpy|vectorization | 1 |
377,143 | 21,752,989 | numpy: Efficiently avoid 0s when taking log(matrix) | <pre><code>from numpy import *
m = array([[1,0],
[2,3]])
</code></pre>
<p>I would like to compute the element-wise <code>log2(m)</code>, but only in the places where <code>m</code> is not 0. In those places, I would like to have 0 as a result.</p>
<p>I am now fighting against:</p>
<pre><code>RuntimeWarni... | <p>We can use masked arrays for this:</p>
<pre><code>>>> from numpy import *
>>> m = array([[1,0], [2,3]])
>>> x = ma.log(m)
>>> print x.filled(0)
[[ 0. 0. ]
[ 0.69314718 1.09861229]]
</code></pre> | numpy | 34 |
377,144 | 21,451,776 | convert numpy string array into int array | <hr>
<p>I have a numpy.ndarray</p>
<pre><code>a = [['-0.99' '' '0.56' ..., '0.56' '-2.02' '-0.96']]
</code></pre>
<p>how to convert it to int?</p>
<p>output : </p>
<pre><code>a = [[-0.99 0.0 0.56 ..., 0.56 -2.02 -0.96]]
</code></pre>
<p>I want 0.0 in place of blank ''</p> | <pre><code>import numpy as np
a = np.array([['-0.99', '', '0.56', '0.56', '-2.02', '-0.96']])
a[a == ''] = 0.0
a = a.astype(np.float)
</code></pre>
<p>Result is:</p>
<pre><code>[[-0.99 0. 0.56 0.56 -2.02 -0.96]]
</code></pre>
<p>Your values are floats, not integers. It is not clear if you want a list of lists ... | python|numpy | 15 |
377,145 | 24,876,906 | Removing duplicates from a series based on a symmetric matrix in pandas | <p>I am new to Pandas and have been unable to find a succinct solution to the following problem. </p>
<p>Say I have a Series of data based on a symmetric (distance)matrix, what is the most efficient way to drop duplicates from the following series?</p>
<pre><code>from pandas import DataFrame
df = DataFrame([[0, 1, ... | <p>The following code runs faster than the currently accepted answer:</p>
<pre><code>import numpy as np
def dm_to_series1(df):
df = df.astype(float)
df.values[np.triu_indices_from(df, k=1)] = np.nan
return df.unstack().dropna()
</code></pre>
<p>The type of the <code>DataFrame</code> is converted to <code... | python|pandas | 3 |
377,146 | 24,780,697 | numpy: unique list of colors in the image | <p>I have an image <code>img</code>:</p>
<pre><code>>>> img.shape
(200, 200, 3)
</code></pre>
<p>On pixel (100, 100) I have a nice color:</p>
<pre><code>>>> img[100,100]
array([ 0.90980393, 0.27450982, 0.27450982], dtype=float32)
</code></pre>
<p>Now my question is: How many different colors are... | <p>Your initial idea to use <code>numpy.unique()</code> actually can do the job perfectly with the best performance:</p>
<pre><code>numpy.unique(img.reshape(-1, img.shape[2]), axis=0)
</code></pre>
<p>At first, we flatten rows and columns of matrix. Now the matrix has as much rows as there're pixels in the image. Col... | python|numpy | 52 |
377,147 | 24,666,289 | Converting groupby dataframe (with dropped duplicate rows by group) into normal dataframe | <p>How do I convert a groupby dataframe I created in order to drop duplicates by a group back into a normal dataframe? </p>
<pre><code>df3 = df2.groupby('Organization')
df3 = df3.drop_duplicates('Name')
</code></pre>
<p>I tried this, but this seems to create abnormal properties that don't allow me to subset my data</... | <p>Instead of creating a groupby to drop duplicates, have you considered:</p>
<pre><code>df4 = df3.drop_duplicates(['Organization', 'Name'])
</code></pre>
<p>That will keep you in a normal dataframe the whole time and should accomplish what you're trying to do.</p>
<p>If you want to group and "ungroup" then <a href=... | python|pandas | 0 |
377,148 | 24,593,694 | How to troubleshoot code in the case of big data | <p>I'm trying to implement <a href="https://stackoverflow.com/questions/24581967/count-lines-with-same-value-in-column-in-python">this python solution to count the number of lines with identical content in the first few columns</a> of a table. Here is my code:</p>
<pre><code>#count occurrences of reads
import pandas a... | <p>Open the file <code>/usr/local/lib/python2.7/dist-packages/pandas-0.14.0-py2.7-linux-x86_64.egg/pandas/core/groupby.py</code>, go to line 2799.</p>
<p>Right before the following statement, in the same indent level, add a line to print the value of the offending data.</p>
<pre><code>raise TypeError('Transform func... | python|debugging|pandas|bigdata | 2 |
377,149 | 24,771,027 | evaluating numpy polynomials at other polynomials | <p>numpy.lib.polynomial.polyval lets you evaluate a polynomial using another polynomial:</p>
<pre><code>numpy.polyval(poly1d([1, 2, 3]), 2)
Out[832]: 11
numpy.polyval(poly1d([1, 1]), poly1d([1, 1, 1]))
Out[820]: poly1d([ 1., 1., 2.])
</code></pre>
<p>for instance. How do you do the same using numpy.polynomial.pol... | <p>The easiest way is to use the Polynomial class.</p>
<pre><code>In [1]: from numpy.polynomial import Polynomial as P
In [2]: p1 = P([1,1])
In [3]: p2 = P([1,1,1])
In [4]: p2(p1)
Out[4]: Polynomial([ 3., 3., 1.], [-1., 1.], [-1., 1.])
In [5]: p1(p2)
Out[5]: Polynomial([ 2., 1., 1.], [-1., 1.], [-1., 1.])
... | python|numpy|polynomial-math | 3 |
377,150 | 24,917,580 | Is there a way to pass different vertical lines to each subplot when using pandas histogram with "by=somevar"? | <p>I'm making histograms using pandas and I find this approach convenient. </p>
<p>For example if I do: </p>
<p>df['plotvar'].hist(by='Zone')</p>
<p>I get </p>
<p><img src="https://i.stack.imgur.com/56pgT.png" alt="Histograms">
But now I want to add the 95%CI on each of these subgroups, and of course the intervals ... | <p><code>DataFrame.hist()</code> with <code>by=</code> returns the array of matplotlib Axes, so you could grab that and then iterate over it.</p>
<p>For similar functionality that speaks pandas but has more flexible features you could use the <a href="http://stanford.edu/~mwaskom/software/seaborn/examples/many_facets.... | python|matplotlib|pandas|histogram | 0 |
377,151 | 24,684,441 | Pandas: Concatenate dataframe and keep duplicate indices | <p>I have two dataframes that I would like to concatenate column-wise (axis=1) with an inner join. One of the dataframes has some duplicate indices, but the rows are not duplicates, and I don't want to lose the data from those :</p>
<pre><code>df1 = pd.DataFrame([{'a':1,'b':2},{'a':1,'b':3},{'a':2,'b':4}],
... | <p>You can perform a merge and set the params to use the index from the lhs and rhs:</p>
<pre><code>In [4]:
df1.merge(df2, left_index=True, right_index=True)
Out[4]:
b c
a
1 2 5
1 3 5
2 4 6
[3 rows x 2 columns]
</code></pre>
<p>Concat should've worked, it worked for me:</p>
<pre><code>In [5]:
p... | python|pandas|concat | 7 |
377,152 | 24,556,426 | Aggregate a DataFrame column by counting special elements | <p>I have a DataFrame <code>b</code> in the following format: </p>
<pre><code> chip sampleid WL ok
0 1 test 4 True
1 2 test 4 False
</code></pre>
<p>If I want to count number of True elements in <code>b['ok']</code>, I can run this: </p>
<pre><code>In [125]: sum(b['ok'])
Out[125]: 1
</c... | <p>This clearly is a bug, <code>aggregate</code> will try to convert the result to the same <code>dtype</code> the original <code>DataFrame</code> has. Here the <code>sum</code> will return <code>1</code> and <code>bool(1)</code> is <code>True</code>. If both of the values in <code>ok</code> are <code>False</code>s, th... | python|pandas | 0 |
377,153 | 24,762,706 | Python Scipy Optimization curve_fit | <p>I have two numpy arrays x and y and would like to fit a curve to the data. The fitting function is an exponential with a and t as fitting parameters, and another numpy array ex. </p>
<pre><code>import numpy as np
import scipy
import scipy.optimize as op
k=1.38e-23
h=6.63e-34
c=3e8
def func(ex,a,t):
return a*n... | <p>Your initial guess should contain two values like <code>t0=(300, 1.)</code> since you have two fitting parameters (<code>a</code> and <code>t</code>).</p>
<p>You need to define the points you want to fit, i.e. defining <code>x</code> and <code>y</code> before calling <code>curve_fit()</code>.</p> | python|optimization|numpy|scipy|curve-fitting | 3 |
377,154 | 24,638,059 | RuntimeWarning: overflow encountered in np.exp(x**2) | <p>I need to calculate <code>exp(x**2)</code> where <code>x = numpy.arange(30,90)</code>. This raises the warning:</p>
<pre><code>RuntimeWarning: overflow encountered in exp
inf
</code></pre>
<p>I cannot safely ignore this warning, but neither SymPy nor mpmath is a solution and I need to perform array operations so a... | <p>I think you can use this method to solve this problem:</p>
<blockquote>
<p>Normalized</p>
</blockquote>
<p>I overcome the problem in this method. Before using this method, my classify accuracy is :86%. After using this method, my classify accuracy is :96%!!!
It's great!<br>
first:<br>
<a href="http://i.stack.img... | python|numpy|exp | 3 |
377,155 | 24,825,275 | Selecting rows by members of a list contained in a cell | <p>In my dataframe I have a column that contains lists of items. I would like to select only those rows that contain all or several items. At least matching a list would be great.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[2,[2,3,8]]], columns=['a','b'])
df
</code></pre>
<p>I have tried the following: </... | <p>I think you can do the following :</p>
<pre><code>idx = []
S = [2,3,8]
for i, line in df.iterrows():
if set(S).issubset(line['b']):
idx.append(i)
</code></pre>
<p>Now, you can select only the rows you're interested in :</p>
<pre><code>df_subset = df.ix[idx]
</code></pre> | python|pandas|selection|dataframe | 2 |
377,156 | 24,597,446 | pandas TimeSeries diff() reverts to Series | <p>I am working with some TimeSeries data in this format:</p>
<blockquote>
<p>1984-12-12 14:08:00<br>
1984-12-12 14:25:00<br>
1984-12-12 14:47:00<br>
1984-12-12 16:37:00<br>
1984-12-12 16:37:00<br>
1984-12-12 16:37:00<br>
1984-12-12 17:52:00<br>
1984-12-12 17:52:00<br>
1984-12-12 19:29:00 </p>... | <p>Pandas 0.12.0, Numpy 1.7.1, Python 2.7.5, Linux Mint</p>
<pre><code>import pandas as pd
import StringIO
data = '''time
1984-12-12 14:08:00
1984-12-12 14:25:00
1984-12-12 14:47:00
1984-12-12 16:37:00
1984-12-12 16:37:00
1984-12-12 16:37:00
1984-12-12 17:52:00
1984-12-12 17:52:00
1984-12-12 19:29:00'''
df = pd.read... | python|pandas | 4 |
377,157 | 24,870,953 | Does pandas iterrows have performance issues? | <p>I have noticed very poor performance when using iterrows from pandas.</p>
<p>Is it specific to iterrows and should this function be avoided for data of a certain size (I'm working with 2-3 million rows)?</p>
<p><a href="https://github.com/pydata/pandas/issues/7683" rel="nofollow noreferrer">This discussion</a> on Gi... | <p>Generally, <code>iterrows</code> should only be used in very, very specific cases. This is the general order of precedence for performance of various operations:</p>
<ol>
<li>vectorization</li>
<li>using a custom Cython routine</li>
<li>apply
<ul>
<li>reductions that can be performed in Cython</li>
<li>iteration in ... | python|performance|pandas|iteration | 246 |
377,158 | 24,935,282 | Pandas: merging two dataframes | <p>The output of a MERGE operation on two pandas data frames does not yield the expected result:</p>
<pre><code>**dfmatrix**:
… young label filename
0 … 1 neg cv005_29357
1 … 0 neg cv006_17022
2 … 0 neg cv007_4992
3 … 1 neg cv008_29326
4 … 1 n... | <p>the problem was at the file level: the entries in the <code>filename</code> column of the <code>dfscores</code> file being read had a <code>trailing whitespace</code> which caused the JOIN to fail. Admitted, this is not a glorious moment for me but neverthelesss these things happen and i think it is worth posting th... | python|pandas | 0 |
377,159 | 30,155,740 | Incorrect Pandas DataFrame creation using lists | <p>I want to create a data frame using Python's Panda by reading a text file. The values are tab-separated but when I use this code:</p>
<pre><code>import sys
import pandas as pd
query = sys.argv[1]
df = pd.DataFrame()
with open(query) as file_open:
for line in iter(file_open.readline, ''):
if line.st... | <p>Don’t read the file by hand. Use pandas’ powerful <code>read_csv</code>:</p>
<pre><code>df = pd.read_csv(query, sep='\t')
</code></pre>
<p>Full program:</p>
<pre><code>import sys
import pandas as pd
query = sys.argv[1]
df = pd.read_csv(query, sep='\t')
print df
</code></pre> | python|list|pandas|dataframe | 2 |
377,160 | 29,852,233 | Assigning coefficient vector back to features in scikit learn Lasso | <p>I am running a Lasso in scikit learn on a dataset. Here is how my design matrix(X) looks like: </p>
<pre><code> Year Country SW NY.GDP.DEFL.KD.ZG.1 NY.GDP.PCAP.KD.ZG NY.GDP.DEFL.KD.ZG NE.IMP.GNFS.ZS NY.GDP.DISC.CN FS.AST.PRVT.GD.ZS FS.AST.DOMS.GD.ZS NY.GDS.TOTL.ZS NY.GDP.DISC.KN NY.GDP.NGAS.RT.ZS... | <p>To relate the feature indices back to the original feature columns, you can use the <code>feature_indices_</code> attribute of <code>OneHotEncoder</code> after fitting:</p>
<pre><code>from sklearn import preprocessing
encoder = preprocessing.OneHotEncoder(categorical_features=[0,1,2])
X_train = encoder.fit_transfor... | python|numpy|pandas|scikit-learn | 1 |
377,161 | 29,882,965 | Python list to pandas dataframe | <p>I have a list that follows this format:</p>
<pre><code>a=['date name','10150425010245 name1','10150425020245 name2']
</code></pre>
<p>I am trying to convert this to Pandas df:</p>
<pre><code>newlist=[]
for item in a:
newlist.append(item.split(' '))
</code></pre>
<p>Now, convert this to df:</p>
<pre><code>pd... | <p>you were on the right track. With slight modification, your code works fine.</p>
<pre><code> import pandas as pd
a=['date name','10150425010245 name1','10150425020245 name2']
newlist=[]
for item in a:
newlist.append(item.split(' '))
newlist2=pd.DataFrame(newlist,columns=["date","name"])[... | python|pandas | 4 |
377,162 | 30,028,149 | how to select column values to display in pandas groupby | <p>I am using pandas 0.16.0, I have data:</p>
<pre><code>id A B
1 10 100
2 10 101
3 20 102
</code></pre>
<p>when I call</p>
<pre><code>df.groupby(['A']).groups
</code></pre>
<p>I have </p>
<pre><code>{10: [1 2], 20: [3]}
</code></pre>
<p>and I want to have this (values from column B)</p>
<pre><code>{10: [100... | <p>One way is to groupby and apply function to take list, and then convert to dict.</p>
<pre><code>In [92]: df.groupby(['A']).apply(lambda x: x['B'].tolist()).to_dict()
Out[92]: {10: [100, 101], 20: [102]}
</code></pre> | python|pandas|data-analysis | 2 |
377,163 | 30,037,186 | Splitting each item in an array into a separate data frame column | <p>I'm relatively new to python. I have a data frame and I need to split each character of the data in each column into it's own column in another data frame. I split the data into a dictionary, but just found that I need a new data frame. Here's the deal:</p>
<p>The source data frame looks like this:</p>
<pre><co... | <p>It's not the most elegant, but life is short, so I'd apply <code>list</code> to get the values and then <code>pd.Series</code> to expand them into columns:</p>
<pre><code>>>> df
Col1
1 100100
2 000000
3 020001
4 100300
>>> df.Col1.apply(list).apply(pd.Series).astype(int)
0 1 2 3 4 ... | python|pandas | 3 |
377,164 | 30,178,871 | How do I use numpy.genfromtxt to read a lower triagular matrix into a numpy array? | <p>I have a lower diagonal matrix like this</p>
<pre><code>1
2 3
4 5 6
</code></pre>
<p>in a text file, and I want to read it into a numpy array with zeros above the main diagonal. The simplest code I can think of</p>
<pre><code>import io
import scipy
data = "1\n2 3\n4 5 6"
scipy.genfromtxt(io.BytesIO(data.encode()... | <p><code>np.tril_indices_from()</code> makes it easy to populate your array lower-triagular matrix through fancy idexing:</p>
<pre><code>data = "1\n2 3\n4 5 6"
n = len(data.split('\n'))
data = data.replace('\n', ' ').split()
a = np.zeros((n, n))
a[np.tril_indices_from(a)] = data
print(a)
#array([[ 1., 0., 0.],
# ... | python|arrays|numpy|matrix | 2 |
377,165 | 29,836,477 | Pandas create new column with count from groupby | <p>I have a df that looks like the following:</p>
<pre><code>id item color
01 truck red
02 truck red
03 car black
04 truck blue
05 car black
</code></pre>
<p>I am trying to create a df that looks like this:</p>
<pre><code>item co... | <p>That's not a new column, that's a new DataFrame:</p>
<pre><code>In [11]: df.groupby(["item", "color"]).count()
Out[11]:
id
item color
car black 2
truck blue 1
red 2
</code></pre>
<p>To get the result you want is to use <code>reset_index</code>:</p>
<pre><code>In [12]: df.groupby(["i... | python|pandas | 125 |
377,166 | 30,053,329 | Elegant way to create empty pandas DataFrame with NaN of type float | <p>I want to create a Pandas DataFrame filled with NaNs. During my research I found <a href="https://stackoverflow.com/questions/13784192/creating-an-empty-pandas-dataframe-then-filling-it">an answer</a>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(index=range(0,4),columns=['A'])
</code></pre>
<p>This code ... | <p>Simply pass the desired value as first argument, like <code>0</code>, <code>math.inf</code> or, here, <code>np.nan</code>. The constructor then initializes and fills the value array to the size specified by arguments <code>index</code> and <code>columns</code>:</p>
<pre><code>>>> import numpy as np
>>... | python|pandas|numpy|dataframe|nan | 124 |
377,167 | 30,272,137 | groupby on sparse matrix in pandas: filling them first | <p>I have a pandas DataFrame <code>df</code> with shape (1000000,3) as follows:</p>
<pre><code>id cat team
1 'cat1' A
1 'cat2' A
2 'cat3' B
3 'cat1' A
4 'cat3' B
4 'cat1' B
</code></pre>
<p>Then I dummify with respect to the <code>cat</code> column in o... | <p>I think your problem is due to mixing of dtypes. But you could get around it like this. First, provide only the relevant column to <code>get_dummies()</code> rather than the whole dataframe:</p>
<pre><code>df2 = pd.get_dummies(df['cat']).to_sparse(0)
</code></pre>
<p>After that, you can add other variables back ... | pandas|fill|sparse-matrix | 1 |
377,168 | 30,206,293 | Matrix/Tensor Triple Product? | <p>An algorithm I'm working on requires computing, in a couple places, a type of matrix triple product.</p>
<p>The operation takes three square matrices with identical dimensions, and produces a 3-index tensor. Labeling the operands <code>A</code>, <code>B</code> and <code>C</code>, the <code>(i,j,k)</code>-th elemen... | <h2>Introduction and Solution Code</h2>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a>, is really hard to beat, <strong>but</strong> in rare cases, you can still beat it, if you can bring in <code>matrix-multiplication</code> into ... | matlab|numpy|matrix|matrix-multiplication|blas | 7 |
377,169 | 30,144,170 | What does pandas' sub operator do? | <p>This is coming straight from the tutorial, which I can't understand even after reading the doc.</p>
<pre><code>In [14]: df = DataFrame({'one' : Series(randn(3), index=['a', 'b', 'c']),
....: 'two' : Series(randn(4), index=['a', 'b', 'c', 'd']),
....: 'three' : Series(randn(3), ... | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sub.html#pandas.DataFrame.sub" rel="noreferrer"><code>sub</code></a> means subtract, so lets walk through this:</p>
<pre><code>In [44]:
# create some data
df = pd.DataFrame({'one' : pd.Series(np.random.randn(3), index=['a', 'b', 'c']),
... | python|pandas | 5 |
377,170 | 30,042,873 | how to rapidaly load data into memory with python? | <p>I have a large csv file (5 GB) and I can read it with <code>pandas.read_csv()</code>. This operation takes a lot of time 10-20 minutes. </p>
<p>How can I speed it up? </p>
<p>Would it be useful to transform the data in a <code>sqllite</code> format? In case what should I do?</p>
<p>EDIT: More information:
The dat... | <p>This actually depends on which part of reading it is taking 10 minutes.</p>
<ul>
<li>If it's actually reading from disk, then obviously any more compact form of the data will be better.</li>
<li>If it's processing the CSV format (you can tell this because your CPU is at near 100% on one core while reading; it'll be... | python|performance|pandas | 4 |
377,171 | 29,997,115 | python- pandas read_excel getting wrong numbers for index_col | <p>I'm trying to read a .xlsx file that has 4 sheets each with a Time and Absorbance column like below:</p>
<pre><code>Time Absorbance
0 0.1254
5 0.1278
10 0.128
15 0.1286
20 0.1303
25 0.1295
30 0.1296
35 0.1308
40 0.1301
45 0.1301
50 0.1309
...
</code></pre>
<p>I want to make a DataFrame with each sh... | <p>Note: that each sheet is read correctly, you're just not glueing them up right:</p>
<pre><code>In [11]: for sheet in e.sheet_names:
print(pd.read_excel("PTE_Kinetics_04-30-2015.xlsx", sheet, index_col='Time').head(3))
Absorbance
Time
0 0.1254
5 0.1278
10 0.1280
Absorb... | python|excel|pandas | 0 |
377,172 | 53,723,928 | AttributeError: 'Series' object has no attribute 'reshape' | <p>I'm using sci-kit learn linear regression algorithm.
While scaling Y target feature with:</p>
<pre><code>Ys = scaler.fit_transform(Y)
</code></pre>
<p>I got</p>
<blockquote>
<p>ValueError: Expected 2D array, got 1D array instead:</p>
</blockquote>
<p>After that I reshaped using:</p>
<pre><code>Ys = scaler.fi... | <p>Solution was linked on reshaped method on <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.Series.reshape.html#pandas.Series.reshape" rel="noreferrer">documentation page</a>.</p>
<p>Insted of <code>Y.reshape(-1,1)</code> you need to use:</p>
<pre><code>Y.values.reshape(-1,1)
</code></pr... | python|python-3.x|pandas|reshape|attributeerror | 137 |
377,173 | 53,745,233 | How to use the values in a column to identify which column to analyse in a different dataframe? | <p>I have two pandas dataframes, one with raw data, and the other is an analysis output based on data analysis of the first dataframe. The setup is below:</p>
<pre><code>df1
P1T P2T P3T
P N P
N P U
P P U
U U N
df2
Indicator Indicator State Occurrences
P1T P
P1T N
P1T U
P2T ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> and <a href="http://pand... | python|pandas|dataframe|analysis | 2 |
377,174 | 53,415,157 | Filtering outliers before using group by | <p>I have a dataframe with price column (p) and I have some undesired values like (0, 1.50, 92.80, 0.80). Before I calculate the mean of the price by product code, I would like to remove these outliers</p>
<pre><code> Code Year Month Day Q P
0 100 2017 1 4 2.0 ... | <p>IIUC You can use a groupby on <code>Code</code>, do your <code>z</code> score calculation on <code>P</code>, and filter if the <code>z</code> score is greater than your threshold:</p>
<pre><code>stds = 1.0
filtered_ df = df[~df.groupby('Code')['P'].transform(lambda x: abs((x-x.mean()) / x.std()) > stds)]
C... | python|pandas|numpy | 2 |
377,175 | 53,473,188 | Why is Python Pandas loc not returning a single item? | <p>For an assignment I need to access entries in a CSV file by the column name and index.</p>
<p>I am using a for loop to get each index. Contrary to my expectations,</p>
<pre><code>read.loc[[i], ["magType"]]
</code></pre>
<p>returns something like
<a href="https://i.stack.imgur.com/Unxiq.png" rel="nofollow noreferr... | <p><code>read.loc[0, "magType"]</code> returns the element at <code>0</code>-th row and <code>magType</code> column - presumably the result you desire.</p>
<p><code>read.loc[[0], ["magType"]]</code>, on the other hand, returns a <em>slice</em> of the DataFrame, with columns from <code>["magType"]</code>, with all the ... | python|pandas | 1 |
377,176 | 53,454,043 | Python: How to tokenize every type of URL paths? | <p>I have a dataframe of website urls and I need to first extract url domains (e.g. google.com) and url paths (e.g. foo/foo2/foo3/sjj.html), and second to tokenize the path part of the urls. The problem is that they can be in any of the following forms:</p>
<pre><code>1- https://www.politics.com/watch?v=4PykB_cU
(des... | <p>First three can be accomplished with string.split()</p>
<p>Fifth you can split in the capital letter with regex or just iterating through.</p>
<p>Fourth one will require much more effort. The only method I can think of is entity recognition with the entire English dictionary as entities to match, and even then you... | python-3.x|pandas|nltk | 1 |
377,177 | 53,501,449 | Numerically append binary numbers in np.array | <p>Considering the following example array :</p>
<pre><code>a = np.array([0,1,1,0,1,1,1,0,1,0])
</code></pre>
<p>Which could be of any dtype (int, float...) </p>
<p>How would I get the following output without using nasty loops and string casts ?</p>
<pre><code>np.array([0b01,0b10,0b11,0b10,0b10])
</code></pre> | <pre><code>a = a.astype(int)
output = a[0::2] * 2 + a[1::2]
</code></pre>
<p>Gives the array you've described (though it doesn't print in binary).</p> | python|numpy | 1 |
377,178 | 53,685,733 | How to identify column value change in pandas python | <p>I have a pandas DataFrame as below that have data for strike_price and value. </p>
<pre><code> date time int_sp value
1 20180903 09:16 11700 283.90
315 20180903 14:31 11700 273.85
316 20180903 14:32 11700 274.05
317 20180903 14:33 11600 ... | <p>IIUC, use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.diff.html" rel="nofollow noreferrer"><code>diff</code></a> to get sell info</p>
<pre><code>ndf = df.loc[df['int_sp'].diff().ne(0)].add_prefix('sell_').reset_index().copy()
</code></pre>
<p>Now, use mask</p>
<pre><code>mask ... | python|pandas | 1 |
377,179 | 53,789,715 | Transform pandas DataFrame from wide to long and count occurences of a unique value | <p>Hello dear community i have a pretty specific problem that i sadly can not work my mind around. The DataFrame I want to transform currently looks like this.</p>
<pre><code>df_larceny
CATEGORY INCIDENTYEAR INCIDENTMONTH
LARCENY 2009 1
LARCENY 2009 1
LARCENY 2009 ... | <p>Maybe something like this:</p>
<pre><code>df_larceny[df_larceny['CATEGORY'] == 'LARCENY'].groupby(['INCIDENTYEAR', 'INCIDENTMONTH']).count().reset_index()
</code></pre> | python|pandas|dataframe|format|transform | 2 |
377,180 | 53,662,651 | Unable to fill missing hours with appropriate values in pandas dataframe | <p>I have a dataset which is basically a list of list</p>
<pre><code>data = [[(datetime.datetime(2018, 12, 6, 10, 0), Decimal('7.0000000000000000')), (datetime.datetime(2018, 12, 6, 11, 0), Decimal('2.0000000000000000')), (datetime.datetime(2018, 12, 6, 12, 0), Decimal('43.6666666666666667')), (datetime.datetime(2018,... | <p>Try:</p>
<pre><code>df.resample('H').interpolate()
</code></pre>
<p>Output:</p>
<pre><code> 1_x 1_y
0
2018-12-06 10:00:00 7.000000 28.50
2018-12-06 11:00:00 2.000000 12.75
2018-12-06 12:00:00 43.666667 12.15
2018-12-06 13:00:00 25.833333 12... | python|pandas | 1 |
377,181 | 53,674,690 | Creating a Y_true Dataset in Keras | <p>Here's my current call to model.fit in Keras </p>
<pre><code>history_callback = model.fit(x_train/255.,
validation_train_data,
validation_split=validation_split,
batch_size=batch_size,
callbacks=callb... | <p>I managed to solve my problem by writing a generator function which generated a batch of x and y data as lists and put them together as a tuple. I then called fit_generator with the argument where generator = my_generator and it worked just fine. If you have odd input data then you should consider writing a generato... | python|tensorflow|keras | 0 |
377,182 | 53,533,907 | Delete values in rows based on value in column and then split cell in multiple rows in Pandas | <p>When System appears in column "Type" I want to delete all values from that row, except the value from the column "Name". When Hardware appears in column "Type" I want to delete all values from that row except the value from column "Color".
After that, I want to split all cells from the column "Text" which are not em... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>mask</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow noreferrer"><code>difference</code></a> in preprocessi... | python|pandas|dataframe|split|cell | 1 |
377,183 | 53,751,882 | Pytorch modify dataset label | <p>This is a code snippet for loading images as dataset from <a href="https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html" rel="nofollow noreferrer">pytorch transfer learning tutorial</a>:</p>
<pre><code>data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),... | <p>Yes, though not (easily) programmatically. The labels are coming from <a href="https://pytorch.org/docs/stable/torchvision/datasets.html#imagefolder" rel="nofollow noreferrer">torchvision.datasets.ImageFolder</a> and reflect the directory structure of your dataset (as seen on your HDD). Firstly, I suspect you may wa... | python|deep-learning|pytorch|transfer-learning | 1 |
377,184 | 53,607,181 | Run multiple Keras models in sequence | <p>I am running 3 keras cnn models in sequence on all images in a folder. After completing prediction of all three models on 1 image, I am getting below error in next iteration of the loop. </p>
<pre><code> File "/home/ubuntu/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1078, in _run... | <p>Adding tf.Session().as_default() resolved the issue: </p>
<pre><code>def model_1():
K.clear_session()
cnn_model = load_model(model_path, compile=False)
tf.Session().as_default()
with K.get_session().as_default() as sess:
...Do inference....
</code></pre>
<p>Adding answer that worked for... | python|tensorflow|keras | 1 |
377,185 | 53,726,915 | How to use RandomState with Sklearn RandomizedSearchCV on multiple cores | <p>I am puzzled about the right way to use <code>np.random.RandomState</code> with <code>sklearn.model_selection.RandomizedSearchCV</code> when running on multiple cores. </p>
<p>I use <code>RandomState</code> to generate pseudo-random numbers so that my results are reproducible. I give <code>RandomizedSearchCV</code>... | <p>The parameter candidates are generated before passing to the multi-threaded functionality using a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.ParameterSampler.html" rel="nofollow noreferrer">ParameterSampler object</a>. So only a single <code>random_state</code> is enough for r... | python|numpy|scikit-learn|scipy|numpy-random | 3 |
377,186 | 53,613,722 | Loss function for simple Reinforcement Learning algorithm | <p>This question comes from watching the following video on TensorFlow and Reinforcement Learning from Google I/O 18: <a href="https://www.youtube.com/watch?v=t1A3NTttvBA" rel="nofollow noreferrer">https://www.youtube.com/watch?v=t1A3NTttvBA</a></p>
<p>Here they train a very simple RL algorithm to play the game of Pon... | <p>Great question Corey. I am also wondering exactly what this popular loss function in RL actually means. I've seen many implementations of it, but many contradict each other. For my understanding, it means this:</p>
<p>Loss = - log(pi) * A</p>
<p>Where A is the advantage compared to a baseline case. In Google's... | python|tensorflow|reinforcement-learning | 3 |
377,187 | 53,444,173 | Replace zeros with last value different from zero | <p>I have the following dataframe:</p>
<pre><code>print(inventory_df)
dt_op Prod_1 Prod_2 Prod_n
1 10/09/18 5 50 2
2 11/09/18 4 0 0
3 12/09/18 2 0 0
4 13/09/18 0 0 0
5 14/09/18 4 30 1
</code></pre>
<p>I would like t... | <p>Idea is replace <code>0</code> to NaNs by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>mask</code></a> and then forward filling them by previous non missing values:</p>
<pre><code>cols = df.columns.difference(['dt_op'])
df[cols] = df[cols... | python|pandas | 5 |
377,188 | 53,520,576 | Is it possible to feed dynamic shape matrix in Tensorflow? | <p>I have data set with unstatic shape like <code>(batch_size, None, None, None, 92)</code></p>
<pre><code>for x in x_data:
print(x.shape)
(4, 4, 8, 92)
(3, 3, 7, 92)
(4, 4, 8, 92)
(3, 3, 7, 92)
(4, 4, 8, 92)
(4, 4, 7, 92)
(3, 3, 7, 92)
(4, 4, 8, 92)
(4, 4, 8, 92)
(3, 3, 8, 92)
</code></pre>
<p>But when I try to ... | <p>It won't work for the data which you provide, but there are some options how to deal with that.</p>
<p><strong>Why it doesn't work</strong></p>
<p>The line</p>
<pre><code> x = tf.placeholder(tf.float32, [None, None, None, 92])
</code></pre>
<p>means that the shape of the input array is not known beforehand. But ... | python|tensorflow|deep-learning | 2 |
377,189 | 53,664,902 | Parsing from Excel multisheet file: List comprehension between columns | <p>I am trying to parse an excel file that has many sheets. Each sheet has a column that has information as follows (3 sheets=3 columns):</p>
<pre><code>ReceivedEmail OpenedEmail ClickedURL
aaaa@aaa.com gggg@aaa.com aaaa@aaa.com
bbbb@aaa.com dddd@aaa.com rrrr@aaa.com
cccc@aaa.com rrrr@aaa.com
dd... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow noreferrer"><code>read_excel</code></a> with parameter <code>sheetname=None</code> for return all sheets to ordered dictionary of DataFrames:</p>
<p><em>Notice:</em></p>
<p><em>Each sheet have one colum... | python|excel|pandas|parsing|list-comprehension | 1 |
377,190 | 53,663,293 | How to change the tensor shape in middle layers? | <p>Saying I have a 2000x100 matrix, I put it into 10 dimension embedding layer, which gives me 2000x100x10 tensor. so it's 2000 examples and each example has a 100x10 matrix. and then, I pass it to a conv1d and KMaxpolling to get 2000x24 matrix, which is 2000 examples and each example has a 24 dimension vector. and now... | <p>The idea of using "samples" is that these samples should be unique and not relate to each other. </p>
<p>This is something Keras will demand from your model: if it started with 2000 samples, it must end with 2000 samples. Ideally, these samples do not talk to each other, but you can use custom layers to hack this, ... | tensorflow|keras|nlp|embedding|word-embedding | 0 |
377,191 | 53,494,667 | Can traing deep learning model using Intel Xeon CPU in tensorflow , solving short of gpu memory | <p>NVidia GPU has 16GB memory at most, which limits large model training. Model parallism may needs modification of deep learning framework. Is it feasible to train tensorflow models using Intel multi-core CPUs? Could you give some advice about the hardware configuration and the performance?</p> | <p>You can try using Intel AI Devcloud which is cloud hosted hardware and software platform available to developers, researchers and startups to learn and get started on their Artificial Intelligence projects. It has Intel® Xeon® Scalable Processors and each processor has 24 cores with 2-way hyper-threading. Each proce... | tensorflow|cpu | 1 |
377,192 | 53,597,813 | Groupby pandas in different sections | <p>I have a serialized dataset that has its content separated by spaces, like this <code>#a value1 #b value2 ....</code> where the first element with # is the column name and second is the value. My problem occurs in some sections of this dataset that has a sequence like this "#% value1 #% value2" this especific mark ... | <p>First create the help key by using <code>shift</code> and <code>cumsum</code> , then it become the regular <code>groupby</code> and <code>join</code> problem </p>
<pre><code>s=(df.Key!=df.Key.shift()).cumsum()
df.groupby([df.Key,s]).value.apply(','.join).\
sort_index(level=1).\
reset_index(level=1,drop=... | python|pandas|pandas-groupby | 4 |
377,193 | 53,496,913 | Import error tensorflow-gpu in ubuntu18.04 | <p>I'm getting some error while importing tensorflow.</p>
<p>My computer's Specifications:</p>
<p>OS:ubuntu 18.04</p>
<p>Nvidia RTX 2080 Ti*2 </p>
<p>Nvidia driver-415</p>
<p>CUDA:10.0</p>
<p>cuDNN:7.3.0
tensorflow:1.11.0</p>
<pre><code>import tensorflow
</code></pre>
<p>Error:</p>
<blockquote>
<p>Traceback ... | <p>The <code>tensorflow-gpu</code> package is built against Cuda 9.0, but you have Cuda 10.0 installed. </p>
<p>You need either to downgrade your version of Cuda to 9.0 (but if I recall, that's not possible with a 2080Ti), or build tensorflow from the sources. There is extensive documentation on how to do so on the <a... | python|tensorflow|nvidia|ubuntu-18.04 | 1 |
377,194 | 53,553,444 | Determining a cell value based on previous/next cell value(s) | <p>This is a follow-up from a previous post of mine: <a href="https://stackoverflow.com/questions/53539078/change-multiple-cell-values-based-on-other-cell-values/53539132?noredirect=1#comment93950476_53539132">Change multiple cell values based on other cell value(s)</a></p>
<p>this is what a normal cycle of an object ... | <p>If I understand what you mainly ask, it's "how do I assign a value based on the value of previous row." The way I Would do this is to simply shift the filtering condition by one row. I won't give the solution for all the options, but you can just expand the filtering condition appropriately. </p>
<p>this line of co... | python|pandas|dataframe | 1 |
377,195 | 53,513,032 | Pandas groupby and apply - getting a new DataFrame over the groupby variable | <p>I'm trying to use <code>pandas.DataFrame.groupby['x']</code> in order to make calculation on the grouped <code>df</code>, by <code>x</code>.</p>
<p>Problem arise when <code>'x'</code> repeats more then once. apply function will do the calculations as many times as <code>'x'</code> repeats, though I only need the 'a... | <p>One idea is return <code>Series</code> from custom function, so <code>drop_duplicates</code> is not necessary:</p>
<pre><code>def simulate_complicated_func(df):
# This function simulates complicate calculations
returned_col_names = ['calc1', 'calc2', 'calc3']
a = ''.join(df['var1'])
b = df['var2'].... | python|pandas | 2 |
377,196 | 53,680,401 | Combining date and time (timestamp) in a list of dataframes | <p>I wish to combine date and time into one timestamp on a list of dataframes and to designate a week to the call date. </p>
<p>Here is the error :
ValueError: could not convert string to Timestamp </p>
<p>I have used the following function :</p>
<pre><code>def new_call_time(df):
i=0
df[' CALL_DATE_MAN... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> with indexing <code>str[0]</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><co... | python|pandas|timestamp|unix-timestamp|valueerror | 1 |
377,197 | 53,530,132 | Convert pandas datetime to hours from start | <p>I have a dataframe with the following datatime index:</p>
<pre><code>DatetimeIndex(['2018-10-17 00:00:00', '2018-10-17 01:00:00',
'2018-10-17 02:00:00', '2018-10-17 03:00:00',
'2018-10-17 04:00:00', '2018-10-17 05:00:00',
'2018-10-17 06:00:00', '2018-10-17 07:00:00',
... | <p>You can subtract the the first datetime from all values in your index, then divide by <code>numpy.timedelta(1,'h')</code> (timedelta of 1 hour):</p>
<pre><code>(df.index - df.index[0]) / np.timedelta64(1,'h')
Float64Index([ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0,
8.0, 9.0,... | python|pandas|datetime|indexing | 2 |
377,198 | 53,361,618 | How to Upsample Pandas DataFrame using Timestamp | <p>I have a DataFrame like this (don't care about NaN values):</p>
<p><a href="https://i.stack.imgur.com/FHgOZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FHgOZ.png" alt="enter image description here"></a></p>
<p>And I would like to upsample it each 20 milliseconds.</p>
<p>What I did is:</p>
... | <p>First set first level of <code>MultiIndex</code> to columns for remove broken one level <code>MultiIndex</code>.</p>
<p>Add parameter <code>errors='coerce'</code> for convert non parseable values to <code>NaT</code> if necessary, also is possible first converting column, then create <code>DatetimeIndex</code> and l... | python|pandas|resampling | 3 |
377,199 | 53,565,437 | MLWIC: Machine Learning for Wildlife Image Classification in R Issues with Python | <p>I am a wildlife PhD researcher manually identifying ~1.5 million game camera photos by species. A machine learning package in R has recently come out of a research project and I've been trying to get the script to run in R for about 12 hours and can't seem to get it right (I have used R and python a lot, but I am no... | <p>If I am not mistaken there is a small bug in their code that ignores the "data_info" path. Try renaming your "image_labels.csv" to "data_info.csv" and put the file inside the model_dir. This solved the problem for me. Also, use "C:/ProgramData/Anaconda3/" instead of "C:/ProgramData/Anaconda3/python.exe"</p> | python|r|tensorflow|github|anaconda | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.