Skip to main content
 首页 » 编程设计

python之从数据框中打印单个日期字符串

2024年10月17日30dyllove98

我有一个名为 swap_input 的数据框,我想将当前的“日期”打印到屏幕上。

swap_input.loc[ind_current, 'date'] 
Out[26]:  
3   2016-08-31 

如何只打印“2016-08-31”?上面的方法打印索引 '3',这是误导性的

我试过了

swap_input.loc[ind_current, 'date'].values 

但给了我

Out[27]: array(['2016-08-31T00:00:00.000000000'], dtype='datetime64[ns]') 

请您参考如下方法:

ind_current 必须是某种可迭代对象。

尝试:

swap_input.loc[ind_current[0], 'date'] 

或者:

pd.DataFrame.squeeze(swap_input.loc[ind_current, 'date']) 

解释
设置

swap_input = pd.DataFrame(pd.Timestamp('2016-08-31'), [3], ['date']) 
ind_current = [3] # this is ind_current being an iterable of some kind 
 
swap_input.loc[ind_current, 'date'] 
 
3   2016-08-31 
Name: date, dtype: datetime64[ns] 

另一方面

swap_input = pd.DataFrame(pd.Timestamp('2016-08-31'), [3], ['date']) 
ind_current = 3 # this is ind_current being a single index value 
swap_input.loc[ind_current, 'date'] 
 
Timestamp('2016-08-31 00:00:00') 

每当您将类似数组的对象传递给索引器(如 loc)时,您都会沿该维度返回类似数组的东西。

因此,在您的示例中,ind_current 类似于数组,'date' 是一个标量。因此你会得到一个一维对象或一个 pandas 系列。 squeeze 压缩维度(如果可以的话)。因此可以将一维对象中的单个项目压缩到零维。