简体   繁体   中英

Adding an np.array as a column in a pandas.DataFrame

I have a pandas data frame and a numpy nd array with one dimension. Effectively it is a list.

How do I add a new column to the DataFrame with the values from the array?

test['preds'] = preds gives SettingWithCopyWarning And a warning:

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

And when I try pd.DataFrame({test,preds}) I get TypeError: unhashable type: 'list'

Thanks to EdChum the problem was this

test= DataFrame(test)
test['preds']=preds

It works!

This is not a pandas error, this error is because you are trying to instantiate a set with two lists.

{test,preds}
#TypeError: unhashable type: 'list'

A set is a container which needs all its content to be hashable, since sets may not contain the same element twice.

That being said, handing pandas a set will not work for your desired result.

Handing pandas a dict however, will work, like this:

pd.DataFrame({"test":test,"preds":preds})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM