.get() 方法在获取 DataFrame 或 Series 中特定索引位置的值

202 阅读1分钟

这个用法是针对 Pandas 的 Series 或 DataFrame 的列 'A' 进行操作,其中 get() 方法用于获取指定索引(或键)的值,如果索引不存在,则返回默认值。

让我们通过一个示例来解释这个用法:

假设有以下的 DataFrame df

import pandas as pd

data = {
    'A': [10, 20, 30, 40, 50],
    'B': [100, 200, 300, 400, 500]
}
index = ['Apple', 'Banana', 'Orange', 'Apple', 'Orange']
df = pd.DataFrame(data, index=index)
print(df)

输出如下:

         A    B
Apple   10  100
Banana  20  200
Orange  30  300
Apple   40  400
Orange  50  500

现在,我们想获取列 'A' 中指定索引 'Apple' 的值,如果 'Apple' 索引不存在,则返回默认值 0。可以使用 .get() 方法来实现:

brand = 'Apple'
value = df['A'].get(brand, 0)
print(f"Value at index '{brand}' in column 'A': {value}")

输出结果为:

Value at index 'Apple' in column 'A': 10

解释:

  • df['A'] 选择了 DataFrame 中的列 'A'
  • .get(brand, 0) 方法用于获取索引为 'Apple' 的值。在这个例子中,列 'A' 中有两个索引为 'Apple' 的行,但是 .get() 方法只返回第一个匹配到的值。
  • 如果指定的索引 'Apple' 不存在,.get() 方法将返回默认值 0

因此,.get() 方法在获取 DataFrame 或 Series 中特定索引位置的值时非常有用,尤其是当你想要处理可能不存在的索引时。