【问题标题】:SettingWithCopyWarning message when transforming Datetime Date into String Python Dataframe将 Datetime Date 转换为 String Python Dataframe 时的 SettingWithCopyWarning 消息
【发布时间】:2017-06-09 19:33:51
【问题描述】:

在将日期转换为字符串时,我收到以下警告消息:

SettingWithCopyWarning:试图在一个副本上设置一个值 从 DataFrame 切片。尝试使用 .loc[row_indexer,col_indexer] = 取而代之的价值

我正在做以下事情:

Data['Date'] = Data['Date'].dt.strftime('%Y-%m-%d')

【问题讨论】:

  • 它实际上建议你Try using .loc[row_indexer,col_indexer] = value instead
  • @VitaliiStrimbanu,谢谢,但我试过 Data.loc['Date'] = Data['Date'].dt.strftime('%Y-%m-%d')它不工作,我收到以下错误消息:SettingWithCopyWarning: A value is trying to be set on a slice of a copy from a数据框
  • 你将不得不在你的数据框上使用 .apply 和一个 lambda 函数:stackoverflow.com/questions/19738169/…
  • 试试Data.loc[:, 'Date'] = Data['Date'].dt.strftime('%Y-%m-%d')。在post中查看更多信息

标签: python date dataframe


【解决方案1】:

如果您提供代码示例,我可以修改此答案以更具体地满足您的要求。如果这个答案被认为对引用的问题中给出的答案是多余的,请告诉我,我将删除它。

我应该说清楚,以下是对这个问题的答案的几乎完全复制:datetime to string with series in python pandas

对于一些数据框:

df = pandas.Series(['20010101', '20010331'])

0    20010101
1    20010331
dtype: object

# Convert to the format you need:

dates = pandas.to_datetime(A, format = '%Y-%m-%d')

0   2001-01-01
1   2001-03-31
dtype: datetime64[ns]

# Then to convert back, do:

df2 = dates.apply(lambda x: x.strftime('%Y-%m-%d'))

0    2001-01-01
1    2001-03-31
dtype: object

【讨论】:

  • 谢谢。上面的答案有所帮助。您可以根据需要将其删除,但它也有助于解决其他问题。
  • 好的,很高兴它有帮助,我会留下它。但@EdChum 应该知道:这取决于你,我不争辩。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多