我有一個熊貓系列,在將其連接到主 DataFrame 之前必須將其倒置。
我可以用 myseries = myseries.iloc[::-1] 輕松翻轉它
但是當我將它附加到主 DataFrame 時,它??附加了默認系列而不是翻轉版本。為什么翻轉的系列不留在原地?
myseries = myseries.iloc[::-1]
newdf = pd.concat([newdf, myseries], axis=1)
編輯: 所以我的猜測是索引也被翻轉了,當我連接它時可能使用索引來附加系列。有沒有辦法翻轉系列中的值但保持索引不變?我的索引從 2 開始。
uj5u.com熱心網友回復:
發生這種情況是因為基于索引進行連接。您可以保存原始索引,然后將反轉序列的索引設定為等于原始索引:
myseries_index = myseries.index
myseries = myseries.iloc[::-1]
myseries.index = myseries_index
uj5u.com熱心網友回復:
連接查看索引。所以你只需要在連接之前反轉你的系列的索引。請參見以下示例:
s = pd.Series([1,2,3], name='b')
s.index = s.index[::-1]
df = pd.DataFrame({'a': list('xyz')})
pd.concat([df, s], axis=1)
uj5u.com熱心網友回復:
試試這個。對我有用:)
myseries = myseries.iloc[:,::-1]
示例代碼:
import numpy as np
import pandas as pd
dataframe = pd.DataFrame([[1, 'A', "Student"],
[2, 'B', "Tutor"],
[3, 'C', "Instructor"]])
dataframe1 = pd.DataFrame([[1, 'A', "Student"],
[2, 'B', "Tutor"],
[3, 'C', "Instructor"]])
# reversing the dataframe
print("Reversed DataFrame")
dataframe = dataframe.iloc[:,::-1]
dataframe1 = pd.concat([dataframe1,dataframe],axis=1);
print(dataframe1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/427006.html
