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 |
|---|---|---|---|---|---|---|
356,100 | 56,124,278 | Obtaining paths from .tfrecords file in tensorflow | <p>Is it possible to get the paths of records (data items) from .tfrecord file? For example, in order to get the total number of records, we can use <code>tf.python_io.tf_record_iterator </code>.</p>
<p><strong>For example</strong>
If I have 100 raw images and I converted them to .tfrecords format. Now I can load them... | <p>When you create a tfrecord file from a batch of images, It means that the data from these images is stored in the tfrecord file in bytes format. You can store the path of the original image to the tfrecord file e.g.:</p>
<pre><code>def image_example(image_string, label, path):
feature = {
'label': _int... | tensorflow|tfrecord | 0 |
356,101 | 56,280,621 | Apply the same operation to multiple DataFrames efficiently | <p>I have two data frames with the same columns, and similar content.</p>
<p>I'd like apply the same functions on each, without having to brute force them, or concatenate the dfs. I tried to pass the objects into nested dictionaries, but that seems more trouble than it's worth (I don't believe dataframe.to_dict suppor... | <p>If you write the filter as a function you can apply it in a list comprehension:</p>
<pre><code>def filter(df):
return df[(df['Column1']==2) & (df['Column2'].isin(['B']))]
df1, df2 = [filter(df) for df in (df1, df2)]
</code></pre> | python|pandas|loops|dataframe | 4 |
356,102 | 56,208,413 | Have anyone compiled Tensorflow_federated on Jetson TX2? | <p>Please find the logs here:</p>
<pre><code>pip install --requirement "requirements.txt"
</code></pre>
<p>This is all okay but still the source is not getting compiled</p>
<p><a href="https://devtalk.nvidia.com/default/topic/1052076/jetson-tx2/tensorflow_federated-on-tx2-/" rel="nofollow noreferrer">https://devtal... | <pre><code>jetson@jetson-desktop:~$ pip3 freeze
absl-py==0.7.1
apturl==0.5.2
asn1crypto==0.24.0
astor==0.7.1
beautifulsoup4==4.6.0
blinker==1.4
Brlapi==0.6.6
certifi==2019.3.9
chardet==3.0.4
conda==4.3.16
cryptography==2.1.4
cupshelpers==1.0
cycler==0.10.0
Cython==0.29.7
decorator==4.1.2
defer==1.0.6
distro-info===0.18... | compiler-errors|arm64|tensorflow-federated | 0 |
356,103 | 56,340,053 | How to convert Tensor to Numpy array of same dimension? | <p>I am trying to convert tensor of an image which is of shape(253,223) to numpy array of the same size so that I can plot the image. I have looked at the documentation and they suggested me to use the eval function as</p>
<pre><code>sess = tf.Session()
with sess.as_default():
print(type(tf.constant([img1]).eval())... | <p>Any tensor returned by Session.run or eval is a NumPy array.</p>
<pre><code>>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
</code></pre>
<p></p>
<p>Or:</p>
<pre><code>>>> sess = tf.InteractiveSession()
print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>
</cod... | python|tensorflow|numpy-ndarray | 1 |
356,104 | 56,127,434 | How to groupby column and return a dataFrame instead of groupby object | <p>I have a dataFrame that looks as such:</p>
<pre><code>Date Yearly_cost
2009-01-01 230
2010-03-03 260
2009-01-01 320
2007-03-02 430
</code></pre>
<p>The same dataFrame contains multiple duplicate values for Date but different values for Yearly_cost. I want to groupby Date so that I have a consistent time... | <p>Say you have the following df:</p>
<pre><code>df1 = pd.DataFrame({'Date': ['2009-01-01', '2009-01-01', '2010-03-03' , '2010-03-03', '2004-04-03' ,'2007-03-02'],
'Yearly_cost': [230 ,460, 260, 250, 320 ,430],})
df1
</code></pre>
<p>df1</p>
<pre><code> Date Yearly_cost
0 2009-01-01 230
1 2009-01-01 ... | python|pandas | 1 |
356,105 | 56,431,408 | Adding rows to DataFrame conditioned on values | <p>I have the following Pandas DataFrame:</p>
<pre><code> start_timestamp_milli end_timestamp_milli name rating
1 1555414708025 1555414723279 Valence 2
2 1555414708025 1555414723279 Arousal 6
3 1555414708025 1555414723279 Domina... | <p>You can do with filter before <code>groupby</code> <code>agg</code> + <code>all</code> , then <code>concat</code> back the result </p>
<pre><code>s=df.loc[df.name.isin(['Sadness', 'Happiness', 'Anger', 'Surprise' , 'Stress']),'rating'].\
eq(0).\
groupby([df['start_timestamp_milli'],df['end_timest... | python|pandas|dataframe|pandas-groupby | 4 |
356,106 | 56,195,797 | Efficient way to modify a column of textual data based on occurences of substrings for a large dataset? | <p>I'm looking to modify a column in a data-set which contains a comma separated listing of the genders of a group of people. So an entry could be 'male, male' or 'female, female, female, male' or just 'female'. I want to process the data so the categories are 'all male', 'all female', 'majority male', 'majority female... | <p>If i Understand you correctly - you are trying to create a new categorical feature from your column "genders".</p>
<p>The column may contain 4 values - all male, all female, majority male and majority female.
(i assume that majority male means count of males>count of females)</p>
<pre><code>def categorical_gender(... | python|pandas|numpy|machine-learning | 1 |
356,107 | 56,146,811 | How to solve issue of PendingDeprecationWarning: the matrix subclass is not the recommended way to represent matrices | <p>I am using a python code as a black box that I do not want to touch. The code was working well using Python under Ubuntu 12.04 but after upgrading the system to Ubuntu 16, I got the below warning which interrupt the code from running. Any idea how I can fix this without changing the code? Many thanks.</p>
<blockquo... | <p>With the <code>import warnings</code> module, it's possible to control the display of warnings.</p>
<p>With <code>M</code> as a sparse matrix:</p>
<pre><code>In [26]: warnings.filterwarnings('ignore', category=PendingDeprecationWarning)
In [27]: M.todense() ... | python-2.7|numpy|matrix|scipy|deprecated | 2 |
356,108 | 56,157,920 | Why isn't my data printed in the dataframe? | <p>I'm trying to make a function that will generate a dataframe/table with data about movies based on a search word from imdb. However the dataframe only shows "NaN". </p>
<p>I can see the data when I try to print it, writing:</p>
<pre><code>print(r)
</code></pre>
<p>But my data frame shows nothing. </p>
<p>My fun... | <p>Hamlet in your <code>r</code> per your comment is capitalized and in your code is not.</p> | python-3.x|pandas | 0 |
356,109 | 56,409,596 | Flatten np.ndarray in customized order | <p>I have a np.ndarray with the shape (24, 3). I want to flatten this array but in a rathor unusual way. I would like to have [0:8, 0] then [0:8, 1] then [0:8, 2] then [8:16, 0] and so on.</p>
<p>Of course i could do it the brute force way but maybe there is a more elegant and efficient solution to this problem.</p>
... | <p><a href="https://stackoverflow.com/a/47978032/"><code>Reshape, permute and reshape</code></a> -</p>
<pre><code>n = 8 # cut length along first axis
new_array = old_array.reshape(-1,n,old_array.shape[1]).swapaxes(1,2).ravel()
</code></pre> | python|numpy | 1 |
356,110 | 56,296,518 | How to bin column of floats with pandas | <p>This code was working until I upgrade my python 2.x to 3.x.
I have a df consisting of 3 columns ipk1, ipk2, ipk3.
ipk1, ipk2, ipk3 consisting of float numbers 0 - 4.0,
I would like to bin them into string. </p>
<p>The data looks something like this:</p>
<pre><code> ipk1 ipk2 ipk3 ipk4 ipk5 jk
0 ... | <p>This is a good use case for <a href="https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>pandas.cut</code></a>:</p>
<pre><code>bins = [-np.inf, 1.2, 1.6, 2.0, 2.4, 2.8, 3.2, 3.6, np.inf]
labels = ['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']
df['ipk1'] = p... | python|pandas|dataframe|binning | 5 |
356,111 | 56,193,793 | ValueError: operands could not be broadcast together with shapes (1521,) (1521,1522) () | <p>I have a large data-frame <code>df</code> where a sample of the frame is:</p>
<pre><code> A B
0 0 4140
1 0.142857 1071
2 0 1196
3 0.090909 2110
4 0.083333 1926
5 0.166667 1388
6 0 3081
7 0 1149
8 0 1600
9 0.058824 1... | <p>Your errors looks very similar when mistakenly passing dataframe to <code>np.where</code>. Could you check that you pass <code>df['A']</code> and '<code>df['B']</code>, not <code>df[['A']]</code> and '<code>df[['B']]</code>. Because passing mixing series and dataframe to np.where` will cause those errors.</p>
<p><s... | python|pandas | 1 |
356,112 | 56,394,692 | How to avoid Collection Error Python Numpy | <p>I am trying to train a Linear Regression Qualifier to continue a grap.
I have a couple of thousand lines of data in my csv file that I import into numpy arrays. Here is my code :</p>
<pre><code>import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import csv
import math
from sklearn import ... | <p>After discussion in comments:</p>
<pre><code>import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import csv
import math
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
def predict():
sample_... | python|pandas|scikit-learn|sklearn-pandas | 0 |
356,113 | 56,122,776 | How can I read and manipulate large csv files in Google Colaboratory while not using all the RAM? | <p>I am trying to import and manipulate compressed .csv files (that are each about 500MB in compressed form) in Google Colaboratory. There are 7 files. Using pandas.read_csv(), I "use all the available RAM" just after 2 files are imported and I have to restart my runtime.</p>
<p>I have searched forever on here looking... | <p>To solve my problem, I created 7 cells (one for each data file). Within each cell I read the file, manipulated it, saved what I needed, then deleted everything:</p>
<pre><code>import pandas as pd
import gc
df = pd.read_csv('Google drive path', compression = 'gzip')
filtered_df = df.query('my query condition here')... | pandas|ram|large-files|google-colaboratory | 1 |
356,114 | 56,400,511 | Iterating over matrixes in a list stopped in numpy | <p>I would like to iterate over a matrix of matrixes (indeed, sounds weird),</p>
<pre><code>import numpy as np
ar = np.array
A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]], [[1,2,3],[4,5,6],[7,8,9]], [[20,21,22],[23,24,25],[26,27,28]]])
B = np.copy(A)
C = np.copy(A)
im = np.array([A,B,C])
</c... | <pre><code>In [44]: A = np.array([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]],
...: [[1,2,3],[4,5,6],[7,8,9]], [[20,21,22],[23,24,25],[26,27,28]]])
...:
In [45]: A.shape ... | python-3.x|loops|numpy|matrix | 1 |
356,115 | 56,249,276 | why is my Keras Siamese network gives issue on sample size | <p>So basically I copied the whole keras example for Siamese network from here <a href="https://keras.io/examples/mnist_siamese/" rel="nofollow noreferrer">https://keras.io/examples/mnist_siamese/</a></p>
<p>But I have changed a few things mainly the create pair function. </p>
<pre><code>def create_pairs(datapath, di... | <p>I figured out a way around the issues.
So the new model fit is similar to what constt stated like this :</p>
<pre><code>history = model.fit([a_train, c_train], y_train,
batch_size=128,
epochs=epochs,
verbose = 1,
validation_data=([a_test, c_test], y_test))
</code></pre>
<p>The big change I ... | python|tensorflow|keras | 0 |
356,116 | 56,262,004 | how to define target variable for linear regression | <p>I want to perform regression analysis on a dataset of dimensions 96x100. The columns represent the value for number of days(100) while the independent variable is the time. How can I perform linear regression as my target variable is multiple columns. Sample dataset is as:</p>
<pre><code>time day1 day2 day... | <p>You can make time as the dependent variable(label) and Values at a different date, the features of your model(independent variable). You could use sklearn to conduct he multilevel regression quite easily:</p>
<pre><code>from sklearn.linear_model import LinearRegression
X=np.array(df.drop("time",1))
y=np.array(df["t... | python|pandas|machine-learning|scikit-learn|linear-regression | 0 |
356,117 | 56,057,490 | How to iterate over text stored in dataframe to extract in sentences and look for values within the loop? | <p>I have text stored in a Dataframe which contains many sentences. I have written a separate function where I look for certain keywords and values in a sentence and want to be able to store those values in a different column of the same Dataframe. I am having a problem when I iterate over rows of Dataframe to tokenize... | <p>Below code should meet your requirement. </p>
<pre><code>rf["Nod_size"] = ""
for i,sub_list in zip(range(len(rf)),rf['Text']):
temp = []
for sentence in sent_tokenize(sub_list):
result_calcified_nod = GetNodule(sentence)
temp.append(result_calcified_nod)
rf.loc[i]["Nod_size"] = temp
... | python|pandas|loops | 1 |
356,118 | 55,935,346 | Change stacked bar plot legend in Python | <p>I have the following data in a csv file:</p>
<pre><code>Date City TruckA TruckB TruckC TruckD
Date1 City1 1 0 0 0
Date1 City2 0 0 1 0
Date1 City3 1 0 0 0
Date1 City4 0 0 1 0
Date2 City1 1 0 0 0
Date2 City2 0 1 0 0
Date2 City3 0 0 0 1
Dat... | <p>Following @Scott's great answer you can get the stacked columns as desired.</p>
<pre><code>import matplotlib.pyplot as plt
cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
df_out = df.unstack()
d = dict(zip(df.columns.get_level_values(0),cycle))
c = df_out.columns.get_level_values(0).map(d)
g=df_out.plot.b... | python|pandas|dataframe|matplotlib | 3 |
356,119 | 55,922,431 | how to filter single column(dtype=object) in pandas on mutliple values | <p>I have a dataframe and iam trying to filter columns(dtype=object) based pandas str.contains or startswith. However when i run the code iam getting first argument must be string or compiled pattern error. how to resolve it. </p>
<p>df_ipp_h_simple_hsr = df_ipp_h_simple[df_ipp_h_simple['ORDER_TYPE'].str.startswith(('... | <p><code>pd.Series.str.contains</code> does not accept a tuple of strings as first argument (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html#pandas-series-str-contains" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.... | pandas | 0 |
356,120 | 55,845,637 | Metrics not displaying when running model.fit | <p>I am working my way through an ML example in Google Colabs. The documentation says that when I run model.fit, the loss and accuracy metrics are displayed. I am not seeing any loss or accuracy metric. </p>
<p>I have added <code>accuracy</code> as a metric in model.compile </p>
<pre class="lang-py prettyprint-overri... | <p>You can use the <a href="https://keras.io/models/sequential/" rel="nofollow noreferrer">verbose flag</a> and set it to 2 to display 1 line per epoch or 1 for a progress bar.</p> | python|tensorflow|keras|google-colaboratory | 2 |
356,121 | 55,731,824 | Reading multiple files using pandas | <p>I want to read multiple files at once.I have data in two files as below: </p>
<p><strong>data:</strong> </p>
<pre><code>123.22.21.11,sid
112.112.11.1,john
110.11.23.23,jenny
122.23.21.13,ankit
</code></pre>
<p><strong>data1:</strong> </p>
<pre><code>145.123.11.1, Joaquin
</code></pre>
<p>I tried a couple... | <p>I think it'd be easier and more readable to split it into a few steps. You also want to explicitly tell pandas that there are no headers by passing <code>header=None</code> to <code>pd.read_csv</code>.</p>
<pre><code># Get list of files
files = glob.glob(os.path.join(" ", "/home/cloudera/Desktop/sample/*"))
# Read ... | python|pandas|dataframe | 1 |
356,122 | 55,659,818 | Is there a way to perform multiple checks on columns using numpy's array indexing? | <p>I have a 2D array of data, and I'm trying to efficiently trim bad columns from this data. I'm trying to remove any columns that contain the value 0, that have an absolute difference greater than 12 between the minimum and maximum values, or that contain a value greater than 9.5.</p>
<p>The code that I have works, ... | <p>I think it's not possible to perform those three checks in a single loop.</p>
<p>You are likely to improve performance by properly ordering the trimming operations. Indeed, you should check the condition that removes the most columns first, so that the array passed to the second filter is as small as possible. The ... | python|arrays|numpy | 0 |
356,123 | 55,944,143 | Multi-class Keras perceptron classifier is classifying everything as a single class | <p>My dataset has the following shape</p>
<pre><code>[[ 1. 337. 118. ... 9.65 1. 0.92]
[ 2. 324. 107. ... 8.87 1. 0.76]
[ 3. 316. 104. ... 8. 1. 0.72]
...
[498. 330. 120. ... 9.56 1. 0.93]
[499. 312. 103. ... 8.43 0. 0.73]
[500. 327. ... | <p>Two things I would suggest first:</p>
<ol>
<li>Splitting your data in a stratified manner during the <code>train_test_split</code> to ensure your train and test sets contain a representative number of samples of all classes. This is easily implemented:</li>
</ol>
<p><code>train_X, test_X, train_Y, test_Y = train_t... | python|tensorflow|machine-learning|keras|neural-network | 1 |
356,124 | 55,986,767 | keras predicting classes method | <p>So, I have this little project going on about predicting the nba 2019 champion but it seems that my code is not clear enough to make keras understand what I want. I have passed a list of past champions on my dataset and made it the output class to get the current champion.</p>
<p>I'm using a dataset for teams stats... | <p>The <code>to_categorical</code> function is used to convert a list of class IDs to an one-hot matrix. You don't need it here. You should get the output you expect by removing in this case.</p> | python|tensorflow|machine-learning|keras|deep-learning | 0 |
356,125 | 55,729,059 | Python: How to subtract timestamps from a column and create a new TimeElapsed column? | <p>I have a couple of columns in my <code>dataframe</code> that looks like this:</p>
<pre><code>ContextID Time_ms
1 09:12:48.502
1 09:12:48.603
1 09:12:48.934
2 09:15:36.434
2 09:15:36.654
3 09:17:55.940
3 09:17:56.160
3 09:17:57.267
</code></pre>
<p>What I would like t... | <p>Subtract the result of <code>groupby</code> + <code>transform</code>:</p>
<pre><code>#df['Time_ms'] = pd.to_timedelta(df.Time_ms)
df['Time_Elapsed'] = df.Time_ms - df.groupby('ContextID').Time_ms.transform('first')
ContextID Time_ms Time_Elapsed
0 1 09:12:48.502000 00:00:00
1 ... | python|python-3.x|pandas | 3 |
356,126 | 55,669,902 | To scale the Coordinate axis using Group by in Python | <p>My Y axis includes from 0 to 2.5 million. Can I divide this number by 1000</p>
<p>How do I implement into this code?. My code is as follows. </p>
<pre><code>df.groupby('CASE_STATUS')['Index'].nunique().plot(kind='bar',fontsize=12)
</code></pre>
<p>As you can see in the picture I want to divide the Y axis with a ... | <p>isn't this enough to do the trick:</p>
<pre><code>(df.groupby('CASE_STATUS')['Index'].nunique()/1000).plot(kind='bar',fontsize=12)
</code></pre> | python|pandas | 0 |
356,127 | 55,595,188 | Count maximum consecutive occurences of a string in a dataframe column | <p>I have a panda dataframe in which I would like to count the number of consecutive occurences of a specific string in one column.</p>
<p>Let's say I have the following dataframe.</p>
<pre><code> col1
0 string1
1 string1
2 string1
3 string2
4 string3
5 string3
6 string1
</code></pre>
<p>I would like to def... | <p>Can do the usual trick of grouping consecutive values:</p>
<pre><code>df1 = df.groupby((df.col1 != df.col1.shift()).cumsum().rename(None)).col1.agg(['size', 'first'])
# size first
#1 3 string1
#2 1 string2
#3 2 string3
#4 1 string1
</code></pre>
<p>Then <code>sort_values</code> + <code>dro... | python|pandas | 3 |
356,128 | 55,676,745 | Join based on multiple complex conditions in Python | <p>I am wondering if there is a way in Python (within or outside Pandas) to do the equivalent joining as we can do in SQL on two tables based on multiple complex conditions such as value in table 1 is more than 10 less than in table 2, or only on some field in table 1 satisfying some conditions, etc.</p>
<p>This is fo... | <p>In principle, your query could be rewritten as a <code>join</code> and a filter <code>where</code> clause.</p>
<pre class="lang-sql prettyprint-override"><code>SELECT a.*, b.*
FROM Table1 AS a
JOIN Table2 AS b
ON a.id = b.id
WHERE a.sales - b.sales > 10 AND a.country IN ('US', 'MX', 'GB', 'CA')
</code></pre>
<... | python|sql|pandas|join|merge | 1 |
356,129 | 55,702,459 | How to update the variable in tf.variable_scope with variable's name? | <p>I want to modification the value about variable 'weight1' in tf.variable_scope.</p>
<p>I try to modification the value by other function, but it not work follow me.</p>
<pre><code>def inference(q, reuse=False):
with tf.variable_scope('layer1', reuse = reuse):
x = tf.get_variable('weight1', [1, 3], init... | <p>You need to run <code>sess.run(update)</code> in <code>update_process</code> in the same session that the <code>inference</code> part of the graph runs:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
def inference(q, reuse=False):
with tf.variable_scope('layer1', reuse = reuse):
... | tensorflow|scope | 0 |
356,130 | 55,861,743 | Converting dataframe to dict using groupby | <p>I have a dataframe </p>
<pre><code>df = pd.DataFrame({'a':[1,1,1,2,2,3], 'b':['a','a','a','b','b','c'],
'c':['qw','sw','aw','ew','rw','qw'],'d':['cv','fv','gv','bv','nb','fv']})
</code></pre>
<p>I want to convert it into <code>dict</code> like below:</p>
<pre><code>{
{'a':1,'b':'a', 'xyz':[{'c... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>DataFrame.to_dict</code></a> with <code>records</code>:</p>
<pre><code>df1 = (df.groupby(['a','b'])['c','d']
.apply(lambda x: x.to_dict(orient='records'))
... | python|python-3.x|pandas | 3 |
356,131 | 56,002,847 | How can I identify for multi condition by pandas.factorize? | <p>I read <a href="https://stackoverflow.com/questions/36646923/in-pandas-how-to-create-a-unique-id-based-on-the-combination-of-many-columns">this</a> which is talking about pd.factorize to identify and create the unique value for the user identify.</p>
<p>However, in my case, I would like to apply the multi condition... | <p>IIUC, you can do:</p>
<pre><code>df['unique_id']=df.apply(lambda x: pd.factorize(x)[0]+1).min(axis=1)
print(df)
</code></pre>
<hr>
<pre><code> cond_1(email) cond_2(phone) cond_3(other) unique_id
0 abc@yahoo.com 12345678 qwe 1
1 asd@yahoo.com 789456123 rty ... | python|pandas|dataframe|uniqueidentifier | 1 |
356,132 | 55,835,540 | Tabulate deeply nested MongoDB collection using PyMongo | <p>I am querying a collection using <strong>pymongo</strong>:</p>
<pre><code>import pymongo
client = pymongo.MongoClient('0.0.0.0', 27017)
db = client.documents
collection = db.collections
test_data = collection.find_one({'metadata.encodingStage.terms.data.line.data.account.shortDescription': {'$exists': True}},
{'m... | <p><strong>Solution</strong></p>
<p>First problem with my logic was that <code>line</code> was an array, so needed to be unwound first.</p>
<p>Combining that with two <code>$project</code> steps and a final <code>$unwind</code> on the leaf array flattens out the data to give <code>(_id, shortDescription)</code> pairs... | python|mongodb|pandas|pymongo | 0 |
356,133 | 55,770,768 | Drop and Head Giving AttributeError When Reading from Excel | <p>I am trying to import many sheets into the python and use pandas to do the data wrangling.</p>
<p>I tried to use the <code>drop()</code> function to delete the first row of the first sheet. Here is the code I'm using in my Jupyter notebook:</p>
<pre><code>data = pd.read_excel('dataset.xlsx', sheet_name = ['Table1'... | <p>The reason is simple: you passed a <code>list</code> to <code>read_excel</code>.</p>
<p>When you do that, even a <code>list</code> with one element, <code>pandas</code> will return an <code>OrderedDict</code> containing one <code>DataFrame</code> for each sheet.</p>
<p>Do <code>data = pd.read_excel('dataset.xlsx',... | python|pandas|dataframe | 0 |
356,134 | 55,917,297 | How to use a tensorflow-lite model in tensorflow for java | <p>Is it possible to load tensorflow lite models with tensorflow for java?</p>
<p>I've testet the <code>SavedModleBundle</code> and <code>org.tensorflow.Graph.importGraphDef</code>
but it doesnt work.</p>
<p>By loading the GraphDef there is a <code>java.lang.IllegalArgumentException: Invalid GraphDef</code> exceptio... | <p>To use tensorflow model on standalone java(not in android), you have to use <code>SavedModleBundle</code> and you need to compile with java compiler as described <a href="https://www.tensorflow.org/install/lang_java#tensorflow_with_the_jdk" rel="nofollow noreferrer">here</a>. For that you need TensorFlow Jar Archiv... | tensorflow|tensorflow-lite | 2 |
356,135 | 55,820,934 | print out two or more dataframes in jupyter (python) side by side | <p>I'm trying print two or more dataframe in the output of jupyter notebook cell using Python. Actually I am using a function from Wes Mckinney that perform this work but the dataframes don't have headers. I would like that each table has title specifying the name of each table, of course. I need a function similar to ... | <p>Jupyter is just the interpreter for python. So you don’t need to do anything special other than format the python output, like what’s done in this post: <a href="https://stackoverflow.com/questions/42818361/how-to-make-two-plots-side-by-side-using-python">How to make two plots side-by-side using Python</a></p>
<p>O... | python|html|pandas|printing | 0 |
356,136 | 55,621,322 | Why is torch.nn.Sigmoid a class instead of a method? | <p>I'm trying to understand how pytorch works a little bit better. Usually, when defining a neural network class, in the <strong>init</strong>() constructor, people write self.sigmoid = nn.Sigmoid(), so that in the forward() method they can call the sigmoid function multiple times with having to reinstantiate nn.Sigmoi... | <p>Sigmoid is available as both a module <a href="https://pytorch.org/docs/stable/nn.html#sigmoid" rel="noreferrer"><code>torch.nn.Sigmoid</code></a> and a function <a href="https://pytorch.org/docs/stable/torch.html#torch.sigmoid" rel="noreferrer"><code>torch.sigmoid</code></a>. The two are equivalent: the module is j... | python|pytorch | 5 |
356,137 | 55,580,836 | How to use the saved model in tensorflow | <p>First, I tried to restore the model as people instructed, but I could not find any clues yet.
Following is my code to save the model and model was successfully saved. </p>
<pre><code>import tensorflow as tf
from sklearn.utils import shuffle
EPOCHS = 10
BATCH_SIZE = 128
x = tf.placeholder(tf.float32, (None, 32, 32... | <p>In short, I suggest using <code>tf.data</code> and <code>tf.saved_model</code> APIs. There are 2 mechanisms: <code>tf.train.Saver()</code> or a higher level API <code>tf.saved_model</code> based on the previous one. Differences you can find in other posts <a href="https://stackoverflow.com/questions/46513923/tensorf... | python|tensorflow|neural-network | 0 |
356,138 | 55,797,448 | pandas map a series to another series by 2 columns of a dataframe | <p>Let's say I have a dataframe with 2 columns:</p>
<pre><code>indexes = pd.Series(np.arange(10))
np.random.seed(seed=42)
values = pd.Series(np.random.normal(size=10))
df = pd.DataFrame({"unique_col": indexes, "value": values})
# df:
unique_col value
0 0 0.496714
1 1 -0.138264
2 ... | <p>Is this what you need ?</p>
<pre><code>s=df.set_index('unique_col').value.reindex(uniq).values
pd.Series(s,index=uniq.index)
Out[147]:
20 -0.138264
45 1.523030
47 -0.234137
51 1.579213
dtype: float64
</code></pre> | python|pandas|merge | 3 |
356,139 | 55,710,929 | Input dimension mismatch between dense layers and conv layers of imagenet while attempting transfer learning | <p>I am trying to train dense layers on top of the conv layers of InceptionV3.
But I'm unable to initialize the fully connected model. I'm getting a ValueError.</p>
<pre><code>model_inc = applications.InceptionV3(weights='imagenet',
include_top=False)
model = Sequential()
model.a... | <p>You want your input to go to your <code>model_inc</code> so you have to define the <code>input_shape</code> there. Something like the following should work</p>
<pre><code>model_inc = applications.InceptionV3(input_shape=(224,224,3), weights='imagenet',
include_top=False)
model ... | tensorflow|keras|transfer-learning|imagenet | 0 |
356,140 | 55,697,546 | Need to use functionality of iLoc, but for Dictionary values (text) | <p>I am trying to make an API call that pulls the value of a column within a spreadsheet and sends it as a param within the API call. </p>
<p>I've done this successfully before with this code, but that was for integer values. Now I need to do it with text and they are stored as Dict values which give me an error. </p>... | <p>The code has <code>params</code> in an extra set of braces.</p>
<p>This is interpreted as a dict.</p>
<p>You don't want that.</p>
<p>You'll want to remove the extra braces like this:</p>
<pre><code>for i in range(10):
r = requests.post(
url = "DummyAPIEndpoint",
headers = {
'Auth... | python|pandas|dictionary | 0 |
356,141 | 55,698,466 | Pivoting (reshaping) a pandas dataframe in alphabetical case-insensitive order | <p>I have a dataframe with 3 columns: variable1, variable2, value.
value is measured from all possible combinations of variable1 and variable2 (all-against-all). Also, variable1 and variable2 have the same names. When reshaping my dataframe using the built-in pivot function, this is not done in a certain order.</p>
<p... | <p>If I understand you correctly. </p>
<pre><code>result = pd.pivot_table(df, values='value', index='var1',
columns='var2', aggfunc=lambda x: x)
result.fillna('')
var2 A B C D E F G H
var1 ... | python|pandas|dataframe|pivot-table|reshape | 0 |
356,142 | 55,880,412 | How to use row name to sort when it has () in its body? | <p>I'm not able to sort the values as the row label contains brackets().</p>
<p>I'm not sure if my code is correct. I've tried to rename, maybe my code was not correct.</p>
<pre><code>GSDP_plot = GSDP_plot.set_index('Item')
GSDP_plot = GSDP_plot.sort_values(by='Per Capita GSDP (Rs.)', ascending=False)
</code></pre>
... | <p>Firstly, make sure that the 'by' value is presented in your dataframe in rows or in columns depending on the axis parameter. It must be exact value (with parentheses).</p>
<p>As far as I've understood you need to sort columns by values in them for a row.
There's a serveral ways by which you can achieve that.</p>
... | pandas|data-science | 1 |
356,143 | 55,763,069 | why won't these matrices broadcast together? ValueError: operands could not be broadcast together with shapes (5,2) (2,1) | <p>I'm trying to setup back propagation for my neural network using numpy, but for some reason when I'm setting up the gradient decent equation for the matrix that holds my output weights, two of the matrix's (2,5)(5,1) in the gradient decent equation are not broadcasting together. Am I doing this wrong?</p>
<p>I've tr... | <p>With a matrix product, <code>dot</code>, the rule is <code>last dim of A pairs with 2nd to the last dim of B</code>:</p>
<pre><code>In [136]: x=np.arange(10).reshape(5,2); y=np.arange(2)[:,None]
In [137]: x.shape, y.shape
Out[137]: ((... | python|python-3.x|numpy | 0 |
356,144 | 55,851,950 | How to see if value in column X is also in column Y and return True/False? | <p>I'm trying to get python to loop through all of the rows in my pandas dataframe.x column and return True if this value is anywhere in the dataframe.y column. </p>
<p>I've already tried to do it like this, but it isn't working.</p>
<pre><code>#Create a column for storage
df["y_exists"] = ""
#Here is a loop that al... | <p>You are looking for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html" rel="nofollow noreferrer">pandas.DataFrame.isin</a>. </p>
<p>However, you shouldn't loop but use vectorization instead, as it is more efficient, like this:</p>
<pre><code>df['exists_in_y']=df['x'].is... | python|pandas | 4 |
356,145 | 55,728,056 | Resample Pandas dataframe not valid | <p>I try to import a .csv 30-minutes-timeseries file with pandas to resample it to hours but the resample function doesn't recognise the datetime format.</p>
<ol>
<li>Import works correct with a script found on stackoverflow.</li>
<li>When I open the Dataframe and double-click on a date+time it mentions that I can't e... | <p>Set the index of the dataframe to the <code>datetime</code> column first, convert it to a datetime index, and it should work.</p>
<pre><code>def dateparse(d,t):
dt = d + " " + t
return pd.datetime.strptime(dt, '%d/%m/%Y %H:%M:%S')
df = pd.read_csv(infile, parse_dates={'datetime': ['date', 'time']}, date_par... | python|pandas|csv|datetime | 0 |
356,146 | 55,590,974 | How to find the most similar item from within a set to my test item depending on certain criteria? | <p>I have a dataset of a group of players and various stats. Here's a sample of the file.</p>
<pre><code> name nat tm age pos cm kg app \
0 Héctor Bellerín Arsenal es 21 D(R),M(R) 177 74 36
1 Mathieu Debuchy Arsenal fr 31 D(R) 177 ... | <p>each player here is a vector, you can perform any vector similarity </p>
<p>Euclidean Distance for your problem,</p>
<pre><code>player = tac + int + blcks + unsT + cOff + spG
distance(player_1, player_2) = sqrt (sqr(tac_1-tac_2) + sqr(int_1-int_2) + .....)
</code></pre> | python-3.x|pandas|grouping|similarity | 1 |
356,147 | 55,711,496 | Upper triangular kernel initializer in Keras | <p>I wonder if there is a kernel initializer in Keras that initializes the kernel with random values, except that the low-left values are initialized as zeros. I want to use that in a custom Keras layer in add_weights method. Or maybe a reliable TensorFlow operation? Thank you!</p> | <h1>Methods:</h1>
<p>You can define your own initializer. And use the <code>np.triu()</code> to create an upper triangular kernel.</p>
<h1>A small example:</h1>
<pre><code>from tensorflow.keras import layers
import tensorflow as tf
import numpy as np
def my_init(shape, dtype=None):
init = tf.random_normal(shape,... | python-3.x|tensorflow|keras | 1 |
356,148 | 55,634,848 | replace numpy array elements with a value between 0 and 1 | <p>I've got a very simple task and numpy is doing something I don't understand. I'm trying to replace elements of an array that meet some criteria with a number between 0 and 1, and numpy is converting them all into zeroes. For example:</p>
<pre><code>In [1]: some_array = np.array([0,0,0,1,0,1,1,1,0])
In [2]: nonzero... | <pre><code>some_array = np.array([0,0,0,1,0,1,1,1,0]).astype(float)
</code></pre>
<p>Using numpy array as a float will solve your issue. By default it seems its integer and just shovel down the value to zero.</p>
<pre><code>nonzero_idxs = np.where(some_array != 0)[0]
some_array[nonzero_idxs] = 0.2
# output: array([0... | python|arrays|numpy | 5 |
356,149 | 55,678,047 | In attempting to combine two arays I have a type problem in numpy | <p>When I attempt:</p>
<pre><code>data_f = hstack([data,Ki])
</code></pre>
<p>I get: </p>
<blockquote>
<p>TypeError: 'list' object is not callable.</p>
</blockquote>
<p>I have 'googled' in vain without result. What have I missed?</p>
<p>I have successfully created the two arrays I want to combine:</p>
<pre><cod... | <p>Please <a href="https://numpy.readthedocs.io/en/latest/reference/generated/numpy.hstack.html#numpy.hstack" rel="nofollow noreferrer">Read The Fine Manual</a>,
where they clearly explain that <code>hstack()</code> wants
a tuple of ndarrays of similar shape.
You're not supplying that.</p>
<p>Carefully examine <code>d... | python|python-3.x|numpy | 1 |
356,150 | 55,578,378 | How to exchange Msgpack files between Python and R? | <p>Consider this simple example</p>
<pre><code>import pandas as pd
mydata = pd.DataFrame({'mytime': [pd.to_datetime('2018-01-01 10:00:00.513'),
pd.to_datetime('2018-01-03 10:00:00.513')],
'myvariable': [1,2],
'mystring': ['hello', 'world']})
... | <p>How about you use <code>library(reticulate)</code> in R:</p>
<pre><code>library(reticulate)
pyData = py_run_string("import pandas as pd
mydata = pd.DataFrame({'mytime': [pd.to_datetime('2018-01-01 10:00:00.513'),
pd.to_datetime('2018-01-03 10:00:00.513')],
'myva... | python|r|pandas|tibble|msgpack | 1 |
356,151 | 55,612,557 | Can you replicate tf.random_crop in TensorFlow JS efficiently? | <p>Random cropping is not implemented in TensorFlow JS, but is it possible to replicate it? My idea was to use Tensor.slice() with tensors generated from tf.randomUniform as parameters, but it only accepts "numbers". So it seems to me, that in order to get random cropping working, I'd have to reconstruct that part of t... | <p><a href="https://js.tensorflow.org/api/latest/#slice" rel="nofollow noreferrer">slice</a> will allow to slice or crop a part of the input. Using <a href="https://js.tensorflow.org/api/latest/#gatherND" rel="nofollow noreferrer">gatherND</a> will allow on the other hand to slice multiples times if one wants to avoid ... | javascript|tensorflow|tensorflow.js | 0 |
356,152 | 55,659,821 | In pandas or numpy can we set a flag on row to do vectorization and use it for next row calculations | <p>I am new to python but have been in the programming world for a while. I have already tried to do the following with if else loop using python dataframes and <code>iloc</code> and was successful. I want to use vectorization. The problem is that once a data changes its state based upon <em>rule 1 (b < a)</em> I wa... | <p>My for loop solution was very slow. Here it is a proper vector solution, this works. Very fast.</p>
<pre><code>mask1 = df['b'] < df['a']
mask2 = df['c'] < df['a']
mask3 = (mask1 == False) & (mask2 == False)
</code></pre>
<p>This True/False flag changes when mask1 mask3 alternate.</p>
<pre><code>df.loc[m... | python|pandas|numpy|vectorization | 0 |
356,153 | 64,957,777 | LSTM error - 'logits and labels must have the same shape' | <p>I have searched the other threads on the here regarding the error, but am unable to figure out the issue. I am trying to create an LSTM using a toy dataset with two predictors and three outcomes, setting the output layer to sigmoid such that each outcome label is afford a probability between 0-1. My code:</p>
<pre><... | <h1>Fixing the 'same shape' issue</h1>
<p>I think you want to change your model to this</p>
<pre><code>#create LSTM
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(6, input_shape=(3,2)),
tf.keras.layers.LSTM(12, return_sequences=True),
tf.keras.layers.Dense(3, activation='sigmoid')
])
</code></pr... | tensorflow|lstm | 1 |
356,154 | 64,805,903 | Pool performance for a simple linear regression model trained by TensorFlow2 | <p>My model as simple as <code>y = 2*x + 200 + error</code>, but I cannot get proper result in a simple way. I don't know what happened.</p>
<pre><code>import numpy as np
from tensorflow import keras
x = np.arange(100)
error = np.random.rand(100,1).ravel()
y = 2*x + 200 + error
opt = keras.optimizers.Adam(lr=0.0005)
m... | <p>I got it, the main problem is that <code>EarlyStopping</code> stopped my training process too early! Another problem is learning rate is too small.</p>
<p>So when I changed two paremeter setting, I got proper result:</p>
<pre><code>import numpy as np
from tensorflow import keras
x = np.arange(100)
error = np.random.... | tensorflow|linear-regression|tensorflow2.0 | 1 |
356,155 | 64,931,183 | parse information from list of dics to Series level | <p>as result of SQL request to PostgreSQL database, I have dataframe:
<a href="https://i.stack.imgur.com/QKRRn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QKRRn.png" alt="enter image description here" /></a></p>
<p>my_table['receipt'] has following structure:</p>
<pre><code>{'id': '272f9730-000f-... | <p>You could apply a lambda function to the column with the dictionaries to extract the relevant value:</p>
<pre><code>df = pd.DataFrame({'a':[{'foo':1, 'bar':2}, {'foo':5, 'bar':6}]})
# a
# 0 {'foo': 1, 'bar': 2}
# 1 {'foo': 5, 'bar': 6}
# If you only want a single column with a particular key from the dic... | python|pandas|list | 1 |
356,156 | 64,858,911 | Categories in Python with Pandas (special case) | <p>I have some data and want to build some categories.</p>
<p>Now, the data looks like this:</p>
<pre><code>Var Category
a cat1
a cat1
b cat2
a cat1
b cat2
a cat1
</code></pre>
<p>But it should look like this:</p>
<pre><code>Var Category
a cat1
a ... | <p>You can compare for not equal and then add cumulative sum by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>Series.cumsum</code></a>, add <code>1</code> if necessary, convert to strings and add to <code>cat</code>:</p>
<pre><code>df['Cate... | python|pandas|dataframe|categories | 0 |
356,157 | 64,978,108 | Find the smallest value in row and store it | <pre><code>+----+-------+-------+-------+--+
| ID | Test1 | Test2 | Test3 | |
+----+-------+-------+-------+--+
| 1 | 2 | 3 | 4 | |
+----+-------+-------+-------+--+
| 2 | 2 | 3 | 1 | |
+----+-------+-------+-------+--+
| 3 | 1 | 5 | 7 | |
+----+-------+-------+-------+--+
</c... | <p>We can get the <code>min</code> value over each row <code>axis=1</code>. Then we check on each row which value is equal to this with <code>.eq(axis=0)</code>. Then we use <code>where</code> to convert all other values to <code>0</code>:</p>
<pre><code>df = df.set_index('ID')
mask = df.eq(df.min(axis=1), axis=0)
df.... | python|pandas|dataframe | 1 |
356,158 | 64,918,556 | Pandas - Add many new columns based on many aggregate functions | <p>Pandas 1.0.5</p>
<pre><code>import pandas as pd
d = pd.DataFrame({
"card_id": [1, 1, 2, 2, 1, 1, 2, 2],
"day": [1, 1, 1, 1, 2, 2, 2, 2],
"amount": [1, 2, 10, 20, 3, 4, 30, 40]
})
#add columns
d['count'] = d.groupby(['card_id', 'day'])["amount"].transform('count'... | <p>Use merge,</p>
<pre><code>d = pd.DataFrame({
"card_id": [1, 1, 2, 2, 1, 1, 2, 2],
"day": [1, 1, 1, 1, 2, 2, 2, 2],
"amount": [1, 2, 10, 20, 3, 4, 30, 40]
})
df_out = d.groupby(['card_id', 'day']).agg(
count = pd.NamedAgg('amount', 'count')
,min = pd.NamedAgg('amou... | pandas|pandas-groupby | 2 |
356,159 | 64,811,841 | Tensorflow 1.15 + CUDA + cuDNN installation using Conda | <p>I am trying to install tensorflow-gpu 1.15 using Conda for an easy install of CUDA and cuDNN. The problem is that checking the <a href="https://www.tensorflow.org/install/source#configuration_options" rel="noreferrer">compatibility chart</a> of the official web I need python 3.6, CUDA 10.0 and cuDNN 7.4.</p>
<p>Sear... | <p>I am not sure if that is the problem, but I installed the following way</p>
<pre><code>conda create -n tensorflow1.15 python=3.5
conda activate tensorflow1.15
conda install cudatoolkit=10.0
conda install cudnn=7.3.1
pip3 install tensorflow-gpu==1.15
</code></pre>
<p>And it seems to works perfectly with the GPU. I di... | tensorflow|conda|miniconda | 15 |
356,160 | 64,962,547 | Converting CSV file data into federated data | <p>I am trying to convert my CSV dataset into a federated data. Please find the code and the error I am getting while I am running my code</p>
<p>code: import collections</p>
<pre><code>import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_federated as tff
np.random.seed(0)
df = pd.read_csv(... | <p>Python cannot find the <code>sample</code> function. The code will need to import it from somewhere, a few possible options:</p>
<ul>
<li><a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow noreferrer"><code>random.sample</code></a></li>
<li><a href="https://docs.scipy.org/doc/numpy-1... | python|pandas|tensorflow|tensorflow-federated|federated-learning | 2 |
356,161 | 64,938,669 | Replace rows with different number of characters | <p>I have a column having strings of different number of characters. Most of rows have the following number of characters:</p>
<pre><code>xx.xx.xxxx xx-xx-xx
</code></pre>
<p>but there are also rows having different number, for instance</p>
<pre><code>xxx.xxx.xxxx
xxxx
xxxxxxxxxxxxxxx
</code></pre>
<p>I would like to r... | <p>Try with <code>loc</code></p>
<pre><code>df.loc[df['Char'].str.len()!=len('xx.xx.xxxx xx-xx-xx'),'Char']=np.nan
</code></pre> | python|pandas | 2 |
356,162 | 64,713,096 | How does my output show real column headers INSTEAD OF AUTO INCREMENT NUMBERS | <p>How does my output show real column headers instead of auto increment numbers.
<img src="https://i.stack.imgur.com/L3UId.jpg" alt="" /></p>
<pre><code>mydb = mysql.connector.connect(
host="***************",
user="****",
password="****")
mycursor = mydb.cursor()
que... | <p>You need to create the cursor so it can return the dictionary object instead:</p>
<pre><code>mycursor = mydb.cursor(dictionary=True)
</code></pre> | python|pandas|dataframe|mysql-python | 1 |
356,163 | 64,626,654 | How to melt the pd.DataFrame to organize the data? (toy example included) | <h2>Issue</h2>
<ul>
<li>I am curious to know how to melt the <code>data_df</code> in the toy example provided below to the <code>desired_df</code>.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
data_df = pd.DataFrame(data = [['FR','Aug',100], ['FR','Sep',170], ['FR','Oct',250],
... | <p>Try <code>pivot</code>:</p>
<pre><code>data = data_df.pivot(index = 'time', columns = 'country')
print(data)
</code></pre>
<p>Which gives:</p>
<pre><code>country FR KR US
time
Aug 100 9 360
Oct 250 19 700
Sep 170 12 500
</code></pre>
<p>The indices are in al... | python|pandas|dataframe|pivot|melt | 2 |
356,164 | 65,015,242 | Pandas: Groupby count as column value | <p>I have a pandas dataframe that looks like this:</p>
<p><img src="https://i.stack.imgur.com/H7oqI.png" alt="enter image description here" /></p>
<p>I would like to generate counts instances of 'x' (regardless of whether they're unique, or not) per 'id'. The result would be insert as a column labeled 'x_count' as show... | <p>Simply a groupby with transform <code>count</code></p>
<pre><code>df['x_count'] = df.groupby('id')['x'].transform('count')
</code></pre>
<p>If you also want to count the <code>NaN</code>, use `size'</p>
<pre><code>df['x_count'] = df.groupby('id')['x'].transform('size')
</code></pre> | python|pandas|dataframe | 2 |
356,165 | 64,817,724 | pandas df to JSON with duplicate keys | <p>I am trying to convert a <code>df</code> with unique keys to a <code>JSON</code> file. The <code>pandas dataframe</code> looks like the below.</p>
<pre><code>import pandas as pd
d = {'col1': [1,2,2,2,3,3], 'col2': ['a','b','c','','e','f'], 'col3': ['one','two','three','four','five','six']}
df = pd.DataFrame(data=d... | <p>First create nested lists by convert <code>col1</code> to index, group by index values and all columns convert to <code>list</code>s in lambda function, last convert <code>Series</code> to dictionary by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_dict.html" rel="nofollow nore... | json|python-3.x|pandas|duplicates | 1 |
356,166 | 64,850,376 | Assign int to strings in a column of lists in pandas | <p>I have a Pandas dataframe that contains a column with lists of strings.</p>
<pre><code>>>> df.head()
genre
0 [Comedy, Supernatural, Romance]
1 [Comedy, Parody, Romance]
2 [Comedy]
3 [Comedy, Drama, Romance, Fantasy]
4 [Comedy, Drama, Romance]
</code></pre>
<p>How could I go about assignin... | <p>The complication here is we're dealing with a column of lists. We can improve performance a bit by exploding the rows first. Then use <code>factorize</code> and return to the original format:</p>
<pre><code>v = df['genre'].explode()
v[:] = pd.factorize(v)[0] + 1
df['genre2'] = v.groupby(level=0).agg(list)
df
... | python|pandas | 3 |
356,167 | 65,035,334 | How to split a 2D numpy array directly into numpy array of objects | <p>For a special application dealing with numpy arrays of different lengths, I need my preferably numpy array, <strong>not just a list</strong>, to have the form <code>np.ndarray[np.ndarray[ ], np.ndarray[ ], ..., dtype=object]</code>. If I have given sequence, list, etc. of <code>numpy</code> arrays, I want them alway... | <p><code>np.array(...)</code> by design tries to return as high a dimensional numeric array as possible. If the inputs are ragged it will raise a future-warning (unless you specify <code>object</code> dtype) and return the object array containing arrays. Or with some combinations of shapes it will raise an error.</p>... | python|arrays|numpy | 0 |
356,168 | 64,802,257 | Pandas get max of sequence | <p>I have a dataframe that looks as follows:</p>
<pre><code>index status counting
2018-02-11 10:00:00 close 0
2018-02-11 10:00:01 close 0
2018-02-11 10:00:02 close 0
2018-02-11 10:00:03 open 1
2018-02-11 10:00:04 open 2
2018-02-11 10:00:05 open 3
2018-02-11 10:0... | <p>You can compare values by <code>open</code>, then invert mask by <code>~</code> with cumulative sum for groups and filter only <code>open</code> rows, last pass to <code>groupby</code>:</p>
<pre><code>m = df['status'].eq('open')
s = df.groupby((~m).cumsum()[m])['counting'].max()
print (s)
status
3.0 3
6.0 6
N... | pandas|dataframe|time|timestamp | 2 |
356,169 | 64,748,103 | Not enough disk space when loading dataset with TFDS | <p>I was implementing a DCGAN application based on the lsun-bedroom dataset. I was planning to utilize tfds, since lsun was on its <a href="https://www.tensorflow.org/datasets/catalog/lsun?hl=en" rel="nofollow noreferrer">catalog</a>. Since the total dataset contains 42.7 GB of images, I only wanted to load a portion(1... | <p>TFDS download the dataset from the original author website. As the datasets are often published as monolithic archive (e.g <code>lsun.zip</code>), it is unfortunately
impossible for TFDS to only download/install part of the dataset.</p>
<p>The split argument only filter the dataset after it has been fully generated.... | tensorflow|large-data | 2 |
356,170 | 64,877,137 | Pandas total count each day | <p>I have a large dataset (df) with lots of columns and I am trying to get the total number of each day.</p>
<pre><code> |datetime|id|col3|col4|col...
1 |11-11-2020|7|col3|col4|col...
2 |10-11-2020|5|col3|col4|col...
3 |09-11-2020|5|col3|col4|col...
4 |10-11-2020|4|col3|col4|col...
5 |10-11-2020|4|col3|col... | <p>try this:</p>
<pre><code>df = df.groupby(['datetime','id','col3']).count()
</code></pre> | python|pandas|dataframe | 1 |
356,171 | 64,914,293 | Bin data based on ranges of borders | <p>I have the following two dataframes:</p>
<p><code>borders</code></p>
<pre><code>start end
25000 30000
85000 90000
105000 110000
</code></pre>
<p>... this specifies start & end of borders.</p>
<p><code>to_bin</code></p>
<pre><code>start end
3676 4686
24943 25902
25010 26000
29000 31000
51174 52100
54224 54... | <p>Define functions:</p>
<ol>
<li><p><em>getBin</em> to get bin definition from a row of (a little changed) <em>borders</em>:</p>
<pre><code>def getBin(row):
return pd.Series([pd.Interval(row.stPrev, row.start, closed='neither'),
'bin_' + str(row.name + 1)], index=['Range', 'label'])
</code></pre>
<p>Detail... | python|pandas | 2 |
356,172 | 64,844,412 | Concatenate two pandas dataframes on a new axis | <p>I have two pandas dataframes both with shape <code>(d, w)</code> , I need to concatenate these two into a new dataframe with shape <code>(2, d, w)</code> (or even <code>(d, 2, w)</code>). A naive way to do this is by <a href="https://stackoverflow.com/questions/22963263/creating-a-zero-filled-pandas-data-frame">crea... | <p>DataFrames are inherently two dimensional. It is possible to use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Panel.html" rel="nofollow noreferrer">Panels</a> for 3d data, but they are deprecated and should not be used at this point. The Pandas docs recommend using <a href="https://... | python|pandas|dataframe | 2 |
356,173 | 64,918,360 | What is the more efficient way to create a pairwise 2D array for a 1D numpy array? | <p>Given 2 numPy arrays of length N, I would like to create a pairwise 2D array (N x N) based on a custom function.</p>
<pre><code> import numpy as np
import pandas as pd
A = np.array(A) # size N
B = np.array(B) # size N
Fij = f(A[i], B[i], A[j], B[j])
# f is a pairwise function of Ai, ... | <p>If you aren't able to break up the guts of your function, you can do something like this:</p>
<pre><code>import numpy as np
from itertools import product
A = [1,2,3,4]
B = ['a', 'b', 'c', 'd']
N = len(A)
def f(i,j):
return str(A[i] + A[j]) + B[i] + B[j]
arr = np.array([f(i,j) for i, j in product(range(N), ran... | python|arrays|numpy|pairwise | 0 |
356,174 | 64,801,199 | How to create and access several datasets in pyQt5 GUI on python? | <p>I have some trouble with my PyQt5 GUI code. What I would like to do is asking the user for a file using the actionLoad_file menu. I would like then to import the datasets using my LoadFile function located in another file. The issue is that I don't know how to assign the name of the file selected by the user to the ... | <p>I'm not sure why you are using a <code>tkinter</code> file dialog when <code>Qt</code> has a perfectly serviceable file dialog built in.</p>
<p>Anyway, as I understand the question, you want to be able to read multiple files, create data frames from the data in these files and store the file names in what I assume i... | python|pandas|pyqt5 | 1 |
356,175 | 64,826,735 | Pandas - write dataframe in fixed-width formatted lines to a file | <p>Have a huge pandas dataframe (df) like this:</p>
<pre><code> id date a b c
0 0023 201110132120 -30 -45 7
1 0023 201110132130 -30 11 9111
2 0023 201110132140 -24 44 345
3 0023 201110132150 -19 223 11
4 0023 201110132200 ... | <p>One option is to abuse <code>header</code> option in <code>savetxt</code>:</p>
<pre><code>formats = '%+4s %+12s %+5s %+5s %+6s'
headers = [format(str(x),y.replace('%+','>'))
for x, y in zip(df.columns,formats.split())]
np.savetxt('out.txt', df.values, fmt=formats,
header=' '.join(heade... | python|python-3.x|pandas|numpy|dataframe | 2 |
356,176 | 64,834,668 | Could not find a Profile button in tensorboard after install profile-plugin | <p>Tensorboard version: 2.3.0</p>
<p>before I install profile-plugin on Tensorboard:</p>
<p><a href="https://i.stack.imgur.com/vZYMv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vZYMv.png" alt="enter image description here" /></a></p>
<p>so I followed that order:</p>
<pre class="lang-sh prettyprin... | <h1>Problem Analysis</h1>
<p>Your problem sounds like you are using a <strong>virtual environment</strong>. Probably, you mixed up package installations within and outside of the environment.</p>
<p>For instance, you might have installed TensorBoard and the plugin in the virtual environment, but forgot activating the e... | pip|tensorflow2.0|tensorboard|profile | 1 |
356,177 | 64,732,830 | Python CSV Add Numbers to Empty Cells | <p>Python 3.8. I've a CSV file with 12,000 rows and 4 columns. One column has over 4000 blank cells in various places. Starting at the top, I need to place a sequential number in each blank cell starting at 1.</p>
<p><strong>Existing</strong>:</p>
<pre><code>First,Sec,Third,Fourth
R,E,C,D
S,F,C,D
blank,S,C,D
V,G,C,D
bl... | <p>Its easier to use pandas and process the df then you can save the processed df:</p>
<pre><code>import pandas as pd
df = pd.read_csv('Original.csv')
Start_Number = 1
for i,row in df.iterrows():
if pd.isnull(row['Data ID']):
df.loc[i,'Data ID'] = Start_Number;
Start_Number +=1
df.to_csv('New.csv... | python|pandas|csv | 2 |
356,178 | 64,951,181 | Change price format from dot (.) to Comma (,) in python | <p>Iam using python's pandas dataframe to create a csv from a txt file.
This txt file has a price in dot format eg 23.45</p>
<p>In my csv I want the out in comma format, like 23,45.</p>
<p>I tried the following but failed to achieve the end result:</p>
<ol>
<li>Replace the particular column's (.) to (,)
-> Result: ... | <p>Try this, You almost got it. Just had to convert the <code>float</code> to <code>str</code> and then apply <code>str.replace</code>.</p>
<pre><code>df['price'] = df['price'].astype(str).str.replace('.',',')
</code></pre>
<p>Input:</p>
<pre><code> price
0 20.12
1 10.12
2 34.12
3 35.43
</code></pre>
<p>Output (A... | python|pandas | 1 |
356,179 | 64,778,222 | How to fix "RuntimeError: The current Numpy installation fails to pass a sanity check due to a bug in the windows runtime." | <p>I am having a problem with running my Python programs after installing a new package. The error message that I am getting states:</p>
<blockquote>
<p>RuntimeError: The current Numpy installation ("[Location of file]") fails to pass a sanity check due to a bug in the windows
runtime.See this issue for more... | <ol>
<li>Open the command prompt.</li>
<li>Type <code>pip install --upgrade numpy==1.19.3</code></li>
</ol>
<p>The current numpy version is having some bugs.
You can use <code>--upgrade</code> to upgrade and downgrade packages</p> | python|python-3.x|numpy | 9 |
356,180 | 64,824,765 | Combine two colums of string data in one with selection rule | <p>I have to combine two colums of string data in one (in the same DataFrame), also I need some sort of selection rule, I give you an example</p>
<pre><code> import numpy as np
import pandas as pd
df = pd.DataFrame({'nameA':['martin', 'peter', 'john', 'tom', 'bill'],
'nameB':[ np.NaN,np... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>df.combine_first()</code></a>:</p>
<pre><code>In [1972]: df['nameAB'] = df.nameB.combine_first(df.nameA)
In [1973]: df
Out[1973]:
nameA nameB nameAB
0 martin ... | python|pandas | 2 |
356,181 | 64,678,328 | Pandas wrongfully reading csv | <p>I have a very easy question: I try to read following data into an Dataframe <a href="https://www.ecdc.europa.eu/en/publications-data/download-data-response-measures-covid-19" rel="nofollow noreferrer">https://www.ecdc.europa.eu/en/publications-data/download-data-response-measures-covid-19</a></p>
<p>If I use folllow... | <p>You can read CSV directly from URL:</p>
<pre><code>url = 'https://www.ecdc.europa.eu/sites/default/files/documents/Data_response_graphs_2020-10-21.csv'
dmeasures = pd.read_csv(url, sep=",")
print(dmeasures)
</code></pre>
<p>Prints:</p>
<pre><code> Country Response_measure date_start ... | python|pandas|csv | 2 |
356,182 | 64,897,695 | How to extract date AND hour from date time in python? | <p>What's the best way to do this? I thought about extracting the two separately then combining them? This doesn't seem like it should be the most efficient way?</p>
<pre><code>df['date'] = df['datetime'].dt.date
df['hour'] = df['datetime'].hour
df['dateAndHour'] = df['datetime'].dt.date.astype(str) + ' ' + df['dateti... | <p>Depends what you want to do with it, but one way to do this would be to use <code>strftime</code> to format the datetime column to <code>%Y-%m-%d %H</code> or similar:</p>
<pre><code>>>> df
datetime
0 2020-01-01 12:15:00
1 2020-10-22 11:11:11
>>> df.datetime.dt.strftime("%Y-%m-%d... | python|pandas|datetime | 0 |
356,183 | 64,756,385 | numpy concatenate error " only integer scalar arrays can be converted to a scalar index" | <p>I have numpy data</p>
<p><code>x = [[1. 2.2 3.4] [3. 4. 5. ]]</code></p>
<p>and</p>
<p><code>y = [[2.6660993 3.6791213 3.7325573]]</code></p>
<p>Just want to concatenate these, result should be this.</p>
<p><code>[[1. 2.2 3.4] [3. 4. 5. ] [2.6660993 3.6791213 3.7325573] ]</code></p>
<p>However, <code>np.conca... | <p>The function concatenate receives a tuple of ndarrays:</p>
<pre><code>import numpy as np
x = np.array( [[1,2,3],[4,5,6]] )
y = np.array([[7,8,9]])
z = np.concatenate((x,y))
print(z)
</code></pre> | python|numpy | 0 |
356,184 | 64,987,818 | Plot grid of histograms based on group variable using plotly | <p>I have a data frame that contains multiple variables where each variable is logically connected to a factor level of an additional group variable. I would like to plot a histogram of each variable in such a way that it is possible to show a grid of multiple histograms 'group-wise'.</p>
<p>Here's an example data fram... | <p>Best I came up with is the following. Sadly, this is not in the nicely plotted format that you wanted, but I think/hope you can start with this.</p>
<pre><code>import numpy as np
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# simulate data and create plot-ready dat... | python|pandas|plotly|data-visualization | 0 |
356,185 | 64,806,660 | How to read float values with decimal comma using read_sql_query | <p>I am getting problems using <code>DataFrame.read_sql_query</code> and SQLite on my german computer: according to the local settings for numbers, the decimal character is a comma ',' and not a dot '.'</p>
<p>Working with CSV and pandas, it is easy to set the decimal character to ',' in the functions <code>read_csv</c... | <p>I my have found the root cause of my problem:
An equivalent question was posted and answered in stack overflow:
<a href="https://stackoverflow.com/questions/62225393/problem-doing-multiplication-operation-in-a-select-between-a-float-and-an-intege/62225862#62225862">Problem doing multiplication operation in a select ... | python|pandas | 0 |
356,186 | 65,053,730 | Is there a way to draw shapes on a python pandas plot | <p>I am creating shot plots for NHL games and I have succeeded in making the plot, but I would like to draw the lines that you see on a hockey rink on it. I basically just want to draw two circles and two lines on the plot like this.</p>
<p><a href="https://i.stack.imgur.com/NEF3M.png" rel="nofollow noreferrer"><img sr... | <p>Pandas plot is in fact matplotlib plot, you can assign it to variable and modify it according to your needs ( add horizontal and vertical lines or shapes, text, etc)</p>
<pre><code># plot your data, but instead diplaying it assing Figure and Axis to variables
fig, ax = df.plot()
ax.vlines(x, ymin, ymax, colors='k',... | pandas|plot|graphics|geometry|drawing | 0 |
356,187 | 64,808,427 | Avoid pandas.to_sql writes into table with double quotes (PostgreSQL database) | <p>I am trying to export my dataframe to sql database (Postgres).</p>
<p><strong>I created the table as following:</strong></p>
<pre><code>CREATE TABLE dataops.OUTPUT
(
ID_TAIL CHAR(30) NOT NULL,
ID_MODEL CHAR(30) NOT NULL,
ID_FIN CHAR(30) NOT NULL,
ID_GROUP_FIN CHAR(30) NOT NULL,
ID_COMPONENT CHAR(... | <p>this line of code worked for me</p>
<pre><code>appended_data.columns = map(str.lower, df2.columns)
appended_data.to_sql('table_name', con=engine,
schema='public', index=False, if_exists='append',method='multi')
</code></pre> | python|pandas|postgresql | 0 |
356,188 | 64,844,278 | Csv pandas reader delimiter does not work | <p>I have a csv file delimited by a comma.</p>
<pre><code>df = pd.read_csv('data/data_notebook-1_crime.csv', sep= ',')
print(df.head)
</code></pre>
<p>Unfortunately if I print the results all values are in the first column as seen in the picture</p>
<p><a href="https://i.stack.imgur.com/Sa7hI.jpg" rel="nofollow norefer... | <p>Here are the results from 3.8.6</p>
<pre><code>Python 3.8.6 (default, Oct 28 2020, 18:56:32)
[Clang 12.0.0 (clang-1200.0.31.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.>>> import pandas as pd
>>> df = pd.read_csv('~/Do... | pandas|csv | 0 |
356,189 | 64,890,773 | Python Pandas vectorise find matching datetime from varying size | <p>so my solution to what I thought would be a straightforward problem to solve within Python Pandas turns out to be terribly slow, for what will be, in just one moment, obvious reasons.</p>
<p>Imagine two dataframes:</p>
<pre><code>stt = datetime.strptime(args.stt_str, '%Y-%m-%d')
stp = datetime.strptime(a... | <p>Here is what I would do, set datetimes as index for both dataframes and set the values of the smaller dataframe as a slice of the larger one. This implies that the columns are ordered in the same way. Provided they have the same name, you can simply :</p>
<pre class="lang-py prettyprint-override"><code>big_df = big_... | python|pandas | 0 |
356,190 | 64,810,357 | Create Pandas column which finds and returns matching data | <p>I have a large DataFrame (150,000 x 25) of financial transactions. This DataFrame represents a type of financial holding account, such that transactions often "pass through" this ledger. For example (below), the row in position 0 shows a -$123.21 transaction. The row in position 2 is the corresponding (or ... | <p>You could do the following:</p>
<p><strong>Step 1</strong>: Setting up <code>transform</code> function:</p>
<pre><code>def coupling(ser):
keys = ser.index
values = ser.values
couples = [None] * len(ser)
free = {*range(len(ser))}
while free:
i = min(free)
j = i + 1
while j ... | python|pandas|dataframe | 2 |
356,191 | 64,831,334 | Pandas fillna and rolling mean | <p>I am trying to fill all missing values until the end of the dataframe but unable to do so. In the example below, I am taking average of the last three values. My code is only filling until 2017-01-10 whereas I want to fill until 2017-01-14. For 1/14, I want to use values from 11,12 & 13.Please help.</p>
<pre><co... | <p>You can iterate over the values in y and if a nan value is encountered, look at the 3 earlier values and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iteritems.html" rel="nofollow noreferrer">.at[]</a> to set the mean of the 3 earlier values as the new value:</p>
<pre><code>f... | python|pandas | 3 |
356,192 | 64,848,023 | NumPy - generate multiple intervals | <p>I have an array like this:</p>
<pre><code>[[0.13, 0.19],
[0.25, 0.6 ],
[0.7 , 0.89]]
</code></pre>
<p>I want, given the above array, to create a result like this:</p>
<pre><code>[[0, 0.12],
[0.13, 0.19],
[0.20, 0.24],
[0.25, 0.60],
[0.61, 0.69],
[0.70, 0.89],
[0.90, 1]]
</code></pre>
<p>Namely, I want to create a to... | <p>This isn't specific to numpy, but maybe it will point you in the correct direction.</p>
<p>Basically, you need to know where to start, end, and the 'resolution' (for lack of a better word) — how far apart the gaps are. With that you can loop through the existing intervals and fill in the others. You'll want to watch... | python|numpy | 0 |
356,193 | 64,864,800 | Drop rows in dataframe if the column matches particular string | <p>I tried to follow the process which was mentioned <a href="https://stackoverflow.com/questions/28679930/how-to-drop-rows-from-pandas-data-frame-that-contains-a-particular-string-in-a-p">here</a> but it did not work(completely) for me, so pls point me out to any duplicates which i might be missing, so below is the re... | <p>Essentially you are forgetting to pass the boolean series (True/False) into brackets <code>[...]</code> or better with <code>.loc[...]</code>. Instead, you are re-assigning the values within those chunk columns to the result of your conditions but not applying conditions logically to the data frame.</p>
<p>Therefore... | python|pandas|dataframe | 1 |
356,194 | 64,903,720 | Numpy to convert series of integers in array to hex value | <p>I have an image array where I use Numpy to convert it to a 16 x 1000000 array of 4 values where each value is a 2 bit integer. Shown below is a small part of an array. I need to convert each column to a hexadecimal word in this format(0x00000000). The first column would be ??3022133203023123 or (0xCA7E32DB). All val... | <p>I found my solution. Using np.arange(...) is literally a numpy direct replacement of a (for) loop that generates a matrix. I am using it to sum over indices. Here is an example. I can also use np.set_printoptions to get hex format if needed.</p>
<pre><code>b = np.arange(0,160).reshape(16,10)
r = ((4** np.arange(16)[... | python|arrays|numpy | 0 |
356,195 | 64,894,009 | Python pandas plotting multiple lines | <p>I want to make two trend lines in the plot. I wrote a code but it is not working as expected.
Is there any other way to do this?</p>
<pre><code>by_type = df.filter(["Total","Academic_Year","Institute_Type"]).groupby(["Institute_Type","Academic_Year"]).sum()
print(by_... | <pre><code>import matplotlib.pyplot as plt
# Convert back to single dataframe instead of groups
df = by_type.apply(pd.DataFrame)
# Loop through, grouping by JUST Institute_Type
for Institute_Type, vals in df.groupby('Institute_Type'):
vals.plot(x='Academic_Year', y='Total', kind='line',
label=Institut... | python|pandas|dataframe|data-visualization | 0 |
356,196 | 64,822,870 | Is there a way to roll Pandas Grouper backwards over a dataframe? | <p>The first option below isn't very elegant, but I think gets to the right place. The second option using pd.Grouper, but chops off values during the group and produces different results and groups to the beginning of the period. Using grouper begins the grouping of the Timestamp column from the earliest date to the l... | <p>I think what you really want to do is just get minimum number of elements to reproduce the result of the most recent date.</p>
<p>I doubled-ish your dataset to illustrate. For 30-day rolling averages you only need 60 days worth of data to get the same result.</p>
<pre><code>data = pd.DataFrame({
'Timestamp': pd.... | python|pandas|dataframe|pandas-groupby | 0 |
356,197 | 64,921,864 | Pandas Aggregate price and calculate weights/weightage of that of price vs volume data and group by step of 5 prices | <p>I have a dataframe like this:</p>
<pre><code> price volume
0 100.0 2500
1 100.5 4100
2 101.0 2311
3 101.5 5066
4 102.0 9585
... ... ...
</code></pre>
<p>I want to first get a grouping of price and sum the volumes with a step of 5.
For example (using random val... | <p>I used the standard way to round the price so 97.5 to 102.49 will be in group 100.
Weight - I have used simple formula as evident.</p>
<p>data.csv:</p>
<pre><code>price volume
100.0 2500
103.5 4100
101.0 2311
105.5 5066
109.0 9585
</code></pre>
<p>Code:</p>
<pre><code>import pandas as pd
import... | python|pandas|dataframe | 0 |
356,198 | 64,751,686 | Numpy more verbose information about warnings while using np.where | <p>I am using numpy (<code>np.where</code>) to calculate some indicators (pretty complicated formulas) on spatial data arrays. Sometimes when I operate on them, I am getting warnings like:</p>
<pre><code>RuntimeWarning: overflow encountered in exp
mo_arr = np.where(self.p > 0.5, mo+42.5*(self.p - 0.5)*np.exp(-100.... | <p>As with your <a href="https://stackoverflow.com/questions/64747346/numpy-divide-by-zero-encountered-in-true-divide-on-np-where">Last question</a>, you can get rid of the warning by using <code>np.errstate</code>:</p>
<pre><code>with np.errstate(divide = 'ignore', over = 'ignore'):
mo_arr = np.where(self.p > 0... | python|numpy|pycharm | 1 |
356,199 | 64,713,914 | Can anyone make sense of this unexpected value error from scipy.sparse.csr_matrix((data, indices, indptr), [shape=(M, N)])? | <p>When using scipy.sparse.csr_matrix((data, indices, indptr), [shape=(M, N)]) I get the value error: data, indices, and indptr should be rank 1. BUT the data indices and indptr I am using are rank 1 and I have confirmed this with numpy.linalg.matrix_rank() which returns rank 1 for each of the matrices … does anyone h... | <p>rank 1 arrays are arrays of shape <code>(m, )</code>, the arrays of shape <code>(m, 1)</code> are commonly known as vectors. To make your numpy arrays rank-1 array, use <code>ravel</code> method. You can read the doc <a href="https://numpy.org/doc/stable/reference/generated/numpy.ravel.html" rel="nofollow noreferrer... | python|numpy|machine-learning|scipy|artificial-intelligence | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.