将增量整数分配为列标题 - Python

问题描述 投票:0回答:1

我试图在特定的assign后自动integers column作为headers pandas dfstring。我可以通过读取和计算任何一个columns中的df的数量来手动完成此操作。例如

df.columns=['X',1,2,3...]

但我想自动实现这一点,而不必count columns的数量。第一个column应该是string然后自动将增量integers分配给其他列。

我尝试使用@ kudeh的建议来实现这一点。

df.columns = 'X' + [i for i in range(1,len(df.columns)+1)]

但是这会返回一个错误:

df.columns = 'X' + [i for i in range(1,len(df.columns)+1)]

TypeError: must be str, not list

预期产出:

df.columns = ['X',1,2,3...]
python pandas dataframe int assign
1个回答
1
投票
cols = ['X']
otherCols = [i for i in range(1,len(df.columns))]
cols.extend(otherCols)

df.columns = cols
© www.soinside.com 2019 - 2024. All rights reserved.