Pandas:在没有 MultiIndex 的情况下重塑 DataFrame
Pandas: Reshape DataFrame without MultiIndex
我需要重塑我的数据框
data = [
['Name 1', '17-11-2018', '2'],
['Name 2', '17-11-2018', '4'],
['Name 3', '17-11-2018', '6'],
['Name 1', '18-11-2018', '4'],
['Name 2', '18-11-2018', '6'],
['Name 3', '18-11-2018', '8'],
]
df = pd.DataFrame(data, columns = ['name', 'date', 'price'])
print(df)
product date price
0 Name 1 17-11-2018 2
1 Name 2 17-11-2018 4
2 Name 3 17-11-2018 6
3 Name 1 18-11-2018 4
4 Name 2 18-11-2018 6
5 Name 3 18-11-2018 8
我想得到这样的结果:
name 17-11-2018 18-11-2018
Name 1 2 4
Name 2 4 6
Name 3 6 8
但我最好的解决方案是使用 MultiIndex。
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)
print(qty)
date 17-11-2018 18-11-2018
name
Name 1 2 4
Name 2 4 6
Name 3 6 8
需要一些建议或解决方案,我怎样才能得到我需要的结果。
您可以使用 reset_index
重置索引并使用 rename_axis
重命名列索引:
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)\
.reset_index()\
.rename_axis(None, axis=1)
name 17-11-2018 18-11-2018
0 Name 1 2 4
1 Name 2 4 6
2 Name 3 6 8
如果要name
作为索引,只使用rename_axis
:
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)\
.rename_axis(None, axis=1)
17-11-2018 18-11-2018
name
Name 1 2 4
Name 2 4 6
Name 3 6 8
我需要重塑我的数据框
data = [
['Name 1', '17-11-2018', '2'],
['Name 2', '17-11-2018', '4'],
['Name 3', '17-11-2018', '6'],
['Name 1', '18-11-2018', '4'],
['Name 2', '18-11-2018', '6'],
['Name 3', '18-11-2018', '8'],
]
df = pd.DataFrame(data, columns = ['name', 'date', 'price'])
print(df)
product date price
0 Name 1 17-11-2018 2
1 Name 2 17-11-2018 4
2 Name 3 17-11-2018 6
3 Name 1 18-11-2018 4
4 Name 2 18-11-2018 6
5 Name 3 18-11-2018 8
我想得到这样的结果:
name 17-11-2018 18-11-2018
Name 1 2 4
Name 2 4 6
Name 3 6 8
但我最好的解决方案是使用 MultiIndex。
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)
print(qty)
date 17-11-2018 18-11-2018
name
Name 1 2 4
Name 2 4 6
Name 3 6 8
需要一些建议或解决方案,我怎样才能得到我需要的结果。
您可以使用 reset_index
重置索引并使用 rename_axis
重命名列索引:
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)\
.reset_index()\
.rename_axis(None, axis=1)
name 17-11-2018 18-11-2018
0 Name 1 2 4
1 Name 2 4 6
2 Name 3 6 8
如果要name
作为索引,只使用rename_axis
:
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)\
.rename_axis(None, axis=1)
17-11-2018 18-11-2018
name
Name 1 2 4
Name 2 4 6
Name 3 6 8