无法从字典中打印月份值
Can't print month value from dictionary
我正在尝试从这本字典中打印月份名称,它在代码之前定义得很好:
month_index = { '1': 'January',
'2': 'February',
'3': 'March',
'4': 'April',
'5': 'May',
'6': 'June'}
我尝试使用 dataframe.mode()
从一些输出多列的数据框中访问元素,其中一列生成月份列,其中的值仅为 1、2、3、4、5 或 6,代表一月到六月。 dataframe.mode
正在生产 0 6
,其中 6 = 六月。
common_month = df['month'].mode()
if common_month in month_index:
print('The most common month is ', month_index, '.')
我应该用 .mode()
的结果创建一个字典,还是只使用 df['month'].mode().str[1]
然后使用 in
来访问 month_index 中的值?如有任何帮助,我们将不胜感激。
您现在的做法是检查 common_month
的字典键,但您需要检查值。另外我假设你只想打印最常见的月份,而不是整个字典。只需将 if 语句更改为此即可。
if common_month in month_index.values():
print(f'The most common month is {common_month}.')
mode() 函数将 returning object pandas.core.series.Series
数据类型。而且您没有检查字典值。所以你必须在common_month中使用any/all,获取索引,并检查字典中的值。
if common_month.any() in month_index.values():
print('The most common month is', common_month[0], '.')
我正在尝试从这本字典中打印月份名称,它在代码之前定义得很好:
month_index = { '1': 'January',
'2': 'February',
'3': 'March',
'4': 'April',
'5': 'May',
'6': 'June'}
我尝试使用 dataframe.mode()
从一些输出多列的数据框中访问元素,其中一列生成月份列,其中的值仅为 1、2、3、4、5 或 6,代表一月到六月。 dataframe.mode
正在生产 0 6
,其中 6 = 六月。
common_month = df['month'].mode()
if common_month in month_index:
print('The most common month is ', month_index, '.')
我应该用 .mode()
的结果创建一个字典,还是只使用 df['month'].mode().str[1]
然后使用 in
来访问 month_index 中的值?如有任何帮助,我们将不胜感激。
您现在的做法是检查 common_month
的字典键,但您需要检查值。另外我假设你只想打印最常见的月份,而不是整个字典。只需将 if 语句更改为此即可。
if common_month in month_index.values():
print(f'The most common month is {common_month}.')
mode() 函数将 returning object pandas.core.series.Series
数据类型。而且您没有检查字典值。所以你必须在common_month中使用any/all,获取索引,并检查字典中的值。
if common_month.any() in month_index.values():
print('The most common month is', common_month[0], '.')