Python 如何基于列(obj)将熊猫中的2行合并为1行
以下是我的数据帧信息:Python 如何基于列(obj)将熊猫中的2行合并为1行,python,pandas,Python,Pandas,以下是我的数据帧信息: 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
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)
我试图将这两行合并:
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_mean
和time_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”方式(熊猫)。您可以使用:
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
请尝试另一种方法解决问题,但不要使用1代码:
df2= df.groupby(df.time_range_1).mean().reset_index()
df2['B'] = '1001'
Output:
index time_range_1 A_mean B
0 08:00 - 08:59 5.519954 1001
1 09:00 - 09:59 5.267687 1001
谢谢@lilisten的快速回复!哦,是的,可以用。阿格!你救了我一天!:)
df2= df.groupby(df.time_range_1).mean().reset_index()
df2['B'] = '1001'
Output:
index time_range_1 A_mean B
0 08:00 - 08:59 5.519954 1001
1 09:00 - 09:59 5.267687 1001