如何获得大熊猫索引栏的价值?

时间:2020-06-03 02:59:34

标签: python pandas

我有一个如下的熊猫数据框。

                  colName      
date        
2020-06-02 03:00:00 39

我可以使用以下方法获取colName的每个条目的值。如何获取日期值?

for index, row in max_items.iterrows():
        print(str(row['colName]))
        // How to get date??

1 个答案:

答案 0 :(得分:1)

反模式警告

首先,我想强调一下,这是一种反模式,使用迭代会适得其反。 在极少数情况下,您需要遍历熊猫数据框。本质上,Map,Apply和applymap可以有效地实现结果。


谈到当前的问题: 您需要将索引转换为日期时间(如果还没有的话)。

简单示例:

# Creating the dataframe
df1 = pd.DataFrame({'date':pd.date_range(start='1/1/2018', end='1/03/2018'), 
                   'test_value_a':[5, 6, 9], 
                   'test_value_b':[2, 5, 1]})

# Coverting date column into index of type datetime.
df1.index = pd.to_datetime(df1.date)

# Dropping date column we had created
df1.drop(labels='date', axis="columns")

要打印日期,月份,月份名称,日期或日期名称:

df1.index.date
df1.index.month
df1.index.month
df1.index.month_name
df1.index.day
df1.index.day_name

我建议在熊猫的文档中阅读有关 loc,iloc和ix 的信息,这应该会有所帮助。 我希望我不会偏离问题的症结所在。

相关问题