0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.