Pandas子字符串DataFrame列

4

我有一个名为positions的pandas DataFrame列,其中包含以下示例语法的字符串值:

[{'y': 49, 'x': 44}, {'y': 78, 'x': 31}]
[{'y': 1, 'x': 63}, {'y': 0, 'x': 23}]
[{'y': 54, 'x': 9}, {'y': 78, 'x': 3}]

我想在pandas DataFrame中创建四个新列,y_startx_starty_endx_end,这些列只提取数字。
例如,对于第一行示例,我的新列将具有以下值: y_start = 49
x_start = 44
y_end = 78
x_end = 31
总之,我希望提取数字的第一个、第二个、第三个和第四个出现,并将它们保存到各个列中。
4个回答

3
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

2

将字符串转换为对象:

import ast
df['positions'] = df['positions'].apply(ast.literal_eval)

这是一种方法:
df1 = pd.DataFrame.from_records(pd.DataFrame.from_records(df.positions)[0]).rename(columns={"x":"x_start", "y":"y_start"})    
df2 = pd.DataFrame.from_records(pd.DataFrame.from_records(df.positions)[1]).rename(columns={"x":"x_end", "y":"y_end"})
df_new = pd.concat([df1, df2], axis=1)

另外,再简洁一些:

df1 = pd.DataFrame(df.positions.to_list())[0].apply(pd.Series).rename(columns={"x":"x_start", "y":"y_start"})
df2 = pd.DataFrame(df.positions.to_list())[1].apply(pd.Series).rename(columns={"x":"x_end", "y":"y_end"})
df_new = pd.concat([df1, df2], axis=1)

我不知道这些方法在时间或内存性能上的比较情况。

输出(任一方法):

   y_start  x_start  y_end  x_end
0       49       44     78     31
1        1       63      0     23
2       54        9     78      3

2

虽然不太简洁,但实现方法是编写自定义函数并应用lambda,假设所有行都遵循您在问题中提供的相同模式:

### custom function
def startEndxy(x):
    x = x.split(':')
    return x[1].split(',')[0].replace(' ', ''), x[2].split('},')[0].replace(' ', ''), x[3].split(',')[0].replace(' ', ''), x[4].split('}')[0].replace(' ', '')


### columns creations
df['y_start'] = df['positions'].apply(lambda x: startEndxy(x)[0])
df['x_start'] = df['positions'].apply(lambda x: startEndxy(x)[1])
df['y_end'] = df['positions'].apply(lambda x: startEndxy(x)[2])
df['x_end'] = df['positions'].apply(lambda x: startEndxy(x)[3])

它应该会输出以下内容: 输出

1

首先重构你的系列

df = pd.DataFrame(df['position'].tolist()).rename(columns={0: 'starts', 1:'ends'})

              starts               ends
0  {'y': 54, 'x': 9}  {'y': 78, 'x': 3}
1  {'y': 1, 'x': 63}  {'y': 0, 'x': 23}
2  {'y': 54, 'x': 9}  {'y': 78, 'x': 3}

然后指定开始和结束列。
starts = pd.DataFrame(df['starts'].tolist()).rename(columns={'y': 'y_start', 'x': 'x_start'})
ends = pd.DataFrame(df['end'].tolist()).rename(columns={'y': 'y_start', 'x': 'x_start'})

df = pd.concat([starts, ends], axis=1)

   y_start  x_start  y_end  x_end
0       54        9     78      3
1        1       63      0     23
2       54        9     78      3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接