python - Pandas 0.19.0explode() 解决方法

标签 python pandas explode

大家好!

我需要有关 pandas 0.19.0 中的explode() 的替代方案或解决方法的帮助 我有这个 csv 文件

  item        CODE
0 apple       REDGRNYLW
1 strawberry  REDWHT
2 corn        YLWREDPRLWHTPNK

我需要得到这个结果

  item        CODE
1 apple       RED
2 apple       GRN
3 apple       YLW
4 strawberry  RED
5 strawberry  WHT
6 corn        YLW
7 corn        RED
8 corn        PRL
9 corn        WHT
10 corn       PNK

我设法使用 pandas 1.3.3 获得结果,这就是我所做的

import pandas as pd

filename = r'W:\plant_CODE.csv'

df2 = pd.read_csv(filename)

def split_every_3_char(string):
    return [string[i:i+3] for i in range(0, len(string), 3)]

df2.columns = ['item', 'CODE']
df_splitted = (df2.set_index(df2.columns.drop('CODE', 1).tolist())
    .CODE.apply(lambda x: split_every_3_char(x))
    .explode()
    .to_frame()
    .reset_index()
)

print(df_splitted)

不幸的是,我刚刚意识到我仅限于 pandas 0.19.0 并且 explode() 尚不可用。

Traceback (most recent call last):
   File "<string>", line 69, in <module>
   File "lib\site-packages\pandas\core\generic.py", line 2744, in __getattr__
 AttributeError: 'Series' object has no attribute 'explode'

如果有任何解决方案或解决方法,我将不胜感激。 谢谢!

csv_file

最佳答案

将函数的输出转换为Series并使用DataFrame.stack :

df_splitted = (df2.set_index(df2.columns.drop('CODE', 1).tolist())
    .CODE.apply(lambda x: pd.Series(split_every_3_char(x)))
    .stack()
    .reset_index(-1, drop=True)
    .reset_index(name='CODE')
)

print(df_splitted)
         item CODE
0       apple  RED
1       apple  GRN
2       apple  YLW
3  strawberry  RED
4  strawberry  WHT
5        corn  YLW
6        corn  RED
7        corn  PRL
8        corn  WHT
9        corn  PNK

关于python - Pandas 0.19.0explode() 解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71658556/

相关文章:

python - 从 TfidfVectorizer 获取全文

python - 没有唯一列的透视数据框

php - 如何获取数组范围

php - 分解/分解文本字符串的最佳分隔符 - @、!、<>、# 或 |

php - 类似于 MySQL 中 Explode 工作的功能

python - 是否有可能在 numpy 中使用高级列表切片并仍然获得 View ?

python - 精确查找的 QuerySet 值必须使用切片限制为一个结果 - Django

python - 处理超出范围的选择

python - Pandas 创建只有列名的空 DataFrame

python - 垂直读取和写入多个字典到csv文件