簡體   English   中英

Pandas 通過部分字符串匹配大小將列分配給數組維度錯誤

[英]Pandas Assign column by partial string match size to array dimension error

我有一個這樣的數據框:

  Postcode         Country
0  PR2 6AS  United Kingdom
1  PR2 6AS  United Kingdom
2  CF5 3EG  United Kingdom
3  DG2 9FH  United Kingdom

我根據部分字符串匹配創建了一個要分配的新列:

mytestdf['In_Preston'] = "FALSE"

mytestdf

  Postcode         Country In_Preston
0  PR2 6AS  United Kingdom      FALSE
1  PR2 6AS  United Kingdom      FALSE
2  CF5 3EG  United Kingdom      FALSE
3  DG2 9FH  United Kingdom      FALSE

我希望通過“郵政編碼”上的部分字符串匹配來分配“In_Preston”列。 我嘗試以下操作:

mytestdf.loc[(mytestdf[mytestdf['Postcode'].str.contains("PR2")]), 'In_Preston'] = "TRUE"

但這會返回錯誤“無法將大小為 3 的序列復制到維度為 2 的數組軸”

我再次查看我的代碼並相信問題在於我正在從數據幀的切片中選擇數據幀的切片。 因此我改為

mytestdf.loc[(mytestdf['Postcode'].str.contains("PR2")]), 'In_Preston'] = "TRUE"

但是我的解釋器告訴我這是不正確的語法,盡管我不明白為什么。

我的代碼或我的方法有什么錯誤?

您需要移除內部過濾器:

mytestdf.loc[mytestdf['Postcode'].str.contains("PR2"), 'In_Preston'] = "TRUE"

另一種解決方案是使用numpy.where

mytestdf['In_Preston'] = np.where(mytestdf['Postcode'].str.contains("PR2"), 'TRUE', 'FALSE')
print (mytestdf)
  Postcode         Country In_Preston
0  PR2 6AS  United Kingdom       TRUE
1  PR2 6AS  United Kingdom       TRUE
2  CF5 3EG  United Kingdom      FALSE
3  DG2 9FH  United Kingdom      FALSE

但是,如果要分配 boolean True s 和False s:

mytestdf['In_Preston'] = mytestdf['Postcode'].str.contains("PR2")
print (mytestdf)
  Postcode         Country  In_Preston
0  PR2 6AS  United Kingdom        True
1  PR2 6AS  United Kingdom        True
2  CF5 3EG  United Kingdom       False
3  DG2 9FH  United Kingdom       False

通過comment of Zero編輯:

如果只想檢查Postcode開頭:

mytestdf.Postcode.str.startswith('PR2')

或者為字符串的開頭添加正則表達式^

mytestdf['Postcode'].str.contains("^PR2")

暫無
暫無

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

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