Pandas 循环遍历数据框列表和更改索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44630805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:50:04  来源:igfitidea点击:

Pandas Loop through list of Data Frames and Change Index

pythonpandas

提问by geeb.24

This is a basic quesion, but I want to loop through a list of data frames and for each data frame, set the index as one of the columns in the data frame. The issue with the code below is that it doesn't save the data frame with a new index. How do I format this For loop so that the dataframes are permanently changed outside of the for loop? Thanks.

这是一个基本问题,但我想遍历数据框列表,并为每个数据框将索引设置为数据框中的列之一。下面代码的问题在于它没有使用新索引保存数据框。如何格式化此 For 循环,以便在 for 循环之外永久更改数据帧?谢谢。

dflist = [df_1, df_2, df_3]

for i in dflist:
    i = i.set_index('column_2')

回答by Oasa

As you have probably guessed, i is just a temporary value. Use i as only an index using enumerate

正如您可能已经猜到的那样, i 只是一个临时值。使用 enumerate 将 i 仅用作索引

for i, df in enumerate(dflist):
dflist[i] = dflist[i].set_index('column_2'))

回答by Love T?tting

for i in dflist:
    i.set_index('column_2', inplace=True)

回答by ChuHo

Try it with the in place option: i = i.set_index('column_2', inplace=True)

尝试使用就地选项: i = i.set_index('column_2', inplace=True)