我似乎无法为带有列表的pandas datafram重新分配值。 Python想遍历该列表,但我认为它不会那样做。例如,如果我有以下内容:
import pandas as pd
val1 = [0, 1, 2]
val2 = [3, 4, 5]
d_list = []
for v1, v2 in zip(val1, val2):
d_list.append({'val1':v1, 'val2':v2})
df = pd.DataFrame(d_list)
val3 = [6, 7, 8, 9]
df['val3'] = [val3]*len(df)
print df
我得到了预期的输出:
val1 val2 val3
0 0 3 [6, 7, 8, 9]
1 1 4 [6, 7, 8, 9]
2 2 5 [6, 7, 8, 9]
现在,我想重新分配val3
中的值:
df.loc[0, 'val3'] = [11, 12, 13, 14]
,我收到以下错误消息:
raise ValueError('Must have equal len keys and value '
ValueError: Must have equal len keys and value when setting with an iterable
我在这里做什么错了?
答案 0 :(得分:2)
您正在寻找的是df.at
尝试:
df.at[0, 'val3'] = [11, 12, 13, 14]
从文档中
类似于loc,两者都提供基于标签的查找。如果只需要在DataFrame或Series中获取或设置单个值,请使用at
http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.at.html