gpt4 book ai didi

Pandas assign a pd series with longer len than df, to a col in that df(熊猫将具有比Df更长镜头的PD系列分配给Df中的颜色)

转载 作者:bug小助手 更新时间:2023-10-25 17:54:49 25 4
gpt4 key购买 nike



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

更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com