原代码:
def change_to_date_format_backup(data_frame, head):
for idx in data_frame.index:
value = data_frame.loc[idx, head]
if pd.isnull(value): # NaT 也会是datetime.datetime
pass
elif value == '-': # 这种待修改
pass
elif isinstance(value, datetime.datetime):
pass
elif '/' in value:
value = datetime.datetime.strptime(value, '%Y/%m/%d')
elif '-' in value:
value = datetime.datetime.strptime(value, '%Y-%m-%d')
else:
pass
data_frame.loc[idx, head] = value
return (data_frame)
处理东西的时候的报错信息:
C:\Users\Administrator\anaconda3\lib\site-packages\pandas\core\indexing.py:190: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)
02.pandas_time_seq.py:52: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
data_frame.loc[idx, head] = value
后来搜了一下,处理方式都放在了下面这个函数的说明中了 (几个链接)
主要是要避免链式索引
def change_to_date_format(data_frame, head):
'''
报错的地方及修改方式:
https://www.pianshen.com/article/4967875215/
https://blog.csdn.net/zaishijizhidian/article/details/98207892
https://blog.51cto.com/yunyaniu/2912530
https://www.jianshu.com/p/72274ccb647a
:param data_frame:
:param head:
:return:
'''
data_frame = data_frame.copy()
for idx in data_frame.index:
value = data_frame.loc[idx, head]
if pd.isnull(value): # NaT 也会是datetime.datetime
pass
elif value == '-': # 这种待修改
pass
elif isinstance(value, datetime.datetime):
pass
elif '/' in value:
value = datetime.datetime.strptime(value, '%Y/%m/%d')
elif '-' in value:
value = datetime.datetime.strptime(value, '%Y-%m-%d')
else:
pass
data_frame.loc[idx, head] = value
return (data_frame)
很多时候,要在原来的DataFrame 上修改,但原来的DataFrame的shape与新的DataFrame的shape可能不一样。
set, 可以理解为复制。
所以 df = df.copy()
新建一个副本来操作,很重要