为唯一的数据组合生成日期

Generating dates for unique combination of data

相对于 Python 较新。我正在尝试为我的数据框中的每个唯一数据组合生成一个日期列。例如,在此示例中,我只需要每行 3 天的数据 -

输入:

  a      |      b      |      c      |      d     
  dogs          15           brown         30
  cats          24           black         43

理想输出:

date      |     a      |      b      |      c      |      d     
day 1           dogs          15           brown         30
day 2           dogs          15           brown         30
day 3           dogs          15           brown         30
day 1           dogs          24           black         43
day 2           dogs          24           black         43
day 3           dogs          24           black         43

在我的实际数据集中,每行大约需要 2 年的数据,但理想情况下,这是一个我可以在某处输入的变量,以防有一天我需要 4/5 年的数据。有什么建议吗?

num_days = len(combinations_thing)
pandas.date_range('2020-07-19',freq="1d",periods=num_days)

我想可能会做你想做的,最简单的...但是很难理解你从问题陈述中实际问的是什么。

你的意思可能是这样的:

import pandas as pd

# Create the sample dataframe
df = pd.DataFrame([
  ["dogs", 15, "brown", 30],
  ["cats", 24, "black", 43]
], columns=["a", "b", "c", "d"]
)

# Repeat each row 3 times
df = df.loc[df.index.repeat(3)]

# Create a new column called date, as a list comprehension containing f-strings
df["date"] = [f"day {i}" for i in range(1, 4)] * 2

# Make the new date column into the dataframe index
df = df.set_index('date')

# Show the results
print(df)

返回:

          a   b      c   d
date                      
day 1  dogs  15  brown  30
day 2  dogs  15  brown  30
day 3  dogs  15  brown  30
day 1  cats  24  black  43
day 2  cats  24  black  43
day 3  cats  24  black  43