代码之家  ›  专栏  ›  技术社区  ›  OlavT

从熊猫数据框中提取单列有两种方法,区别是什么?[副本]

  •  0
  • OlavT  · 技术社区  · 6 年前

    df = floor_temperatures.join(power_consumption, how='outer').join(outside_temperatures, how='outer')
    df = df.resample('5Min').mean()
    print (df)
    
                               floor_temperature  power_consumption  outside_temperature
    timestamp
    2019-01-23 00:00:00+00:00           8.350000           0.045000           -11.388889
    ...                                      ...                ...                  ...
    2019-01-24 07:25:00+00:00          10.400000           0.060000            -8.900000
    [407 rows x 3 columns]
    

    然后我基于一列创建一个新的数据帧,如下所示:

    y = df[['floor_temperature']]
    print("1:")
    print (y)
    
    1:
                               floor_temperature
    timestamp
    2019-01-23 00:00:00+00:00           8.350000
    2019-01-23 02:25:00+00:00           8.600000
    ...                                      ...
    2019-01-24 07:25:00+00:00          10.400000
    [407 rows x 1 columns]
    

    print("2:")
    y = df['floor_temperature']
    print (y)
    
    2:
    timestamp
    2019-01-23 00:00:00+00:00     8.350000
                                   ...
    2019-01-24 07:25:00+00:00    10.400000
    Freq: 5T, Name: floor_temperature, Length: 407, dtype: float64
    

    为什么最后两个DataFrame对象的打印略有不同?

    第一个页脚为“[407行x 1列]”,第二个页脚为“Freq:5T,Name:floor\u temperature,Length:407,dtype:float64”。

    1 回复  |  直到 6 年前
        1
  •  2
  •   jpp    5 年前

    方括号很重要

    df['floor_temperature'] 表示一个系列。 pd.Series 对象是一维的。争论 pd.DataFrame.__getitem__ [] 是语法糖,是标量。

    df[['floor_temperature']] 表示数据帧。 pd.DataFrame 对象是二维的,由作为列表的参数表示。