I want to rename rows in python program (version – spyder 3
– python 3.6
) . At this point I have something like that:
JavaScript
x
3
1
import pandas as pd
2
data = pd.read_csv(filepath, delim_whitespace = True, header = None)
3
Before that i wanted to rename my columns:
JavaScript
1
2
1
data.columns = ['A', 'B', 'C']
2
It gave me something like that.
JavaScript
1
6
1
A B C
2
0 1 n 1
3
1 1 H 0
4
2 2 He 1
5
3 3 Be 2
6
But now, I want to rename rows. I want:
JavaScript
1
6
1
A B C
2
n 1 n 1
3
H 1 H 0
4
He 2 He 1
5
Be 3 Be 2
6
How can I do it? The main idea is to rename every row created by pd.read
by the data in the B column. I tried something like this:
JavaScript
1
3
1
for rows in data:
2
data.rename(index={0:'df.loc(index, 'B')', 1:'one'})
3
but it’s not working.
Any ideas? Maybe just replace the data frame rows by column B? How?
Advertisement
Answer
I think need set_index
with rename_axis
:
JavaScript
1
2
1
df1 = df.set_index('B', drop=False).rename_axis(None)
2
Solution with rename
and dictionary:
JavaScript
1
5
1
df1 = df.rename(dict(zip(df.index, df['B'])))
2
3
print (dict(zip(df.index, df['B'])))
4
{0: 'n', 1: 'H', 2: 'He', 3: 'Be'}
5
If default RangeIndex
solution should be:
JavaScript
1
5
1
df1 = df.rename(dict(enumerate(df['B'])))
2
3
print (dict(enumerate(df['B'])))
4
{0: 'n', 1: 'H', 2: 'He', 3: 'Be'}
5
Output:
JavaScript
1
7
1
print (df1)
2
A B C
3
n 1 n 1
4
H 1 H 0
5
He 2 He 1
6
Be 3 Be 2
7
EDIT:
If dont want column B
solution is with read_csv
by parameter index_col
:
JavaScript
1
16
16
1
import pandas as pd
2
3
temp=u"""1 n 1
4
1 H 0
5
2 He 1
6
3 Be 2"""
7
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
8
df = pd.read_csv(pd.compat.StringIO(temp), delim_whitespace=True, header=None, index_col=[1])
9
print (df)
10
0 2
11
1
12
n 1 1
13
H 1 0
14
He 2 1
15
Be 3 2
16