将值分配给熊猫 /重命名为日期列的DateTime列中的DateTime列



dataframe image

我已经在pandas中创建了以下数据帧" user_char",

## Create a new workbook User Char with empty datetime columns to import data from the ledger
user_char = all_users[['createdAt', 'uuid','gasType','role']]
## filter on consumers in the user_char table
user_char = user_char[user_char.role == 'CONSUMER']
user_char.set_index('uuid', inplace = True)
## creates datetime columns that need to be added to the existing df
user_char_rng = pd.date_range('3/1/2016', periods = 25, dtype = 'period[M]', freq = 'MS')
## converts date time index to a list
user_char_rng = list(user_char_rng)
## adds empty cols
user_char = user_char.reindex(columns = user_char.columns.tolist() + user_char_rng) 
user_char

我试图使用以下命令为突出显示的列分配一个值:

user_char['2016-03-01 00:00:00'] = 1

但这是创建一个新列而不是编辑现有列。如何在不添加新列的情况下将值1分配给所有索引?

还如何重命名DateTime列,该列不包括时间戳,仅在其中留下日期字段?

尝试

user_char.loc[:, '2016-03-01'] = 1

由于您的列索引是DatetimeIndex,因此PANDAS足够聪明,可以将字符串'2016-03-01'转换为DateTime格式。使用loc[c]似乎暗示了Pandas在索引中首次查找c,而不是创建一个名为c的新列。

旁注:时间序列数据的数据录制通常用作数据框的(行(索引,而不是列中。(当然,没有技术原因为什么您不能在列中使用时间!(根据我的经验,构建了大多数Pydata堆栈是为了期望"整洁数据",其中每个变量(如时间(形成列,并且每个观察值(时间戳值(形成一行。例如,您需要在调用 plot()之前要转换数据框。

最新更新