1

I have a pandas data frame like following.

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

I can get value of each entry of colName using following. How to get date value?

for index, row in max_items.iterrows():
        print(str(row['colName]))
        // How to get date??
1
  • 2
    print(index) ? pd.DataFrame.index returns a tuple of the index and row. The 'date' is in the index of the dataframe as you have displayed it in this question. Commented Jun 3, 2020 at 3:00

1 Answer 1

1

Anti-pattern Warning

First I want to highlight, this is an anti-pattern, using iteration is highly counterproductive. There are extremely rare cases when you need to iterate through the pandas dataframes. Essentially, Map, Apply and applymap can achieve results efficiently.


Coming to the issue at hand: you need to convert your index to datetime if not already there.

Simple example:

# 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")

To print date, month, month name, day or day_name:

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

I would suggest read about loc, iloc and ix in the pandas' documentation that should help. I hope I didn't veer off from the crux of the question.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.