-1

I'm trying to create a new dataframe using chaining in pandas.

result = (
    df.drop(['Day_of_year', 'Month', 'Week_of_year'], axis='columns'),
    pd.to_datetime(df['timestamp']),
    .assign("random" = 0)
)


# Access the first element of the tuple
updated_df = result[0]
updated_df

If I comment out the last line the code in the tuple work but I want to assign new columns.

How do I do this?

elksie5000
  • 7,084
  • 12
  • 57
  • 87
  • 1
    You want `.assign(random = 0)`, not `.assign("random" = 0)` – rafaelc Jul 06 '23 at 17:08
  • Do you realize that `, .` is a syntax error? And did you read the docs on `df.assign`? And why are you creating a tuple in the first place? What's your desired result? Please make a [mre]. For specifics, see [How to make good reproducible pandas examples](/q/20109391/4518341). – wjandrea Jul 07 '23 at 01:31

1 Answers1

1

Try this:

updated_df = (
    df.drop(columns=['Day_of_year', 'Month', 'Week_of_year'])
    .assign(**{"random": 0, 'timestamp': pd.to_datetime(df['timestamp'])})
)

Testing

Evaluating the above code on a dummy dataframe:

import pandas as pd

# Create a date range
date_range = pd.date_range(start='2023-07-01', end='2023-07-10')

# Create the DataFrame
df = pd.DataFrame()
df['timestamp'] = date_range
df['Day_of_year'] = df['timestamp'].dt.dayofyear
df['Month'] = df['timestamp'].dt.month
df['Week_of_year'] = df['timestamp'].dt.isocalendar().week

updated_df = (
    df.drop(columns=['Day_of_year', 'Month', 'Week_of_year'])
    .assign(**{"random": 0, 'timestamp': pd.to_datetime(df['timestamp'])})
)
print(updated_df)
# Prints:
#
#    timestamp  random
# 0 2023-07-01       0
# 1 2023-07-02       0
# 2 2023-07-03       0
# 3 2023-07-04       0
# 4 2023-07-05       0
# 5 2023-07-06       0
# 6 2023-07-07       0
# 7 2023-07-08       0
# 8 2023-07-09       0
# 9 2023-07-10       0
Ingwersen_erik
  • 1,701
  • 1
  • 2
  • 9