gpt4 book ai didi

python - 更好的 Pandas 方法来计算不同列中值的频率

转载 作者:行者123 更新时间:2023-12-02 02:07:02 25 4
gpt4 key购买 nike

我有一个 pandas.DataFrame,邮政编码分为两列。我只想用 value_counts() 计算所有邮政编码的出现次数。但他们在哪一栏对我来说并不重要。我需要 DataFrame 中所有 ZIPCODE 列的结果。

这是列中带有邮政编码的初始数据:

   ZIPCODE_A  ZIPCODE_B
0 10000 40000
1 20000 30000
2 20000 20000
3 10000 50000
4 30000 10000

最终的预期结果是:

       ZIPCODE_N
10000 3
20000 3
30000 2
40000 1
50000 1

问题

我的解决方案有效,但看起来很复杂。还有另一种更优雅的pandas方式来解决这个问题吗?

MWE

#!/usr/bin/env python3
import pandas as pd
0000
df = pd.DataFrame({'ZIPCODE_A': [10000, 20000, 20000, 10000, 30000],
'ZIPCODE_B': [40000, 30000, 20000, 50000, 10000]})

print(df)

a = df.ZIPCODE_A.value_counts()
b = df.ZIPCODE_B.value_counts()

a = pd.DataFrame(a)
b = pd.DataFrame(b)

r = a.join(b, how='outer')

r.loc[r.ZIPCODE_A.isna(), 'ZIPCODE_A'] = 0
r.loc[r.ZIPCODE_B.isna(), 'ZIPCODE_B'] = 0

r['ZIPCODE_N'] = r.ZIPCODE_A + r.ZIPCODE_B
r.ZIPCODE_N = r.ZIPCODE_N.astype(int)

del r['ZIPCODE_A']
del r['ZIPCODE_B']

print(r)

最佳答案

首先堆叠数据帧以将所有列的值包含在单个列中,然后调用value_counts(),如果需要,调用to_frame() code> 并传递新的列名称,即 ZIPCODE_N

>>> df.stack().value_counts().to_frame("ZIPCODE_N")

ZIPCODE_N
10000 3
20000 3
30000 2
50000 1
40000 1

关于python - 更好的 Pandas 方法来计算不同列中值的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68301817/

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