我有一个调查数据,其中一列如下:
Evaluations_Col
E: 3, D: 3, C: 3, S: 3, E: 3, X, K: 3
E: 1, D: 1, C: 1, S: 1, E: 1, X, K: 1
E: 2, D: 2, C: 2, S: 2, E: 2, X, K: 2
E: 5, D: 5, C: 5, S: 5, E: 5, X, K: 5
E: 3, D: 1, C: 1, S: 1, E: 1, X, K: 1
注意 :我需要忽略列中的 X 值。我想提取每个评估并将它们分开作为每种评估类型的列。最后预期的列将如下所示:
E_col D_col C_Col ...
3 3 3
1 1 1
2 2 2
5 5 5
3 1 1
我可以用逗号分隔它们并得到这样的列表,[E: 3, D: 3, C: 3, S: 3, E: 3, K: 3]
如何为每个创建单独的列并正确分布相应的值?我可以通过这个正常实现但是 X 值导致问题 bc 字典...我怎样才能排除它?
df1 = pd.DataFrame([dict([y.split(':') for y in x.split(',')]) for x in test_col])
df1.head()
错误是ValueError: dictionary update sequence element #9 has length 1; 2 is required
最佳答案
仅使用带有 ':' 分隔符的列表理解和过滤行:
让我们将列表理解分解为部分:
for x in test_col
x
表示)分隔为列,用 ',' 分割:for y in x.split(',')
y.split(':') for y in x.split(',') ***only*** if ':' in y
(解决了所描述的问题)代码:
import pandas as pd
import numpy as np
test_col = []
with open('data.csv', 'r') as f:
test_col = [l.strip() for l in f.readlines()]
df = pd.DataFrame([dict([y.split(':') for y in x.split(',') if ':' in y]) for x in test_col])
print(df.head())
输出: E D C S E K
0 3 3 3 3 3 3
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 5 5 5 5 5 5
4 3 1 1 1 1 1
关于python - 拆分列中的值并创建新的 cols 小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63833879/