Pandas DataFrame索引的自增选项
有没有办法在往pandas.DataFrame里添加新行的时候,自动给索引编号,或者定义一个函数来管理新索引的创建呢?
2 个回答
0
请注意,如果你现有的索引是有意义的,那么接受的答案可能会很危险。例如:
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)
27
在使用append
方法添加数据时,你可以设置一个选项叫做 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