📜  Python Pandas Series(1)

📅  最后修改于: 2023-12-03 15:34:03.126000             🧑  作者: Mango

Python Pandas Series

Pandas Series is a one-dimensional labeled array in pandas. It can hold data of any data type such as integer, float, and string. Each element in a Pandas Series is associated with a unique index, which is used to access the element of the Series.

Creating a Pandas Series

You can create a Pandas Series using the pd.Series() method. Here is an example:

import pandas as pd

data = [10, 20, 30, 40, 50]
s = pd.Series(data)

print(s)

This will output:

0    10
1    20
2    30
3    40
4    50
dtype: int64
Accessing Elements in a Pandas Series

You can access elements in a Pandas Series using the index of the element. Here is an example:

import pandas as pd

data = [10, 20, 30, 40, 50]
s = pd.Series(data)

print(s[0])

This will output:

10

You can also access a range of elements using the slice notation. Here is an example:

import pandas as pd

data = [10, 20, 30, 40, 50]
s = pd.Series(data)

print(s[1:4])

This will output:

1    20
2    30
3    40
dtype: int64
Attributes of a Pandas Series

A Pandas Series has several useful attributes. Here are a few examples:

  • values: returns the values of the Series as a NumPy array
  • index: returns the index of the Series
  • dtype: returns the data type of the elements in the Series

Here is an example:

import pandas as pd

data = [10, 20, 30, 40, 50]
s = pd.Series(data)

print(s.values)
print(s.index)
print(s.dtype)

This will output:

[10 20 30 40 50]
RangeIndex(start=0, stop=5, step=1)
int64
Applying Functions to a Pandas Series

You can apply functions to a Pandas Series using the apply() method. Here is an example:

import pandas as pd

data = [10, 20, 30, 40, 50]
s = pd.Series(data)

def add_one(x):
    return x + 1

result = s.apply(add_one)

print(result)

This will output:

0    11
1    21
2    31
3    41
4    51
dtype: int64
Conclusion

Pandas Series is a powerful tool for working with one-dimensional data in pandas. It provides a lot of functionality for manipulating and analyzing data in a concise and efficient manner.