gpt4 book ai didi

python-3.x - 如何将列的内容移动到它旁边的列

转载 作者:行者123 更新时间:2023-12-04 10:19:26 25 4
gpt4 key购买 nike

数据框如下所示:

import pandas as pd 

df = pd.DataFrame ({
'Name':['Brian','John','Adam'],
'HomeAddr':[12,32,44],
'Age':['M','M','F'],
'Genre': ['NaN','NaN','NaN']
})

当前输出为:
    Name  HomeAddr Age Genre
0 Brian 12 M NaN
1 John 32 M NaN
2 Adam 44 F NaN

我想以某种方式将 HomeAddr 和 Age 列的内容转移到 column+1。以下是预期输出的示例。
    Name HomeAddr  Age Genre
0 Brian NaN 12 M
1 John NaN 32 M
2 Adam NaN 44 F

我尝试使用 .shift() 但它不起作用。
import pandas as pd 

df = pd.DataFrame ({
'Name':['Brian','John','Adam'],
'HomeAddr':[12,32,44],
'Age':['M','M','F'],
'Genre': ['NaN','NaN','NaN']
})

df['HomeAddr'] = df['HomeAddr'].shift(-1)
print(df)


Name HomeAddr Age Genre
0 Brian 32.0 M NaN
1 John 44.0 M NaN
2 Adam NaN F NaN

有什么想法吗?谢谢!

最佳答案

使用 DataFrame.shift ,但有必要将列转换为字符串以避免丢失值,然后将数字列转换回:

df.loc[:, 'HomeAddr':] = df.loc[:, 'HomeAddr':].astype(str).shift(1, axis=1)
df['Age'] = pd.to_numeric(df['Age'])
print (df)
Name HomeAddr Age Genre
0 Brian NaN 12 M
1 John NaN 32 M
2 Adam NaN 44 F

另一个开箱即用的解决方案:
df = df.drop('Genre', axis=1).rename(columns={'HomeAddr':'Age', 'Age':'Genre'})
df.insert(1, 'HomeAddr', np.nan)
print (df)
Name HomeAddr Age Genre
0 Brian NaN 12 M
1 John NaN 32 M
2 Adam NaN 44 F

关于python-3.x - 如何将列的内容移动到它旁边的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60931508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com