如何将熊猫日期时间对象转换为不带索引的字符串

时间:2019-07-03 09:13:33

标签: pandas list datetime casting

我正在尝试将datetime64熊猫对象转换为字符串而不打印索引。

我有一个包含以下内容的csv文件

Dates
2019-06-01
2019-06-02
2019-06-03

当我通过熊猫导入csv文件时,该列中有一个普通的熊猫对象。

df['Dates'] =  pd.to_datetime(df['Dates'], format='%Y-%m-%d')

这提供了datetime64 [ns]对象。我尝试使用以下输出打印该对象。

>>> What is the date 0   2019-06-01
    Name: Dates, dtype: datetime64[ns]

所以我必须将此对象转换为字符串。该文档建议我使用dt.strftime()。

s=df["Dates"].dt.strftime("%Y-%m-%d")
print(f"What is the date {s['Dates'}")

上面的输出是:

>>> What is the date 0  2019-06-01

如何从输出中删除索引?


file = r'test.csv'
df = pd.read_csv(file)

df['Dates'] =  pd.to_datetime(df['Dates'], format='%Y-%m-%d')


s = df[df["Dates"] < "2019-06-02"]
print(f"What is the date {s['Dates']}")

print(s["Dates"])

预期的输出如下:

>>> What is the date 2019-06-01

但是我得到以下内容

>>> What is the date 0  2019-06-01

1 个答案:

答案 0 :(得分:0)

您可以尝试:

[print(f"What is the date {x}") for x in s['Dates'].astype('str')]

给予:

What is the date 2019-06-01
What is the date 2019-06-02
What is the date 2019-06-03