簡體   English   中英

用具有相同索引但順序不同的另一列替換Pandas數據框中的一列

[英]Replace a column in Pandas dataframe with another that has same index but in a different order

我正在嘗試將提取的列重新插入到pandas數據框中,並對其排序進行了更改。

很簡單,我從pandas df中提取了一列:

col1 = df.col1

此列包含整數,我使用.sort()方法將其從最小到最大排序。 並對數據做了一些操作。

col1.sort()
#do stuff that changes the values of col1.

現在,col1的索引與整個df的索引相同,但是順序不同。

我想知道如何將列插入回原始數據幀中(替換目前的col1)

我嘗試了以下兩種方法:

1)

df.col1 = col1

2)

df.insert(column_index_of_col1, "col1", col1)

但是兩種方法都給我以下錯誤:

ValueError: cannot reindex from a duplicate axis

任何幫助將不勝感激。 謝謝。

考慮以下DataFrame:

df = pd.DataFrame({'A': [1, 2, 3], 'B': [6, 5, 4]}, index=[0, 0, 1])

df
Out: 
   A  B
0  1  6
0  2  5
1  3  4

將第二列分配給b並對其進行排序並取平方,例如:

b = df['B']
b = b.sort_values()
b = b**2

現在b是:

b
Out: 
1    16
0    25
0    36
Name: B, dtype: int64

如果不知道您對列所做的確切操作,就無法知道25是對應於原始DataFrame的第一行還是第二行。 您可以取反運算(例如,取平方根並匹配),但是我認為這是不必要的。 如果您從具有唯一元素的索引開始( df = df.reset_index() ),它將容易得多。 在這種情況下,

df['B'] = b

應該工作正常。

暫無
暫無

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

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