如何使用Pandas Read(Python)重命名DataFrame中的行? [英] How to rename the rows in dataframe using pandas read (Python)?

查看:42
本文介绍了如何使用Pandas Read(Python)重命名DataFrame中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重命名python程序中的行(版本-spyder 3-python 3.6)。在这一点上,我有一些类似的东西:

import pandas as pd
data = pd.read_csv(filepath, delim_whitespace = True, header = None)

在此之前,我想重命名我的列:

data.columns = ['A', 'B', 'C']

它给了我类似的东西。

    A   B   C  
0   1   n   1  
1   1   H   0  
2   2   He  1  
3   3   Be  2  

但现在,我想重命名行。我想:

     A   B   C  
n    1   n   1  
H    1   H   0  
He   2   He  1  
Be   3   Be  2

我该怎么做?其主要思想是根据B列中的数据重命名pd.read创建的每一行。我尝试了这样的操作:

for rows in data:
    data.rename(index={0:'df.loc(index, 'B')', 1:'one'})

但它不起作用。

有什么想法吗?也许只需将数据框行替换为B列?如何?

推荐答案

我认为需要set_indexrename_axis

df1 = df.set_index('B', drop=False).rename_axis(None)

rename和词典的解决方案:

df1 = df.rename(dict(zip(df.index, df['B'])))

print (dict(zip(df.index, df['B'])))
{0: 'n', 1: 'H', 2: 'He', 3: 'Be'}

如果默认RangeIndex解决方案应为:

df1 = df.rename(dict(enumerate(df['B'])))

print (dict(enumerate(df['B'])))
{0: 'n', 1: 'H', 2: 'He', 3: 'Be'}

输出

print (df1)
    A   B  C
n   1   n  1
H   1   H  0
He  2  He  1
Be  3  Be  2

编辑:

如果不需要列B解决方案是read_csv按参数index_col

import pandas as pd

temp=u"""1 n 1
1 H 0
2 He 1
3 Be 2"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(pd.compat.StringIO(temp), delim_whitespace=True, header=None, index_col=[1])
print (df)
    0  2
1       
n   1  1
H   1  0
He  2  1
Be  3  2

这篇关于如何使用Pandas Read(Python)重命名DataFrame中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆