gpt4 book ai didi

python - 如何根据列(obj)将pandas中的2行合并为1行

转载 作者:行者123 更新时间:2023-12-01 09:26:46 25 4
gpt4 key购买 nike

这是我的数据框信息:

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 4 columns):
A_mean 6 non-null float64
time_range 6 non-null object
time_range_1 6 non-null object
B 6 non-null object
dtypes: float64(1), object(3)

这是df:

df

index A_mean time_range time_range_1 B
0 5.936667 07 08:00 - 08:59 1001
1 5.103241 08 08:00 - 08:59 1001
2 5.267687 09 09:00 - 09:59 1001

我试图合并这两行:

index    A_mean    time_range    time_range_1    B
0 5.936667 07 08:00 - 08:59 1001
1 5.103241 08 08:00 - 08:59 1001

进入一行,所需的输出应如下所示:

index    A_mean    time_range    time_range_1    B
0 5.519954 08 08:00 - 08:59 1001

** P/S:最重要的列是 A_meantime_range_1,B 列应保持不变。

我尝试过 .groupby,但出现错误:

df2 = df.groupby('time_range_1')['A_mean'].apply(' '.join).reset_index()

TypeError: sequence item 0: expected str instance, numpy.float64 found

任何解决方案都将受到赞赏,但以“pythonic”方式( Pandas )。

最佳答案

您可以使用:

df.groupby(['time_range_1', 'B'], as_index=False).agg({'A_mean': 'mean', 'time_range':'last'})

结果:

    time_range_1     B    A_mean  time_range
0 08:00 - 08:59 1001 5.519954 8
1 09:00 - 09:59 1001 5.267687 9

关于python - 如何根据列(obj)将pandas中的2行合并为1行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50324728/

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