gpt4 book ai didi

python - 使用分层索引更改数据框中的数据

转载 作者:太空狗 更新时间:2023-10-29 21:53:21 24 4
gpt4 key购买 nike

如何使用分层索引更改 DataFrame 中的每个元素?例如,也许我想将字符串转换为 float :

from pandas import DataFrame
f = DataFrame({'a': ['1,000','2,000','3,000'], 'b': ['2,000','3,000','4,000']})
f.columns = [['level1', 'level1'],['item1', 'item2']]
f
Out[152]:
level1
item1 item2
0 1,000 2,000
1 2,000 3,000
2 3,000 4,000

我试过这个:

def clean(group):
group = group.map(lambda x: x.replace(',', ''))
return group
f.apply(clean)
Out[153]:
(level1, item1) (level1, item2)
0 1000 2000
1 2000 3000
2 3000 4000

如您所见,它对层次索引做了相当大的改变。我怎样才能避免这种情况?或者也许有更好的方法。

谢谢

最佳答案

axis 选项传递给 apply 函数:

In [265]: f.apply(clean, axis=1)
Out[265]:
level1
item1 item2
0 1000 2000
1 2000 3000
2 3000 4000

当两个轴都有分层索引时,这里有一个解决方法:

In [316]: f.index = [[1,2,3],[1,2,3]]

In [317]: f
Out[317]:
level1
item1 item2
1 1 1,000 2,000
2 2 2,000 3,000
3 3 3,000 4,000

In [314]: f.apply(clean, axis=1).reindex(f.index)
Out[314]:
level1
item1 item2
1 1 1000 2000
2 2 2000 3000
3 3 3000 4000

关于python - 使用分层索引更改数据框中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14025549/

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