【发布时间】: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