python - Add constant value column that changes half way down to pandas dataframe -
i have list:
[['abc', 1, 2, 3], ['bfg', 4, 5, 6], ['abc', 7, 8, 9], ['bfg', 10, 11, 12]]
and make pandas dataframe, returns (after adding column 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 make return 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
solution 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 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 if there 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
Comments
Post a Comment