Home python Pandas Concat Sequential Adding Data to One Column DataFrame

Pandas Concat Sequential Adding Data to One Column DataFrame

Author

Date

Category

Example:

import pandas as pd
Import NUMPY AS NP
df = pd.dataframe (columns = ['a', 'b'])
DF ['A'] = np.random.randint (5,10,3)
For i in Range (3):
  temp = pd.dataframe (np.random.randint (1,5,3), columns = ['b'])
  df = pd.concat ([DF, TEMP], ignore_Index = True)
Print (DF)

We get:

a b
0 9.0 Nan.
1 7.0 Nan.
2 6.0 Nan.
3 Nan 2.
4 Nan 1.
5 Nan 1.
6 Nan 2.
7 Nan 4.
8 Nan 2.
9 Nan 4.
10 Nan 2.
11 Nan 4.

How to make that the DF [‘B’] column is consistently filled with the beginning of the column (from the zero index), and not from the index where the DF column [‘A’] ended? Thank!


Answer 1, Authority 100%

You can still do it:

import pandas as pd
Import NUMPY AS NP
df = pd.dataframe (columns = ['a', 'b'])
DF ['A'] = np.random.randint (5,10,3)
For i in Range (3):
  temp = pd.dataframe (np.random.randint (1,5,3), columns = ['b'])
  df = pd.concat ([DF, TEMP], ignore_Index = True)
  df = df.apply (Lambda X: PD.Series (X.DROPNA (). Values))
Print (DF)

df:

a b
0 9.0 2.
1 9.0 2.
2 5.0 1.
3 Nan 2.
4 Nan 1.
5 Nan 3.
6 Nan 1.
7 Nan 4.
8 Nan 3.

Answer 2, Authority 100%

I do not figure it out if there is a universal solution, but the easiest thing is probably first time to write in the b column, and then convert:

import pandas as pd
Import NUMPY AS NP
df = pd.dataframe (columns = ['a', 'b'])
DF ['A'] = np.random.randint (5,10,3)
For i in Range (3):
  temp = pd.dataframe (np.random.randint (1,5,3), columns = ['b'])
  IF i == 0:
    DF ['B'] = Temp ['B']
  ELSE:
    df = pd.concat ([DF, TEMP], ignore_Index = True)
Print (DF)

Conclusion:

a b
0 5.0 1.
1 9.0 2.
2 7.0 1.
3 Nan 1.
4 Nan 4.
5 Nan 3.
6 Nan 3.
7 Nan 1.
8 Nan 4.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions