将列表作为行和列索引添加到pandas数据框

时间:2018-07-25 14:56:15

标签: python pandas dataframe

我有一个熊猫数据框:

    0   1   2   3   4
0   4.8 2.1 0  6.2  0
1   8.5 4.9 0  2.2  0
2   0   5.3 6  9.3  0

和两个列表: ind = [ind1,ind2,ind3]和col = [col1,col2,col3,col4,col5]

我想重命名数据框索引和列,例如:

     col1 col2 col3 col4 col5
ind1 4.8  2.1   0    6.2  0
ind2 8.5  4.9   0    2.2  0
ind3  0   5.3   6    9.3  0

我尝试将列表转换为数据框,并通过df.append(col)和df.append(ind)追加。但这是行不通的(可能是因为df的索引不同于col和ind数据帧的索引)

我该怎么做?

5 个答案:

答案 0 :(得分:6)

set_axis

df.set_axis(ind, inplace=False).set_axis(col, axis=1, inplace=False)

      col1  col2  col3  col4  col5
ind1   4.8   2.1     0   6.2     0
ind2   8.5   4.9     0   2.2     0
ind3   0.0   5.3     6   9.3     0

当前版本的Pandas需要使用inplace=False。以后的版本将以inplace=False作为默认值。这会将代码减少为

df.set_axis(ind).set_axis(col, axis=1)

这将并行使用set_index。在set_index中使用set_axisaxis=0的主要区别在于,set_index需要一个Numpy数组,而set_axis使用列表。 set_index 不适用于列表,因为它会将列表解释为列列表,将其值用作MultiIndex中的元素。


我喜欢user3483203rename的使用。您还可以将callable传递给参数。这是处理为索引和列添加通用前缀的便捷方法

def prefix(t):
    def p(x):
        return f"{t}{int(x)+1}"
    return p

df.rename(index=prefix('ind'), columns=prefix('col'))

      col1  col2  col3  col4  col5
ind1   4.8   2.1     0   6.2     0
ind2   8.5   4.9     0   2.2     0
ind3   0.0   5.3     6   9.3     0

答案 1 :(得分:3)

重新创建df

ind = ['ind1', 'ind2', 'ind3']  
col = ['col1', 'col2', 'col3', 'col4', 'col5']
pd.DataFrame(df.values,columns=col,index=ind)
Out[377]: 
      col1  col2  col3  col4  col5
ind1   4.8   2.1   0.0   6.2   0.0
ind2   8.5   4.9   0.0   2.2   0.0
ind3   0.0   5.3   6.0   9.3   0.0

答案 2 :(得分:3)

如果要避免创建初始列表,请使用 rename f-strings

df.rename(
    index={i: f'ind{i+1}' for i in df.index},
    columns={i: f'col{int(i)+1}' for i in df.columns}
)

      col1  col2  col3  col4  col5
ind1   4.8   2.1     0   6.2     0
ind2   8.5   4.9     0   2.2     0
ind3   0.0   5.3     6   9.3     0

如果这只是示例命名约定,而您正在遵循另一种模式,则建议使用@piRSquared's答案。

答案 3 :(得分:2)

df = df.set_index(ind)

df.columns = col

答案 4 :(得分:0)

尝试:

df.index = ind

df.columns = col

>>> df
      col1  col2  col3  col4  col5
ind1   4.8   2.1     0   6.2     0
ind2   8.5   4.9     0   2.2     0
ind3   0.0   5.3     6   9.3     0