[英]How can I add a Python Object to new column in a pandas dataframe?
I am iterating over all rows in a Pandas Dataframe and I want to add a couple of new columns while iterating over each row. 我正在遍历Pandas Dataframe中的所有行,并且想在遍历每一行时添加几个新列。 One column is an integer, the other is a Python object (class MyClass). 一列是整数,另一列是Python对象(类MyClass)。
for index, row in df.iterrows():
... calculate myinteger and myclass_object ...
df.loc[df.index[index], 'breakout'] = myinteger
df.loc[df.index[index], 'object'] = myclass_object
But I get: 但是我得到:
ValueError: invalid literal for int() with base 10: b'\xd3\x07\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x13\x00\x00\x00\t\x00\x00\x00'
I think it is related to Pandas trying to figure out value of myclass_object, when dtype shall be set up to object but I am not sure. 我认为这与Pandas试图找出myclass_object的值有关,当dtype应该设置为object时,但我不确定。
Maybe u can try this: 也许您可以尝试以下操作:
for i in df.index.tolist():
df.at[i,'breakout'] = myinteger
df.at[i, 'object'] = myclass_object
If you would like do it with pandas
I recommend assign it after for loop 如果您想用pandas
做它,我建议在for循环后分配它
myi=[]
myo=[]
for index, row in df.iterrows():
myi.append(myinteger)
myo.append(myclass_object)
Then 然后
df['breakout'] = myi
df['object'] = myo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.