category
stringclasses
107 values
title
stringlengths
15
179
question_link
stringlengths
59
147
question_body
stringlengths
53
33.8k
answer_html
stringlengths
0
28.8k
__index_level_0__
int64
0
1.58k
pandas
How to avoid pandas creating an index in a saved csv
https://stackoverflow.com/questions/20845213/how-to-avoid-pandas-creating-an-index-in-a-saved-csv
<p>I am trying to save a csv to a folder after making some edits to the file. </p> <p>Every time I use <code>pd.to_csv('C:/Path of file.csv')</code> the csv file has a separate column of indexes. I want to avoid printing the index to csv.</p> <p>I tried: </p> <pre><code>pd.read_csv('C:/Path to file to edit.csv', ind...
<p>Use <code>index=False</code>.</p> <pre><code>df.to_csv('your.csv', index=False) </code></pre>
634
pandas
Difference between map, applymap and apply methods in Pandas
https://stackoverflow.com/questions/19798153/difference-between-map-applymap-and-apply-methods-in-pandas
<p>Can you tell me when to use these vectorization methods with basic examples? </p> <p>I see that <code>map</code> is a <code>Series</code> method whereas the rest are <code>DataFrame</code> methods. I got confused about <code>apply</code> and <code>applymap</code> methods though. Why do we have two methods for apply...
<h2>Comparing <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="noreferrer"><code>map</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.applymap.html" rel="noreferrer"><code>applymap</code></a> and <a href="https://pandas.pydata.org/pandas-...
635
pandas
Get statistics for each group (such as count, mean, etc) using pandas GroupBy?
https://stackoverflow.com/questions/19384532/get-statistics-for-each-group-such-as-count-mean-etc-using-pandas-groupby
<p>I have a dataframe <code>df</code> and I use several columns from it to <code>groupby</code>:</p> <pre class="lang-py prettyprint-override"><code>df['col1','col2','col3','col4'].groupby(['col1','col2']).mean() </code></pre> <p>In the above way, I almost get the table (dataframe) that I need. What is missing is an ad...
<p>On <code>groupby</code> object, the <code>agg</code> function can take a list to <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#applying-multiple-functions-at-once" rel="noreferrer">apply several aggregation methods</a> at once. This should give you the result you need:</p> <pre><code...
636
pandas
How to check if any value is NaN in a Pandas DataFrame
https://stackoverflow.com/questions/29530232/how-to-check-if-any-value-is-nan-in-a-pandas-dataframe
<p>How do I check whether a pandas DataFrame has NaN values?</p> <p>I know about <code>pd.isnan</code> but it returns a DataFrame of booleans. I also found <a href="https://stackoverflow.com/questions/27754891/python-nan-value-in-pandas">this post</a> but it doesn't exactly answer my question either.</p>
<p><a href="https://stackoverflow.com/users/1567452/jwilner">jwilner</a>'s response is spot on. I was exploring to see if there's a faster option, since in my experience, summing flat arrays is (strangely) faster than counting. This code seems faster:</p> <pre class="lang-py prettyprint-override"><code>df.isnull().valu...
637
pandas
Set value for particular cell in pandas DataFrame using index
https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index
<p>I have created a Pandas DataFrame</p> <pre class="lang-py prettyprint-override"><code>df = DataFrame(index=['A','B','C'], columns=['x','y']) </code></pre> <p>Now, I would like to assign a value to particular cell, for example to row <code>C</code> and column <code>x</code>. In other words, I would like to perform th...
<p><a href="https://stackoverflow.com/a/24517695/190597">RukTech's answer</a>, <code>df.set_value('C', 'x', 10)</code>, is far and away faster than the options I've suggested below. However, it has been <a href="https://github.com/pandas-dev/pandas/issues/15269" rel="noreferrer"><strong>slated for deprecation</strong><...
638
pandas
Import multiple CSV files into pandas and concatenate into one DataFrame
https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe
<p>I would like to read several CSV files from a directory into pandas and concatenate them into one big DataFrame. I have not been able to figure it out though. Here is what I have so far:</p> <pre><code>import glob import pandas as pd # Get data file names path = r'C:\DRO\DCL_rawdata_files' filenames = glob.glob(pat...
<p>See <a href="https://pandas.pydata.org/docs/user_guide/io.html" rel="noreferrer">pandas: IO tools</a> for all of the available <code>.read_</code> methods.</p> <p>Try the following code if all of the CSV files have the same columns.</p> <p>I have added <code>header=0</code>, so that after reading the CSV file's firs...
639
pandas
How to apply a function to two columns of Pandas dataframe
https://stackoverflow.com/questions/13331698/how-to-apply-a-function-to-two-columns-of-pandas-dataframe
<p>Suppose I have a function and a dataframe defined as below:</p> <pre class="lang-py prettyprint-override"><code>def get_sublist(sta, end): return mylist[sta:end+1] df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]}) mylist = ['a','b','c','d','e','f'] </code></pre> <p>Now I want to apply <...
<p>There is a clean, one-line way of doing this in Pandas:</p> <pre><code>df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1) </code></pre> <p>This allows <code>f</code> to be a user-defined function with multiple input values, and uses (safe) column names rather than (unsafe) numeric indices to access the ...
640
pandas
How can I get a value from a cell of a dataframe?
https://stackoverflow.com/questions/16729574/how-can-i-get-a-value-from-a-cell-of-a-dataframe
<p>I have constructed a condition that extracts exactly one row from my dataframe:</p> <pre class="lang-py prettyprint-override"><code>d2 = df[(df['l_ext']==l_ext) &amp; (df['item']==item) &amp; (df['wn']==wn) &amp; (df['wd']==1)] </code></pre> <p>Now I would like to take a value from a particular column:</p> <pre clas...
<p>If you have a DataFrame with only one row, then access the first (only) row as a Series using <em><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="noreferrer">iloc</a></em>, and then the value using the column name:</p> <pre><code>In [3]: sub_df Out[3]: A...
641
pandas
What does `ValueError: cannot reindex from a duplicate axis` mean?
https://stackoverflow.com/questions/27236275/what-does-valueerror-cannot-reindex-from-a-duplicate-axis-mean
<p>I am getting a <code>ValueError: cannot reindex from a duplicate axis</code> when I am trying to set an index to a certain value. I tried to reproduce this with a simple example, but I could not do it.</p> <p>Here is my session inside of <code>ipdb</code> trace. I have a DataFrame with string index, and integer col...
<p>This error usually rises when you join / assign to a column when the index has duplicate values. Since you are assigning to a row, I suspect that there is a duplicate value in <code>affinity_matrix.columns</code>, perhaps not shown in your question.</p>
642
pandas
Filter dataframe rows if value in column is in a set list of values
https://stackoverflow.com/questions/12065885/filter-dataframe-rows-if-value-in-column-is-in-a-set-list-of-values
<p>I have a Python pandas DataFrame <code>rpt</code>:</p> <pre><code>rpt &lt;class 'pandas.core.frame.DataFrame'&gt; MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231') Data columns: STK_ID 47518 non-null values STK_Name 47518 non-null values RPT_Date ...
<p>Use the <code>isin</code> method: </p> <p><code>rpt[rpt['STK_ID'].isin(stk_list)]</code></p>
643
pandas
UnicodeDecodeError when reading CSV file in Pandas
https://stackoverflow.com/questions/18171739/unicodedecodeerror-when-reading-csv-file-in-pandas
<p>I'm running a program which is processing 30,000 similar files. A random number of them are stopping and producing this error...</p> <pre class="lang-none prettyprint-override"><code> File &quot;C:\Importer\src\dfman\importer.py&quot;, line 26, in import_chr data = pd.read_csv(filepath, names=fields) File &qu...
<p><code>read_csv</code> takes an <code>encoding</code> option to deal with files in different formats. I mostly use <code>read_csv('file', encoding = &quot;ISO-8859-1&quot;)</code>, or alternatively <code>encoding = &quot;utf-8&quot;</code> for reading, and generally <code>utf-8</code> for <code>to_csv</code>.</p> <p>...
644
pandas
Convert Pandas dataframe to NumPy array
https://stackoverflow.com/questions/13187778/convert-pandas-dataframe-to-numpy-array
<p>How do I convert a Pandas dataframe into a NumPy array?</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame( { 'A': [np.nan, np.nan, np.nan, 0.1, 0.1, 0.1, 0.1], 'B': [0.2, np.nan, 0.2, 0.2, 0.2, np.nan, np.nan], 'C': [np.nan, 0.5,...
<h1>Use <code>df.to_numpy()</code></h1> <p>It's better than <code>df.values</code>, here's why.<sup>*</sup></p> <p>It's time to deprecate your usage of <code>values</code> and <code>as_matrix()</code>.</p> <p>pandas v0.24.0 introduced two new methods for obtaining NumPy arrays from pandas objects:</p> <ol> <li><strong>...
645
pandas
How do I check if a pandas DataFrame is empty?
https://stackoverflow.com/questions/19828822/how-do-i-check-if-a-pandas-dataframe-is-empty
<p>How do I check if a pandas <code>DataFrame</code> is empty? I'd like to print some message in the terminal if the <code>DataFrame</code> is empty.</p>
<p>You can use the attribute <code>df.empty</code> to check whether it's empty or not:</p> <pre><code>if df.empty: print('DataFrame is empty!') </code></pre> <p>Source: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.empty.html" rel="noreferrer">Pandas Documentation</a></p>
646
pandas
How to sort pandas dataframe by one column
https://stackoverflow.com/questions/37787698/how-to-sort-pandas-dataframe-by-one-column
<p>I have a dataframe like this:</p> <pre class="lang-none prettyprint-override"><code> 0 1 2 0 354.7 April 4.0 1 55.4 August 8.0 2 176.5 December 12.0 3 95.5 February 2.0 4 85.6 January 1.0 5 152 July 7.0 6 238.7 June 6.0 7 104.8 Ma...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="noreferrer"><code>sort_values</code></a> to sort the df by a specific column's values:</p> <pre><code>In [18]: df.sort_values('2') Out[18]: 0 1 2 4 85.6 January 1.0 3 95.5 ...
647
pandas
Converting a Pandas GroupBy multiindex output from Series back to DataFrame
https://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-multiindex-output-from-series-back-to-dataframe
<p>I have a dataframe:</p> <pre class="lang-none prettyprint-override"><code> City Name 0 Seattle Alice 1 Seattle Bob 2 Portland Mallory 3 Seattle Mallory 4 Seattle Bob 5 Portland Mallory </code></pre> <p>I perform the following grouping:</p> <pre class="lang-py prettyprint-override"><co...
<p><code>g1</code> here <em>is</em> a DataFrame. It has a hierarchical index, though:</p> <pre><code>In [19]: type(g1) Out[19]: pandas.core.frame.DataFrame In [20]: g1.index Out[20]: MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'), ('Mallory', 'Seattle')], dtype=object) </code></...
648
pandas
Pandas: Get first row value of a given column
https://stackoverflow.com/questions/25254016/pandas-get-first-row-value-of-a-given-column
<p>This seems like a ridiculously easy question... but I'm not seeing the easy answer I was expecting.</p> <p>So, how do I get the value at an nth row of a given column in Pandas? (I am particularly interested in the first row, but would be interested in a more general practice as well).</p> <p>For example, let's say I...
<p>To select the <code>ith</code> row, <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing-loc-iloc-and-ix" rel="noreferrer">use <code>iloc</code></a>:</p> <pre><code>In [31]: df_test.iloc[0] Out[31]: ATime 1.2 X 2.0 Y 15.0 Z 2.0 Btime 1.2 C...
649
pandas
How to replace NaN values in a dataframe column
https://stackoverflow.com/questions/13295735/how-to-replace-nan-values-in-a-dataframe-column
<p>I have a Pandas Dataframe as below:</p> <pre class="lang-none prettyprint-override"><code> itm Date Amount 67 420 2012-09-30 00:00:00 65211 68 421 2012-09-09 00:00:00 29424 69 421 2012-09-16 00:00:00 29877 70 421 2012-09-23 00:00:00 30990 71 421 2012-09-30 00:00:00 613...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="noreferrer"><code>DataFrame.fillna()</code></a> or <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="noreferrer"><code>Series.fillna()</code></a> will do this for y...
650
pandas
Convert Python dict into a dataframe
https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe
<p>I have a Python dictionary:</p> <pre class="lang-py prettyprint-override"><code>{u'2012-07-01': 391, u'2012-07-02': 392, u'2012-07-03': 392, u'2012-07-04': 392, u'2012-07-05': 392, u'2012-07-06': 392} </code></pre> <p>I would like to convert this into a pandas dataframe by having the dates and their correspondi...
<p>The error here, is since calling the DataFrame constructor with scalar values (where it expects values to be a list/dict/... i.e. have multiple columns):</p> <pre><code>pd.DataFrame(d) ValueError: If using all scalar values, you must must pass an index </code></pre> <p>You could take the items from the dictionary (i...
651
pandas
How to check if a column exists in Pandas
https://stackoverflow.com/questions/24870306/how-to-check-if-a-column-exists-in-pandas
<p>How do I check if a column exists in a Pandas DataFrame <code>df</code>?</p> <pre class="lang-none prettyprint-override"><code> A B C 0 3 40 100 1 6 30 200 </code></pre> <p>How would I check if the column <code>&quot;A&quot;</code> exists in the above DataFrame so that I can compute:</p> <pre class="lan...
<p>This will work:</p> <pre><code>if 'A' in df: </code></pre> <p>But for clarity, I'd probably write it as:</p> <pre><code>if 'A' in df.columns: </code></pre>
652
pandas
Selecting/excluding sets of columns in pandas
https://stackoverflow.com/questions/14940743/selecting-excluding-sets-of-columns-in-pandas
<p>I would like to create views or dataframes from an existing dataframe based on column selections.</p> <p>For example, I would like to create a dataframe <code>df2</code> from a dataframe <code>df1</code> that holds all columns from it except two of them. I tried doing the following, but it didn't work:</p> <pre><c...
<p>You can either Drop the columns you do not need OR Select the ones you need</p> <pre><code># Using DataFrame.drop df.drop(df.columns[[1, 2]], axis=1, inplace=True) # drop by Name df1 = df1.drop(['B', 'C'], axis=1) # Select the ones you want df1 = df[['a','d']] </code></pre>
653
pandas
Sorting columns in pandas dataframe based on column name
https://stackoverflow.com/questions/11067027/sorting-columns-in-pandas-dataframe-based-on-column-name
<p>I have a <code>dataframe</code> with over 200 columns. The issue is as they were generated the order is</p> <pre><code>['Q1.3','Q6.1','Q1.2','Q1.1',......] </code></pre> <p>I need to <em>sort</em> the columns as follows:</p> <pre><code>['Q1.1','Q1.2','Q1.3',.....'Q6.1',......] </code></pre> <p>Is there some way for ...
<pre><code>df = df.reindex(sorted(df.columns), axis=1) </code></pre> <p>This assumes that sorting the column names will give the order you want. If your column names won't sort lexicographically (e.g., if you want column Q10.3 to appear after Q9.1), you'll need to sort differently, but that has nothing to do with pan...
654
pandas
How to reset index in a pandas dataframe?
https://stackoverflow.com/questions/20490274/how-to-reset-index-in-a-pandas-dataframe
<p>I have a dataframe from which I remove some rows. As a result, I get a dataframe in which index is something like <code>[1,5,6,10,11]</code> and I would like to reset it to <code>[0,1,2,3,4]</code>. How can I do it?</p> <hr /> <p>The following seems to work:</p> <pre class="lang-py prettyprint-override"><code>df = d...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>DataFrame.reset_index</code></a> is what you're looking for. If you don't want it saved as a column, then do:</p> <pre><code>df = df.reset_index(drop=True) </code></pre> <p>If you don't want ...
655
pandas
Create new column based on values from other columns / apply a function of multiple columns, row-wise in Pandas
https://stackoverflow.com/questions/26886653/create-new-column-based-on-values-from-other-columns-apply-a-function-of-multi
<p>I want to apply my custom function (it uses an if-else ladder) to these six columns (<code>ERI_Hispanic</code>, <code>ERI_AmerInd_AKNatv</code>, <code>ERI_Asian</code>, <code>ERI_Black_Afr.Amer</code>, <code>ERI_HI_PacIsl</code>, <code>ERI_White</code>) in each row of my dataframe.</p> <p>I've tried different method...
<p>OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:</p> <pre><code>def label_race(row): if row['eri_hispanic'] == 1: return 'Hispanic' if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_n...
656
pandas
How can I display full (non-truncated) dataframe information in HTML when converting from Pandas dataframe to HTML?
https://stackoverflow.com/questions/25351968/how-can-i-display-full-non-truncated-dataframe-information-in-html-when-conver
<p>I converted a Pandas dataframe to an HTML output using the <code>DataFrame.to_html</code> function. When I save this to a separate HTML file, the file shows truncated output.</p> <p>For example, in my TEXT column,</p> <p><code>df.head(1)</code> will show</p> <p><em>The film was an excellent effort...</em></p> <p>ins...
<p>Set the <code>display.max_colwidth</code> option to <code>None</code> (or <code>-1</code> before version 1.0):</p> <pre><code>pd.set_option('display.max_colwidth', None) </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html#pandas-set-option" rel="noreferrer"><code>se...
657
pandas
How to flatten a hierarchical index in columns
https://stackoverflow.com/questions/14507794/how-to-flatten-a-hierarchical-index-in-columns
<p>I have a data frame with a hierarchical index in axis 1 (columns) (from a <code>groupby.agg</code> operation):</p> <pre><code> USAF WBAN year month day s_PC s_CL s_CD s_CNT tempf sum sum sum sum amax amin 0 702730 26451 1993 1 1 1 ...
<p>I think the easiest way to do this would be to set the columns to the top level:</p> <pre><code>df.columns = df.columns.get_level_values(0) </code></pre> <p><em>Note: if the to level has a name you can also access it by this, rather than 0.</em></p> <p>.</p> <p>If you want to combine/<a href="http://docs.python....
658
pandas
How can I pivot a dataframe?
https://stackoverflow.com/questions/47152691/how-can-i-pivot-a-dataframe
<p><strong>How do I pivot the pandas dataframe <code>df</code> defined at bottom such that the <code>col</code> values become columns, <code>row</code> values become the index, and mean of <code>val0</code> becomes the values?</strong> (in some cases this is called transforming from long-format to wide-format)</p> <p>(...
<p>Here is a list of idioms we can use to pivot</p> <ol> <li><p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="noreferrer"><code>pd.DataFrame.pivot_table</code></a></p> <ul> <li>A glorified version of <code>groupby</code> with more intuitive API. For many pe...
659
pandas
How do I create test and train samples from one dataframe with pandas?
https://stackoverflow.com/questions/24147278/how-do-i-create-test-and-train-samples-from-one-dataframe-with-pandas
<p>I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing.</p> <p>Thanks!</p>
<p>I would just use numpy's <code>randn</code>:</p> <pre><code>In [11]: df = pd.DataFrame(np.random.randn(100, 2)) In [12]: msk = np.random.rand(len(df)) &lt; 0.8 In [13]: train = df[msk] In [14]: test = df[~msk] </code></pre> <p>And just to see this has worked:</p> <pre><code>In [15]: len(test) Out[15]: 21 In [...
660
pandas
Python Pandas: Get index of rows where column matches certain value
https://stackoverflow.com/questions/21800169/python-pandas-get-index-of-rows-where-column-matches-certain-value
<p>Given a DataFrame with a column &quot;BoolCol&quot;, we want to find the indexes of the DataFrame in which the values for &quot;BoolCol&quot; == True</p> <p>I currently have the iterating way to do it, which works perfectly:</p> <pre class="lang-py prettyprint-override"><code>for i in range(100,3000): if df.iloc...
<p><code>df.iloc[i]</code> returns the <code>ith</code> row of <code>df</code>. <code>i</code> does not refer to the index label, <code>i</code> is a 0-based index.</p> <p>In contrast, <strong>the attribute <code>index</code> returns actual index labels</strong>, not numeric row-indices:</p> <pre><code>df.index[df['B...
661
pandas
Remap values in pandas column with a dict, preserve NaNs
https://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict-preserve-nans
<p>I have a dictionary which looks like this: <code>di = {1: &quot;A&quot;, 2: &quot;B&quot;}</code></p> <p>I would like to apply it to the <code>col1</code> column of a dataframe similar to:</p> <pre class="lang-none prettyprint-override"><code> col1 col2 0 w a 1 1 2 2 2 NaN </code...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>.replace</code></a>. For example:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}}) &gt;&gt;&gt; di = {1: "A", 2: "B"} &gt...
662
pandas
How to reversibly store and load a Pandas dataframe to/from disk
https://stackoverflow.com/questions/17098654/how-to-reversibly-store-and-load-a-pandas-dataframe-to-from-disk
<p>Right now I'm importing a fairly large <code>CSV</code> as a dataframe every time I run the script. Is there a good solution for keeping that dataframe constantly available in between runs so I don't have to spend all that time waiting for the script to run?</p>
<p>The easiest way is to <a href="https://docs.python.org/3/library/pickle.html" rel="noreferrer">pickle</a> it using <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#pickling" rel="noreferrer"><code>to_pickle</code></a>:</p> <pre><code>df.to_pickle(file_name) # where to save it, usually as a .pkl </code><...
663
pandas
Pandas read_csv: low_memory and dtype options
https://stackoverflow.com/questions/24251219/pandas-read-csv-low-memory-and-dtype-options
<pre><code>df = pd.read_csv('somefile.csv') </code></pre> <p>...gives an error:</p> <blockquote> <p>.../site-packages/pandas/io/parsers.py:1130: DtypeWarning: Columns (4,5,7,16) have mixed types. Specify dtype option on import or set low_memory=False.</p> </blockquote> <p>Why is the <code>dtype</code> option related t...
<h1>The deprecated low_memory option</h1> <p>The <code>low_memory</code> option is not properly deprecated, but it should be, since it does not actually do anything differently[<a href="https://github.com/pydata/pandas/issues/5888" rel="noreferrer">source</a>]</p> <p>The reason you get this <code>low_memory</code> warn...
664
pandas
Pandas: drop a level from a multi-level column index?
https://stackoverflow.com/questions/22233488/pandas-drop-a-level-from-a-multi-level-column-index
<p>If I've got a multi-level column index:</p> <pre><code>&gt;&gt;&gt; cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]) &gt;&gt;&gt; pd.DataFrame([[1,2], [3,4]], columns=cols) </code></pre> <pre> a ---+-- b | c --+---+-- 0 | 1 | 2 1 | 3 | 4 </pre> <p>How can I drop the "a" level of that index, s...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.MultiIndex.droplevel.html" rel="noreferrer"><code>MultiIndex.droplevel</code></a>:</p> <pre><code>&gt;&gt;&gt; cols = pd.MultiIndex.from_tuples([(&quot;a&quot;, &quot;b&quot;), (&quot;a&quot;, &quot;c&quot;)]) &gt;&gt;&gt; df ...
665
pandas
Improve subplot size/spacing with many subplots
https://stackoverflow.com/questions/6541123/improve-subplot-size-spacing-with-many-subplots
<p>I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using <code>savefig</code> and viewed on a webpage, so I don't care how tall the final image is, as long as the subplots are spaced so they don't overlap.</p> <p>No matter how big I allow the figure to be, the subplo...
<p>Please review <a href="https://matplotlib.org/stable/users/explain/axes/tight_layout_guide.html" rel="noreferrer">matplotlib: Tight Layout guide</a> and try using <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html" rel="noreferrer"><code>matplotlib.pyplot.tight_layout</code></a>, ...
666
pandas
How to group dataframe rows into list in pandas groupby
https://stackoverflow.com/questions/22219004/how-to-group-dataframe-rows-into-list-in-pandas-groupby
<p>Given a dataframe, I want to groupby the first column and get second column as lists in rows, so that a dataframe like:</p> <pre><code>a b A 1 A 2 B 5 B 5 B 4 C 6 </code></pre> <p>becomes</p> <pre><code>A [1,2] B [5,5,4] C [6] </code></pre> <p>How do I do this?</p>
<p>You can do this using <code>groupby</code> to group on the column of interest and then <code>apply</code> <code>list</code> to every group:</p> <pre><code>In [1]: df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]}) df Out[1]: a b 0 A 1 1 A 2 2 B 5 3 B 5 4 B 4 5 C 6 In [...
667
pandas
Get list from pandas dataframe column or row?
https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column-or-row
<p>I have a dataframe <code>df</code> imported from an Excel document like this:</p> <pre class="lang-none prettyprint-override"><code>cluster load_date budget actual fixed_price A 1/1/2014 1000 4000 Y A 2/1/2014 12000 10000 Y A 3/1/2014 36000 2000 Y B 4/1/2014 15000 10000 N B...
<p>Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call <code>x.tolist()</code> on to turn them into a Python list. Alternatively you cast it with <code>list(x)</code>.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data_dict = {'one': pd.Series([1, 2, 3],...
668
pandas
Selecting a row of pandas series/dataframe by integer index
https://stackoverflow.com/questions/16096627/selecting-a-row-of-pandas-series-dataframe-by-integer-index
<p>I am curious as to why <code>df[2]</code> is not supported, while <code>df.ix[2]</code> and <code>df[2:3]</code> both work. </p> <pre><code>In [26]: df.ix[2] Out[26]: A 1.027680 B 1.514210 C -1.466963 D -0.162339 Name: 2000-01-03 00:00:00 In [27]: df[2:3] Out[27]: A B C...
<p>echoing @HYRY, see the new docs in 0.11</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/indexing.html</a></p> <p>Here we have new operators, <code>.iloc</code> to explicity support only integer indexing, and <code>.loc</code> t...
669
pandas
How can I use the apply() function for a single column?
https://stackoverflow.com/questions/34962104/how-can-i-use-the-apply-function-for-a-single-column
<p>I have a pandas dataframe with multiple columns. I want to change the values of the only the first column without affecting the other columns. How can I do that using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html" rel="noreferrer"><code>apply()</code></a> in pandas?</p>
<p>Given a sample dataframe <code>df</code> as:</p> <pre><code> a b 0 1 2 1 2 3 2 3 4 3 4 5 </code></pre> <p>what you want is:</p> <pre><code>df['a'] = df['a'].apply(lambda x: x + 1) </code></pre> <p>that returns:</p> <pre><code> a b 0 2 2 1 3 3 2 4 4 3 5 5 </code></pre>
670
pandas
How to select all columns except one in pandas?
https://stackoverflow.com/questions/29763620/how-to-select-all-columns-except-one-in-pandas
<p>I have a dataframe that look like this:</p> <pre class="lang-none prettyprint-override"><code> a b c d 0 0.418762 0.042369 0.869203 0.972314 1 0.991058 0.510228 0.594784 0.534366 2 0.407472 0.259811 0.396664 0.894202 3 0.726168 0.139531 0.324932 0.906575 </code></pre>...
<p>When the columns are not a MultiIndex, <code>df.columns</code> is just an array of column names so you can do:</p> <pre><code>df.loc[:, df.columns != 'b'] a c d 0 0.561196 0.013768 0.772827 1 0.882641 0.615396 0.075381 2 0.368824 0.651378 0.397203 3 0.788730 0.568099 0.869127 ...
671
pandas
How to add an empty column to a dataframe?
https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe
<p>What's the easiest way to add an empty column to a pandas DataFrame object? The best I've stumbled upon is something like</p> <pre class="lang-py prettyprint-override"><code>df['foo'] = df.apply(lambda _: '', axis=1) </code></pre> <p>Is there a less perverse method?</p>
<p>If I understand correctly, assignment should fill:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]}) &gt;&gt;&gt; df A B 0 1 2 1 2 3 2 3 4 &gt;&gt;&gt; df["C"] = "" &gt;&gt;&gt; df["D"] = np.nan &gt;&gt;&gt; df A...
672
pandas
How do I create a new column where the values are selected based on an existing column?
https://stackoverflow.com/questions/19913659/how-do-i-create-a-new-column-where-the-values-are-selected-based-on-an-existing
<p>How do I add a <code>color</code> column to the following dataframe so that <code>color='green'</code> if <code>Set == 'Z'</code>, and <code>color='red'</code> otherwise?</p> <pre><code> Type Set 1 A Z 2 B Z 3 B X 4 C Y </code></pre>
<p><strong>If you only have two choices to select from then use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>np.where</code></a>:</strong></p> <pre><code>df['color'] = np.where(df['Set']=='Z', 'green', 'red') </code></pre> <p>For example,</p> <pre><code>import p...
673
pandas
How to draw vertical lines on a given plot
https://stackoverflow.com/questions/24988448/how-to-draw-vertical-lines-on-a-given-plot
<p>Given a plot of a signal in time representation, how can I draw lines marking the corresponding time index?</p> <p>Specifically, given a signal plot with a time index ranging from 0 to 2.6 (seconds), I want to draw vertical red lines indicating the corresponding time index for the list <code>[0.22058956, 0.33088437,...
<p>The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is <code>plt.axvline</code></p> <pre><code>import matplotlib.pyplot as plt plt.axvline(x=0.22058956) plt.axvline(x=0.33088437) plt.axvline(x=2.20589566) </code></pre> <p>OR</p> <pre><c...
674
pandas
pandas get rows which are NOT in other dataframe
https://stackoverflow.com/questions/28901683/pandas-get-rows-which-are-not-in-other-dataframe
<p>I've two pandas data frames that have some rows in common.</p> <p>Suppose dataframe2 is a subset of dataframe1.</p> <p><strong>How can I get the rows of dataframe1 which are not in dataframe2?</strong></p> <pre><code>df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14]}) df2 = pand...
<p>One method would be to store the result of an inner merge form both dfs, then we can simply select the rows when one column's values are not in this common:</p> <pre><code>In [119]: common = df1.merge(df2,on=['col1','col2']) print(common) df1[(~df1.col1.isin(common.col1))&amp;(~df1.col2.isin(common.col2))] col1...
675
pandas
pandas: filter rows of DataFrame with operator chaining
https://stackoverflow.com/questions/11869910/pandas-filter-rows-of-dataframe-with-operator-chaining
<p>Most operations in <code>pandas</code> can be accomplished with operator chaining (<code>groupby</code>, <code>aggregate</code>, <code>apply</code>, etc), but the only way I've found to filter rows is via normal bracket indexing</p> <pre><code>df_filtered = df[df['column'] == value] </code></pre> <p>This is unappe...
<p>I'm not entirely sure what you want, and your last line of code does not help either, but anyway:</p> <p>"Chained" filtering is done by "chaining" the criteria in the boolean index.</p> <pre><code>In [96]: df Out[96]: A B C D a 1 4 9 1 b 4 5 0 2 c 5 5 1 0 d 1 3 9 6 In [99]: df[(df.A == 1) &a...
676
pandas
What does axis in pandas mean?
https://stackoverflow.com/questions/22149584/what-does-axis-in-pandas-mean
<p>Here is my code to generate a dataframe:</p> <pre><code>import pandas as pd import numpy as np dff = pd.DataFrame(np.random.randn(1, 2), columns=list('AB')) </code></pre> <p>then I got the dataframe:</p> <pre><code> A B 0 0.626386 1.52325 </code></pre> <p>When I type the command <code>dff.mean(axi...
<p>It specifies the axis <strong>along which</strong> the means are computed. By default <code>axis=0</code>. This is consistent with the <code>numpy.mean</code> usage when <code>axis</code> is specified <em>explicitly</em> (in <code>numpy.mean</code>, axis==None by default, which computes the mean value over the flatt...
677
pandas
Normalize columns of a dataframe
https://stackoverflow.com/questions/26414913/normalize-columns-of-a-dataframe
<p>I have a dataframe in pandas where each column has different value range. For example:</p> <p>df:</p> <pre><code>A B C 1000 10 0.5 765 5 0.35 800 7 0.09 </code></pre> <p>Any idea how I can normalize the columns of this dataframe where each value is between 0 and 1?</p> <p>My desired output is:</p...
<p>You can use the package sklearn and its associated preprocessing utilities to normalize the data.</p> <pre><code>import pandas as pd from sklearn import preprocessing x = df.values #returns a numpy array min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) df = pd.DataFrame(x_sc...
678
pandas
Remove pandas rows with duplicate indices
https://stackoverflow.com/questions/13035764/remove-pandas-rows-with-duplicate-indices
<p>How to remove rows with duplicate index values?</p> <p>In the weather DataFrame below, sometimes a scientist goes back and corrects observations -- not by editing the erroneous rows, but by appending a duplicate row to the end of a file.</p> <p>I'm reading some automated weather data from the web (observations occur...
<p>I would suggest using the <a href="https://pandas.pydata.org/docs/reference/api/pandas.Index.duplicated.html" rel="nofollow noreferrer">duplicated</a> method on the Pandas Index itself:</p> <pre><code>df3 = df3[~df3.index.duplicated(keep='first')] </code></pre> <p>While all the other methods work, <code>.drop_duplic...
679
pandas
Converting between datetime, Timestamp and datetime64
https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64
<p>How do I convert a <code>numpy.datetime64</code> object to a <code>datetime.datetime</code> (or <code>Timestamp</code>)?</p> <p>In the following code, I create a datetime, timestamp and datetime64 objects.</p> <pre><code>import datetime import numpy as np import pandas as pd dt = datetime.datetime(2012, 5, 1) # A ...
<p>To convert <code>numpy.datetime64</code> to <code>datetime</code> object that represents time in UTC on <code>numpy-1.8</code>:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; dt = datetime.utcnow() &gt;&gt;&gt; dt datetime.datetime(2012, 12, 4, 19, 51, 25, 3624...
680
pandas
How to drop a list of rows from Pandas dataframe?
https://stackoverflow.com/questions/14661701/how-to-drop-a-list-of-rows-from-pandas-dataframe
<p>I have a dataframe df :</p> <pre><code>&gt;&gt;&gt; df sales discount net_sales cogs STK_ID RPT_Date 600141 20060331 2.709 NaN 2.709 2.245 20060630 6.590 NaN 6.590 5.291 20060930 10.103 NaN 10.103 7....
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="noreferrer">DataFrame.drop</a> and pass it a Series of index labels:</p> <pre><code>In [65]: df Out[65]: one two one 1 4 two 2 3 three 3 2 four 4 1 In [66]: df.drop(df.i...
681
pandas
How to sort a pandas dataFrame by two or more columns?
https://stackoverflow.com/questions/17141558/how-to-sort-a-pandas-dataframe-by-two-or-more-columns
<p>Suppose I have a dataframe with columns <code>a</code>, <code>b</code> and <code>c</code>. I want to sort the dataframe by column <code>b</code> in ascending order, and by column <code>c</code> in descending order. How do I do this?</p>
<p>As of the 0.17.0 release, the <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sort.html" rel="noreferrer"><code>sort</code></a> method was deprecated in favor of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="noreferrer">...
682
pandas
how do I insert a column at a specific column index in pandas?
https://stackoverflow.com/questions/18674064/how-do-i-insert-a-column-at-a-specific-column-index-in-pandas
<p>Can I insert a column at a specific column index in pandas? </p> <pre><code>import pandas as pd df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]}) df['n'] = 0 </code></pre> <p>This will put column <code>n</code> as the last column of <code>df</code>, but isn't there a way to tell <code>df</code> to put <cod...
<p>see docs: <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html</a></p> <p>using loc = 0 will insert at the beginning</p> <pre><code>df.insert(loc, column, value) </code>...
683
pandas
How to add pandas data to an existing csv file?
https://stackoverflow.com/questions/17530542/how-to-add-pandas-data-to-an-existing-csv-file
<p>I want to know if it is possible to use the pandas <code>to_csv()</code> function to add a dataframe to an existing csv file. The csv file has the same structure as the loaded data. </p>
<p>You can specify a python write mode in the pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="noreferrer"><code>to_csv</code></a> function. For append it is 'a'.</p> <p>In your case:</p> <pre><code>df.to_csv('my_csv.csv', mode='a', header=False) </code></pre> <p>...
684
pandas
Count the frequency that a value occurs in a dataframe column
https://stackoverflow.com/questions/22391433/count-the-frequency-that-a-value-occurs-in-a-dataframe-column
<p>I have a dataset</p> <pre class="lang-none prettyprint-override"><code>category cat a cat b cat a </code></pre> <p>I'd like to return something like the following which shows the unique values and their frequencies</p> <pre class="lang-none prettyprint-override"><code>category freq cat a 2 cat b 1 </c...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="noreferrer"><code>value_counts()</code></a> as @DSM commented.</p> <pre><code>In [37]: df = pd.DataFrame({'a':list('abssbab')}) df['a'].value_counts() Out[37]: b 3 a 2 s 2 dtype: int64 </code></pre> <p...
685
pandas
Extracting just Month and Year separately from Pandas Datetime column
https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-separately-from-pandas-datetime-column
<p>I have a Dataframe, <code>df</code>, with the following column:</p> <pre class="lang-none prettyprint-override"><code> ArrivalDate 936 2012-12-31 938 2012-12-29 965 2012-12-31 966 2012-12-31 967 2012-12-31 968 2012-12-31 969 2012-12-31 970 2012-12-29 971 2012-12-31 972 2012-12-29 973 2012-1...
<p>If you want new columns showing year and month separately you can do this:</p> <pre><code>df['year'] = pd.DatetimeIndex(df['ArrivalDate']).year df['month'] = pd.DatetimeIndex(df['ArrivalDate']).month </code></pre> <p>or...</p> <pre><code>df['year'] = df['ArrivalDate'].dt.year df['month'] = df['ArrivalDate'].dt.mo...
686
pandas
Add column to dataframe with constant value
https://stackoverflow.com/questions/29517072/add-column-to-dataframe-with-constant-value
<p>I have an existing dataframe which I need to add an additional column to which will contain the same value for every row.</p> <p>Existing df:</p> <pre><code>Date, Open, High, Low, Close 01-01-2015, 565, 600, 400, 450 </code></pre> <p>New df:</p> <pre><code>Name, Date, Open, High, Low, Close abc, 01-01-2015, 565,...
<p><code>df['Name']='abc'</code> will add the new column and set all rows to that value:</p> <pre><code>In [79]: df Out[79]: Date, Open, High, Low, Close 0 01-01-2015, 565, 600, 400, 450 In [80]: df['Name'] = 'abc' df Out[80]: Date, Open, High, Low, Close Name 0 01-01-2015, 565, 600, ...
687
pandas
Get the row(s) which have the max value in groups using groupby
https://stackoverflow.com/questions/15705630/get-the-rows-which-have-the-max-value-in-groups-using-groupby
<p>How do I find all rows in a pandas DataFrame which have the max value for <code>count</code> column, after grouping by <code>['Sp','Mt']</code> columns?</p> <p><strong>Example 1:</strong> the following DataFrame:</p> <pre><code> Sp Mt Value count 0 MM1 S1 a **3** 1 MM1 S1 n 2 2 MM1 S3 cb ...
<p>Firstly, we can get the max count for each group like this:</p> <pre><code>In [1]: df Out[1]: Sp Mt Value count 0 MM1 S1 a 3 1 MM1 S1 n 2 2 MM1 S3 cb 5 3 MM2 S3 mk 8 4 MM2 S4 bg 10 5 MM2 S4 dgd 1 6 MM4 S2 rd 2 7 MM4 S2 cb 2 8 MM4 ...
688
pandas
Create Pandas DataFrame from a string
https://stackoverflow.com/questions/22604564/create-pandas-dataframe-from-a-string
<p>In order to test some functionality I would like to create a <code>DataFrame</code> from a string. Let's say my test data looks like:</p> <pre><code>TESTDATA="""col1;col2;col3 1;4.4;99 2;4.5;200 3;4.7;65 4;3.2;140 """ </code></pre> <p>What is the simplest way to read that data into a Pandas <code>DataFrame</code>?...
<p>A simple way to do this is to use <a href="https://docs.python.org/2/library/io.html#io.StringIO" rel="noreferrer"><code>StringIO.StringIO</code> (python2)</a> or <a href="https://docs.python.org/3/library/io.html#io.StringIO" rel="noreferrer"><code>io.StringIO</code> (python3)</a> and pass that to the <a href="http...
689
pandas
How to split a dataframe string column into two columns?
https://stackoverflow.com/questions/14745022/how-to-split-a-dataframe-string-column-into-two-columns
<p>I have a data frame with one (string) column and I'd like to split it into two (string) columns, with one column header as '<code>fips'</code> and the other <code>'row'</code></p> <p>My dataframe <code>df</code> looks like this:</p> <pre><code> row 0 00000 UNITED STATES 1 01000 ALABAMA 2 01001 Auta...
<p>There might be a better way, but this here's one approach:</p> <pre><code> row 0 00000 UNITED STATES 1 01000 ALABAMA 2 01001 Autauga County, AL 3 01003 Baldwin County, AL 4 01005 Barbour County, AL </code></pre> <pre><code>df = pd.DataFrame(df.row.s...
690
pandas
Dropping infinite values from dataframes in pandas?
https://stackoverflow.com/questions/17477979/dropping-infinite-values-from-dataframes-in-pandas
<p>How do I drop <code>nan</code>, <code>inf</code>, and <code>-inf</code> values from a <code>DataFrame</code> without resetting <code>mode.use_inf_as_null</code>?</p> <p>Can I tell <code>dropna</code> to include <code>inf</code> in its definition of missing values so that the following works?</p> <pre><code>df.dropna...
<p>First <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>replace()</code></a> infs with NaN:</p> <pre><code>df.replace([np.inf, -np.inf], np.nan, inplace=True) </code></pre> <p>and then drop NaNs via <a href="http://pandas.pydata.org/pandas-docs/stabl...
691
pandas
Convert a Pandas DataFrame to a dictionary
https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary
<p>I have a DataFrame with four columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be <code>keys</code> and the elements of other columns in the same row be <code>values</code>.</p> <p>DataFrame:</p> <pre class="lang-py prettyprint-override"><code> ID A B C 0 ...
<p>The <a href="http://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.to_dict.html" rel="noreferrer"><code>to_dict()</code></a> method sets the column names as dictionary keys so you'll need to reshape your DataFrame slightly. Setting the 'ID' column as the index and then transposing the DataFram...
692
pandas
Convert Pandas Column to DateTime
https://stackoverflow.com/questions/26763344/convert-pandas-column-to-datetime
<p>I have one field in a pandas DataFrame that was imported as string format.</p> <p>It should be a datetime variable. How do I convert it to a datetime column, and then filter based on date?</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>raw_data = pd.DataFrame({'Mycol': ['05SEP2014:00:00:00.000']...
<p>Use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> function, specifying a <a href="http://strftime.org/" rel="noreferrer">format</a> to match your data.</p> <pre><code>df['Mycol'] = pd.to_datetime(df['Mycol'], format='%d%b%Y:...
693
pandas
How to determine whether a Pandas Column contains a particular value
https://stackoverflow.com/questions/21319929/how-to-determine-whether-a-pandas-column-contains-a-particular-value
<p>I am trying to determine whether there is an entry in a Pandas column that has a particular value. I tried to do this with <code>if x in df['id']</code>. I thought this was working, except when I fed it a value that I knew was not in the column <code>43 in df['id']</code> it still returned <code>True</code>. When I ...
<p><code>in</code> of a Series checks whether the value is in the index:</p> <pre><code>In [11]: s = pd.Series(list('abc')) In [12]: s Out[12]: 0 a 1 b 2 c dtype: object In [13]: 1 in s Out[13]: True In [14]: 'a' in s Out[14]: False </code></pre> <p>One option is to see if it's in <a href="http://pandas....
694
pandas
How to invert the x or y axis
https://stackoverflow.com/questions/2051744/how-to-invert-the-x-or-y-axis
<p>I have a scatter plot graph with a bunch of random x, y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0.</p> <pre><code>points = [(10,5), (5,11), (24,13), (7,8)] x_arr = [] y_arr = [] for x,y in points: x_arr.append...
<p>There is a new API that makes this even simpler.</p> <pre><code>plt.gca().invert_xaxis() </code></pre> <p>and/or</p> <pre><code>plt.gca().invert_yaxis() </code></pre>
695
pandas
How to show all columns&#39; names on a large pandas dataframe?
https://stackoverflow.com/questions/49188960/how-to-show-all-columns-names-on-a-large-pandas-dataframe
<p>I have a dataframe that consist of hundreds of columns, and I need to see all column names.</p> <p>What I did:</p> <pre><code>In[37]: data_all2.columns </code></pre> <p>The output is:</p> <pre><code>Out[37]: Index(['customer_id', 'incoming', 'outgoing', 'awan', 'bank', 'family', 'food', 'government', 'int...
<p>You can globally set printing options. I think this should work:</p> <p><strong>Method 1:</strong></p> <pre><code>pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) </code></pre> <p><strong>Method 2:</strong></p> <pre><code>pd.options.display.max_columns = None pd.options.display.max_...
696
pandas
Appending to an empty DataFrame in Pandas?
https://stackoverflow.com/questions/16597265/appending-to-an-empty-dataframe-in-pandas
<p>Is it possible to append to an empty data frame that doesn't contain any indices or columns?</p> <p>I have tried to do this, but keep getting an empty dataframe at the end.</p> <p>e.g.</p> <pre><code>import pandas as pd df = pd.DataFrame() data = ['some kind of data here' --&gt; I have checked the type already, and...
<p>The answers are very useful, but since <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.append.html#" rel="noreferrer"><code>pandas.DataFrame.append</code></a> was deprecated (as already mentioned by various users), and the answers using <a href="https://pandas.pydata.org/docs/reference/api/pan...
697
pandas
Convert DataFrame column type from string to datetime
https://stackoverflow.com/questions/17134716/convert-dataframe-column-type-from-string-to-datetime
<p>How can I convert a DataFrame column of strings (in <em><strong>dd/mm/yyyy</strong></em> format) to datetime dtype?</p>
<p>The easiest way is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a>:</p> <pre><code>df['col'] = pd.to_datetime(df['col']) </code></pre> <p>It also offers a <code>dayfirst</code> argument for European times (but beware <a href...
698
pandas
python pandas remove duplicate columns
https://stackoverflow.com/questions/14984119/python-pandas-remove-duplicate-columns
<p>What is the easiest way to remove duplicate columns from a dataframe?</p> <p>I am reading a text file that has duplicate columns via:</p> <pre><code>import pandas as pd df=pd.read_table(fname) </code></pre> <p>The column names are:</p> <pre><code>Time, Time Relative, N2, Time, Time Relative, H2, etc... </code><...
<p>Here's a one line solution to remove columns based on duplicate <strong>column names</strong>:</p> <pre><code>df = df.loc[:,~df.columns.duplicated()].copy() </code></pre> <p><strong>How it works:</strong></p> <p>Suppose the columns of the data frame are <code>['alpha','beta','alpha']</code></p> <p><code>df.columns.d...
699
tenserflow
pip install tenserflow in command
https://stackoverflow.com/questions/54931918/pip-install-tenserflow-in-command
<p>I checked them, python --version Python 3.7.1</p> <p>pip --version pip 18.1</p> <p>and I'm using Windows 10.</p> <p>but,pip install tenserflow running command line,The following error comes out.</p> <p>pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.</p> ...
<p>First, update pip by</p> <pre><code>pip install --upgrade pip </code></pre> <p>Then install TensorFlow using</p> <pre><code>pip install tensorflow </code></pre>
700
tenserflow
Installing Tenserflow on GPU NVIDIA GeForce MX230
https://stackoverflow.com/questions/67633123/installing-tenserflow-on-gpu-nvidia-geforce-mx230
<p>Is it worth installing Tenserflow on a <strong>NVIDIA GeForce MX230</strong> (It is CUDA Supported ). <a href="https://www.nvidia.com/en-us/geforce/gaming-laptops/geforce-mx230/specifications/" rel="nofollow noreferrer">https://www.nvidia.com/en-us/geforce/gaming-laptops/geforce-mx230/specifications/</a> or should I...
<p>Tensorflow is going to perform better with GPU, but MX230 isn't that powerful. I also have MX230, but I instead use google colab.</p>
701
tenserflow
Training Tenserflow Model for Speech Recognition in React
https://stackoverflow.com/questions/70567700/training-tenserflow-model-for-speech-recognition-in-react
<p>I'm using Electron + ReactJS and Tenserflow.</p> <p>I want to have like a collection of 500-1000 words like 'dog', 'newline', 'cat' be recognized when i talk.</p> <ol> <li>How much time can it take for the model to be trained with 500 words? I used 5 words and it took a bit of time. I don't want to have a loader and...
702
tenserflow
how to check if tenserflow is using gpu?
https://stackoverflow.com/questions/60863574/how-to-check-if-tenserflow-is-using-gpu
<p>I am using Jupyter notebook for training neural network. I choose in the anaconda applications on tenserflow-gpu however I dont think it is using GPU. How can I check it if it is using GPU for processing? </p>
<p>You could use the </p> <pre><code>&lt;tf.config.list_physical_devices('GPU')&gt; </code></pre> <p>For tensorflow 2.1. Also check the documentation found <a href="https://www.tensorflow.org/api_docs/python/tf/config/list_physical_devices" rel="nofollow noreferrer">here</a></p>
703
tenserflow
problem while installing tenserflow on EC2 machine the process gets killed
https://stackoverflow.com/questions/62701637/problem-while-installing-tenserflow-on-ec2-machine-the-process-gets-killed
<p>Whenever I try to install tenserflow on my free tier eligible ec2 machine on AWS it downloads and then the further process gets killed I tried many things but didn't get any solution for the same<a href="https://i.sstatic.net/hxw1Z.png" rel="nofollow noreferrer">as you can see the tenserflow has been downloaded and ...
<p>I found the solution there were multiple factors one of them was configuration of machine didn't support Tensorflow thats the reason the job waas getting cancelled .</p>
704
tenserflow
No MSE in tenserflow trainmodel in JS
https://stackoverflow.com/questions/78538556/no-mse-in-tenserflow-trainmodel-in-js
<p>I am trying to train a tenserflow model in JS but I can't get the MSE score. It returns NaN even in the Epoch, so I am not sure it trains as it should. This is part of my code:</p> <pre><code>// Check tensors checkForNaNs(xs, 'Features'); //returns : //Features does not contains NaNs //Features does not contains Inf...
<p>The problem was in the optimizerType, I changed it to Adam and it worked first try!</p>
705
tenserflow
How to switch keras backend from tenserflow to theano?
https://stackoverflow.com/questions/65475584/how-to-switch-keras-backend-from-tenserflow-to-theano
<p>I need keras for my work, it needs tenserflow but I'm operating Windows 32. So I decided to switch keras backend. I created json file in &quot;C/USERS/admin/.keras&quot; it looks like:</p> <pre><code>{ &quot;image_data_format&quot;:&quot;channels first&quot;, &quot;epsilon&quot;: 1e-07, &quot;floatx&quot;: &quot;flo...
<p>Maybe should I change anything in init.py?</p> <pre><code>try: from tensorflow.keras.layers.experimental.preprocessing import RandomRotation except ImportError: raise ImportError( 'Keras requires TensorFlow 2.2 or higher. ' 'Install TensorFlow via `pip install tensorflow`') from . import uti...
706
tenserflow
why I can not use tenserflow and Keras in my Jupyter notebook?
https://stackoverflow.com/questions/60728132/why-i-can-not-use-tenserflow-and-keras-in-my-jupyter-notebook
<p>I successfully installed tenserflow and Keras but when I import them in Jupyter notebook it say </p> <pre><code>ModuleNotFoundError </code></pre> <p>but in my VScode is working! what is problem?</p> <p>I use Mac I installed them in terminal like this:</p> <pre><code>pip3 install --upgrade tensorflow pip install...
707
tenserflow
Installing/Using tenserflow
https://stackoverflow.com/questions/74526250/installing-using-tenserflow
<p>I am getting this error when trying to import tensorflow:</p> <blockquote> <p>File &quot;/Users/alexkaram/untitled3.py&quot;, line 7, in import tensorflow as tf ModuleNotFoundError: No module named 'tensorflow'</p> </blockquote> <p>My Spyder version is 5.3.3 and anaconda navigator 2.3.1.</p> <p>I tried to install t...
708
tenserflow
long() argument must be a string or a number error in tenserflow
https://stackoverflow.com/questions/49627073/long-argument-must-be-a-string-or-a-number-error-in-tenserflow
<p>Iḿ trying to run an objects detection code using tensorflow</p> <pre><code>import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import...
<p>The problem is with this part:</p> <pre><code>ret = True while (ret): ret,image_np = cap.read() </code></pre> <p>After the last frame it will read <code>None</code> into image_np, but the inside of your loop still runs and tries to feed that <code>None</code> to the network, and would only stop when it gets to...
709
tenserflow
NMT Using Tenserflow
https://stackoverflow.com/questions/73656822/nmt-using-tenserflow
<p>My Code:</p> <pre><code>vocab_size = 10000 total_sentences = 25000 maxlen = 10 epochs = 50 validation_split = 0.05 </code></pre> <pre><code>split = int(0.95 * total_sentences) X_train = [encoder_inputs[:split], decoder_inputs[:split]] y_train = decoder_outputs[:split] # Test data to evaluate our NMT model using BL...
710
tenserflow
Read .mp4 file from firebase storage using fs to send that video to tenserflow model
https://stackoverflow.com/questions/62159550/read-mp4-file-from-firebase-storage-using-fs-to-send-that-video-to-tenserflow-m
<p>my graduation project is to convert video into text. I'm trying to read video uploaded in Firebase storage &amp; sent from android app, to send it to TenserFlow model. but I can't read the video.</p> <h3>here is my function:</h3> <pre><code>exports.readVideo = functions.storage .object() .onFinalize(async (object) =...
<p>As the error message shows, the regular file system on Cloud Functions is read only. The only place you can write to is <code>/tmp</code>, as also shown in the documentation on <a href="https://cloud.google.com/functions/docs/concepts/exec#file_system" rel="nofollow noreferrer">file system access in Cloud Functions<...
711
tenserflow
tenserflow kernel keeps dying after installing &quot;pydot (version 1.4.1)&quot; and &quot;python-graphviz (version 0.8.4)&quot;
https://stackoverflow.com/questions/71845340/tenserflow-kernel-keeps-dying-after-installing-pydot-version-1-4-1-and-pyth
<p>I installed &quot;pydot (version 1.4.1)&quot; and &quot;python-graphviz (version 0.8.4)&quot; to my tensorflow environment in anaconda. Now my tenserflow kernel keeps dying. I did get this warning once when I was trying to import the tensorflow libraries.</p> <p>C:\Users\lbasnet\Anaconda3\envs\tflow\lib\site-package...
<p>I got it resolved by myself. I uninstalled h5py <code>pip uninstall h5py</code> and reinstalled it <code>pip install h5py</code></p> <p>If you were trying to get <code>plot_model</code> to work and ended up with the above issue I faced, the following links can be very helpful to get &quot;pydot&quot; and &quot;grap...
712
tenserflow
How to deploy python project with tenserflow to exe file?And is it even possible?
https://stackoverflow.com/questions/66656250/how-to-deploy-python-project-with-tenserflow-to-exe-fileand-is-it-even-possible
<p>I have a project based on ImageAI (the code is taken directly from the documentation), which uses tenserflow, keras and other dependencies, and it needs to be packed into an exe file.</p> <p>The problem is that, so far, I haven't been able to do it, I've been using the pyinstaller library.But the problem I have with...
<p>1.first you need to save your tensorflow model weight i.e (model.pb)</p> <ol start="2"> <li><p>convert this into tensorflowlite (TF.lite) &amp; you can use this in android phone</p> <p><a href="https://www.tensorflow.org/tutorials/keras/save_and_load" rel="nofollow noreferrer">load and save model -tensorflow</a></...
713
tenserflow
No module named tenserflow
https://stackoverflow.com/questions/66411278/no-module-named-tenserflow
<p>i came to this problem when im about to generate tfrecord for my test and training data. can anyone help me?</p> <pre><code>C:\Object_detection\models-master\research\object_detection&gt;python generate_tfrecord.py --csv_input=images/test_labels.csv --image_dir=images/test --output_path=test.record </code></pre> <p>...
<p>Try to run</p> <pre><code>pip show tensorflow </code></pre> <p>to check you tensorflow version. It's possible that you will need to downgrade or upgrade you tf package to be able to run your tfrecord. Check the documentation of the function to know the version you need.</p>
714
tenserflow
Tenserflow issue when tokenizing sentences
https://stackoverflow.com/questions/74123446/tenserflow-issue-when-tokenizing-sentences
<p>I followed a tutorial about tokenizing sentences using Tensorflow, here's the code I'm trying:</p> <pre><code>from tensorflow.keras.preprocessing.text import Tokenizer #API for tokenization t = Tokenizer(num_words=4) #meant to catch most imp _ listofsentences=['Apples are fruits', 'An orange is a tasty fruit', 'Fru...
<p>To specify an unlimited amount of tokens use:</p> <pre><code>t = Tokenizer(num_words=None) </code></pre> <p>Output:</p> <pre><code>{'are': 1, 'fruits': 2, 'tasty': 3, 'apples': 4, 'an': 5, 'orange': 6, 'is': 7, 'a': 8, 'fruit': 9} [[4, 1, 2], [5, 6, 7, 8, 3, 9], [2, 1, 3]] </code></pre>
715
tenserflow
tenserflow tutorial error or mistake
https://stackoverflow.com/questions/42706111/tenserflow-tutorial-error-or-mistake
<p>Incorrect code from training examples <a href="https://www.tensorflow.org/get_started/get_started" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/get_started</a></p> <pre><code> sess=tf.InteractiveSession() a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) adder_node = a...
716
tenserflow
element wise multiplication tenserflow Error
https://stackoverflow.com/questions/59050126/element-wise-multiplication-tenserflow-error
<p>i made my autoencoder in this way </p> <pre><code>autoencoder = Sequential() Atac=Atac.iloc[range(2),range(2)] autoencoder.add(Dense(minFeature, activation='relu',name="encoder4",input_shape=(Atac.shape[1],),kernel_constraint=prova())) autoencoder.add(Dense(Atac.shape[1], activation='relu',name="decoder4",kernel_co...
717
tenserflow
Tenserflow module is giving errors
https://stackoverflow.com/questions/76003183/tenserflow-module-is-giving-errors
<p>I am trying to import some modules but I get errors back. These are what I am trying to import and install:</p> <pre><code>%pip install pandas %pip install numpy %pip install requests %pip install beautifulsoup4 %pip install tensorflow import requests import pandas import numpy import requests from bs4 import Beaut...
718
tenserflow
import error on transformers and tenserflow
https://stackoverflow.com/questions/78085996/import-error-on-transformers-and-tenserflow
<pre><code>RuntimeError: Failed to import transformers.models.bert.modeling_tf_bert because of the following error (look up to see its traceback): module 'tensorflow._api.v2.compat.v2.__internal__' has no attribute 'register_load_context_function' </code></pre> <pre><code>sentiment_analysis = pipeline(&quot;sentiment-a...
<p>Seems a version compatibility problem.</p> <p>I would try to pin version of python to 3.10 and tensorflow/keras seeking stability.</p> <pre><code>conda create -n my_env python=3.10 conda activate my_env python -m pip install tensorflow==2.15.0 keras==2.15.0 </code></pre> <p>And try to run your program with this setu...
719
tenserflow
Where in tenserflow to show elements
https://stackoverflow.com/questions/46367159/where-in-tenserflow-to-show-elements
<p>This code shows only indexes of array, where it used</p> <pre><code>tensor1 = tf.convert_to_tensor(np.array([1536, 2, 5], dtype='float32')) tf.where(tensor1 &gt; 3).eval().reshape(1, 2)[0] </code></pre> <p>Output is:</p> <blockquote> <p>array([0, 2], dtype=int64)</p> </blockquote> <p>I did for loop to print us...
<p>tf.gather can also be used to index into arrays, so</p> <pre><code>indices = tf.where(tensor1 &gt; 3) tf.gather(tensor1, indices) </code></pre> <p>should do the right thing</p>
720
tenserflow
tenserflow quites before it is done installing
https://stackoverflow.com/questions/57560411/tenserflow-quites-before-it-is-done-installing
<p>When I do</p> <pre><code>pip install tenserflow </code></pre> <p>tensorflow stops before is is finished, no message saying successful ( i tried this several times thought maybe it was a network issue)</p> <pre><code>Successfully installed absl-py-0.7.1 astor-0.8.0 gast-0.2.2 google-pasta-0.1.7 grpcio-1.23.0 h5py-...
<p>Those are simply warnings (So you can safely ignore them, they are not actual errors), your numpy version is not compatible with the tensorflow version you are using. Tensorflow did install correctly; as seen in the outpout from pip:</p> <pre><code>**Successfully installed** absl-py-0.7.1 astor-0.8.0 gast-0.2.2 goo...
721
tenserflow
Keras/Tenserflow - Cannot make model.fit() work
https://stackoverflow.com/questions/70178206/keras-tenserflow-cannot-make-model-fit-work
<p>I am trying to make a CNN network to make predictions on images of mushrooms.</p> <p>Sadly, I can't even begin to train my model, the fit() method always gives me errors.</p> <p>There are 10 classes, the tf Datasets correctly found their names based on their subfolders.</p> <p>With my current code, it says:</p> <pre...
<p>I think you need to flatten before passing to the <code>Dense</code> layer</p> <pre><code>input_layer = keras.Input(shape=(64, 64, 3)) x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation=&quot;relu&quot;)(input_layer) x = layers.MaxPooling2D(pool_size=(3, 3))(x) x = keras.layers.ReLU()(x) x = keras.layers.F...
722
tenserflow
Exporting a Trained Inference Graph TENSERFLOW
https://stackoverflow.com/questions/57563619/exporting-a-trained-inference-graph-tenserflow
<p>I have trained my custom model and want to export a trained inference graph</p> <p>I ran the following command</p> <pre><code>INPUT_TYPE=image_tensor PIPELINE_CONFIG_PATH= training/ ssd_mobilenet_v1_pets.config TRAINED_CKPT_PREFIX= training/model.ckpt-2509 EXPORT_DIR= training/new_model python exporter.py \ --...
<p>Fixed with this code</p> <p>python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/ssd_mobilenet_v1_pets.config --trained_checkpoint_prefix training/model.ckpt-3970 --output_directory ships_inference_graph</p>
723
tenserflow
Tenserflow custom layer input doesn&#39;t work
https://stackoverflow.com/questions/64955811/tenserflow-custom-layer-input-doesnt-work
<p>I need to create custom layer for my model. Here is the code:</p> <pre><code>class Custom_layer_2(keras.layers.Layer): def __init__(self, input_neurons_nmber, nn_neurons_number, connections_matrix, inputs_neurons): super(Custom_layer_2, self).__init__() self.cn = tf.dtypes.cast(tf.constant(connec...
724
tenserflow
Where does Bazel store TenserFlow build?
https://stackoverflow.com/questions/42354675/where-does-bazel-store-tenserflow-build
<p>I'm trying to build TensorFlow from sources following this guide: <a href="https://www.tensorflow.org/install/install_sources" rel="nofollow noreferrer">Installing TensorFlow from Sources</a>. The build seems to have worked fine, but then there's the last step:</p> <blockquote> <p>Invoke pip install to install th...
<p>It sounds like you may have skipped a step. Bazel does not create this file. The program that Bazel builds does.</p> <p>The prior step on <a href="https://www.tensorflow.org/install/install_sources" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_sources</a> to the one that you mention is to ru...
725
tenserflow
Jupyter Notebook Kernel dies when importing tenserflow
https://stackoverflow.com/questions/68511374/jupyter-notebook-kernel-dies-when-importing-tenserflow
<p>I am using Macbook Air with M1 chip. When trying to import tensorflow in Jupyter notebook, the kernel dies and displays a prompt that &quot;Kernel has died and will restart in sometime&quot;. Could someone help me fix this?</p> <p>Tensorflow version - 2.5.0 Python version - 3.8.8</p>
<p>Try running the notebook file within VS Code, there are extensions to help with that. Also check this article on how to install tf on M1 <a href="https://towardsdatascience.com/installing-tensorflow-on-the-m1-mac-410bb36b776" rel="nofollow noreferrer">https://towardsdatascience.com/installing-tensorflow-on-the-m1-m...
726
tenserflow
Setting up on Macbook Pro M1 Tenserflow with OpenCV, Scipy, Scikit-learn
https://stackoverflow.com/questions/69427204/setting-up-on-macbook-pro-m1-tenserflow-with-opencv-scipy-scikit-learn
<p>I think I read pretty much most of the guides on setting up tensorflow, tensorflow-hub, object detection on Mac M1 on BigSur v11.6. I managed to figure out most of the errors after more than 2 weeks. But I am stuck at OpenCV setup. I tried to compile it from source but seems like it can't find the modules from its c...
<p>In my case I also had lot of trouble trying to install both modules. I finally managed to do so but to be honest not really sure how and why. I leave below the requirements in case you might want to recreate the environment that worked in my case. You should have the conda Miniforge 3 installed :</p> <pre><code># Th...
727
tenserflow
AttributeError: &#39;module&#39; object has no attribute &#39;contrib&#39;
https://stackoverflow.com/questions/44092475/attributeerror-module-object-has-no-attribute-contrib
<p>I am using tenserflow first time with Python 2.7 . I am following tenserflow tutorial and when I am running the below line features </p> <pre><code>[tf.contrib.layers.real_valued_column("x", dimension=1)] </code></pre> <p>its throwing the error </p> <blockquote> <p>"AttributeError: 'module' object has no attrib...
<p>However, it got solved after reinstalling the protofub.</p>
728
tenserflow
Tenserflow hangs when running inference with GPU enabled
https://stackoverflow.com/questions/61382445/tenserflow-hangs-when-running-inference-with-gpu-enabled
<p>I am new to AI and TensorFlow and I am trying to use the TensorFlow object detection API on windows. <br> My current goal is to do real time human detection in a video stream. <br> For this I modified a python example from the TensorFlow Model Garden (<a href="https://github.com/tensorflow/models" rel="nofollow nore...
<p>If you are using GPU try to install tensorflow-gpu. The tensorflow you are using seems based on the documentation to support GPU but you can try and specify is implicitly. Try this on a python virtual environment first.</p> <pre><code> pip uninstall tensorflow </code></pre> <p>uninstall tensorflow-gpu: (make su...
729
tenserflow
Tenserflow model for text classification doesn&#39;t predict as expected?
https://stackoverflow.com/questions/60015820/tenserflow-model-for-text-classification-doesnt-predict-as-expected
<p>I am trying to train a model for sentiment analysis and it shows an accuracy of 90% when splitting the data into training and testing! But whenever I am testing it on a new phrase is has pretty much the same result(usually it's in the range 0.86 - 0.95)! Here is the code:</p> <pre><code>sentences = data['text'].va...
<p>It seems that you're victim of <code>overfitting</code>. In other words, our model would overfit to the <code>training data</code>. Although it’s often possible to achieve <em>high accuracy</em> on the training set, as in your case, what we really want is to develop models that generalize well to <em>testing data</e...
730
tenserflow
Can we transfer model trained on one PC to another PC
https://stackoverflow.com/questions/55080843/can-we-transfer-model-trained-on-one-pc-to-another-pc
<p>I have trained cnn model on MAC using tenserflow and keras.Can I move this trained model to another PC which has windows? If Yes, then can we use that trained model for prediction whithout having tenserflow , keras installed on it?</p>
<p>You can save your trained model with <code>save()</code> method. To load again your trained model you can use the function provided by the library:</p> <pre><code>from keras.models import load_model model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' del model # deletes the existing model # returns a...
731
tenserflow
Tenserflow Keras model not accepting my python generator output
https://stackoverflow.com/questions/64682863/tenserflow-keras-model-not-accepting-my-python-generator-output
<p>I am following some tutorials on setting up my first conv NN for some image classifications.</p> <p>The tutorials load all images into memory and pass them into model.fit(). I can't do that because my data set is too large.</p> <p>I wrote this generator to &quot;drip feed&quot; preprocessed images to model.fit, but ...
<p>Converting the outputs from the generator to numpy arrays seems to have stopped the error.</p> <pre><code>np_x = np.array(batch_x) np_y = np.array(batch_y) </code></pre> <p>Seems like it didn't like the classifications as a std list of ints.</p>
732
tenserflow
ERROR: Could not install packages due to an OSError: [WinError 5]
https://stackoverflow.com/questions/68133846/error-could-not-install-packages-due-to-an-oserror-winerror-5
<p>i was trying to install tensorflow-gpu on my pycharm (<code>pip install tensorflow-gpu</code>), but unfortunately im getting a Error Message. How can i install this package on my pycharm? What is wrong here? Should i install it directly with cmd? How can I install them with pycharm? However, I was able to install th...
<p>You need to run the command prompt or terminal as an administrator. This will permit you to install packages.</p> <p>And also, you need to upgrade pip to the latest version - <code>python -m pip install --upgrade pip</code> in cmd or terminal.</p>
733