英文:
Converting a dataframe from a matrix format
问题
我有一个看起来像这样的数据框:
1 2 3
1 1 4 2
2 4 1 8
3 2 8 1
我试图将其转换为以下格式的数据框:
Comparison Value
1 v 1 1
1 v 2 4
1 v 3 2
2 v 3 8
可复现的数据框:
{1: {1: 1.0, 2: 4, 3: 2}, 2: {1: 4, 2: 1.0, 3: 8}, 3: {1: 2, 2: 8, 3: 1.0}}
英文:
I have a dataframe that looks like this:
1 2 3
1 1 4 2
2 4 1 8
3 2 8 1
I am trying to convert it to a dataframe with this format:
Comparison Value
1 v 1 1
1 v 2 4
1 v 3 2
2 v 3 8
Reproducible dataframe:
{1: {1: 1.0, 2: 4, 3: 2}, 2: {1: 4, 2: 1.0, 3: 8}, 3: {1: 2, 2: 8, 3: 1.0}}
答案1
得分: 0
你可以这样做:
import pandas as pd
df = pd.DataFrame({1: {1: 1.0, 2: 4, 3: 2}, 2: {1: 4, 2: 1.0, 3: 8}, 3: {1: 2, 2: 8, 3: 1.0}})
# 用于保存新的“矩阵”格式的字典
matdata = {"Comparison": [], "Value": []}
# 遍历行和列
for i in range(1, 4):
for j in range(1, 4):
matdata["Comparison"].append(f"{i} v {j}")
matdata["Value"].append(df.loc[i, j])
newdf = pd.DataFrame(matdata)
print(newdf)
Comparison Value
0 1 v 1 1.0
1 1 v 2 4.0
2 1 v 3 2.0
3 2 v 1 4.0
4 2 v 2 1.0
5 2 v 3 8.0
6 3 v 1 2.0
7 3 v 2 8.0
8 3 v 3 1.0
英文:
You could do something like:
import pandas as pd
df = pd.DataFrame({1: {1: 1.0, 2: 4, 3: 2}, 2: {1: 4, 2: 1.0, 3: 8}, 3: {1: 2, 2: 8, 3: 1.0}})
# dictionary to hold new "matrix" format
matdata = {"Comparison": [], "Value": []}
# loop over rows and columns
for i in range(1, 4):
for j in range(1, 4):
matdata["Comparison"].append(f"{i} v {j}")
matdata["Value"].append(df.loc[i, j])
newdf = pd.DataFrame(matdata)
print(newdf)
Comparison Value
0 1 v 1 1.0
1 1 v 2 4.0
2 1 v 3 2.0
3 2 v 1 4.0
4 2 v 2 1.0
5 2 v 3 8.0
6 3 v 1 2.0
7 3 v 2 8.0
8 3 v 3 1.0
答案2
得分: 0
使用以下简单方法与pandas.DataFrame.at
一起使用:
pd.DataFrame([(f'{c} v {i}', df.at[i, c]) for c in df.columns for i in df.index],
columns=['Comparison', 'Value'])
Comparison Value
0 1 v 1 1.0
1 1 v 2 4.0
2 1 v 3 2.0
3 2 v 1 4.0
4 2 v 2 1.0
5 2 v 3 8.0
6 3 v 1 2.0
7 3 v 2 8.0
8 3 v 3 1.0
英文:
Use the following simple approach with pandas.DataFrame.at
:
pd.DataFrame([(f'{c} v {i}', df.at[i, c]) for c in df.columns for i in df.index],
columns=['Comparison', 'Value'])
Comparison Value
0 1 v 1 1.0
1 1 v 2 4.0
2 1 v 3 2.0
3 2 v 1 4.0
4 2 v 2 1.0
5 2 v 3 8.0
6 3 v 1 2.0
7 3 v 2 8.0
8 3 v 3 1.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论