【问题标题】:Unable to change to type string from type series无法从类型系列更改为类型字符串
【发布时间】:2021-08-26 16:00:37
【问题描述】:

我对 Python 还是很陌生。 我有一个包含两列的数据框。第二列来自系列类型。 他们都有一个我想删除的后缀。我试图将其转换为字符串,然后最大化字符串大小。但没有任何效果。

我试过了:.

df['id'].astype(basestring)

df['id']= df['id'].astype(str)

df['id'] = df['id'].astype("string")

df['id'] = pandas.Series(df['id'], dtype="string")

df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)

该列如下所示:

28.04.2019 10:00

29.04.2019 13:00

30.04.2019 14:00
...

我只想要日期并删除时间。我还有其他选择可以达到我的目标吗?

提前谢谢你!

【问题讨论】:

标签: python pandas string dataframe series


【解决方案1】:

1.如果ID列的类型是日期时间,那么试试

df['id'] = df['id'].dt.date

2.如果类型是字符串,则先转换成datetime再去掉时间戳

df['id'] = pd.to_datetime(df['id'], format = '%d.%m.%Y %H:%M').dt.date

【讨论】:

  • 感谢您的帮助。不幸的是,两者都不起作用。第一次尝试的错误是:AttributeError: Can only use .dt accessor with datetimelike values 第二个:KeyError: "None of [Int64Index([67], dtype='int64')] are in the [columns]" 是还有什么我可以尝试的吗?
  • 您能告诉我“ID”列中数据的确切格式吗?
猜你喜欢
  • 2015-08-02
  • 2020-06-24
  • 2023-03-16
  • 2018-03-21
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多