Lev*_*ich 4 python dataframe python-3.x pandas
我有数据帧df
:
a b c
0 7 5 [[-4, 7], [-5, 6]]
1 13 5 [[-9, 4], [-3, 7]]
Run Code Online (Sandbox Code Playgroud)
我想将带有列表单元格列表(列“c”)的列展平到一个单独的 DataFrame 中,以便:
我设法在下面获得了所需的结果(我知道有一个int
tofloat
转换,但这对我来说并不麻烦):
a b d e
0 7 5 -4.0 7.0
1 7 5 -5.0 6.0
2 13 5 -9.0 4.0
3 13 5 -3.0 7.0
Run Code Online (Sandbox Code Playgroud)
但是,我认为我这样做的方式并不理想,因为它首先使用了大量代码,其次使用iterrows()
.
下面是我的代码:
old_cols = list(df)
old_cols.remove('c')
new_cols = ['d', 'e']
all_cols = old_cols + new_cols
df_flat = pd.DataFrame(columns=all_cols)
for idx, row in df.iterrows():
data = row['c']
for entry in data:
temp_series = pd.Series(index=new_cols)
temp_series['d'] = entry[0]
temp_series['e'] = entry[1]
new_row = pd.concat([row[old_cols], temp_series])
df_flat = df_flat.append(new_row, ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
df = df.groupby(['a','b'])\
.apply(lambda x: pd.DataFrame(x['c'].tolist()[0], columns=['c','d']))\
.reset_index([0,1]).reset_index(drop=True)
print(df)
a b c d
0 7 5 -4 7
1 7 5 -5 6
2 13 5 -9 4
3 13 5 -3 7
Run Code Online (Sandbox Code Playgroud)
解释 :
因为对于列c
中的每个值都是列表列表。为了upack他们,使他们不同的列,我们采取x['c'].tolist()
这个包含2个打开和关闭括号([[[values],[values]]]
),它没有用的,所以x['c'].tolist()[0]
给[[values],[values]]
它用作数据pd.DataFrame
的列['c','d']
和finalyreset_index
上levels = [0,1]
它们是列['a','b']
。
print(pd.DataFrame([[-4, 7], [-5, 6]],columns=['c','d']))
c d
0 -4 7
1 -5 6
print(df.groupby(['a','b'])\
.apply(lambda x: pd.DataFrame(x['c'].tolist()[0], columns=['c','d'])))
c d
a b
7 5 0 -4 7
1 -5 6
13 5 0 -9 4
1 -3 7
Run Code Online (Sandbox Code Playgroud)