Home > Blockchain >  How do I Split a DataFrame Row into Multiple Rows?
How do I Split a DataFrame Row into Multiple Rows?

Time:05-12

Im new to Python and I want to split the single row that my code prints, into multiple rows, specifically I want to separate each row where the String Variable Starts...

df = pd.DataFrame()
Var1 = "X"
Var2 = 300
Var3 = Var2*15
Var4 = Var3*0.75
df2 = df.append([Var1, Var2, Var3, Var4])

Var5 = "Y"
Var6 = 650
Var7 = Var2*20
df2 = df2.append([Var5, Var6, Var7])

print(df2.T)

If you run this code, you'll notice that there is only one row in the DataFrame, I need the first 4 Variables in one row and the last 3 Variables in another row

CodePudding user response:

Since no columns are defined, append() assumes each VarX is a new row (i.e. single column). You need to first create a dataframe with the relevant number of columns and then append.

df = pd.DataFrame(columns=[1,2,3,4])
Var1 = "X"
Var2 = 300
Var3 = Var2*15
Var4 = Var3*0.75
df = df.append({1:Var1, 2:Var2, 3:Var3, 4:Var4}, ignore_index=True)

Var5 = "Y"
Var6 = 650
Var7 = Var2*20
df = df.append({1:Var5, 2:Var6, 3:Var7}, ignore_index=True)

Output:

   1    2     3       4
0  X  300  4500  3375.0
1  Y  650  6000     NaN

CodePudding user response:

You could also use use pd.concat() and pass axis=1. The above solution is better but it may be helpful to know multiple ways to do this.

df = pd.DataFrame()
Var1 = "X"
Var2 = 300
Var3 = Var2*15
Var4 = Var3*0.75
col1 = pd.DataFrame([Var1, Var2, Var3, Var4])

Var5 = "Y"
Var6 = 650
Var7 = Var2*20
col2 = pd.DataFrame([Var5, Var6, Var7])

print(pd.concat([col1,col2], axis = 1).T)

Output:

   0    1     2     3
0  X  300  4500  3375
0  Y  650  6000   NaN
  • Related