gpt4 book ai didi

python - 从 groupby pandas python 中连接字符串的一部分

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:23 25 4
gpt4 key购买 nike

执行 groupby 后如何将日期的一部分与文件名连接起来。
我想最终得到一个数组:'你好,2014 年 1 月 2 日','你好,2014 年 1 月 2 日'

我的代码的结果令人惊讶。

import pandas as pd
from datetime import datetime
d = { 'File' : pd.Series(['hello', 'what']),
'Status' : pd.Series([0., 0.]),
'Error' : pd.Series([2., 2.]),
'AlertDays' : pd.Series([2., 2.]),
'Date' : pd.Series([datetime(2014, 1, 2), datetime(2014, 1, 2)])}
df=pd.DataFrame(d)
df['Date']=pd.to_datetime(df['Date'])
Faildf=df[df.Status==0]
Fx=Faildf.groupby('File')['Date'].max().reset_index()
Fx['concat']=Fx['File'] +' '+ str(Fx['Date'])
#FailArray=Fx['concat'].unique()

为什么有多个日期...我以为我通过执行 groupby 和 max 丢失了其他日期?结果:

>>> Fx
File Date concat
0 hello 2012-05-02 00:00:00 0 2012-05-02 00:00:00\n1 2012-05-02 00:00:...
1 what 2012-05-02 00:00:00 0 2012-05-02 00:00:00\n1 2012-05-02 00:00:...

最佳答案

问题是您正在将 pandas Series Fx['File'] 与 pandas Series str(Fx['Date']) 的字符串表示形式连接起来,您需要做的是将 str 转换函数应用于 Fx['Date'] 的元素,如下所示:

>>> Fx['File'] + " " + Fx['Date'].apply(str)
0 hello 2014-01-02 00:00:00
1 what 2014-01-02 00:00:00

关于python - 从 groupby pandas python 中连接字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21099427/

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