我認爲可以將所有值轉換爲lists
,然後創建Series
,但隨後失去了指標:
df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df)
A B C D E F
0 1 4 7 1 5 7
1 2 5 8 3 3 4
2 3 6 9 5 6 3
row_count = 1
print (df.iloc[row_count, range (2, 4)])
C 8
D 3
Name: 1, dtype: int64
dfnow = pd.Series([df.iloc[row_count,0]] + df.iloc[row_count, range (2, 4)].tolist())
print (dfnow)
0 2
1 8
2 3
dtype: int64
或者你可以使用concat
,那麼指數是列名:
row_count = 1
a = df.iloc[row_count, range (2, 4)]
b = df.iloc[row_count, range (4, 6)]
print (a)
C 8
D 3
Name: 1, dtype: int64
print (b)
E 3
F 4
Name: 1, dtype: int64
print (pd.concat([a,b]))
C 8
D 3
E 3
F 4
Name: 1, dtype: int64
但是,如果需要添加標(a
),這是一個有點複雜 - 需要Series
:
row_count = 1
a = pd.Series(df.iloc[row_count, 0], index=[df.columns[0]])
b = df.iloc[row_count, range (2, 4)]
c = df.iloc[row_count, range (4, 6)]
print (a)
A 2
dtype: int64
print (b)
C 8
D 3
Name: 1, dtype: int64
print (c)
E 3
F 4
Name: 1, dtype: int64
print (pd.concat([a,b,c]))
A 2
C 8
D 3
E 3
F 4
dtype: int64
這個工作,並且我通過以下方式維護了索引:.... df.iloc [row_count,range(9,14) ] .tolist(),index = columns)。謝謝 – user2723494