python - 将一行分解为多行
问题描述
我有只有一行的数据框。
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
查找爆炸,但仍然无法弄清楚如何做到这一点。
谢谢。
解决方案
我不知道它是否会与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)
推荐阅读
- authentication - 无法授予 MS Asure 图形 API 客户端应用程序获取有关 ManagedDevices 的数据的权限。如何克服?
- sql-server - Subshell 中的 Bash BG 进程:显示输出以及管道到命令(Docker CMD 启动 Shell 脚本)
- python - 尝试在某个日期范围内抓取 google 的结果数量错误
- ajax - 如何从 MVC ViewModel 获取输入数据到 ajax post
- python - Python - 将导入转换为模块格式
- c# - Asp.net core MVC 中 ViewModel 的适配器模式
- java - 从不在类路径中的目录运行测试
- java - Java 秒表 GUI 程序符合但不运行
- angular - 从Angular 8中的父组件调用动态子组件中的通用接口方法
- vue.js - 组件中的 VueJS 点击事件