-1

I'm trying to save a named tuple n=NamedTuple(value1='x'=, value2='y') in a row of a pandas dataframe.

The problem is that the named tuple is showing a length of 2 because it has 2 parameters in my case (value1 and value2), so it doesn't fit it into a single cell of the dataframe.

How can I achieve that the named tuple is written into every call of a row of a dataframe?

df['columnd1']=n

an example:

from collections import namedtuple
import pandas as pd

n = namedtuple("test", ['param1', 'param2'])

n1 = n(param1='1', param2='2')

df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
df['nt'] = n1

print(df)
Nickpick
  • 6,163
  • 16
  • 65
  • 116
  • You could create a small `Class` instead of the named tuple – Dan May 04 '18 at 11:10
  • I need a named tuple – Nickpick May 04 '18 at 11:15
  • Can you provide an [MCVE](https://stackoverflow.com/help/mcve)? – Dan May 04 '18 at 11:19
  • But what are you trying to achieve here? `df['nt'] = n1` assigns `n1` to the entire column, is that what you want? i.e. you're trying get the same result as `pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "nt": [n1, n1, n1]})`? – Dan May 04 '18 at 12:10

1 Answers1

1

I don't really understand what you're trying to do, but if you want to put that named tuple in every row of a new column (i.e. like a scalar) then you can't rely on broadcasting but should instead replicate it yourself:

df['nt'] = [n1 for _ in range(df.shape[0])]
Dan
  • 45,079
  • 17
  • 88
  • 157