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 integers 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With