将新的数字范围添加为数据集中的列



我想添加一个新列作为一种数字,以指示在Pandas中创建的数据帧的值。

train = pd.read_csv(r"C:MessungenTDXD1000A_Engine-Off.csv", sep=';')
seq = range(len(train.columns))
for x in seq:
print(x)
train.insert(0, 'measurement_index', x)
print(train)
Output:
[            measurement_index     t[s] timeslices[5].profilerDataProcess[8]_C0[us]  
0                    351         3,9610                                      0,0000   
1                    351         3,9620                                      0,0000   
2                    351         3,9630                                      0,0000   
3                    351         3,9640                                      0,0000   
4                    351         3,9650                                      0,0000   
...                  ...      ...                                         ...   
59843                351        63,9570                                      0,0000   
59844                351        63,9580                                      0,0000   
59845                351        63,9590                                      0,0000   
59846                351        63,9600                                      0,0000   
59847                351        63,9610                                      0,0000   

为什么我在新专栏中没有得到从0到351的数字范围?我只得到351作为我专栏的所有值?

在您现有的代码中,由于train.insert(0, 'measurement_index', x)语句存在于for循环之外,所以您将获得常量值351。

您可以像这样简单地添加新列。无需用于循环并使其复杂

seq = list(range(len(train.columns) + 1)). # The +1 is because the end value of range is usually one value less
train['measurement_index'] = seq  # Just assign the generated range to a new dataframe column

最新更新