Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 更改数据帧所有行中的日期_Python_Dataframe_Python 3.7 - Fatal编程技术网

Python 更改数据帧所有行中的日期

Python 更改数据帧所有行中的日期,python,dataframe,python-3.7,Python,Dataframe,Python 3.7,我有一个示例数据帧: 我想将所有日期替换为“2012-04-28” In[101]: sample_df Out[398]: Var dates 0 A 2012-04-22 1 B 2012-04-22 2 C 2012-04-22 3 D 2012-04-22 我尝试了以下操作,但出现了一个错误: In[102]: sample_df.date.replace('2012-04-22','2012-04-28',inplace=True) C:

我有一个示例数据帧: 我想将所有日期替换为“2012-04-28”

In[101]: sample_df
Out[398]: 
  Var       dates
0   A  2012-04-22
1   B  2012-04-22
2   C  2012-04-22
3   D  2012-04-22

我尝试了以下操作,但出现了一个错误:

In[102]: sample_df.date.replace('2012-04-22','2012-04-28',inplace=True)

C:\Users\WorkStation\Anaconda3\lib\site-packages\pandas\core\generic.py:6746: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self._update_inplace(new_data)
有什么建议吗

sample_df.loc[sample_df['dates'].eq('2012-04-22'), 'dates'] = '2012-04-28'
这应该有用。

我希望这会有所帮助

df['Dates']=df.Dates.astype(str).replace('2012-04-22','2012-04-28') 

更容易。您可以指定一个值,该值将应用于所有列

sample_df.dates = '2012-04-28'

另外:在您的示例中,数据框列显示带有S的“日期”。但在代码示例中,您的“日期”是单数。

sample_df.loc[sample_df['date'].eq('2012-04-22'),'date']='2012-04-28'C:\Users\WorkStation\Anaconda3\lib\site packages\pandas\core\index.py:966:settingwithcopy警告:试图在数据帧中的切片副本上设置值。尝试使用.loc[row\u indexer,col\u indexer]=value,请参见文档中的注意事项:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-vs-a-copy self.obj[item]=s
运行此命令时,我得到以下结果…`abc.日期.替换('2012-04-22','2012-04-28')出[421]:4718 2012-04-22 4719 2012-04-22 4720 2012-04-22 4721 2012-04-22 6347 2012-04-22 6348 2012-04-22 6349 2012-04-22 6350 2012-04-22 6351 2012-04-22姓名:日期,长度:1473,数据类型:datetime64[ns]“由于某种原因,它又把原始日期返回给我。我认为你的dates列是一个datetime对象。首先需要将其转换为字符串。df['Dates']=df.Dates.astype(str).replace('2012-04-22','2012-04-28')#转换回datetime df['Dates']=pd.to_datetime(df['Dates'])@阿比吉亚,你的上帝!。转换为STR,然后更改…很乐意帮助:)@JohnDoe