首页 > 解决方案 > 将一行分解为多行

问题描述

我有只有一行的数据框。

from datetime import datetime
spark = SparkSession.builder.getOrCreate()
as_of_date = datetime.strptime('2013-01-01', '%Y-%m-%d')
columns = ['id', 'row', 'month']
vals = [('A', 1, as_of_date)]
df = spark.createDataFrame(vals, columns)

我想根据“行”列的值 1 创建更多行,以便新数据框看起来像

id, row, month
A, -2, 2012-10-01
A, -1, 2012-11-01
A, 0, 2012-12-01
A, 1, 2013-01-01

查找爆炸,但仍然无法弄清楚如何做到这一点。

谢谢。

标签: pythonpyspark

解决方案


我不知道它是否会与spark.

首先,pandas我尝试使用append()添加新行,然后是相反的顺序

import pandas as pd
from datetime import datetime
from datetime import timedelta

as_of_date = datetime.strptime('2013-01-01', '%Y-%m-%d')
columns = ['id', 'row', 'month']
vals = [('A', 1, as_of_date)]
df = pd.DataFrame(vals, columns=columns)

#print(df.dtypes)
#print(df)

item = df.iloc[0].copy()  # original value

for x in range(3):
    item['row'] = -x
    item['month'] = item['month'] - timedelta(days=1)
    item['month'] = item['month'].replace(day=1)
    df = df.append(item)

# reverse and reset index
df = df[::-1].reset_index(drop=True)

print(df)

但后来我发布了我可以直接用DataFrame

import pandas as pd
from datetime import datetime

as_of_date = datetime.strptime('2013-01-01', '%Y-%m-%d')
columns = ['id', 'row', 'month']
vals = [('A', 1, as_of_date)]

ID, ROW, MONTH = vals[0]
N = 4 # number of rows

df = pd.DataFrame({
    'id': [ID for _ in range(N)],
    'row': range(ROW, ROW-N, -1),
    'month': pd.date_range(MONTH, periods=N, freq='-1M')
})

# reverse and reset index
df = df[::-1].reset_index(drop=True)                     

print(df)

推荐阅读