gpt4 book ai didi

python - 具有特定参数的多个字符串选择

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:52 25 4
gpt4 key购买 nike

我正在尝试对一列日期进行多项选择和修改。对于其他应用程序,日期以字符串形式转换。现在我想使用 df.loc[] 选择 1900 年的所有日期。日期格式为 mm/dd/yyyy(仍然是字符串)
所以我的尝试:

df.loc[df['Trade Date'][-4:]=='1900']=1

引发此错误:

IndexingError('Unalignable boolean Series key provided') pandas.core.indexing.IndexingError: Unalignable boolean Series key provided

这可能吗?或者我是否必须使用 df.get_value()

进行迭代

最佳答案

看起来你想对字符串进行切片,为此使用 .str:

df.loc[df['Trade Date'].str[-4:]=='1900']=1

根据您真正打算做的事情,转换为日期时间可能更有意义:

df['Trade Date'] = pd.to_datetime(df['Trade Date'])

然后你可以这样做:

df.loc[df['Trade Date'].dt.year == 1900]=1

使用 datetime 更有意义,因为数值运算可以正常工作,而将数据保存为字符串则不那么容易处理

关于python - 具有特定参数的多个字符串选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com