Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a tuple to a specific cell of a pandas dataframe

Just when I thought I was getting the hang of Python and Pandas, another seemingly simple issue crops up. I want to add tuples to specific cells of a pandas dataframe. These tuples need to be calculated on-the-fly based on the contents of other cells in the dataframe - in other words, I can't easily calculate all tuples in advance and add them as a single array.

As an example, I define a dataframe with some data and add a couple of empty columns:

import pandas as pd
import bumpy as np
tempDF = pd.DataFrame({'miscdata': [1.2,3.2,4.1,2.3,3.3,2.5,4.3,2.5,2.2,4.2]})
tempDF['newValue'] = np.nan
tempDF['newTuple'] = np.nan

I can scroll through each cell of the 'newValue' column and add an integer value without problems:

anyOldValue = 3.5
for i in range(10):
    tempDF.ix[(i,'newValue')] = anyOldValue

print tempDF

However, if I try to add a tuple I get an error message:

anyOldTuple = (2.3,4.5)
for i in range(10):
    tempDF.ix[(i,'newTuple')] = anyOldTuple

print tempDF

I've received several error messages including:

ValueError: Must have equal len keys and value when setting with an ndarray

…and…

ValueError: setting an array element with a sequence.

I'm sure I've seen data frames with tuples (or lists) in the cells - haven't I? Any suggestions how to get this code working would be much appreciated.

like image 271
user1718097 Avatar asked Jan 14 '15 18:01

user1718097


People also ask

How to insert list into cell of pandas Dataframe?

Complete Example to Insert List into Cell of Pandas DataFrame By using df.at (), df.iat (), df.loc [] method you can insert a list of values into a pandas DataFrame cell. I have covered this here by using these functions with a sample DataFrame.

How to create a Dataframe from a list of simple tuples?

We can create a DataFrame from a list of simple tuples, and can even choose the specific elements of the tuples we want to use. Code #1: Simply passing tuple to DataFrame constructor. Code #4: For pivoting it possible.

How to assign a tuple to a column in a cell?

As J.Melody pointed out, .at [] and .iat [] can be used to assign a tuple to a cell, if the dtype of the column is object. ValueError: setting an array element with a sequence.

What are the column names in The Dataframe?

Our DataFrame contains column names Courses , Fee , Duration, and Discount. Yields below output. 2. Insert List into Cell Using DataFrame.at () Method


2 Answers

You can use set_value:

tempDF.set_value(i,'newTuple', anyOldTuple)

Also make sure that the column is not a float column, for example:

tempDF['newTuple'] = 's' # or set the dtype

otherwise you will get an error.

like image 189
elyase Avatar answered Sep 21 '22 09:09

elyase


set_value is deprecated.

you can just use .at[] or iat[]

e.g. some_df.at[ idx, col_name] = any_tuple

like image 41
J.Melody Avatar answered Sep 20 '22 09:09

J.Melody