gpt4 book ai didi

python - Pandas 重新排列数据框

转载 作者:太空狗 更新时间:2023-10-30 00:24:01 28 4
gpt4 key购买 nike

我有一个如下的数据框:

Honda [edit]
Accord (4 models)
Civic (4 models)
Pilot (3 models)
Toyota [edit]
Prius (4 models)
Highlander (3 models)
Ford [edit]
Explorer (2 models)

我希望 reshape 它,以便得到如下所示的 2 列数据框:

 Honda     Accord
Honda Civic
Honda Pilot
Toyota Prius
Toyota Highlander

等等。我试过 str.split 试图在编辑之间进行拆分,但没有成功。非常感谢任何建议!此处为 Python 新手...如果之前已解决此问题,我们深表歉意。谢谢!

到目前为止我已经尝试过了

     maker=car['T'].str.extract('(.*\[edit\])', expand=False).str.replace('\[edit\]',"")

这为我提供了制造商列表:本田、丰田和福特。然而,我一直在寻找一种方法来提取制造商之间的模型以创建 2 col DF。

最佳答案

诀窍是先提取汽车列,然后再获取制造商。

import pandas as pd
import numpy as np

df['model'] = df['T'].apply(lambda x: x.split(
'(')[0].strip() if x.count('(') > 0 else np.NaN)

df['maker'] = df['T'].apply(lambda x: x.split('[')[0].strip(
) if x.count('[') > 0 else np.NaN).fillna(method="ffill")

df = df.dropna().drop('T', axis=1).reindex(
columns=['maker', 'model']).reset_index(drop=True)

如果条目包含'(',代码的第一行通过使用拆分和剥离字符串操作提取所有汽车。 , 它分配 NaN否则,我们使用 NaN这样我们就可以在找到制造商后删除这些行。现阶段数据框df将是:

+----+-----------------------+------------+
| | T | model |
|----+-----------------------+------------|
| 0 | Honda [edit] | nan |
| 1 | Accord (4 models) | Accord |
| 2 | Civic (4 models) | Civic |
| 3 | Pilot (3 models) | Pilot |
| 4 | Toyota [edit] | nan |
| 5 | Prius (4 models) | Prius |
| 6 | Highlander (3 models) | Highlander |
| 7 | Ford [edit] | nan |
| 8 | Explorer (2 models) | Explorer |
+----+-----------------------+------------+

第二行做同样的事情,但对于 '['记录,这里是NaNs用于使用 fillna 填充空的制造商单元格现阶段数据框df将是:

+----+-----------------------+------------+---------+
| | T | model | maker |
|----+-----------------------+------------+---------|
| 0 | Honda [edit] | nan | Honda |
| 1 | Accord (4 models) | Accord | Honda |
| 2 | Civic (4 models) | Civic | Honda |
| 3 | Pilot (3 models) | Pilot | Honda |
| 4 | Toyota [edit] | nan | Toyota |
| 5 | Prius (4 models) | Prius | Toyota |
| 6 | Highlander (3 models) | Highlander | Toyota |
| 7 | Ford [edit] | nan | Ford |
| 8 | Explorer (2 models) | Explorer | Ford |
+----+-----------------------+------------+---------+

第三行删除多余的记录并重新排列列并重置索引

|    | maker   | model      |
|----+---------+------------|
| 0 | Honda | Accord |
| 1 | Honda | Civic |
| 2 | Honda | Pilot |
| 3 | Toyota | Prius |
| 4 | Toyota | Highlander |
| 5 | Ford | Explorer |

编辑:

一个更“可爱”的版本(我喜欢单行本)

df = df['T'].str.extractall('(.+)\[|(.+)\(').apply(
lambda x: x.ffill()
if x.name==0
else x).dropna(subset=[1]).reset_index(
drop=True).rename(columns={1:'Model',0:'Maker'})

以上工作原理如下 extractall 将返回一个包含两列的 DataFrame;专栏0对应于使用第一组提取的正则表达式中的组 '(.+)\['即制造商记录以;和列 1 ,对应于第二组即'(.+)\(' , apply 用于遍历列,列名为0将被修改为通过 ffill 向前传播“Maker”值和列 1将保持原样。 dropna 然后与子集 1 一起使用删除列 1 中值所在的所有行是NaN , reset_index 用于删除多索引 extractall产生。最后使用 rename 重命名列和对应字典

enter image description here

另一个衬里(func ;))

 df['T'].apply(lambda line: [line.split('[')[0],None] if line.count('[') 
else [None,line.split('(')[0].strip()]
).apply(pd.Series
).rename(
columns={0:'Maker',1:'Model'}
).apply(
lambda col: col.ffill() if col.name == 'Maker'
else col).dropna(
subset=['Model']
).reset_index(drop=True)

关于python - Pandas 重新排列数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41457322/

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