【问题标题】:In Python (Pandas-Numpy), how to modify column names (strings), using a condition and iteration?在 Python(Pandas-Numpy)中,如何使用条件和迭代修改列名(字符串)?
【发布时间】:2015-04-25 02:11:24
【问题描述】:

我正在尝试修改具有很多列的数据框的列名。列名是字符串,如:

'0000', '0005'...'0100'...'2355'

由于是大量的列,我需要通过迭代来做到这一点。修改的要点是,如果列名(字符串)以“0”开头,则修改该列名(字符串),使新值仅是字符串的最后 3 位(所有字符串都有 4 位)。

所以我做的是:

将列名放在列表中

 df_cols = df.columns.tolist()

然后通过迭代做列表中的变化

for i in range(len(df_cols)):
    if df_cols[i][0] == '0':
        df_cols[i] = df_cols[i][1:4]

当我检查列表时,它有效地进行了修改。但是,当我尝试在数据框中使用列名的修改列表 (df_cols) 时:

df = df[df_cols]

我收到一条错误消息:

File "c:\users\hernan\anaconda\lib\site-packages\pandas\core\frame.py", line 1774, in __getitem__
return self._getitem_array(key)

File "c:\users\hernan\anaconda\lib\site-packages\pandas\core\frame.py", line 1818, in _getitem_array
indexer = self.ix._convert_to_indexer(key, axis=1)

File "c:\users\hernan\anaconda\lib\site-packages\pandas\core\indexing.py", line 1143, in _convert_to_indexer
raise KeyError('%s not in index' % objarr[mask])

KeyError: "['000' '001' '002' '003' '004' '005' '006' '007'....] not in index"

感谢您的帮助

【问题讨论】:

  • 你可以使用transformed_cols = ["{:03}".format(int(i)) for i in cols] 来删除一个前导零:)

标签: python numpy pandas iteration dataframe


【解决方案1】:

您刚刚更改了df_cols 的值。您必须先更新 DataFrame 的列名,然后才能使用它们:

df.columns = df_cols

【讨论】:

    【解决方案2】:

    您正在修改列的副本,而不是实际的 column_names。应该这样做:

    df_cols = df.columns.tolist()
    for i in range(len(df_cols)):
    if df_cols[i][0] == '0':
        df_cols[i] = df_cols[i][1:4]
    
    df.columns = df_cols  #Here you substitute back the modified column names to the dataframe
    

    希望对您有所帮助.. :)

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多