繁体   English   中英

如何根据 python 中的其他列值创建另一列?

[英]How to create another column according to other column value in python?

我有以下 dataframe 和以下代码:

for i in range(int(tower1_base),int(tower1_top)):
     if i not in tower1_not_included_int :
         df = pd.concat([df, pd.DataFrame({"Tower": 1, "Floor": i, "Unit": list("ABCDEFG")})],ignore_index=True)

Result:
   Tower    Floor   Unit
0   1       1.0      A
1   1       1.0      B
2   1       1.0      C
3   1       1.0      D
4   1       1.0      E
5   1       1.0      F
6   1       1.0      G

如何创建另一个这样的索引列?

   Tower    Floor   Unit     Index
0   1       1.0      A       1A1
1   1       2.0      B       1B2
2   1       3.0      C       1C3
3   1       4.0      D       1D4 
4   1       5.0      E       1E5
5   1       6.0      F       1F6
6   1       7.0      G       1G7

您可以简单地添加列:

df['Index'] = df['Tower'].astype(str)+df['Unit']+df['Floor'].astype(int).astype(str)

为您的 dataframe 的第一个版本输出此:

   Tower  Floor Unit Index
0      1    1.0    A   1A1
1      1    1.0    B   1B1
2      1    1.0    C   1C1
3      1    1.0    D   1D1
4      1    1.0    E   1E1
5      1    1.0    F   1F1
6      1    1.0    G   1G1

另一种方法。 我创建了 dataframe 的副本并重新排序了列,以使“熔化”更容易。

dfAl = df.reindex(columns=['Tower','Unit','Floor'])

to_load = []  #list to load the new column
vals    = pd.DataFrame.to_numpy(dfAl)   #All values extracted

for sublist in vals:
    combs = ''.join([str(i).strip('.0') for i in sublist]) #melting values
    to_load.append(combs)

df['Index'] = to_load

如果您真的希望“索引”列成为真正的索引,最后一步:

df = df.set_index('Index')

print(df)

        Tower  Floor Unit
Index                   
1A1        1    1.0    A
1B2        1    2.0    B
1C3        1    3.0    C
1D4        1    4.0    D
1E5        1    5.0    E
1F6        1    6.0    F
1G7        1    7.0    G

暂无
暂无

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

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