Python 如何透视和重新构造复杂的数据帧,以便所有行中的所有键值对都可以放入数据库?
目前,我有一个csv文件,如下所示:Python 如何透视和重新构造复杂的数据帧,以便所有行中的所有键值对都可以放入数据库?,python,pandas,csv,dataframe,pivot-table,Python,Pandas,Csv,Dataframe,Pivot Table,目前,我有一个csv文件,如下所示: id key1 value1 key2 value2 key3 value3 key4 value4 0 Colour Blue Shape Square Price 3 1 Age 4 Colour Red Price 5 Condition New 我正在尝试将此作为熊猫中的数据帧来阅读。我如何将其转换为 id Colour Shape Price
id key1 value1 key2 value2 key3 value3 key4 value4
0 Colour Blue Shape Square Price 3
1 Age 4 Colour Red Price 5 Condition New
我正在尝试将此作为熊猫中的数据帧来阅读。我如何将其转换为
id Colour Shape Price Age Condition
0 Blue Square 3 NULL NULL
1 Red NULL 5 4 New
最终目标是对其进行格式化,以便将其作为表导入MySQL数据库 你可以用这个
df1 = df.filter(like='key').stack().reset_index().rename(columns={'level_0':'id','level_1':'keys',0:'key_val'})
df2 = df.filter(like='value').stack().reset_index().rename(columns={'level_0':'id','level_1':'valnum',0:'val'})
(df1.merge(df2,on ='id',how='outer', left_index=True, right_index=True).pivot('id','key_val','val')
.reset_index()
.rename_axis(None, axis=1)
.drop('None',axis=1))
输出
id Age Colour Condition Price Shape
0 0 NaN Blue NaN 3 Square
1 1 4 Red New 5 NaN
我更喜欢@moys解决方案,但这是我的
# get every key-value column pair
cols_zipped = [*zip(df.columns,df.columns[1:])][::2]
# create single key-value column pair
df_lst = []
for _ in cols_zipped:
df_ = df.loc[:,[*_]]
df_.rename({_[0]:'key', _[1]:'value'}, axis=1, inplace=True)
df_lst.append(df_)
df_concat = pd.concat(df_lst)
# groupby key, apply list to values, and convert to a dictionary
key_dct = df_concat.groupby('key')['value'].apply(list).to_dict()
# create new dataframe
pd.DataFrame.from_dict(key_dct, orient='index').T
您最初是如何将数据转换成这种格式的?