[英]split arrays as string in one column of pandas to multiple columns
我有以下格式的數據框。 描述為字符串格式。
文件 | 描述 |
---|---|
X | [[array(['MIT', 'MIT', 'MIT', 'MIT', 'MIT'], dtype=object), array([0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217])]] |
是的 | [[array(['APSL-1.0', 'APSL-1.0', 'APSL-1.0', 'APSL-1.0', 'APSL-1.0'], dtype=object), array([0.28552457, 0.28552457, 0.28552457, 0.28552457, 0.28552457])]] |
如何將數據幀轉換為以下格式。
文件 | 執照 | 分數 |
---|---|---|
X | ['麻省理工學院','麻省理工學院','麻省理工學院','麻省理工學院','麻省理工學院'] | [0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217] |
是的 | ['APSL-1.0'、'APSL-1.0'、'APSL-1.0'、'APSL-1.0'、'APSL-1.0'] | [0.28552457, 0.28552457, 0.28552457, 0.28552457, 0.28552457] |
以上只是一個例子。 數據框非常大。
更新,如果列中的元素為字符串格式,則可以使用regex
找到數組。 (注意不要使用eval, 為什么要避免exec()和eval()? )
import ast
new_cols = lambda x: pd.Series({'licence':ast.literal_eval(x[0]),
'score':ast.literal_eval(x[1])})
df = df.join(df['m'].str.findall(r'\[[^\[\]]*\]').apply(new_cols)).drop('m', axis=1)
print(df)
輸出:
file licence score
0 x ['MIT', 'MIT', 'MIT', 'MIT', 'MIT'] [0.71641791, 0.71641791, 0.71641791, 0.6956521...
1 y ['APSL-1.0', 'APSL-1.0', 'APSL-1.0', 'APSL-1.0', ... [0.28552457, 0.28552457, 0.28552457, 0.2855245...
regex
如何查找數組:(查找以[
開頭並以]
結尾的字符串,但在查找字符串時不應該有[
或]
來查找所有數組。)
>>> import re
>>> re.findall(r'\[[^\[\]]*\]', "[[np.array(['MIT', 'MIT', 'MIT', 'MIT', 'MIT'], dtype=object), np.array([0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217])]]",)
["['MIT', 'MIT', 'MIT', 'MIT', 'MIT']",
'[0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217]']
舊的,您可以創建新列,然后加入舊dataframe
。
new_cols = lambda x: pd.Series({'licence':x[0][0], 'score':x[0][1]})
df = df.join(df['m'].apply(new_cols)).drop('m', axis=1)
print(df)
輸入:
file description
0 x [[array(['MIT', 'MIT', 'MIT', 'MIT', 'MIT'], d...
1 y [[array(['APSL-1.0', 'APSL-1.0', 'APSL-1.0', '...
正在做:
import ast
df.description = (df.description.str.replace('array', '')
.str.replace(', dtype=object', '')
.apply(ast.literal_eval))
df[['license', 'score']] = [(x[0], x[1]) for x in df.description.str[0]]
df = df.drop('description', axis=1)
print(df)
輸出:
file license score
0 x [MIT, MIT, MIT, MIT, MIT] [0.71641791, 0.71641791, 0.71641791, 0.6956521...
1 y [APSL-1.0, APSL-1.0, APSL-1.0, APSL-1.0, APSL-... [0.28552457, 0.28552457, 0.28552457, 0.2855245...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.