簡體   English   中英

Pandas Dataframe 未將字符串識別為相同的分組

[英]Pandas Dataframe not recognizing strings as identical for grouping

我有一個包含數百個帳號及其描述的數據集。 它已從 Excel 導入到 Python dataframe。 Excel 中的描述具有不同數量的前導和尾隨空格。 帳號為 integer,描述為 object,最終余額為浮點數。

我嘗試去除前導和尾隨空格,用單個替換多個空格,但是當我使用 groupby 時,它不會將描述識別為相同。 如果我只 groupby Account 我得到 435 行,這是正確的。 如果我 groupby 描述我得到超過 1100 這是不正確的(這是原始的行數)。 按帳戶和描述分組產生與按描述分組相同的結果。 這對我來說意味着描述仍然不被視為相同。

我也嘗試過完全不脫衣服,然后毫無喜悅地離開。

關於如何使描述相同的任何想法?

# Replaces multiple white spaces in string to a single whitespace
PE5901_df['Description'] = PE5901_df['Description'].str.replace('\s+', ' ', regex=True)

# Strip leading and trailing spaces from fields to avoid groupby, concat, and merge issues later.
PE5901_df['Description'] = PE5901_df['Description'].str.strip()

# Groupby Account number and Asset name - sums individual rows with identical account numbers.
PE5901_df=PE5901_df.groupby(['Account','Description'],as_index=False).sum()

數據框

這是檢查“描述”列中數據的一種方法。 這將顯示問題是空格還是其他問題。

import pandas as pd

description = [
    '111001 cash deposit', '111001 cash deposit ', '111001 cash deposit  ',
    ' 111001 cash deposit', '  111001 cash deposit', '   111001 cash deposit',
]

elements = pd.Series(description).sort_values().unique()

for element in elements:
    print(f">>{element}<<")

打印輸出為:

>>   111001 cash deposit<<
>>  111001 cash deposit<<
>> 111001 cash deposit<<
>>111001 cash deposit<<
>>111001 cash deposit <<
>>111001 cash deposit  <<

可以使用.str訪問器刪除前導/尾隨空格:

elements = pd.Series(description).str.strip().sort_values().unique()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM