【问题标题】:Pandas only return Value from Cell熊猫只从单元格返回值
【发布时间】:2019-04-02 11:55:02
【问题描述】:

我目前正在尝试从数据框中的单元格中检索值。我正在搜索数据框以查找与行中的列中的值匹配的字符串,然后从另一列返回该行中的值。

我的代码如下所示:

df:
Fruit   Value
apple     7.0
banana    6.0
orange    8.0
lemon     3.0
melon     2.0

myList = ['apple', 'lemon']

result = []

for word in myList:

    result.append(df['Value'].loc[df['Fruit'] == word].values)

print(result)

打印语句正在输出:

[array([], dtype=float64), array([7.0]), array([], dtype=float64), array([3.0])]

我想要的输出只是一个浮点值数组:

[7.0, 3.0]

我将如何清理我的输出以实现此目的?我的最终目标是得到数组的平均值。

【问题讨论】:

    标签: python pandas dataframe jupyter jupyter-lab


    【解决方案1】:

    使用Series.isinboolean indexing 并转换为列表:

    print (df.loc[df['Fruit'].isin(myList), 'Value'].values.tolist())
    [7.0, 3.0]
    

    我的最终目标是得到数组的平均值。

    那么更好的是调用mean 过滤Series

    val = df.loc[df['Fruit'].isin(myList), 'Value'].mean()
    print (val)
    5.0
    

    【讨论】:

      猜你喜欢
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2020-11-07
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      相关资源
      最近更新 更多