gpt4 book ai didi

python - 在 pandas 数据框末尾添加新行,并在所有列中添加特定值

转载 作者:行者123 更新时间:2023-12-01 08:33:04 25 4
gpt4 key购买 nike

我有一个如下所示的数据框:

 Col1     Col2  .....    Col48
078 abc 0.99
097 def 0.91
027 xyz 0.66
065 90 0.76

我想在最后一行之后添加新行,其中所有值均为“0”。所以新的 df 应该是这样的:

Col1     Col2  .....    Col48
078 abc 0.99
097 def 0.91
027 xyz 0.66
065 bcd 0.76
0 0 0

之后,我想将 Col2 值从 0 替换为“目标”,这样最终的数据帧将如下所示:

Col1     Col2  .....    Col48
078 abc 0.99
097 def 0.91
027 xyz 0.66
065 bcd 0.76
0 target 0

代码:

 df.loc[len(df)] = 0
df['Col2'] = df['Col2'].astype(str)
df['Col2'].str.replace('0','target')

最佳答案

使用setting with enlargement ,必要的默认 RangeIndex:

df.loc[len(df)] = 0
print (df)
Col1 Col2 Col48
0 78 abc 0.99
1 97 def 0.91
2 27 xyz 0.66
3 65 90 0.76
4 0 0 0.00

另一种解决方案是创建一列 DataFrameconcat一起:

df1 = pd.DataFrame(np.repeat(0, len(df.columns))[None, :], 
columns=df.columns,
index=[10])

df = pd.concat([df, df1])
print (df)
Col1 Col2 Col48
0 78 abc 0.99
1 97 def 0.91
2 27 xyz 0.66
3 65 90 0.76
10 0 0 0.00

关于python - 在 pandas 数据框末尾添加新行,并在所有列中添加特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53852208/

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