我试图在循环遍历 pandas 数据框的列时访问下一列标题。for cols in data.columns:
if data.columns.get_loc(cols) < len(data.columns): # skip last column of data
count = data.groupby([cols, cols+1]).size() # create new df and how many times the two columns occur但是cols+1给我一个错误。这是因为cols返回标题名称,所以你不能 +1 一个字符串,但是在这样的循环中获取下一列标题的最佳方法是什么?
2 回答
慕田峪4524236
TA贡献1875条经验 获得超5个赞
您可以枚举列
for col_index, cols in enumerate(data.columns): if col_index+1 < len(data.columns): # skip last column of data count = data.groupby([cols,data.columns[col_index+1]]).size() # create new df and how many times the two columns occur
长风秋雁
TA贡献1757条经验 获得超7个赞
for col_idx in range(len(data.columns)-1): if data.columns.get_loc(data.columns[col_idx]) < len(data.columns): count = data.groupby([col_idx, col_idx+1]).size()
添加回答
举报
0/150
提交
取消