简体   繁体   English

pivot python dataframe 行到列

[英]pivot python dataframe rows to columns

I have a python dataframe like this我有一个像这样的 python dataframe

       date      col1       col2    val
0   2019-01-01    A         hello   12
1   2019-01-01    A           hi    10
2   2019-01-02    B         hello   5
3   2019-01-02    B           hi    6

I want to convert it to我想把它转换成

       date      col1       hello  hi
0   2019-01-01    A           12    10
1   2019-01-02    B            5    6

Use pandas pivot_table() method.使用 pandas pivot_table()方法。 You can read more about it here .你可以在这里阅读更多关于它的信息。

The values belong to the val column, the indexes which we will retain are the date and col1 , and we would like to "create" columns out of the col2 col.这些values属于val列,我们将保留的索引是datecol1 ,我们想从col2 col 中“创建”列。

df = pd.pivot_table(df, values='val', index=['date', 'col1'],columns=['col2'], aggfunc=np.sum, fill_value=0)

Note that might some values be NaN , the above function will automatically set them to 0 , as per the fill_value parameter.请注意,可能某些值是NaN ,上面的 function 将根据fill_value参数自动将它们设置为0

Input:输入:

import pandas as pd
import numpy as np

a = ['2019-01-01', 'A', 'hello', 12]
b = ['2019-01-01', 'A', 'hi', 10]
c = ['2019-01-02', 'B', 'hello', 5]
d = ['2019-01-02', 'B', 'hi', 6]
df = pd.DataFrame([a, b, c, d], columns=['date', 'col1', 'col2', 'val'])

df = pd.pivot_table(df, values='val', index=['date', 'col1'],columns=['col2'], aggfunc=np.sum, fill_value=0)

print(df)

Output: Output:

col2             hello  hi
date       col1           
2019-01-01 A        12  10
2019-01-02 B         5   6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM