DataFrame根据某列的值取另一列的值

import pandas as pd

# 创建示例 DataFrame
data = {
    'A': [1, 2, 3, 4, 5],
    'B': ['apple', 'banana', 'orange', 'apple', 'banana']
}
df = pd.DataFrame(data)

# 根据列 'B' 中的值选择列 'A' 中对应的值
value_for_banana = df.loc[df['B'] == 'banana', 'A'].values[0]
print("Value for 'banana':", value_for_banana)
print("--------------------------------------")
value = df.loc[df['A'] >= 3, 'B']
print(value)
print("--------------------------------------")
value = df.loc[df['A'] >= 3, 'B'].values[0]
print(value)
print("--------------------------------------")
value = df.loc[df['A'] >= 3, 'B'].tolist()
print(value)
print("--------------------------------------")
value = df.loc[df['A'] >= 3, 'B'].items()
print(value)

 

posted @ 2023-08-08 13:28  OTAKU_nicole  阅读(972)  评论(0)    收藏  举报