lmi*_*asf 4 python datetime pandas
我需要将数据框转换为列表,其中一列的类型为datetime64,但是当我values.tolist()在数据框中应用时,它会转换为Timestamp,而我希望它是datetime.date.
此数据框是从之前读取的 Google Sheet 中获取的:
def get_dataframe_from_sheet(spreadsheet_id, sheet_name, sheet_range):
range_name = '{}!{}'.format(sheet_name, sheet_range)
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheet_id, range=range_name).execute()
values = result.get('values', [])
col_names = values.pop(0)
df = pd.DataFrame(values, columns=col_names)
for col in col_names:
if col in ('forecast_month'):
df[col] = pd.to_datetime(df[col], infer_datetime_format=True)
df[col] = df.apply()
else:
df[col] = pd.to_numeric(df[col], errors='coerce')
return df
short_term_df = get_dataframe_from_sheet(SHORT_TERM_SPREADSHEET_ID, SHEET_NAME, COLUMNS)
Run Code Online (Sandbox Code Playgroud)
但是,当我应用以下内容时:
LIST__SHORT_TERM_FORECAST_SEASON_ADJ_OCC = short_term_df[base_columns + ['season_adj_occ']].values.tolist()
Run Code Online (Sandbox Code Playgroud)
该列的值forecast_month是 类型Timestamp,我需要datetime.date. 我怎样才能做到这一点?我已经阅读了几个问题及其答案,但似乎它们无法正常工作。
例子:
这是我从函数中得到的get_dataframe_from_sheet:
property_id beds forecast_month rent_growth baseline_occ \
0 329 1 2017-02-01 0.02 0.953623
1 329 1 2017-03-01 0.02 0.953623
2 329 1 2017-04-01 0.02 0.953623
3 329 1 2017-05-01 0.02 0.953623
4 329 1 2017-06-01 0.02 0.953623
5 329 1 2017-07-01 0.02 0.953623
6 329 1 2017-08-01 0.02 0.953623
7 329 1 2017-09-01 0.02 0.953623
8 329 1 2017-10-01 0.02 0.953623
9 329 1 2017-11-01 0.02 0.953623
10 329 1 2017-12-01 0.02 0.953623
11 329 1 2018-01-01 0.02 0.953623
12 329 1 2018-02-01 0.02 0.953623
13 329 1 2018-03-01 0.02 0.953623
14 329 1 2018-04-01 0.02 0.953623
15 329 1 2018-05-01 0.02 0.953623
16 329 1 2018-06-01 0.02 0.953623
17 329 1 2018-07-01 0.02 0.953623
18 329 1 2018-08-01 0.02 0.953623
19 329 1 2018-09-01 0.02 0.953623
20 329 1 2018-10-01 0.02 0.953623
21 329 1 2018-11-01 0.02 0.953623
22 329 1 2018-12-01 0.02 0.953623
Run Code Online (Sandbox Code Playgroud)
当我申请时.values.tolist():
[[329,
1,
Timestamp('2017-02-01 00:00:00'),
0.02,
0.95362261,
0.9927,
1.0048,
0.9581999984999999,
0.082725,
0.082725,
0.0016545000000000002],
[329,
1,
Timestamp('2017-03-01 00:00:00'),
0.02,
0.95362261,
1.0006,
1.004,
0.9574371004000001,
0.08338333332999999,
0.1661083333,
0.003322166667], ...
]
Run Code Online (Sandbox Code Playgroud)
尝试这个:
df['forecast_month_alt'] = df['forecast_month'].dt.date
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2535 次 |
| 最近记录: |