向Pandas DataFrame添加分组均值列时结果异常问题求解
问题原因
你的猜测是正确的,df['Date_time'].copy()返回的是一维Series对象,不是二维DataFrame,因此直接赋值新列时会将整列均值作为一个新的索引项添加到Series中,而非新增一列。
解决步骤
- 首先将Date_time列以DataFrame格式复制,两种写法可选:
# 写法1:双方括号选取列,直接得到DataFrame means = df[['Date_time']].copy() # 写法2:将Series转为DataFrame # means = df['Date_time'].copy().to_frame()
- 分别计算三组列的行均值并赋值:
# 写法1:按列名前缀自动匹配分组,鲁棒性更高,不受列顺序影响 means['10cm'] = df.loc[:, df.columns.str.startswith('10')].mean(axis=1) means['40cm'] = df.loc[:, df.columns.str.startswith('40')].mean(axis=1) means['100cm'] = df.loc[:, df.columns.str.startswith('100')].mean(axis=1) # 写法2:列顺序固定时兼容你原来的切片写法 # means['10cm'] = df.loc[:, '10a':'10c'].mean(axis=1) # means['40cm'] = df.loc[:, '40a':'40c'].mean(axis=1) # means['100cm'] = df.loc[:, '100a':'100c'].mean(axis=1)
注:pandas的
mean方法默认开启skipna=True,会自动忽略NaN值计算非空值的均值,和你给出的预期输出规则完全匹配。
内容的提问来源于stack exchange,提问作者georussell
相关产品推荐
相关产品推荐

