根据 pandas 中的行值创建 x 列数

问题描述 投票:0回答:0

使用 pandas(和一些 pyspark),我在 csv 的一行中提取了一个值 (x),并使用该值创建了 x 行数。

我使用 pyspark 在数据块中完成了此操作。不是问题只是想我会把它贴在这里。 我使用 pyspark 在数据块中完成了此操作。不是问题只是想我会把它贴在这里。 我使用 pyspark 在数据块中完成了此操作。不是问题只是想我会把它贴在这里。

# Import Pandas and Pyspark sql types

import pandas as pd
from pyspark.sql.types import IntegerType, StringType, DoubleType, StructField, StructType


# Create the dataframe (defining the schema as string on purpose)

from pyspark.sql.types import IntegerType, StringType, DoubleType, StructField, StructType
data2 = [
        ("1","2"),
        ("2","3"),
        ("3","2"),
        ("4","1"),
        ("5","3"),
        ("6","4")
        ]

table_schema = StructType([
    StructField("ID", StringType(), False),
    StructField("A", StringType(), False)
    ]
    )
 
df = spark.createDataFrame(data=data2,schema=table_schema)
df.show(truncate=False)

df = df.toPandas()


# Save the row value as a variable and cast as an int

variable = (df.iloc[1].A)
variable = int(variable)


# You can see I have the dataframe and the integer value

print(variable)
df.display()


# Declare the row value as a list with the value of the variable = n

list = [n for n in range(variable)]


# Print the add column function for how many values in the list

df[list] = pd.DataFrame([[1, 1, 1]], index=df.index)


# View the new dataframe with the columns added

df.display()
pandas pyspark databricks multiple-columns
© www.soinside.com 2019 - 2024. All rights reserved.