用于基于其他密钥的名称创建密钥的循环



以下是我所拥有的数据的快照:

import pandas as pd
df = pd.DataFrame({
'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
'X1': [7,7,7,7,9],
'X2': [8,9,7,5,6],
})
print(df)

我正在寻找一个将识别多少";X〃;我拥有的密钥;X〃;键,它将创建"Y"键。在上面的情况下,我有X1和X2,因此,新的密钥是Y1和Y2(请参阅下面的代码(。

如果我有X1、X2和X3键,那么循环将自动创建Y1=1、Y2=2和Y3=3键,依此类推

df2 = pd.DataFrame({
'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
'X1': [7,7,7,7,9],
'X2': [8,9,7,5,6],
'Y1': [1,1,1,1,1],
'Y2': [2,2,2,2,2],
})
print(df2)

我怎样才能得到这些想要的结果?

您可以这样做:

current_columns = df.columns
for c in current_columns:
if c[0] == 'X':
df['y'+c[1:]] = int(c[:1])
print(df.head())

我认为您需要创建具有基于上一列后缀的值的新列

import pandas as pd
df = pd.DataFrame({
'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
'X1': [7,7,7,7,9],
'X2': [8,9,7,5,6],
'X3': [18,19,17,15,16]
})
for col in df.columns:
if col.startswith('X'):
df['Y'+col[1:]] = int(col[1:])
print(df)

输出:

brand  X1  X2  X3 Y1 Y2 Y3
0  Yum Yum   7   8  18  1  2  3
1  Yum Yum   7   9  19  1  2  3
2  Indomie   7   7  17  1  2  3
3  Indomie   7   5  15  1  2  3
4  Indomie   9   6  16  1  2  3

最新更新