[英]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']})
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. 我是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
: 我觉得需要分开这两个操作-第一rename
,然后round
柱Series.round
采用铸造到integer
由s 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. 因为inplace=True
就地工作,这意味着没有必要的分配。
df.rename(columns = {
'k1' : 'num',
'k2' : 'name'},inplace = True)
But if want assign remove inplace=True
: 但如果想要分配删除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 各种操作执行的一般优先顺序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.