如何按行名将DataFrame中两行的字符串值合并为新行?
解决DataFrame按行拼接字符串添加新行的问题
原始DataFrame
Jan Feb a 1 3 b 2 4
注:实际数据类型为字符串,目标是将a、b两行对应列的字符串以/拼接,新增行名为c的行。
实现代码
import pandas as pd # 构造原始DataFrame(确保数据为字符串类型) df = pd.DataFrame( {'Jan': ['1', '2'], 'Feb': ['3', '4']}, index=['a', 'b'] ) # 生成新行:对每一列拼接a、b行的字符串 new_row = df.loc[['a', 'b']].apply(lambda col: '/'.join(col), axis=0) new_row.name = 'c' # 将新行添加到原DataFrame,新版本pandas推荐用pd.concat df = pd.concat([df, new_row.to_frame().T])
最终结果
Jan Feb a 1 3 b 2 4 c 1/2 3/4
如果原始数据是数值类型,只需把拼接逻辑改成lambda col: '/'.join(map(str, col)),先转字符串再拼接即可。
内容的提问来源于stack exchange,提问作者Rachel Porter
相关产品推荐
相关产品推荐

