简体   繁体   中英

python rename multiple columns and roundup dataframe

import pandas as pd 
sample = pd.DataFrame({'k1':[1.1455,2.444,3.5,4.9],
                      'k2':['b','c','d','e']})

it can rename columns successfully

sample.rename(columns = {
      'k1' : '3',
      'k2' : '5'},inplace = True)

case 1: don't know the problem in the function -rename columns

def rename1(df):
    print(df)
    test1 = df.rename(columns = {
              'k1' : 'num',
              'k2' : 'name'},inplace = True)  

    print(test1)

    return test1
rename1(sample)

Q1: Why the output will be none?

case 2: 1. roundup the number 2. rename all columns

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)

roundup data

print(sample['k1'].apply(lambda num : int(round(num))))

Q2: How to roundup the value based on the specific column properly?

expected the result

     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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM