1

I have the list:

[['abc', 1, 2, 3], ['bfg', 4, 5, 6], ['abc', 7, 8, 9], ['bfg', 10, 11, 12]] 

And I make it into a pandas DataFrame, which returns (after adding a column with the color lst[4] = 'blue'):

 0 1 2 3 4 0 abc 1 2 3 blue 1 bfg 4 5 6 blue 2 abc 7 8 9 blue 3 bfg 10 11 12 blue 

Is there anyway to make it return this instead:

 0 1 2 3 4 0 abc 1 2 3 blue 1 bfg 4 5 6 blue 2 abc 7 8 9 red 3 bfg 10 11 12 red 

3 Answers 3

2

Solution with DataFrame.from_records:

lst = [['abc', 1, 2, 3], ['bfg', 4, 5, 6], ['abc', 7, 8, 9], ['bfg', 10, 11, 12]] df = pd.DataFrame.from_records(lst) print (df) 0 1 2 3 0 abc 1 2 3 1 bfg 4 5 6 2 abc 7 8 9 3 bfg 10 11 12 

Add values by loc:

l = len(df.index) // 2 df.loc[:l - 1, 4] = 'blue' df.loc[l:, 4] = 'red' print (df) 0 1 2 3 4 0 abc 1 2 3 blue 1 bfg 4 5 6 blue 2 abc 7 8 9 red 3 bfg 10 11 12 red 

More interesting is if there is odd length of df - floor division //:

lst = [['abc', 1, 2, 3], ['bfg', 4, 5, 6], ['abc', 7, 8, 9], ['bfg', 10, 11, 12], ['bfg', 3, 4, 5]] df = pd.DataFrame.from_records(lst) print (df) 0 1 2 3 0 abc 1 2 3 1 bfg 4 5 6 2 abc 7 8 9 3 bfg 10 11 12 4 bfg 3 4 5 l = len(df.index) // 2 df.loc[:l, 4] = 'blue' df.loc[l:, 4] = 'red' print (df) 0 1 2 3 4 0 abc 1 2 3 blue 1 bfg 4 5 6 blue 2 abc 7 8 9 red 3 bfg 10 11 12 red 4 bfg 3 4 5 red 

or normal division /:

l = len(df.index) / 2 df.loc[:l, 4] = 'blue' df.loc[l:, 4] = 'red' print (df) 0 1 2 3 4 0 abc 1 2 3 blue 1 bfg 4 5 6 blue 2 abc 7 8 9 blue 3 bfg 10 11 12 red 4 bfg 3 4 5 red 
Sign up to request clarification or add additional context in comments.

Comments

1

It could be even simplified using np.repeat in addition with np.resize to account for the loss of size due to floating point division.

lst[4] = np.resize(np.repeat(['blue', 'red'], lst.shape[0] // 2), lst.shape[0]) 

Comments

0

Simplest is:

lst.loc[len(lst)/2:, 4] = 'red' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.