【问题标题】:Fetching column values in Panda DataFrame using while loop使用 while 循环获取 Panda DataFrame 中的列值
【发布时间】:2020-08-30 22:41:32
【问题描述】:

我创建了一个 panda DataFrame,其列如下:“Radius”、“Zenith”、“Tem”。现在我想根据 DataFrame 中的天顶值检索所有温度值。接下来是获取每个天顶角值的“Tem”的最大值和最小值。

我已经编写了下面的代码块,但它抛出了我 ValueError: DataFrame 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

theta = np.around(np.arange(0,90,90/151),6)
a = np.ndarray(shape=(1,2), dtype=float, order='C')

for i in theta:
    while (final_data[final_data['zenith'] == i]):
        T = final_data[['Tem']].values
        T_max = np.max(T)
        T_min = np.min(T)
        T_range = np.row_stack((a,[[T_max,T_min]])) 

【问题讨论】:

  • 您想对每个 I 的行进行迭代?
  • 数据框在哪里?你应该展示一个例子和预期的输出。我认为您根本不应该在这里迭代
  • 是的,我想迭代行
  • @roganjosh 你是对的。我很愚蠢地迭代它。我想到了。我直接使用了索引并且它起作用了。 for i in theta:final_data[final_data['zenith'] == i]T = final_data[['Tem']].valuesT_max = np.max(T)T_min = np.min(T)`T_limit = np.row_stack((a,[[T_max,T_min]]))` 非常感谢您的帮助。

标签: python pandas


【解决方案1】:

这些操作已经在 pandas 中实现了:

import pandas as pd

# example data
df = pd.DataFrame({'Zenith': [70, 70, 70, 80, 80, 80], 
                   'Tem':    [20, 21, 22, 23, 24, 25]})

# get all temperatures for a given zenith value (e.g. 80)
df.Tem[df.Zenith == 80]
3    23
4    24
5    25
Name: Tem, dtype: int64
# get the minimum temperature for each zenith value
df.groupby('Zenith').min()
       Tem
Zenith  
70     20
80     23
# get the maximum temperature for each zenith value
df.groupby('Zenith').max()
       Tem
Zenith  
70     22
80     25

【讨论】:

  • 非常感谢。这是一个很大的帮助,你为我节省了很多时间和精力。
【解决方案2】:

您可以使用它来获取最小值、最大值和范围

import pandas as pd

df = pd.DataFrame({'Zenith': [70, 70, 70, 80, 80, 80],
                   'Tem':    [20, 21, 22, 23, 24, 25]})

df.groupby('Zenith')['Tem'].agg([
    ('T_min',  'min'),
    ('T_max',  'max'),
    ('T_range', lambda x: x.max() - x.min())
])

返回

        T_min  T_max  T_range
Zenith
70         20     22        2
80         23     25        2

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2020-10-02
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多