包含datafram中单个元素列表的正确列

2024-10-02 04:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有福勒。数据帧:

      a_name  Season    yl
yl
4.939  cherka  2000.0  [4.939]
4.441  cherka  2001.0  [4.441]
4.320  cherka  2002.0   [4.32]
3.718  cherka  2003.0  [3.718]
4.533  cherka  2004.0  [4.533]

如何将其转换为:

      a_name  Season    yl
yl
4.939  cherka  2000.0  4.939
4.441  cherka  2001.0  4.441
4.320  cherka  2002.0  4.32
3.718  cherka  2003.0  3.718
4.533  cherka  2004.0  4.533

我是这样做的:

df.groupby(['a_name', 'Season', 'yl'])['yl'].unique().reset_index(level=[0,1])

Tags: 数据namedfindexlevelseasonuniquereset
3条回答
df['max']=df['max'].apply(pd.Series)
df
Out[1428]: 
   idCaseMax  idCaseMin  lineId  max  min
0          5         10       1  120 -110
1         27         23       2  150 -205
2         15         40       3  110  -80
3         11          8       4   90 -150

数据输入

df = pd.DataFrame({"lineId":[1,2,3,4], "idCaseMin": [10, 23, 40, 8], "min": [-110, -205, -80, -150], "idCaseMax": [5, 27, 15, 11], "max": [[120], [150], [110], [90]]})

使用numpy:

df["y1"] = np.vstack(df["y1"])

扩展我的评论,使用.str[0]

df

       a_name  Season       yl
yl                            
4.939  cherka  2000.0  [4.939]
4.441  cherka  2001.0  [4.441]
4.320  cherka  2002.0   [4.32]
3.718  cherka  2003.0  [3.718]
4.533  cherka  2004.0  [4.533]

df['yl'] = df['yl'].str[0]
df

       a_name  Season     yl
yl                          
4.939  cherka  2000.0  4.939
4.441  cherka  2001.0  4.441
4.320  cherka  2002.0  4.320
3.718  cherka  2003.0  3.718
4.533  cherka  2004.0  4.533

您可以选择使用assignpiRsquared's suggestion)创建副本:

df_new = df.assign(df['yl'].str[0])

df_new

       a_name  Season     yl
yl                          
4.939  cherka  2000.0  4.939
4.441  cherka  2001.0  4.441
4.320  cherka  2002.0  4.320
3.718  cherka  2003.0  3.718
4.533  cherka  2004.0  4.533

相关问题 更多 >

    热门问题