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



当我使用自定义索引值创建新的数据帧时,它会用 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

从构造函数中删除SeriesDataFrame因为它们的默认索引是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] 
)

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

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

最新更新