[英]create multiple new dataframes based on an existing data frames column in python
我有一個熊貓數據框df
,它有4列和很多行。
我想基於數據框架的列之一的值創建5個不同的數據框架。 我所指的列稱為color
。
color
具有5個唯一值: red
, blue
, green
, yellow
, orange
。
我想做的是5個新數據框中的每一個都應包含所有具有color
值的行。 例如, df_blue
應該具有所有行和列,而在其他數據框中, color
列中的值是藍色。
我的代碼如下:
# create 5 new data frames
df_red = []
df_blue= []
df_green= []
df_yellow= []
df_orange= []
for i in range(len(df)):
if df['color'] == "blue"
df_blue.append(df)
# i would do if-else statements to satisfy all 5 colors
我覺得我缺少一些邏輯...有什么建議或意見嗎?
謝謝!
您需要使用groupby
。 下面的代碼片段創建一個示例DataFrame並將其轉換為字典,其中顏色是鍵,而匹配的數據幀是值:
df = pd.DataFrame({'color': ['red','blue','red','green','blue'],
'foo': [1,2,3,4,5]})
colors = {color: dfc for color,dfc in df.groupby('color')}
#{'blue': color foo
# 1 blue 2
# 4 blue 5,
# 'green': color foo
# 3 green 4,
# 'red': color foo
# 0 red 1
# 2 red 3}
我最終對每種顏色都做了這個。
blue_data = data[data.color =='blue']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.