将索引值设置为pd.数据帧`index`参数从列中删除数据

2024-04-27 04:52:55 发布

您现在位置:Python中文网/ 问答频道 /正文

当我用自定义索引值创建新的DataFrame时,它用NaN/NaT值替换列中的数据。你知道吗

我试过分配pd索引作为index参数,结果也是一样的。你知道吗

pd.DataFrame(
    data={
        "date": pd.Series([datetime(2000, 1, 2)]),
        "duration": pd.Series([datetime(1970, 1, 1, 0, 5)]),
    }
    index = [1] 
    )

而不是:

    date    duration
1   2000-01-02  1970-01-01 00:05:00

我收到:

    date    duration
1   NaT NaT

是虫子吗?你知道吗

我用熊猫0.25.0


Tags: 数据dataframedata参数datetimedateindexnan
1条回答
网友
1楼 · 发布于 2024-04-27 04:52:55

DataFrame构造函数中删除Series,因为它们的默认索引是0,与index of DataFrame不同,所以返回缺少的值(索引必须匹配):

df = pd.DataFrame(
    data={
        "date": [datetime(2000, 1, 2)],
        "duration": [datetime(1970, 1, 1, 0, 5)],
    },
    index = [1] 
    )

print (df)
        date            duration
1 2000-01-02 1970-01-01 00:05:00

细节

print (pd.Series([datetime(2000, 1, 2)]))
0   2000-01-02
dtype: datetime64[ns]

因此,如果需要Series,也需要将索引设置为1

df = pd.DataFrame(
    data={
        "date": pd.Series([datetime(2000, 1, 2)], index = [1]),
        "duration": pd.Series([datetime(1970, 1, 1, 0, 5)],index = [1]),
    },
    index = [1] 
    )

或删除DataFrame中的默认0索引:

df = pd.DataFrame(
    data={
        "date": pd.Series([datetime(2000, 1, 2)]),
        "duration": pd.Series([datetime(1970, 1, 1, 0, 5)]),
    },
    )

print (df)
        date            duration
0 2000-01-02 1970-01-01 00:05:00

相关问题 更多 >