Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing pandas DataFrame to Series

Tags:

python

pandas

I've looked at this and this question so far but they didn't really help me with my problem.

The problem is very simple but a little difficult to put to words.

I have a Dataframe which is matrix like:

       Stock1 Stock2
Date1   3      4
Date2   1      4

For each date, which is my index, I want to compare the values to a single point in a Series.

Be the Series like:

      Value
Date1   2
Date2   3

I want to build the following DataFrame from a comparison like DataFrame > Series

       Stock1 Stock2
Date1   True   True
Date2   False  True

So for Date1 both values are greater than 2, and for Date2 only Stock2 is greater than 3.

Thanks in advance

like image 924
Pedro Braz Avatar asked Jun 03 '16 12:06

Pedro Braz


People also ask

What is the difference between Pandas DataFrame and Series?

Series can only contain single list with index, whereas dataframe can be made of more than one series or we can say that a dataframe is a collection of series that can be used to analyse the data.

How do you compare Pandas Series?

It is possible to compare two pandas Series with help of Relational operators, we can easily compare the corresponding elements of two series at a time. The result will be displayed in form of True or False. And we can also use a function like Pandas Series. equals() to compare two pandas series.

How do I compare two DataFrames in Pandas?

The compare method in pandas shows the differences between two DataFrames. It compares two data frames, row-wise and column-wise, and presents the differences side by side. The compare method can only compare DataFrames of the same shape, with exact dimensions and identical row and column labels.

Can we analyze data in Pandas with Series?

It is built on top of NumPy (a Python library for scientific computing) and it has several functions for cleaning, analyzing, and manipulating data, which can help you extract valuable insights about your data set. Pandas is great for working with tabular data, as in SQL tables or Excel spreadsheets.


1 Answers

Use .gt and pass axis=0 to compare row-wise against a Series:

In [126]:
df.gt(s, axis=0)

Out[126]:
      Stock1 Stock2
index              
Date1   True   True
Date2  False   True
like image 114
EdChum Avatar answered Oct 23 '22 22:10

EdChum