如果我想打印一列的子字符串,这是有效的:
print(myDf["thisCol"].str[:2])
但是,如果我想对另一列进行子串运算并将其包含在输出中,我不知道如何做到这一点。
上述控制输出大致为:
0 fo
1 ba
我想要的是输出:,第二列是"anotherCol",其中最大长度大于2
0 fo tr
1 ba ca
(免责声明:我多次搜索都找不到答案。我正在以一种横向的方式学习熊猫……(
您可以提供一个表示所需空间数的因子,将其乘以print
语句中的单个空间
import pandas as pd
# mock data following your example, replace by your own data
col1 = ['foo', 'bar']
col2 = ['tri', 'car']
my_df = pd.DataFrame({'this_col': col1, 'another_col': col2})
# Specify your desired number of spaces between the dataframe columns print
desired_num_spaces = 10
# Print dataframes with specified columns separated by the desired number of spaces
print(my_df['this_col'].str[:2] + desired_num_spaces * ' ' + my_df['another_col'].str[:2])
给出
0 fo tr
1 ba ca
dtype: object
顺便说一句:在Python中,变量和键名称最好使用snake_case。请不要像在C#、Java、…等其他语言中使用的那样使用camelCase命名风格。。。
df=pd.DataFrame({'col1':['foo','bar'],'col2':['foo','bar'],'col3':['foo','bar']})
选择所需的列,然后应用chooper函数,该函数将把字符串剪切到前两个字符
def chopper(x):
return x[:2]
print(df[['col1','col3']].applymap(chopper))
输出:
col1 col3
0 fo fo
1 ba ba
另一种选择:
如果子字符串的阈值为5或更高,则可以使用pandas显示选项
pd.set_option('max_colwidth',6)
pd.set_option('max_colwidth',6)
df=pd.DataFrame({0:['asdfzklnlkdsfnalsdfknals;dknfs','asdfs0'],1:['foo','bar'],2:['foo','bar']})
print(df)
输出:
0 1 2
0 as... foo foo
1 as... bar bar