我在python中有一个非结构化数据框架,它有两个变量X和Y。X中的每个观察都是数组,Y是类变量,看起来像
X Y
1. [ [ 1,2] ] a
2. [ [ 2,3] ] b
我想拥有它
1. 1 2 a
2. 2 3 b
I have tried option from numpy to data frame but not working
import pandas as pd
df=pd.DataFrame({'X':[[[1,2]],[[3,4]]],'Y':['a','b']})
def expand(x):
x=x['X'][0]
return x
df['X1'],df['X2']=zip(*df.apply(expand,axis=1))
df=df.drop(['X'],axis=1)
说明:使用 zip() 和 apply(axis=1),我们可以使用 'X' 生成 2 个新列。
对于“X”中的许多元素:
import pandas as pd
df=pd.DataFrame({'X':[[[1,2,3,4]],[[3,4,5,6]]],'Y':['a','b']})
def expand(x):
new_columns=x['X'][0]
return new_columns+[x['Y']]
df=pd.DataFrame(zip(*df.apply(expand,axis=1))).T
现在,“X”可以有任意数量的元素。例如,我使用带有 4 个元素的“X”。
import pandas as pd
# Create the initial DataFrame
data = {'X': [[[1, 2]], [[2, 3]]], 'Y': ['a', 'b']}
df = pd.DataFrame(data)
# Transform the DataFrame
df_transformed = pd.DataFrame(df['X'].apply(lambda x: x[0]).tolist(), columns=['X1', 'X2'])
df_transformed['Y'] = df['Y']
# Display the transformed DataFrame
print(df_transformed)