首页 > 解决方案 > 我可以更有效地拆分包含元组/无混合的列吗?

问题描述

我有一个简单的数据框:

import pandas as pd
df = pd.DataFrame({'id':list('abcd')})
df['tuples'] = df.index.map(lambda i:(i,i+1))

# outputs:
#   id  tuples
# 0  a  (0, 1)
# 1  b  (1, 2)
# 2  c  (2, 3)
# 3  d  (3, 4)

然后我可以非常简单地将元组列分成两个,例如

df[['x','y']] = pd.DataFrame(df.tuples.tolist())

# outputs:
#   id  tuples  x  y
# 0  a  (0, 1)  0  1
# 1  b  (1, 2)  1  2
# 2  c  (2, 3)  2  3
# 3  d  (3, 4)  3  4

这种方法也有效:

df[['x','y']] = df.apply(lambda x:x.tuples,result_type='expand',axis=1)

但是,如果我的 DataFrame 稍微复杂一些,例如

df = pd.DataFrame({'id':list('abcd')})
df['tuples'] = df.index.map(lambda i:(i,i+1) if i%2 else None)

# outputs:
#   id  tuples
# 0  a    None
# 1  b  (1, 2)
# 2  c    None
# 3  d  (3, 4)

然后第一种方法抛出“列必须与键的长度相同”(当然),因为有些行有两个值,有些没有,而我的代码预计有两个。

我可以使用 .loc 创建单列,两次。

get_rows = df.tuples.notnull() # return rows with tuples

df.loc[get_rows,'x'] = df.tuples.str[0]
df.loc[get_rows,'y'] = df.tuples.str[1]

# outputs:
#   id  tuples    x    y
# 0  a    None  NaN  NaN
# 1  b  (1, 2)  1.0  2.0
# 2  c    None  NaN  NaN
# 3  d  (3, 4)  3.0  4.0

[旁白:索引如何从右侧仅分配相关行很有用,而不必指定它们。]

但是,我不能使用 .loc 一次创建两列,例如

# This isn't valid use of .loc
df.loc[get_rows,['x','y']] = df.loc[get_rows,'tuples'].map(lambda x:list(x))

因为它抛出错误“形状不匹配:形状(2,2)的值数组无法广播到形状(2,)的索引结果”。

我也不能用这个

df[get_rows][['x','y']] = df[get_rows].apply(lambda x:x.tuples,result_type='expand',axis=1)

因为它抛出通常的“一个值正在尝试在数据帧的切片副本上设置。尝试使用.loc ...”

我忍不住想我错过了什么。

标签: pythonpandasdataframe

解决方案


这是另一种方式(内联评论):

c=df.tuples.astype(bool) #similar to df.tuples.notnull()
#create a dataframe by dropping the None and assign index as df.index where c is True
d=pd.DataFrame(df.tuples.dropna().values.tolist(),columns=list('xy'),index=df[c].index)
final=pd.concat([df,d],axis=1) #concat them both

  id  tuples    x    y
0  a    None  NaN  NaN
1  b  (1, 2)  1.0  2.0
2  c    None  NaN  NaN
3  d  (3, 4)  3.0  4.0

推荐阅读