Python 将常量列表添加到列中
假设我有一个df:Python 将常量列表添加到列中,python,pandas,list,Python,Pandas,List,假设我有一个df: df=pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}) 我只想添加一个新列,c,其中包含一个常量列表(例如:[7,8,9,10]) 当我尝试时: df['c']=[7,8,9,10] 我得到: ValueError: Length of values does not match length of index 我也试着玩loc,at,ix——但没能弄明白 我发现的一个丑陋的解决方法是: df['c'] = df['b'].apply(la
df=pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})
我只想添加一个新列,c
,其中包含一个常量列表(例如:[7,8,9,10]
)
当我尝试时:
df['c']=[7,8,9,10]
我得到:
ValueError: Length of values does not match length of index
我也试着玩loc
,at
,ix
——但没能弄明白
我发现的一个丑陋的解决方法是:
df['c'] = df['b'].apply(lambda x: [7,8,9,10])
但必须有一种更优雅的方法来做。更简单的方法是:
df['c'] = [[7,8,9,10]]*len(df)
结果:
a b c
0 1 4 [7, 8, 9, 10]
1 2 5 [7, 8, 9, 10]
2 3 6 [7, 8, 9, 10]
更新:
为避免每行列表的浅拷贝问题(如@YOBEN_所述),请使用:
例如,现在可以通过调用以下命令来更改第一行c
列中的第一个元素:
df.loc[0,'c'][0]='test'
这将向df添加常量列表
#df['c']=pd.Series([[7,8,9,10]]*len(df))
df=df.assign(c=pd.Series([[7,8,9,10]]*len(df)))
a b c
0 1 4 [7, 8, 9, 10]
1 2 5 [7, 8, 9, 10]
2 3 6 [7, 8, 9, 10]
这将使用其索引向df添加列
df['c']=pd.Series([7,8,9,10])
a b c
0 1 4 7
1 2 5 8
2 3 6 9
这是不安全的。在这种情况下,“不安全”是什么意思?顺便说一句,我试图找到一个替代方案,但失败了@YOBEN_S您有更合适的答案吗?请尝试df.loc[0,'c'][0]='test',您将更改所有行~是的,似乎存在浅拷贝问题。为了避免它,可以使用
df['c']=df.apply(lambda x:[7,8,9,10],axis=1)
。但是有没有比lambda更好的方法呢?我会为你做的,这是有原因的。为什么需要在数据帧的每一行中存储一个列表,更不用说具有相同确切信息的列表了?
#df['c']=pd.Series([[7,8,9,10]]*len(df))
df=df.assign(c=pd.Series([[7,8,9,10]]*len(df)))
a b c
0 1 4 [7, 8, 9, 10]
1 2 5 [7, 8, 9, 10]
2 3 6 [7, 8, 9, 10]
df['c']=pd.Series([7,8,9,10])
a b c
0 1 4 7
1 2 5 8
2 3 6 9