以下是我所掌握的数据的快照:
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)我怎样才能得到这些想要的结果?
发布于 2022-08-10 04:22:49
我认为您需要创建基于前一列后缀的值的新列。
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发布于 2022-08-10 02:50:27
你可以这样做:
current_columns = df.columns
for c in current_columns:
if c[0] == 'X':
df['y'+c[1:]] = int(c[:1])
print(df.head())https://stackoverflow.com/questions/73300059
复制相似问题