在DataFrame中添加列(日期)

时间:2019-01-30 04:01:14

标签: python pandas

我想用日期替换“一”和“二”,所以我将代码如下:

df = pd.DataFrame(d,columns = dates)

我可以知道我缺少哪一部分吗?

我有这样的代码:

d = { 'one': pd.Series([100,200,300],index = ['Sai Ying Pun','Kennedy Town','Sheung Wan']),
    'two': pd.Series([150,250,350,450], index = ['Sai Ying Pun','Kennedy Town','Sheung Wan','Central'])}

dates = pd.date_range('20190101',periods = 4)

我期望:

             2019-01-01   2019-01-02   2019-01-03  2019-01-04
Central         NaN       450             NaN        NaN
Kennedy Town    200.0     250             NaN        NaN
Sai Ying Pun    100.0     150             NaN        NaN
Sheung Wan      300.0     350             NaN        NaN

但不幸的是,仅显示了以下内容,而没有其他内容:

2019-01-01 00:00:00 2019-01-02 00:00:00 2019-01-03 00:00:00 2019-01-04 00:00:00

2 个答案:

答案 0 :(得分:2)

尝试以下

d = {'one': pd.Series([100, 200, 300], index=['Sai Ying Pun', 'Kennedy Town', 'Sheung Wan']),
     'two': pd.Series([150, 250, 350, 450], index=['Sai Ying Pun', 'Kennedy Town', 'Sheung Wan', 'Central'])}

# format the datetimeindex to %Y-%m-%d to give the date column names and put them in a list
dates = pd.date_range('20190101', periods=4).strftime('%Y-%m-%d').tolist()

# create an empty dataframe with dates as its column names
df = pd.DataFrame(columns=dates)

# create another dataframe using d as its data
df_to_append = pd.DataFrame(d)

# rename the column names to dates following the order
df_to_append.columns = dates[:len(d)]

# finally, append the dataframe together
df = df.append(df_to_append)

输出

              2019-01-01 2019-01-02 2019-01-03 2019-01-04
Central              NaN        450        NaN        NaN
Kennedy Town       200.0        250        NaN        NaN
Sai Ying Pun       100.0        150        NaN        NaN
Sheung Wan         300.0        350        NaN        NaN

答案 1 :(得分:0)

这对您有用吗?

import numpy as np
new_df =pd.DataFrame(d)
new_df.columns = dates[:2]   # rename the existings columns
new_df[dates[2]] = np.nan    # new column with NaN
new_df[dates[3]] = np.nan
new_df