python - Pandas :如何将具有多个值的单元格转换为多行?

标签 python pandas dataframe

我有一个像这样的 DataFrame:

Name asn
Org1 asn1,asn2
org2 asn3
org3 asn4,asn5

我想将我的 DataFrame 转换成如下所示:

Name asn
Org1 asn1
Org1 asn2
org2 asn3
org3 asn4
Org3 asn5

有人知道我该怎么做吗?

最佳答案

假设您的起始 DataFrame 名为 df,您可以这样写:

>>> df2 = df.asn.str.split(',').apply(pd.Series)          # break df.asn into columns
>>> df2.index = df.Name                                   # set the index as df.Name
>>> df2 = df2.stack().reset_index('Name')                 # stack and reset_index
>>> df2
    Name       0
0   Org1    asn1
1   Org1    asn2
0   org2    asn3
0   org3    asn4
1   org3    asn5

剩下要做的就是重命名该列:

df2.rename(columns={0: 'asn'}, inplace=True)

根据您的下一步行动,您可能还想设置一个更有用的索引。

关于python - Pandas :如何将具有多个值的单元格转换为多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29589977/

相关文章:

python - 线程中的 while 循环

python - 尝试使用 Pandas 和 Python 绘图时出现空系列

python-3.x - pandas SettingWithCopyWarning 仅在函数内部

python - 数据帧列中的时间差

python - 使用 pd.merge 映射两个数据帧

python - 将带有 JOIN ON 的 SQL 查询转换为 SQLAlchemy

python - 在列上使用 `split` 太慢 - 如何获得更好的性能?

python - 如何将列值除以不同行的值?

python - 如何从 pandas 数据框中选择相同的行以及 null

python - 将 DataFrame.query() 与 pandas.Series.str.contains 一起使用会得到 AttributeError : 'dict' object has no attribute 'append'