【问题标题】:Dataframe.reset_index() doesn't work on after concat连接后 Dataframe.reset_index() 不起作用
【发布时间】:2021-05-01 17:12:04
【问题描述】:

还有两个类似的问题 [1], [2];但没有人帮助我解决问题。

我确实在df_new 的开头和结尾连接了几列df。索引已增加,我找不到使用 df.reset_index() 解决此问题的方法。

MWE:

import pandas as pd

print("1- df: ", len(df.index),len(df.columns),"\n")
print("1- df_new: ", len(df_new.index),len(df_new.columns),"\n")

# Adding 5 columns at the begininig and 2 columns at the end of df_new from df
df_new = pd.concat([df[df.columns[0:self.x_col_start]], df_new], axis =1)
df_new = pd.concat([df_pca, df[df.columns[self.y_col:]]], axis =1)
print("2- df: ", len(df.index),len(df.columns),"\n")
print("2- df_new: ", len(df_new.index),len(df_new.columns),"\n")

# Resetting df_new
df_pca.reset_index(level=df_pca.index.names, drop=True, inplace=True)
print("3- df: ", len(df.index),len(df.columns),"\n")
print("3- df_new: ", len(df_new.index),len(df_new.columns),"\n")

Output:

1- df: 32770, 178
1- df_new: 32770, 15

2- df: 32770, 178
2- df_new: 61441, 22

3- df: 32770, 178
3- df_new: 61441, 22

这里有什么问题?

【问题讨论】:

    标签: python pandas dataframe indexing


    【解决方案1】:

    花了几个小时调试我的代码后,我发现df 已经在之前的代码块中进行了修改,因此在此处使用之前需要重置索引。经验教训。

    总是这样

    # drop=True for not adding the index column to the df
    # inplace=True for updating df inplace without copying to another object. 
    df.reset_index(drop=True, inplace=True)
    

    你做进一步的操作之前,否则,调试到最后将是一场噩梦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2015-12-02
      • 2017-08-12
      • 1970-01-01
      相关资源
      最近更新 更多