我有一个这样的数据框 -
df = pd.DataFrame(
{'key': [1, 2, 3, 4],
'col1': [['apple','orange'], ['pineapple'], ['','','guava','',''], ['','','orange','apple','']],
'col2': [['087','799'], ['681'], ['078'], ['816','018']]
}
)
# key col1 col2
#0 1 [apple, orange] [087, 799]
#1 2 [pineapple] [681]
#2 3 [, , guava, , ] [078]
#3 4 [, , orange, apple, ] [816, 018]
我需要拆分“col1”和“col2”列并创建单独的行,但根据它们的索引映射列表元素。所需的输出是这样的 -
desired_df = pd.DataFrame(
{'key': [1, 1, 2, 3, 4, 4],
'col1': [['apple'],['orange'],['pineapple'], ['guava'], ['orange'],['apple']],
'col2': [['087'],['799'], ['681'], ['078'], ['816'],['018']]
}
)
在col1中,可能有元素是空白的,但非空col1元素的总长度将与col2中相应元素的长度相匹配。示例:df 的第 2 行和第 3 行。
我尝试了以下方法,但没有用 -
df.set_index(['key'])[['col1','col2']].apply(pd.Series).stack().reset_index(level=1, drop=True)
最佳答案
因为您知道每个列表中非空元素的数量总是匹配的,所以您可以分别展开
每一列,过滤掉空白,然后将结果连接回来。添加 .reset_index()
如果您希望 'key'
作为列返回。
import pandas as pd
pd.concat([df.set_index('key')[[col]].explode(col).query(f'{col} != ""')
for col in ['col1', 'col2']], axis=1)
# Without the f-string
#pd.concat([df.set_index('key')[[col]].explode(col).query(col + ' != ""')
# for col in ['col1', 'col2']], axis=1)
col1 col2
key
1 apple 087
1 orange 799
2 pineapple 681
3 guava 078
4 orange 816
4 apple 018
如果您使用的是 pandas
的旧版本,它不允许使用 explode
方法,请使用 @BEN_YO's method to unnest .我将把相关代码复制到这里,因为有几个不同的版本可供选择。
import numpy as np
def unnesting(df, explode):
idx = df.index.repeat(df[explode[0]].str.len())
df1 = pd.concat([
pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
df1.index = idx
return df1.join(df.drop(explode, 1), how='left')
pd.concat([unnesting(df.set_index('key')[[col]], explode=[col]).query(f'{col} !=""')
for col in ['col1', 'col2']], axis=1)
# Same output as above
关于python - 将多列列表拆分为单独的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63583059/