#🔒 The code doesn't work when I combine the two functions

6 messages · Page 1 of 1 (latest)

wise mantle
#

I am trying to read data from a csv file & i'm performing the following transformations

  • Read the data
  • convert time column to datetime[ns]
  • Filter the dataframe to only include rows where the hour of the timecolumn is 8
  • Format the time column to only include the date part

In both cases the code works but in the first one, timecolumn becomes datetime[ns] dtype and in the second one it remains as object

I want to use the second code (since it solves both problems) and convert the dtype to object.

Following are both the codes,

df_2020 = pd.read_csv("2020.csv")

    df[column_name] = pd.to_datetime(df[column_name], format=date_format)
    return df```
`df_2020 = convert_to_datetime(df_2020, 'time', 'ISO8601')`

```def filter_and_format(df):
    
    df = df[df['time'].dt.hour == 8]
    
    df['time'] = df['time'].dt.date
    
    return df```
`df_2020 = filter_and_format(df_2020)`

And the second code
```def convert_filter_format(df, column_name, date_format):
    df[column_name] = pd.to_datetime(df[column_name], format=date_format)
    
    df = df[df[column_name].dt.hour == 8]
    
    df[column_name] = df[column_name].dt.date
    
    return df```

`df_2020 = convert_filter_format(df_2020,'time','ISO8601')`

I want to use the second code. It should convert time column to `datetime[ns]` format
hardy fractalBOT
#

Hey @wise mantle!

It looks like you pasted Python code without syntax highlighting.

Please use syntax highlighting to improve the legibility of your code and make it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
#

@wise mantle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

wise mantle
#

The second code is working well but is not converting timecolumn to datetime[ns]. It is still objectdata type

hardy fractalBOT
#

@wise mantle

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.