首页 > 解决方案 > 两个 CSV 文件之间的 Pandas Merge 会导致 NaN 返回,它不应该是

问题描述

import pandas
import requests
from bs4 import BeautifulSoup
website_text = requests.get('https://en.wikipedia.org/wiki/List_of_New_Mexico_locations_by_per_capita_income').text
soup = BeautifulSoup(website_text,'lxml')

table = soup.find('table',{'class':'wikitable sortable'})
table_rows = table.find_all('tr')

我正在合并这个文件

data = []
for row in table_rows:
    data.append([t.text.strip() for t in row.find_all('td')])

df = pandas.DataFrame(data, columns=['Rank', 'County', 'Per capita income', 'Median household income', 'Median family income', 'Population', 'Number of households'])
df = df[~df['Rank'].isnull()]  #Ignore Not Assigned rows

df.head(35)

用“插入代码”编写的个人 CSV 文件。

使用此代码:

df_NewMex = pd.merge(df2, df_latlong, how='left', left_on = 'County', right_on = 'County')
df_NewMex.drop("Rank", axis=1, inplace=True)
df_NewMex.head(33)

我收到了很多 NaN 输出照片

请帮忙。我已确保县名相同,没有丢失空格等。我不知所措,并且在 2 小时的大部分时间里一直在解决这个问题。

预先感谢您提供的任何帮助

标签: pythonpandasdataframemerge

解决方案


在将文件与 df_latlong 合并之前,我需要在 df2 中删除“排名”列,而不是之后。

菜鸟/新手错误。我感谢您的帮助


推荐阅读