Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the value when I do this in pandas Series

I have the following code.

s2 = pd.Series([100,"PYTHON","Soochow","Qiwsir"],
               index=["mark","title","university","name"])

s2.mark = "102"

s2.price = "100"

When I print s2 , I can see the value of mark was changed and there is no price; but I can get result by printing s2.price. Why is the price not printed?

like image 364
C.Ming Avatar asked Apr 10 '18 08:04

C.Ming


People also ask

How do you find the only value of a data frame?

get_value() function is used to quickly retrieve the single value in the data frame at the passed column and index. The input to the function is the row label and the column label.

How do I get value from DF Loc?

You can use DataFrame properties loc[] , iloc[] , at[] , iat[] and other ways to get/select a cell value from a Pandas DataFrame. Pandas DataFrame is structured as rows & columns like a table, and a cell is referred to as a basic block that stores the data.

Which property of Series return all the index value?

index attribute has successfully returned the index labels for the given Series object.


1 Answers

You are confusing attributes with series indices.

The syntax s2.xyz = 100 first looks for xyz in the series index and overwrites it if it exists.

If it does not exist, it adds a new attribute to the series.

How to add an attribute

if 'price' not in s2:
    s2.price = 100

You should not add attributes which conflict with indices; this is asking for trouble given the similar syntax permitted for access.

How to add an element to series

In order to add an element to the series with an index, use pd.Series.loc:

s2.loc['price'] = 100

How to tell the difference

Run s2.__dict__. You will find:

{'_data': SingleBlockManager
 Items: Index(['mark', 'title', 'university', 'name'], dtype='object')
 ObjectBlock: 4 dtype: object,
 '_index': Index(['mark', 'title', 'university', 'name'], dtype='object'),
 '_item_cache': {},
 '_name': None,
 '_subtyp': 'series',
 'is_copy': None,
 'price': '100'}

It is clear that price has been added as an attribute, not as an index.

like image 158
jpp Avatar answered Oct 12 '22 02:10

jpp