python Pandas DataFrame索引的自动递增选项

tvz2xvvm  于 2022-12-17  发布在  Python
关注(0)|答案(2)|浏览(73)

有没有办法在添加新行时设置自动递增panda.DataFrame索引的选项,或者定义一个函数来管理新索引的创建?

ogsagwnx

ogsagwnx1#

append-ing时,可以设置ignore_index=True

In [1]: df = pd.DataFrame([[1,2],[3,4]])

In [2]: row = pd.Series([5,6])

In [3]: df.append(row, ignore_index=True)
Out[3]: 
   0  1
0  1  2
1  3  4
2  5  6
siv3szwd

siv3szwd2#

请注意,如果您现有的索引是有意义的,则可接受的答案是危险的。例如:

df = pd.DataFrame(
    [('Alice', 1010, 'sales'), ('Bob', 1011, 'service')],
    columns = ['name', 'emp_id', 'dept']
).set_index('emp_id')

# here's a new employee to append, who has no id:
row = pd.Series({'name': 'Eve', 'dept': 'r&d'})

# this will wipe all the existing employee id numbers:
df.append(row, ignore_index=True)

解决此问题的一种方法是手动递增索引:

def add_new_row(df, row):
    row.name = max(df.index)+1
    return df.append(row)

# the existing ids are now preserved:
add_new_row(df, row)

相关问题