在以下情况下,是否有一种向Dataframe列添加前导零的有效方法:
中另一列的给定值。
例如,对于下面的Dataframe,如何创建一个新的DataFrame,如果:
col_2是整数值(即不是"text"或"text2")col_1 == "A")。
初始Dataframe:
col_1 col_2
0 A 12345
1 B 863
2 A text
3 C 893423
4 D text2期望输出数据:
col_1 col_2
0 A 00012345
1 B 863
2 A text
3 C 893423
4 D text2发布于 2022-09-06 12:31:50
可以将to_numeric与errors="coerce"一起使用,以确保值是数字的:
# is the value numeric?
m1 = pd.to_numeric(df['col_2'], errors='coerce').notna()
# is col_1 equal to "A"?
m2 = df['col_1'].eq('A')
# pick the rows matching both conditions
# and do something with it
df[m1&m2]如果要确保具有整数而不是任何数字值(即浮点数),则可以使用:
s = pd.to_numeric(df['col_2'], errors='coerce')
# is a numeric value and an integer
m1 = s.notna() & s.eq(s.round())锌填充
m1 = pd.to_numeric(df['col_2'], errors='coerce').notna()
m2 = df['col_1'].eq('A')
df.loc[m1&m2, 'col_2'] = df.loc[m1&m2, 'col_2'].astype(str).str.zfill(8)产出:
col_1 col_2
0 A 00012345
1 B 863
2 A text
3 C 893423
4 D text2发布于 2022-09-06 12:37:25
我觉得这能做你想做的事
df[df['col_1']=='A'].apply(lambda x: isinstance(x, int) )产出:
col_1 False
col_2 Falsehttps://stackoverflow.com/questions/73622081
复制相似问题