![](/img/trans.png)
[英]Pandas: Convert DataFrame Column Values Into New Dataframe Indices and Columns
[英]Pandas DataFrame - Convert columns into JSON and add as a new column
考虑使用我从11k行大小的 MySQL 表中获得的 DataFrame:
col1 | col2 | col3 | col4
-----------------------------
cat | black | small | lovely
-----------------------------
dog | white | medium| brave
-----------------------------
mice | grey | tinny | fast
...
我想将其动态转换为以下内容:
col1 | newcol
------------------------------------------------------------
cat | {"col2": "black", "col3": "small", "col4": "lovely"}
------------------------------------------------------------
dog | {"col2": "white", "col3": "medium", "col4": "brave"}
------------------------------------------------------------
mice | {"col2": "grey", "col3": "tinny", "col4": "fast"}
...
您可以在axis=1
上将agg
作为dict
对于字典:
out = df[['col1']].assign(new_col=df.iloc[:,1:].agg(dict,1))
对于 json:
out = df[['col1']].assign(new_col=df.iloc[:,1:].agg(pd.Series.to_json,1))
print(out)
col1 new_col
0 cat {'col2': 'black', 'col3': 'small', 'col4': 'lo...
1 dog {'col2': 'white', 'col3': 'medium', 'col4': 'b...
2 mice {'col2': 'grey', 'col3': 'tinny', 'col4': 'fast'}
正如您所料,有很多方法可以做到这一点,但这是我想到的:
>>> import pandas as pd
>>> d = {"col1": ["cat", 'dog', 'mice'], "col2": ["black", "white", "grey"], "col3": ["small", 'medium', 'tinny'], 'col4': ['lovely', 'brave','fast']}
>>> df = pd.DataFrame(d)
>>> pd.concat([df[['col1']], pd.DataFrame({"newcol": df[['col2','col3','col4']].to_dict(orient='records')})], axis=1)
对于您可能不知道 DataFrame 中的列名的情况,您可以使用以下 select 列索引。 在这种情况下,从第 1 列开始,直到结束。
>>> pd.concat([df[['col1']], pd.DataFrame({"newcol": df.iloc[:, 1:].to_dict(orient='records')})], axis=1)
使用df.to_json(orient='records')
转储 json 记录列表,然后将 json 加载到字典列表,分配给新列。
import pandas as pd
df = pd.DataFrame({'col1': ['cat', 'dog', 'mice'],
'col2' : ['black', 'white', 'grey'],
'col3' : ['small', 'medium', 'tinny']})
# create json column
# data_json = df.iloc[:, 1:].to_json(orient='records')
# data = json.loads(data_json)
data = df.iloc[:, 1:].to_dict(orient='records')
# keep first column
dfn = df.iloc[:, [0]].copy()
dfn['newcol'] = data
# dfn['newcol'] = pd.Series(data).map(json.dumps)
dfn
col1 newcol
0 cat {"col2": "black", "col3": "small"}
1 dog {"col2": "white", "col3": "medium"}
2 mice {"col2": "grey", "col3": "tinny"}
data_json
(类型str
)
[{"col2":"black","col3":"small"},{"col2":"white","col3":"medium"},{"col2":"grey","col3":"tinny"}]
除了 Anky 的回答,我发现这篇文章描述了更多的操作: https://codeflex.co/mysql-table-migration-with-pandas-dataframe/
我在下面的示例中使用了三列。
data = {'col1': ['cat', 'dog', 'mice'], 'col2' : ['black', 'white', 'grey'], 'col3' : ['small', 'medium', 'tinny']}
import pandas as pd
df = pd.DataFrame(data)
col = list(df.columns)
我们可以使用 lambda function 如下
df.apply(lambda x: {col[1]:x[1], col[2]:x[2]}, axis =1)
您可以将其添加到 dataframe 如下
df['new_col'] = df.apply(lambda x: {col[1]:x[1], col[2]:x[2]}, axis =1)
这将产生以下 output。
df
col1 col2 col3 new_col
0 cat black small {'col2': 'black', 'col3': 'small'}
1 dog white medium {'col2': 'white', 'col3': 'medium'}
2 mice grey tinny {'col2': 'grey', 'col3': 'tinny'}
然后使用 df.drop 删除不需要的列
这应该会产生所需的 output。
df.drop(['col2', 'col3'], axis = 1)
col1 new_col
0 cat {'col2': 'black', 'col3': 'small'}
1 dog {'col2': 'white', 'col3': 'medium'}
2 mice {'col2': 'grey', 'col3': 'tinny'}
对于给定要求,我建议使用 itertuples 生成字典列表并将其分配给 dataframe,如下所示
import pandas as pd
data = {'col1': ['cat', 'dog', 'mice'], 'col2' : ['black', 'white', 'grey'], 'col3' : ['small', 'medium', 'tinny'], 'col4': ['lovely','brave','fast']}
df = pd.DataFrame(data)
def getDictColumn_df1(df, new_col_name="newcol", cols_from_start=1):
df[new_col_name] = tuple(map(lambda row: row._asdict(), df.iloc[:,cols_from_start:].itertuples()))
return df[['col1', new_col_name]]
getDictColumn_df1(df)
要了解有关 itertuples() 的更多信息, 请查看
当您想保留所有索引并将所有值转换为单个字典时,对于稍微不同的情况,您可以这样做
def getDictColumn_df2(df, new_col_name="newcol"):
df[new_col_name] = tuple(map(lambda row: row._asdict(), df.itertuples(index=False)))
return df[[new_col_name]]
getDictColumn_df2(df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.