本文介绍了重命名数据框中的元组列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是python和pandas的新手.我附上了熊猫数据框的图片,我需要知道如何从最后一列中获取数据以及如何重命名最后一列.
I am new to python and pandas. I have attached a picture of a pandas dataframe,I need to know how I can fetch data from the last column and how to rename the last column.
推荐答案
您可以使用:
df = df.rename(columns = {df.columns[-1] : 'newname'})
或者:
df.columns = df.columns[:-1].tolist() + ['new_name']
似乎解决方案:
df.columns.values[-1] = 'newname'
是越野车.因为重命名熊猫函数后会返回奇怪的错误.
is buggy. Because after rename pandas functions return weird errors.
要从最后一列获取数据,可以使用 iloc
:
For fetch data from last column is possible use select by position by iloc
:
s = df.iloc[:,-1]
重命名后:
s1 = df['newname']
print (s1)
示例:
df = pd.DataFrame({'R':[7,8,9],
'T':[1,3,5],
'E':[5,3,6],
('Z', 'a'):[7,4,3]})
print (df)
E T R (Z, a)
0 5 1 7 7
1 3 3 8 4
2 6 5 9 3
s = df.iloc[:,-1]
print (s)
0 7
1 4
2 3
Name: (Z, a), dtype: int64
df.columns = df.columns[:-1].tolist() + ['new_name']
print (df)
E T R new_name
0 5 1 7 7
1 3 3 8 4
2 6 5 9 3
df = df.rename(columns = {('Z', 'a') : 'newname'})
print (df)
E T R newname
0 5 1 7 7
1 3 3 8 4
2 6 5 9 3
s = df['newname']
print (s)
0 7
1 4
2 3
Name: newname, dtype: int64
df.columns.values[-1] = 'newname'
s = df['newname']
print (s)
>KeyError: 'newname'
这篇关于重命名数据框中的元组列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!