简体   繁体   English

熊猫数据框-具有重组数据的新数据框

[英]Pandas Dataframes - new dataframe with reorganized data

I'm new to Pandas and trying to create a new dataframe from an existing one. 我是Pandas的新手,正在尝试从现有的数据库创建一个新的数据框架。

My current dataframe has a format: 我当前的数据框具有以下格式:

ID   Country    Status  
ABC  USA        Go
ABC  Columbia   Stop
ABC  Japan      Pause
ABC  Egypt      Go 
DEF  Canada     Go
DEF  Peru       Stop

I'm trying to consolidate the data to make it more compact. 我正在尝试合并数据以使其更紧凑。 My new format is: 我的新格式是:

ID   Go          Stop      Pause
ABC  USA, Egypt  Columbia  Japan
DEF  Canada      Peru

Basically, the possible Status values become the columns and, for each ID, these columns are populated with a list of countries having that status. 基本上,可能的状态值将成为列,对于每个ID,这些列将填充具有该状态的国家/地区的列表。 I'm new to pandas and struggling with the best way to approach this - any suggestions would be greatly appreciated. 我是熊猫的新手,正在努力寻求最好的方法-任何建议将不胜感激。

You can use pd.pivot_table : 您可以使用pd.pivot_table

res = df.pivot_table(index='ID', columns='Status', values='Country', aggfunc=', '.join)

print(res)

Status          Go  Pause      Stop
ID                                 
ABC     USA, Egypt  Japan  Columbia
DEF         Canada   None      Peru

If you absolutely must do this then this is how you do it. 如果您绝对必须这样做,那么这就是您的做法。

In [48]: df.groupby(['ID', 'Status'])['Country'].apply(','.join).unstack()
Out[48]:
Status         Go  Pause      Stop
ID
ABC     USA,Egypt  Japan  Columbia
DEF        Canada    NaN      Peru

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将pandas数据帧压缩到新的数据帧中 - Zip pandas dataframes into a new dataframe Pandas:if 语句比较 2 个数据帧中的数据。 如果满足条件,则将行数据复制到新的 dataframe - Pandas: if statement comparing data in 2 dataframes. If condition met, then copy the row data to a new dataframe Select 数据从两个数据帧转换成两个数据帧 Pandas DataFrame 和 ZA7F5F35426B567411FCZ9231 - Select data from two dataframes into two dataframes with Pandas DataFrame and Python 熊猫数据框:通过查找和计算现有数据框来制作新数据框 - pandas dataframe: make new dataframe from lookup and computation of existing dataframes 如何将 pandas 数据帧值连接到相应的行 ID 并在 ID 不在第一个 df 中时添加包含来自第二个 dataframe 的新数据的新行 - how to join pandas dataframes values to correspondant rows ID and add a new rows with new data from the second dataframe when the ID not in first df 比较两个数据框以使用Pandas返回新数据框-Python - Comparing two dataframes to return a new dataframe using pandas - Python 通过对现有数据框应用逻辑来创建新的 Pandas 数据框 - Creating a new pandas dataframe by applying logic to already existing dataframes 将 Pandas 数据帧行拆分为搜索的列值到新的数据帧中 - Split pandas dataframe rows up to searched column value into new dataframes Pandas 通过在不使用 iterrows 的情况下查询其他数据帧来创建新的 dataframe - Pandas create new dataframe by querying other dataframes without using iterrows 选择具有两个唯一标识符的 pandas dataframe 中的行并将它们存储为新数据帧 - Selecting rows in a pandas dataframe with two unique identifiers and storing these as new dataframes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM