gpt4 book ai didi

python - 我可以更有效地拆分包含混合元组/无的列吗?

转载 作者:太空狗 更新时间:2023-10-29 21:41:21 27 4
gpt4 key购买 nike

我有一个简单的 DataFrame:

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)

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

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

最佳答案

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

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

关于python - 我可以更有效地拆分包含混合元组/无的列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57290269/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com