import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
new_series = pd.Series([7, 8,9,10], name='C')
df['B'] = new_series
in this code the column 'B' does not get replaced with new series. so I want the df to be
在此代码中,列‘B’不会被新系列替换。所以我希望DF是
df["B"]=[1, 2, 3,nan]
df["B"]=[7, 8,9,10]
更多回答
优秀答案推荐
Make indices between df
and new_series
agreed, then - assign the needed column:
使df和new_Series之间的索引达成一致,然后-分配所需的列:
df.reindex(new_series.index).assign(B=new_series)
A B
0 1.0 7
1 2.0 8
2 3.0 9
3 NaN 10
A possible solution, which is based on pandas.concat
:
一种可能的解决方案,基于PANDAS.CONCAT:
pd.concat([df.iloc[:,:-1], new_series.rename('B')], axis=1)
Output:
产出:
A B
0 1.0 7
1 2.0 8
2 3.0 9
3 NaN 10
更多回答
我是一名优秀的程序员,十分优秀!