我有一个pandas DataFrame,其列名为positions
,其中包含具有以下示例语法的字符串值:
[{'y': 49, 'x': 44}, {'y': 78, 'x': 31}]
[{'y': 1, 'x': 63}, {'y': 0, 'x': 23}]
[{'y': 54, 'x': 9}, {'y': 78, 'x': 3}]
我想在我的熊猫数据帧创建4个新列,y_start
,x_start
,y_end
,x_end
,这仅仅是数字的提取。
例如,对于第一行的示例,我的新列将具有以下值:
y_start
= 49
x_start
= 44
y_end
= 78
x_end
= 31
总而言之,我希望仅提取出现的第一,第二,第三和四个数字,并将其保存到单独的列中。
ast.literal_eval
pandas.DataFrame
构造函数将列表分开以分隔列,因为它比使用列表要快.apply(pd.Series)
pandas.json_normalize
,.rename
各列以及.concat
它们一起将每列中的dict转换为每个键单独的列。converters
参数.read_csv
。
df = pd.read_csv('data.csv', converters={'str_column': literal_eval})
import pandas as pd
from ast import literal_eval
# dataframe
data = {'data': ["[{'y': 49, 'x': 44}, {'y': 78, 'x': 31}]", "[{'y': 1, 'x': 63}, {'y': 0, 'x': 23}]", "[{'y': 54, 'x': 9}, {'y': 78, 'x': 3}]"]}
df = pd.DataFrame(data)
# convert the strings in the data column to dicts
df.data = df.data.apply(literal_eval)
# separate the strings into separate columns
df[['start', 'end']] = pd.DataFrame(df.data.tolist(), index=df.index)
# use json_normalize to convert the dicts to separate columns and join the dataframes with concat
cleaned = pd.concat([pd.json_normalize(df.start).rename(lambda x: f'{x}_start', axis=1), pd.json_normalize(df.end).rename(lambda x: f'{x}_end', axis=1)], axis=1)
# display(cleaned)
y_start x_start y_end x_end
0 49 44 78 31
1 1 63 0 23
2 54 9 78 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句