python - 如何综合查看两个不同的 DataFrame

标签 python pandas

我想显示一个将两个 DataFrame 与条件索引组合在一起的表。这适用于一个 DataFrame:

room1,weather = pd.read_excel(mypath,sheetnames[0]),pd.read_excel(mypath,sheetnames[2])
selector = (room1.Time>='08:00') & (room1.Time<='18:00')
view     = ['Time','Cooling_plant_sensible_load']
room1[selector][view][:12]

这给了我这样的东西:

    Time    Cooling_plant_sensible_load
7   08:00   0.000
8   09:00   0.000
....
16  17:00   0.000
17  18:00   0.000
31  08:00   0.000

天气 DataFrame 有一个名为 Dry_Bulb_Temperature 的系列,我想将其添加到 View 中,使其显示如下

    Time    Cooling_plant_sensible_load    Dry_Bulb_Temperature
7   08:00   0.000                          18
8   09:00   0.000                          22
....
16  17:00   0.000                          19
17  18:00   0.000                          16
31  08:00   0.000                          12

我尝试添加:

selector2 = (weather.Time>='08:00') & (weather.Time<='18:00')
pd.concat({'room1':room1[selector][view][:12],'wea':weather[selector2]['Dry_bulb_temperature']},axis=1)

这给了我一个AttributeError:'Series'对象没有属性'_data'

编辑:

天气[selector2]['Dry_bulb_Temperature'][:12]如下所示:

major
7        15.3
8        16.0
9        18.0
10       19.9
11       21.9
12       22.9
13       24.0
14       25.0
15       24.8
16       24.5
17       24.3
31       16.2
Name: Dry_bulb_temperature, dtype: float64

编辑2:

AttributeError: 'Series' object has no attribute '_data' 是因为 weather[selector2]['Dry_bulb_Temperature'] 是一个 Series while concat需要一个不能与 Dataframe 连接的 DataFrame,即 concat 需要两个相似的类型(前面的评论是错误的,正如下面 @Philip 指出的那样)。

所以我可以将 room1 DataFrame 与天气 DataFrame 结合起来。这是要走的路吗?如何避免两个“时间”系列重复?

我有许多 room(n) 数据帧,并且认为可能有一种方法可以让每个数据帧引用相同的天气数据集。

最佳答案

看起来您想要进行联接(可以合并索引上的 DataFrame 和 Series):

In [11]: df
Out[11]:
    Time  Cooling_plant_sensible_load  Dry_Bulb_Temperature
7  08:00                            0                    18
8  09:00                            0                    22

In [12]: s
Out[12]:
7    15.3
8    16.0
Name: Dry_bulb_temperature, dtype: float64

In [13]: df.join(s)
Out[13]:
    Time  Cooling_plant_sensible_load  Dry_Bulb_Temperature  Dry_bulb_temperature
7  08:00                            0                    18                  15.3
8  09:00                            0                    22                  16.0

查看更多信息 merging, join and concating section of the docs .

注意:

您可以使用 loc 创建系列/列,避免链接:

s = weather.loc[selector2, 'Dry_bulb_temperature']

关于python - 如何综合查看两个不同的 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18669699/

相关文章:

python - 在 JSON 序列化中嵌套一组带有新 header 的列

python - 在 Python pandas DataFrame 中交换值以清理数据的最佳方法是什么

python - 如何将满足特定条件的列标题返回到pandas中的新列

python - 附加到列表理解中的列表

python - 如何在 python 中定义类?

python - 访问多处理映射中的共享数据帧

python - pandas 数据框,并对 n 个最常见的值使用 idmax()

python - 将列表写入 pandas 数据帧到 csv,从 csv 读取数据帧并再次转换为列表而无需字符串

python - 如何按元素检查多个 pandas DataFrame.Series 的条件并将结果应用于新列?

python - 如何在不重复函数评估的情况下编写列表理解?