使用Python Pandas进行数据分析

在本教程中,我们将看到使用Python pandas库进行的数据分析。图书馆的熊猫都是用C语言编写的。因此,我们在速度上没有任何问题。它以数据分析而闻名。我们在熊猫中有两种类型的数据存储结构。它们是SeriesDataFrame。让我们一一看。

1.系列

系列是具有自定义索引和值的一维数组。我们可以使用pandas.Series(data,index)类创建一个Series对象。系列将整数,列表,字典作为数据。让我们看一些例子。

示例

# importing the pandas library
import pandas as pd
# data
data = [1, 2, 3]
# creating Series object
# Series automatically takes the default index
series = pd.Series(data)
print(series)

输出结果

如果运行上面的程序,您将得到以下结果。

0 1
1 2
2 3
dtype: int64

如何拥有定制索引?参见示例。

示例

# importing the pandas library
import pandas as pd
# data
data = [1, 2, 3]
# index
index = ['a', 'b', 'c']
# creating Series object
series = pd.Series(data, index)
print(series)

输出结果

如果运行上面的程序,您将得到以下结果。

a 1
b 2
c 3
dtype: int64

当我们将数据作为字典提供给Series类时,它将键作为索引,将值作为实际数据。让我们看一个例子。

示例

# importing the pandas library
import pandas as pd
# data
data = {'a':97, 'b':98, 'c':99}
# creating Series object
series = pd.Series(data)
print(series)

输出结果

如果运行上面的程序,您将得到以下结果。

a 97
b 98
c 99
dtype: int64

我们可以使用索引访问系列中的数据。让我们看看例子。

示例

# importing the pandas library
import pandas as pd
# data
data = {'a':97, 'b':98, 'c':99}
# creating Series object
series = pd.Series(data)
# accessing the data from the Series using indexes
print(series['a'], series['b'], series['c'])

输出结果

如果运行上面的代码,您将得到以下结果。

97 98 99

2.熊猫

我们有如何在熊猫中使用Series类的信息。让我们看看如何使用DataFrame类。包含行和列的pandas中的DataFrame数据结构类。

我们可以使用列表,字典,系列等创建DataFrame对象。让我们使用列表创建DataFrame。

示例

# importing the pandas library
import pandas as pd
# lists
names = ['Nhooo', 'Mohit', 'Sharma']
ages = [25, 32, 21]
# creating a DataFrame
data_frame = pd.DataFrame({'Name': names, 'Age': ages})
# printing the DataFrame
print(data_frame)

输出结果

如果运行上面的程序,您将得到以下结果。

               Name    Age
0    Nhooo    25
1             Mohit    32
2            Sharma    21

让我们看看如何使用Series创建数据框对象。

示例

# importing the pandas library
import pandas as pd
# Series
_1 = pd.Series([1, 2, 3])
_2 = pd.Series([1, 4, 9])
_3 = pd.Series([1, 8, 27])
# creating a DataFrame
data_frame = pd.DataFrame({"a":_1, "b":_2, "c":_3})
# printing the DataFrame
print(data_frame)

输出结果

如果运行上面的代码,您将得到以下结果。

   a  b  c
0  1  1  1
1  2  4  8
2  3  9  27

我们可以使用列名从DataFrames中访问数据。让我们看一个例子。

示例

# importing the pandas library
import pandas as pd
# Series
_1 = pd.Series([1, 2, 3])
_2 = pd.Series([1, 4, 9])
_3 = pd.Series([1, 8, 27])
# creating a DataFrame
data_frame = pd.DataFrame({"a":_1, "b":_2, "c":_3})
# accessing the entire column with name 'a'
print(data_frame['a'])

输出结果

如果运行上面的代码,您将得到以下结果。

0 1
1 2
2 3
Name: a, dtype: int64

结论

如果您对本教程有任何疑问,请在评论部分中提及。