Python 在Dataframe中的特定位置添加列
我有一个数据帧-Python 在Dataframe中的特定位置添加列,python,pandas,Python,Pandas,我有一个数据帧- data={'a':[1,2,3,6],'b':[5,6,7,6],'c':[45,77,88,99]} df=pd.DataFrame(data) 现在,我想在dataframe中的下两行添加一列 更新后的数据帧应该如下所示- l=[4,5] #column to add a b c d 0 1 5 45 0 1 2 6 77 0 2 3 7 88 4 3 6 6 99 5 是我干的- df
data={'a':[1,2,3,6],'b':[5,6,7,6],'c':[45,77,88,99]}
df=pd.DataFrame(data)
现在,我想在dataframe中的下两行添加一列
更新后的数据帧应该如下所示-
l=[4,5] #column to add
a b c d
0 1 5 45 0
1 2 6 77 0
2 3 7 88 4
3 6 6 99 5
是我干的-
df.loc[:2,'f'] = pd.Series(l)
想法是按索引添加
系列
,按长度添加列表
:
df['d'] = pd.Series(l, index=df.index[-len(l):])
print (df)
a b c d
0 1 5 45 NaN
1 2 6 77 NaN
2 3 7 88 4.0
3 6 6 99 5.0
最后为0
按原始索引添加的值
df['d'] = pd.Series(l, index=df.index[-len(l):]).reindex(df.index, fill_value=0)
print (df)
a b c d
0 1 5 45 0
1 2 6 77 0
2 3 7 88 4
3 6 6 99 5
另一个想法是通过长度差重复0
值并添加l
:
df['d'] = [0] * (len(df) - len(l)) + l
print (df)
a b c d
0 1 5 45 0
1 2 6 77 0
2 3 7 88 4
3 6 6 99 5
您可以添加0
s的列并设置索引:
>>> df
a b c
0 1 5 45
1 2 6 77
2 3 7 88
3 6 6 99
>>> df['d'] = 0
>>> df.iloc[-2:, df.columns.get_loc('d')] = [4,5]
>>> df
a b c d
0 1 5 45 0
1 2 6 77 0
2 3 7 88 4
3 6 6 99 5
reindex在做什么?。没有它似乎可以工作also@ubuntu_noob-添加了两种解决方案