如何使用python中的循环重置多个熊猫数据帧的索引?

时间:2019-04-08 17:28:23

标签: python pandas

如何使用python中的循环重置多个熊猫数据框的索引?

我的列表中有17个数据帧,我想使用循环为所有这些数据帧重新设置索引。

有帮助吗?

3 个答案:

答案 0 :(得分:2)

您需要记住,reset_index并不是就地操作,您需要重新分配或使用inplace参数。

df1 = pd.DataFrame(index=np.arange(1,10))
df2 = pd.DataFrame(index=pd.date_range('2019-01-1', periods=10))
df3 = pd.DataFrame(index=[*'ABCDEFGHIJ'])

lofdfs = [df1, df2, df3]
for df in lofdfs:
    df.reset_index(inplace=True)

或者,使用列表理解:

[df.reset_index(inplace=True) for df in lofdfs]

答案 1 :(得分:1)

这将是imo的最简单方法:

#This list contains the names of all of your dataframes
list_dataframes = [foo1, foo2, foo3, ..... , foo17]

for dataframe in list_dataframes:
    dataframe.reset_index(inplace=True)

答案 2 :(得分:1)

熊猫人的documentation说:

reset_index::重置DataFrame的索引,并使用默认索引。如果DataFrame具有MultiIndex,则此方法可以删除一个或多个级别。

当您具有复杂的数据框时,这是util,但是如果您有单独的数据框,则可以执行以下操作:

for df in dataframes:
    df.reset_index(inplace=True)