【问题标题】:Split pandas column objects with no str attributes拆分没有 str 属性的 pandas 列对象
【发布时间】:2018-02-15 05:59:51
【问题描述】:

我正在尝试.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])

【问题讨论】:

  • 您的 CSV 文件无效:不同的行有不同的列数。你能适当地格式化它吗?

标签: python pandas object split attributes


【解决方案1】:

您可以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

【讨论】:

  • 我仍然收到属性错误:AttributeError: 'DataFrame' object has no attribute 'str' 有什么想法吗?
  • @M-M - 是的,我知道。有问题A 列名重复。你能升级熊猫吗?因为在新版本中 pd.read_csv 将 A, A 列更改为 A, A.1 - 重命名列名。
猜你喜欢
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 2015-07-14
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多