【问题标题】:convert to df column to datetime - raise SettingWithCopyWarning转换为 df 列到日期时间 - 提高 SettingWithCopyWarning
【发布时间】:2020-08-27 07:45:51
【问题描述】:

我有一个 Pandas DataFrame 'Date' 列,我正在尝试将其转换为日期时间。它正在转换并引发“SettingWithCopyWarning”

我尝试遵循其他出色的解释,例如:How to deal with SettingWithCopyWarning in Pandas? 等,但无法弄清楚。 谢谢大家!

我的原始代码:

import numpy as np
import pandas as pd

data = pd.DataFrame(pd.read_excel('Restaurant Shifts Data.xlsx', na_values='-'))    # (-) value in cash
data.fillna(0)

columns = ['Waiter','Start','Finish','Cash','Credit','Total Hours','Total Shift','Date','Shift','Shift manager']
restaurant_data = data[columns]
restaurant_data[['Cash', 'Credit','Total Shift']] = restaurant_data[['Cash', 'Credit','Total Shift']].apply(pd.to_numeric)
restaurant_data['Date'] = pd.to_datetime(restaurant_data['Date'])
restaurant_data['Day'] = restaurant_data['Date'].dt.day_name()

用 .loc 尝试了不同的组合: restaurant_data.loc[:,'Date'] = pd.to_datetime(restaurant_data['Date'])

日期(数据示例)

0 2020-01-01

1 2020-01-01

2 2020-01-01

完整的错误信息

...\python\python38-32\lib\site-packages\pandas\core\frame.py:2963: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self[k1] = value[k2]
<ipython-input-51-0b817be48c52>:10: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  restaurant_data['Date'] = pd.to_datetime(restaurant_data['Date'])

【问题讨论】:

  • restaurant_data = data[columns].copy()。另外,data=data.fillna().

标签: python pandas dataframe datetime


【解决方案1】:

使用.loc syntax 获取和设置值。这种语法的好处是更清晰(即,您引用的是行还是列更明显)。

您写道您尝试了.loc,但您没有显示不起作用的代码。试试下面的。

import numpy as np
import pandas as pd

data = pd.DataFrame(pd.read_excel('Restaurant Shifts Data.xlsx', na_values='-'))    # (-) value in cash
data.fillna(0)

columns = ['Waiter','Start','Finish','Cash','Credit','Total Hours','Total Shift','Date','Shift','Shift manager']
restaurant_data = data.loc[:, columns]
restaurant_data.loc[:, ['Cash', 'Credit','Total Shift']] = restaurant_data.loc[:, ['Cash', 'Credit','Total Shift']].apply(pd.to_numeric)
restaurant_data.loc[:, 'Date'] = pd.to_datetime(restaurant_data.loc[:, 'Date'])
restaurant_data.loc[:, 'Day'] = restaurant_data.loc[:, 'Date'].dt.day_name()

【讨论】:

  • 感谢您的描述性回答,非常有帮助!
猜你喜欢
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
  • 2017-05-14
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
相关资源
最近更新 更多