Python Pandas 将字符串分割函数应用于索引

问题描述 投票:0回答:1

我有一个包含邮政编码和计数的 Pandas DataFrame。它是使用

value_count
创建的。

数据框看起来像这样:

          count
Postcode       
AL1 1AJ     151
AL1 1AR      36
AL1 1AS      21
AL1 1AT      12
AL1 1AU      11
...         ...
YO8 9YD      10
YO8 9YE       4
YO90 1UU      2
YO90 1WR      1
YO91 1RT      1

我正在尝试使用字符串拆分函数来拆分索引列。我的目标是截取每个邮政编码,仅返回第一部分。

这是一个可以(应该做?)这个功能的函数。

def split_postcode(postcode):
    postcode_parts = postcode.split(' ')
    
    if len(postcode_parts) == 2:
        return postcode_parts[0]
    elif len(postcode_parts) == 1:
        return postcode
    else:
        print(f'unexpected postcode length: {len(postcode_parts)}')

我尝试将其应用到

# value_count_df is the above DataFrame
value_count_df.apply(split_postcode, axis=0)

但是失败并出现错误

ValueError: Length mismatch: Expected axis has 1 elements, new values have 2 elements

我想做的事情可能没有多大意义,因为如果我没记错的话,索引列是不可变的。

所以我不知道如何继续。

我创建此 DataFrame 的方式可能比替代方法不太合适。


这里有一些关于我如何创建

value_count_df
对象的信息。

  • 我从 SQL 文件中读取邮政编码数据,并将所有值插入到列表中。
  • 然后我这样做了:
postcode_df = pandas.DataFrame(postcode_list)
postcode_df.columns = ['Postcode']
    
value_count = postcode_df.value_counts()
    
value_count_df = pandas.DataFrame(value_count)
value_count_df.columns = ['Postcode', 'Count']
value_count_df = value_count_df.sort_index()

# fails
value_count_df.apply(split_postcode, axis=0)

我应该如何以不同的方式做事才能获得合理的结果?

最终目标是将邮政编码截断为邮政编码的“第一个”部分(用空格

' '
字符分割,并返回第一个字符串),然后获取每个唯一字符串的值计数。

我目前有每个唯一邮政编码的值计数,我只想对“截断的”邮政编码重复此操作。

我可以通过从现有列表创建一个新的截断邮政编码列表来完成此操作,但这似乎效率低下,最好了解如何直接使用 DataFrame 中的数据来完成此操作。

python pandas dataframe series
1个回答
0
投票

IIUC,你可以使用简单的

.str.split
:

first_part = df.index.str.split(" ").str[0]
print(first_part)

打印:

Index(['AL1', 'AL1', 'AL1', 'AL1', 'AL1', 'YO8', 'YO8', 'YO90', 'YO90',
       'YO91'],
      dtype='object', name='Postcode')

如果你想要独特的:

print(first_part.unique())

打印:

Index(['AL1', 'YO8', 'YO90', 'YO91'], dtype='object', name='Postcode')

如果要设置索引:

df.index = df.index.str.split(" ").str[0]
print(df)

打印:

          count
Postcode       
AL1         151
AL1          36
AL1          21
AL1          12
AL1          11
YO8          10
YO8           4
YO90          2
YO90          1
YO91          1
© www.soinside.com 2019 - 2024. All rights reserved.