Pandas数据帧形状的改变

2024-10-01 04:45:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据在jupyter中的显示方式enter image description here

我想用这种方式显示,月份转换为datetime,并使用加拿大人来浮点数或整数
enter image description here

我使用了这段代码,但我不断收到错误“几个月没有定义,雇佣了加拿大人”

nfl2 = nfl.melt(id_vars=["Month", "Employer Persons"], 
    var_name="Province", 
    value_name="Newfoundland and Labrador")


nfl2 = nfl2.rename(columns={'Province': 'Months','Newfoundland and Labrador': 'Employed Canadians'})

nfl_final['Months'] = nfl_final['Months'].dt.strftime('%y-%m' )
nfl_final = nfl_final['Employer Persons'] = pd.Series(dtype='int')

Tags: and数据name方式jupyterfinalnfl月份
2条回答
import pandas as pd

data = {
    'Province': 'Newfound and Labrador',
    'January': 204,
    'February': 204,
    'March': 195,
    'April': 173,
    'May': 179,
    'June': 197,
    'July': 204
}

nfl = pd.DataFrame(data, index=[0])
nfl = nfl.transpose().drop('Province').reset_index()
nfl = nfl.rename({'index': 'Months', 0: 'Employed Canadians'}, axis=1)
nfl['Employed Canadians'] = nfl['Employed Canadians'].astype(float)
nfl['Months'] = pd.to_datetime(nfl['Months'], format='%B')
nfl['Months'] = nfl['Months'].apply(lambda x: x.replace(year=2020))

这应该行得通

请注意,由于没有为每个日期提供年份或日期,datetime对象默认为1970-01-01,因此我最后使用lambda函数将其更改为2020。您可以轻松地将这些日期时间格式化为仅显示为月份名称,但这会将数据类型更改为字符串

你错误地使用了melt。我建议您查看文档/教程,了解其工作原理

import pandas as pd

df = pd.DataFrame({"Province":["Hee"], "January":[4.12], "February":[76.23423]}).set_index("Province")

nfl2 = df.melt(value_vars=["January", "February"], var_name=["Months"], value_name="Employed")
nfl2.index = range(1,3)
nfl2['Months'] = pd.DatetimeIndex(pd.to_datetime(nfl2['Months'], format='%B')).month
nfl2

结果:

    Months  Employed
1   1   4.12000
2   2   76.23423

我允许自己用两个月的时间创建一个小例子。你可以随心所欲地扩展它。请提供代码,以便下次提问时预制作数据帧

当使用melt时,您应该将月份声明为“value_vars”(因为它们是值)。索引移位是为了从1开始索引,而不是从0开始索引

你不太清楚你到底想要哪种日期时间格式,所以我只花了几个月的时间%B将“一月”转换为日期格式,然后我只提取月份

相关问题 更多 >