更清洁的方式来填充数据帧?

时间:2018-05-22 05:34:18

标签: python pandas

将数据加载到数据框中的更简洁方法是什么?我现在把它当作:

df = pd.DataFrame()
df['title'] = title_list
df['url'] = url_list
df['category'] = category_list
df['traffic'] = traffic_list
df['revenue'] = revenue_list
df['price'] = value_list
df.to_csv('test.csv', sep=",")

2 个答案:

答案 0 :(得分:4)

我建议使用dictionary,参数columns用于python bellow 3.6中列的自定义排序:

cols = ['title','url', 'category','traffic','revenue','price']
df = pd.DataFrame({'title':title_list, 
                   'url':url_list,
                   'category':category_list,
                   'traffic':traffic_list,
                   'revenue':revenue_list,
                   'price':value_list}, columns=cols)

答案 1 :(得分:4)

设置

title_list = list('ABCDE')
url_list = list('VWXYZ')
category_list = 'dog cat bird fish lizard'.split()
traffic_list = 'red green yellow blue amber'.split()
revenue_list = range(5, 10)
value_list = range(100, 600, 100)

zip

如果所有列表长度相等

,则此方法有效
data = [title_list, url_list, category_list,
        traffic_list, revenue_list, value_list]
cols = 'title url category traffic revenue price'.split()
pd.DataFrame(dict(zip(cols, data)))

  title url category traffic  revenue  price
0     A   V      dog     red        5    100
1     B   W      cat   green        6    200
2     C   X     bird  yellow        7    300
3     D   Y     fish    blue        8    400
4     E   Z   lizard   amber        9    500

如果长度不同

data = [title_list, url_list, category_list,
        traffic_list, revenue_list, value_list]
cols = 'title url category traffic revenue price'.split()
pd.DataFrame(list(zip(*data)), columns=cols)

   title url category traffic  revenue  price
0     A   V      dog     red        5    100
1     B   W      cat   green        6    200
2     C   X     bird  yellow        7    300
3     D   Y     fish    blue        8    400
4     E   Z   lizard   amber        9    500