gpt4 book ai didi

python - 在数据框的位置 [0] 处插入行

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:02 26 4
gpt4 key购买 nike

我有一个像这样的框架,我在其中插入一个新行

import pandas as pd

s1 = pd.Series([5, 6, 7])
s2 = pd.Series([11, 12, 13])
s3 = pd.Series([22, 23, 24])

index_lst = ['StockA','StockB','StockC']

df = pd.DataFrame([list(s1), list(s2), list(s3)], columns = ["A", "B", "C"], index = index_lst)
insert_line = pd.DataFrame({'A' : 99, 'C' : 98}, index = ['NewStock'])
df2 = pd.concat([df.ix[0:], insert_line])

这给了我这个

           A     B   C     
StockA 5 6.00 7
StockB 11 12.00 13
StockC 22 23.00 24
NewStock 11 nan 22

如何将“NewStock”条目插入到第 0 行?我想要这个订单

           A     B   C     
NewStock 11 nan 22
StockA 5 6.00 7
StockB 11 12.00 13
StockC 22 23.00 24

最佳答案

我认为如果它们都是数据帧,您可以使用pd.concat()

也许是这样的?

import pandas as pd

s1 = pd.Series([5, 6, 7])
s2 = pd.Series([11, 12, 13])
s3 = pd.Series([22, 23, 24])

index_lst = ['StockA','StockB','StockC']

df = pd.DataFrame([list(s1), list(s2), list(s3)], columns = ["A", "B", "C"], index = index_lst)
insert_line = pd.DataFrame({'A' : 99, 'C' : 98}, index = ['NewStock'])


df = pd.concat([insert_line, df])

关于python - 在数据框的位置 [0] 处插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41828595/

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