'Selecting and renaming columns at the same time
I looked around but could not find the solution for this. In R's dplyr we can select and rename column in one line of code.
select(Com=Commander,Sco=Score)
I'm trying to do the same thing in pandas but could not find feasible solution for it yet!
Let's say we have this sample data
# Create an example dataframe
data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08'],
'Score': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df
Commander Date Score
Cochice Jason 2012, 02, 08 4
Pima Molly 2012, 02, 08 24
Santa Cruz Tina 2012, 02, 08 31
Maricopa Jake 2012, 02, 08 2
Yuma Amy 2012, 02, 08 3
and want to select and rename Commander and Score columns like this
df[['Com'=='Commander','Sco'=='Score']]
ValueError: Item wrong length 2 instead of 5.
How can I do that ?
Solution 1:[1]
df.rename(columns = {"presentColumnName" : "NametoWhichYouWantTOChangeTo", "presentColumnName":"NametoWhichYouWantTOChangeTo"}, inplace=True)
for your example
df.rename(columns = {"Com" : "Commander", "Sco":"Score"}, inplace=True)
Solution 2:[2]
Try this:
df.columns = ['Com', 'Date', 'Sco']
Solution 3:[3]
You can do it in the same way in python as you did in R, using datar:
>>> from datar.all import tibble, select, f
>>>
>>> data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
... 'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08'],
... 'Score': [4, 24, 31, 2, 3]}
>>>
>>> df = tibble(**data)
>>> df >> select(Com=f.Commander,Sco=f.Score)
Com Sco
<object> <int64>
0 Jason 4
1 Molly 24
2 Tina 31
3 Jake 2
4 Amy 3
Disclaimer: I am the author of the datar package.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yatish Kadam |
| Solution 2 | Derek Langley |
| Solution 3 | Panwen Wang |
