'Append list to an existing dataframe as a column
I have a pandas dataframe as below
df = [['A',1],
['A',1],
['A',0],
['A',0],
['A',5],
['B',0],
['B',0],
['B',1],
['B',1]]
df = pd.DataFrame(df, columns = ['A', 'B'])
df
A B
0 A 1
1 A 1
2 A 0
3 A 0
4 A 5
5 B 0
6 B 0
7 B 1
8 B 1
I have a list of items as below. I want to append 'new_list ' into my 'df' dataframe as column C
new_list = [[1], [1], [1], [1], [5], [0], [0], [1], [1]]
Solution 1:[1]
Try using .join() like so:
df = df.join(pd.DataFrame({'C': new_list}))
df:
A B C
0 A 1 1
1 A 1 1
2 A 0 1
3 A 0 1
4 A 5 5
5 B 0 0
6 B 0 0
7 B 1 1
8 B 1 1
Note you need to turn your list into a data frame for this to work.
Solution 2:[2]
try using numpy method .flatten()
df['C'] = numpy.asarray(new_list).flatten()
df
A B C
0 A 1 1
1 A 1 1
2 A 0 1
3 A 0 1
4 A 5 5
5 B 0 0
6 B 0 0
7 B 1 1
8 B 1 1
Solution 3:[3]
IIUC
df['C']=sum(new_list,[])
df
Out[8]:
A B C
0 A 1 1
1 A 1 1
2 A 0 1
3 A 0 1
4 A 5 5
5 B 0 0
6 B 0 0
7 B 1 1
8 B 1 1
Or
import itertools
df['C']=list(itertools.chain(*new_list))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | BENY |