熊猫:绘制包含一列元组的数据框

时间:2017-10-16 17:11:07

标签: python pandas matplotlib

我有一个非标准的CSV文件,如下所示:

x,y
1,"(5, 27, 4)"
2,"(3, 1, 6, 2)"
3,"(4, 5)"

使用pd.read_csv()导致一些并非完全有用的东西,因为没有解析元组。现有的答案解决了这个问题(12),但由于这些元组的长度不同,这些答案对我遇到的问题并不完全有用。

我想做的是使用pandas绘图程序绘制x vs y。天真的方法导致错误,因为元组存储为字符串:

>>> # df = pd.read_csv('data.csv')
>>> df = pd.DataFrame({'x': [1, 2, 3],
                       'y': ["(5, 27, 4)","(3, 1, 6, 2)","(4, 5)"]})
>>> df.plot.scatter('x', 'y')
[...]
ValueError: scatter requires y column to be numeric

我希望的结果是这样的:

import numpy as np
import matplotlib.pyplot as plt
for x, y in zip(df['x'], df['y']):
    y = eval(y)
    plt.scatter(x * np.ones_like(y), y, color='blue')

enter image description here

是否有直接从Pandas创建此图的方法,通过转换数据框并使用df.plot.scatter()(最好不使用eval())?

2 个答案:

答案 0 :(得分:2)

您可以展开dfplot

In [3129]: s = df.y.map(ast.literal_eval)

In [3130]: dff = pd.DataFrame({'x': df.x.repeat(s.str.len()).values,
                               'y': np.concatenate(s.values)})

In [3131]: dff
Out[3131]:
   x   y
0  1   5
1  1  27
2  1   4
3  2   3
4  2   1
5  2   6
6  2   2
7  3   4
8  3   5

并且,情节

dff.plot.scatter('x', 'y')

答案 1 :(得分:1)

您可以使用KeyError访问器提取整数,特别是.str.extractall

.str

如果您有浮点数而不是整数,只需根据需要修改正则表达式和# Index by 'x' to retain its values once we extract from 'y' df = df.set_index('x') # Extract integers from 'y' df = df['y'].str.extractall(r'(\d+)')[0].astype('int64') # Rename and reset the index (remove 'match' level, get 'x' as column) df = df.rename('y').reset_index(level='match', drop=True).reset_index()

这提供了一个类似于:

的DataFrame
astype

从那里 x y 0 1 5 1 1 27 2 1 4 3 2 3 4 2 1 5 2 6 6 2 2 7 3 4 8 3 5 应该产生预期的情节。