You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于pandas Timestamp创建目录报错:无法读取numpy.ndarray类型对象求助

Creating Directories with pandas Timestamp & Fixing "Unable to read from object of type: <class 'numpy.ndarray'>"

Hey there! Let's break down how to fix that error and successfully create directories using pandas Timestamps. That error usually pops up when you're trying to use a numpy ndarray (instead of a single, formatted string) as a directory name—file systems only understand string paths, not raw timestamp objects or arrays.

Step 1: Work with a Single pandas Timestamp

If you're dealing with one Timestamp, the key is to format it into a directory-friendly string using strftime(), then create the directory with os.makedirs() (use exist_ok=True to skip errors if the directory already exists):

import pandas as pd
import os

# Create a single pandas Timestamp
single_ts = pd.Timestamp('2024-05-20 14:30:00')

# Format it into a valid directory name (customize the format as needed)
dir_name = single_ts.strftime('%Y-%m-%d_%H-%M')  # Example output: "2024-05-20_14-30"

# Create the directory
os.makedirs(dir_name, exist_ok=True)

Step 2: Handle Multiple Timestamps (e.g., from a DataFrame)

If your Timestamps live in a DataFrame column, make sure you iterate over individual Timestamp objects (not the entire column, which is a Series backed by a numpy array):

import pandas as pd
import os

# Sample DataFrame with timestamps
df = pd.DataFrame({
    'event_time': [pd.Timestamp('2024-05-20'), pd.Timestamp('2024-05-21'), pd.Timestamp('2024-05-22')]
})

# Loop through each Timestamp in the column
for ts in df['event_time']:
    # Build a nested directory path (adjust structure to your needs)
    dir_path = f"events/{ts.strftime('%Y/%m/%d')}"  # Example output: "events/2024/05/20"
    # Create nested directories recursively
    os.makedirs(dir_path, exist_ok=True)

Step 3: Fixing the numpy.ndarray Error

If you accidentally ended up with a numpy datetime64 array (e.g., using df['event_time'].values), convert each element to a pandas Timestamp first, or format it directly:

import numpy as np
import pandas as pd
import os

# Example numpy datetime64 array
np_ts_array = np.array(['2024-05-20', '2024-05-21'], dtype='datetime64[D]')

# Option 1: Convert to pandas Timestamp then format
for np_ts in np_ts_array:
    ts = pd.Timestamp(np_ts)
    dir_name = ts.strftime('%Y-%m-%d')
    os.makedirs(dir_name, exist_ok=True)

# Option 2: Format directly from numpy datetime64
for np_ts in np_ts_array:
    dir_name = np.datetime_as_string(np_ts, unit='D')
    os.makedirs(dir_name, exist_ok=True)

Key Takeaway

The core issue is that file systems can't interpret raw Timestamp objects or numpy arrays as directory names. Always convert your timestamp to a string-formatted path first—this ensures the system recognizes it as a valid directory.

内容的提问来源于stack exchange,提问作者thotam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:10:05