python - 如果数据框中的列有多个值,则创建多行

标签 python pandas dataframe

我有一个如下所示的 df :-

import pandas as pd 
  
# intialise data of lists. 
data = {'cust':['fnwp', 'utp'], 'events':[['abhi','ashu'],'abhi']} 
  
# Create DataFrame 
df = pd.DataFrame(data) 
  
# Print the output. 
df

enter image description here

我的预期结果是:-

enter image description here

最佳答案

您可以使用 pandas.explode() 函数:

>>> df.explode('events').reset_index(drop=True)

   cust events
0  fnwp   abhi
1  fnwp   ashu
2   utp   abhi

关于python - 如果数据框中的列有多个值,则创建多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65083064/

相关文章:

python - 将不同的聚合函数应用于不同的列(现在不推荐使用重命名的字典)

r - 多个数据框中的多个相同列 - R

python - isinstance(...) 的功能;但没有实例?

python-2.7 在对象导入时执行代码

python - 在 Python 中,如何将一个字符串拆分为多个整数?

python - 我想使用 matplotlib 绘制数据图表,但它显示 float() : 2014-12-10 的无效文字

python - 在 pandas-python 中或制表 : how to set FIXED column width?

python - 在单个 Pandas Dataframe 列中将字符串与数字分开并创建两个新列

python - 如果第一列中的数字是整数,则更新第二列

python - 将 csv 文件中的日期字段读取到数据框中