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 columns
def rename1(df):
print(df)
test1 = df.rename(columns = {
'k1' : 'num',
'k2' : 'name'},inplace = True)
print(test1)
return test1
rename1(sample)
Q1:为什么会输出none?
案例 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 的新手。我正在尝试为我的数据框重命名多个列,但我不知道问题所在。
最佳答案
我认为需要将这两个操作分开 - 首先是 rename
,然后是 round
column by Series.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
Why the output will be none?
因为 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
关于python重命名多列和汇总数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49650618/