python - 在熊猫中将一个表连接到另一个表
问题描述
我正在尝试从https://www.espn.com/nhl/standings获取数据
当我试图抓住它时,它会将佛罗里达黑豹队排在前一排,并弄乱了数据。所有团队名称都需要向下移动一行。我试图改变数据并尝试过,
dataset_one = dataset_one.shift(1)
然后加入统计表,但我得到的是 NaN。
文档似乎展示了许多使用类似列标题连接和合并数据的方法,但不确定没有类似列标题的最佳解决方案。
代码:
import pandas as pd
page = pd.read_html('https://www.espn.com/nhl/standings')
dataset_one = page[0] # Team Names
dataset_two = page[1] # Stats
combined_data = dataset_one.join(dataset_two)
print(combined_data)
输出:
FLAFlorida Panthers GP W L OTL ... GF GA DIFF L10 STRK
0 CBJColumbus Blue Jackets 6 5 0 1 ... 22 16 6 5-0-1 W2
1 CARCarolina Hurricanes 10 4 3 3 ... 24 28 -4 4-3-3 L1
2 DALDallas Stars 6 5 1 0 ... 18 10 8 5-1-0 W4
3 TBTampa Bay Lightning 6 4 1 1 ... 23 14 9 4-1-1 L2
4 CHIChicago Blackhawks 6 4 1 1 ... 19 14 5 4-1-1 W1
5 NSHNashville Predators 10 3 4 3 ... 26 31 -5 3-4-3 W1
6 DETDetroit Red Wings 8 4 4 0 ... 20 24 -4 4-4-0 L1
期望:
GP W L OTL ... GF GA DIFF L10 STRK
0 FLAFlorida Panthers 6 5 0 1 ... 22 16 6 5-0-1 W2
1 CBJColumbus Blue Jackets 10 4 3 3 ... 24 28 -4 4-3-3 L1
2 CARCarolina Hurricanes 6 5 1 0 ... 18 10 8 5-1-0 W4
3 DALDallas Stars 6 4 1 1 ... 23 14 9 4-1-1 L2
4 TBTampa Bay Lightning 6 4 1 1 ... 19 14 5 4-1-1 W1
5 CHIChicago Blackhawks 10 3 4 3 ... 26 31 -5 3-4-3 W1
6 NSHNashville Predators 8 4 4 0 ... 20 24 -4 4-4-0 L1
7 DETDetriot Red Wings 10 2 6 2 6 ... 20 35 -15 2-6-2 L6
解决方案
为@Noah 的回答提供另一种方法。您可以先添加一个额外的行,shift
将 df 向下添加一行,然后将标题 col 分配为索引 0 值。
import pandas as pd
page = pd.read_html('https://www.espn.com/nhl/standings')
dataset_one = page[0] # Team Names
dataset_two = page[1] # Stats
# Shifting down by one row
dataset_one.loc[max(dataset_one.index) + 1, :] = None
dataset_one = dataset_one.shift(1)
dataset_one.iloc[0] = dataset_one.columns
dataset_one.columns = ['team']
combined_data = dataset_one.join(dataset_two)
推荐阅读
- javascript - 使用 localfield 键从另一个文档连接对象
- angular - Ngrx StoreModule 声明 forRoot 错误 Angular 9
- java - 将优先级更改为 PRIORITY_MAX 是否会延迟通知 .setRepeating?
- kotlin - 使用协程在 kotlin 中的列表上实现 monad 理解
- ssh - 如何使用 Termius 应用程序将 SSH 远程连接到 MacOS 或 Linux 终端?
- typescript - TypeError:未定义不是对象(评估'details.geometry.location')
- python - 用 BeautifulSoup 抓取 href
- android - java.lang.InstantiationException: java.lang.Class
没有零参数构造函数 - jboss - JBoss 6.4 EAP 使用的连接池库是什么?
- c++ - 如何从文本文件中读取空白字符?