简体   繁体   English

如何在计算中使用 Pandas 数据框中的值?

[英]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.

相关问题 如何在pandas的数据框中检索k个最高值? - How can I retrieve the k highest values in a data frame in pandas? pandas:如何根据列值在一个数据帧中从另一个数据帧中 append 行? - pandas: How can I append rows in one data frame from another based on column values? 如何将列表中的值插入 pandas 数据框列? - How can i insert values from a list into a pandas data frame column? 如何从 pandas 数据框中删除下午 6:00 到上午 9:00 之间的日期时间索引值? - How can I remove a datetime index values from a pandas data frame that are in between 6:00 p.m. and 9:00 a.m.? 如何从数据框和字符串中找到匹配值? - How can I find matching values from a data frame and a string? 如何在熊猫数据框中将join()与groupby一起使用,以便可以使用分隔符分隔值 - How to use join() with groupby in pandas data frame so that the values can be separated using a separator 在Pandas中,如何使用一个表中的值作为索引从另一个表中提取数据? - In Pandas how can I use the values in one table as an index to extract data from another table? 如何使用列名称作为熊猫数据框中的值? - how to use column names as values in a pandas data frame? 如何通过计算熊猫数据框中的值来创建新系列? - How can I create a new series by calculating the values in my pandas data frame? 如何一次将不同大小的值添加到 Pandas 数据框中 - how can I add different size of the values into a pandas data frame at a time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM