簡體   English   中英

Python dataframe 用 n 個元素的列表替換最后 n 行

[英]Python dataframe replace last n rows with a list of n elements

我有一個 2500 行的數據框。 我正在嘗試用 n 個元素的列表替換最后 n 行 dataframe 。 我正在舉一個我的問題和我想要的例子

df = 
      A
0    10.5
1    10.5
2    10.5
3    10.5
4    10.5
5    10.5
6    10.5

我的新列表有兩個元素放置在底部兩行。

op_res = [20.5, 30.5]

我的代碼和當前 output:

df.loc[-2:,'A'] = pd.Series(op_res)
df = 
      A
0    10.5
1    10.5
2    10.5
3    10.5
4    10.5
5    nan
6    nan

我的代碼可能有什么問題? 我的代碼和當前 output:

df = 
      A
0    10.5
1    10.5
2    10.5
3    10.5
4    10.5
5    20.5
6    30.5

我們可以使用DataFrame.iloc並將列表廣播到具有numpy.array的數組:

df.iloc[-len(op_res):] = np.array(op_res)[:, None]


      A
0  10.5
1  10.5
2  10.5
3  10.5
4  10.5
5  20.5
6  30.5

或使用DataFrame.append

df.iloc[:-len(op_res)].append(pd.DataFrame({'A': op_res}), ignore_index=True)

      A
0  10.5
1  10.5
2  10.5
3  10.5
4  10.5
5  20.5
6  30.5

國際大學聯盟

df.A.to_numpy()[-2:]=op_res
df
      A
0  10.5
1  10.5
2  10.5
3  10.5
4  10.5
5  20.5
6  30.5

代碼中的問題:索引不匹配,所以當它重新分配時,它將返回 nan,因為 pandas 分配將一如既往地匹配索引

pd.Series(op_res)
0    20.5
1    30.5
dtype: float64

原始df的索引

df.iloc[-2:,0] 
5    10.5
6    10.5
Name: A, dtype: float64

從上面我們知道,索引 [0,1] 不能與索引 [5,6] 匹配,所以所有賦值都會返回nan

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM