我正在列表中创建一个数据框,如下所示:
[{'points': [-9.3613566605198262, 4.0910018605047171, -9.3473134841172731, 4.0960021770649475], 'uid': 0},
{'points': [-9.4687215264026712, 4.0132947848279499, -9.3641925245477857, 4.0159059337303784], 'uid': 1},
以上是名为l1
的清单对于数据框:
df = pd.DataFrame.from_records(l1)
这会创建以下df:
points uid
0 [-9.3613566605198262, 4.09100186050......] 0
1 [-9.4687215264026712, 4.01329478482......] 1
我想知道如何从points列中删除列表格式/方括号,它应该包含简单的逗号分隔值。
另外,如何将小数位限制为2位?
我尝试了以下操作,但它不起作用。
np.round(df, 2)
和
df.round({'points':2})
预期df
points uid
0 -9.36, 4.09, -9.34, 4.09 0
1 -9.46, 4.01, -9.36, 4.01 1
答案 0 :(得分:3)
尝试这种方式:
df = pd.DataFrame.from_records(l1)
df['points'] = [', '.join(str(e) for e in [round(i, 2) for i in j])
for j in df['points']]
df
df将是:
points uid
0 -9.36, 4.09, -9.35, 4.1 0
1 -9.47, 4.01, -9.36, 4.02 1
答案 1 :(得分:3)
使用apply对列表中的数字进行舍入,然后以字符串形式连接。
df['points'] = df.apply(lambda x: ', '.join(str(round(e,2)) for e in x.points),axis=1)
df
Out[1042]:
points uid
0 -9.36, 4.09, -9.35, 4.1 0
1 -9.47, 4.01, -9.36, 4.02 1
答案 2 :(得分:1)
只是抬头......你不需要from_records
,pd.DataFrame
处理词典列表就好了。
df = pd.DataFrame(l1)
df
points uid
0 [-9.361356660519826, 4.091001860504717, -9.347313484117272, 4.096002177064947] 0
1 [-9.468721526402671, 4.01329478482795, -9.364192524547786, 4.015905933730378] 1
我喜欢使用这些字符串格式化程序
f = lambda n: ', '.join(['{:.2f}'] * n).format
d = lambda x: f(len(x))(*x)
df.assign(points=df.points.apply(d))
points uid
0 -9.36, 4.09, -9.35, 4.10 0
1 -9.47, 4.01, -9.36, 4.02 1