add a numpy array to dataframe in python

To add a numpy array to a pandas dataframe in Python, you can use the pandas' DataFrame method along with the numpy.ndarray method. Here's an example:

main.py
import pandas as pd
import numpy as np

# create a numpy array
np_arr = np.array([1, 2, 3, 4, 5])

# create a pandas dataframe
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo'],
                   'B': ['one', 'one', 'two', 'three', 'two']})

# add the numpy array to the dataframe as a new column
df['C'] = np_arr

# print the dataframe
print(df)
358 chars
16 lines

This outputs:

main.py
     A      B  C
0  foo    one  1
1  bar    one  2
2  foo    two  3
3  bar  three  4
4  foo    two  5
102 chars
7 lines

In this case, the numpy array is added to the dataframe as a new column with the label 'C'. You can replace 'C' with the desired label for your new column.

gistlibby LogSnag