Skip to main content
 首页 » 编程设计

python之拆分没有 str 属性的 pandas 列对象

2025年01月19日10lvdongjie

我正在尝试 .split() 具有多个值的表格中的单元格。然后我想将这些拆分值堆叠到一个列中。

我不断收到:AttributeError: 'DataFrame' object has no attribute 'str'

  1. 一些列将具有相同的名称/标签
  2. 值将在 str、flt、int 等之间混合
  3. 会有缺失值
  4. 我将此表保存为 .csv

示例表:

(原表)

List , A,  A , B     , B , A , C   
row 1,joey,mike,henry,albert    ,sherru,tomkins   
row 2, ,pig|soap    , ,123, ,  ,   
row 3,yes, , , and|5.3|7, , ,      
row 4, ,new york|up, , , , ,                   
row 5,bubbles, ,movie, , , ,   

(修改后的表格)

List | Value | Category   
row 1,joey, A   
row 1,mike,A   
row 1,henry,B   
row 1,albert,B   
row 1,sherru,A   
row 1,tomkins,C   
row 2,pig,A   
row 2,soap,A   
row 2,123,B   
row 3,yes,A   
row 3,and,B   
row 3,5.3,B   
...    
row 5,movie,B 

这是我正在使用的代码,我是 python/pandas 的新手,所以它不是很好:

import pandas as pd   
df = pd.read_csv('test.csv')   
 
df2 = df.A.str.split('|').apply(pd.series)   
df2.index = df.set_index([List]).index   
df2.stack().reset_index([List]) 

请您参考如下方法:

您可以 set_index作为第一步,将参数 expand=True 添加到 split对于 DataFrame:

df2 = df.set_index('List').A.str.split(',', expand=True).stack().reset_index() 

你得到错误是因为列名中的重复,所以 df.A 将所有列 A 作为 DataFrame 返回。

有两种可能的解决方案:

  1. 升级 pandas,因为 read_csv在较新的版本中管理欺骗 - 添加 .1, .2 ( pandas 0.19+ )

  2. 按 cumcount 更改列名称:


s = df.columns.to_series() 
df.columns = df.columns + s.groupby(s).cumcount().astype(str).radd('.').replace('.0','') 

示例:

df = pd.DataFrame({'A':list('abcdef'), 
                   'B':[4,5,4,5,5,4], 
                   'C':[7,8,9,4,2,3], 
                   'D':[1,3,5,7,1,0], 
                   'E':[5,3,6,9,2,4], 
                   'F':list('aaabbb')}) 
df.columns = list('AABBCD') 
print (df) 
   A  A  B  B  C  D 
0  a  4  7  1  5  a 
1  b  5  8  3  3  a 
2  c  4  9  5  6  a 
3  d  5  4  7  9  b 
4  e  5  2  1  2  b 
5  f  4  3  0  4  b 
 
s = df.columns.to_series() 
df.columns = df.columns + s.groupby(s).cumcount().astype(str).radd('.').replace('.0','') 
print (df) 
   A  A.1  B  B.1  C  D 
0  a    4  7    1  5  a 
1  b    5  8    3  3  a 
2  c    4  9    5  6  a 
3  d    5  4    7  9  b 
4  e    5  2    1  2  b 
5  f    4  3    0  4  b