gpt4 book ai didi

python - 如何在 pandas 数据框中快速高效地将两列( float )分类为一列?

转载 作者:太空宇宙 更新时间:2023-11-03 13:10:23 24 4
gpt4 key购买 nike

我想通过 cat 两列(float 或 int)获得一个新列,如下所示,

所以有人有更好的主意吗?

我觉得我的东西太复杂了

a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,5,6,5,10])

abc=pandas.DataFrame({'a':a, 'b':b, 'c':c})

abc
a b c
0 1 2 3
1 3 4 5
2 5 6 6
3 7 8 5
4 9 10 10

abc['new']=pandas.Series(map(str,abc.iloc[:,0])).str.cat(pandas.Series(map(str,abc.iloc[:,1])), sep='::')

abc
a b c new
0 1 2 3 1::2
1 3 4 5 3::4
2 5 6 6 5::6
3 7 8 5 7::8
4 9 10 10 9::10

最佳答案

使用astype转换为 str:

#if need select columns by position with iloc
abc['new'] = abc.iloc[:,0].astype(str) + '::' + abc.iloc[:,1].astype(str)
print (abc)
a b c new
0 1 2 3 1::2
1 3 4 5 3::4
2 5 6 6 5::6
3 7 8 5 7::8
4 9 10 10 9::10

#if need select by column names
abc['new'] = abc['a'].astype(str) + '::' + abc['b'].astype(str)
print (abc)
a b c new
0 1 2 3 1::2
1 3 4 5 3::4
2 5 6 6 5::6
3 7 8 5 7::8
4 9 10 10 9::10

解决方案 str.cat :

abc['new'] = abc['a'].astype(str).str.cat(abc['b'].astype(str), sep='::')
print (abc)
a b c new
0 1 2 3 1::2
1 3 4 5 3::4
2 5 6 6 5::6
3 7 8 5 7::8
4 9 10 10 9::10

关于python - 如何在 pandas 数据框中快速高效地将两列( float )分类为一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44942637/

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