[英]How can I use values from a Pandas data frame in a calcul?
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"]
在
A
列中有类似[1, 5, 3]
的整数,在B
列中有类似["abcdef", "ghijklmno", "qwertyuiop"]
的字符串
I want to create a C
columns with the columns B
first char according to the columns A
.我想根据列
A
创建一个C
列,其中B
列第一个字符。 In my example I want the C
columns to be like ["a", "ghijk", "qwe" ]
在我的示例中,我希望
C
列类似于["a", "ghijk", "qwe" ]
I tried:我试过了:
data_frame['C'] = data_frame.B.str[:data_frame["A"]]
but it doesn't work.但它不起作用。
You can set use a lambda function and set the axis = 1 to use column A to set the string length of B您可以设置使用 lambda 函数并设置 axis = 1 以使用列 A 设置 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
也许尝试遍历列:
df['C'] = [b[:a] for a, b in zip(df['A'], df['B'])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.