📜  获取元素 pandas - Python (1)

📅  最后修改于: 2023-12-03 14:57:13.699000             🧑  作者: Mango

获取元素 pandas - Python

Pandas是一个被广泛应用于数据处理和分析的Python库。在Pandas中,获取元素操作是我们必须掌握的基本操作之一。在本文中,我们将介绍如何使用Pandas库获取数据框中的元素。

获取单个元素

我们可以使用.at[].iat[]方法获取单个元素。

  • .at[]方法接收行和列的标签索引作为输入
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df)

#   A  B
# 0 1  3
# 1 2  4

print(df.at[1, 'B']) # 4
  • .iat[]方法接收行和列的整数位置作为输入
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df)

#   A  B
# 0 1  3
# 1 2  4

print(df.iat[1, 1]) # 4
获取行或列

我们可以使用.loc[].iloc[]方法获取行或列。

  • .loc[]方法接收行和列的标签索引作为输入
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df)

#   A  B
# 0 1  3
# 1 2  4

print(df.loc[:, 'A'])

# 0    1
# 1    2
# Name: A, dtype: int64
  • .iloc[]方法接收行和列的整数位置作为输入
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df)

#   A  B
# 0 1  3
# 1 2  4

print(df.iloc[:, 0])

# 0    1
# 1    2
# Name: A, dtype: int64
获取多个元素

我们可以使用.loc[].iloc[]方法获取多个元素。

  • .loc[]方法接收行和列的标签索引作为输入
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df)

#   A  B
# 0 1  3
# 1 2  4

print(df.loc[0:1, 'A':'B'])

#    A  B
# 0  1  3
# 1  2  4
  • .iloc[]方法接收行和列的整数位置作为输入
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df)

#   A  B
# 0 1  3
# 1 2  4

print(df.iloc[0:2, 0:2])

#    A  B
# 0  1  3
# 1  2  4

以上是在Pandas中获取元素的基础操作介绍,更多Pandas操作和使用技巧请参考官方文档。