【问题标题】:Modify the column headers of a pandas data frame修改 pandas 数据框的列标题
【发布时间】:2019-04-19 02:28:30
【问题描述】:

我有这个列标题:

我将这些放在x = list(df) 的列表中,x 的类型是一个字符串。我想将它们放入另一个字符串列表中,但将它们转换为 8/18、7/18、6/18 等...

这里是 df.head() 输出:

print(df.columns)的输出

<class 'str'>
Index(['NDD 8/31', 'Aug 2018(P&I Applied)', 'Jul 2018(P&I Applied)',
       'Jun 2018(P&I Applied)', 'May 2018(P&I Applied)',
       'Apr 2018(P&I Applied)', 'Mar 2018(P&I Applied)',
       'Feb 2018(P&I Expected)', 'Jan 2018(P&I Applied)',
       'Dec 2017(P&I Applied)', 'Nov 2017(P&I Applied)',
       'Oct 2017(P&I Applied)', 'Sep 2017(P&I Applied)',
       'Paystring as of cut off as if 10.31',
       'Paystrings as of 

有谁知道如何做到这一点?

【问题讨论】:

  • 能否将 print(df.columns) 的输出添加到问题中?
  • @ScottBoston 添加
  • 您想只替换Jun 2018 -&gt; 6/18,还是应该将整个列名替换为6/18
  • @MatthiasOssadnik 不,我不需要修改数据框,我只想转换 Jun 2018 -> 6/18 并将其放入向量或列表中

标签: python pandas datetime dataframe indexing


【解决方案1】:

您可以转换为datetime,然后使用strftime。以下逻辑还确保非日期列保持不变。

df = pd.DataFrame(columns=['Aug 2018(P&I Applied)', 'Jul 2018(P&I Applied)',
                           'Jun 2018(P&I Applied)', 'Paystring as of cut off as if 10.31'])

dates = pd.Series(pd.to_datetime(df.columns.str[:8], errors='coerce'))

df.columns = dates.dt.strftime('%m/%y').mask(dates.isnull(), pd.Series(df.columns))

print(df.columns)

# Index(['08/18', '07/18', '06/18', 'Paystring as of cut off as if 10.31'], dtype='object')

print(dates.dt.month)

# 0    8.0
# 1    7.0
# 2    6.0
# 3    NaN
# dtype: float64

【讨论】:

  • 您能否重新编辑您的答案以包含我拥有的数据框?
  • @Snorrlaxxx,不,我不能,因为您的问题没有完整的数据框。
  • 好的,如何将系列转换为字符串?
  • @Snorrlaxxx,我不明白你的问题,也许是str(my_series)
  • 快速提问如何从日期列表中获取月份?
猜你喜欢
  • 2019-07-15
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
相关资源
最近更新 更多