首页 文章

python重命名多个列和roundup数据帧

提问于
浏览
3
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)

案例1:不知道函数-rename列中的问题

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

    print(test1)

    return test1
rename1(sample)

Q1:为什么输出不是?

案例2:1 . 对数字进行综合2.重命名所有列

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))))

Q2:如何正确地根据特定列对值进行汇总?

期待结果

num  name
0       1  b
1       2  c
2       4  d
3       5  e

这是我的样本数据 . 我是python的新手 . 我正在尝试为我的数据框重命名多个列,但我不知道问题 .

1 回答

  • 1

    我认为需要将两个操作分开 - 首先 rename 然后 roundSeries.round并通过astype强制转换为 integer

    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
    

    为什么输出不是?

    因为 inplace=True 在原地工作,这意味着没有必要的分配 .

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

    但如果要分配删除 inplace=True

    test1 = df.rename(columns = {
              'k1' : 'num',
              'k2' : 'name'})
    

    如果存在矢量化替代方案,则应更好地避免应用解决方案 . General order of precedence for performance of various operations

相关问题