![](/img/trans.png)
[英]Merge two columns into one within the same data frame in pandas/python
[英]Python pandas data frame: how to perform operations on two columns with the same name
假設您有一個如下的數據框(請注意,有些列具有相同的名稱):
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(4,5), columns = list('abcab'))
問題是如果你想對兩個列'a'執行一些操作,你怎么做,因為它們具有相同的名稱? 我嘗試使用replace()和rename()方法重命名兩列之一,然后執行一些操作,但是我沒有設法僅對一列進行此操作。
您應該能夠執行以下操作更改列的標簽:
df.columns = ['a', 'b', 'c', 'd', 'e']
如果您不想重命名列,可以使用iloc
:
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame(np.random.rand(4,5), columns = list('abcab'))
print df
a b c a b
0 0.548814 0.715189 0.602763 0.544883 0.423655
1 0.645894 0.437587 0.891773 0.963663 0.383442
2 0.791725 0.528895 0.568045 0.925597 0.071036
3 0.087129 0.020218 0.832620 0.778157 0.870012
#select first a column
print df.iloc[:,0]
0 0.548814
1 0.645894
2 0.791725
3 0.087129
Name: a, dtype: float64
#select second a column
print df.iloc[:,3]
Name: a, dtype: float64
0 0.544883
1 0.963663
2 0.925597
3 0.778157
Name: a, dtype: float64
#select first a column
print df['a'].iloc[:,0]
0 0.548814
1 0.645894
2 0.791725
3 0.087129
Name: a, dtype: float64
#select second a column
print df['a'].iloc[:,1]
0 0.544883
1 0.963663
2 0.925597
3 0.778157
Name: a, dtype: float64
編輯:如果只需要重命名具有相同名稱的列,請使用get_loc
:
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame(np.random.rand(4,5), columns = list('abbab'))
print df
a b b a b
0 0.548814 0.715189 0.602763 0.544883 0.423655
1 0.645894 0.437587 0.891773 0.963663 0.383442
2 0.791725 0.528895 0.568045 0.925597 0.071036
3 0.087129 0.020218 0.832620 0.778157 0.870012
cols=pd.Series(df.columns)
for dup in df.columns.get_duplicates():
cols[df.columns.get_loc(dup)]=[dup+'_'+str(d_idx) if d_idx!=0 else dup for d_idx in range(df.columns.get_loc(dup).sum())]
df.columns=cols
print df
a b b_1 a_1 b_2
0 0.548814 0.715189 0.602763 0.544883 0.423655
1 0.645894 0.437587 0.891773 0.963663 0.383442
2 0.791725 0.528895 0.568045 0.925597 0.071036
3 0.087129 0.020218 0.832620 0.778157 0.870012
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.