【发布时间】:2020-03-18 17:03:02
【问题描述】:
我正在尝试连接一些数据框,但完成后我得到了错误的列顺序。
我的代码是:
def numOfDays(date1, date2):
return (date2-date1).days
first_case_report = datetime.strptime('22-01-2020', '%d-%m-%Y')
NumOfdays_reported = numOfDays(first_case_report, datetime.today())
column_names = ['Province/State','Country/Region','Last Update','Confirmed','Deaths','Recovered']
df = pd.DataFrame(columns = column_names)
df.to_csv(index=True)
df.head()
Output:
Province/State Country/Region Last Update Confirmed Deaths Recovered
ind = 0
while ind < NumOfdays_reported:
date_report = (pd.Timestamp(first_case_report) + pd.DateOffset(days=ind)).strftime('%m-%d-%Y')
url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{0}.csv".format(date_report)
source = pd.read_csv(url,index_col=0,parse_dates=[0])
df = pd.concat([df,source], sort=True)
ind += 1
df.head()
Output:
Confirmed Country/Region Deaths Last Update Latitude Longitude Province/State Recovered
最后的 df.head() 显示列乱了,例如将列 Province/State 与执行的 df.head() 进行比较,为什么会发生这种情况?
任何想法都将受到高度赞赏。
非常感谢。
【问题讨论】:
-
您的示例代码对我不起作用:
NameError: name 'NumOfdays_reported' is not defined,请提供一个 mcve -
请查看How to make good pandas examples 并提供示例输入和输出。 “栏目乱七八糟”并不足以让我们理解问题
-
嗨@G.Anderson 我刚刚编辑了这个问题!
-
我想现在可能更清楚了。我还编辑了代码@anky_91
-
明确一点,您关心的不是数据列错误,而是列的顺序错误?如果是这种情况,那么您可以根据需要对列重新排序,这将是 How to change order of dataframe columns 的副本