熊猫没有将数据框的某些列转换为datetimeindex

时间:2020-08-19 18:12:30

标签: python pandas dataframe datetimeindex

直到现在我的数据框, enter image description here

,并且我尝试将cols(这是从{strong> 0到188 ( cols = list(hdata.columns[ range(0,188) ]) )的所有列,这些列的格式为yyyy-mm转换为datetimeIndex的列表。还有其他几列是“字符串”名称,因此无法将其转换为dateTime,所以我尝试这样做,

hdata[cols].columns = pd.to_datetime(hdata[cols].columns) #convert columns to **datetimeindex**

但这有效。 您能找出问题在哪里吗?

编辑: 处理此类数据的更好方法是使用 Split-Apply-Combine 方法。

步骤1:拆分要执行某些特定操作的数据。

nonReqdf = hdata.iloc[:,188:].sort_index()
reqdf= reqdf.drop(['CountyName','Metro','RegionID','SizeRank'],axis=1)

第2步:。在我的情况下,它将具有年和月的数据框列转换为datetimeIndex。然后每季度重新采样。

reqdf.columns = pd.to_datetime(reqdf.columns)
reqdf = reqdf.resample('Q',axis=1).mean()
reqdf = reqdf.rename(columns=lambda x: str(x.to_period('Q')).lower()).sort_index() # renaming so that string is yyyy**q**<1/2/3/4> like 2012q1 or 2012q2 likewise

步骤3:组合两个拆分的数据框。(merge可以使用,但可能取决于您想要的内容)

reqdf = pd.concat([reqdf,nonReqdf],axis=1)

1 个答案:

答案 0 :(得分:1)

为了修改索引中的某些标签(用于行或列),您需要使用df.rename

for i in range(188):
    df.rename({df.columns[i]: pd.to_datetime(df.columns[i])},
        axis=1, inplace=True)

或者您可以通过构建完整大小的索引来覆盖所有列来避免循环

df.columns = (
    pd.to_datetime(cols) # pass the list with strings to get a partial DatetimeIndex
    .append(df.columns.difference(cols)) # complete the index with the rest of the columns
)