I have a Pandas DataFrame as follows:
import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns=['Name', 'keys'])
When I want to change the value of keys
by follows:
df = pd.DataFrame(data, columns=['Name', 'keys'])
df.loc[0, 'keys'] = [540, 12]
It throws an error:
ValueError: Must have equal len keys and value when setting with an iterable
I don't know what the problem is.
CodePudding user response:
I am assuming you want to go from this dataframe :
name keywords
0 name1 k1
To this one :
name keywords
0 name1 [k1, k2, k3]
Which is what I obtain writing this code :
import pandas as pd
my_dataframe=pd.DataFrame({
'name': 'name1',
'keywords':['k1']
})
new_keywords = ['k1', 'k2', 'k3']
my_dataframe.loc[0, 'keywords'] = new_keywords
Tell me if I misunderstood anything.
CodePudding user response:
So, to answer the edited problem :
I think the error comes from the fact that you are trying to replace an int by a table and Pandas doesn't like this. If your input data is a table at the beginning, the error does not appear anymore
Then if you try to replace the line
data = [['tom', 10], ['nick', 15], ['juli', 14]]
by this one : data = [['tom', [10]], ['nick', [15]], ['juli', [14]]]
, it should work.