I have a Pandas data frame. In the A
columns there are ints like [1, 5, 3]
, and in the B
columns there are string like ["abcdef", "ghijklmno", "qwertyuiop"]
I want to create a C
columns with the columns B
first char according to the culumns A
. In my example I want the C
columns to be like ["a", "ghijk", "qwe" ]
I tried:
data_frame['C'] = data_frame.B.str[:data_frame["A"]]
But it doesn't work.
CodePudding user response:
You can set use a lambda function and set the axis = 1 to use column A to set the string length of B
df = pd.DataFrame({
'A' : [1, 5, 3,],
'B' : ["abcdef", "ghijklmno", "qwertyuiop"]
})
df['c'] = df.apply(lambda x : x['B'][:x['A']], axis = 1)
df
CodePudding user response:
Maybe try looping over the columns:
df['C'] = [b[:a] for a, b in zip(df['A'], df['B'])]