import pandas as pd
sample = pd.DataFrame({'k1':[1.1455,2.444,3.5,4.9],
'k2':['b','c','d','e']})
sample.rename(columns = {
'k1' : '3',
'k2' : '5'},inplace = True)
def rename1(df):
print(df)
test1 = df.rename(columns = {
'k1' : 'num',
'k2' : 'name'},inplace = True)
print(test1)
return test1
rename1(sample)
def rename2(df):
print(df)
test2 = []
test2 = df.rename(columns = {
'k1' : df['num'].apply(lambda num : int(round(num))),
'k2' : df['name']},inplace = True)
print(test2)
return test2
rename2(sample)
print(sample['k1'].apply(lambda num : int(round(num))))
num name
0 1 b
1 2 c
2 4 d
3 5 e
This is my sample data. I'm new in python. I'm trying to rename multiple columns for my data frame but I don't know the problem.
I think need separate both operations - first rename
and then round
column by Series.round
with cast to integer
s by astype
:
sample.rename(columns = {
'k1' : 'num',
'k2' : 'name'},inplace = True)
sample['num'] = sample['num'].round().astype(int)
print (sample)
num name
0 1 b
1 2 c
2 4 d
3 5 e
Why the output will be none?
Because inplace=True
working inplace, it means no assign necessary.
df.rename(columns = {
'k1' : 'num',
'k2' : 'name'},inplace = True)
But if want assign remove inplace=True
:
test1 = df.rename(columns = {
'k1' : 'num',
'k2' : 'name'})
Also if exist vectorized alternative, apply solutions is better avoid. General order of precedence for performance of various operations
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.